From 999c3499968596b2ef78db45b0e23693cf6f0bdc Mon Sep 17 00:00:00 2001 From: Rajesh Battala Date: Thu, 5 Jul 2012 13:29:06 +0530 Subject: [PATCH 01/26] modified Bucketpolicydao to extend BaseDAO --- .../cloud/bridge/persist/dao/BucketPolicyDao.java | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/awsapi/src/com/cloud/bridge/persist/dao/BucketPolicyDao.java b/awsapi/src/com/cloud/bridge/persist/dao/BucketPolicyDao.java index acd441e3b73..82e620b90ad 100644 --- a/awsapi/src/com/cloud/bridge/persist/dao/BucketPolicyDao.java +++ b/awsapi/src/com/cloud/bridge/persist/dao/BucketPolicyDao.java @@ -30,15 +30,10 @@ import org.apache.log4j.Logger; import com.cloud.bridge.util.ConfigurationHelper; -public class BucketPolicyDao { +public class BucketPolicyDao extends BaseDao { public static final Logger logger = Logger.getLogger(BucketPolicyDao.class); private Connection conn = null; - private String dbName = null; - private String dbUser = null; - private String dbPassword = null; - private String dbHost = null; - private String dbPort = null; public BucketPolicyDao() { @@ -54,11 +49,14 @@ public class BucketPolicyDao { } catch (IOException e) { logger.warn("Unable to read properties file: " + propertiesFile.getAbsolutePath(), e); } + /* using the values from base class dbHost = EC2Prop.getProperty( "db.cloud.host" ); dbName = EC2Prop.getProperty( "db.awsapi.name" ); dbUser = EC2Prop.getProperty( "db.cloud.username" ); dbPassword = EC2Prop.getProperty( "db.cloud.password" ); dbPort = EC2Prop.getProperty( "db.cloud.port" ); + */ + } } @@ -147,7 +145,7 @@ public class BucketPolicyDao { { if (null == conn) { Class.forName( "com.mysql.jdbc.Driver" ).newInstance(); - conn = DriverManager.getConnection( "jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName, dbUser, dbPassword ); + conn = DriverManager.getConnection( "jdbc:mysql://" + dbHost + ":" + dbPort + "/" + awsapi_dbName, dbUser, dbPassword ); } } From 93916abcff5ef117fae3d84ab465682ab47582cc Mon Sep 17 00:00:00 2001 From: Chirag Jog Date: Thu, 5 Jul 2012 21:28:14 +0530 Subject: [PATCH 02/26] Adding Upload volumes & security enhancements tests --- .../test_security_keys_encryption.py | 372 ++++++++ .../component/test_upload_volumes.py | 896 ++++++++++++++++++ test/integration/lib/base.py | 34 +- 3 files changed, 1292 insertions(+), 10 deletions(-) create mode 100755 test/integration/component/test_security_keys_encryption.py create mode 100644 test/integration/component/test_upload_volumes.py diff --git a/test/integration/component/test_security_keys_encryption.py b/test/integration/component/test_security_keys_encryption.py new file mode 100755 index 00000000000..89907c217d2 --- /dev/null +++ b/test/integration/component/test_security_keys_encryption.py @@ -0,0 +1,372 @@ +""" P1 tests for Security Keys Encryption +""" +#Import Local Modules +from integration.lib.base import * +from integration.lib.common import * +from integration.lib.utils import * +from marvin import remoteSSHClient +from marvin.cloudstackAPI import * +from marvin.cloudstackTestCase import * +import datetime +import marvin + + +class Services: + """Test Security encryption Services + """ + + def __init__(self): + self.services = { + "account": { + "email": "test@test.com", + "firstname": "Test", + "lastname": "User", + "username": "test", + # Random characters are appended for unique + # username + "password": "fr3sca", + }, + "service_offering": { + "name": "Tiny Instance", + "displaytext": "Tiny Instance", + "cpunumber": 1, + "cpuspeed": 100, # in MHz + "memory": 64, # In MBs + }, + "virtual_machine": { + "displayname": "TestVM", + "username": "root", + "password": "password", + "ssh_port": 22, + "hypervisor": 'XenServer', + "privateport": 22, + "publicport": 22, + "protocol": 'TCP', + }, + "vpn_user": { + "username": "test", + "password": "test", + }, + "host": { + "username": "root", + "password": "fr3sca", + }, + "globalconfig": { + "security.hash.key": "test", + "vmware.guest.vswitch": "test", + "vmware.public.vswitch": "test", + "vmware.private.vswitch": "test", + "kvm.guest.network.device": "test", + "ovm.guest.network.device": "test", + "xen.guest.network.device": "test", + "kvm.public.network.device": "test", + "ovm.public.network.device": "test", + "xen.public.network.device": "test", + "kvm.private.network.device": "test", + "ovm.private.network.device": "test", + "xen.private.network.device": "test", + "xen.storage.network.device1": "test", + "xen.storage.network.device2": "test", + "alert.smtp.password": "test", + "project.smtp.password": "test", + }, + "ostypeid": '7ddbbbb5-bb09-40de-b038-ee78995788ea', + # Cent OS 5.3 (64 bit) + "sleep": 60, + "timeout": 10, + "mode": 'advanced' + } + + +class TestSecurityKeysEncryption(cloudstackTestCase): + + @classmethod + def setUpClass(cls): + cls.api_client = super(TestSecurityKeysEncryption, cls).getClsTestClient().getApiClient() + cls.services = Services().services + # Get Zone, Domain and templates + cls.domain = get_domain(cls.api_client, cls.services) + cls.zone = get_zone(cls.api_client, cls.services) + + template = get_template( + cls.api_client, + cls.zone.id, + cls.services["ostypeid"] + ) + cls.services["virtual_machine"]["zoneid"] = cls.zone.id + + cls.services["template"] = template.id + + # Create Account, VMs etc + cls.account = Account.create( + cls.api_client, + cls.services["account"], + domainid=cls.domain.id + ) + cls.services["account"] = cls.account.account.name + + cls.service_offering = ServiceOffering.create( + cls.api_client, + cls.services["service_offering"] + ) + cls.virtual_machine = VirtualMachine.create( + cls.api_client, + cls.services["virtual_machine"], + templateid=template.id, + accountid=cls.account.account.name, + domainid=cls.account.account.domainid, + serviceofferingid=cls.service_offering.id + ) + + cls.public_ip = PublicIPAddress.create( + cls.api_client, + cls.virtual_machine.account, + cls.virtual_machine.zoneid, + cls.virtual_machine.domainid, + cls.services["virtual_machine"] + ) + + cls._cleanup = [ + cls.service_offering, + cls.account, + ] + return + + @classmethod + def tearDownClass(cls): + try: + #Cleanup resources used + 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.cleanup = [] + return + + def tearDown(self): + try: + #Clean up, terminate the created instance, volumes and snapshots + cleanup_resources(self.apiclient, self.cleanup) + except Exception as e: + raise Exception("Warning: Exception during cleanup : %s" % e) + return + + def test_vm_instance_vnc_password(self): + """ Verify vm_instance table's vnc_password column encryption """ + + tags = ["advanced", "basic"] + + #Steps, + #Deploy a VM + #Once VM is running goto db Server + #Validation, + #Verify vm_instance table's vnc_password column is encrypted + + qresultset = self.dbclient.execute( + "select vnc_password from vm_instance where uuid = '%s';" \ + % self.virtual_machine.id + ) + self.assertEqual( + isinstance(qresultset, list), + True, + "Check DB query result set for valid data" + ) + self.assertNotEqual( + qresultset[0][0], + self.services["virtual_machine"]["password"], + "Check vnc_password in vm_instance table to verify encryption" + ) + return + + def test_vpn_users_password(self): + """ Verify vpn_users table's password column encryption """ + + tags = ["advanced"] + + #Steps, + #Deploy a VM + #Aquire a IP + #Enable VPN on the acquired IP + #Add VPN user + #Validations, + #Verify vpn_users table's password column is encrypted + + self.debug("Created VPN with public IP: %s" % self.public_ip.ipaddress.id) + + #Assign VPN to Public IP + vpn = Vpn.create( + self.apiclient, + self.public_ip.ipaddress.id, + account=self.account.account.name, + domainid=self.account.account.domainid + ) + + self.debug("Created VPN user for account: %s" % + self.account.account.name) + + vpnuser = VpnUser.create( + self.apiclient, + self.services["vpn_user"]["username"], + self.services["vpn_user"]["password"], + account=self.account.account.name, + domainid=self.account.account.domainid + ) + + qresultset = self.dbclient.execute( + "select password from vpn_users where uuid = '%s';" \ + % vpnuser.id + ) + + self.assertEqual( + isinstance(qresultset, list), + True, + "Check DB query result set for valid data" + ) + + self.assertNotEqual( + qresultset[0][0], + self.services["vpn_user"]["password"], + "Check password in vpn_users table to verify encryption" + ) + + def test_user_secret_key(self): + """ Verify user table's SECRET key column encryption """ + #Steps, + #generate key for the user of the account + #Validations, + #Verify user table's secret key column is encrypted + + tags = ["advanced", "basic"] + + user_keys = User.registerUserKeys(self.apiclient, self.account.account.user[0].id) + qresultset = self.dbclient.execute( + "select secret_key from user where uuid = '%s';" \ + % self.account.account.user[0].id + ) + + self.assertEqual( + isinstance(qresultset, list), + True, + "Check DB query result set for valid data" + ) + + self.assertNotEqual( + qresultset[0][0], + user_keys.secretkey, + "Check secret key in users table to verify encryption" + ) + return + + def test_host_password(self): + """ Verify host details table's value column encryption where name is password """ + + tags = ["advanced", "basic"] + + #Validations, + #Verify host details table's value column is encrypted where name is password + + hosts = list_hosts( + self.apiclient, + zoneid=self.services["virtual_machine"]["zoneid"], + type='Routing', + state='Up' + ) + self.assertEqual( + isinstance(hosts, list), + True, + "Check list host returns a valid list" + ) + + host = hosts[0] + + qresultset = self.dbclient.execute( + "select id from host where uuid = '%s';" \ + % host.id + ) + + self.assertEqual( + isinstance(qresultset, list), + True, + "Check DB query result set for valid data" + ) + + hostid = qresultset[0][0] + + qresultset = self.dbclient.execute( + "select value from host_details where host_id = '%s' and name='password';" \ + % hostid + ) + + self.assertEqual( + isinstance(qresultset, list), + True, + "Check DB query result set for valid data" + ) + + self.assertNotEqual( + qresultset[0][0], + self.services["host"]["password"], + "Check password field value in host_details table to verify encryption" + ) + return + + def test_configurations_value_encryption(self): + """ verify configuration tables following name records value field are encrypted """ + + tags = ["advanced", "basic"] + + #Steps + #verify configuration tables following name records value field are encrypted + #security.hash.key + #vmware.guest.vswitch + #vmware.public.vswitch + #vmware.private.vswitch + #kvm.guest.network.device + #ovm.guest.network.device + #xen.guest.network.device + #kvm.public.network.device + #ovm.public.network.device + #xen.public.network.device + #kvm.private.network.device + #ovm.private.network.device + #xen.private.network.device + #xen.storage.network.device1 + #xen.storage.network.device2 + #alert.smtp.password + #project.smtp.password + #Validations, + #Verify configuration table's following name records value filed is encrypted + + for k, v in self.services["globalconfig"].items(): + + #setting some test value to the configuration + Configurations.update(self.apiclient, k, v) + + #fetching the value of the configuration from DB + qresultset = self.dbclient.execute( + "select value from configuration where name = '%s';" \ + % k + ) + + self.assertEqual( + isinstance(qresultset, list), + True, + "Check DB query result set for valid data" + ) + + config_value = qresultset[0][0] + + #verifying the value from db and set are not equal and the value in db is encrypted + self.assertNotEqual( + config_value, + v, + "Configuration %s 's value should be stored in encrypted format in DB" % k + ) + + #Setting the configuration value back to None as default value + Configurations.update(self.apiclient, k) + return diff --git a/test/integration/component/test_upload_volumes.py b/test/integration/component/test_upload_volumes.py new file mode 100644 index 00000000000..a7fa8286e4c --- /dev/null +++ b/test/integration/component/test_upload_volumes.py @@ -0,0 +1,896 @@ +# -*- encoding: utf-8 -*- +# Copyright 2012 Citrix Systems, Inc. Licensed under the +# Apache License, Version 2.0 (the "License"); you may not use this +# file except in compliance with the License. Citrix Systems, Inc. +# reserves all rights not expressly granted by the License. +# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 04/03/2012 + +""" P1 tests for Upload Volumes +""" + +#Import Local Modules +import marvin +from marvin.cloudstackTestCase import * +from marvin.cloudstackAPI import * +from integration.lib.utils import * +from integration.lib.base import * +from integration.lib.common import * +from marvin.remoteSSHClient import remoteSSHClient +#Import System modules +import os +import urllib +import time +import tempfile + + +class Services: + """Test Volume Services + """ + + def __init__(self): + self.services = { + "account": { + "email": "test@test.com", + "firstname": "Test", + "lastname": "User", + "username": "test", + # Random characters are appended for unique + # username + "password": "fr3sca", + }, + "service_offering": { + "name": "Tiny Instance", + "displaytext": "Tiny Instance", + "cpunumber": 1, + "cpuspeed": 100, # in MHz + "memory": 64, # In MBs + }, + "disk_offering": { + "displaytext": "Small", + "name": "Small", + "disksize": 1 + }, + "volume": { + "diskname": "UploadedVolume", + "url": "http://192.168.100.21/images/upload_1_gb.vhd", + "format": 'VHD', + }, + "volumes": { + # If you are testing for other hypervisor than XenServer, + # Please change this dict according to following + # "HYPERVISOR" : { + # 0: { + # """Configs for volume type 1 + # supported by HYPERVISOR""" + # Xenserver specific settings for volumes + "xenserver": { + 0: { + "diskname": "Volume_VHD_Format", + "url": "http://192.168.100.21/images/upload_1_gb.vhd", + "format": 'VHD', + }, + }, + }, + "virtual_machine": { + "displayname": "testVM", + "hypervisor": 'XenServer', + "protocol": 'TCP', + "ssh_port": 22, + "username": "root", + "password": "password", + "privateport": 22, + "publicport": 22, + }, + "sleep": 50, + "ostypeid": '7ddbbbb5-bb09-40de-b038-ee78995788ea', + "mode": 'basic', + } + + +class TestUploadDataDisk(cloudstackTestCase): + + @classmethod + def setUpClass(cls): + cls.api_client = super( + TestUploadDataDisk, + cls + ).getClsTestClient().getApiClient() + cls.services = Services().services + + # Get Zone, Domain and templates + cls.domain = get_domain(cls.api_client, cls.services) + cls.zone = get_zone(cls.api_client, cls.services) + template = get_template( + cls.api_client, + cls.zone.id, + cls.services["ostypeid"] + ) + # Create account, service offerings etc + cls.account = Account.create( + cls.api_client, + cls.services["account"], + domainid=cls.domain.id + ) + + cls.services["account"] = cls.account.account.name + cls.services["zoneid"] = cls.zone.id + cls.service_offering = ServiceOffering.create( + cls.api_client, + cls.services["service_offering"] + ) + cls.disk_offering = DiskOffering.create( + cls.api_client, + cls.services["disk_offering"] + ) + cls._cleanup = [ + cls.service_offering, + cls.disk_offering, + cls.account + ] + + def setUp(self): + + self.apiclient = self.testClient.getApiClient() + self.dbclient = self.testClient.getDbConnection() + self.cleanup = [] + + def tearDown(self): + try: + #Clean up, terminate the created volumes + self.debug("Cleanup the resources..") + cleanup_resources(self.apiclient, self.cleanup) + self.debug("Cleanup succeeded") + except Exception as e: + raise Exception("Warning: Exception during cleanup : %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) + + def test_01_upload_data_disk(self): + """Test Upload a data disk + """ + + tags = ["advanced", "basic", "eip", "advancedns", "sg"] + + # Validate the following + # 1. call upload volume API with following parameters HTTP URL of the + # data disk, Zone ID, Name, Description, Hyper visor + # 2. Upload volume is successful + + self.debug("Uploading the volume to account: %s" % + self.account.account.name) + # Upload the volume + volume = Volume.upload( + self.apiclient, + self.services["volume"], + zoneid=self.zone.id, + account=self.account.account.name, + domainid=self.account.account.domainid, + url=self.services["volume"]["url"] + ) + self.debug("Registered volume: %s for account: %s" % ( + volume.name, + self.account.account.name + )) + self.debug("Waiting for upload of volume: %s" % volume.name) + try: + volume.wait_for_upload(self.apiclient) + self.debug("Volume: %s uploaded to CS successfully" % volume.name) + except Exception as e: + self.fail("Upload volume failed: %s" % e) + + # Check List Volume response for newly created volume + list_volume_response = Volume.list( + self.apiclient, + id=volume.id, + zoneid=self.zone.id, + listall=True + ) + self.assertNotEqual( + list_volume_response, + None, + "Check if volume exists in ListVolumes" + ) + volume_response = list_volume_response[0] + self.assertEqual( + volume_response.state, + "Uploaded", + "Volume state should be 'Uploaded' after importing to CS" + ) + return + + def test_02_upload_volume_limit(self): + """Test upload volume limits + """ + + tags = ["advanced", "basic", "eip", "advancedns", "sg"] + + # Validate the following + # 1. Update the volume resource limit for account to 1 + # 2. Upload volume in that account + # 3. Upload volume should fail with appropriate error + + self.debug( + "Updating volume resource limit for account: %s" % + self.account.account.name) + # Set usage_vm=1 for Account 1 + update_resource_limit( + self.apiclient, + 2, # Volume + account=self.account.account.name, + domainid=self.account.account.domainid, + max=1 + ) + + self.debug("Uploading the volume to account: %s" % + self.account.account.name) + with self.assertRaises(Exception): + # Upload the volume + volume = Volume.upload( + self.apiclient, + self.services["volume"], + zoneid=self.zone.id, + account=self.account.account.name, + domainid=self.account.account.domainid, + url=self.services["volume"]["url"] + ) + self.debug("Registered volume: %s for account: %s" % ( + volume.name, + self.account.account.name + )) + self.debug("Upload volume failed! Test succeeded..") + return + + +class TestUploadDiskDiffFormat(cloudstackTestCase): + + @classmethod + def setUpClass(cls): + cls.api_client = super( + TestUploadDiskDiffFormat, + cls + ).getClsTestClient().getApiClient() + cls.services = Services().services + + # Get Zone, Domain and templates + cls.domain = get_domain(cls.api_client, cls.services) + cls.zone = get_zone(cls.api_client, cls.services) + template = get_template( + cls.api_client, + cls.zone.id, + cls.services["ostypeid"] + ) + # Create account, service offerings etc + cls.account = Account.create( + cls.api_client, + cls.services["account"], + domainid=cls.domain.id + ) + cls.services["zoneid"] = cls.zone.id + cls.service_offering = ServiceOffering.create( + cls.api_client, + cls.services["service_offering"] + ) + cls.disk_offering = DiskOffering.create( + cls.api_client, + cls.services["disk_offering"] + ) + cls._cleanup = [ + cls.service_offering, + cls.disk_offering, + cls.account + ] + + def setUp(self): + + self.apiclient = self.testClient.getApiClient() + self.dbclient = self.testClient.getDbConnection() + self.cleanup = [] + + def tearDown(self): + try: + #Clean up, terminate the created volumes + self.debug("Cleanup the resources..") + cleanup_resources(self.apiclient, self.cleanup) + self.debug("Cleanup succeeded") + except Exception as e: + raise Exception("Warning: Exception during cleanup : %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) + + def test_upload_disk_diff_format(self): + """Test Upload a data disk in different format + """ + + tags = ["advanced", "basic", "eip", "advancedns", "sg"] + + # Validate the following + # 1. call upload volume API with following parameters HTTP URL of the + # data disk, Zone ID, Name, Description, Hyper visor + # disk types are: zip file format,tar format,tar gzip format + # tar bzip format + # 2. Upload volume is successful + + for hypervisor, settings in self.services["volumes"].items(): + for k, v in settings.items(): + self.debug( + "Uploading the volume (type: %s) for Hypervisor: %s to account: %s" % ( + v["format"], + hypervisor, + self.account.account.name + )) + # Upload the volume + volume = Volume.upload( + self.apiclient, + v, + zoneid=self.zone.id, + account=self.account.account.name, + domainid=self.account.account.domainid, + ) + self.debug("Registered volume: %s for account: %s" % ( + volume.name, + self.account.account.name + )) + self.debug("Waiting for upload of volume: %s" % volume.name) + try: + volume.wait_for_upload(self.apiclient) + self.debug("Volume: %s uploaded to CS successfully" % + volume.name) + except Exception as e: + self.fail("Upload volume failed: %s" % e) + + # Check List Volume response for newly created volume + list_volume_response = list_volumes( + self.apiclient, + id=volume.id + ) + self.assertNotEqual( + list_volume_response, + None, + "Check if volume exists in ListVolumes" + ) + volume_response = list_volume_response[0] + self.assertEqual( + volume_response.state, + "Uploaded", + "Volume state should be 'Uploaded' after importing to CS" + ) + return + + +class TestUploadAttachDisk(cloudstackTestCase): + + @classmethod + def setUpClass(cls): + cls.api_client = super( + TestUploadAttachDisk, + cls + ).getClsTestClient().getApiClient() + cls.services = Services().services + + # Get Zone, Domain and templates + cls.domain = get_domain(cls.api_client, cls.services) + cls.zone = get_zone(cls.api_client, cls.services) + template = get_template( + cls.api_client, + cls.zone.id, + cls.services["ostypeid"] + ) + # Create account, service offerings etc + cls.account = Account.create( + cls.api_client, + cls.services["account"], + domainid=cls.domain.id + ) + + cls.services["account"] = cls.account.account.name + cls.services["virtual_machine"]["zoneid"] = cls.zone.id + cls.services["zoneid"] = cls.zone.id + cls.service_offering = ServiceOffering.create( + cls.api_client, + cls.services["service_offering"] + ) + cls.disk_offering = DiskOffering.create( + cls.api_client, + cls.services["disk_offering"] + ) + cls.virtual_machine = VirtualMachine.create( + cls.api_client, + cls.services["virtual_machine"], + templateid=template.id, + accountid=cls.account.account.name, + domainid=cls.account.account.domainid, + serviceofferingid=cls.service_offering.id, + ) + cls._cleanup = [ + cls.service_offering, + cls.disk_offering, + cls.account + ] + + def setUp(self): + + self.apiclient = self.testClient.getApiClient() + self.dbclient = self.testClient.getDbConnection() + self.cleanup = [] + + def tearDown(self): + try: + #Clean up, terminate the created volumes + self.debug("Cleanup the resources..") + cleanup_resources(self.apiclient, self.cleanup) + self.debug("Cleanup succeeded") + except Exception as e: + raise Exception("Warning: Exception during cleanup : %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) + + def test_upload_attach_data_disk(self): + """Test Upload and attach a data disk + """ + + tags = ["advanced", "basic", "eip", "advancedns", "sg"] + + # Validate the following + # 1. call upload volume API with following parameters HTTP URL of the + # data disk, Zone ID, Name, Description, Hyper visor + # 2. Upload volume is successful + + self.debug("Uploading the volume to account: %s" % + self.account.account.name) + # Upload the volume + volume = Volume.upload( + self.apiclient, + self.services["volume"], + zoneid=self.zone.id, + account=self.account.account.name, + domainid=self.account.account.domainid, + url=self.services["volume"]["url"] + ) + self.debug("Registered volume: %s for account: %s" % ( + volume.name, + self.account.account.name + )) + self.debug("Waiting for upload of volume: %s" % volume.name) + try: + volume.wait_for_upload(self.apiclient) + self.debug("Volume: %s uploaded to CS successfully" % volume.name) + except Exception as e: + self.fail("Upload volume failed: %s" % e) + + # Check List Volume response for newly created volume + list_volume_response = Volume.list( + self.apiclient, + id=volume.id, + zoneid=self.zone.id, + listall=True + ) + self.assertNotEqual( + list_volume_response, + None, + "Check if volume exists in ListVolumes" + ) + volume_response = list_volume_response[0] + self.assertEqual( + volume_response.state, + "Uploaded", + "Volume state should be 'Uploaded' after importing to CS" + ) + self.debug( + "Attaching the disk: %s to VM: %s" % ( + self.virtual_machine.name, + volume.name + )) + self.virtual_machine.attach_volume(self.apiclient, volume) + self.debug( + "Volume attached to instance: %s" % + self.virtual_machine.name) + # Check List Volume response for newly created volume + list_volume_response = Volume.list( + self.apiclient, + id=volume.id, + virtualmachineid=self.virtual_machine.id, + listall=True + ) + self.assertNotEqual( + list_volume_response, + None, + "Check if volume exists in ListVolumes" + ) + + volume_response = list_volume_response[0] + self.assertEqual( + volume_response.state, + "Ready", + "Volume state should be 'Uploaded' after importing to CS" + ) + return + + +class TestUploadAttachDiskDiffFormat(cloudstackTestCase): + + @classmethod + def setUpClass(cls): + cls.api_client = super( + TestUploadAttachDiskDiffFormat, + cls + ).getClsTestClient().getApiClient() + cls.services = Services().services + + # Get Zone, Domain and templates + cls.domain = get_domain(cls.api_client, cls.services) + cls.zone = get_zone(cls.api_client, cls.services) + template = get_template( + cls.api_client, + cls.zone.id, + cls.services["ostypeid"] + ) + # Create account, service offerings etc + cls.account = Account.create( + cls.api_client, + cls.services["account"], + domainid=cls.domain.id + ) + cls.services["virtual_machine"]["zoneid"] = cls.zone.id + cls.services["zoneid"] = cls.zone.id + cls.service_offering = ServiceOffering.create( + cls.api_client, + cls.services["service_offering"] + ) + cls.disk_offering = DiskOffering.create( + cls.api_client, + cls.services["disk_offering"] + ) + cls.virtual_machine = VirtualMachine.create( + cls.api_client, + cls.services["virtual_machine"], + templateid=template.id, + accountid=cls.account.account.name, + domainid=cls.account.account.domainid, + serviceofferingid=cls.service_offering.id, + ) + cls._cleanup = [ + cls.service_offering, + cls.disk_offering, + cls.account + ] + + def setUp(self): + + self.apiclient = self.testClient.getApiClient() + self.dbclient = self.testClient.getDbConnection() + self.cleanup = [] + + def tearDown(self): + try: + #Clean up, terminate the created volumes + self.debug("Cleanup the resources..") + cleanup_resources(self.apiclient, self.cleanup) + self.debug("Cleanup succeeded") + except Exception as e: + raise Exception("Warning: Exception during cleanup : %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) + + def test_upload_disk_diff_format(self): + """Test Upload a data disk in different format + """ + + tags = ["advanced", "basic", "eip", "advancedns", "sg"] + + # Validate the following + # 1. call upload volume API with following parameters HTTP URL of the + # data disk, Zone ID, Name, Description, Hyper visor + # disk types are: zip file format,tar format,tar gzip format + # tar bzip format + # 2. Upload volume is successful + + for hypervisor, settings in self.services["volumes"].items(): + for k, v in settings.items(): + self.debug( + "Uploading the volume (type: %s) for Hypervisor: %s to account: %s" % ( + v["format"], + hypervisor, + self.account.account.name + )) + # Upload the volume + volume = Volume.upload( + self.apiclient, + v, + zoneid=self.zone.id, + account=self.account.account.name, + domainid=self.account.account.domainid, + ) + self.debug("Registered volume: %s for account: %s" % ( + volume.name, + self.account.account.name + )) + self.debug("Waiting for upload of volume: %s" % volume.name) + try: + volume.wait_for_upload(self.apiclient) + self.debug("Volume: %s uploaded to CS successfully" % + volume.name) + except Exception as e: + self.fail("Upload volume failed: %s" % e) + + # Check List Volume response for newly created volume + list_volume_response = list_volumes( + self.apiclient, + id=volume.id + ) + self.assertNotEqual( + list_volume_response, + None, + "Check if volume exists in ListVolumes" + ) + volume_response = list_volume_response[0] + self.assertEqual( + volume_response.state, + "Uploaded", + "Volume state should be 'Uploaded' after importing to CS" + ) + + self.debug( + "Attaching the disk: %s to VM: %s" % ( + self.virtual_machine.name, + volume.name + )) + self.virtual_machine.attach_volume(self.apiclient, volume) + self.debug( + "Volume attached to instance: %s" % + self.virtual_machine.name) + # Check List Volume response for newly created volume + list_volume_response = Volume.list( + self.apiclient, + id=volume.id, + virtualmachineid=self.virtual_machine.id, + listall=True + ) + self.assertNotEqual( + list_volume_response, + None, + "Check if volume exists in ListVolumes" + ) + + volume_response = list_volume_response[0] + self.assertEqual( + volume_response.state, + "Ready", + "Volume state should be 'Uploaded' after importing to CS" + ) + return + + +class TestUploadDiskMultiStorage(cloudstackTestCase): + + @classmethod + def setUpClass(cls): + cls.api_client = super( + TestUploadDiskMultiStorage, + cls + ).getClsTestClient().getApiClient() + cls.services = Services().services + + # Get Zone, Domain and templates + cls.domain = get_domain(cls.api_client, cls.services) + cls.zone = get_zone(cls.api_client, cls.services) + cls.pod = get_pod(cls.api_client, zoneid=cls.zone.id) + + template = get_template( + cls.api_client, + cls.zone.id, + cls.services["ostypeid"] + ) + # Create account, service offerings etc + cls.account = Account.create( + cls.api_client, + cls.services["account"], + domainid=cls.domain.id + ) + + cls.services["account"] = cls.account.account.name + cls.services["zoneid"] = cls.zone.id + cls.service_offering = ServiceOffering.create( + cls.api_client, + cls.services["service_offering"] + ) + cls.disk_offering = DiskOffering.create( + cls.api_client, + cls.services["disk_offering"] + ) + cls._cleanup = [ + cls.service_offering, + cls.disk_offering, + cls.account + ] + + def setUp(self): + + self.apiclient = self.testClient.getApiClient() + self.dbclient = self.testClient.getDbConnection() + self.cleanup = [] + + def tearDown(self): + try: + #Clean up, terminate the created volumes + self.debug("Cleanup the resources..") + cleanup_resources(self.apiclient, self.cleanup) + self.debug("Cleanup succeeded") + except Exception as e: + raise Exception("Warning: Exception during cleanup : %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) + + def test_01_upload_volume_multi_sec_storage(self): + """Test Upload a data disk when multiple sec storages are present + """ + + tags = ["advanced", "basic", "eip", "advancedns", "sg"] + + # Validate the following + # 1. Assume multiple secondary storages are present in a zone + # 2. call upload volume API with following parameters HTTP URL of the + # data disk, Zone ID, Name, Description, Hyper visor + # 2. Upload volume is successful + + sec_storages = Host.list( + self.apiclient, + type='SecondaryStorage', + zoneid=self.zone.id + ) + self.assertEqual( + isinstance(sec_storages, list), + True, + "List Secondary storage should return a valid list" + ) + self.assertGreaterEqual( + len(sec_storages), + 2, + "Test requires atleast 2 secondary storages added to zone" + ) + self.debug("Uploading the volume to account: %s" % + self.account.account.name) + # Upload the volume + volume = Volume.upload( + self.apiclient, + self.services["volume"], + zoneid=self.zone.id, + account=self.account.account.name, + domainid=self.account.account.domainid, + url=self.services["volume"]["url"] + ) + self.debug("Registered volume: %s for account: %s" % ( + volume.name, + self.account.account.name + )) + self.debug("Waiting for upload of volume: %s" % volume.name) + try: + volume.wait_for_upload(self.apiclient) + self.debug("Volume: %s uploaded to CS successfully" % volume.name) + except Exception as e: + self.fail("Upload volume failed: %s" % e) + + # Check List Volume response for newly created volume + list_volume_response = Volume.list( + self.apiclient, + id=volume.id, + zoneid=self.zone.id, + listall=True + ) + self.assertNotEqual( + list_volume_response, + None, + "Check if volume exists in ListVolumes" + ) + volume_response = list_volume_response[0] + self.assertEqual( + volume_response.state, + "Uploaded", + "Volume state should be 'Uploaded' after importing to CS" + ) + return + + def test_02_upload_volume_multi_pri_storage(self): + """Test Upload a data disk when multiple primary storages are present + """ + + tags = ["advanced", "basic", "eip", "advancedns", "sg"] + + # Validate the following + # 1. Assume multiple primary storages are present in a pod + # 2. call upload volume API with following parameters HTTP URL of the + # data disk, Zone ID, Name, Description, Hyper visor + # 2. Upload volume is successful + + storage_pools = StoragePool.list( + self.apiclient, + zoneid=self.zone.id, + podid=self.pod.id + ) + self.assertEqual( + isinstance(storage_pools, list), + True, + "List Primary storage should return a valid list" + ) + self.assertGreaterEqual( + len(storage_pools), + 2, + "Test requires atleast 2 primary storages added to pod" + ) + self.debug("Uploading the volume to account: %s" % + self.account.account.name) + # Upload the volume + volume = Volume.upload( + self.apiclient, + self.services["volume"], + zoneid=self.zone.id, + account=self.account.account.name, + domainid=self.account.account.domainid, + url=self.services["volume"]["url"] + ) + self.debug("Registered volume: %s for account: %s" % ( + volume.name, + self.account.account.name + )) + self.debug("Waiting for upload of volume: %s" % volume.name) + try: + volume.wait_for_upload(self.apiclient) + self.debug("Volume: %s uploaded to CS successfully" % volume.name) + except Exception as e: + self.fail("Upload volume failed: %s" % e) + + # Check List Volume response for newly created volume + list_volume_response = Volume.list( + self.apiclient, + id=volume.id, + zoneid=self.zone.id, + listall=True + ) + self.assertNotEqual( + list_volume_response, + None, + "Check if volume exists in ListVolumes" + ) + volume_response = list_volume_response[0] + self.assertEqual( + volume_response.state, + "Uploaded", + "Volume state should be 'Uploaded' after importing to CS" + ) + return diff --git a/test/integration/lib/base.py b/test/integration/lib/base.py index 69882bcb13d..cc783c6764b 100644 --- a/test/integration/lib/base.py +++ b/test/integration/lib/base.py @@ -51,8 +51,12 @@ class Domain: cmd.parentdomainid = parentdomainid elif "parentdomainid" in services: cmd.parentdomainid = services["parentdomainid"] - - return Domain(apiclient.createDomain(cmd).__dict__) + try: + domain = apiclient.createDomain(cmd) + if domain is not None: + return Domain(domain.__dict__) + except Exception as e: + raise e def delete(self, apiclient, cleanup=None): """Delete an domain""" @@ -155,6 +159,12 @@ class User: [setattr(cmd, k, v) for k, v in kwargs.items()] return(apiclient.listUsers(cmd)) + @classmethod + def registerUserKeys(cls, apiclient, userid): + cmd = registerUserKeys.registerUserKeysCmd() + cmd.id = userid + return apiclient.registerUserKeys(cmd) + class VirtualMachine: """Manage virtual machine lifecycle""" @@ -255,14 +265,14 @@ class VirtualMachine: virtual_machine.domainid, services ) - fw_rule = FireWallRule.create( + FireWallRule.create( apiclient, ipaddressid=public_ip.ipaddress.id, protocol='TCP', cidrlist=['0.0.0.0/0'], startport=22, endport=22 - ) + ) nat_rule = NATRule.create( apiclient, virtual_machine, @@ -481,7 +491,7 @@ class Volume: return(apiclient.listVolumes(cmd)) @classmethod - def upload(cls, apiclient, services, zoneid=None, account=None, domainid=None): + def upload(cls, apiclient, services, zoneid=None, account=None, domainid=None, url=None): """Uploads the volume to specified account""" cmd = uploadVolume.uploadVolumeCmd() @@ -493,7 +503,10 @@ class Volume: cmd.domainid = domainid cmd.format = services["format"] cmd.name = services["diskname"] - cmd.url = services["url"] + if url: + cmd.url = url + else: + cmd.url = services["url"] return Volume(apiclient.uploadVolume(cmd).__dict__) def wait_for_upload(self, apiclient, timeout=5, interval=60): @@ -506,14 +519,13 @@ class Volume: apiclient, id=self.id, zoneid=self.zoneid, - templatefilter='self' ) if isinstance(volume_response, list): volume = volume_response[0] # If volume is ready, # volume.state = Allocated - if volue.state == 'Allocated': + if volume.state == 'Uploaded': break elif 'Uploading' in volume.state: @@ -523,7 +535,6 @@ class Volume: raise Exception( "Error in uploading volume: status - %s" % volume.state) - elif timeout == 0: break @@ -532,6 +543,7 @@ class Volume: timeout = timeout - 1 return + class Snapshot: """Manage Snapshot Lifecycle """ @@ -1104,7 +1116,7 @@ class NetworkOffering: cmd.specifyVlan = services["specifyVlan"] if "specifyIpRanges" in services: cmd.specifyIpRanges = services["specifyIpRanges"] - cmd.availability = 'Optional' + cmd.availability = 'Optional' [setattr(cmd, k, v) for k, v in kwargs.items()] @@ -1811,6 +1823,7 @@ class PhysicalNetwork: [setattr(cmd, k, v) for k, v in kwargs.items()] return(apiclient.listPhysicalNetworks(cmd)) + class SecurityGroup: """Manage Security Groups""" @@ -2178,6 +2191,7 @@ class NetworkServiceProvider: [setattr(cmd, k, v) for k, v in kwargs.items()] return(apiclient.listNetworkServiceProviders(cmd)) + class Router: """Manage router life cycle""" From 931c3eb78eabcfbba1ba8c8af5b8e9390f137bc0 Mon Sep 17 00:00:00 2001 From: Alena Prokharchyk Date: Thu, 5 Jul 2012 09:45:03 -0700 Subject: [PATCH 03/26] VPC: removed NetworkACL interface; added getTrafficType() to Firewall --- api/src/com/cloud/api/ResponseGenerator.java | 3 +-- .../api/commands/CreateFirewallRuleCmd.java | 10 ++++--- .../commands/CreateIpForwardingRuleCmd.java | 5 ++++ .../api/commands/CreateNetworkACLCmd.java | 7 +++-- .../commands/CreatePortForwardingRuleCmd.java | 5 ++++ .../api/commands/DeleteFirewallRuleCmd.java | 5 ++-- .../api/commands/DeleteNetworkACLCmd.java | 4 +-- .../api/commands/ListNetworkACLsCmd.java | 7 +++-- .../network/firewall/NetworkACLService.java | 8 +++--- .../cloud/network/lb/LoadBalancingRule.java | 5 ++++ .../com/cloud/network/rules/FirewallRule.java | 6 +++++ .../com/cloud/network/rules/NetworkACL.java | 26 ------------------- .../src/com/cloud/api/ApiResponseHelper.java | 3 +-- .../element/VpcVirtualRouterElement.java | 3 +-- .../VpcVirtualNetworkApplianceManager.java | 6 ++--- ...VpcVirtualNetworkApplianceManagerImpl.java | 16 ++++++------ .../cloud/network/rules/FirewallRuleVO.java | 2 +- .../network/rules/StaticNatRuleImpl.java | 7 +++-- .../cloud/network/vpc/NetworkACLManager.java | 4 +-- .../network/vpc/NetworkACLManagerImpl.java | 25 ++++++++++-------- 20 files changed, 78 insertions(+), 79 deletions(-) delete mode 100644 api/src/com/cloud/network/rules/NetworkACL.java diff --git a/api/src/com/cloud/api/ResponseGenerator.java b/api/src/com/cloud/api/ResponseGenerator.java index 0906706ce06..ce1245b3947 100755 --- a/api/src/com/cloud/api/ResponseGenerator.java +++ b/api/src/com/cloud/api/ResponseGenerator.java @@ -109,7 +109,6 @@ import com.cloud.network.VpnUser; import com.cloud.network.router.VirtualRouter; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.LoadBalancer; -import com.cloud.network.rules.NetworkACL; import com.cloud.network.rules.PortForwardingRule; import com.cloud.network.rules.StaticNatRule; import com.cloud.network.rules.StickinessPolicy; @@ -320,7 +319,7 @@ public interface ResponseGenerator { * @param networkACL * @return */ - NetworkACLResponse createNetworkACLResponse(NetworkACL networkACL); + NetworkACLResponse createNetworkACLResponse(FirewallRule networkACL); /** * @param result diff --git a/api/src/com/cloud/api/commands/CreateFirewallRuleCmd.java b/api/src/com/cloud/api/commands/CreateFirewallRuleCmd.java index 885405e64e0..abeaa15ebac 100644 --- a/api/src/com/cloud/api/commands/CreateFirewallRuleCmd.java +++ b/api/src/com/cloud/api/commands/CreateFirewallRuleCmd.java @@ -33,7 +33,6 @@ import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.IpAddress; import com.cloud.network.rules.FirewallRule; -import com.cloud.network.rules.NetworkACL; import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.utils.net.NetUtils; @@ -118,13 +117,13 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal public void execute() throws ResourceUnavailableException { UserContext callerContext = UserContext.current(); boolean success = false; - FirewallRule rule = _entityMgr.findById(NetworkACL.class, getEntityId()); + FirewallRule rule = _entityMgr.findById(FirewallRule.class, getEntityId()); try { UserContext.current().setEventDetails("Rule Id: " + getEntityId()); success = _firewallService.applyFirewallRules(rule.getSourceIpAddressId(), callerContext.getCaller()); // State is different after the rule is applied, so get new object here - rule = _entityMgr.findById(NetworkACL.class, getEntityId()); + rule = _entityMgr.findById(FirewallRule.class, getEntityId()); FirewallResponse fwResponse = new FirewallResponse(); if (rule != null) { fwResponse = _responseGenerator.createFirewallResponse(rule); @@ -313,5 +312,10 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; } + + @Override + public TrafficType getTrafficType() { + return null; + } } diff --git a/api/src/com/cloud/api/commands/CreateIpForwardingRuleCmd.java b/api/src/com/cloud/api/commands/CreateIpForwardingRuleCmd.java index af65b4493fe..4e65a0ffbf4 100644 --- a/api/src/com/cloud/api/commands/CreateIpForwardingRuleCmd.java +++ b/api/src/com/cloud/api/commands/CreateIpForwardingRuleCmd.java @@ -298,5 +298,10 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; } + + @Override + public TrafficType getTrafficType() { + return null; + } } diff --git a/api/src/com/cloud/api/commands/CreateNetworkACLCmd.java b/api/src/com/cloud/api/commands/CreateNetworkACLCmd.java index 487b6c9d041..68d996a2ea7 100644 --- a/api/src/com/cloud/api/commands/CreateNetworkACLCmd.java +++ b/api/src/com/cloud/api/commands/CreateNetworkACLCmd.java @@ -22,7 +22,6 @@ import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network; import com.cloud.network.rules.FirewallRule; -import com.cloud.network.rules.NetworkACL; import com.cloud.network.vpc.Vpc; import com.cloud.user.Account; import com.cloud.user.UserContext; @@ -30,7 +29,7 @@ import com.cloud.utils.net.NetUtils; @Implementation(description = "Creates a ACL rule the given network (the network has to belong to VPC)", responseObject = NetworkACLResponse.class) -public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements NetworkACL { +public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallRule { public static final Logger s_logger = Logger.getLogger(CreateNetworkACLCmd.class.getName()); private static final String s_name = "createnetworkaclresponse"; @@ -139,7 +138,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements NetworkAC public void execute() throws ResourceUnavailableException { UserContext callerContext = UserContext.current(); boolean success = false; - NetworkACL rule = _networkACLService.getNetworkACL(getEntityId()); + FirewallRule rule = _networkACLService.getNetworkACL(getEntityId()); try { UserContext.current().setEventDetails("Rule Id: " + getEntityId()); success = _networkACLService.applyNetworkACLs(rule.getNetworkId(), callerContext.getCaller()); @@ -239,7 +238,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements NetworkAC } try { - NetworkACL result = _networkACLService.createNetworkACL(this); + FirewallRule result = _networkACLService.createNetworkACL(this); setEntityId(result.getId()); } catch (NetworkRuleConflictException ex) { s_logger.info("Network rule conflict: " + ex.getMessage()); diff --git a/api/src/com/cloud/api/commands/CreatePortForwardingRuleCmd.java b/api/src/com/cloud/api/commands/CreatePortForwardingRuleCmd.java index 50650810cc7..2c5a0739094 100644 --- a/api/src/com/cloud/api/commands/CreatePortForwardingRuleCmd.java +++ b/api/src/com/cloud/api/commands/CreatePortForwardingRuleCmd.java @@ -354,4 +354,9 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P return AsyncJob.Type.FirewallRule; } + @Override + public TrafficType getTrafficType() { + return null; + } + } diff --git a/api/src/com/cloud/api/commands/DeleteFirewallRuleCmd.java b/api/src/com/cloud/api/commands/DeleteFirewallRuleCmd.java index 0640be4f274..7d8f0e71174 100644 --- a/api/src/com/cloud/api/commands/DeleteFirewallRuleCmd.java +++ b/api/src/com/cloud/api/commands/DeleteFirewallRuleCmd.java @@ -27,7 +27,6 @@ import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.rules.FirewallRule; -import com.cloud.network.rules.NetworkACL; import com.cloud.user.UserContext; @Implementation(description="Deletes a firewall rule", responseObject=SuccessResponse.class) @@ -76,11 +75,11 @@ public class DeleteFirewallRuleCmd extends BaseAsyncCmd { @Override public long getEntityOwnerId() { if (ownerId == null) { - FirewallRule rule = _entityMgr.findById(NetworkACL.class, id); + FirewallRule rule = _entityMgr.findById(FirewallRule.class, id); if (rule == null) { throw new InvalidParameterValueException("Unable to find firewall rule by id=" + id); } else { - ownerId = _entityMgr.findById(NetworkACL.class, id).getAccountId(); + ownerId = _entityMgr.findById(FirewallRule.class, id).getAccountId(); } } return ownerId; diff --git a/api/src/com/cloud/api/commands/DeleteNetworkACLCmd.java b/api/src/com/cloud/api/commands/DeleteNetworkACLCmd.java index 414822bdb33..9c0846544dd 100644 --- a/api/src/com/cloud/api/commands/DeleteNetworkACLCmd.java +++ b/api/src/com/cloud/api/commands/DeleteNetworkACLCmd.java @@ -29,7 +29,7 @@ import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.rules.NetworkACL; +import com.cloud.network.rules.FirewallRule; import com.cloud.user.UserContext; @Implementation(description="Deletes a Network ACL", responseObject=SuccessResponse.class) @@ -78,7 +78,7 @@ public class DeleteNetworkACLCmd extends BaseAsyncCmd { @Override public long getEntityOwnerId() { if (ownerId == null) { - NetworkACL rule = _networkACLService.getNetworkACL(id); + FirewallRule rule = _networkACLService.getNetworkACL(id); if (rule == null) { throw new InvalidParameterValueException("Unable to find network ACL by id=" + id); } else { diff --git a/api/src/com/cloud/api/commands/ListNetworkACLsCmd.java b/api/src/com/cloud/api/commands/ListNetworkACLsCmd.java index c6e477b9428..e7d37907dad 100644 --- a/api/src/com/cloud/api/commands/ListNetworkACLsCmd.java +++ b/api/src/com/cloud/api/commands/ListNetworkACLsCmd.java @@ -26,10 +26,9 @@ import com.cloud.api.BaseListProjectAndAccountResourcesCmd; import com.cloud.api.IdentityMapper; import com.cloud.api.Implementation; import com.cloud.api.Parameter; -import com.cloud.api.response.FirewallResponse; import com.cloud.api.response.ListResponse; import com.cloud.api.response.NetworkACLResponse; -import com.cloud.network.rules.NetworkACL; +import com.cloud.network.rules.FirewallRule; @Implementation(description="Lists all network ACLs", responseObject=NetworkACLResponse.class) public class ListNetworkACLsCmd extends BaseListProjectAndAccountResourcesCmd { @@ -78,11 +77,11 @@ public class ListNetworkACLsCmd extends BaseListProjectAndAccountResourcesCmd { @Override public void execute(){ - List result = _networkACLService.listNetworkACLs(this); + List result = _networkACLService.listNetworkACLs(this); ListResponse response = new ListResponse(); List aclResponses = new ArrayList(); - for (NetworkACL acl : result) { + for (FirewallRule acl : result) { NetworkACLResponse ruleData = _responseGenerator.createNetworkACLResponse(acl); aclResponses.add(ruleData); } diff --git a/api/src/com/cloud/network/firewall/NetworkACLService.java b/api/src/com/cloud/network/firewall/NetworkACLService.java index 3cdb0583aae..4aaf058d93e 100644 --- a/api/src/com/cloud/network/firewall/NetworkACLService.java +++ b/api/src/com/cloud/network/firewall/NetworkACLService.java @@ -17,21 +17,21 @@ import java.util.List; import com.cloud.api.commands.ListNetworkACLsCmd; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.rules.NetworkACL; +import com.cloud.network.rules.FirewallRule; import com.cloud.user.Account; /** * @author Alena Prokharchyk */ public interface NetworkACLService { - NetworkACL getNetworkACL(long ruleId); + FirewallRule getNetworkACL(long ruleId); boolean applyNetworkACLs(long networkId, Account caller) throws ResourceUnavailableException; /** * @param createNetworkACLCmd * @return */ - NetworkACL createNetworkACL(NetworkACL acl) throws NetworkRuleConflictException; + FirewallRule createNetworkACL(FirewallRule acl) throws NetworkRuleConflictException; /** * @param ruleId * @param apply @@ -42,6 +42,6 @@ public interface NetworkACLService { * @param listNetworkACLsCmd * @return */ - List listNetworkACLs(ListNetworkACLsCmd cmd); + List listNetworkACLs(ListNetworkACLsCmd cmd); } diff --git a/api/src/com/cloud/network/lb/LoadBalancingRule.java b/api/src/com/cloud/network/lb/LoadBalancingRule.java index 0ef55a16afe..fb789fd6d73 100644 --- a/api/src/com/cloud/network/lb/LoadBalancingRule.java +++ b/api/src/com/cloud/network/lb/LoadBalancingRule.java @@ -214,4 +214,9 @@ public class LoadBalancingRule implements FirewallRule, LoadBalancer{ public FirewallRuleType getType() { return FirewallRuleType.User; } + + @Override + public TrafficType getTrafficType() { + return null; + } } diff --git a/api/src/com/cloud/network/rules/FirewallRule.java b/api/src/com/cloud/network/rules/FirewallRule.java index b3b90a94567..2b57f96a9f1 100644 --- a/api/src/com/cloud/network/rules/FirewallRule.java +++ b/api/src/com/cloud/network/rules/FirewallRule.java @@ -15,6 +15,7 @@ package com.cloud.network.rules; import java.util.List; import com.cloud.acl.ControlledEntity; +import com.cloud.network.rules.FirewallRule.TrafficType; public interface FirewallRule extends ControlledEntity { enum Purpose { @@ -86,4 +87,9 @@ public interface FirewallRule extends ControlledEntity { FirewallRuleType getType(); + /** + * @return + */ + TrafficType getTrafficType(); + } diff --git a/api/src/com/cloud/network/rules/NetworkACL.java b/api/src/com/cloud/network/rules/NetworkACL.java deleted file mode 100644 index d0f7f21eca0..00000000000 --- a/api/src/com/cloud/network/rules/NetworkACL.java +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2012 Citrix Systems, Inc. Licensed under the -// Apache License, Version 2.0 (the "License"); you may not use this -// file except in compliance with the License. Citrix Systems, Inc. -// reserves all rights not expressly granted by the License. -// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 04/03/2012 -package com.cloud.network.rules; - - -/** - * @author Alena Prokharchyk - */ -public interface NetworkACL extends FirewallRule{ - - /** - * @return - */ - TrafficType getTrafficType(); - -} diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index f616f933b18..26245e22076 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -149,7 +149,6 @@ import com.cloud.network.VpnUser; import com.cloud.network.router.VirtualRouter; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.LoadBalancer; -import com.cloud.network.rules.NetworkACL; import com.cloud.network.rules.PortForwardingRule; import com.cloud.network.rules.StaticNatRule; import com.cloud.network.rules.StickinessPolicy; @@ -3095,7 +3094,7 @@ public class ApiResponseHelper implements ResponseGenerator { } @Override - public NetworkACLResponse createNetworkACLResponse(NetworkACL networkACL) { + public NetworkACLResponse createNetworkACLResponse(FirewallRule networkACL) { NetworkACLResponse response = new NetworkACLResponse(); response.setId(networkACL.getId()); diff --git a/server/src/com/cloud/network/element/VpcVirtualRouterElement.java b/server/src/com/cloud/network/element/VpcVirtualRouterElement.java index b6f6d65340a..29a82dd2d34 100644 --- a/server/src/com/cloud/network/element/VpcVirtualRouterElement.java +++ b/server/src/com/cloud/network/element/VpcVirtualRouterElement.java @@ -46,7 +46,6 @@ import com.cloud.network.router.VirtualRouter; import com.cloud.network.router.VirtualRouter.Role; import com.cloud.network.router.VpcVirtualNetworkApplianceManager; import com.cloud.network.rules.FirewallRule; -import com.cloud.network.rules.NetworkACL; import com.cloud.network.vpc.PrivateGateway; import com.cloud.network.vpc.StaticRouteProfile; import com.cloud.network.vpc.Vpc; @@ -406,7 +405,7 @@ public class VpcVirtualRouterElement extends VirtualRouterElement implements Vpc return true; } - if (!_vpcRouterMgr.applyNetworkACLs(config, (List)rules, routers)) { + if (!_vpcRouterMgr.applyNetworkACLs(config, rules, routers)) { throw new CloudRuntimeException("Failed to apply firewall rules in network " + config.getId()); } else { return true; diff --git a/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManager.java b/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManager.java index f0a3cececd3..fd05e984217 100644 --- a/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManager.java +++ b/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManager.java @@ -22,10 +22,10 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network; import com.cloud.network.Site2SiteVpnConnection; import com.cloud.network.VpcVirtualNetworkApplianceService; -import com.cloud.network.rules.NetworkACL; +import com.cloud.network.rules.FirewallRule; +import com.cloud.network.vpc.PrivateGateway; import com.cloud.network.vpc.StaticRouteProfile; import com.cloud.network.vpc.Vpc; -import com.cloud.network.vpc.PrivateGateway; import com.cloud.user.Account; import com.cloud.vm.DomainRouterVO; import com.cloud.vm.VirtualMachineProfile.Param; @@ -56,7 +56,7 @@ public interface VpcVirtualNetworkApplianceManager extends VirtualNetworkApplian * @return * @throws ResourceUnavailableException */ - boolean applyNetworkACLs(Network network, List rules, List routers) + boolean applyNetworkACLs(Network network, List rules, List routers) throws ResourceUnavailableException; /** diff --git a/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java index 89f16c3f847..82303b205d2 100644 --- a/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java @@ -75,7 +75,7 @@ import com.cloud.network.VirtualRouterProvider.VirtualRouterProviderType; import com.cloud.network.VpcVirtualNetworkApplianceService; import com.cloud.network.addr.PublicIp; import com.cloud.network.dao.PhysicalNetworkDao; -import com.cloud.network.rules.NetworkACL; +import com.cloud.network.rules.FirewallRule; import com.cloud.network.vpc.NetworkACLManager; import com.cloud.network.vpc.PrivateGateway; import com.cloud.network.vpc.PrivateIpAddress; @@ -687,7 +687,7 @@ public class VpcVirtualNetworkApplianceManagerImpl extends VirtualNetworkApplian } @Override - public boolean applyNetworkACLs(Network network, final List rules, List routers) + public boolean applyNetworkACLs(Network network, final List rules, List routers) throws ResourceUnavailableException { if (rules == null || rules.isEmpty()) { s_logger.debug("No network ACLs to be applied for network " + network.getId()); @@ -696,20 +696,20 @@ public class VpcVirtualNetworkApplianceManagerImpl extends VirtualNetworkApplian return applyRules(network, routers, "network acls", false, null, false, new RuleApplier() { @Override public boolean execute(Network network, VirtualRouter router) throws ResourceUnavailableException { - return sendNetworkACLs(router, (List)rules, network.getId()); + return sendNetworkACLs(router, rules, network.getId()); } }); } - protected boolean sendNetworkACLs(VirtualRouter router, List rules, long guestNetworkId) + protected boolean sendNetworkACLs(VirtualRouter router, List rules, long guestNetworkId) throws ResourceUnavailableException { Commands cmds = new Commands(OnError.Continue); createNetworkACLsCommands(rules, router, cmds, guestNetworkId); return sendCommandsToRouter(router, cmds); } - private void createNetworkACLsCommands(List rules, VirtualRouter router, Commands cmds, long guestNetworkId) { + private void createNetworkACLsCommands(List rules, VirtualRouter router, Commands cmds, long guestNetworkId) { List rulesTO = null; String guestVlan = null; Network guestNtwk = _networkDao.findById(guestNetworkId); @@ -721,7 +721,7 @@ public class VpcVirtualNetworkApplianceManagerImpl extends VirtualNetworkApplian if (rules != null) { rulesTO = new ArrayList(); - for (NetworkACL rule : rules) { + for (FirewallRule rule : rules) { NetworkACLTO ruleTO = new NetworkACLTO(rule, guestVlan, rule.getTrafficType()); rulesTO.add(ruleTO); } @@ -898,11 +898,11 @@ public class VpcVirtualNetworkApplianceManagerImpl extends VirtualNetworkApplian super.finalizeNetworkRulesForNetwork(cmds, router, provider, guestNetworkId); if (_networkMgr.isProviderSupportServiceInNetwork(guestNetworkId, Service.NetworkACL, Provider.VPCVirtualRouter)) { - List networkACLs = _networkACLMgr.listNetworkACLs(guestNetworkId); + List networkACLs = _networkACLMgr.listNetworkACLs(guestNetworkId); s_logger.debug("Found " + networkACLs.size() + " network ACLs to apply as a part of VPC VR " + router + " start for guest network id=" + guestNetworkId); if (!networkACLs.isEmpty()) { - createNetworkACLsCommands((List)networkACLs, router, cmds, guestNetworkId); + createNetworkACLsCommands(networkACLs, router, cmds, guestNetworkId); } } } diff --git a/server/src/com/cloud/network/rules/FirewallRuleVO.java b/server/src/com/cloud/network/rules/FirewallRuleVO.java index 4440c31d6f2..bcb10eddae0 100644 --- a/server/src/com/cloud/network/rules/FirewallRuleVO.java +++ b/server/src/com/cloud/network/rules/FirewallRuleVO.java @@ -40,7 +40,7 @@ import com.cloud.utils.net.NetUtils; @Table(name="firewall_rules") @Inheritance(strategy=InheritanceType.JOINED) @DiscriminatorColumn(name="purpose", discriminatorType=DiscriminatorType.STRING, length=32) -public class FirewallRuleVO implements Identity, NetworkACL { +public class FirewallRuleVO implements Identity, FirewallRule { protected final FirewallRulesCidrsDaoImpl _firewallRulesCidrsDao = ComponentLocator.inject(FirewallRulesCidrsDaoImpl.class); @Id diff --git a/server/src/com/cloud/network/rules/StaticNatRuleImpl.java b/server/src/com/cloud/network/rules/StaticNatRuleImpl.java index cf6783926c4..52d6d3dcf55 100644 --- a/server/src/com/cloud/network/rules/StaticNatRuleImpl.java +++ b/server/src/com/cloud/network/rules/StaticNatRuleImpl.java @@ -14,8 +14,6 @@ package com.cloud.network.rules; import java.util.List; -import com.cloud.network.rules.FirewallRule.FirewallRuleType; - public class StaticNatRuleImpl implements StaticNatRule{ long id; @@ -128,5 +126,10 @@ public class StaticNatRuleImpl implements StaticNatRule{ public FirewallRuleType getType() { return FirewallRuleType.User; } + + @Override + public TrafficType getTrafficType() { + return null; + } } diff --git a/server/src/com/cloud/network/vpc/NetworkACLManager.java b/server/src/com/cloud/network/vpc/NetworkACLManager.java index 01f54f01b2f..c271bfa9c96 100644 --- a/server/src/com/cloud/network/vpc/NetworkACLManager.java +++ b/server/src/com/cloud/network/vpc/NetworkACLManager.java @@ -16,7 +16,7 @@ import java.util.List; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.firewall.NetworkACLService; -import com.cloud.network.rules.NetworkACL; +import com.cloud.network.rules.FirewallRule; import com.cloud.user.Account; /** @@ -33,6 +33,6 @@ public interface NetworkACLManager extends NetworkACLService{ */ boolean revokeAllNetworkACLsForNetwork(long networkId, long userId, Account caller) throws ResourceUnavailableException; - List listNetworkACLs(long guestNtwkId); + List listNetworkACLs(long guestNtwkId); } diff --git a/server/src/com/cloud/network/vpc/NetworkACLManagerImpl.java b/server/src/com/cloud/network/vpc/NetworkACLManagerImpl.java index 985f7145ad8..faef7115ed9 100644 --- a/server/src/com/cloud/network/vpc/NetworkACLManagerImpl.java +++ b/server/src/com/cloud/network/vpc/NetworkACLManagerImpl.java @@ -42,7 +42,6 @@ import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.FirewallRule.Purpose; import com.cloud.network.rules.FirewallRule.TrafficType; import com.cloud.network.rules.FirewallRuleVO; -import com.cloud.network.rules.NetworkACL; import com.cloud.projects.Project.ListProjectResourcesCriteria; import com.cloud.user.Account; import com.cloud.user.AccountManager; @@ -111,7 +110,7 @@ public class NetworkACLManagerImpl implements Manager,NetworkACLManager{ } @Override - public NetworkACL createNetworkACL(NetworkACL acl) throws NetworkRuleConflictException { + public FirewallRule createNetworkACL(FirewallRule acl) throws NetworkRuleConflictException { return createNetworkACL(UserContext.current().getCaller(), acl.getXid(), acl.getSourcePortStart(), acl.getSourcePortEnd(), acl.getProtocol(), acl.getSourceCidrList(), acl.getIcmpCode(), acl.getIcmpType(), null, acl.getType(), acl.getNetworkId(), acl.getTrafficType()); @@ -119,7 +118,7 @@ public class NetworkACLManagerImpl implements Manager,NetworkACLManager{ @DB @ActionEvent(eventType = EventTypes.EVENT_FIREWALL_OPEN, eventDescription = "creating firewall rule", create = true) - protected NetworkACL createNetworkACL(Account caller, String xId, Integer portStart, + protected FirewallRule createNetworkACL(Account caller, String xId, Integer portStart, Integer portEnd, String protocol, List sourceCidrList, Integer icmpCode, Integer icmpType, Long relatedRuleId, FirewallRule.FirewallRuleType type, long networkId, TrafficType trafficType) throws NetworkRuleConflictException { @@ -173,7 +172,7 @@ public class NetworkACLManagerImpl implements Manager,NetworkACLManager{ txn.commit(); - return newRule; + return getNetworkACL(newRule.getId()); } @@ -210,9 +209,13 @@ public class NetworkACLManagerImpl implements Manager,NetworkACLManager{ } } - protected void detectNetworkACLConflict(NetworkACL newRule) throws NetworkRuleConflictException { - - List rules = _firewallDao.listByNetworkPurposeTrafficTypeAndNotRevoked(newRule.getNetworkId(), Purpose.NetworkACL, newRule.getTrafficType()); + protected void detectNetworkACLConflict(FirewallRuleVO newRule) throws NetworkRuleConflictException { + if (newRule.getPurpose() != Purpose.NetworkACL) { + return; + } + + List rules = _firewallDao.listByNetworkPurposeTrafficTypeAndNotRevoked(newRule.getNetworkId(), + Purpose.NetworkACL, newRule.getTrafficType()); assert (rules.size() >= 1) : "For network ACLs, we now always first persist the rule and then check for " + "network conflicts so we should at least have one rule at this point."; @@ -301,8 +304,8 @@ public class NetworkACLManagerImpl implements Manager,NetworkACLManager{ } @Override - public NetworkACL getNetworkACL(long ACLId) { - FirewallRuleVO rule = _firewallDao.findById(ACLId); + public FirewallRule getNetworkACL(long ACLId) { + FirewallRule rule = _firewallDao.findById(ACLId); if (rule != null && rule.getPurpose() == Purpose.NetworkACL) { return rule; } @@ -310,7 +313,7 @@ public class NetworkACLManagerImpl implements Manager,NetworkACLManager{ } @Override - public List listNetworkACLs(ListNetworkACLsCmd cmd) { + public List listNetworkACLs(ListNetworkACLsCmd cmd) { Long networkId = cmd.getNetworkId(); Long id = cmd.getId(); String trafficType = cmd.getTrafficType(); @@ -357,7 +360,7 @@ public class NetworkACLManagerImpl implements Manager,NetworkACLManager{ @Override - public List listNetworkACLs(long guestNtwkId) { + public List listNetworkACLs(long guestNtwkId) { return _firewallDao.listByNetworkAndPurpose(guestNtwkId, Purpose.NetworkACL); } From e6d73fb1149f648eadb279c620f001400da488ab Mon Sep 17 00:00:00 2001 From: Alena Prokharchyk Date: Thu, 5 Jul 2012 10:32:51 -0700 Subject: [PATCH 04/26] VPC: added dns1/dns2 + networkDomain to the list of bootload args passed on VPC VR start --- .../VirtualNetworkApplianceManagerImpl.java | 5 ----- .../VpcVirtualNetworkApplianceManagerImpl.java | 18 +++++++++++++++--- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java index 456677aac57..b5aed7e089b 100755 --- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java @@ -48,7 +48,6 @@ import com.cloud.agent.api.GetDomRVersionCmd; import com.cloud.agent.api.ModifySshKeysCommand; import com.cloud.agent.api.NetworkUsageAnswer; import com.cloud.agent.api.NetworkUsageCommand; -import com.cloud.agent.api.RebootAnswer; import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StopAnswer; import com.cloud.agent.api.check.CheckSshAnswer; @@ -63,7 +62,6 @@ import com.cloud.agent.api.routing.SetFirewallRulesCommand; import com.cloud.agent.api.routing.SetPortForwardingRulesCommand; import com.cloud.agent.api.routing.SetPortForwardingRulesVpcCommand; import com.cloud.agent.api.routing.SetStaticNatRulesCommand; -import com.cloud.agent.api.routing.Site2SiteVpnCfgCommand; import com.cloud.agent.api.routing.VmDataCommand; import com.cloud.agent.api.routing.VpnUsersCfgCommand; import com.cloud.agent.api.to.FirewallRuleTO; @@ -129,9 +127,6 @@ import com.cloud.network.Networks.TrafficType; import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.network.PublicIpAddress; import com.cloud.network.RemoteAccessVpn; -import com.cloud.network.Site2SiteCustomerGatewayVO; -import com.cloud.network.Site2SiteVpnConnection; -import com.cloud.network.Site2SiteVpnGatewayVO; import com.cloud.network.SshKeysDistriMonitor; import com.cloud.network.VirtualNetworkApplianceService; import com.cloud.network.VirtualRouterProvider; diff --git a/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java index 82303b205d2..4805df8f1d5 100644 --- a/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java @@ -666,21 +666,33 @@ public class VpcVirtualNetworkApplianceManagerImpl extends VirtualNetworkApplian ReservationContext context) { if (profile.getVirtualMachine().getVpcId() != null) { - //remove public and guest nics as we will plug them later + String defaultDns1 = null; + String defaultDns2 = null; + //remove public and guest nics as we will plug them later Iterator it = profile.getNics().iterator(); while (it.hasNext()) { NicProfile nic = it.next(); if (nic.getTrafficType() == TrafficType.Public || nic.getTrafficType() == TrafficType.Guest) { + //save dns information + if(nic.getTrafficType() == TrafficType.Public) { + defaultDns1 = nic.getDns1(); + defaultDns2 = nic.getDns2(); + } s_logger.debug("Removing nic of type " + nic.getTrafficType() + " from the nics passed on vm start. " + "The nic will be plugged later"); it.remove(); } } - //add vpc cidr to the boot load args + //add vpc cidr/dns/networkdomain to the boot load args StringBuilder buf = profile.getBootArgsBuilder(); Vpc vpc = _vpcMgr.getVpc(profile.getVirtualMachine().getVpcId()); - buf.append(" vpccidr=" + vpc.getCidr()); + buf.append(" vpccidr=" + vpc.getCidr() + " domain=" + vpc.getNetworkDomain()); + + buf.append(" dns1=").append(defaultDns1); + if (defaultDns2 != null) { + buf.append(" dns2=").append(defaultDns2); + } } return super.finalizeVirtualMachineProfile(profile, dest, context); From f1ac568a912df647a397dc47e5842e4ab7609987 Mon Sep 17 00:00:00 2001 From: anthony Date: Thu, 5 Jul 2012 11:53:04 -0700 Subject: [PATCH 05/26] VPC : check if dns1 is null --- .../network/router/VirtualNetworkApplianceManagerImpl.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java index b5aed7e089b..2488c680db2 100755 --- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java @@ -1717,7 +1717,9 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian * to return DNS server rather than * virtual router itself. */ if (dnsProvided || dhcpProvided) { - buf.append(" dns1=").append(defaultDns1); + if (defaultDns1 != null) { + buf.append(" dns1=").append(defaultDns1); + } if (defaultDns2 != null) { buf.append(" dns2=").append(defaultDns2); } From 212baba7b1b5fb6429d7e3aa6e496a5440e1a210 Mon Sep 17 00:00:00 2001 From: Jessica Wang Date: Thu, 5 Jul 2012 13:14:52 -0700 Subject: [PATCH 06/26] cloudstack 3.0 UI - VPC - implement "Add new tier" action. --- ui/scripts/vpc.js | 109 ++++++++++++++++++++++++++++++++++------------ 1 file changed, 81 insertions(+), 28 deletions(-) diff --git a/ui/scripts/vpc.js b/ui/scripts/vpc.js index b8beeaa5aa7..23b424decab 100644 --- a/ui/scripts/vpc.js +++ b/ui/scripts/vpc.js @@ -380,35 +380,84 @@ return state == 'Running' ? ['start'] : ['stop']; }, - actions: { - // Add new tier + actions: { add: { - label: 'Add new tier to VPC', - action: function(args) { - setTimeout(function() { - args.response.success({ - data: { - name: args.data.name, - cidr: args.data.cidr, - state: 'Stopped' - } - }); - }, 500); - }, - - createForm: { - title: 'Add new tier', - desc: 'Please fill in the following to add a new VPC tier.', - fields: { - name: { label: 'label.name', validation: { required: true } }, - cidr: { label: 'label.cidr', validation: { required: true } } - } - }, - - notification: { - poll: function(args) { args.complete(); } - } - }, + label: 'Add new tier', + createForm: { + title: 'Add new tier', + fields: { + name: { label: 'label.name', + validation: { required: true } + }, + networkOfferingId: { + label: 'label.network.offering', + validation: { required: true }, + dependsOn: 'zoneId', + select: function(args) { + $.ajax({ + url: createURL('listNetworkOfferings'), + data: { + forvpc: true, + zoneid: args.zoneId, + guestiptype: 'Isolated', + supportedServices: 'SourceNat', + specifyvlan: false, + state: 'Enabled' + }, + success: function(json) { + var networkOfferings = json.listnetworkofferingsresponse.networkoffering; + args.response.success({ + data: $.map(networkOfferings, function(zone) { + return { + id: zone.id, + description: zone.name + }; + }) + }); + } + }); + } + }, + gateway: { + label: 'label.gateway', + validation: { required: true } + }, + netmask: { + label: 'label.netmask', + validation: { required: true } + }, + } + }, + action: function(args) { + var dataObj = { + vpcid: args.context.vpc[0].id, + zoneId: args.context.vpc[0].zoneid, + networkOfferingId: args.data.networkOfferingId, + name: args.data.name, + displayText: args.data.name, + gateway: args.data.gateway, + netmask: args.data.netmask + }; + + $.ajax({ + url: createURL('createNetwork'), + dataType: 'json', + data: dataObj, + success: function(json) { + args.response.success({ + data: json.createnetworkresponse.network + }); + }, + error: function(XMLHttpResponse) { + args.response.error(parseXMLHttpResponse(XMLHttpResponse)); + } + }); + }, + messages: { + notification: function() { return 'Add new tier'; } + } + }, + start: { label: 'Start tier', shortLabel: 'Start', @@ -419,6 +468,7 @@ poll: function(args) { args.complete({ data: { state: 'Running' } }); } } }, + stop: { label: 'Stop tier', shortLabel: 'Stop', @@ -429,6 +479,7 @@ poll: function(args) { args.complete({ data: { state: 'Stopped' } }); } } }, + addVM: { label: 'Add VM to tier', shortLabel: 'Add VM', @@ -439,11 +490,13 @@ poll: pollAsyncJobResult } }, + acl: { label: 'Configure ACL for tier', shortLabel: 'ACL', multiEdit: aclMultiEdit }, + remove: { label: 'Remove tier', action: function(args) { From 26afe3a96c36ed13bc71db46becc4eb444faa4f0 Mon Sep 17 00:00:00 2001 From: Jessica Wang Date: Thu, 5 Jul 2012 13:16:57 -0700 Subject: [PATCH 07/26] cloudstack 3.0 UI - instance wizard - network offering dropdown - populate only network offerings that are not for VPC. --- ui/scripts/instanceWizard.js | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/ui/scripts/instanceWizard.js b/ui/scripts/instanceWizard.js index 9d4a151f086..9d3347a3677 100644 --- a/ui/scripts/instanceWizard.js +++ b/ui/scripts/instanceWizard.js @@ -286,15 +286,18 @@ networkObjs = json.listnetworksresponse.network ? json.listnetworksresponse.network : []; } }); - - - var apiCmd = "listNetworkOfferings&guestiptype=Isolated&supportedServices=sourceNat&state=Enabled&specifyvlan=false&zoneid=" + args.currentData.zoneid ; - var array1 = []; - var guestTrafficTypeTotal = 0; - + $.ajax({ - url: createURL(apiCmd + array1.join("")), //get the network offering for isolated network with sourceNat + url: createURL("listNetworkOfferings"), dataType: "json", + data: { + forvpc: false, + zoneid: args.currentData.zoneid, + guestiptype: 'Isolated', + supportedServices: 'SourceNat', + specifyvlan: false, + state: 'Enabled' + }, async: false, success: function(json) { networkOfferingObjs = json.listnetworkofferingsresponse.networkoffering; From a39a08a40d040d326709ca733264d15d1e80c805 Mon Sep 17 00:00:00 2001 From: Jessica Wang Date: Thu, 5 Jul 2012 13:19:07 -0700 Subject: [PATCH 08/26] cloudstack 3.0 UI: ui-custom VPC - add error handling to addTierDialog(). --- ui/scripts/ui-custom/vpc.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/ui/scripts/ui-custom/vpc.js b/ui/scripts/ui-custom/vpc.js index c598c0880a6..84d0abe58b7 100644 --- a/ui/scripts/ui-custom/vpc.js +++ b/ui/scripts/ui-custom/vpc.js @@ -504,7 +504,11 @@ $loading.remove(); } ); - } + }, + error: function(errorMsg) { + cloudStack.dialog.notice({ message: _s(errorMsg) }); + $loading.remove(); + } } }); } From 2699e2c508177c12daddc9dd52f98c5a1afb30d5 Mon Sep 17 00:00:00 2001 From: Alena Prokharchyk Date: Thu, 5 Jul 2012 13:33:46 -0700 Subject: [PATCH 09/26] VPC: CS-15447 - fail vpc creation when vpc provider is not enabled at least in one physical network in the target zone --- .../com/cloud/network/NetworkManagerImpl.java | 6 +++--- .../com/cloud/network/vpc/VpcManagerImpl.java | 19 ++++++++++++++++++- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index e135264d3a4..14c48b6c3cb 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -2084,7 +2084,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag List providersToImplement = getNetworkProviders(network.getId()); for (NetworkElement element : _networkElements) { if (providersToImplement.contains(element.getProvider())) { - if (!isProviderEnabledInPhysicalNetwork(getPhysicalNetworkId(network), "VirtualRouter")) { + if (!isProviderEnabledInPhysicalNetwork(getPhysicalNetworkId(network), element.getProvider().getName())) { // The physicalNetworkId will not get translated into a uuid by the reponse serializer, // because the serializer would look up the NetworkVO class's table and retrieve the // network id instead of the physical network id. @@ -3521,7 +3521,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag for (NetworkElement element : _networkElements) { if (providersToShutdown.contains(element.getProvider())) { try { - if (!isProviderEnabledInPhysicalNetwork(getPhysicalNetworkId(network), "VirtualRouter")) { + if (!isProviderEnabledInPhysicalNetwork(getPhysicalNetworkId(network), element.getProvider().getName())) { s_logger.warn("Unable to complete shutdown of the network elements due to element: " + element.getName() + " either doesn't exist or not enabled in the physical network " + getPhysicalNetworkId(network)); success = false; @@ -3608,7 +3608,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag for (NetworkElement element : _networkElements) { if (providersToDestroy.contains(element.getProvider())) { try { - if (!isProviderEnabledInPhysicalNetwork(getPhysicalNetworkId(network), "VirtualRouter")) { + if (!isProviderEnabledInPhysicalNetwork(getPhysicalNetworkId(network), element.getProvider().getName())) { s_logger.warn("Unable to complete destroy of the network elements due to element: " + element.getName() + " either doesn't exist or not enabled in the physical network " + getPhysicalNetworkId(network)); success = false; diff --git a/server/src/com/cloud/network/vpc/VpcManagerImpl.java b/server/src/com/cloud/network/vpc/VpcManagerImpl.java index 12529134032..1697864323f 100644 --- a/server/src/com/cloud/network/vpc/VpcManagerImpl.java +++ b/server/src/com/cloud/network/vpc/VpcManagerImpl.java @@ -56,6 +56,7 @@ import com.cloud.network.Networks.TrafficType; import com.cloud.network.PhysicalNetwork; import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.NetworkDao; +import com.cloud.network.dao.PhysicalNetworkDao; import com.cloud.network.element.VpcProvider; import com.cloud.network.vpc.VpcOffering.State; import com.cloud.network.vpc.Dao.PrivateIpDao; @@ -132,6 +133,8 @@ public class VpcManagerImpl implements VpcManager, Manager{ NetworkOfferingServiceMapDao _ntwkOffServiceDao ; @Inject VpcOfferingServiceMapDao _vpcOffServiceDao; + @Inject + PhysicalNetworkDao _pNtwkDao; private final ScheduledExecutorService _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("VpcChecker")); @@ -502,7 +505,7 @@ public class VpcManagerImpl implements VpcManager, Manager{ if (networkDomain == null) { networkDomain = "cs" + Long.toHexString(owner.getId()) + _ntwkMgr.getDefaultNetworkDomain(); } - } + } return createVpc(zoneId, vpcOffId, owner, vpcName, displayText, cidr, networkDomain); } @@ -511,6 +514,20 @@ public class VpcManagerImpl implements VpcManager, Manager{ public Vpc createVpc(long zoneId, long vpcOffId, Account vpcOwner, String vpcName, String displayText, String cidr, String networkDomain) { + //the provider has to be enabled at least in one network in the zone + boolean providerEnabled = false; + for (PhysicalNetwork pNtwk : _pNtwkDao.listByZone(zoneId)) { + if (_ntwkMgr.isProviderEnabledInPhysicalNetwork(pNtwk.getId(), Provider.VPCVirtualRouter.getName())) { + providerEnabled = true; + break; + } + } + + if (!providerEnabled) { + throw new InvalidParameterValueException("Provider " + Provider.VPCVirtualRouter.getName() + + " should be enabled in at least one physical network of the zone specified"); + } + //Validate CIDR if (!NetUtils.isValidCIDR(cidr)) { throw new InvalidParameterValueException("Invalid CIDR specified " + cidr); From 2195f3ad838047f2492b58395820ce27db7b6be8 Mon Sep 17 00:00:00 2001 From: Murali Reddy Date: Thu, 5 Jul 2012 13:45:29 -0700 Subject: [PATCH 10/26] VPC : CS-15424 default route & gateway is missing for private network in VPC virtual router on Vmware reviewd by : Anthony adding route configuration through eth0 when VPC router --- patches/systemvm/debian/config/etc/init.d/cloud-early-config | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/patches/systemvm/debian/config/etc/init.d/cloud-early-config b/patches/systemvm/debian/config/etc/init.d/cloud-early-config index 2e6d3c3bca7..21324cbbac5 100755 --- a/patches/systemvm/debian/config/etc/init.d/cloud-early-config +++ b/patches/systemvm/debian/config/etc/init.d/cloud-early-config @@ -596,7 +596,10 @@ EOF fi if [ -n "$MGMTNET" -a -n "$LOCAL_GW" ] then - ip route add $MGMTNET via $LOCAL_GW dev eth1 + if [ "$hyp" == "vmware" ] + then + ip route add $MGMTNET via $LOCAL_GW dev eth0 + fi fi ip route delete default From d8cdb89721bab3ed9f77270a142b0c84eaa08246 Mon Sep 17 00:00:00 2001 From: Alena Prokharchyk Date: Thu, 5 Jul 2012 13:52:11 -0700 Subject: [PATCH 11/26] VPC: added field networkacl_service_provided to physical_network_service_providers table --- .../network/PhysicalNetworkServiceProvider.java | 2 ++ .../dao/PhysicalNetworkServiceProviderVO.java | 13 +++++++++++++ setup/db/create-schema.sql | 1 + 3 files changed, 16 insertions(+) diff --git a/api/src/com/cloud/network/PhysicalNetworkServiceProvider.java b/api/src/com/cloud/network/PhysicalNetworkServiceProvider.java index 109db0d7ee4..195640678e2 100644 --- a/api/src/com/cloud/network/PhysicalNetworkServiceProvider.java +++ b/api/src/com/cloud/network/PhysicalNetworkServiceProvider.java @@ -60,4 +60,6 @@ public interface PhysicalNetworkServiceProvider { List getEnabledServices(); String getUuid(); + + boolean isNetworkAclServiceProvided(); } diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderVO.java b/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderVO.java index 3e5694100c6..0fac443037e 100644 --- a/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderVO.java +++ b/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderVO.java @@ -87,6 +87,9 @@ public class PhysicalNetworkServiceProviderVO implements PhysicalNetworkServiceP @Column(name = "security_group_service_provided") boolean securitygroupServiceProvided; + @Column(name = "networkacl_service_provided") + boolean networkAclServiceProvided; + @Column(name=GenericDao.REMOVED_COLUMN) Date removed; @@ -261,6 +264,7 @@ public class PhysicalNetworkServiceProviderVO implements PhysicalNetworkServiceP this.setPortForwardingServiceProvided(services.contains(Service.PortForwarding)); this.setUserdataServiceProvided(services.contains(Service.UserData)); this.setSecuritygroupServiceProvided(services.contains(Service.SecurityGroup)); + this.setNetworkAclServiceProvided(services.contains(Service.NetworkACL)); } @Override @@ -301,4 +305,13 @@ public class PhysicalNetworkServiceProviderVO implements PhysicalNetworkServiceP } return services; } + + @Override + public boolean isNetworkAclServiceProvided() { + return networkAclServiceProvided; + } + + public void setNetworkAclServiceProvided(boolean networkAclServiceProvided) { + this.networkAclServiceProvided = networkAclServiceProvided; + } } diff --git a/setup/db/create-schema.sql b/setup/db/create-schema.sql index c2eafd661f7..b33459ad2f4 100755 --- a/setup/db/create-schema.sql +++ b/setup/db/create-schema.sql @@ -2003,6 +2003,7 @@ CREATE TABLE `cloud`.`physical_network_service_providers` ( `port_forwarding_service_provided` tinyint(1) unsigned NOT NULL DEFAULT 0 COMMENT 'Is Port Forwarding service provided', `user_data_service_provided` tinyint(1) unsigned NOT NULL DEFAULT 0 COMMENT 'Is UserData service provided', `security_group_service_provided` tinyint(1) unsigned NOT NULL DEFAULT 0 COMMENT 'Is SG service provided', + `networkacl_service_provided` tinyint(1) unsigned NOT NULL DEFAULT 0 COMMENT 'Is Network ACL service provided', `removed` datetime COMMENT 'date removed if not null', PRIMARY KEY (`id`), CONSTRAINT `fk_pnetwork_service_providers__physical_network_id` FOREIGN KEY (`physical_network_id`) REFERENCES `physical_network`(`id`) ON DELETE CASCADE, From a44843af69591e397e73b32ddfaa90dd310985dc Mon Sep 17 00:00:00 2001 From: Alena Prokharchyk Date: Thu, 5 Jul 2012 14:04:34 -0700 Subject: [PATCH 12/26] VPC: added "forVpc" (boolean) parameter to listRouters call - filter by the fact if router belongs to VPC or not --- api/src/com/cloud/api/commands/ListRoutersCmd.java | 7 +++++++ server/src/com/cloud/server/ManagementServerImpl.java | 11 ++++++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/api/src/com/cloud/api/commands/ListRoutersCmd.java b/api/src/com/cloud/api/commands/ListRoutersCmd.java index 0fb4dcc65c9..32dc0695fa6 100644 --- a/api/src/com/cloud/api/commands/ListRoutersCmd.java +++ b/api/src/com/cloud/api/commands/ListRoutersCmd.java @@ -66,6 +66,9 @@ public class ListRoutersCmd extends BaseListProjectAndAccountResourcesCmd { @IdentityMapper(entityTableName="vpc") @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, description="List networks by VPC") private Long vpcId; + + @Parameter(name=ApiConstants.FOR_VPC, type=CommandType.BOOLEAN, description="if true is passed for this parameter, list only VPC routers") + private Boolean forVpc; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -102,6 +105,10 @@ public class ListRoutersCmd extends BaseListProjectAndAccountResourcesCmd { public Long getVpcId() { return vpcId; } + + public Boolean getForVpc() { + return forVpc; + } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// diff --git a/server/src/com/cloud/server/ManagementServerImpl.java b/server/src/com/cloud/server/ManagementServerImpl.java index 40b9265318f..2f0f334ea9a 100755 --- a/server/src/com/cloud/server/ManagementServerImpl.java +++ b/server/src/com/cloud/server/ManagementServerImpl.java @@ -1601,6 +1601,7 @@ public class ManagementServerImpl implements ManagementServer { String keyword = cmd.getKeyword(); Long networkId = cmd.getNetworkId(); Long vpcId = cmd.getVpcId(); + Boolean forVpc = cmd.getForVpc(); Account caller = UserContext.current().getCaller(); List permittedAccounts = new ArrayList(); @@ -1622,6 +1623,14 @@ public class ManagementServerImpl implements ManagementServer { sb.and("podId", sb.entity().getPodIdToDeployIn(), SearchCriteria.Op.EQ); sb.and("hostId", sb.entity().getHostId(), SearchCriteria.Op.EQ); sb.and("vpcId", sb.entity().getVpcId(), SearchCriteria.Op.EQ); + + if (forVpc != null) { + if (forVpc) { + sb.and("forVpc", sb.entity().getVpcId(), SearchCriteria.Op.NNULL); + } else { + sb.and("forVpc", sb.entity().getVpcId(), SearchCriteria.Op.NULL); + } + } if (networkId != null) { SearchBuilder nicSearch = _nicDao.createSearchBuilder(); @@ -1632,7 +1641,7 @@ public class ManagementServerImpl implements ManagementServer { sb.join("nicSearch", nicSearch, sb.entity().getId(), nicSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER); } - + SearchCriteria sc = sb.create(); _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); From c258664a69d613a223d1044049e26e6cd2422e7f Mon Sep 17 00:00:00 2001 From: anthony Date: Thu, 5 Jul 2012 14:21:15 -0700 Subject: [PATCH 13/26] VPC : CS-15463 allow input traffic for established connection --- patches/systemvm/debian/config/etc/init.d/cloud-early-config | 2 +- patches/systemvm/debian/config/etc/iptables/iptables-vpcrouter | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/patches/systemvm/debian/config/etc/init.d/cloud-early-config b/patches/systemvm/debian/config/etc/init.d/cloud-early-config index 21324cbbac5..b141110a80e 100755 --- a/patches/systemvm/debian/config/etc/init.d/cloud-early-config +++ b/patches/systemvm/debian/config/etc/init.d/cloud-early-config @@ -560,7 +560,7 @@ setup_vpcrouter() { fi cat > /etc/network/interfaces << EOF -auto lo $1 +auto lo iface lo inet loopback EOF setup_interface "0" $ETH0_IP $ETH0_MASK $GW diff --git a/patches/systemvm/debian/config/etc/iptables/iptables-vpcrouter b/patches/systemvm/debian/config/etc/iptables/iptables-vpcrouter index 8e3069bc033..f60a1e41234 100644 --- a/patches/systemvm/debian/config/etc/iptables/iptables-vpcrouter +++ b/patches/systemvm/debian/config/etc/iptables/iptables-vpcrouter @@ -11,7 +11,8 @@ COMMIT -A INPUT -d 225.0.0.50/32 -j ACCEPT -A INPUT -p icmp -j ACCEPT -A INPUT -i lo -j ACCEPT --A INPUT -i eth0 -p tcp --dport 3922 -j ACCEPT +-A INPUT -i eth0 -p tcp -m state --state NEW --dport 3922 -j ACCEPT +-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT COMMIT *mangle From 24023fd14d4233bbf01649e89f470d0aa64cd09d Mon Sep 17 00:00:00 2001 From: Alena Prokharchyk Date: Thu, 5 Jul 2012 15:20:22 -0700 Subject: [PATCH 14/26] VPC: don't allow vpcs for the same account with overlapping cidrs --- server/src/com/cloud/network/vpc/VpcManagerImpl.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/server/src/com/cloud/network/vpc/VpcManagerImpl.java b/server/src/com/cloud/network/vpc/VpcManagerImpl.java index 1697864323f..1ad63f1ffa6 100644 --- a/server/src/com/cloud/network/vpc/VpcManagerImpl.java +++ b/server/src/com/cloud/network/vpc/VpcManagerImpl.java @@ -543,6 +543,15 @@ public class VpcManagerImpl implements VpcManager, Manager{ } + //don't allow overlapping CIDRS for the VPCs of the same account + List vpcs = getVpcsForAccount(vpcOwner.getId()); + for (Vpc vpc : vpcs) { + if (NetUtils.isNetworksOverlap(cidr, vpc.getCidr())) { + throw new InvalidParameterValueException("Account already has vpc with cidr " + vpc.getCidr() + + " that overlaps the cidr specified: " + cidr); + } + } + VpcVO vpc = new VpcVO (zoneId, vpcName, displayText, vpcOwner.getId(), vpcOwner.getDomainId(), vpcOffId, cidr, networkDomain); vpc = _vpcDao.persist(vpc); From 21cdd08948725c519e88d7486c4ee27167e3967a Mon Sep 17 00:00:00 2001 From: Alena Prokharchyk Date: Thu, 5 Jul 2012 15:28:30 -0700 Subject: [PATCH 15/26] VPC: don't allow vm to be a part of more than one VPC --- server/src/com/cloud/vm/UserVmManagerImpl.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java index 1ea462c72d2..aa384702e26 100755 --- a/server/src/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/com/cloud/vm/UserVmManagerImpl.java @@ -2341,6 +2341,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager List> networks = new ArrayList>(); short defaultNetworkNumber = 0; boolean securityGroupEnabled = false; + boolean vpcNetwork = false; for (NetworkVO network : networkList) { if (network.getDataCenterId() != zone.getId()) { throw new InvalidParameterValueException("Network id=" + network.getId() + " doesn't belong to zone " + zone.getId()); @@ -2368,6 +2369,14 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (_networkMgr.isSecurityGroupSupportedInNetwork(network)) { securityGroupEnabled = true; } + + //vm can't be a part of more than 1 VPC network + if (network.getVpcId() != null) { + if (vpcNetwork) { + throw new InvalidParameterValueException("Vm can't be a part of more than 1 VPC network"); + } + vpcNetwork = true; + } } if (securityGroupIdList != null && !securityGroupIdList.isEmpty() && !securityGroupEnabled) { From a0a5e25e323ad72619ef5c287ac3922f7e43b27b Mon Sep 17 00:00:00 2001 From: Sheng Yang Date: Thu, 5 Jul 2012 15:43:46 -0700 Subject: [PATCH 16/26] CS-15456: Prohibit creating more than one VPN gateway of VPC --- .../network/dao/Site2SiteVpnGatewayDao.java | 1 + .../dao/Site2SiteVpnGatewayDaoImpl.java | 21 +++++++++++++++++++ .../network/vpn/Site2SiteVpnManagerImpl.java | 5 +++++ 3 files changed, 27 insertions(+) diff --git a/server/src/com/cloud/network/dao/Site2SiteVpnGatewayDao.java b/server/src/com/cloud/network/dao/Site2SiteVpnGatewayDao.java index e9dcbbfbeb0..c1d075e2768 100644 --- a/server/src/com/cloud/network/dao/Site2SiteVpnGatewayDao.java +++ b/server/src/com/cloud/network/dao/Site2SiteVpnGatewayDao.java @@ -7,4 +7,5 @@ import com.cloud.utils.db.GenericDao; public interface Site2SiteVpnGatewayDao extends GenericDao { Site2SiteVpnGatewayVO findByIpAddrId(long id); + List listByVpcId(long vpcId); } diff --git a/server/src/com/cloud/network/dao/Site2SiteVpnGatewayDaoImpl.java b/server/src/com/cloud/network/dao/Site2SiteVpnGatewayDaoImpl.java index feab33a992f..4963d827ec9 100644 --- a/server/src/com/cloud/network/dao/Site2SiteVpnGatewayDaoImpl.java +++ b/server/src/com/cloud/network/dao/Site2SiteVpnGatewayDaoImpl.java @@ -6,21 +6,35 @@ import javax.ejb.Local; import org.apache.log4j.Logger; +import com.cloud.network.IPAddressVO; import com.cloud.network.Site2SiteVpnGatewayVO; +import com.cloud.utils.component.ComponentLocator; +import com.cloud.utils.component.Inject; import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.JoinBuilder.JoinType; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; @Local(value={Site2SiteVpnGatewayDao.class}) public class Site2SiteVpnGatewayDaoImpl extends GenericDaoBase implements Site2SiteVpnGatewayDao { + protected final IPAddressDaoImpl _addrDao = ComponentLocator.inject(IPAddressDaoImpl.class); + private static final Logger s_logger = Logger.getLogger(Site2SiteVpnGatewayDaoImpl.class); private final SearchBuilder AllFieldsSearch; + private final SearchBuilder VpcSearch; + private final SearchBuilder AddrSearch; protected Site2SiteVpnGatewayDaoImpl() { AllFieldsSearch = createSearchBuilder(); AllFieldsSearch.and("addrId", AllFieldsSearch.entity().getAddrId(), SearchCriteria.Op.EQ); AllFieldsSearch.done(); + + VpcSearch = createSearchBuilder(); + AddrSearch = _addrDao.createSearchBuilder(); + AddrSearch.and("vpcId", AddrSearch.entity().getVpcId(), SearchCriteria.Op.EQ); + VpcSearch.join("addrSearch", AddrSearch, AddrSearch.entity().getId(), VpcSearch.entity().getAddrId(), JoinType.INNER); + VpcSearch.done(); } @Override @@ -29,4 +43,11 @@ public class Site2SiteVpnGatewayDaoImpl extends GenericDaoBase listByVpcId(long vpcId) { + SearchCriteria sc = VpcSearch.create(); + sc.setJoinParameters("addrSearch", "vpcId", vpcId); + return listBy(sc); + } } diff --git a/server/src/com/cloud/network/vpn/Site2SiteVpnManagerImpl.java b/server/src/com/cloud/network/vpn/Site2SiteVpnManagerImpl.java index 0104d09c27a..56934e91981 100644 --- a/server/src/com/cloud/network/vpn/Site2SiteVpnManagerImpl.java +++ b/server/src/com/cloud/network/vpn/Site2SiteVpnManagerImpl.java @@ -80,12 +80,17 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnService, Manager { public Site2SiteVpnGateway createVpnGateway(CreateVpnGatewayCmd cmd) { Long ipId = cmd.getPublicIpId(); IpAddress ip = _networkMgr.getIp(ipId); + Long vpcId = ip.getVpcId(); if (ip.getVpcId() == null) { throw new InvalidParameterValueException("The VPN gateway cannot create with ip not belong to VPC"); } if (_vpnGatewayDao.findByIpAddrId(ipId) != null) { throw new InvalidParameterValueException("The VPN gateway with ip ID " + ipId + " already existed!"); } + List gws = _vpnGatewayDao.listByVpcId(vpcId); + if (gws != null && gws.size() != 0) { + throw new InvalidParameterValueException("The VPN gateway of VPC " + vpcId + " already existed!"); + } Site2SiteVpnGatewayVO gw = new Site2SiteVpnGatewayVO(ipId); _vpnGatewayDao.persist(gw); return gw; From 78e1d37e8f88879479e8fdd1958d1df0787236d9 Mon Sep 17 00:00:00 2001 From: Jessica Wang Date: Thu, 5 Jul 2012 15:18:50 -0700 Subject: [PATCH 17/26] cloudstack 3.0 UI - VPC - add zone wizard - enable VpcVirtualRouter element, enable VpcVirtualRouter provider for advanced zone. --- ui/scripts/zoneWizard.js | 118 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 114 insertions(+), 4 deletions(-) diff --git a/ui/scripts/zoneWizard.js b/ui/scripts/zoneWizard.js index 5843001dce4..f5f09c29cf9 100644 --- a/ui/scripts/zoneWizard.js +++ b/ui/scripts/zoneWizard.js @@ -1226,7 +1226,7 @@ }, action: function(args) { - var advZoneConfiguredPhysicalNetworkCount = 0; //for multiple physical networks in advanced zone + var advZoneConfiguredVirtualRouterCount = 0; //for multiple physical networks in advanced zone. Each physical network has 2 virtual routers: regular one and VPC one. var success = args.response.success; var error = args.response.error; @@ -1874,7 +1874,7 @@ if (result.jobstatus == 1) { //alert("updatePhysicalNetwork succeeded."); - // get network service provider ID of Virtual Router + // ***** Virtual Router ***** (begin) ***** var virtualRouterProviderId; $.ajax({ url: createURL("listNetworkServiceProviders&name=VirtualRouter&physicalNetworkId=" + thisPhysicalNetwork.id), @@ -1947,8 +1947,8 @@ clearInterval(enableVirtualRouterProviderIntervalID); if (result.jobstatus == 1) { //Virtual Router Provider has been enabled successfully - advZoneConfiguredPhysicalNetworkCount++; - if(advZoneConfiguredPhysicalNetworkCount == args.data.returnedPhysicalNetworks.length) { //not call addPod() until all physical networks get configured + advZoneConfiguredVirtualRouterCount++; + if(advZoneConfiguredVirtualRouterCount == (args.data.returnedPhysicalNetworks.length * 2)) { //not call addPod() until virtualRouter and vpcVirtualRouter of all physical networks get configured stepFns.addPod({ data: args.data }); @@ -1981,6 +1981,116 @@ }, 3000); } }); + // ***** Virtual Router ***** (end) ***** + + // ***** VPC Virtual Router ***** (begin) ***** + var vpcVirtualRouterProviderId; + $.ajax({ + url: createURL("listNetworkServiceProviders&name=VpcVirtualRouter&physicalNetworkId=" + thisPhysicalNetwork.id), + dataType: "json", + async: false, + success: function(json) { + var items = json.listnetworkserviceprovidersresponse.networkserviceprovider; + if(items != null && items.length > 0) { + vpcVirtualRouterProviderId = items[0].id; + } + } + }); + if(vpcVirtualRouterProviderId == null) { + alert("error: listNetworkServiceProviders API doesn't return VpcVirtualRouter provider ID"); + return; + } + + var vpcVirtualRouterElementId; + $.ajax({ + url: createURL("listVirtualRouterElements&nspid=" + vpcVirtualRouterProviderId), + dataType: "json", + async: false, + success: function(json) { + var items = json.listvirtualrouterelementsresponse.virtualrouterelement; + if(items != null && items.length > 0) { + vpcVirtualRouterElementId = items[0].id; + } + } + }); + if(vpcVirtualRouterElementId == null) { + alert("error: listVirtualRouterElements API doesn't return VPC Virtual Router Element Id"); + return; + } + + $.ajax({ + url: createURL("configureVirtualRouterElement&enabled=true&id=" + vpcVirtualRouterElementId), + dataType: "json", + async: false, + success: function(json) { + var jobId = json.configurevirtualrouterelementresponse.jobid; + var enableVpcVirtualRouterElementIntervalID = setInterval(function() { + $.ajax({ + url: createURL("queryAsyncJobResult&jobId="+jobId), + dataType: "json", + success: function(json) { + var result = json.queryasyncjobresultresponse; + if (result.jobstatus == 0) { + return; //Job has not completed + } + else { + clearInterval(enableVpcVirtualRouterElementIntervalID); + + if (result.jobstatus == 1) { //configureVirtualRouterElement succeeded + $.ajax({ + url: createURL("updateNetworkServiceProvider&state=Enabled&id=" + vpcVirtualRouterProviderId), + dataType: "json", + async: false, + success: function(json) { + var jobId = json.updatenetworkserviceproviderresponse.jobid; + var enableVpcVirtualRouterProviderIntervalID = setInterval(function() { + $.ajax({ + url: createURL("queryAsyncJobResult&jobId="+jobId), + dataType: "json", + success: function(json) { + var result = json.queryasyncjobresultresponse; + if (result.jobstatus == 0) { + return; //Job has not completed + } + else { + clearInterval(enableVpcVirtualRouterProviderIntervalID); + + if (result.jobstatus == 1) { //Virtual Router Provider has been enabled successfully + advZoneConfiguredVirtualRouterCount++; + if(advZoneConfiguredVirtualRouterCount == (args.data.returnedPhysicalNetworks.length * 2)) { //not call addPod() until virtualRouter and vpcVirtualRouter of all physical networks get configured + stepFns.addPod({ + data: args.data + }); + } + } + else if (result.jobstatus == 2) { + alert("failed to enable VPC Virtual Router Provider. Error: " + _s(result.jobresult.errortext)); + } + } + }, + error: function(XMLHttpResponse) { + var errorMsg = parseXMLHttpResponse(XMLHttpResponse); + alert("updateNetworkServiceProvider failed. Error: " + errorMsg); + } + }); + }, 3000); + } + }); + } + else if (result.jobstatus == 2) { + alert("configureVirtualRouterElement failed. Error: " + _s(result.jobresult.errortext)); + } + } + }, + error: function(XMLHttpResponse) { + var errorMsg = parseXMLHttpResponse(XMLHttpResponse); + alert("configureVirtualRouterElement failed. Error: " + errorMsg); + } + }); + }, 3000); + } + }); + // ***** VPC Virtual Router ***** (end) ***** } else if (result.jobstatus == 2) { alert("updatePhysicalNetwork failed. Error: " + _s(result.jobresult.errortext)); From c3215d1c1f8af4fe04c296516a3a16e94c04a4b6 Mon Sep 17 00:00:00 2001 From: Jessica Wang Date: Thu, 5 Jul 2012 15:51:51 -0700 Subject: [PATCH 18/26] cloudstack 3.0 UI - VPC - infrasture page - network service providers - add "VPC Virtual Router". --- ui/scripts/system.js | 536 ++++++++++++++++++++++++++++++++++++------- 1 file changed, 458 insertions(+), 78 deletions(-) diff --git a/ui/scripts/system.js b/ui/scripts/system.js index 2cba42bbd5b..2f6fd844b55 100644 --- a/ui/scripts/system.js +++ b/ui/scripts/system.js @@ -1909,26 +1909,13 @@ supportedServices: { label: 'label.supported.services' } } ], - dataProvider: function(args) { - $.ajax({ - url: createURL("listNetworkServiceProviders&id=" + nspMap["virtualRouter"].id), - dataType: "json", - async: true, - success: function(json) { - var items = json.listnetworkserviceprovidersresponse.networkserviceprovider; - for(var i = 0; i < items.length; i++) { - if(items[i].name == "VirtualRouter" ) { - nspMap["virtualRouter"] = items[i]; - args.response.success({ - actionFilter: virtualRouterProviderActionFilter, - data: $.extend(nspMap["virtualRouter"], { - supportedServices: nspMap["virtualRouter"].servicelist.join(', ') - }) - }); - break; - } - } - } + dataProvider: function(args) { + refreshNspData("VirtualRouter"); + args.response.success({ + actionFilter: virtualRouterProviderActionFilter, + data: $.extend(nspMap["virtualRouter"], { + supportedServices: nspMap["virtualRouter"].servicelist.join(', ') + }) }); } }, @@ -1970,6 +1957,9 @@ $.ajax({ url: createURL("listRouters&zoneid=" + selectedZoneObj.id + "&listAll=true&page=" + args.page + "&pagesize=" + pageSize + array1.join("")), dataType: 'json', + data: { + forvpc: false + }, async: true, success: function(json) { var items = json.listroutersresponse.router; @@ -1984,6 +1974,9 @@ $.ajax({ url: createURL("listRouters&zoneid=" + selectedZoneObj.id + "&listAll=true&page=" + args.page + "&pagesize=" + pageSize + array1.join("") + "&projectid=-1"), dataType: 'json', + data: { + forvpc: false + }, async: true, success: function(json) { var items = json.listroutersresponse.router; @@ -2108,64 +2101,7 @@ poll: pollAsyncJobResult } }, - - /* - changeService: { - label: 'label.change.service.offering', - createForm: { - title: 'label.change.service.offering', - desc: '', - fields: { - serviceOfferingId: { - label: 'label.compute.offering', - select: function(args) { - $.ajax({ - url: createURL("listServiceOfferings&issystem=true&systemvmtype=domainrouter"), - dataType: "json", - async: true, - success: function(json) { - var serviceofferings = json.listserviceofferingsresponse.serviceoffering; - var items = []; - $(serviceofferings).each(function() { - if(this.id != args.context.routers[0].serviceofferingid) { - items.push({id: this.id, description: this.displaytext}); - } - }); - args.response.success({data: items}); - } - }); - } - } - } - }, - messages: { - notification: function(args) { - return 'label.change.service.offering'; - } - }, - action: function(args) { - $.ajax({ - url: createURL("changeServiceForRouter&id=" + args.context.routers[0].id + "&serviceofferingid=" + args.data.serviceOfferingId), - dataType: "json", - async: true, - success: function(json) { - var jsonObj = json.changeserviceforrouterresponse.domainrouter; - args.response.success({data: jsonObj}); - }, - error: function(XMLHttpResponse) { - var errorMsg = parseXMLHttpResponse(XMLHttpResponse); - args.response.error(errorMsg); - } - }); - }, - notification: { - poll: function(args) { - args.complete(); - } - } - }, - */ - + migrate: { label: 'label.action.migrate.router', createForm: { @@ -2381,7 +2317,441 @@ } } }, + + vpcVirtualRouter: { + id: 'vpcVirtualRouterProviders', + label: 'VPC Virtual Router', + isMaximized: true, + type: 'detailView', + fields: { + name: { label: 'label.name' }, + ipaddress: { label: 'label.ip.address' }, + state: { label: 'label.status', indicator: { 'Enabled': 'on' } } + }, + tabs: { + network: { + title: 'label.network', + fields: [ + { + name: { label: 'label.name' } + }, + { + id: { label: 'label.id' }, + state: { label: 'label.state' }, + physicalnetworkid: { label: 'label.physical.network.ID' }, + destinationphysicalnetworkid: { label: 'label.destination.physical.network.id' }, + supportedServices: { label: 'label.supported.services' } + } + ], + dataProvider: function(args) { + refreshNspData("VpcVirtualRouter"); + args.response.success({ + actionFilter: virtualRouterProviderActionFilter, + data: $.extend(nspMap["vpcVirtualRouter"], { + supportedServices: nspMap["vpcVirtualRouter"].servicelist.join(', ') + }) + }); + } + }, + instances: { + title: 'label.instances', + listView: { + label: 'label.virtual.appliances', + id: 'routers', + fields: { + name: { label: 'label.name' }, + zonename: { label: 'label.zone' }, + state: { + converter: function(str) { + // For localization + return str; + }, + label: 'label.status', + indicator: { + 'Running': 'on', + 'Stopped': 'off', + 'Error': 'off' + } + } + }, + dataProvider: function(args) { + var array1 = []; + if(args.filterBy != null) { + if(args.filterBy.search != null && args.filterBy.search.by != null && args.filterBy.search.value != null) { + switch(args.filterBy.search.by) { + case "name": + if(args.filterBy.search.value.length > 0) + array1.push("&keyword=" + args.filterBy.search.value); + break; + } + } + } + + $.ajax({ + url: createURL("listRouters&zoneid=" + selectedZoneObj.id + "&listAll=true&page=" + args.page + "&pagesize=" + pageSize + array1.join("")), + dataType: 'json', + data: { + forvpc: true + }, + async: true, + success: function(json) { + var items = json.listroutersresponse.router; + args.response.success({ + actionFilter: routerActionfilter, + data: items + }); + } + }); + + // Get project routers + $.ajax({ + url: createURL("listRouters&zoneid=" + selectedZoneObj.id + "&listAll=true&page=" + args.page + "&pagesize=" + pageSize + array1.join("") + "&projectid=-1"), + dataType: 'json', + data: { + forvpc: true + }, + async: true, + success: function(json) { + var items = json.listroutersresponse.router; + args.response.success({ + actionFilter: routerActionfilter, + data: items + }); + } + }); + }, + detailView: { + name: 'Virtual applicance details', + actions: { + start: { + label: 'label.action.start.router', + messages: { + confirm: function(args) { + return 'message.action.start.router'; + }, + notification: function(args) { + return 'label.action.start.router'; + } + }, + action: function(args) { + $.ajax({ + url: createURL('startRouter&id=' + args.context.routers[0].id), + dataType: 'json', + async: true, + success: function(json) { + var jid = json.startrouterresponse.jobid; + args.response.success({ + _custom: { + jobId: jid, + getUpdatedItem: function(json) { + return json.queryasyncjobresultresponse.jobresult.domainrouter; + }, + getActionFilter: function() { + return routerActionfilter; + } + } + }); + } + }); + }, + notification: { + poll: pollAsyncJobResult + } + }, + + stop: { + label: 'label.action.stop.router', + createForm: { + title: 'label.action.stop.router', + desc: 'message.action.stop.router', + fields: { + forced: { + label: 'force.stop', + isBoolean: true, + isChecked: false + } + } + }, + messages: { + notification: function(args) { + return 'label.action.stop.router'; + } + }, + action: function(args) { + var array1 = []; + array1.push("&forced=" + (args.data.forced == "on")); + $.ajax({ + url: createURL('stopRouter&id=' + args.context.routers[0].id + array1.join("")), + dataType: 'json', + async: true, + success: function(json) { + var jid = json.stoprouterresponse.jobid; + args.response.success({ + _custom: { + jobId: jid, + getUpdatedItem: function(json) { + return json.queryasyncjobresultresponse.jobresult.domainrouter; + }, + getActionFilter: function() { + return routerActionfilter; + } + } + }); + } + }); + }, + notification: { + poll: pollAsyncJobResult + } + }, + + 'remove': { + label: 'label.destroy.router', + messages: { + confirm: function(args) { + return 'message.confirm.destroy.router'; + }, + notification: function(args) { + return 'label.destroy.router'; + } + }, + action: function(args) { + $.ajax({ + url: createURL("destroyRouter&id=" + args.context.routers[0].id), + dataType: "json", + async: true, + success: function(json) { + var jid = json.destroyrouterresponse.jobid; + args.response.success({ + _custom: { + jobId: jid + } + }); + } + }); + }, + notification: { + poll: pollAsyncJobResult + } + }, + + migrate: { + label: 'label.action.migrate.router', + createForm: { + title: 'label.action.migrate.router', + desc: '', + fields: { + hostId: { + label: 'label.host', + validation: { required: true }, + select: function(args) { + $.ajax({ + url: createURL("listHosts&VirtualMachineId=" + args.context.routers[0].id), + //url: createURL("listHosts"), //for testing only, comment it out before checking in. + dataType: "json", + async: true, + success: function(json) { + var hostObjs = json.listhostsresponse.host; + var items = []; + $(hostObjs).each(function() { + items.push({id: this.id, description: (this.name + ": " +(this.hasEnoughCapacity? "Available" : "Full"))}); + }); + args.response.success({data: items}); + } + }); + }, + error: function(XMLHttpResponse) { + var errorMsg = parseXMLHttpResponse(XMLHttpResponse); + args.response.error(errorMsg); + } + } + } + }, + messages: { + notification: function(args) { + return 'label.action.migrate.router'; + } + }, + action: function(args) { + $.ajax({ + url: createURL("migrateSystemVm&hostid=" + args.data.hostId + "&virtualmachineid=" + args.context.routers[0].id), + dataType: "json", + async: true, + success: function(json) { + var jid = json.migratesystemvmresponse.jobid; + args.response.success({ + _custom: { + jobId: jid, + getUpdatedItem: function(json) { + //return json.queryasyncjobresultresponse.jobresult.systemvminstance; //not all properties returned in systemvminstance + $.ajax({ + url: createURL("listRouters&id=" + json.queryasyncjobresultresponse.jobresult.systemvminstance.id), + dataType: "json", + async: false, + success: function(json) { + var items = json.listroutersresponse.router; + if(items != null && items.length > 0) { + return items[0]; + } + } + }); + }, + getActionFilter: function() { + return routerActionfilter; + } + } + }); + } + }); + }, + notification: { + poll: pollAsyncJobResult + } + }, + + viewConsole: { + label: 'label.view.console', + action: { + externalLink: { + url: function(args) { + return clientConsoleUrl + '?cmd=access&vm=' + args.context.routers[0].id; + }, + title: function(args) { + return args.context.routers[0].id.substr(0,8); //title in window.open() can't have space nor longer than 8 characters. Otherwise, IE browser will have error. + }, + width: 820, + height: 640 + } + } + } + }, + tabs: { + details: { + title: 'label.details', + preFilter: function(args) { + var hiddenFields = []; + if (!args.context.routers[0].project) { + hiddenFields.push('project'); + hiddenFields.push('projectid'); + } + if(selectedZoneObj.networktype == 'Basic') { + hiddenFields.push('publicip'); //In Basic zone, guest IP is public IP. So, publicip is not returned by listRouters API. Only guestipaddress is returned by listRouters API. + } + return hiddenFields; + }, + fields: [ + { + name: { label: 'label.name' }, + project: { label: 'label.project' } + }, + { + id: { label: 'label.id' }, + projectid: { label: 'label.project.id' }, + state: { label: 'label.state' }, + publicip: { label: 'label.public.ip' }, + guestipaddress: { label: 'label.guest.ip' }, + linklocalip: { label: 'label.linklocal.ip' }, + hostname: { label: 'label.host' }, + serviceofferingname: { label: 'label.compute.offering' }, + networkdomain: { label: 'label.network.domain' }, + domain: { label: 'label.domain' }, + account: { label: 'label.account' }, + created: { label: 'label.created', converter: cloudStack.converters.toLocalDate }, + isredundantrouter: { + label: 'label.redundant.router', + converter: cloudStack.converters.toBooleanText + }, + redundantRouterState: { label: 'label.redundant.state' } + } + ], + dataProvider: function(args) { + $.ajax({ + url: createURL("listRouters&id=" + args.context.routers[0].id), + dataType: 'json', + async: true, + success: function(json) { + var jsonObj = json.listroutersresponse.router[0]; + addExtraPropertiesToRouterInstanceObject(jsonObj); + args.response.success({ + actionFilter: routerActionfilter, + data: jsonObj + }); + } + }); + } + } + } + } + } + } + }, + actions: { + enable: { + label: 'label.enable.provider', + action: function(args) { + $.ajax({ + url: createURL("updateNetworkServiceProvider&id=" + nspMap["vpcVirtualRouter"].id + "&state=Enabled"), + dataType: "json", + success: function(json) { + var jid = json.updatenetworkserviceproviderresponse.jobid; + args.response.success( + {_custom: + { + jobId: jid, + getUpdatedItem: function(json) { + $(window).trigger('cloudStack.fullRefresh'); + } + } + } + ); + } + }); + }, + messages: { + confirm: function(args) { + return 'message.confirm.enable.provider'; + }, + notification: function() { + return 'label.enable.provider'; + } + }, + notification: { poll: pollAsyncJobResult } + }, + disable: { + label: 'label.disable.provider', + action: function(args) { + $.ajax({ + url: createURL("updateNetworkServiceProvider&id=" + nspMap["vpcVirtualRouter"].id + "&state=Disabled"), + dataType: "json", + success: function(json) { + var jid = json.updatenetworkserviceproviderresponse.jobid; + args.response.success( + {_custom: + { + jobId: jid, + getUpdatedItem: function(json) { + $(window).trigger('cloudStack.fullRefresh'); + } + } + } + ); + } + }); + }, + messages: { + confirm: function(args) { + return 'message.confirm.disable.provider'; + }, + notification: function() { + return 'label.disable.provider'; + } + }, + notification: { poll: pollAsyncJobResult } + } + } + }, + // NetScaler provider detail view netscaler: { type: 'detailView', @@ -9174,6 +9544,9 @@ case "VirtualRouter": nspMap["virtualRouter"] = items[i]; break; + case "VpcVirtualRouter": + nspMap["vpcVirtualRouter"] = items[i]; + break; case "Netscaler": nspMap["netscaler"] = items[i]; break; @@ -9215,6 +9588,13 @@ ); } else if(selectedZoneObj.networktype == "Advanced"){ + nspHardcodingArray.push( + { + id: 'vpcVirtualRouter', + name: 'VPC Virtual Router', + state: nspMap.vpcVirtualRouter ? nspMap.vpcVirtualRouter.state : 'Disabled' + } + ); nspHardcodingArray.push( { id: 'f5', From f8aa415a978042312adeb0f71ea54a3ded9223b8 Mon Sep 17 00:00:00 2001 From: frank Date: Thu, 5 Jul 2012 16:02:51 -0700 Subject: [PATCH 19/26] CloudStack CS-15455 There are no iptable rules configured to open awsapi port (7080) for external world. resolved fixed reviewed-by:edison --- python/lib/cloudutils/serviceConfig.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/lib/cloudutils/serviceConfig.py b/python/lib/cloudutils/serviceConfig.py index 539e26ae732..4ab08a21ba7 100755 --- a/python/lib/cloudutils/serviceConfig.py +++ b/python/lib/cloudutils/serviceConfig.py @@ -699,7 +699,7 @@ class firewallConfigServer(firewallConfigBase): if self.syscfg.env.svrMode == "myCloud": self.ports = "443 8080 8250 8443 9090".split() else: - self.ports = "8080 8250 9090".split() + self.ports = "8080 7080 8250 9090".split() class ubuntuFirewallConfigServer(firewallConfigServer): def allowPort(self, port): From 96a3b496c863ad244ea300289cc618095df910df Mon Sep 17 00:00:00 2001 From: frank Date: Thu, 5 Jul 2012 16:18:24 -0700 Subject: [PATCH 20/26] CloudStack CS-15448 java.io.FileNotFoundException: /usr/share/cloud/management/webapps7080/awsapi/WEB-INF/classes/xes.keystore (Permission denied) resolved fixed reviewed-by: edison --- cloud.spec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cloud.spec b/cloud.spec index 9824b9ac776..6b551b7144f 100644 --- a/cloud.spec +++ b/cloud.spec @@ -633,7 +633,7 @@ fi %config(noreplace) %attr(0640,root,%{name}) %{_sysconfdir}/%{name}/usage/db.properties %files aws-api -%defattr(0644,cloud,cloud,0755) +%defattr(0666,cloud,cloud,0755) %{_datadir}/cloud/bridge/conf/* %{_datadir}/cloud/bridge/lib/* %{_datadir}/cloud/bridge/webapps/* From f1ec4fddd3cbf1c6e4de540bbef1855cf2816f9b Mon Sep 17 00:00:00 2001 From: Vijayendra Bhamidipati Date: Thu, 5 Jul 2012 16:22:44 -0700 Subject: [PATCH 21/26] CS-15217: Security: Malicious user is able to get the size of the cloud by enumerating IDs Description: As part of the fix for Bug CS-13127, a new overloaded function, addProxyObject() was added to facilitate transparent db id to uuid conversions when db IDs were added to exceptions that were thrown in the Cloudstack mgmt server code. However, it turns out that there are quite many db IDs still in the code that are being directly embedded in the String message that is passed during exception creation. In this commit, we modify the default constructor of InvalidParameterValueException so that it takes a second argument of type List. This will help developers see that there is a second parameter required, and make them look into what that parameter is about. Hopefully, this will stop db IDs from being embedded into the exception message. The parameter can be set to null though, since there are many places in the code that don't embed any DB IDs in the exception. This is still a WIP, so the older default constructor for InvalidParameterValueException has not been removed yet. When all instances of throw new InvalidParameterValueException() have been moved over to the new default constructor, the old one will be removed, else compilation will break. The reason for having to do this in batches is that there are way too many places in the code that throw exceptions, and they all cannot be covered in a single commit without it taking much time. In following commits, all other exceptions will be changed in the same way as InvalidParameterValueException. --- api/src/com/cloud/api/BaseCmd.java | 22 +- api/src/com/cloud/api/BaseListCmd.java | 4 +- .../cloud/api/BaseListTaggedResourcesCmd.java | 4 +- .../api/commands/ActivateProjectCmd.java | 15 +- .../api/commands/AddAccountToProjectCmd.java | 23 +- .../commands/AssignToLoadBalancerRuleCmd.java | 12 +- .../api/commands/AssociateIPAddrCmd.java | 97 +- .../com/cloud/api/commands/AttachIsoCmd.java | 10 +- .../AuthorizeSecurityGroupEgressCmd.java | 28 +- .../AuthorizeSecurityGroupIngressCmd.java | 24 +- .../api/commands/CreateFirewallRuleCmd.java | 56 +- .../commands/CreateIpForwardingRuleCmd.java | 79 +- .../commands/CreateLoadBalancerRuleCmd.java | 135 ++- .../api/commands/CreateNetworkACLCmd.java | 48 +- .../cloud/api/commands/CreateNetworkCmd.java | 78 +- .../commands/CreateNetworkOfferingCmd.java | 64 +- .../commands/CreatePortForwardingRuleCmd.java | 32 +- .../api/commands/CreatePrivateGatewayCmd.java | 40 +- .../cloud/api/commands/CreateProjectCmd.java | 3 +- .../commands/CreateRemoteAccessVpnCmd.java | 113 +- .../cloud/api/commands/CreateSnapshotCmd.java | 15 +- .../api/commands/CreateSnapshotPolicyCmd.java | 24 +- .../api/commands/CreateStaticRouteCmd.java | 25 +- .../cloud/api/commands/CreateTemplateCmd.java | 41 +- .../api/commands/CreateVpnConnectionCmd.java | 38 +- .../api/commands/CreateVpnGatewayCmd.java | 44 +- .../commands/DeleteAccountFromProjectCmd.java | 16 +- .../api/commands/DeleteFirewallRuleCmd.java | 18 +- .../commands/DeleteIpForwardingRuleCmd.java | 12 +- .../commands/DeleteLBStickinessPolicyCmd.java | 6 +- .../commands/DeleteLoadBalancerRuleCmd.java | 16 +- .../api/commands/DeleteNetworkACLCmd.java | 18 +- .../cloud/api/commands/DeleteNetworkCmd.java | 14 +- .../commands/DeletePortForwardingRuleCmd.java | 20 +- .../api/commands/DeletePrivateGatewayCmd.java | 18 +- .../cloud/api/commands/DeleteProjectCmd.java | 12 +- .../commands/DeleteRemoteAccessVpnCmd.java | 46 +- .../api/commands/DeleteSecurityGroupCmd.java | 48 +- .../api/commands/DeleteStaticRouteCmd.java | 20 +- .../com/cloud/api/commands/DeployVMCmd.java | 79 +- .../com/cloud/api/commands/DetachIsoCmd.java | 4 +- .../api/commands/DisableStaticNatCmd.java | 18 +- .../api/commands/DisassociateIPAddrCmd.java | 22 +- .../api/commands/EnableStaticNatCmd.java | 14 +- .../cloud/api/commands/ListCapacityCmd.java | 52 +- .../com/cloud/api/commands/ListHostsCmd.java | 37 +- .../ListSupportedNetworkServicesCmd.java | 22 +- .../com/cloud/api/commands/ListVMsCmd.java | 43 +- .../api/commands/MigrateSystemVMCmd.java | 32 +- .../com/cloud/api/commands/MigrateVMCmd.java | 78 +- .../RemoveFromLoadBalancerRuleCmd.java | 12 +- .../cloud/api/commands/RestartNetworkCmd.java | 21 +- .../cloud/api/commands/SuspendProjectCmd.java | 12 +- .../cloud/api/commands/UpdateClusterCmd.java | 68 +- .../cloud/api/commands/UpdateNetworkCmd.java | 32 +- .../cloud/api/commands/UpdateProjectCmd.java | 16 +- .../UpdateTemplateOrIsoPermissionsCmd.java | 16 +- .../api/commands/UpgradeSystemVMCmd.java | 16 +- .../com/cloud/api/commands/UpgradeVMCmd.java | 16 +- .../InvalidParameterValueException.java | 12 + .../com/cloud/network/NetworkManagerImpl.java | 1054 +++++++++-------- .../cloud/template/TemplateAdapterBase.java | 469 ++++---- .../com/cloud/user/AccountManagerImpl.java | 220 ++-- .../src/com/cloud/vm/UserVmManagerImpl.java | 553 ++++----- utils/src/com/cloud/utils/IdentityProxy.java | 34 +- 65 files changed, 2207 insertions(+), 2083 deletions(-) diff --git a/api/src/com/cloud/api/BaseCmd.java b/api/src/com/cloud/api/BaseCmd.java index 5899354207b..8895bf0a173 100755 --- a/api/src/com/cloud/api/BaseCmd.java +++ b/api/src/com/cloud/api/BaseCmd.java @@ -14,6 +14,7 @@ package com.cloud.api; import java.text.DateFormat; import java.text.SimpleDateFormat; +import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; @@ -56,6 +57,7 @@ import com.cloud.user.Account; import com.cloud.user.AccountService; import com.cloud.user.DomainService; import com.cloud.user.ResourceLimitService; +import com.cloud.utils.IdentityProxy; import com.cloud.utils.Pair; import com.cloud.utils.component.ComponentLocator; import com.cloud.vm.BareMetalVmService; @@ -196,9 +198,9 @@ public abstract class BaseCmd { } public ManagementService getMgmtServiceRef() { - return _mgr; + return _mgr; } - + public static String getDateString(Date date) { if (date == null) { return ""; @@ -482,12 +484,12 @@ public abstract class BaseCmd { public Long finalyzeAccountId(String accountName, Long domainId, Long projectId, boolean enabledOnly) { if (accountName != null) { if (domainId == null) { - throw new InvalidParameterValueException("Account must be specified with domainId parameter"); + throw new InvalidParameterValueException("Account must be specified with domainId parameter", null); } Domain domain = _domainService.getDomain(domainId); if (domain == null) { - throw new InvalidParameterValueException("Unable to find domain by id=" + domainId); + throw new InvalidParameterValueException("Unable to find domain by id", null); } Account account = _accountService.getActiveAccountByName(accountName, domainId); @@ -498,7 +500,9 @@ public abstract class BaseCmd { throw new PermissionDeniedException("Can't add resources to the account id=" + account.getId() + " in state=" + account.getState() + " as it's no longer active"); } } else { - throw new InvalidParameterValueException("Unable to find account by name " + accountName + " in domain id=" + domainId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", domainId, "domainId")); + throw new InvalidParameterValueException("Unable to find account by name " + accountName + " in domain with specified id", idList); } } @@ -508,14 +512,12 @@ public abstract class BaseCmd { if (!enabledOnly || project.getState() == Project.State.Active) { return project.getProjectAccountId(); } else { - PermissionDeniedException ex = new PermissionDeniedException("Can't add resources to the project with specified projectId in state=" + project.getState() + " as it's no longer active"); - ex.addProxyObject(project, projectId, "projectId"); + PermissionDeniedException ex = new PermissionDeniedException("Can't add resources to the project with specified projectId in state=" + project.getState() + " as it's no longer active"); + ex.addProxyObject(project, projectId, "projectId"); throw ex; } } else { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified projectId"); - ex.addProxyObject(project, projectId, "projectId"); - throw ex; + throw new InvalidParameterValueException("Unable to find project by id", null); } } return null; diff --git a/api/src/com/cloud/api/BaseListCmd.java b/api/src/com/cloud/api/BaseListCmd.java index 0bf288051d0..d3455c49e24 100755 --- a/api/src/com/cloud/api/BaseListCmd.java +++ b/api/src/com/cloud/api/BaseListCmd.java @@ -48,11 +48,11 @@ public abstract class BaseListCmd extends BaseCmd { public Integer getPageSize() { if (pageSize != null && MAX_PAGESIZE != null && pageSize.longValue() > MAX_PAGESIZE.longValue()) { - throw new InvalidParameterValueException("Page size can't exceed max allowed page size value: " + MAX_PAGESIZE.longValue()); + throw new InvalidParameterValueException("Page size can't exceed max allowed page size value: " + MAX_PAGESIZE.longValue(), null); } if (pageSize != null && pageSize.longValue() == PAGESIZE_UNLIMITED && page != null) { - throw new InvalidParameterValueException("Can't specify page parameter when pagesize is -1 (Unlimited)"); + throw new InvalidParameterValueException("Can't specify page parameter when pagesize is -1 (Unlimited)", null); } return pageSize; diff --git a/api/src/com/cloud/api/BaseListTaggedResourcesCmd.java b/api/src/com/cloud/api/BaseListTaggedResourcesCmd.java index 9a70b107089..fb50f0cd692 100644 --- a/api/src/com/cloud/api/BaseListTaggedResourcesCmd.java +++ b/api/src/com/cloud/api/BaseListTaggedResourcesCmd.java @@ -25,7 +25,7 @@ import com.cloud.exception.InvalidParameterValueException; public abstract class BaseListTaggedResourcesCmd extends BaseListProjectAndAccountResourcesCmd{ @Parameter(name = ApiConstants.TAGS, type = CommandType.MAP, description = "List resources by tags (key/value pairs)") private Map tags; - + public Map getTags() { Map tagsMap = null; if (tags != null && !tags.isEmpty()) { @@ -37,7 +37,7 @@ public abstract class BaseListTaggedResourcesCmd extends BaseListProjectAndAccou String key = services.get("key"); String value = services.get("value"); if (value == null) { - throw new InvalidParameterValueException("No value is passed in for key " + key); + throw new InvalidParameterValueException("No value is passed in for key " + key, null); } tagsMap.put(key, value); } diff --git a/api/src/com/cloud/api/commands/ActivateProjectCmd.java b/api/src/com/cloud/api/commands/ActivateProjectCmd.java index 24df6491478..6af996492cb 100644 --- a/api/src/com/cloud/api/commands/ActivateProjectCmd.java +++ b/api/src/com/cloud/api/commands/ActivateProjectCmd.java @@ -18,7 +18,6 @@ import com.cloud.api.ApiConstants; import com.cloud.api.BaseAsyncCmd; import com.cloud.api.BaseCmd; import com.cloud.api.IdentityMapper; -import com.cloud.api.BaseCmd.CommandType; import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; @@ -37,7 +36,7 @@ public class ActivateProjectCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + @IdentityMapper(entityTableName="projects") @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="id of the project to be modified") private Long id; @@ -54,18 +53,18 @@ public class ActivateProjectCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Project project= _projectService.getProject(id); //verify input parameters if (project == null) { - throw new InvalidParameterValueException("Unable to find project by id " + id); + throw new InvalidParameterValueException("Unable to find project by id", null); } - + return _projectService.getProjectOwner(id).getId(); } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -83,12 +82,12 @@ public class ActivateProjectCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to activate a project"); } } - + @Override public String getEventType() { return EventTypes.EVENT_PROJECT_ACTIVATE; } - + @Override public String getEventDescription() { return "Activating project: " + id; diff --git a/api/src/com/cloud/api/commands/AddAccountToProjectCmd.java b/api/src/com/cloud/api/commands/AddAccountToProjectCmd.java index b430a706c2b..c9db4791431 100644 --- a/api/src/com/cloud/api/commands/AddAccountToProjectCmd.java +++ b/api/src/com/cloud/api/commands/AddAccountToProjectCmd.java @@ -26,7 +26,6 @@ import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.projects.Project; import com.cloud.user.UserContext; -import com.cloud.utils.AnnotationHelper; @Implementation(description="Adds acoount to a project", responseObject=SuccessResponse.class, since="3.0.0") @@ -42,10 +41,10 @@ public class AddAccountToProjectCmd extends BaseAsyncCmd { @IdentityMapper(entityTableName="projects") @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, required=true, description="id of the project to add the account to") private Long projectId; - + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="name of the account to be added to the project") private String accountName; - + @Parameter(name=ApiConstants.EMAIL, type=CommandType.STRING, description="email to which invitation to the project is going to be sent") private String email; @@ -62,7 +61,7 @@ public class AddAccountToProjectCmd extends BaseAsyncCmd { return projectId; } - + public String getEmail() { return email; } @@ -79,9 +78,9 @@ public class AddAccountToProjectCmd extends BaseAsyncCmd { @Override public void execute(){ if (accountName == null && email == null) { - throw new InvalidParameterValueException("Either accountName or email is required"); + throw new InvalidParameterValueException("Either accountName or email is required", null); } - + UserContext.current().setEventDetails("Project id: "+ projectId + "; accountName " + accountName); boolean result = _projectService.addAccountToProject(getProjectId(), getAccountName(), getEmail()); if (result) { @@ -91,25 +90,25 @@ public class AddAccountToProjectCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add account to the project"); } } - + @Override public long getEntityOwnerId() { Project project= _projectService.getProject(projectId); //verify input parameters if (project == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id"); - ex.addProxyObject(project, projectId, "projectId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id", null); + ex.addProxyObject(project, projectId, "projectId"); throw ex; } - + return _projectService.getProjectOwner(projectId).getId(); } - + @Override public String getEventType() { return EventTypes.EVENT_PROJECT_ACCOUNT_ADD; } - + @Override public String getEventDescription() { if (accountName != null) { diff --git a/api/src/com/cloud/api/commands/AssignToLoadBalancerRuleCmd.java b/api/src/com/cloud/api/commands/AssignToLoadBalancerRuleCmd.java index 9224613cdd3..364ab51a93a 100644 --- a/api/src/com/cloud/api/commands/AssignToLoadBalancerRuleCmd.java +++ b/api/src/com/cloud/api/commands/AssignToLoadBalancerRuleCmd.java @@ -88,7 +88,7 @@ public class AssignToLoadBalancerRuleCmd extends BaseAsyncCmd { public String getEventDescription() { return "applying instances for load balancer: " + getLoadBalancerId() + " (ids: " + StringUtils.join(getVirtualMachineIds(), ",") + ")"; } - + @Override public void execute(){ UserContext.current().setEventDetails("Load balancer Id: "+getLoadBalancerId()+" VmIds: "+StringUtils.join(getVirtualMachineIds(), ",")); @@ -100,7 +100,7 @@ public class AssignToLoadBalancerRuleCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to assign load balancer rule"); } } - + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -108,10 +108,10 @@ public class AssignToLoadBalancerRuleCmd extends BaseAsyncCmd { @Override public Long getSyncObjId() { - LoadBalancer lb = _lbService.findById(id); - if(lb == null){ - throw new InvalidParameterValueException("Unable to find load balancer rule: " + id); - } + LoadBalancer lb = _lbService.findById(id); + if(lb == null){ + throw new InvalidParameterValueException("Unable to find load balancer rule by id", null); + } return lb.getNetworkId(); } } diff --git a/api/src/com/cloud/api/commands/AssociateIPAddrCmd.java b/api/src/com/cloud/api/commands/AssociateIPAddrCmd.java index e87548765cd..625793d1a4f 100644 --- a/api/src/com/cloud/api/commands/AssociateIPAddrCmd.java +++ b/api/src/com/cloud/api/commands/AssociateIPAddrCmd.java @@ -56,37 +56,38 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { @IdentityMapper(entityTableName="domain") @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, - description="the ID of the domain to associate with this IP address") + description="the ID of the domain to associate with this IP address") private Long domainId; @IdentityMapper(entityTableName="data_center") @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, - description="the ID of the availability zone you want to acquire an public IP address from") + description="the ID of the availability zone you want to acquire an public IP address from") private Long zoneId; - + @IdentityMapper(entityTableName="networks") @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, - description="The network this ip address should be associated to.") + description="The network this ip address should be associated to.") private Long networkId; - + @IdentityMapper(entityTableName="projects") @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, - description="Deploy vm for the project") + description="Deploy vm for the project") private Long projectId; @IdentityMapper(entityTableName="vpc") @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, description="the VPC you want the ip address to " + - "be associated with") + "be associated with") private Long vpcId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// + @Override public String getEntityTable() { - return "user_ip_address"; + return "user_ip_address"; } - + public String getAccountName() { if (accountName != null) { return accountName; @@ -103,7 +104,7 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { private long getZoneId() { if (zoneId != null) { - return zoneId; + return zoneId; } else if (vpcId != null) { Vpc vpc = _entityMgr.findById(Vpc.class, vpcId); if (vpc != null) { @@ -115,28 +116,28 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { return ntwk.getDataCenterId(); } } - - throw new InvalidParameterValueException("Unable to figure out zone to assign ip to"); + + throw new InvalidParameterValueException("Unable to figure out zone to assign ip to", null); } - + public Long getVpcId() { return vpcId; } - + public Long getNetworkId() { if (vpcId != null) { return null; } - + if (networkId != null) { return networkId; } Long zoneId = getZoneId(); - + if (zoneId == null) { return null; } - + DataCenter zone = _configService.getZone(zoneId); if (zone.getNetworkType() == NetworkType.Advanced) { List networks = _networkService.getIsolatedNetworksOwnedByAccountInZone(getZoneId(), @@ -144,52 +145,52 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { if (networks.size() == 0) { String domain = _domainService.getDomain(getDomainId()).getName(); throw new InvalidParameterValueException("Account name=" + getAccountName() + " domain=" + domain + - " doesn't have virtual networks in zone=" + zone.getName()); + " doesn't have virtual networks in zone=" + zone.getName(), null); } - + if (networks.size() < 1) { - throw new InvalidParameterValueException("Account doesn't have any Isolated networks in the zone"); + throw new InvalidParameterValueException("Account doesn't have any Isolated networks in the zone", null); } else if (networks.size() > 1) { - throw new InvalidParameterValueException("Account has more than one Isolated network in the zone"); + throw new InvalidParameterValueException("Account has more than one Isolated network in the zone", null); } - + return networks.get(0).getId(); } else { Network defaultGuestNetwork = _networkService.getExclusiveGuestNetwork(zoneId); if (defaultGuestNetwork == null) { throw new InvalidParameterValueException("Unable to find a default Guest network for account " + - getAccountName() + " in domain id=" + getDomainId()); + getAccountName() + " in domain id=" + getDomainId(), null); } else { return defaultGuestNetwork.getId(); } } } - + @Override public long getEntityOwnerId() { - Account caller = UserContext.current().getCaller(); - if (accountName != null && domainId != null) { - Account account = _accountService.finalizeOwner(caller, accountName, domainId, projectId); - return account.getId(); - } else if (getNetworkId() != null){ - Network network = _networkService.getNetwork(getNetworkId()); + Account caller = UserContext.current().getCaller(); + if (accountName != null && domainId != null) { + Account account = _accountService.finalizeOwner(caller, accountName, domainId, projectId); + return account.getId(); + } else if (getNetworkId() != null){ + Network network = _networkService.getNetwork(getNetworkId()); return network.getAccountId(); - } else if (vpcId != null) { - Vpc vpc = _vpcService.getVpc(getVpcId()); - if (vpc == null) { - throw new InvalidParameterValueException("Can't find Enabled vpc by id specified"); - } - return vpc.getAccountId(); - } - - throw new InvalidParameterValueException("Failed to determine ip owner"); + } else if (vpcId != null) { + Vpc vpc = _vpcService.getVpc(getVpcId()); + if (vpc == null) { + throw new InvalidParameterValueException("Can't find Enabled vpc by id specified", null); + } + return vpc.getAccountId(); + } + + throw new InvalidParameterValueException("Failed to determine ip owner", null); } @Override public String getEventType() { return EventTypes.EVENT_NET_IP_ASSIGN; } - + @Override public String getEventDescription() { return "associating ip to network id: " + getNetworkId() + " in zone " + getZoneId(); @@ -206,9 +207,9 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { } public static String getResultObjectName() { - return "addressinfo"; + return "addressinfo"; } - + @Override public void create() throws ResourceAllocationException{ try { @@ -227,14 +228,14 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); } } - + @Override public void execute() throws ResourceUnavailableException, ResourceAllocationException, - ConcurrentOperationException, InsufficientCapacityException { + ConcurrentOperationException, InsufficientCapacityException { UserContext.current().setEventDetails("Ip Id: " + getEntityId()); IpAddress result = null; - + result = _networkService.associateIP(getEntityId(), getNetworkId(), getVpcId()); if (result != null) { @@ -245,8 +246,8 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to assign ip address"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -256,7 +257,7 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { public Long getSyncObjId() { return getNetworkId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.IpAddress; diff --git a/api/src/com/cloud/api/commands/AttachIsoCmd.java b/api/src/com/cloud/api/commands/AttachIsoCmd.java index 690f17b8093..1e5a27a8347 100755 --- a/api/src/com/cloud/api/commands/AttachIsoCmd.java +++ b/api/src/com/cloud/api/commands/AttachIsoCmd.java @@ -67,14 +67,14 @@ public class AttachIsoCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { UserVm vm = _entityMgr.findById(UserVm.class, getVirtualMachineId()); if (vm == null) { - throw new InvalidParameterValueException("Unable to find virtual machine by id " + getVirtualMachineId()); + throw new InvalidParameterValueException("Unable to find virtual machine by id " + getVirtualMachineId(), null); } - + return vm.getAccountId(); } @@ -87,10 +87,10 @@ public class AttachIsoCmd extends BaseAsyncCmd { public String getEventDescription() { return "attaching ISO: " + getId() + " to vm: " + getVirtualMachineId(); } - + @Override public void execute(){ - UserContext.current().setEventDetails("Vm Id: " +getVirtualMachineId()+ " ISO Id: "+getId()); + UserContext.current().setEventDetails("Vm Id: " +getVirtualMachineId()+ " ISO Id: "+getId()); boolean result = _templateService.attachIso(id, virtualMachineId); if (result) { UserVm userVm = _responseGenerator.findUserVmById(virtualMachineId); diff --git a/api/src/com/cloud/api/commands/AuthorizeSecurityGroupEgressCmd.java b/api/src/com/cloud/api/commands/AuthorizeSecurityGroupEgressCmd.java index a56a8e0d200..1c8bce8ba31 100644 --- a/api/src/com/cloud/api/commands/AuthorizeSecurityGroupEgressCmd.java +++ b/api/src/com/cloud/api/commands/AuthorizeSecurityGroupEgressCmd.java @@ -17,7 +17,9 @@ import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; + import org.apache.log4j.Logger; + import com.cloud.api.ApiConstants; import com.cloud.api.BaseAsyncCmd; import com.cloud.api.BaseCmd; @@ -25,8 +27,8 @@ import com.cloud.api.IdentityMapper; import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; -import com.cloud.api.response.SecurityGroupRuleResponse; import com.cloud.api.response.SecurityGroupResponse; +import com.cloud.api.response.SecurityGroupRuleResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -65,22 +67,22 @@ public class AuthorizeSecurityGroupEgressCmd extends BaseAsyncCmd { @Parameter(name = ApiConstants.USER_SECURITY_GROUP_LIST, type = CommandType.MAP, description = "user to security group mapping") private Map userSecurityGroupList; - + @IdentityMapper(entityTableName="domain") @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId for the security group. If the account parameter is used, domainId must also be used.") private Long domainId; - + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for the security group. Must be used with domainId.") private String accountName; - + @IdentityMapper(entityTableName="projects") @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="an optional project of the security group") private Long projectId; - + @IdentityMapper(entityTableName="security_group") @Parameter(name=ApiConstants.SECURITY_GROUP_ID, type=CommandType.LONG, description="The ID of the security group. Mutually exclusive with securityGroupName parameter") private Long securityGroupId; - + @Parameter(name=ApiConstants.SECURITY_GROUP_NAME, type=CommandType.STRING, description="The name of the security group. Mutually exclusive with securityGroupName parameter") private String securityGroupName; @@ -110,21 +112,21 @@ public class AuthorizeSecurityGroupEgressCmd extends BaseAsyncCmd { public Long getSecurityGroupId() { if (securityGroupId != null && securityGroupName != null) { - throw new InvalidParameterValueException("securityGroupId and securityGroupName parameters are mutually exclusive"); + throw new InvalidParameterValueException("securityGroupId and securityGroupName parameters are mutually exclusive", null); } - + if (securityGroupName != null) { securityGroupId = _responseGenerator.getSecurityGroupId(securityGroupName, getEntityOwnerId()); if (securityGroupId == null) { - throw new InvalidParameterValueException("Unable to find security group " + securityGroupName + " for account id=" + getEntityOwnerId()); + throw new InvalidParameterValueException("Unable to find security group " + securityGroupName + " for account id=" + getEntityOwnerId(), null); } securityGroupName = null; } - + if (securityGroupId == null) { - throw new InvalidParameterValueException("Either securityGroupId or securityGroupName is required by authorizeSecurityGroupIngress command"); + throw new InvalidParameterValueException("Either securityGroupId or securityGroupName is required by authorizeSecurityGroupIngress command", null); } - + return securityGroupId; } @@ -162,7 +164,7 @@ public class AuthorizeSecurityGroupEgressCmd extends BaseAsyncCmd { if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; } diff --git a/api/src/com/cloud/api/commands/AuthorizeSecurityGroupIngressCmd.java b/api/src/com/cloud/api/commands/AuthorizeSecurityGroupIngressCmd.java index 33fc240d17c..f5e010a94c4 100644 --- a/api/src/com/cloud/api/commands/AuthorizeSecurityGroupIngressCmd.java +++ b/api/src/com/cloud/api/commands/AuthorizeSecurityGroupIngressCmd.java @@ -68,22 +68,22 @@ public class AuthorizeSecurityGroupIngressCmd extends BaseAsyncCmd { @Parameter(name = ApiConstants.USER_SECURITY_GROUP_LIST, type = CommandType.MAP, description = "user to security group mapping") private Map userSecurityGroupList; - + @IdentityMapper(entityTableName="domain") @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId for the security group. If the account parameter is used, domainId must also be used.") private Long domainId; - + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for the security group. Must be used with domainId.") private String accountName; - + @IdentityMapper(entityTableName="projects") @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="an optional project of the security group") private Long projectId; - + @IdentityMapper(entityTableName="security_group") @Parameter(name=ApiConstants.SECURITY_GROUP_ID, type=CommandType.LONG, description="The ID of the security group. Mutually exclusive with securityGroupName parameter") private Long securityGroupId; - + @Parameter(name=ApiConstants.SECURITY_GROUP_NAME, type=CommandType.STRING, description="The name of the security group. Mutually exclusive with securityGroupName parameter") private String securityGroupName; @@ -113,21 +113,21 @@ public class AuthorizeSecurityGroupIngressCmd extends BaseAsyncCmd { public Long getSecurityGroupId() { if (securityGroupId != null && securityGroupName != null) { - throw new InvalidParameterValueException("securityGroupId and securityGroupName parameters are mutually exclusive"); + throw new InvalidParameterValueException("securityGroupId and securityGroupName parameters are mutually exclusive", null); } - + if (securityGroupName != null) { securityGroupId = _responseGenerator.getSecurityGroupId(securityGroupName, getEntityOwnerId()); if (securityGroupId == null) { - throw new InvalidParameterValueException("Unable to find security group " + securityGroupName + " for account id=" + getEntityOwnerId()); + throw new InvalidParameterValueException("Unable to find security group " + securityGroupName + " for account id=" + getEntityOwnerId(), null); } securityGroupName = null; } - + if (securityGroupId == null) { - throw new InvalidParameterValueException("Either securityGroupId or securityGroupName is required by authorizeSecurityGroupIngress command"); + throw new InvalidParameterValueException("Either securityGroupId or securityGroupName is required by authorizeSecurityGroupIngress command", null); } - + return securityGroupId; } @@ -165,7 +165,7 @@ public class AuthorizeSecurityGroupIngressCmd extends BaseAsyncCmd { if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; } diff --git a/api/src/com/cloud/api/commands/CreateFirewallRuleCmd.java b/api/src/com/cloud/api/commands/CreateFirewallRuleCmd.java index abeaa15ebac..c940add63f6 100644 --- a/api/src/com/cloud/api/commands/CreateFirewallRuleCmd.java +++ b/api/src/com/cloud/api/commands/CreateFirewallRuleCmd.java @@ -59,25 +59,26 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal @Parameter(name = ApiConstants.END_PORT, type = CommandType.INTEGER, description = "the ending port of firewall rule") private Integer publicEndPort; - + @Parameter(name = ApiConstants.CIDR_LIST, type = CommandType.LIST, collectionType = CommandType.STRING, description = "the cidr list to forward traffic from") private List cidrlist; - + @Parameter(name = ApiConstants.ICMP_TYPE, type = CommandType.INTEGER, description = "type of the icmp message being sent") private Integer icmpType; @Parameter(name = ApiConstants.ICMP_CODE, type = CommandType.INTEGER, description = "error code for this icmp message") private Integer icmpCode; - + @Parameter(name = ApiConstants.TYPE, type = CommandType.STRING, description = "type of firewallrule: system/user") private String type; - + // /////////////////////////////////////////////////// // ///////////////// Accessors /////////////////////// // /////////////////////////////////////////////////// - + + @Override public String getEntityTable() { - return "firewall_rules"; + return "firewall_rules"; } public Long getIpAddressId() { @@ -89,6 +90,7 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal return protocol.trim(); } + @Override public List getSourceCidrList() { if (cidrlist != null) { return cidrlist; @@ -97,7 +99,7 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal oneCidrList.add(NetUtils.ALL_CIDRS); return oneCidrList; } - + } // /////////////////////////////////////////////////// @@ -108,7 +110,7 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal public String getCommandName() { return s_name; } - + public void setSourceCidrList(List cidrs){ cidrlist = cidrs; } @@ -171,7 +173,7 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal } else { return publicEndPort.intValue(); } - + return null; } @@ -189,14 +191,14 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal public long getNetworkId() { IpAddress ip = _entityMgr.findById(IpAddress.class, getIpAddressId()); Long ntwkId = null; - + if (ip.getAssociatedWithNetworkId() != null) { ntwkId = ip.getAssociatedWithNetworkId(); } - + if (ntwkId == null) { throw new InvalidParameterValueException("Unable to create firewall rule for the ipAddress id=" + ipAddressId + - " as ip is not associated with any network and no networkId is passed in"); + " as ip is not associated with any network and no networkId is passed in", null); } return ntwkId; } @@ -268,11 +270,11 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal private IpAddress getIp() { IpAddress ip = _networkService.getIp(ipAddressId); if (ip == null) { - throw new InvalidParameterValueException("Unable to find ip address by id " + ipAddressId); + throw new InvalidParameterValueException("Unable to find ip address by id", null); } return ip; } - + @Override public Integer getIcmpCode() { if (icmpCode != null) { @@ -282,14 +284,14 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal } return null; } - + @Override public Integer getIcmpType() { if (icmpType != null) { return icmpType; } else if (protocol.equalsIgnoreCase(NetUtils.ICMP_PROTO)) { - return -1; - + return -1; + } return null; } @@ -299,20 +301,20 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal return null; } - @Override - public FirewallRuleType getType() { - if (type != null && type.equalsIgnoreCase("system")) { - return FirewallRuleType.System; - } else { - return FirewallRuleType.User; - } - } - + @Override + public FirewallRuleType getType() { + if (type != null && type.equalsIgnoreCase("system")) { + return FirewallRuleType.System; + } else { + return FirewallRuleType.User; + } + } + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; } - + @Override public TrafficType getTrafficType() { return null; diff --git a/api/src/com/cloud/api/commands/CreateIpForwardingRuleCmd.java b/api/src/com/cloud/api/commands/CreateIpForwardingRuleCmd.java index 4e65a0ffbf4..97a83b650d4 100644 --- a/api/src/com/cloud/api/commands/CreateIpForwardingRuleCmd.java +++ b/api/src/com/cloud/api/commands/CreateIpForwardingRuleCmd.java @@ -50,19 +50,19 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta @IdentityMapper(entityTableName="user_ip_address") @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.LONG, required=true, description="the public IP address id of the forwarding rule, already associated via associateIp") private Long ipAddressId; - + @Parameter(name=ApiConstants.START_PORT, type=CommandType.INTEGER, required=true, description="the start port for the rule") private Integer startPort; @Parameter(name=ApiConstants.END_PORT, type=CommandType.INTEGER, description="the end port for the rule") private Integer endPort; - + @Parameter(name=ApiConstants.PROTOCOL, type=CommandType.STRING, required=true, description="the protocol for the rule. Valid values are TCP or UDP.") private String protocol; - + @Parameter(name = ApiConstants.OPEN_FIREWALL, type = CommandType.BOOLEAN, description = "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") private Boolean openFirewall; - + @Parameter(name = ApiConstants.CIDR_LIST, type = CommandType.LIST, collectionType = CommandType.STRING, description = "the cidr list to forward traffic from") private List cidrlist; @@ -70,23 +70,24 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + + @Override public String getEntityTable() { - return "firewall_rules"; + return "firewall_rules"; } - + public Long getIpAddressId() { return ipAddressId; } - + public int getStartPort() { return startPort; } - + public int getEndPort() { return endPort; } - + public Boolean getOpenFirewall() { if (openFirewall != null) { return openFirewall; @@ -111,11 +112,11 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta FirewallRule rule = null; try { UserContext.current().setEventDetails("Rule Id: "+ getEntityId()); - + if (getOpenFirewall()) { result = result && _firewallService.applyFirewallRules(ipAddressId, UserContext.current().getCaller()); } - + result = result && _rulesService.applyStaticNatRules(ipAddressId, UserContext.current().getCaller()); rule = _entityMgr.findById(FirewallRule.class, getEntityId()); StaticNatRule staticNatRule = _rulesService.buildStaticNatRule(rule, false); @@ -124,26 +125,26 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta this.setResponseObject(fwResponse); } finally { if (!result || rule == null) { - + if (getOpenFirewall()) { _firewallService.revokeRelatedFirewallRule(getEntityId(), true); } - + _rulesService.revokeStaticNatRule(getEntityId(), true); - + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Error in creating ip forwarding rule on the domr"); } } } - @Override - public void create() { - - //cidr list parameter is deprecated + @Override + public void create() { + + //cidr list parameter is deprecated if (cidrlist != null) { - throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall rule for the specific cidr, please refer to createFirewallRule command"); + throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall rule for the specific cidr, please refer to createFirewallRule command", null); } - + try { StaticNatRule rule = _rulesService.createStaticNatRule(this, getOpenFirewall()); this.setEntityId(rule.getId()); @@ -151,7 +152,7 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta s_logger.info("Unable to create Static Nat Rule due to ", e); throw new ServerApiException(BaseCmd.NETWORK_RULE_CONFLICT_ERROR, e.getMessage()); } - } + } @Override public long getEntityOwnerId() { @@ -174,16 +175,16 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta IpAddress ip = _networkService.getIp(ipAddressId); return ("Applying an ipforwarding 1:1 NAT rule for Ip: "+ip.getAddress()+" with virtual machine:"+ this.getVirtualMachineId()); } - + private long getVirtualMachineId() { Long vmId = _networkService.getIp(ipAddressId).getAssociatedWithVmId(); - + if (vmId == null) { - throw new InvalidParameterValueException("Ip address is not associated with any network, unable to create static nat rule"); + throw new InvalidParameterValueException("Ip address is not associated with any network, unable to create static nat rule", null); } return vmId; } - + @Override public String getDestIpAddress(){ return null; @@ -244,13 +245,13 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta IpAddress ip = _networkService.getIp(ipAddressId); return ip.getAccountId(); } - + @Override public String getXid() { // FIXME: We should allow for end user to specify Xid. return null; } - + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -264,16 +265,16 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta private IpAddress getIp() { IpAddress ip = _networkService.getIp(ipAddressId); if (ip == null) { - throw new InvalidParameterValueException("Unable to find ip address by id " + ipAddressId); + throw new InvalidParameterValueException("Unable to find ip address by id", null); } return ip; } - + @Override public Integer getIcmpCode() { return null; } - + @Override public Integer getIcmpType() { return null; @@ -283,22 +284,22 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta public List getSourceCidrList() { return null; } - + @Override public Long getRelated() { return null; } - @Override - public FirewallRuleType getType() { - return FirewallRuleType.User; - } - - @Override + @Override + public FirewallRuleType getType() { + return FirewallRuleType.User; + } + + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; } - + @Override public TrafficType getTrafficType() { return null; diff --git a/api/src/com/cloud/api/commands/CreateLoadBalancerRuleCmd.java b/api/src/com/cloud/api/commands/CreateLoadBalancerRuleCmd.java index c2ff39665f7..dbad001b8f0 100644 --- a/api/src/com/cloud/api/commands/CreateLoadBalancerRuleCmd.java +++ b/api/src/com/cloud/api/commands/CreateLoadBalancerRuleCmd.java @@ -12,6 +12,7 @@ // Automatically generated by addcopyright.py at 04/03/2012 package com.cloud.api.commands; +import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; @@ -38,6 +39,7 @@ import com.cloud.network.Network; import com.cloud.network.rules.LoadBalancer; import com.cloud.user.Account; import com.cloud.user.UserContext; +import com.cloud.utils.IdentityProxy; import com.cloud.utils.net.NetUtils; @Implementation(description="Creates a load balancer rule", responseObject=LoadBalancerResponse.class) @@ -65,7 +67,7 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements @IdentityMapper(entityTableName="user_ip_address") @Parameter(name=ApiConstants.PUBLIC_IP_ID, type=CommandType.LONG, description="public ip address id from where the network traffic will be load balanced from") private Long publicIpId; - + @IdentityMapper(entityTableName="data_center") @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=false, description="zone where the load balancer is going to be created. This parameter is required when LB service provider is ElasticLoadBalancerVm") private Long zoneId; @@ -74,8 +76,8 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements private Integer publicPort; @Parameter(name = ApiConstants.OPEN_FIREWALL, type = CommandType.BOOLEAN, description = "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 LB" + - " rule is being created for VPC guest network 2) in all other cases defaulted to true") + " source/end pubic 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") private Boolean openFirewall; @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="the account associated with the load balancer. Must be used with the domainId parameter.") @@ -84,15 +86,15 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements @IdentityMapper(entityTableName="domain") @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the domain ID associated with the load balancer") private Long domainId; - + @Parameter(name = ApiConstants.CIDR_LIST, type = CommandType.LIST, collectionType = CommandType.STRING, description = "the cidr list to forward traffic from") private List cidrlist; - + @IdentityMapper(entityTableName="networks") @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, description="The guest network this " + - "rule will be created for. Required when public Ip address is not associated with any Guest network yet (VPC case)") + "rule will be created for. Required when public Ip address is not associated with any Guest network yet (VPC case)") private Long networkId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -113,97 +115,100 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements return privatePort; } + @Override public String getEntityTable() { - return "firewall_rules"; + return "firewall_rules"; } - + public Long getSourceIpAddressId() { - if (publicIpId != null) { - IpAddress ipAddr = _networkService.getIp(publicIpId); - if (ipAddr == null || !ipAddr.readyToUse()) { - throw new InvalidParameterValueException("Unable to create load balancer rule, invalid IP address id " + ipAddr.getId()); - } - } else if (getEntityId() != null) { - LoadBalancer rule = _entityMgr.findById(LoadBalancer.class, getEntityId()); - return rule.getSourceIpAddressId(); - } - - return publicIpId; + if (publicIpId != null) { + IpAddress ipAddr = _networkService.getIp(publicIpId); + if (ipAddr == null || !ipAddr.readyToUse()) { + throw new InvalidParameterValueException("Unable to create load balancer rule, invalid IP address id provided", null); + } + } else if (getEntityId() != null) { + LoadBalancer rule = _entityMgr.findById(LoadBalancer.class, getEntityId()); + return rule.getSourceIpAddressId(); + } + + return publicIpId; } - + private Long getVpcId() { if (publicIpId != null) { IpAddress ipAddr = _networkService.getIp(publicIpId); if (ipAddr == null || !ipAddr.readyToUse()) { - throw new InvalidParameterValueException("Unable to create load balancer rule, invalid IP address id " + ipAddr.getId()); + throw new InvalidParameterValueException("Unable to create load balancer rule, invalid IP address id povided", null); } else { return ipAddr.getVpcId(); } } return null; } - - + + public Long getNetworkId() { if (networkId != null) { return networkId; } Long zoneId = getZoneId(); - + if (zoneId == null) { - Long ipId = getSourceIpAddressId(); - if (ipId == null) { - throw new InvalidParameterValueException("Either networkId or zoneId or publicIpId has to be specified"); - } + Long ipId = getSourceIpAddressId(); + if (ipId == null) { + throw new InvalidParameterValueException("Either networkId or zoneId or publicIpId has to be specified", null); + } } - + if (zoneId != null) { - DataCenter zone = _configService.getZone(zoneId); - if (zone.getNetworkType() == NetworkType.Advanced) { + DataCenter zone = _configService.getZone(zoneId); + if (zone.getNetworkType() == NetworkType.Advanced) { List networks = _networkService.getIsolatedNetworksOwnedByAccountInZone(getZoneId(), _accountService.getAccount(getEntityOwnerId())); if (networks.size() == 0) { String domain = _domainService.getDomain(getDomainId()).getName(); - throw new InvalidParameterValueException("Account name=" + getAccountName() + " domain=" + domain + " doesn't have virtual networks in zone=" + zone.getName()); + throw new InvalidParameterValueException("Account name=" + getAccountName() + " domain=" + domain + " doesn't have virtual networks in zone=" + zone.getName(), null); } - + if (networks.size() < 1) { - throw new InvalidParameterValueException("Account doesn't have any Isolated networks in the zone"); + throw new InvalidParameterValueException("Account doesn't have any Isolated networks in the zone", null); } else if (networks.size() > 1) { - throw new InvalidParameterValueException("Account has more than one Isolated network in the zone"); + throw new InvalidParameterValueException("Account has more than one Isolated network in the zone", null); } - + return networks.get(0).getId(); } else { Network defaultGuestNetwork = _networkService.getExclusiveGuestNetwork(zoneId); if (defaultGuestNetwork == null) { - throw new InvalidParameterValueException("Unable to find a default Guest network for account " + getAccountName() + " in domain id=" + getDomainId()); + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", getDomainId(), "domainId")); + throw new InvalidParameterValueException("Unable to find a default Guest network for account " + getAccountName() + " in domain with specified id", idList); } else { return defaultGuestNetwork.getId(); } } } else { - IpAddress ipAddr = _networkService.getIp(publicIpId); - if (ipAddr.getAssociatedWithNetworkId() != null) { + IpAddress ipAddr = _networkService.getIp(publicIpId); + if (ipAddr.getAssociatedWithNetworkId() != null) { return ipAddr.getAssociatedWithNetworkId(); - } else { - throw new InvalidParameterValueException("Ip address id=" + publicIpId + " is not associated with any network"); - } + } else { + throw new InvalidParameterValueException("Ip address id=" + publicIpId + " is not associated with any network", null); + } } } public Integer getPublicPort() { return publicPort; } - + public String getName() { return loadBalancerRuleName; } - + public Boolean getOpenFirewall() { boolean isVpc = getVpcId() == null ? false : true; if (openFirewall != null) { if (isVpc && openFirewall) { - throw new InvalidParameterValueException("Can't have openFirewall=true when IP address belongs to VPC"); + throw new InvalidParameterValueException("Can't have openFirewall=true when IP address belongs to VPC", null); } return openFirewall; } else { @@ -213,10 +218,10 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements return true; } } - + public List getSourceCidrList() { if (cidrlist != null) { - throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall rule for the specific cidr, please refer to createFirewallRule command"); + throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall rule for the specific cidr, please refer to createFirewallRule command", null); } return null; } @@ -229,16 +234,16 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements public String getCommandName() { return s_name; } - + @Override public void execute() throws ResourceAllocationException, ResourceUnavailableException { - + UserContext callerContext = UserContext.current(); boolean success = true; LoadBalancer rule = null; try { UserContext.current().setEventDetails("Rule Id: " + getEntityId()); - + if (getOpenFirewall()) { success = success && _firewallService.applyFirewallRules(getSourceIpAddressId(), callerContext.getCaller()); } @@ -252,10 +257,10 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements } lbResponse.setResponseName(getCommandName()); } catch (Exception ex) { - s_logger.warn("Failed to create LB rule due to exception ", ex); + s_logger.warn("Failed to create LB rule due to exception ", ex); }finally { if (!success || rule == null) { - + if (getOpenFirewall()) { _firewallService.revokeRelatedFirewallRule(getEntityId(), true); } @@ -266,12 +271,12 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements } } } - + @Override public void create() { //cidr list parameter is deprecated if (cidrlist != null) { - throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall rule for the specific cidr, please refer to createFirewallRule command"); + throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall rule for the specific cidr, please refer to createFirewallRule command", null); } try { LoadBalancer result = _lbService.createLoadBalancerRule(this, getOpenFirewall()); @@ -296,21 +301,23 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements public String getProtocol() { return NetUtils.TCP_PROTO; } - + public long getAccountId() { if (publicIpId != null) return _networkService.getIp(getSourceIpAddressId()).getAccountId(); - + Account account = null; if ((domainId != null) && (accountName != null)) { account = _responseGenerator.findAccountByNameDomain(accountName, domainId); if (account != null) { return account.getId(); } else { - throw new InvalidParameterValueException("Unable to find account " + account + " in domain id=" + domainId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", getDomainId(), "domainId")); + throw new InvalidParameterValueException("Unable to find account " + account + " in domain with specified id", idList); } } else { - throw new InvalidParameterValueException("Can't define IP owner. Either specify account/domainId or ipAddressId"); + throw new InvalidParameterValueException("Can't define IP owner. Either specify account/domainId or ipAddressId", null); } } @@ -330,16 +337,16 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements public int getDefaultPortEnd() { return privatePort.intValue(); } - + @Override public long getEntityOwnerId() { - return getAccountId(); + return getAccountId(); } - + public String getAccountName() { return accountName; } - + public Long getZoneId() { return zoneId; } @@ -367,7 +374,7 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements public void setSourceIpAddressId(Long ipId) { this.publicIpId = ipId; } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; diff --git a/api/src/com/cloud/api/commands/CreateNetworkACLCmd.java b/api/src/com/cloud/api/commands/CreateNetworkACLCmd.java index 68d996a2ea7..0efc57004c6 100644 --- a/api/src/com/cloud/api/commands/CreateNetworkACLCmd.java +++ b/api/src/com/cloud/api/commands/CreateNetworkACLCmd.java @@ -47,30 +47,31 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR @Parameter(name = ApiConstants.END_PORT, type = CommandType.INTEGER, description = "the ending port of ACL") private Integer publicEndPort; - + @Parameter(name = ApiConstants.CIDR_LIST, type = CommandType.LIST, collectionType = CommandType.STRING, description = "the cidr list to allow traffic from/to") private List cidrlist; - + @Parameter(name = ApiConstants.ICMP_TYPE, type = CommandType.INTEGER, description = "type of the icmp message being sent") private Integer icmpType; @Parameter(name = ApiConstants.ICMP_CODE, type = CommandType.INTEGER, description = "error code for this icmp message") private Integer icmpCode; - + @IdentityMapper(entityTableName="networks") @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, required=true, - description="The network of the vm the ACL will be created for") + description="The network of the vm the ACL will be created for") private Long networkId; - + @Parameter(name=ApiConstants.TRAFFIC_TYPE, type=CommandType.STRING, description="the traffic type for the ACL," + - "can be Ingress or Egress, defaulted to Ingress if not specified") + "can be Ingress or Egress, defaulted to Ingress if not specified") private String trafficType; - + // /////////////////////////////////////////////////// // ///////////////// Accessors /////////////////////// // /////////////////////////////////////////////////// - + + @Override public String getEntityTable() { return "firewall_rules"; } @@ -84,6 +85,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR return protocol.trim(); } + @Override public List getSourceCidrList() { if (cidrlist != null) { return cidrlist; @@ -93,21 +95,21 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR return oneCidrList; } } - + public long getVpcId() { Network network = _networkService.getNetwork(getNetworkId()); if (network == null) { - throw new InvalidParameterValueException("Invalid networkId is given"); + throw new InvalidParameterValueException("Invalid networkId is given", null); } - + Long vpcId = network.getVpcId(); if (vpcId == null) { - throw new InvalidParameterValueException("Can create network ACL only for the network belonging to the VPC"); + throw new InvalidParameterValueException("Can create network ACL only for the network belonging to the VPC", null); } - + return vpcId; } - + @Override public FirewallRule.TrafficType getTrafficType() { if (trafficType == null) { @@ -118,7 +120,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR return type; } } - throw new InvalidParameterValueException("Invalid traffic type " + trafficType); + throw new InvalidParameterValueException("Invalid traffic type " + trafficType, null); } // /////////////////////////////////////////////////// @@ -129,7 +131,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR public String getCommandName() { return s_name; } - + public void setSourceCidrList(List cidrs){ cidrlist = cidrs; } @@ -191,7 +193,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR } else { return publicEndPort.intValue(); } - + return null; } @@ -214,7 +216,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR public long getEntityOwnerId() { Vpc vpc = _vpcService.getVpc(getVpcId()); if (vpc == null) { - throw new InvalidParameterValueException("Invalid vpcId is given"); + throw new InvalidParameterValueException("Invalid vpcId is given", null); } Account account = _accountService.getAccount(vpc.getAccountId()); @@ -273,7 +275,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR public Long getSyncObjId() { return getNetworkId(); } - + @Override public Integer getIcmpCode() { if (icmpCode != null) { @@ -283,14 +285,14 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR } return null; } - + @Override public Integer getIcmpType() { if (icmpType != null) { return icmpType; } else if (protocol.equalsIgnoreCase(NetUtils.ICMP_PROTO)) { - return -1; - + return -1; + } return null; } @@ -304,7 +306,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR public FirewallRuleType getType() { return FirewallRuleType.User; } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; diff --git a/api/src/com/cloud/api/commands/CreateNetworkCmd.java b/api/src/com/cloud/api/commands/CreateNetworkCmd.java index a9e1291a782..a1d01c7bcc3 100644 --- a/api/src/com/cloud/api/commands/CreateNetworkCmd.java +++ b/api/src/com/cloud/api/commands/CreateNetworkCmd.java @@ -39,54 +39,54 @@ public class CreateNetworkCmd extends BaseCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the network") private String name; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, required=true, description="the display text of the network") private String displayText; - + @IdentityMapper(entityTableName="network_offerings") @Parameter(name=ApiConstants.NETWORK_OFFERING_ID, type=CommandType.LONG, required=true, description="the network offering id") private Long networkOfferingId; - + @IdentityMapper(entityTableName="data_center") @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="the Zone ID for the network") private Long zoneId; - + @IdentityMapper(entityTableName="physical_network") @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="the Physical Network ID the network belongs to") private Long physicalNetworkId; @Parameter(name=ApiConstants.GATEWAY, type=CommandType.STRING, description="the gateway of the network. Required " + - "for Shared networks and Isolated networks when it belongs to VPC") + "for Shared networks and Isolated networks when it belongs to VPC") private String gateway; - + @Parameter(name=ApiConstants.NETMASK, type=CommandType.STRING, description="the netmask of the network. Required " + "for Shared networks and Isolated networks when it belongs to VPC") private String netmask; - + @Parameter(name=ApiConstants.START_IP, type=CommandType.STRING, description="the beginning IP address in the network IP range") private String startIp; - + @Parameter(name=ApiConstants.END_IP, type=CommandType.STRING, description="the ending IP address in the network IP" + - " range. If not specified, will be defaulted to startIP") + " range. If not specified, will be defaulted to startIP") private String endIp; @Parameter(name=ApiConstants.VLAN, type=CommandType.STRING, description="the ID or VID of the network") private String vlan; - + @Parameter(name=ApiConstants.NETWORK_DOMAIN, type=CommandType.STRING, description="network domain") private String networkDomain; - + @Parameter(name=ApiConstants.ACL_TYPE, type=CommandType.STRING, description="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") + " 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") private String aclType; @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="account who will own the network") private String accountName; - + @IdentityMapper(entityTableName="projects") @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="an optional project for the ssh key") private Long projectId; @@ -94,11 +94,11 @@ public class CreateNetworkCmd extends BaseCmd { @IdentityMapper(entityTableName="domain") @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="domain ID of the account owning a network") private Long domainId; - + @Parameter(name=ApiConstants.SUBDOMAIN_ACCESS, type=CommandType.BOOLEAN, description="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") + " 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") private Boolean subdomainAccess; - + @IdentityMapper(entityTableName="vpc") @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, description="the VPC network belongs to") private Long vpcId; @@ -126,7 +126,7 @@ public class CreateNetworkCmd extends BaseCmd { public Long getDomainId() { return domainId; } - + public String getNetmask() { return netmask; } @@ -138,11 +138,11 @@ public class CreateNetworkCmd extends BaseCmd { public String getEndIp() { return endIp; } - + public String getNetworkName() { return name; } - + public String getDisplayText() { return displayText; } @@ -150,48 +150,48 @@ public class CreateNetworkCmd extends BaseCmd { public String getNetworkDomain() { return networkDomain; } - + public Long getProjectId() { return projectId; } public String getAclType() { - return aclType; - } + return aclType; + } - public Boolean getSubdomainAccess() { - return subdomainAccess; - } + public Boolean getSubdomainAccess() { + return subdomainAccess; + } - public Long getVpcId() { + public Long getVpcId() { return vpcId; } public Long getZoneId() { Long physicalNetworkId = getPhysicalNetworkId(); - + if (physicalNetworkId == null && zoneId == null) { - throw new InvalidParameterValueException("Zone id is required"); + throw new InvalidParameterValueException("Zone id is required", null); } - + return zoneId; } - + public Long getPhysicalNetworkId() { NetworkOffering offering = _configService.getNetworkOffering(networkOfferingId); if (offering == null) { - throw new InvalidParameterValueException("Unable to find network offering by id " + networkOfferingId); + throw new InvalidParameterValueException("Unable to find network offering by id", null); } - + if (physicalNetworkId != null) { if (offering.getGuestType() == GuestType.Shared) { return physicalNetworkId; } else { - throw new InvalidParameterValueException("Physical network id can be specified for networks of guest ip type " + GuestType.Shared + " only."); + throw new InvalidParameterValueException("Physical network id can be specified for networks of guest ip type " + GuestType.Shared + " only.", null); } } else { if (zoneId == null) { - throw new InvalidParameterValueException("ZoneId is required as physicalNetworkId is null"); + throw new InvalidParameterValueException("ZoneId is required as physicalNetworkId is null", null); } return _networkService.findPhysicalNetworkId(zoneId, offering.getTags(), offering.getTrafficType()); } @@ -204,17 +204,17 @@ public class CreateNetworkCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Long accountId = finalyzeAccountId(accountName, domainId, projectId, true); if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; } - + @Override public void execute() throws InsufficientCapacityException, ConcurrentOperationException, ResourceAllocationException{ Network result = _networkService.createGuestNetwork(this); diff --git a/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java b/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java index 80120c888cc..8b69aec1261 100644 --- a/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java +++ b/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java @@ -46,55 +46,55 @@ public class CreateNetworkOfferingCmd extends BaseCmd { @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the network offering") private String networkOfferingName; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, required=true, description="the display text of the network offering") private String displayText; - + @Parameter(name=ApiConstants.TRAFFIC_TYPE, type=CommandType.STRING, required=true, description="the traffic type for the network offering. Supported type in current release is GUEST only") private String traffictype; - + @Parameter(name=ApiConstants.TAGS, type=CommandType.STRING, description="the tags for the network offering.", length=4096) private String tags; - + @Parameter(name=ApiConstants.SPECIFY_VLAN, type=CommandType.BOOLEAN, description="true if network offering supports vlans") private Boolean specifyVlan; - + @Parameter(name=ApiConstants.AVAILABILITY, type=CommandType.STRING, description="the availability of network offering. Default value is Optional") private String availability; - + @Parameter(name=ApiConstants.NETWORKRATE, type=CommandType.INTEGER, description="data transfer rate in megabits per second allowed") private Integer networkRate; - + @Parameter(name=ApiConstants.CONSERVE_MODE, type=CommandType.BOOLEAN, description="true if the network offering is IP conserve mode enabled") private Boolean conserveMode; - + @IdentityMapper(entityTableName="disk_offering") @Parameter(name=ApiConstants.SERVICE_OFFERING_ID, type=CommandType.LONG, description="the service offering ID used by virtual router provider") private Long serviceOfferingId; - + @Parameter(name=ApiConstants.GUEST_IP_TYPE, type=CommandType.STRING, required=true, description="guest type of the network offering: Shared or Isolated") private String guestIptype; - + @Parameter(name=ApiConstants.SUPPORTED_SERVICES, type=CommandType.LIST, required=true, collectionType=CommandType.STRING, description="services supported by the network offering") private List supportedServices; - + @Parameter(name = ApiConstants.SERVICE_PROVIDER_LIST, type = CommandType.MAP, description = "provider to service mapping. If not specified, the provider for the service will be mapped to the default provider on the physical network") private Map serviceProviderList; @Parameter(name = ApiConstants.SERVICE_CAPABILITY_LIST, type = CommandType.MAP, description = "desired service capabilities as part of network offering") private Map serviceCapabilitystList; - + @Parameter(name=ApiConstants.SPECIFY_IP_RANGES, type=CommandType.BOOLEAN, description="true if network offering supports specifying ip ranges; defaulted to false if not specified") private Boolean specifyIpRanges; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public String getNetworkOfferingName() { return networkOfferingName; } - + public String getDisplayText() { return displayText; } @@ -106,7 +106,7 @@ public class CreateNetworkOfferingCmd extends BaseCmd { public String getTraffictype() { return traffictype; } - + public Boolean getSpecifyVlan() { return specifyVlan == null ? false : specifyVlan; } @@ -114,7 +114,7 @@ public class CreateNetworkOfferingCmd extends BaseCmd { public String getAvailability() { return availability == null ? Availability.Optional.toString() : availability; } - + public Integer getNetworkRate() { return networkRate; } @@ -126,18 +126,18 @@ public class CreateNetworkOfferingCmd extends BaseCmd { public Long getServiceOfferingId() { return serviceOfferingId; } - - public List getSupportedServices() { - return supportedServices; - } - public String getGuestIpType() { + public List getSupportedServices() { + return supportedServices; + } + + public String getGuestIpType() { return guestIptype; } - - public Boolean getSpecifyIpRanges() { - return specifyIpRanges == null ? false : specifyIpRanges; - } + + public Boolean getSpecifyIpRanges() { + return specifyIpRanges == null ? false : specifyIpRanges; + } public Boolean getConserveMode() { if (conserveMode == null) { @@ -166,7 +166,7 @@ public class CreateNetworkOfferingCmd extends BaseCmd { serviceProviderMap.put(service, providerList); } } - + return serviceProviderMap; } @@ -180,22 +180,22 @@ public class CreateNetworkOfferingCmd extends BaseCmd { while (iter.hasNext()) { HashMap svcCapabilityMap = (HashMap) iter.next(); Capability capability = null; - String svc = (String) svcCapabilityMap.get("service"); - String capabilityName = (String) svcCapabilityMap.get("capabilitytype"); - String capabilityValue = (String) svcCapabilityMap.get("capabilityvalue"); + String svc = svcCapabilityMap.get("service"); + String capabilityName = svcCapabilityMap.get("capabilitytype"); + String capabilityValue = svcCapabilityMap.get("capabilityvalue"); if (capabilityName != null) { capability = Capability.getCapability(capabilityName); } if ((capability == null) || (capabilityName == null) || (capabilityValue == null) ) { - throw new InvalidParameterValueException("Invalid capability:" + capabilityName + " capability value:" + capabilityValue); + throw new InvalidParameterValueException("Invalid capability:" + capabilityName + " capability value:" + capabilityValue, null); } if (svc.equalsIgnoreCase(service.getName())) { capabilityMap.put(capability, capabilityValue); } else { - //throw new InvalidParameterValueException("Service is not equal ") + //throw new InvalidParameterValueException("Service is not equal ") } } } @@ -210,7 +210,7 @@ public class CreateNetworkOfferingCmd extends BaseCmd { public String getCommandName() { return _name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; diff --git a/api/src/com/cloud/api/commands/CreatePortForwardingRuleCmd.java b/api/src/com/cloud/api/commands/CreatePortForwardingRuleCmd.java index 2c5a0739094..324ab07a387 100644 --- a/api/src/com/cloud/api/commands/CreatePortForwardingRuleCmd.java +++ b/api/src/com/cloud/api/commands/CreatePortForwardingRuleCmd.java @@ -65,7 +65,7 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P @IdentityMapper(entityTableName = "vm_instance") @Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID, type = CommandType.LONG, required = true, - description = "the ID of the virtual machine for the port forwarding rule") + description = "the ID of the virtual machine for the port forwarding rule") private Long virtualMachineId; @Parameter(name = ApiConstants.CIDR_LIST, type = CommandType.LIST, collectionType = CommandType.STRING, @@ -74,20 +74,21 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P @Parameter(name = ApiConstants.OPEN_FIREWALL, type = CommandType.BOOLEAN, description = "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") + "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") private Boolean openFirewall; - + @IdentityMapper(entityTableName="networks") @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, - description="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)") + description="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)") private Long networkId; // /////////////////////////////////////////////////// // ///////////////// Accessors /////////////////////// // /////////////////////////////////////////////////// + @Override public String getEntityTable() { return "firewall_rules"; } @@ -106,10 +107,11 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P return virtualMachineId; } + @Override public List getSourceCidrList() { if (cidrlist != null) { throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall " + - "rule for the specific cidr, please refer to createFirewallRule command"); + "rule for the specific cidr, please refer to createFirewallRule command", null); } return null; } @@ -118,7 +120,7 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P boolean isVpc = getVpcId() == null ? false : true; if (openFirewall != null) { if (isVpc && openFirewall) { - throw new InvalidParameterValueException("Can't have openFirewall=true when IP address belongs to VPC"); + throw new InvalidParameterValueException("Can't have openFirewall=true when IP address belongs to VPC", null); } return openFirewall; } else { @@ -128,12 +130,12 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P return true; } } - + private Long getVpcId() { if (ipAddressId != null) { IpAddress ipAddr = _networkService.getIp(ipAddressId); if (ipAddr == null || !ipAddr.readyToUse()) { - throw new InvalidParameterValueException("Unable to create PF rule, invalid IP address id " + ipAddr.getId()); + throw new InvalidParameterValueException("Unable to create PF rule, invalid IP address id " + ipAddr.getId(), null); } else { return ipAddr.getVpcId(); } @@ -226,7 +228,7 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P public long getNetworkId() { IpAddress ip = _entityMgr.findById(IpAddress.class, getIpAddressId()); Long ntwkId = null; - + if (ip.getAssociatedWithNetworkId() != null) { ntwkId = ip.getAssociatedWithNetworkId(); } else { @@ -234,7 +236,7 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P } if (ntwkId == null) { throw new InvalidParameterValueException("Unable to create port forwarding rule for the ipAddress id=" + ipAddressId + - " as ip is not associated with any network and no networkId is passed in"); + " as ip is not associated with any network and no networkId is passed in", null); } return ntwkId; } @@ -281,7 +283,7 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P public void create() { // cidr list parameter is deprecated if (cidrlist != null) { - throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall rule for the specific cidr, please refer to createFirewallRule command"); + throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall rule for the specific cidr, please refer to createFirewallRule command", null); } try { @@ -324,7 +326,7 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P private IpAddress getIp() { IpAddress ip = _networkService.getIp(ipAddressId); if (ip == null) { - throw new InvalidParameterValueException("Unable to find ip address by id " + ipAddressId); + throw new InvalidParameterValueException("Unable to find ip address by id", null); } return ip; } @@ -348,7 +350,7 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P public FirewallRuleType getType() { return FirewallRuleType.User; } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; diff --git a/api/src/com/cloud/api/commands/CreatePrivateGatewayCmd.java b/api/src/com/cloud/api/commands/CreatePrivateGatewayCmd.java index d493b8bc291..daeb9dd40d3 100644 --- a/api/src/com/cloud/api/commands/CreatePrivateGatewayCmd.java +++ b/api/src/com/cloud/api/commands/CreatePrivateGatewayCmd.java @@ -46,27 +46,27 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + @IdentityMapper(entityTableName="physical_network") @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="the Physical Network ID the network belongs to") private Long physicalNetworkId; @Parameter(name=ApiConstants.GATEWAY, type=CommandType.STRING, required=true, description="the gateway of the Private gateway") private String gateway; - + @Parameter(name=ApiConstants.NETMASK, type=CommandType.STRING, required=true, description="the netmask of the Private gateway") private String netmask; - + @Parameter(name=ApiConstants.IP_ADDRESS, type=CommandType.STRING, required=true, description="the IP address of the Private gateaway") private String ipAddress; - + @Parameter(name=ApiConstants.VLAN, type=CommandType.STRING, required=true, description="the Vlan for the private gateway") private String vlan; - + @IdentityMapper(entityTableName="vpc") @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, required=true, description="the VPC network belongs to") private Long vpcId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -78,7 +78,7 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { public String getVlan() { return vlan; } - + public String getNetmask() { return netmask; } @@ -86,11 +86,11 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { public String getStartIp() { return ipAddress; } - + public Long getPhysicalNetworkId() { return physicalNetworkId; } - + public Long getVpcId() { return vpcId; } @@ -102,8 +102,8 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { public String getCommandName() { return s_name; } - - + + @Override public void create() throws ResourceAllocationException { PrivateGateway result = null; @@ -118,17 +118,17 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); } - + if (result != null) { this.setEntityId(result.getId()); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create private gateway"); } } - + @Override public void execute() throws InsufficientCapacityException, ConcurrentOperationException, - ResourceAllocationException, ResourceUnavailableException { + ResourceAllocationException, ResourceUnavailableException { PrivateGateway result = _vpcService.applyVpcPrivateGateway(getEntityId()); if (result != null) { PrivateGatewayResponse response = _responseGenerator.createPrivateGatewayResponse(result); @@ -138,7 +138,7 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create private gateway"); } } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; @@ -153,13 +153,13 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { public String getEventDescription() { return "creating private gateway"; } - + @Override public String getEntityTable() { return "vpc_gateways"; } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.vpcSyncObject; @@ -169,11 +169,11 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { public Long getSyncObjId() { Vpc vpc = _vpcService.getVpc(vpcId); if (vpc == null) { - throw new InvalidParameterValueException("Invalid id is specified for the vpc"); + throw new InvalidParameterValueException("Invalid id is specified for the vpc", null); } return vpc.getId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.PrivateGateway; diff --git a/api/src/com/cloud/api/commands/CreateProjectCmd.java b/api/src/com/cloud/api/commands/CreateProjectCmd.java index 1880793443e..d584b569ab3 100644 --- a/api/src/com/cloud/api/commands/CreateProjectCmd.java +++ b/api/src/com/cloud/api/commands/CreateProjectCmd.java @@ -56,6 +56,7 @@ public class CreateProjectCmd extends BaseAsyncCreateCmd { // ///////////////// Accessors /////////////////////// // /////////////////////////////////////////////////// + @Override public String getEntityTable() { return "projects"; } @@ -95,7 +96,7 @@ public class CreateProjectCmd extends BaseAsyncCreateCmd { Account caller = UserContext.current().getCaller(); if ((accountName != null && domainId == null) || (domainId != null && accountName == null)) { - throw new InvalidParameterValueException("Account name and domain id must be specified together"); + throw new InvalidParameterValueException("Account name and domain id must be specified together", null); } if (accountName != null) { diff --git a/api/src/com/cloud/api/commands/CreateRemoteAccessVpnCmd.java b/api/src/com/cloud/api/commands/CreateRemoteAccessVpnCmd.java index 7964166b009..70c99cb013a 100644 --- a/api/src/com/cloud/api/commands/CreateRemoteAccessVpnCmd.java +++ b/api/src/com/cloud/api/commands/CreateRemoteAccessVpnCmd.java @@ -45,7 +45,7 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd { @Parameter(name="iprange", type=CommandType.STRING, required=false, description="the range of ip addresses to allocate to vpn clients. The first ip in the range will be taken by the vpn server") private String ipRange; - + @Deprecated @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for the VPN. Must be used with domainId.") private String accountName; @@ -54,46 +54,47 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd { @IdentityMapper(entityTableName="domain") @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId for the VPN. If the account parameter is used, domainId must also be used.") private Long domainId; - + @Parameter(name = ApiConstants.OPEN_FIREWALL, type = CommandType.BOOLEAN, description = "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") private Boolean openFirewall; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// + @Override public String getEntityTable() { - return "user_ip_address"; + return "user_ip_address"; } - + public Long getPublicIpId() { - return publicIpId; - } - - public String getAccountName() { - return accountName; - } - - public Long getDomainId() { - return domainId; - } - - public String getIpRange() { - return ipRange; - } - - public void setIpRange(String ipRange) { - this.ipRange = ipRange; - } - - public Boolean getOpenFirewall() { - if (openFirewall != null) { - return openFirewall; - } else { - return true; - } + return publicIpId; } - + + public String getAccountName() { + return accountName; + } + + public Long getDomainId() { + return domainId; + } + + public String getIpRange() { + return ipRange; + } + + public void setIpRange(String ipRange) { + this.ipRange = ipRange; + } + + public Boolean getOpenFirewall() { + if (openFirewall != null) { + return openFirewall; + } else { + return true; + } + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -104,42 +105,42 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd { return s_name; } - @Override - public long getEntityOwnerId() { - IpAddress ip = _networkService.getIp(publicIpId); - - if (ip == null) { - throw new InvalidParameterValueException("Unable to find ip address by id=" + publicIpId); - } - - return ip.getAccountId(); + @Override + public long getEntityOwnerId() { + IpAddress ip = _networkService.getIp(publicIpId); + + if (ip == null) { + throw new InvalidParameterValueException("Unable to find ip address by id", null); + } + + return ip.getAccountId(); } - @Override - public String getEventDescription() { - return "Create Remote Access VPN for account " + getEntityOwnerId() + " using public ip id=" + publicIpId; - } + @Override + public String getEventDescription() { + return "Create Remote Access VPN for account " + getEntityOwnerId() + " using public ip id=" + publicIpId; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_REMOTE_ACCESS_VPN_CREATE; + } - @Override - public String getEventType() { - return EventTypes.EVENT_REMOTE_ACCESS_VPN_CREATE; - } - public long getNetworkId() { IpAddress ip = _entityMgr.findById(IpAddress.class, getPublicIpId()); Long ntwkId = null; - + if (ip.getAssociatedWithNetworkId() != null) { ntwkId = ip.getAssociatedWithNetworkId(); } - + if (ntwkId == null) { throw new InvalidParameterValueException("Unable to create remote access vpn for the ipAddress id=" + getPublicIpId() + - " as ip is not associated with any network and no networkId is passed in"); + " as ip is not associated with any network and no networkId is passed in", null); } return ntwkId; } - + @Override public void create() { try { @@ -172,8 +173,8 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd { throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -187,7 +188,7 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd { private IpAddress getIp() { IpAddress ip = _networkService.getIp(publicIpId); if (ip == null) { - throw new InvalidParameterValueException("Unable to find ip address by id " + publicIpId); + throw new InvalidParameterValueException("Unable to find ip address by id", null); } return ip; } diff --git a/api/src/com/cloud/api/commands/CreateSnapshotCmd.java b/api/src/com/cloud/api/commands/CreateSnapshotCmd.java index ce2962fd4bf..9a78007f274 100755 --- a/api/src/com/cloud/api/commands/CreateSnapshotCmd.java +++ b/api/src/com/cloud/api/commands/CreateSnapshotCmd.java @@ -60,9 +60,10 @@ public class CreateSnapshotCmd extends BaseAsyncCreateCmd { // /////////////////////////////////////////////////// // ///////////////// Accessors /////////////////////// // /////////////////////////////////////////////////// - + + @Override public String getEntityTable() { - return "snapshots"; + return "snapshots"; } public String getAccountName() { @@ -100,23 +101,23 @@ public class CreateSnapshotCmd extends BaseAsyncCreateCmd { @Override public long getEntityOwnerId() { - + Volume volume = _entityMgr.findById(Volume.class, getVolumeId()); if (volume == null) { - throw new InvalidParameterValueException("Unable to find volume by id=" + volumeId); + throw new InvalidParameterValueException("Unable to find volume by id", null); } - + Account account = _accountService.getAccount(volume.getAccountId()); //Can create templates for enabled projects/accounts only if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - Project project = _projectService.findByProjectAccountId(volume.getAccountId()); + Project project = _projectService.findByProjectAccountId(volume.getAccountId()); if (project.getState() != Project.State.Active) { throw new PermissionDeniedException("Can't add resources to the project id=" + project.getId() + " in state=" + project.getState() + " as it's no longer active"); } } else if (account.getState() == Account.State.disabled) { throw new PermissionDeniedException("The owner of template is disabled: " + account); } - + return volume.getAccountId(); } diff --git a/api/src/com/cloud/api/commands/CreateSnapshotPolicyCmd.java b/api/src/com/cloud/api/commands/CreateSnapshotPolicyCmd.java index 890c66c9121..a6a7212a08e 100644 --- a/api/src/com/cloud/api/commands/CreateSnapshotPolicyCmd.java +++ b/api/src/com/cloud/api/commands/CreateSnapshotPolicyCmd.java @@ -45,11 +45,11 @@ public class CreateSnapshotPolicyCmd extends BaseCmd { private Integer maxSnaps; @Parameter(name=ApiConstants.SCHEDULE, type=CommandType.STRING, required=true, description="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)") + "Format is:" + + "* if HOURLY, MM" + + "* if DAILY, MM:HH" + + "* if WEEKLY, MM:HH:DD (1-7)" + + "* if MONTHLY, MM:HH:DD (1-28)") private String schedule; @Parameter(name=ApiConstants.TIMEZONE, type=CommandType.STRING, required=true, description="Specifies a timezone for this command. For more information on the timezone parameter, see Time Zone Format.") @@ -93,30 +93,30 @@ public class CreateSnapshotPolicyCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Volume volume = _entityMgr.findById(Volume.class, getVolumeId()); if (volume == null) { - throw new InvalidParameterValueException("Unable to find volume by id=" + volumeId); + throw new InvalidParameterValueException("Unable to find volume by id", null); } - + Account account = _accountService.getAccount(volume.getAccountId()); //Can create templates for enabled projects/accounts only if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - Project project = _projectService.findByProjectAccountId(volume.getAccountId()); + Project project = _projectService.findByProjectAccountId(volume.getAccountId()); if (project.getState() != Project.State.Active) { - PermissionDeniedException ex = new PermissionDeniedException("Can't add resources to the specified project id in state=" + project.getState() + " as it's no longer active"); + PermissionDeniedException ex = new PermissionDeniedException("Can't add resources to the specified project id in state=" + project.getState() + " as it's no longer active"); ex.addProxyObject(project, project.getId(), "projectId"); throw ex; } } else if (account.getState() == Account.State.disabled) { throw new PermissionDeniedException("The owner of template is disabled: " + account); } - + return volume.getAccountId(); } - + @Override public void execute(){ SnapshotPolicy result = _snapshotService.createPolicy(this, _accountService.getAccount(getEntityOwnerId())); diff --git a/api/src/com/cloud/api/commands/CreateStaticRouteCmd.java b/api/src/com/cloud/api/commands/CreateStaticRouteCmd.java index 4be141b3cd3..78c789fd247 100644 --- a/api/src/com/cloud/api/commands/CreateStaticRouteCmd.java +++ b/api/src/com/cloud/api/commands/CreateStaticRouteCmd.java @@ -29,7 +29,6 @@ import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.vpc.PrivateGateway; import com.cloud.network.vpc.StaticRoute; import com.cloud.network.vpc.VpcGateway; import com.cloud.user.UserContext; @@ -42,12 +41,12 @@ import com.cloud.user.UserContext; public class CreateStaticRouteCmd extends BaseAsyncCreateCmd{ private static final String s_name = "createstaticrouteresponse"; public static final Logger s_logger = Logger.getLogger(CreateStaticRouteCmd.class.getName()); - + @IdentityMapper(entityTableName="vpc_gateways") @Parameter(name=ApiConstants.GATEWAY_ID, type=CommandType.LONG, required=true, - description="the gateway id we are creating static route for") + description="the gateway id we are creating static route for") private Long gatewayId; - + @Parameter(name = ApiConstants.CIDR, required = true, type = CommandType.STRING, description = "static route cidr") private String cidr; @@ -115,7 +114,7 @@ public class CreateStaticRouteCmd extends BaseAsyncCreateCmd{ } } } - + @Override public String getCommandName() { return s_name; @@ -123,13 +122,13 @@ public class CreateStaticRouteCmd extends BaseAsyncCreateCmd{ @Override public long getEntityOwnerId() { - VpcGateway gateway = _vpcService.getVpcGateway(gatewayId); - if (gateway == null) { - throw new InvalidParameterValueException("Invalid gateway id is specified"); - } - return _vpcService.getVpc(gateway.getVpcId()).getAccountId(); + VpcGateway gateway = _vpcService.getVpcGateway(gatewayId); + if (gateway == null) { + throw new InvalidParameterValueException("Invalid gateway id is specified", null); + } + return _vpcService.getVpc(gateway.getVpcId()).getAccountId(); } - + @Override public String getSyncObjType() { return BaseAsyncCmd.vpcSyncObject; @@ -139,11 +138,11 @@ public class CreateStaticRouteCmd extends BaseAsyncCreateCmd{ public Long getSyncObjId() { VpcGateway gateway = _vpcService.getVpcGateway(gatewayId); if (gateway == null) { - throw new InvalidParameterValueException("Invalid id is specified for the gateway"); + throw new InvalidParameterValueException("Invalid id is specified for the gateway", null); } return gateway.getVpcId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.StaticRoute; diff --git a/api/src/com/cloud/api/commands/CreateTemplateCmd.java b/api/src/com/cloud/api/commands/CreateTemplateCmd.java index 10c8b6ac6b8..33683951253 100755 --- a/api/src/com/cloud/api/commands/CreateTemplateCmd.java +++ b/api/src/com/cloud/api/commands/CreateTemplateCmd.java @@ -41,7 +41,7 @@ import com.cloud.user.UserContext; @Implementation(responseObject = StoragePoolResponse.class, description = "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.") - public class CreateTemplateCmd extends BaseAsyncCreateCmd { +public class CreateTemplateCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(CreateTemplateCmd.class.getName()); private static final String s_name = "createtemplateresponse"; @@ -91,16 +91,17 @@ import com.cloud.user.UserContext; @Parameter(name=ApiConstants.TEMPLATE_TAG, type=CommandType.STRING, description="the tag for this template.") private String templateTag; - + @Parameter(name=ApiConstants.DETAILS, type=CommandType.MAP, description="Template details in key/value pairs.") protected Map details; // /////////////////////////////////////////////////// // ///////////////// Accessors /////////////////////// // /////////////////////////////////////////////////// - + + @Override public String getEntityTable() { - return "vm_template"; + return "vm_template"; } public Integer getBits() { @@ -154,17 +155,17 @@ import com.cloud.user.UserContext; public String getTemplateTag() { return templateTag; } - + public Map getDetails() { - if (details == null || details.isEmpty()) { - return null; - } - - Collection paramsCollection = details.values(); - Map params = (Map) (paramsCollection.toArray())[0]; - return params; + if (details == null || details.isEmpty()) { + return null; + } + + Collection paramsCollection = details.values(); + Map params = (Map) (paramsCollection.toArray())[0]; + return params; } - + // /////////////////////////////////////////////////// // ///////////// API Implementation/////////////////// // /////////////////////////////////////////////////// @@ -188,29 +189,29 @@ import com.cloud.user.UserContext; if (volume != null) { accountId = volume.getAccountId(); } else { - throw new InvalidParameterValueException("Unable to find volume by id=" + volumeId); + throw new InvalidParameterValueException("Unable to find volume by id=" + volumeId, null); } } else { Snapshot snapshot = _entityMgr.findById(Snapshot.class, snapshotId); if (snapshot != null) { accountId = snapshot.getAccountId(); } else { - throw new InvalidParameterValueException("Unable to find snapshot by id=" + snapshotId); + throw new InvalidParameterValueException("Unable to find snapshot by id=" + snapshotId, null); } } - + Account account = _accountService.getAccount(accountId); //Can create templates for enabled projects/accounts only if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - Project project = _projectService.findByProjectAccountId(accountId); + Project project = _projectService.findByProjectAccountId(accountId); if (project.getState() != Project.State.Active) { - PermissionDeniedException ex = new PermissionDeniedException("Can't add resources to the specified project id in state=" + project.getState() + " as it's no longer active"); + PermissionDeniedException ex = new PermissionDeniedException("Can't add resources to the specified project id in state=" + project.getState() + " as it's no longer active"); ex.addProxyObject(project, project.getId(), "projectId"); } } else if (account.getState() == Account.State.disabled) { throw new PermissionDeniedException("The owner of template is disabled: " + account); } - + return accountId; } @@ -246,7 +247,7 @@ import com.cloud.user.UserContext; this.setEntityId(template.getId()); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, - "Failed to create a template"); + "Failed to create a template"); } } } diff --git a/api/src/com/cloud/api/commands/CreateVpnConnectionCmd.java b/api/src/com/cloud/api/commands/CreateVpnConnectionCmd.java index 228b70b3d42..9ec62226280 100644 --- a/api/src/com/cloud/api/commands/CreateVpnConnectionCmd.java +++ b/api/src/com/cloud/api/commands/CreateVpnConnectionCmd.java @@ -30,7 +30,6 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.IpAddress; import com.cloud.network.Site2SiteVpnConnection; import com.cloud.user.Account; -import com.cloud.user.UserContext; @Implementation(description="Create site to site vpn connection", responseObject=Site2SiteVpnConnectionResponse.class) public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd { @@ -53,18 +52,19 @@ public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd { /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// + @Override public String getEntityTable() { - return "s2s_vpn_connection"; + return "s2s_vpn_connection"; } - + public Long getVpnGatewayId() { return vpnGatewayId; } - + public Long getCustomerGatewayId() { return customerGatewayId; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -75,21 +75,21 @@ public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd { return s_name; } - @Override - public long getEntityOwnerId() { + @Override + public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - @Override - public String getEventDescription() { - return "Create site-to-site VPN connection"; - } + @Override + public String getEventDescription() { + return "Create site-to-site VPN connection"; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_S2S_CONNECTION_CREATE; + } - @Override - public String getEventType() { - return EventTypes.EVENT_S2S_CONNECTION_CREATE; - } - @Override public void create() { try { @@ -122,8 +122,8 @@ public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd { throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.vpcSyncObject; @@ -137,7 +137,7 @@ public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd { private IpAddress getIp() { IpAddress ip = _s2sVpnService.getVpnGatewayIp(vpnGatewayId); if (ip == null) { - throw new InvalidParameterValueException("Unable to find ip address by vpn gateway id " + vpnGatewayId); + throw new InvalidParameterValueException("Unable to find ip address by vpn gateway id " + vpnGatewayId, null); } return ip; } diff --git a/api/src/com/cloud/api/commands/CreateVpnGatewayCmd.java b/api/src/com/cloud/api/commands/CreateVpnGatewayCmd.java index 050dbdaf2ff..defb60ac312 100644 --- a/api/src/com/cloud/api/commands/CreateVpnGatewayCmd.java +++ b/api/src/com/cloud/api/commands/CreateVpnGatewayCmd.java @@ -45,9 +45,9 @@ public class CreateVpnGatewayCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// public String getEntityTable() { - return "user_ip_address"; + return "user_ip_address"; } - + public Long getPublicIpId() { return publicIpId; } @@ -62,27 +62,27 @@ public class CreateVpnGatewayCmd extends BaseAsyncCmd { return s_name; } - @Override - public long getEntityOwnerId() { - IpAddress ip = _networkService.getIp(publicIpId); - - if (ip == null) { - throw new InvalidParameterValueException("Unable to find ip address by id=" + publicIpId); - } - - return ip.getAccountId(); + @Override + public long getEntityOwnerId() { + IpAddress ip = _networkService.getIp(publicIpId); + + if (ip == null) { + throw new InvalidParameterValueException("Unable to find ip address by id", null); + } + + return ip.getAccountId(); } - @Override - public String getEventDescription() { - return "Create site-to-site VPN gateway for account " + getEntityOwnerId() + " using public ip id=" + publicIpId; - } + @Override + public String getEventDescription() { + return "Create site-to-site VPN gateway for account " + getEntityOwnerId() + " using public ip id=" + publicIpId; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_S2S_VPN_GATEWAY_CREATE; + } - @Override - public String getEventType() { - return EventTypes.EVENT_S2S_VPN_GATEWAY_CREATE; - } - @Override public void execute(){ Site2SiteVpnGateway result = _s2sVpnService.createVpnGateway(this); @@ -94,7 +94,7 @@ public class CreateVpnGatewayCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create VPN gateway"); } } - + @Override public String getSyncObjType() { return BaseAsyncCmd.vpcSyncObject; @@ -108,7 +108,7 @@ public class CreateVpnGatewayCmd extends BaseAsyncCmd { private IpAddress getIp() { IpAddress ip = _networkService.getIp(publicIpId); if (ip == null) { - throw new InvalidParameterValueException("Unable to find ip address by id " + publicIpId); + throw new InvalidParameterValueException("Unable to find ip address by id", null); } return ip; } diff --git a/api/src/com/cloud/api/commands/DeleteAccountFromProjectCmd.java b/api/src/com/cloud/api/commands/DeleteAccountFromProjectCmd.java index 41bac89273a..395f7de12db 100644 --- a/api/src/com/cloud/api/commands/DeleteAccountFromProjectCmd.java +++ b/api/src/com/cloud/api/commands/DeleteAccountFromProjectCmd.java @@ -39,7 +39,7 @@ public class DeleteAccountFromProjectCmd extends BaseAsyncCmd { @IdentityMapper(entityTableName="projects") @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, required=true, description="id of the project to remove the account from") private Long projectId; - + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, required=true, description="name of the account to be removed from the project") private String accountName; @@ -48,7 +48,7 @@ public class DeleteAccountFromProjectCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// - + @Override public String getCommandName() { @@ -78,24 +78,24 @@ public class DeleteAccountFromProjectCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete account from the project"); } } - - + + @Override public long getEntityOwnerId() { Project project= _projectService.getProject(projectId); //verify input parameters if (project == null) { - throw new InvalidParameterValueException("Unable to find project by id " + projectId); + throw new InvalidParameterValueException("Unable to find project by id", null); } - + return _projectService.getProjectOwner(projectId).getId(); } - + @Override public String getEventType() { return EventTypes.EVENT_PROJECT_ACCOUNT_REMOVE; } - + @Override public String getEventDescription() { return "Removing account " + accountName + " from project: " + projectId; diff --git a/api/src/com/cloud/api/commands/DeleteFirewallRuleCmd.java b/api/src/com/cloud/api/commands/DeleteFirewallRuleCmd.java index 7d8f0e71174..9dc2bb3ccea 100644 --- a/api/src/com/cloud/api/commands/DeleteFirewallRuleCmd.java +++ b/api/src/com/cloud/api/commands/DeleteFirewallRuleCmd.java @@ -53,7 +53,7 @@ public class DeleteFirewallRuleCmd extends BaseAsyncCmd { public Long getId() { return id; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -61,7 +61,7 @@ public class DeleteFirewallRuleCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public String getEventType() { return EventTypes.EVENT_FIREWALL_CLOSE; @@ -71,25 +71,25 @@ public class DeleteFirewallRuleCmd extends BaseAsyncCmd { public String getEventDescription() { return ("Deleting firewall rule id=" + id); } - + @Override public long getEntityOwnerId() { if (ownerId == null) { FirewallRule rule = _entityMgr.findById(FirewallRule.class, id); if (rule == null) { - throw new InvalidParameterValueException("Unable to find firewall rule by id=" + id); + throw new InvalidParameterValueException("Unable to find firewall rule by id", null); } else { ownerId = _entityMgr.findById(FirewallRule.class, id).getAccountId(); } } return ownerId; } - + @Override public void execute() throws ResourceUnavailableException { UserContext.current().setEventDetails("Rule Id: " + id); boolean result = _firewallService.revokeFirewallRule(id, true); - + if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); @@ -97,8 +97,8 @@ public class DeleteFirewallRuleCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete firewall rule"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -108,7 +108,7 @@ public class DeleteFirewallRuleCmd extends BaseAsyncCmd { public Long getSyncObjId() { return _firewallService.getFirewallRule(id).getNetworkId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; diff --git a/api/src/com/cloud/api/commands/DeleteIpForwardingRuleCmd.java b/api/src/com/cloud/api/commands/DeleteIpForwardingRuleCmd.java index 98a4f226a8e..3914465bd8c 100644 --- a/api/src/com/cloud/api/commands/DeleteIpForwardingRuleCmd.java +++ b/api/src/com/cloud/api/commands/DeleteIpForwardingRuleCmd.java @@ -42,7 +42,7 @@ public class DeleteIpForwardingRuleCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the id of the forwarding rule") private Long id; - + // unexposed parameter needed for events logging @IdentityMapper(entityTableName="account") @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.LONG, expose=false) @@ -67,8 +67,8 @@ public class DeleteIpForwardingRuleCmd extends BaseAsyncCmd { @Override public void execute(){ UserContext.current().setEventDetails("Rule Id: "+id); - boolean result = _firewallService.revokeRelatedFirewallRule(id, true); - result = result && _rulesService.revokeStaticNatRule(id, true); + boolean result = _firewallService.revokeRelatedFirewallRule(id, true); + result = result && _rulesService.revokeStaticNatRule(id, true); if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); @@ -83,7 +83,7 @@ public class DeleteIpForwardingRuleCmd extends BaseAsyncCmd { if (ownerId == null) { FirewallRule rule = _entityMgr.findById(FirewallRule.class, id); if (rule == null) { - throw new InvalidParameterValueException("Unable to find static nat rule by id: " + id); + throw new InvalidParameterValueException("Unable to find static nat rule by id", null); } else { ownerId = rule.getAccountId(); } @@ -100,7 +100,7 @@ public class DeleteIpForwardingRuleCmd extends BaseAsyncCmd { public String getEventDescription() { return ("Deleting an ipforwarding 1:1 NAT rule id:"+id); } - + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -110,7 +110,7 @@ public class DeleteIpForwardingRuleCmd extends BaseAsyncCmd { public Long getSyncObjId() { return _rulesService.getFirewallRule(id).getNetworkId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; diff --git a/api/src/com/cloud/api/commands/DeleteLBStickinessPolicyCmd.java b/api/src/com/cloud/api/commands/DeleteLBStickinessPolicyCmd.java index b39c15dc3d7..a3e5c113219 100644 --- a/api/src/com/cloud/api/commands/DeleteLBStickinessPolicyCmd.java +++ b/api/src/com/cloud/api/commands/DeleteLBStickinessPolicyCmd.java @@ -24,8 +24,8 @@ import com.cloud.api.ServerApiException; import com.cloud.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; -import com.cloud.network.rules.StickinessPolicy; import com.cloud.network.rules.LoadBalancer; +import com.cloud.network.rules.StickinessPolicy; import com.cloud.user.Account; import com.cloud.user.UserContext; @@ -101,11 +101,11 @@ public class DeleteLBStickinessPolicyCmd extends BaseAsyncCmd { StickinessPolicy policy = _entityMgr.findById(StickinessPolicy.class, getId()); if (policy == null) { - throw new InvalidParameterValueException("Unable to find LB stickiness rule: " + id); + throw new InvalidParameterValueException("Unable to find LB stickiness rule by id", null); } LoadBalancer lb = _lbService.findById(policy.getLoadBalancerId()); if (lb == null) { - throw new InvalidParameterValueException("Unable to find load balancer rule for stickiness rule: " + id); + throw new InvalidParameterValueException("Unable to find load balancer rule for stickiness rule by id", null); } return lb.getNetworkId(); } diff --git a/api/src/com/cloud/api/commands/DeleteLoadBalancerRuleCmd.java b/api/src/com/cloud/api/commands/DeleteLoadBalancerRuleCmd.java index 050d7908fc7..7a180679ff5 100644 --- a/api/src/com/cloud/api/commands/DeleteLoadBalancerRuleCmd.java +++ b/api/src/com/cloud/api/commands/DeleteLoadBalancerRuleCmd.java @@ -78,13 +78,13 @@ public class DeleteLoadBalancerRuleCmd extends BaseAsyncCmd { public String getEventDescription() { return "deleting load balancer: " + getId(); } - + @Override public void execute(){ UserContext.current().setEventDetails("Load balancer Id: "+getId()); boolean result = _firewallService.revokeRelatedFirewallRule(id, true); result = result && _lbService.deleteLoadBalancerRule(id, true); - + if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); @@ -92,7 +92,7 @@ public class DeleteLoadBalancerRuleCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete load balancer"); } } - + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -100,13 +100,13 @@ public class DeleteLoadBalancerRuleCmd extends BaseAsyncCmd { @Override public Long getSyncObjId() { - LoadBalancer lb = _lbService.findById(id); - if(lb == null){ - throw new InvalidParameterValueException("Unable to find load balancer rule: " + id); - } + LoadBalancer lb = _lbService.findById(id); + if(lb == null){ + throw new InvalidParameterValueException("Unable to find load balancer rule by id", null); + } return lb.getNetworkId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; diff --git a/api/src/com/cloud/api/commands/DeleteNetworkACLCmd.java b/api/src/com/cloud/api/commands/DeleteNetworkACLCmd.java index 9c0846544dd..84dee72f412 100644 --- a/api/src/com/cloud/api/commands/DeleteNetworkACLCmd.java +++ b/api/src/com/cloud/api/commands/DeleteNetworkACLCmd.java @@ -56,7 +56,7 @@ public class DeleteNetworkACLCmd extends BaseAsyncCmd { public Long getId() { return id; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -64,7 +64,7 @@ public class DeleteNetworkACLCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public String getEventType() { return EventTypes.EVENT_FIREWALL_CLOSE; @@ -74,25 +74,25 @@ public class DeleteNetworkACLCmd extends BaseAsyncCmd { public String getEventDescription() { return ("Deleting Network ACL id=" + id); } - + @Override public long getEntityOwnerId() { if (ownerId == null) { FirewallRule rule = _networkACLService.getNetworkACL(id); if (rule == null) { - throw new InvalidParameterValueException("Unable to find network ACL by id=" + id); + throw new InvalidParameterValueException("Unable to find network ACL by id", null); } else { ownerId = rule.getAccountId(); } } return ownerId; } - + @Override public void execute() throws ResourceUnavailableException { UserContext.current().setEventDetails("Network ACL Id: " + id); boolean result = _networkACLService.revokeNetworkACL(id, true); - + if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); @@ -100,8 +100,8 @@ public class DeleteNetworkACLCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete network ACL"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -111,7 +111,7 @@ public class DeleteNetworkACLCmd extends BaseAsyncCmd { public Long getSyncObjId() { return _firewallService.getFirewallRule(id).getNetworkId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; diff --git a/api/src/com/cloud/api/commands/DeleteNetworkCmd.java b/api/src/com/cloud/api/commands/DeleteNetworkCmd.java index 63ad1f996ec..90e240e9db2 100644 --- a/api/src/com/cloud/api/commands/DeleteNetworkCmd.java +++ b/api/src/com/cloud/api/commands/DeleteNetworkCmd.java @@ -58,7 +58,7 @@ public class DeleteNetworkCmd extends BaseAsyncCmd{ public String getCommandName() { return s_name; } - + @Override public void execute(){ UserContext.current().setEventDetails("Network Id: " + id); @@ -70,8 +70,8 @@ public class DeleteNetworkCmd extends BaseAsyncCmd{ throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete network"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -81,22 +81,22 @@ public class DeleteNetworkCmd extends BaseAsyncCmd{ public Long getSyncObjId() { return id; } - + @Override public String getEventType() { return EventTypes.EVENT_NETWORK_DELETE; } - + @Override public String getEventDescription() { return "Deleting network: " + id; } - + @Override public long getEntityOwnerId() { Network network = _networkService.getNetwork(id); if (network == null) { - throw new InvalidParameterValueException("Networkd id=" + id + " doesn't exist"); + throw new InvalidParameterValueException("Couldn't find network by id", null); } else { return _networkService.getNetwork(id).getAccountId(); } diff --git a/api/src/com/cloud/api/commands/DeletePortForwardingRuleCmd.java b/api/src/com/cloud/api/commands/DeletePortForwardingRuleCmd.java index a9e9d6fb4d5..ad87908da89 100644 --- a/api/src/com/cloud/api/commands/DeletePortForwardingRuleCmd.java +++ b/api/src/com/cloud/api/commands/DeletePortForwardingRuleCmd.java @@ -52,7 +52,7 @@ public class DeletePortForwardingRuleCmd extends BaseAsyncCmd { public Long getId() { return id; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -60,7 +60,7 @@ public class DeletePortForwardingRuleCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public String getEventType() { return EventTypes.EVENT_NET_RULE_DELETE; @@ -70,28 +70,28 @@ public class DeletePortForwardingRuleCmd extends BaseAsyncCmd { public String getEventDescription() { return ("Deleting port forwarding rule for id=" + id); } - + @Override public long getEntityOwnerId() { if (ownerId == null) { PortForwardingRule rule = _entityMgr.findById(PortForwardingRule.class, id); if (rule == null) { - throw new InvalidParameterValueException("Unable to find port forwarding rule by id=" + id); + throw new InvalidParameterValueException("Unable to find port forwarding rule by id", null); } else { ownerId = _entityMgr.findById(PortForwardingRule.class, id).getAccountId(); } - + } return ownerId; } - + @Override public void execute(){ UserContext.current().setEventDetails("Rule Id: "+id); //revoke corresponding firewall rule first boolean result = _firewallService.revokeRelatedFirewallRule(id, true); result = result && _rulesService.revokePortForwardingRule(id, true); - + if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); @@ -99,8 +99,8 @@ public class DeletePortForwardingRuleCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete port forwarding rule"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -110,7 +110,7 @@ public class DeletePortForwardingRuleCmd extends BaseAsyncCmd { public Long getSyncObjId() { return _rulesService.getPortForwardigRule(id).getNetworkId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; diff --git a/api/src/com/cloud/api/commands/DeletePrivateGatewayCmd.java b/api/src/com/cloud/api/commands/DeletePrivateGatewayCmd.java index 83714582b1d..87a009652b6 100644 --- a/api/src/com/cloud/api/commands/DeletePrivateGatewayCmd.java +++ b/api/src/com/cloud/api/commands/DeletePrivateGatewayCmd.java @@ -54,7 +54,7 @@ public class DeletePrivateGatewayCmd extends BaseAsyncCmd { public Long getId() { return id; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -62,7 +62,7 @@ public class DeletePrivateGatewayCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public String getEventType() { return EventTypes.EVENT_PRIVATE_GATEWAY_DELETE; @@ -72,12 +72,12 @@ public class DeletePrivateGatewayCmd extends BaseAsyncCmd { public String getEventDescription() { return ("Deleting private gateway id=" + id); } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute() throws ResourceUnavailableException, ConcurrentOperationException { UserContext.current().setEventDetails("Network ACL Id: " + id); @@ -89,8 +89,8 @@ public class DeletePrivateGatewayCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete private gateway"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.vpcSyncObject; @@ -100,14 +100,14 @@ public class DeletePrivateGatewayCmd extends BaseAsyncCmd { public Long getSyncObjId() { VpcGateway gateway = _vpcService.getVpcPrivateGateway(getId()); if (gateway == null) { - throw new InvalidParameterValueException("Invalid private gateway id"); + throw new InvalidParameterValueException("Invalid private gateway id", null); } return gateway.getVpcId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.PrivateGateway; } - + } \ No newline at end of file diff --git a/api/src/com/cloud/api/commands/DeleteProjectCmd.java b/api/src/com/cloud/api/commands/DeleteProjectCmd.java index dc2505a0b80..cd892f65490 100644 --- a/api/src/com/cloud/api/commands/DeleteProjectCmd.java +++ b/api/src/com/cloud/api/commands/DeleteProjectCmd.java @@ -70,26 +70,26 @@ public class DeleteProjectCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete project"); } } - + @Override public String getEventType() { return EventTypes.EVENT_PROJECT_DELETE; } - + @Override public String getEventDescription() { return "Deleting project: " + id; } - + @Override public long getEntityOwnerId() { Project project= _projectService.getProject(id); //verify input parameters if (project == null) { - throw new InvalidParameterValueException("Unable to find project by id " + id); + throw new InvalidParameterValueException("Unable to find project by id", null); } - + return _projectService.getProjectOwner(id).getId(); } - + } \ No newline at end of file diff --git a/api/src/com/cloud/api/commands/DeleteRemoteAccessVpnCmd.java b/api/src/com/cloud/api/commands/DeleteRemoteAccessVpnCmd.java index dae85b488af..471d376d2e0 100644 --- a/api/src/com/cloud/api/commands/DeleteRemoteAccessVpnCmd.java +++ b/api/src/com/cloud/api/commands/DeleteRemoteAccessVpnCmd.java @@ -37,7 +37,7 @@ public class DeleteRemoteAccessVpnCmd extends BaseAsyncCmd { @IdentityMapper(entityTableName="user_ip_address") @Parameter(name=ApiConstants.PUBLIC_IP_ID, type=CommandType.LONG, required=true, description="public ip address id of the vpn server") private Long publicIpId; - + // unexposed parameter needed for events logging @IdentityMapper(entityTableName="account") @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.LONG, expose=false) @@ -45,43 +45,43 @@ public class DeleteRemoteAccessVpnCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - @Override + @Override public String getCommandName() { return s_name; } - @Override - public long getEntityOwnerId() { - if (ownerId == null) { - RemoteAccessVpn vpnEntity = _entityMgr.findById(RemoteAccessVpn.class, publicIpId); - if(vpnEntity != null) - return vpnEntity.getAccountId(); - - throw new InvalidParameterValueException("The specified public ip is not allocated to any account"); - } - return ownerId; + @Override + public long getEntityOwnerId() { + if (ownerId == null) { + RemoteAccessVpn vpnEntity = _entityMgr.findById(RemoteAccessVpn.class, publicIpId); + if(vpnEntity != null) + return vpnEntity.getAccountId(); + + throw new InvalidParameterValueException("The specified public ip is not allocated to any account", null); + } + return ownerId; } - @Override - public String getEventDescription() { - return "Delete Remote Access VPN for account " + getEntityOwnerId() + " for ip id=" + publicIpId; - } + @Override + public String getEventDescription() { + return "Delete Remote Access VPN for account " + getEntityOwnerId() + " for ip id=" + publicIpId; + } - @Override - public String getEventType() { - return EventTypes.EVENT_REMOTE_ACCESS_VPN_DESTROY; - } + @Override + public String getEventType() { + return EventTypes.EVENT_REMOTE_ACCESS_VPN_DESTROY; + } @Override public void execute() throws ResourceUnavailableException { _ravService.destroyRemoteAccessVpn(publicIpId); } - + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -91,5 +91,5 @@ public class DeleteRemoteAccessVpnCmd extends BaseAsyncCmd { public Long getSyncObjId() { return _ravService.getRemoteAccessVpn(publicIpId).getNetworkId(); } - + } diff --git a/api/src/com/cloud/api/commands/DeleteSecurityGroupCmd.java b/api/src/com/cloud/api/commands/DeleteSecurityGroupCmd.java index 3ffd1dc6fd7..9ee743021c8 100644 --- a/api/src/com/cloud/api/commands/DeleteSecurityGroupCmd.java +++ b/api/src/com/cloud/api/commands/DeleteSecurityGroupCmd.java @@ -12,18 +12,18 @@ // Automatically generated by addcopyright.py at 04/03/2012 package com.cloud.api.commands; -import org.apache.log4j.Logger; - -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceInUseException; -import com.cloud.user.UserContext; +import org.apache.log4j.Logger; + +import com.cloud.api.ApiConstants; +import com.cloud.api.BaseCmd; +import com.cloud.api.IdentityMapper; +import com.cloud.api.Implementation; +import com.cloud.api.Parameter; +import com.cloud.api.ServerApiException; +import com.cloud.api.response.SuccessResponse; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.exception.ResourceInUseException; +import com.cloud.user.UserContext; @Implementation(description="Deletes security group", responseObject=SuccessResponse.class) public class DeleteSecurityGroupCmd extends BaseCmd { @@ -40,7 +40,7 @@ public class DeleteSecurityGroupCmd extends BaseCmd { @IdentityMapper(entityTableName="domain") @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the domain ID of account owning the security group") private Long domainId; - + @IdentityMapper(entityTableName="projects") @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="the project of the security group") private Long projectId; @@ -48,7 +48,7 @@ public class DeleteSecurityGroupCmd extends BaseCmd { @IdentityMapper(entityTableName="security_group") @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="The ID of the security group. Mutually exclusive with name parameter") private Long id; - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="The ID of the security group. Mutually exclusive with id parameter") private String name; @@ -64,27 +64,27 @@ public class DeleteSecurityGroupCmd extends BaseCmd { public Long getDomainId() { return domainId; } - + public Long getProjectId() { return projectId; } public Long getId() { if (id != null && name != null) { - throw new InvalidParameterValueException("name and id parameters are mutually exclusive"); + throw new InvalidParameterValueException("name and id parameters are mutually exclusive", null); } - + if (name != null) { id = _responseGenerator.getSecurityGroupId(name, getEntityOwnerId()); if (id == null) { - throw new InvalidParameterValueException("Unable to find security group by name " + name + " for the account id=" + getEntityOwnerId()); + throw new InvalidParameterValueException("Unable to find security group by name " + name + " for the account id=" + getEntityOwnerId(), null); } } - + if (id == null) { - throw new InvalidParameterValueException("Either id or name parameter is requred by deleteSecurityGroup command"); + throw new InvalidParameterValueException("Either id or name parameter is requred by deleteSecurityGroup command", null); } - + return id; } @@ -98,17 +98,17 @@ public class DeleteSecurityGroupCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Long accountId = finalyzeAccountId(accountName, domainId, projectId, true); if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; } - + @Override public void execute(){ try{ diff --git a/api/src/com/cloud/api/commands/DeleteStaticRouteCmd.java b/api/src/com/cloud/api/commands/DeleteStaticRouteCmd.java index a6fc85b798b..ae95d2ca4d3 100644 --- a/api/src/com/cloud/api/commands/DeleteStaticRouteCmd.java +++ b/api/src/com/cloud/api/commands/DeleteStaticRouteCmd.java @@ -57,7 +57,7 @@ public class DeleteStaticRouteCmd extends BaseAsyncCmd{ public Long getId() { return id; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -65,7 +65,7 @@ public class DeleteStaticRouteCmd extends BaseAsyncCmd{ public String getCommandName() { return s_name; } - + @Override public String getEventType() { return EventTypes.EVENT_STATIC_ROUTE_DELETE; @@ -75,25 +75,25 @@ public class DeleteStaticRouteCmd extends BaseAsyncCmd{ public String getEventDescription() { return ("Deleting static route id=" + id); } - + @Override public long getEntityOwnerId() { if (ownerId == null) { StaticRoute route = _entityMgr.findById(StaticRoute.class, id); if (route == null) { - throw new InvalidParameterValueException("Unable to find static route by id=" + id); + throw new InvalidParameterValueException("Unable to find static route by id", null); } else { ownerId = route.getAccountId(); } } return ownerId; } - + @Override public void execute() throws ResourceUnavailableException { UserContext.current().setEventDetails("Route Id: " + id); boolean result = _vpcService.revokeStaticRoute(id); - + if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); @@ -101,8 +101,8 @@ public class DeleteStaticRouteCmd extends BaseAsyncCmd{ throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete static route"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.vpcSyncObject; @@ -112,11 +112,11 @@ public class DeleteStaticRouteCmd extends BaseAsyncCmd{ public Long getSyncObjId() { StaticRoute route = _vpcService.getStaticRoute(id); if (route == null) { - throw new InvalidParameterValueException("Invalid id is specified for the static route"); + throw new InvalidParameterValueException("Invalid id is specified for the static route", null); } return route.getVpcId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.StaticRoute; diff --git a/api/src/com/cloud/api/commands/DeployVMCmd.java b/api/src/com/cloud/api/commands/DeployVMCmd.java index a88449c7909..29eb9063b89 100644 --- a/api/src/com/cloud/api/commands/DeployVMCmd.java +++ b/api/src/com/cloud/api/commands/DeployVMCmd.java @@ -111,39 +111,40 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { @IdentityMapper(entityTableName="host") @Parameter(name=ApiConstants.HOST_ID, type=CommandType.LONG, description="destination Host ID to deploy the VM to - parameter available for root admin only") private Long hostId; - + @IdentityMapper(entityTableName="security_group") @Parameter(name=ApiConstants.SECURITY_GROUP_IDS, type=CommandType.LIST, collectionType=CommandType.LONG, description="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") private List securityGroupIdList; - + @Parameter(name=ApiConstants.SECURITY_GROUP_NAMES, type=CommandType.LIST, collectionType=CommandType.STRING, description="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") private List securityGroupNameList; - + @Parameter(name = ApiConstants.IP_NETWORK_LIST, type = CommandType.MAP, description = "ip to network mapping. Can't be specified with networkIds parameter. Example: iptonetworklist[0].ip=10.10.10.11&iptonetworklist[0].networkid=204 - requests to use ip 10.10.10.11 in network id=204") private Map ipToNetworkList; - + @Parameter(name=ApiConstants.IP_ADDRESS, type=CommandType.STRING, description="the ip address for default vm's network") private String ipAddress; - + @Parameter(name=ApiConstants.KEYBOARD, type=CommandType.STRING, description="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") private String keyboard; - + @IdentityMapper(entityTableName="projects") @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="Deploy vm for the project") private Long projectId; - + @Parameter(name=ApiConstants.START_VM, type=CommandType.BOOLEAN, description="true if network offering supports specifying ip ranges; defaulted to true if not specified") private Boolean startVm; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// + @Override public String getEntityTable() { - return "vm_instance"; + return "vm_instance"; } - + public String getAccountName() { if (accountName == null) { return UserContext.current().getCaller().getAccountName(); @@ -176,16 +177,16 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { public List getSecurityGroupIdList() { if (securityGroupNameList != null && securityGroupIdList != null) { - throw new InvalidParameterValueException("securitygroupids parameter is mutually exclusive with securitygroupnames parameter"); + throw new InvalidParameterValueException("securitygroupids parameter is mutually exclusive with securitygroupnames parameter", null); } - - //transform group names to ids here - if (securityGroupNameList != null) { + + //transform group names to ids here + if (securityGroupNameList != null) { List securityGroupIds = new ArrayList(); for (String groupName : securityGroupNameList) { Long groupId = _responseGenerator.getSecurityGroupId(groupName, getEntityOwnerId()); if (groupId == null) { - throw new InvalidParameterValueException("Unable to find group by name " + groupName + " for account " + getEntityOwnerId()); + throw new InvalidParameterValueException("Unable to find group by name " + groupName + " for account " + getEntityOwnerId(), null); } else { securityGroupIds.add(groupId); } @@ -217,15 +218,15 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { } public List getNetworkIds() { - if (ipToNetworkList != null) { - if (networkIds != null || ipAddress != null) { - throw new InvalidParameterValueException("ipToNetworkMap can't be specified along with networkIds or ipAddress"); - } else { - List networks = new ArrayList(); - networks.addAll(getIpToNetworkMap().keySet()); - return networks; - } - } + if (ipToNetworkList != null) { + if (networkIds != null || ipAddress != null) { + throw new InvalidParameterValueException("ipToNetworkMap can't be specified along with networkIds or ipAddress", null); + } else { + List networks = new ArrayList(); + networks.addAll(getIpToNetworkMap().keySet()); + return networks; + } + } return networkIds; } @@ -240,14 +241,14 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { public Long getHostId() { return hostId; } - + public boolean getStartVm() { return startVm == null ? true : startVm; } - + private Map getIpToNetworkMap() { if ((networkIds != null || ipAddress != null) && ipToNetworkList != null) { - throw new InvalidParameterValueException("NetworkIds and ipAddress can't be specified along with ipToNetworkMap parameter"); + throw new InvalidParameterValueException("NetworkIds and ipAddress can't be specified along with ipToNetworkMap parameter", null); } Map ipToNetworkMap = null; if (ipToNetworkList != null && !ipToNetworkList.isEmpty()) { @@ -257,11 +258,11 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { while (iter.hasNext()) { HashMap ips = (HashMap) iter.next(); Long networkId = Long.valueOf(_responseGenerator.getIdentiyId("networks", ips.get("networkid"))); - String requestedIp = (String) ips.get("ip"); + String requestedIp = ips.get("ip"); ipToNetworkMap.put(networkId, requestedIp); } } - + return ipToNetworkMap; } @@ -284,7 +285,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; } @@ -316,7 +317,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { @Override public void execute(){ UserVm result; - + if (getStartVm()) { try { UserContext.current().setEventDetails("Vm Id: "+getEntityId()); @@ -339,7 +340,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { } else { result = _userVmService.getUserVm(getEntityId()); } - + if (result != null) { UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", result).get(0); response.setResponseName(getCommandName()); @@ -357,24 +358,24 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { DataCenter zone = _configService.getZone(zoneId); if (zone == null) { - throw new InvalidParameterValueException("Unable to find zone by id=" + zoneId); + throw new InvalidParameterValueException("Unable to find zone by id", null); } ServiceOffering serviceOffering = _configService.getServiceOffering(serviceOfferingId); if (serviceOffering == null) { - throw new InvalidParameterValueException("Unable to find service offering: " + serviceOfferingId); + throw new InvalidParameterValueException("Unable to find service offering by id", null); } VirtualMachineTemplate template = _templateService.getTemplate(templateId); // Make sure a valid template ID was specified if (template == null) { - throw new InvalidParameterValueException("Unable to use template " + templateId); + throw new InvalidParameterValueException("Unable to use template " + templateId, null); } - + if (diskOfferingId != null) { DiskOffering diskOffering = _configService.getDiskOffering(diskOfferingId); if (diskOffering == null) { - throw new InvalidParameterValueException("Unable to find disk offering " + diskOfferingId); + throw new InvalidParameterValueException("Unable to find disk offering by id", null); } } @@ -384,7 +385,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { } else { if (zone.getNetworkType() == NetworkType.Basic) { if (getNetworkIds() != null) { - throw new InvalidParameterValueException("Can't specify network Ids in Basic zone"); + throw new InvalidParameterValueException("Can't specify network Ids in Basic zone", null); } else { vm = _userVmService.createBasicSecurityGroupVirtualMachine(zone, serviceOffering, template, getSecurityGroupIdList(), owner, name, displayName, diskOfferingId, size, group, getHypervisor(), userData, sshKeyPairName, getIpToNetworkMap(), ipAddress, keyboard); @@ -395,7 +396,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { owner, name, displayName, diskOfferingId, size, group, getHypervisor(), userData, sshKeyPairName, getIpToNetworkMap(), ipAddress, keyboard); } else { if (getSecurityGroupIdList() != null && !getSecurityGroupIdList().isEmpty()) { - throw new InvalidParameterValueException("Can't create vm with security groups; security group feature is not enabled per zone"); + throw new InvalidParameterValueException("Can't create vm with security groups; security group feature is not enabled per zone", null); } vm = _userVmService.createAdvancedVirtualMachine(zone, serviceOffering, template, getNetworkIds(), owner, name, displayName, diskOfferingId, size, group, getHypervisor(), userData, sshKeyPairName, getIpToNetworkMap(), ipAddress, keyboard); diff --git a/api/src/com/cloud/api/commands/DetachIsoCmd.java b/api/src/com/cloud/api/commands/DetachIsoCmd.java index 68d3e9123b7..70d68c1f79d 100755 --- a/api/src/com/cloud/api/commands/DetachIsoCmd.java +++ b/api/src/com/cloud/api/commands/DetachIsoCmd.java @@ -63,7 +63,7 @@ public class DetachIsoCmd extends BaseAsyncCmd { if (vm != null) { return vm.getAccountId(); } else { - throw new InvalidParameterValueException("Unable to find vm by id " + getVirtualMachineId()); + throw new InvalidParameterValueException("Unable to find vm by id", null); } } @@ -76,7 +76,7 @@ public class DetachIsoCmd extends BaseAsyncCmd { public String getEventDescription() { return "detaching ISO from vm: " + getVirtualMachineId(); } - + @Override public void execute(){ boolean result = _templateService.detachIso(virtualMachineId); diff --git a/api/src/com/cloud/api/commands/DisableStaticNatCmd.java b/api/src/com/cloud/api/commands/DisableStaticNatCmd.java index 020e1214ad2..9291e229044 100644 --- a/api/src/com/cloud/api/commands/DisableStaticNatCmd.java +++ b/api/src/com/cloud/api/commands/DisableStaticNatCmd.java @@ -41,7 +41,7 @@ public class DisableStaticNatCmd extends BaseAsyncCmd { @IdentityMapper(entityTableName="user_ip_address") @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.LONG, required=true, description="the public IP address id for which static nat feature is being disableed") private Long ipAddressId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -49,7 +49,7 @@ public class DisableStaticNatCmd extends BaseAsyncCmd { public Long getIpAddress() { return ipAddressId; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -57,7 +57,7 @@ public class DisableStaticNatCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public String getEventType() { return EventTypes.EVENT_DISABLE_STATIC_NAT; @@ -67,16 +67,16 @@ public class DisableStaticNatCmd extends BaseAsyncCmd { public String getEventDescription() { return ("Disabling static nat for ip id=" + ipAddressId); } - + @Override public long getEntityOwnerId() { return _entityMgr.findById(IpAddress.class, ipAddressId).getAccountId(); } - + @Override public void execute() throws ResourceUnavailableException, NetworkRuleConflictException, InsufficientAddressCapacityException { boolean result = _rulesService.disableStaticNat(ipAddressId); - + if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); @@ -84,8 +84,8 @@ public class DisableStaticNatCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to disable static nat"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -99,7 +99,7 @@ public class DisableStaticNatCmd extends BaseAsyncCmd { private IpAddress getIp() { IpAddress ip = _networkService.getIp(ipAddressId); if (ip == null) { - throw new InvalidParameterValueException("Unable to find ip address by id " + ipAddressId); + throw new InvalidParameterValueException("Unable to find ip address by id", null); } return ip; } diff --git a/api/src/com/cloud/api/commands/DisassociateIPAddrCmd.java b/api/src/com/cloud/api/commands/DisassociateIPAddrCmd.java index ea19ea319c6..cfa31810ef3 100644 --- a/api/src/com/cloud/api/commands/DisassociateIPAddrCmd.java +++ b/api/src/com/cloud/api/commands/DisassociateIPAddrCmd.java @@ -42,7 +42,7 @@ public class DisassociateIPAddrCmd extends BaseAsyncCmd { @IdentityMapper(entityTableName="user_ip_address") @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the id of the public ip address" + - " to disassociate") + " to disassociate") private Long id; // unexposed parameter needed for events logging @@ -77,7 +77,7 @@ public class DisassociateIPAddrCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to disassociate ip address"); } } - + @Override public String getEventType() { return EventTypes.EVENT_NET_IP_RELEASE; @@ -87,23 +87,23 @@ public class DisassociateIPAddrCmd extends BaseAsyncCmd { public String getEventDescription() { return ("Disassociating ip address with id=" + id); } - + @Override public long getEntityOwnerId() { if (ownerId == null) { IpAddress ip = getIpAddress(id); if (ip == null) { - throw new InvalidParameterValueException("Unable to find ip address by id=" + id); + throw new InvalidParameterValueException("Unable to find ip address by id", null); } ownerId = ip.getAccountId(); } - + if (ownerId == null) { return Account.ACCOUNT_ID_SYSTEM; } return ownerId; } - + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -114,22 +114,22 @@ public class DisassociateIPAddrCmd extends BaseAsyncCmd { IpAddress ip = getIpAddress(id); return ip.getAssociatedWithNetworkId(); } - + private IpAddress getIpAddress(long id) { IpAddress ip = _entityMgr.findById(IpAddress.class, id); - + if (ip == null) { - throw new InvalidParameterValueException("Unable to find ip address by id=" + id); + throw new InvalidParameterValueException("Unable to find ip address by id", null); } else { return ip; } } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.IpAddress; } - + @Override public Long getInstanceId() { return getIpAddressId(); diff --git a/api/src/com/cloud/api/commands/EnableStaticNatCmd.java b/api/src/com/cloud/api/commands/EnableStaticNatCmd.java index a8cd131f1c2..5b269fb7321 100644 --- a/api/src/com/cloud/api/commands/EnableStaticNatCmd.java +++ b/api/src/com/cloud/api/commands/EnableStaticNatCmd.java @@ -40,18 +40,18 @@ public class EnableStaticNatCmd extends BaseCmd{ @IdentityMapper(entityTableName="user_ip_address") @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.LONG, required=true, description="the public IP " + - "address id for which static nat feature is being enabled") + "address id for which static nat feature is being enabled") private Long ipAddressId; @IdentityMapper(entityTableName="vm_instance") @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, required=true, description="the ID of " + - "the virtual machine for enabling static nat feature") + "the virtual machine for enabling static nat feature") private Long virtualMachineId; @IdentityMapper(entityTableName="networks") @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, - description="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)") + description="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)") private Long networkId; ///////////////////////////////////////////////////// @@ -69,7 +69,7 @@ public class EnableStaticNatCmd extends BaseCmd{ public long getNetworkId() { IpAddress ip = _entityMgr.findById(IpAddress.class, getIpAddressId()); Long ntwkId = null; - + if (ip.getAssociatedWithNetworkId() != null) { ntwkId = ip.getAssociatedWithNetworkId(); } else { @@ -77,7 +77,7 @@ public class EnableStaticNatCmd extends BaseCmd{ } if (ntwkId == null) { throw new InvalidParameterValueException("Unable to enable static nat for the ipAddress id=" + ipAddressId + - " as ip is not associated with any network and no networkId is passed in"); + " as ip is not associated with any network and no networkId is passed in", null); } return ntwkId; } @@ -90,7 +90,7 @@ public class EnableStaticNatCmd extends BaseCmd{ public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { UserVm userVm = _entityMgr.findById(UserVm.class, getVirtualMachineId()); diff --git a/api/src/com/cloud/api/commands/ListCapacityCmd.java b/api/src/com/cloud/api/commands/ListCapacityCmd.java index 61a859d9128..63ddeab8303 100755 --- a/api/src/com/cloud/api/commands/ListCapacityCmd.java +++ b/api/src/com/cloud/api/commands/ListCapacityCmd.java @@ -38,7 +38,7 @@ public class ListCapacityCmd extends BaseListCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + @IdentityMapper(entityTableName="data_center") @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="lists capacity by the Zone ID") private Long zoneId; @@ -46,28 +46,28 @@ public class ListCapacityCmd extends BaseListCmd { @IdentityMapper(entityTableName="host_pod_ref") @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, description="lists capacity by the Pod ID") private Long podId; - + @IdentityMapper(entityTableName="cluster") @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.LONG, since="3.0.0", description="lists capacity by the Cluster ID") private Long clusterId; @Parameter(name=ApiConstants.FETCH_LATEST, type=CommandType.BOOLEAN, since="3.0.0", description="recalculate capacities and fetch the latest") private Boolean fetchLatest; - + @Parameter(name=ApiConstants.TYPE, type=CommandType.INTEGER, description="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.") + "* 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.") private Integer type; - + @Parameter(name=ApiConstants.SORT_BY, type=CommandType.STRING, since="3.0.0", description="Sort the results. Available values: Usage") private String sortBy; @@ -78,32 +78,32 @@ public class ListCapacityCmd extends BaseListCmd { public Long getZoneId() { return zoneId; } - + public Long getPodId() { return podId; } public Long getClusterId() { - return clusterId; - } + return clusterId; + } - public Boolean getFetchLatest() { - return fetchLatest; - } + public Boolean getFetchLatest() { + return fetchLatest; + } - public Integer getType() { + public Integer getType() { return type; } - + public String getSortBy() { if (sortBy != null) { if (sortBy.equalsIgnoreCase("usage")) { return sortBy; } else { - throw new InvalidParameterValueException("Only value supported for sortBy parameter is : usage"); + throw new InvalidParameterValueException("Only value supported for sortBy parameter is : usage", null); } } - + return null; } @@ -115,7 +115,7 @@ public class ListCapacityCmd extends BaseListCmd { public String getCommandName() { return s_name; } - + @Override public void execute(){ List result = null; @@ -124,7 +124,7 @@ public class ListCapacityCmd extends BaseListCmd { } else { result = _mgr.listCapacities(this); } - + ListResponse response = new ListResponse(); List capacityResponses = _responseGenerator.createCapacityResponse(result, s_percentFormat); response.setResponses(capacityResponses); diff --git a/api/src/com/cloud/api/commands/ListHostsCmd.java b/api/src/com/cloud/api/commands/ListHostsCmd.java index a9d272ddddd..027585e7728 100755 --- a/api/src/com/cloud/api/commands/ListHostsCmd.java +++ b/api/src/com/cloud/api/commands/ListHostsCmd.java @@ -69,16 +69,16 @@ public class ListHostsCmd extends BaseListCmd { @IdentityMapper(entityTableName="vm_instance") @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, required=false, description="lists hosts in the same cluster as this VM and flag hosts with enough CPU/RAm to host this VM") private Long virtualMachineId; - + @Parameter(name=ApiConstants.RESOURCE_STATE, type=CommandType.STRING, description="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]") private String resourceState; - + @Parameter(name=ApiConstants.DETAILS, type=CommandType.LIST, collectionType=CommandType.STRING, description="comma separated list of host details requested, value can be a list of [ min, all, capacity, events, stats]" ) private List viewDetails; - + @Parameter(name=ApiConstants.HA_HOST, type=CommandType.BOOLEAN, description="if true, list only hosts dedicated to HA") private Boolean haHost; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -106,7 +106,7 @@ public class ListHostsCmd extends BaseListCmd { public String getType() { return type; } - + public Boolean getHaHost() { return haHost; } @@ -118,7 +118,7 @@ public class ListHostsCmd extends BaseListCmd { public Long getVirtualMachineId() { return virtualMachineId; } - + public EnumSet getDetails() throws InvalidParameterValueException { EnumSet dv; if (viewDetails==null || viewDetails.size() <=0){ @@ -133,14 +133,14 @@ public class ListHostsCmd extends BaseListCmd { dv = EnumSet.copyOf(dc); } catch (IllegalArgumentException e){ - throw new InvalidParameterValueException("The details parameter contains a non permitted value. The allowed values are " + EnumSet.allOf(HostDetails.class)); + throw new InvalidParameterValueException("The details parameter contains a non permitted value. The allowed values are " + EnumSet.allOf(HostDetails.class), null); } } return dv; } - + public String getResourceState() { - return resourceState; + return resourceState; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -150,23 +150,24 @@ public class ListHostsCmd extends BaseListCmd { public String getCommandName() { return s_name; } - + + @Override public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Host; + return AsyncJob.Type.Host; } @Override public void execute(){ - List result = new ArrayList(); - List hostsWithCapacity = new ArrayList(); - - if(getVirtualMachineId() != null){ + List result = new ArrayList(); + List hostsWithCapacity = new ArrayList(); + + if(getVirtualMachineId() != null){ Pair, List> hostsForMigration = _mgr.listHostsForMigrationOfVM(getVirtualMachineId(), this.getStartIndex(), this.getPageSizeVal()); result = hostsForMigration.first(); hostsWithCapacity = hostsForMigration.second(); - }else{ - result = _mgr.searchForServers(this); - } + }else{ + result = _mgr.searchForServers(this); + } ListResponse response = new ListResponse(); List hostResponses = new ArrayList(); diff --git a/api/src/com/cloud/api/commands/ListSupportedNetworkServicesCmd.java b/api/src/com/cloud/api/commands/ListSupportedNetworkServicesCmd.java index fe74691aad4..22b1c202193 100644 --- a/api/src/com/cloud/api/commands/ListSupportedNetworkServicesCmd.java +++ b/api/src/com/cloud/api/commands/ListSupportedNetworkServicesCmd.java @@ -33,21 +33,21 @@ import com.cloud.user.Account; public class ListSupportedNetworkServicesCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListSupportedNetworkServicesCmd.class.getName()); private static final String _name = "listsupportednetworkservicesresponse"; - + @Parameter(name=ApiConstants.PROVIDER, type=CommandType.STRING, description="network service provider name") private String providerName; - + @Parameter(name=ApiConstants.SERVICE, type=CommandType.STRING, description="network service name to list providers and capabilities of") private String serviceName; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public void setProviderName(String providerName) { this.providerName = providerName; @@ -74,7 +74,7 @@ public class ListSupportedNetworkServicesCmd extends BaseListCmd { public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ List services; @@ -83,7 +83,7 @@ public class ListSupportedNetworkServicesCmd extends BaseListCmd { if(serviceName != null){ service = Network.Service.getService(serviceName); if(service == null){ - throw new InvalidParameterValueException("Invalid Network Service=" + serviceName); + throw new InvalidParameterValueException("Invalid Network Service=" + serviceName, null); } } List serviceList = new ArrayList(); @@ -92,14 +92,14 @@ public class ListSupportedNetworkServicesCmd extends BaseListCmd { }else{ services = _networkService.listNetworkServices(getProviderName()); } - + ListResponse response = new ListResponse(); List servicesResponses = new ArrayList(); for (Network.Service service : services) { - //skip gateway service - if (service == Service.Gateway) { - continue; - } + //skip gateway service + if (service == Service.Gateway) { + continue; + } ServiceResponse serviceResponse = _responseGenerator.createNetworkServiceResponse(service); servicesResponses.add(serviceResponse); } diff --git a/api/src/com/cloud/api/commands/ListVMsCmd.java b/api/src/com/cloud/api/commands/ListVMsCmd.java index e1e527930c5..8919a2a26b2 100755 --- a/api/src/com/cloud/api/commands/ListVMsCmd.java +++ b/api/src/com/cloud/api/commands/ListVMsCmd.java @@ -65,25 +65,25 @@ public class ListVMsCmd extends BaseListTaggedResourcesCmd { @IdentityMapper(entityTableName="data_center") @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the availability zone ID") private Long zoneId; - + @Parameter(name=ApiConstants.FOR_VIRTUAL_NETWORK, type=CommandType.BOOLEAN, description="list by network type; true if need to list vms using Virtual Network, false otherwise") private Boolean forVirtualNetwork; - + @IdentityMapper(entityTableName="networks") @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, description="list by network id") private Long networkId; @Parameter(name=ApiConstants.HYPERVISOR, type=CommandType.STRING, description="the target hypervisor for the template") private String hypervisor; - + @IdentityMapper(entityTableName="storage_pool") @Parameter(name=ApiConstants.STORAGE_ID, type=CommandType.LONG, description="the storage ID where vm's volumes belong to") private Long storageId; @Parameter(name=ApiConstants.DETAILS, type=CommandType.LIST, collectionType=CommandType.STRING, description="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" ) + "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" ) private List viewDetails; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -116,7 +116,7 @@ public class ListVMsCmd extends BaseListTaggedResourcesCmd { public Long getZoneId() { return zoneId; } - + public Boolean getForVirtualNetwork() { return forVirtualNetwork; } @@ -124,19 +124,19 @@ public class ListVMsCmd extends BaseListTaggedResourcesCmd { public void setForVirtualNetwork(Boolean forVirtualNetwork) { this.forVirtualNetwork = forVirtualNetwork; } - + public Long getNetworkId() { return networkId; } - + public String getHypervisor() { - return hypervisor; - } - + return hypervisor; + } + public Long getStorageId() { return storageId; } - + public EnumSet getDetails() throws InvalidParameterValueException { EnumSet dv; if (viewDetails==null || viewDetails.size() <=0){ @@ -151,39 +151,40 @@ public class ListVMsCmd extends BaseListTaggedResourcesCmd { dv = EnumSet.copyOf(dc); } catch (IllegalArgumentException e){ - throw new InvalidParameterValueException("The details parameter contains a non permitted value. The allowed values are " + EnumSet.allOf(VMDetails.class)); + throw new InvalidParameterValueException("The details parameter contains a non permitted value. The allowed values are " + EnumSet.allOf(VMDetails.class), null); } } return dv; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override - public String getCommandName() { + public String getCommandName() { return s_name; } - + + @Override public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.VirtualMachine; + return AsyncJob.Type.VirtualMachine; } - @Override + @Override public void execute(){ List result = _userVmService.searchForUserVMs(this); ListResponse response = new ListResponse(); EnumSet details = getDetails(); List vmResponses; if (details.contains(VMDetails.all)){ // for all use optimized version - vmResponses = _responseGenerator.createUserVmResponse("virtualmachine", result.toArray(new UserVm[result.size()])); + vmResponses = _responseGenerator.createUserVmResponse("virtualmachine", result.toArray(new UserVm[result.size()])); } else { - vmResponses = _responseGenerator.createUserVmResponse("virtualmachine", getDetails(), result.toArray(new UserVm[result.size()])); + vmResponses = _responseGenerator.createUserVmResponse("virtualmachine", getDetails(), result.toArray(new UserVm[result.size()])); } response.setResponses(vmResponses); response.setResponseName(getCommandName()); this.setResponseObject(response); } - + } diff --git a/api/src/com/cloud/api/commands/MigrateSystemVMCmd.java b/api/src/com/cloud/api/commands/MigrateSystemVMCmd.java index e85070eef28..f55eb24e0f1 100644 --- a/api/src/com/cloud/api/commands/MigrateSystemVMCmd.java +++ b/api/src/com/cloud/api/commands/MigrateSystemVMCmd.java @@ -73,7 +73,7 @@ public class MigrateSystemVMCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Account account = UserContext.current().getCaller(); @@ -93,38 +93,38 @@ public class MigrateSystemVMCmd extends BaseAsyncCmd { public String getEventDescription() { return "Attempting to migrate VM Id: " + getVirtualMachineId() + " to host Id: "+ getHostId(); } - + @Override public void execute(){ - + Host destinationHost = _resourceService.getHost(getHostId()); if (destinationHost == null) { - throw new InvalidParameterValueException("Unable to find the host to migrate the VM, host id=" + getHostId()); + throw new InvalidParameterValueException("Unable to find the host to migrate the VM, host id=" + getHostId(), null); } try{ - UserContext.current().setEventDetails("VM Id: " + getVirtualMachineId() + " to host Id: "+ getHostId()); - //FIXME : Should not be calling UserVmService to migrate all types of VMs - need a generic VM layer - VirtualMachine migratedVm = _userVmService.migrateVirtualMachine(getVirtualMachineId(), destinationHost); - if (migratedVm != null) { - // return the generic system VM instance response - SystemVmInstanceResponse response = _responseGenerator.createSystemVmInstanceResponse(migratedVm); + UserContext.current().setEventDetails("VM Id: " + getVirtualMachineId() + " to host Id: "+ getHostId()); + //FIXME : Should not be calling UserVmService to migrate all types of VMs - need a generic VM layer + VirtualMachine migratedVm = _userVmService.migrateVirtualMachine(getVirtualMachineId(), destinationHost); + if (migratedVm != null) { + // return the generic system VM instance response + SystemVmInstanceResponse response = _responseGenerator.createSystemVmInstanceResponse(migratedVm); response.setResponseName(getCommandName()); this.setResponseObject(response); - } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to migrate the system vm"); - } + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to migrate the system vm"); + } } catch (ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException e) { s_logger.warn("Exception: ", e); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } catch (ManagementServerException e) { + } catch (ManagementServerException e) { s_logger.warn("Exception: ", e); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } catch (VirtualMachineMigrationException e) { + } catch (VirtualMachineMigrationException e) { s_logger.warn("Exception: ", e); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } + } } } diff --git a/api/src/com/cloud/api/commands/MigrateVMCmd.java b/api/src/com/cloud/api/commands/MigrateVMCmd.java index 942d1fec41f..d63698cb904 100644 --- a/api/src/com/cloud/api/commands/MigrateVMCmd.java +++ b/api/src/com/cloud/api/commands/MigrateVMCmd.java @@ -68,9 +68,9 @@ public class MigrateVMCmd extends BaseAsyncCmd { public Long getVirtualMachineId() { return virtualMachineId; } - + public Long getStoragePoolId() { - return storageId; + return storageId; } @@ -82,7 +82,7 @@ public class MigrateVMCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { UserVm userVm = _entityMgr.findById(UserVm.class, getVirtualMachineId()); @@ -102,66 +102,66 @@ public class MigrateVMCmd extends BaseAsyncCmd { public String getEventDescription() { return "Attempting to migrate VM Id: " + getVirtualMachineId() + " to host Id: "+ getHostId(); } - + @Override public void execute(){ - if (getHostId() == null && getStoragePoolId() == null) { - throw new InvalidParameterValueException("either hostId or storageId must be specified"); - } - - if (getHostId() != null && getStoragePoolId() != null) { - throw new InvalidParameterValueException("only one of hostId and storageId can be specified"); - } - + if (getHostId() == null && getStoragePoolId() == null) { + throw new InvalidParameterValueException("either hostId or storageId must be specified", null); + } + + if (getHostId() != null && getStoragePoolId() != null) { + throw new InvalidParameterValueException("only one of hostId and storageId can be specified", null); + } + UserVm userVm = _userVmService.getUserVm(getVirtualMachineId()); if (userVm == null) { - throw new InvalidParameterValueException("Unable to find the VM by id=" + getVirtualMachineId()); + throw new InvalidParameterValueException("Unable to find the VM by id=" + getVirtualMachineId(), null); } - + Host destinationHost = null; if (getHostId() != null) { - destinationHost = _resourceService.getHost(getHostId()); - if (destinationHost == null) { - throw new InvalidParameterValueException("Unable to find the host to migrate the VM, host id=" + getHostId()); - } - UserContext.current().setEventDetails("VM Id: " + getVirtualMachineId() + " to host Id: "+ getHostId()); + destinationHost = _resourceService.getHost(getHostId()); + if (destinationHost == null) { + throw new InvalidParameterValueException("Unable to find the host to migrate the VM, host id=" + getHostId(), null); + } + UserContext.current().setEventDetails("VM Id: " + getVirtualMachineId() + " to host Id: "+ getHostId()); } - + StoragePool destStoragePool = null; if (getStoragePoolId() != null) { - destStoragePool = _storageService.getStoragePool(getStoragePoolId()); - if (destStoragePool == null) { - throw new InvalidParameterValueException("Unable to find the storage pool to migrate the VM"); - } - UserContext.current().setEventDetails("VM Id: " + getVirtualMachineId() + " to storage pool Id: "+ getStoragePoolId()); + destStoragePool = _storageService.getStoragePool(getStoragePoolId()); + if (destStoragePool == null) { + throw new InvalidParameterValueException("Unable to find the storage pool to migrate the VM", null); + } + UserContext.current().setEventDetails("VM Id: " + getVirtualMachineId() + " to storage pool Id: "+ getStoragePoolId()); } - + try{ - VirtualMachine migratedVm = null; - if (getHostId() != null) { - migratedVm = _userVmService.migrateVirtualMachine(getVirtualMachineId(), destinationHost); - } else if (getStoragePoolId() != null) { - migratedVm = _userVmService.vmStorageMigration(getVirtualMachineId(), destStoragePool); - } - if (migratedVm != null) { + VirtualMachine migratedVm = null; + if (getHostId() != null) { + migratedVm = _userVmService.migrateVirtualMachine(getVirtualMachineId(), destinationHost); + } else if (getStoragePoolId() != null) { + migratedVm = _userVmService.vmStorageMigration(getVirtualMachineId(), destStoragePool); + } + if (migratedVm != null) { UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", (UserVm)migratedVm).get(0); response.setResponseName(getCommandName()); this.setResponseObject(response); - } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to migrate vm"); - } + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to migrate vm"); + } } catch (ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException e) { s_logger.warn("Exception: ", e); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } catch (ManagementServerException e) { + } catch (ManagementServerException e) { s_logger.warn("Exception: ", e); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } catch (VirtualMachineMigrationException e) { + } catch (VirtualMachineMigrationException e) { s_logger.warn("Exception: ", e); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } + } } } diff --git a/api/src/com/cloud/api/commands/RemoveFromLoadBalancerRuleCmd.java b/api/src/com/cloud/api/commands/RemoveFromLoadBalancerRuleCmd.java index 6c99ccb3730..74b0c536797 100644 --- a/api/src/com/cloud/api/commands/RemoveFromLoadBalancerRuleCmd.java +++ b/api/src/com/cloud/api/commands/RemoveFromLoadBalancerRuleCmd.java @@ -36,7 +36,7 @@ public class RemoveFromLoadBalancerRuleCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(RemoveFromLoadBalancerRuleCmd.class.getName()); private static final String s_name = "removefromloadbalancerruleresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @@ -100,7 +100,7 @@ public class RemoveFromLoadBalancerRuleCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to remove instance from load balancer rule"); } } - + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -108,10 +108,10 @@ public class RemoveFromLoadBalancerRuleCmd extends BaseAsyncCmd { @Override public Long getSyncObjId() { - LoadBalancer lb = _lbService.findById(id); - if(lb == null){ - throw new InvalidParameterValueException("Unable to find load balancer rule: " + id); - } + LoadBalancer lb = _lbService.findById(id); + if(lb == null){ + throw new InvalidParameterValueException("Unable to find load balancer rule by id", null); + } return lb.getNetworkId(); } } diff --git a/api/src/com/cloud/api/commands/RestartNetworkCmd.java b/api/src/com/cloud/api/commands/RestartNetworkCmd.java index 552c4fbe2f8..8c3e8c05f04 100644 --- a/api/src/com/cloud/api/commands/RestartNetworkCmd.java +++ b/api/src/com/cloud/api/commands/RestartNetworkCmd.java @@ -40,7 +40,7 @@ public class RestartNetworkCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + @IdentityMapper(entityTableName="networks") @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The id of the network to restart.") private Long id; @@ -52,16 +52,16 @@ public class RestartNetworkCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getNetworkId() { Network network = _networkService.getNetwork(id); if (network == null) { - throw new InvalidParameterValueException("Unable to find network by id " + id); + throw new InvalidParameterValueException("Unable to find network by id", null); } else { return network.getId(); } } - + public Boolean getCleanup() { if (cleanup != null) { return cleanup; @@ -83,7 +83,7 @@ public class RestartNetworkCmd extends BaseAsyncCmd { public static String getResultObjectName() { return "addressinfo"; } - + @Override public void execute() throws ResourceUnavailableException, ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException { boolean result = _networkService.restartNetwork(this, getCleanup()); @@ -94,7 +94,7 @@ public class RestartNetworkCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to restart network"); } } - + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -104,21 +104,22 @@ public class RestartNetworkCmd extends BaseAsyncCmd { public Long getSyncObjId() { return id; } - + + @Override public String getEventDescription() { return "Restarting network: " + getNetworkId(); } - + @Override public String getEventType() { return EventTypes.EVENT_NETWORK_RESTART; } - + @Override public long getEntityOwnerId() { Network network = _networkService.getNetwork(id); if (network == null) { - throw new InvalidParameterValueException("Networkd id=" + id + " doesn't exist"); + throw new InvalidParameterValueException("Couldn't find network by id", null); } else { return _networkService.getNetwork(id).getAccountId(); } diff --git a/api/src/com/cloud/api/commands/SuspendProjectCmd.java b/api/src/com/cloud/api/commands/SuspendProjectCmd.java index c3d9a69c48f..177f801bf80 100644 --- a/api/src/com/cloud/api/commands/SuspendProjectCmd.java +++ b/api/src/com/cloud/api/commands/SuspendProjectCmd.java @@ -73,26 +73,26 @@ public class SuspendProjectCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to suspend a project"); } } - + @Override public String getEventType() { return EventTypes.EVENT_PROJECT_SUSPEND; } - + @Override public String getEventDescription() { return "Suspending project: " + id; } - + @Override public long getEntityOwnerId() { Project project= _projectService.getProject(id); //verify input parameters if (project == null) { - throw new InvalidParameterValueException("Unable to find project by id " + id); + throw new InvalidParameterValueException("Unable to find project by id", null); } - + return _projectService.getProjectOwner(id).getId(); } - + } \ No newline at end of file diff --git a/api/src/com/cloud/api/commands/UpdateClusterCmd.java b/api/src/com/cloud/api/commands/UpdateClusterCmd.java index 5de22567a61..459c884ef43 100755 --- a/api/src/com/cloud/api/commands/UpdateClusterCmd.java +++ b/api/src/com/cloud/api/commands/UpdateClusterCmd.java @@ -12,18 +12,18 @@ // Automatically generated by addcopyright.py at 04/03/2012 package com.cloud.api.commands; -import org.apache.log4j.Logger; - -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; +import org.apache.log4j.Logger; + +import com.cloud.api.ApiConstants; +import com.cloud.api.BaseCmd; import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ClusterResponse; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.org.Cluster; -import com.cloud.user.Account; +import com.cloud.api.Implementation; +import com.cloud.api.Parameter; +import com.cloud.api.ServerApiException; +import com.cloud.api.response.ClusterResponse; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.org.Cluster; +import com.cloud.user.Account; @Implementation(description="Updates an existing cluster", responseObject=ClusterResponse.class) public class UpdateClusterCmd extends BaseCmd { @@ -34,22 +34,22 @@ public class UpdateClusterCmd extends BaseCmd { @IdentityMapper(entityTableName="cluster") @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the Cluster") private Long id; - + @Parameter(name=ApiConstants.CLUSTER_NAME, type=CommandType.STRING, description="the cluster name") private String clusterName; @Parameter(name=ApiConstants.HYPERVISOR, type=CommandType.STRING, description="hypervisor type of the cluster") private String hypervisor; - + @Parameter(name=ApiConstants.CLUSTER_TYPE, type=CommandType.STRING, description="hypervisor type of the cluster") private String clusterType; - + @Parameter(name=ApiConstants.ALLOCATION_STATE, type=CommandType.STRING, description="Allocation state of this cluster for allocation of new resources") private String allocationState; - + @Parameter(name=ApiConstants.MANAGED_STATE, type=CommandType.STRING, description="whether this cluster is managed by cloudstack") private String managedState; - + public String getClusterName() { return clusterName; } @@ -59,33 +59,33 @@ public class UpdateClusterCmd extends BaseCmd { } public String getHypervisor() { - return hypervisor; + return hypervisor; } - + @Override public String getCommandName() { - return s_name; + return s_name; } - + public String getClusterType() { - return clusterType; + return clusterType; } - + public void setClusterType(String type) { - this.clusterType = type; + this.clusterType = type; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + public String getAllocationState() { - return allocationState; + return allocationState; } - + public void setAllocationState(String allocationState) { - this.allocationState = allocationState; + this.allocationState = allocationState; } public String getManagedstate() { @@ -98,16 +98,16 @@ public class UpdateClusterCmd extends BaseCmd { @Override public void execute(){ - Cluster cluster = _resourceService.getCluster(getId()); + Cluster cluster = _resourceService.getCluster(getId()); if (cluster == null) { - throw new InvalidParameterValueException("Unable to find the cluster by id=" + getId()); + throw new InvalidParameterValueException("Unable to find the cluster by id", null); } - + Cluster result = _resourceService.updateCluster(cluster, getClusterType(), getHypervisor(), getAllocationState(), getManagedstate()); if (result != null) { - ClusterResponse clusterResponse = _responseGenerator.createClusterResponse(cluster, false); - clusterResponse.setResponseName(getCommandName()); - this.setResponseObject(clusterResponse); + ClusterResponse clusterResponse = _responseGenerator.createClusterResponse(cluster, false); + clusterResponse.setResponseName(getCommandName()); + this.setResponseObject(clusterResponse); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update cluster"); } diff --git a/api/src/com/cloud/api/commands/UpdateNetworkCmd.java b/api/src/com/cloud/api/commands/UpdateNetworkCmd.java index 22d111d33ac..f104b5ca9ae 100644 --- a/api/src/com/cloud/api/commands/UpdateNetworkCmd.java +++ b/api/src/com/cloud/api/commands/UpdateNetworkCmd.java @@ -43,43 +43,43 @@ public class UpdateNetworkCmd extends BaseAsyncCmd { @IdentityMapper(entityTableName="networks") @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the network") private Long id; - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the new name for the network") private String name; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, description="the new display text for the network") private String displayText; - + @Parameter(name=ApiConstants.NETWORK_DOMAIN, type=CommandType.STRING, description="network domain") private String networkDomain; - + @Parameter(name=ApiConstants.CHANGE_CIDR, type=CommandType.BOOLEAN, description="Force update even if cidr type is different") private Boolean changeCidr; - + @IdentityMapper(entityTableName="network_offerings") @Parameter(name=ApiConstants.NETWORK_OFFERING_ID, type=CommandType.LONG, description="network offering ID") private Long networkOfferingId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getId() { return id; } - + public String getNetworkName() { return name; } - + public String getDisplayText() { return displayText; } - + private String getNetworkDomain() { return networkDomain; } - + private Long getNetworkOfferingId() { return networkOfferingId; } @@ -98,17 +98,17 @@ public class UpdateNetworkCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Network network = _networkService.getNetwork(id); if (network == null) { - throw new InvalidParameterValueException("Networkd id=" + id + " doesn't exist"); + throw new InvalidParameterValueException("Couldn't find network by id", null); } else { return _networkService.getNetwork(id).getAccountId(); } } - + @Override public void execute() throws InsufficientCapacityException, ConcurrentOperationException{ User callerUser = _accountService.getActiveUser(UserContext.current().getCallerUserId()); @@ -123,12 +123,12 @@ public class UpdateNetworkCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update network"); } } - + @Override public String getEventDescription() { return "Updating network: " + getId(); } - + @Override public String getEventType() { return EventTypes.EVENT_NETWORK_UPDATE; diff --git a/api/src/com/cloud/api/commands/UpdateProjectCmd.java b/api/src/com/cloud/api/commands/UpdateProjectCmd.java index 156f2afe5e3..f35b16ebc38 100644 --- a/api/src/com/cloud/api/commands/UpdateProjectCmd.java +++ b/api/src/com/cloud/api/commands/UpdateProjectCmd.java @@ -37,14 +37,14 @@ public class UpdateProjectCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + @IdentityMapper(entityTableName="projects") @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="id of the project to be modified") private Long id; @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="new Admin account for the project") private String accountName; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, description="display text of the project") private String displayText; @@ -68,18 +68,18 @@ public class UpdateProjectCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Project project= _projectService.getProject(id); //verify input parameters if (project == null) { - throw new InvalidParameterValueException("Unable to find project by id " + id); + throw new InvalidParameterValueException("Unable to find project by id ", null); } - + return _projectService.getProjectOwner(id).getId(); } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -97,12 +97,12 @@ public class UpdateProjectCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update a project"); } } - + @Override public String getEventType() { return EventTypes.EVENT_PROJECT_UPDATE; } - + @Override public String getEventDescription() { return "Updating project: " + id; diff --git a/api/src/com/cloud/api/commands/UpdateTemplateOrIsoPermissionsCmd.java b/api/src/com/cloud/api/commands/UpdateTemplateOrIsoPermissionsCmd.java index 8223228d58f..53d6fa2e0c5 100755 --- a/api/src/com/cloud/api/commands/UpdateTemplateOrIsoPermissionsCmd.java +++ b/api/src/com/cloud/api/commands/UpdateTemplateOrIsoPermissionsCmd.java @@ -44,13 +44,13 @@ public abstract class UpdateTemplateOrIsoPermissionsCmd extends BaseCmd { @Parameter(name = ApiConstants.IS_PUBLIC, type = CommandType.BOOLEAN, description = "true for public template/iso, false for private templates/isos") private Boolean isPublic; - + @Parameter(name = ApiConstants.IS_EXTRACTABLE, type = CommandType.BOOLEAN, description = "true if the template/iso is extractable, false other wise. Can be set only by root admin") private Boolean isExtractable; @Parameter(name = ApiConstants.OP, type = CommandType.STRING, description = "permission operator (add, remove, reset)") private String operation; - + @IdentityMapper(entityTableName="projects") @Parameter(name = ApiConstants.PROJECT_IDS, type = CommandType.LIST, collectionType = CommandType.LONG, description = "a comma delimited list of projects. If specified, \"op\" parameter has to be passed in.") private List projectIds; @@ -61,9 +61,9 @@ public abstract class UpdateTemplateOrIsoPermissionsCmd extends BaseCmd { public List getAccountNames() { if (accountNames != null && projectIds != null) { - throw new InvalidParameterValueException("Accounts and projectIds can't be specified together"); + throw new InvalidParameterValueException("Accounts and projectIds can't be specified together", null); } - + return accountNames; } @@ -78,18 +78,18 @@ public abstract class UpdateTemplateOrIsoPermissionsCmd extends BaseCmd { public Boolean isPublic() { return isPublic; } - + public Boolean isExtractable() { return isExtractable; } - + public String getOperation() { return operation; } - + public List getProjectIds() { if (accountNames != null && projectIds != null) { - throw new InvalidParameterValueException("Accounts and projectIds can't be specified together"); + throw new InvalidParameterValueException("Accounts and projectIds can't be specified together", null); } return projectIds; } diff --git a/api/src/com/cloud/api/commands/UpgradeSystemVMCmd.java b/api/src/com/cloud/api/commands/UpgradeSystemVMCmd.java index b690ab23d0a..4d2c6971bb4 100644 --- a/api/src/com/cloud/api/commands/UpgradeSystemVMCmd.java +++ b/api/src/com/cloud/api/commands/UpgradeSystemVMCmd.java @@ -33,8 +33,8 @@ import com.cloud.user.UserContext; import com.cloud.vm.VirtualMachine; @Implementation(responseObject=SystemVmResponse.class, description="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.") + "The system vm must be in a \"Stopped\" state for " + + "this command to take effect.") public class UpgradeSystemVMCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpgradeVMCmd.class.getName()); private static final String s_name = "changeserviceforsystemvmresponse"; @@ -49,7 +49,7 @@ public class UpgradeSystemVMCmd extends BaseCmd { @IdentityMapper(entityTableName="disk_offering") @Parameter(name=ApiConstants.SERVICE_OFFERING_ID, type=CommandType.LONG, required=true, - description="the service offering ID to apply to the system vm") + description="the service offering ID to apply to the system vm") private Long serviceOfferingId; ///////////////////////////////////////////////////// @@ -72,7 +72,7 @@ public class UpgradeSystemVMCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Account account = UserContext.current().getCaller(); @@ -82,16 +82,16 @@ public class UpgradeSystemVMCmd extends BaseCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute(){ UserContext.current().setEventDetails("Vm Id: "+getId()); - + ServiceOffering serviceOffering = _configService.getServiceOffering(serviceOfferingId); if (serviceOffering == null) { - throw new InvalidParameterValueException("Unable to find service offering: " + serviceOfferingId); + throw new InvalidParameterValueException("Unable to find service offering by id", null); } - + VirtualMachine result = _mgr.upgradeSystemVM(this); if (result != null) { SystemVmResponse response = _responseGenerator.createSystemVmResponse(result); diff --git a/api/src/com/cloud/api/commands/UpgradeVMCmd.java b/api/src/com/cloud/api/commands/UpgradeVMCmd.java index 4ab43a1bfcf..a492b624afe 100644 --- a/api/src/com/cloud/api/commands/UpgradeVMCmd.java +++ b/api/src/com/cloud/api/commands/UpgradeVMCmd.java @@ -28,8 +28,8 @@ import com.cloud.user.UserContext; import com.cloud.uservm.UserVm; @Implementation(responseObject=UserVmResponse.class, description="Changes the service offering for a virtual machine. " + - "The virtual machine must be in a \"Stopped\" state for " + - "this command to take effect.") + "The virtual machine must be in a \"Stopped\" state for " + + "this command to take effect.") public class UpgradeVMCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpgradeVMCmd.class.getName()); private static final String s_name = "changeserviceforvirtualmachineresponse"; @@ -68,9 +68,9 @@ public class UpgradeVMCmd extends BaseCmd { } public static String getResultObjectName() { - return "virtualmachine"; + return "virtualmachine"; } - + @Override public long getEntityOwnerId() { UserVm userVm = _entityMgr.findById(UserVm.class, getId()); @@ -80,16 +80,16 @@ public class UpgradeVMCmd extends BaseCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute(){ UserContext.current().setEventDetails("Vm Id: "+getId()); - + ServiceOffering serviceOffering = _configService.getServiceOffering(serviceOfferingId); if (serviceOffering == null) { - throw new InvalidParameterValueException("Unable to find service offering: " + serviceOfferingId); + throw new InvalidParameterValueException("Unable to find service offering by id", null); } - + UserVm result = _userVmService.upgradeVirtualMachine(this); if (result != null){ UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", result).get(0); diff --git a/api/src/com/cloud/exception/InvalidParameterValueException.java b/api/src/com/cloud/exception/InvalidParameterValueException.java index 2b3122f667e..30b774b1163 100644 --- a/api/src/com/cloud/exception/InvalidParameterValueException.java +++ b/api/src/com/cloud/exception/InvalidParameterValueException.java @@ -12,6 +12,9 @@ // Automatically generated by addcopyright.py at 04/03/2012 package com.cloud.exception; +import java.util.List; + +import com.cloud.utils.IdentityProxy; import com.cloud.utils.exception.CloudRuntimeException; /** @@ -26,4 +29,13 @@ public class InvalidParameterValueException extends CloudRuntimeException { super(message); } + public InvalidParameterValueException(String message, List idProxyList) { + super(message); + if (idProxyList != null) { + for (IdentityProxy id : idProxyList) { + this.addProxyObject(id.getTableName(), id.getValue(), id.getidFieldName()); + } + } + } + } diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index e135264d3a4..dea6f5f6b86 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -179,6 +179,7 @@ import com.cloud.user.User; import com.cloud.user.UserContext; import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.UserStatisticsDao; +import com.cloud.utils.IdentityProxy; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.component.Adapters; @@ -353,7 +354,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public List getElementServices(Provider provider) { NetworkElement element = getElementImplementingProvider(provider.getName()); if (element == null) { - throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + provider.getName() + "'"); + throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + provider.getName() + "'", null); } return new ArrayList(element.getCapabilities().keySet()); } @@ -362,7 +363,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public boolean canElementEnableIndividualServices(Provider provider) { NetworkElement element = getElementImplementingProvider(provider.getName()); if (element == null) { - throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + provider.getName() + "'"); + throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + provider.getName() + "'", null); } return element.canEnableIndividualServices(); } @@ -375,7 +376,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @DB public PublicIp fetchNewPublicIp(long dcId, Long podId, Long vlanDbId, Account owner, VlanType vlanUse, Long guestNetworkId, boolean sourceNat, boolean assign, String requestedIp, boolean isSystem, Long vpcId) - throws InsufficientAddressCapacityException { + throws InsufficientAddressCapacityException { StringBuilder errorMessage = new StringBuilder("Unable to get ip adress in "); Transaction txn = Transaction.currentTxn(); txn.start(); @@ -418,15 +419,15 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (podId != null) { InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException ("Insufficient address capacity", Pod.class, podId); - // for now, we hardcode the table names, but we should ideally do a lookup for the tablename from the VO object. - ex.addProxyObject("Pod", podId, "podId"); - throw ex; + // for now, we hardcode the table names, but we should ideally do a lookup for the tablename from the VO object. + ex.addProxyObject("Pod", podId, "podId"); + throw ex; } s_logger.warn(errorMessage.toString()); InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException ("Insufficient address capacity", DataCenter.class, dcId); ex.addProxyObject("data_center", dcId, "dcId"); - throw ex; + throw ex; } assert (addrs.size() == 1) : "Return size is incorrect: " + addrs.size(); @@ -482,7 +483,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag VlanVO vlan = _vlanDao.findById(addr.getVlanId()); String guestType = vlan.getVlanType().toString(); - + UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NET_IP_ASSIGN, owner.getId(), addr.getDataCenterId(), addr.getId(), addr.getAddress().toString(), addr.isSourceNat(), guestType, addr.getSystem()); @@ -496,34 +497,34 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag txn.commit(); } - + @Override public PublicIp assignSourceNatIpAddressToVpc(Account owner, Vpc vpc) throws InsufficientAddressCapacityException, ConcurrentOperationException { long dcId = vpc.getZoneId(); - + IPAddressVO sourceNatIp = getExistingSourceNat(owner.getId(), null, vpc.getId()); - + PublicIp ipToReturn = null; - + if (sourceNatIp != null) { ipToReturn = new PublicIp(sourceNatIp, _vlanDao.findById(sourceNatIp.getVlanId()), NetUtils.createSequenceBasedMacAddress(sourceNatIp.getMacAddress())); } else { ipToReturn = assignSourceNatIpAddress(owner, null, vpc.getId(), dcId); } - + return ipToReturn; } - + @Override public PublicIp assignSourceNatIpAddressToGuestNetwork(Account owner, Network guestNetwork) throws InsufficientAddressCapacityException, ConcurrentOperationException { assert (guestNetwork.getTrafficType() != null) : "You're asking for a source nat but your network " + - "can't participate in source nat. What do you have to say for yourself?"; + "can't participate in source nat. What do you have to say for yourself?"; long dcId = guestNetwork.getDataCenterId(); - + IPAddressVO sourceNatIp = getExistingSourceNat(owner.getId(), guestNetwork.getId(), guestNetwork.getVpcId()); - + PublicIp ipToReturn = null; if (sourceNatIp != null) { ipToReturn = new PublicIp(sourceNatIp, _vlanDao.findById(sourceNatIp.getVlanId()), @@ -531,7 +532,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } else { ipToReturn = assignSourceNatIpAddress(owner, guestNetwork.getId(), null, dcId); } - + return ipToReturn; } @@ -557,24 +558,24 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag owner = _accountDao.acquireInLockTable(ownerId); if (owner == null) { - // this ownerId comes from owner or type Account. See the class "AccountVO" and the annotations in that class - // to get the table name and field name that is queried to fill this ownerid. - ConcurrentOperationException ex = new ConcurrentOperationException("Unable to lock account"); + // this ownerId comes from owner or type Account. See the class "AccountVO" and the annotations in that class + // to get the table name and field name that is queried to fill this ownerid. + ConcurrentOperationException ex = new ConcurrentOperationException("Unable to lock account"); } if (s_logger.isDebugEnabled()) { s_logger.debug("lock account " + ownerId + " is acquired"); } - // If account has Account specific ip ranges, try to allocate ip from there - Long vlanId = null; - List maps = _accountVlanMapDao.listAccountVlanMapsByAccount(ownerId); - if (maps != null && !maps.isEmpty()) { - //check if the ips from this vlan are associated with this network - List ips = _ipAddressDao.listByVlanId(maps.get(0).getVlanDbId()); - if (ips != null && !ips.isEmpty() && ips.get(0).getAssociatedWithNetworkId() == guestNtwkId) { - vlanId = maps.get(0).getVlanDbId(); - } + // If account has Account specific ip ranges, try to allocate ip from there + Long vlanId = null; + List maps = _accountVlanMapDao.listAccountVlanMapsByAccount(ownerId); + if (maps != null && !maps.isEmpty()) { + //check if the ips from this vlan are associated with this network + List ips = _ipAddressDao.listByVlanId(maps.get(0).getVlanDbId()); + if (ips != null && !ips.isEmpty() && ips.get(0).getAssociatedWithNetworkId() == guestNtwkId) { + vlanId = maps.get(0).getVlanDbId(); } + } ip = fetchNewPublicIp(dcId, null, vlanId, owner, VlanType.VirtualNetwork, guestNtwkId, true, false, null, false, vpcId); @@ -616,7 +617,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // The admin is making the call, determine if it is for someone else or for himself if (domainId != null) { if ((account != null) && !_domainDao.isChildDomain(account.getDomainId(), domainId)) { - // TBD: Check if call to addProxyObject() needs correction. + // TBD: Check if call to addProxyObject() needs correction. PermissionDeniedException ex = new PermissionDeniedException("Invalid domain id given, permission denied"); ex.addProxyObject("domain", domainId, "domainId"); throw ex; @@ -626,10 +627,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (userAccount != null) { account = userAccount; } else { - // TBD: Check if call to addProxyObject() needs correction. - PermissionDeniedException ex = new PermissionDeniedException("Unable to find account " + accountName + " in specified domain, permission denied"); - ex.addProxyObject("domain", domainId, "domainId"); - throw ex; + // TBD: Check if call to addProxyObject() needs correction. + PermissionDeniedException ex = new PermissionDeniedException("Unable to find account " + accountName + " in specified domain, permission denied"); + ex.addProxyObject("domain", domainId, "domainId"); + throw ex; } } } else { @@ -720,10 +721,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag services.add(Service.SourceNat); networkSNAT.add(ip.getAssociatedWithNetworkId()); } else { - CloudRuntimeException ex = new CloudRuntimeException("Multiple generic soure NAT IPs provided for network"); - // see the IPAddressVO.java class. - ex.addProxyObject("user_ip_address", ip.getAssociatedWithNetworkId(), "networkId"); - throw ex; + CloudRuntimeException ex = new CloudRuntimeException("Multiple generic soure NAT IPs provided for network"); + // see the IPAddressVO.java class. + ex.addProxyObject("user_ip_address", ip.getAssociatedWithNetworkId(), "networkId"); + throw ex; } } ipToServices.put(ip, services); @@ -747,7 +748,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (purposes == null || purposes.isEmpty()) { // since no active rules are there check if any rules are applied on the public IP but are in // revoking state - + purposes = getPublicIpPurposeInRules(ip, true, includingFirewall); if (ip.isOneToOneNat()) { if (purposes == null) { @@ -863,7 +864,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } // We only support one provider for one service now Map> serviceToProviders = getServiceProvidersMap(publicIp.getAssociatedWithNetworkId()); - Set oldProviders = serviceToProviders.get((Service) services.toArray()[0]); + Set oldProviders = serviceToProviders.get(services.toArray()[0]); Provider oldProvider = (Provider) oldProviders.toArray()[0]; // Since IP already has service to bind with, the oldProvider can't be null Set newProviders = serviceToProviders.get(service); @@ -1014,7 +1015,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return _networksDao.listBy(owner.getId(), zoneId, Network.GuestType.Isolated); } - + @Override public List getIsolatedNetworksWithSourceNATOwnedByAccountInZone(long zoneId, Account owner) { @@ -1079,10 +1080,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag false, assign, null, isSystem, null); if (ip == null) { - InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException - ("Unable to find available public IP addresses", DataCenter.class, zone.getId()); - ex.addProxyObject("data_center", zone.getId(), "zoneId"); - throw ex; + InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException + ("Unable to find available public IP addresses", DataCenter.class, zone.getId()); + ex.addProxyObject("data_center", zone.getId(), "zoneId"); + throw ex; } UserContext.current().setEventDetails("Ip Id: " + ip.getId()); Ip ipAddress = ip.getAddress(); @@ -1104,14 +1105,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag protected IPAddressVO getExistingSourceNat(long ownerId, Long networkId, Long vpcId) { - + List addrs = null; if (vpcId != null) { addrs = listPublicIpsAssignedToVpc(ownerId, true, vpcId); } else if (networkId != null) { addrs = listPublicIpsAssignedToGuestNtwk(ownerId, networkId, true); } - + IPAddressVO sourceNatIp = null; if (addrs.isEmpty()) { return null; @@ -1125,16 +1126,16 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } assert (sourceNatIp != null) : "How do we get a bunch of ip addresses but none of them are source nat? " + - "account=" + ownerId + "; networkId=" + networkId + "; vpcId=" + vpcId; + "account=" + ownerId + "; networkId=" + networkId + "; vpcId=" + vpcId; } - + return sourceNatIp; } @DB @Override public IPAddressVO associateIPToGuestNetwork(long ipId, long networkId) throws ResourceAllocationException, ResourceUnavailableException, - InsufficientAddressCapacityException, ConcurrentOperationException { + InsufficientAddressCapacityException, ConcurrentOperationException { Account caller = UserContext.current().getCaller(); Account owner = null; @@ -1151,7 +1152,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.debug("IP " + ipToAssoc + " is already assocaited with network id" + networkId); return ipToAssoc; } - + Network network = _networksDao.findById(networkId); if (network != null) { _accountMgr.checkAccess(caller, AccessType.UseNetwork, false, network); @@ -1159,30 +1160,30 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.debug("Unable to find ip address by id: " + ipId); return null; } - + DataCenter zone = _configMgr.getZone(network.getDataCenterId()); // allow associating IP addresses to guest network only if (network.getTrafficType() != TrafficType.Guest) { throw new InvalidParameterValueException("Ip address can be associated to the network with trafficType " + - TrafficType.Guest); + TrafficType.Guest, null); } // Check that network belongs to IP owner - skip this check for Basic zone as there is just one guest network, // and it belongs to the system if (zone.getNetworkType() != NetworkType.Basic && network.getAccountId() != owner.getId()) { - throw new InvalidParameterValueException("The owner of the network is not the same as owner of the IP"); + throw new InvalidParameterValueException("The owner of the network is not the same as owner of the IP", null); } - + // In Advance zone only allow to do IP assoc for Isolated networks with source nat service enabled if (zone.getNetworkType() == NetworkType.Advanced && !(network.getGuestType() == GuestType.Isolated && areServicesSupportedInNetwork(network.getId(), Service.SourceNat))) { throw new InvalidParameterValueException("In zone of type " + NetworkType.Advanced + " ip address can be associated only to the network of guest type " + GuestType.Isolated + " with the " - + Service.SourceNat.getName() + " enabled"); + + Service.SourceNat.getName() + " enabled", null); } - + NetworkOffering offering = _networkOfferingDao.findById(network.getNetworkOfferingId()); boolean sharedSourceNat = offering.getSharedSourceNat(); boolean isSourceNat = false; @@ -1193,7 +1194,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } } - + s_logger.debug("Associating ip " + ipToAssoc + " to network " + network); IPAddressVO ip = _ipAddressDao.findById(ipId); @@ -1201,7 +1202,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag ip.setAssociatedWithNetworkId(networkId); ip.setSourceNat(isSourceNat); _ipAddressDao.update(ipId, ip); - + boolean success = false; try { success = applyIpAssociations(network, false); @@ -1233,7 +1234,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } - + @DB protected IpAddress associateIPToVpc(long ipId, long vpcId) throws ResourceAllocationException, ResourceUnavailableException, InsufficientAddressCapacityException, ConcurrentOperationException { @@ -1248,22 +1249,22 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.debug("Unable to find ip address by id: " + ipId); return null; } - + Vpc vpc = _vpcMgr.getVpc(vpcId); if (vpc == null) { - throw new InvalidParameterValueException("Invalid VPC id " + vpcId); + throw new InvalidParameterValueException("Invalid VPC id provided", null); } - + // check permissions _accountMgr.checkAccess(caller, null, true, owner, vpc); - + boolean isSourceNat = false; if (getExistingSourceNat(owner.getId(), null, vpcId) == null) { isSourceNat = true; } - + s_logger.debug("Associating ip " + ipToAssoc + " to vpc " + vpc); - + Transaction txn = Transaction.currentTxn(); txn.start(); IPAddressVO ip = _ipAddressDao.findById(ipId); @@ -1271,16 +1272,16 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag ip.setVpcId(vpcId); ip.setSourceNat(isSourceNat); _ipAddressDao.update(ipId, ip); - + //mark ip as allocated markPublicIpAsAllocated(ip); txn.commit(); - + s_logger.debug("Successfully assigned ip " + ipToAssoc + " to vpc " + vpc); return _ipAddressDao.findById(ipId); } - + @Override @DB @@ -1397,8 +1398,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.StaticNat, defaultProviders); defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.PortForwarding, defaultProviders); defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.Vpn, defaultProviders); - - + + Map> defaultVPCOffProviders = new HashMap>(); defaultProviders.clear(); @@ -1455,7 +1456,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } - + if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworks) == null) { offering = _configMgr.createNetworkOffering(NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworks, "Offering for Isolated VPC networks with Source Nat service enabled", TrafficType.Guest, @@ -1473,7 +1474,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } - + Map> netscalerServiceProviders = new HashMap>(); Set vrProvider = new HashSet(); vrProvider.add(Provider.VirtualRouter); @@ -1487,7 +1488,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag netscalerServiceProviders.put(Service.SecurityGroup, sgProvider); netscalerServiceProviders.put(Service.StaticNat, nsProvider); netscalerServiceProviders.put(Service.Lb, nsProvider); - + Map> serviceCapabilityMap = new HashMap>(); Map elb = new HashMap(); elb.put(Capability.ElasticLb, "true"); @@ -1495,7 +1496,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag eip.put(Capability.ElasticIp, "true"); serviceCapabilityMap.put(Service.Lb, elb); serviceCapabilityMap.put(Service.StaticNat, eip); - + if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultSharedEIPandELBNetworkOffering) == null) { offering = _configMgr.createNetworkOffering(NetworkOffering.DefaultSharedEIPandELBNetworkOffering, "Offering for Shared networks with Elastic IP and Elastic LB capabilities", TrafficType.Guest, null, true, Availability.Optional, null, netscalerServiceProviders, true, Network.GuestType.Shared, false, null, true, serviceCapabilityMap, true); @@ -1579,7 +1580,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (implementedProvider != null) { if (s_providerToNetworkElementMap.containsKey(implementedProvider.getName())) { s_logger.error("Cannot start NetworkManager: Provider <-> NetworkElement must be a one-to-one map, " + - "multiple NetworkElements found for Provider: " + implementedProvider.getName()); + "multiple NetworkElements found for Provider: " + implementedProvider.getName()); return false; } s_providerToNetworkElementMap.put(implementedProvider.getName(), element.getName()); @@ -1614,7 +1615,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public List listPublicIpsAssignedToGuestNtwk(long accountId, long associatedNetworkId, Boolean sourceNat) { SearchCriteria sc = IpAddressSearch.create(); sc.setParameters("accountId", accountId); - sc.setParameters("associatedWithNetworkId", associatedNetworkId); + sc.setParameters("associatedWithNetworkId", associatedNetworkId); if (sourceNat != null) { sc.addAnd("sourceNat", SearchCriteria.Op.EQ, sourceNat); @@ -1623,7 +1624,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return _ipAddressDao.search(sc, null); } - + @Override public List listPublicIpsAssignedToAccount(long accountId, long dcId, Boolean sourceNat) { SearchCriteria sc = IpAddressSearch.create(); @@ -1637,7 +1638,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return _ipAddressDao.search(sc, null); } - + protected List listPublicIpsAssignedToVpc(long accountId, Boolean sourceNat, long vpcId) { SearchCriteria sc = IpAddressSearch.create(); sc.setParameters("accountId", accountId); @@ -1654,7 +1655,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override public List setupNetwork(Account owner, NetworkOfferingVO offering, DeploymentPlan plan, String name, String displayText, boolean isDefault) - throws ConcurrentOperationException { + throws ConcurrentOperationException { return setupNetwork(owner, offering, null, plan, name, displayText, false, null, null, null, null); } @@ -1663,7 +1664,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public List setupNetwork(Account owner, NetworkOfferingVO offering, Network predefined, DeploymentPlan plan, String name, String displayText, boolean errorIfAlreadySetup, Long domainId, ACLType aclType, Boolean subdomainAccess, Long vpcId) throws ConcurrentOperationException { - + Account locked = _accountDao.acquireInLockTable(owner.getId()); if (locked == null) { throw new ConcurrentOperationException("Unable to acquire lock on " + owner); @@ -1680,10 +1681,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } if (errorIfAlreadySetup) { - InvalidParameterValueException ex = new InvalidParameterValueException("Found existing network configuration (with specified id) for offering (with specified id)"); - ex.addProxyObject(offering, offering.getId(), "offeringId"); - ex.addProxyObject(configs.get(0), configs.get(0).getId(), "networkConfigId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy(offering, offering.getId(), "offeringId")); + idList.add(new IdentityProxy(configs.get(0), configs.get(0).getId(), "networkConfigId")); + throw new InvalidParameterValueException("Found existing network configuration (with specified id) for offering (with specified id)", idList); } else { return configs; } @@ -1697,10 +1698,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } if (errorIfAlreadySetup) { - InvalidParameterValueException ex = new InvalidParameterValueException("Found existing network configuration (with specified id) for offering (with specified id)"); - ex.addProxyObject(offering, offering.getId(), "offeringId"); - ex.addProxyObject(configs.get(0), configs.get(0).getId(), "networkConfigId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy(offering, offering.getId(), "offeringId")); + idList.add(new IdentityProxy(configs.get(0), configs.get(0).getId(), "networkConfigId")); + throw new InvalidParameterValueException("Found existing network configuration (with specified id) for offering (with specified id)", idList); } else { return configs; } @@ -1748,9 +1749,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } if (networks.size() < 1) { - // see networkOfferingVO.java - CloudRuntimeException ex = new CloudRuntimeException("Unable to convert network offering with specified id to network profile"); - ex.addProxyObject(offering, offering.getId(), "offeringId"); + // see networkOfferingVO.java + CloudRuntimeException ex = new CloudRuntimeException("Unable to convert network offering with specified id to network profile"); + ex.addProxyObject(offering, offering.getId(), "offeringId"); throw ex; } @@ -1811,7 +1812,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } deviceId = vmNicPair.second(); - + int devId = vmNic.getDeviceId(); if (devId > deviceIds.length) { throw new IllegalArgumentException("Device id for nic is too large: " + vmNic); @@ -1825,14 +1826,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (vmNic.isDefaultNic()) { if (defaultNic != null) { throw new IllegalArgumentException("You cannot specify two nics as default nics: nic 1 = " + - defaultNic + "; nic 2 = " + vmNic); + defaultNic + "; nic 2 = " + vmNic); } defaultNic = vmNic; } - + nics.add(vmNic); vm.addNic(vmNic); - + } if (nics.size() != networks.size()) { @@ -1847,13 +1848,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag txn.commit(); } - + @DB @Override public Pair allocateNic(NicProfile requested, Network network, Boolean isDefaultNic, int deviceId, VirtualMachineProfile vm) throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException, ConcurrentOperationException{ - + NetworkVO ntwkVO = _networksDao.findById(network.getId()); s_logger.debug("Allocating nic for vm " + vm.getVirtualMachine() + " in network " + network); NetworkGuru guru = _networkGurus.get(ntwkVO.getGuruName()); @@ -1881,12 +1882,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag deviceId = applyProfileToNic(vo, profile, deviceId); vo = _nicDao.persist(vo); - + Integer networkRate = getNetworkRate(network.getId(), vm.getId()); NicProfile vmNic = new NicProfile(vo, network, vo.getBroadcastUri(), vo.getIsolationUri(), networkRate, isSecurityGroupSupportedInNetwork(network), getNetworkTag(vm.getHypervisorType(), - network)); - + network)); + return new Pair(vmNic, Integer.valueOf(deviceId)); } @@ -1988,10 +1989,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag NetworkVO network = _networksDao.acquireInLockTable(networkId, _networkLockTimeout); if (network == null) { - // see NetworkVO.java - ConcurrentOperationException ex = new ConcurrentOperationException("Unable to acquire network configuration"); - ex.addProxyObject("networks", networkId, "networkId"); - throw ex; + // see NetworkVO.java + ConcurrentOperationException ex = new ConcurrentOperationException("Unable to acquire network configuration"); + ex.addProxyObject("networks", networkId, "networkId"); + throw ex; } try { @@ -2047,7 +2048,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag private void implementNetworkElementsAndResources(DeployDestination dest, ReservationContext context, NetworkVO network, NetworkOfferingVO offering) - throws ConcurrentOperationException, InsufficientAddressCapacityException, ResourceUnavailableException, InsufficientCapacityException { + throws ConcurrentOperationException, InsufficientAddressCapacityException, ResourceUnavailableException, InsufficientCapacityException { // If this is a 1) guest virtual network 2) network has sourceNat service 3) network offering does not support a // Shared source NAT rule, // associate a source NAT IP (if one isn't already associated with the network) @@ -2057,7 +2058,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (network.getGuestType() == Network.GuestType.Isolated && areServicesSupportedInNetwork(network.getId(), Service.SourceNat) && !sharedSourceNat) { - + List ips = null; Vpc vpc = null; if (network.getVpcId() != null) { @@ -2066,7 +2067,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } else { ips = _ipAddressDao.listByAssociatedNetwork(network.getId(), true); } - + if (ips.isEmpty()) { String target = vpc != null ? vpc.toString() : network.toString(); @@ -2085,18 +2086,18 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag for (NetworkElement element : _networkElements) { if (providersToImplement.contains(element.getProvider())) { if (!isProviderEnabledInPhysicalNetwork(getPhysicalNetworkId(network), "VirtualRouter")) { - // The physicalNetworkId will not get translated into a uuid by the reponse serializer, - // because the serializer would look up the NetworkVO class's table and retrieve the - // network id instead of the physical network id. - // So just throw this exception as is. We may need to TBD by changing the serializer. - throw new CloudRuntimeException("Service provider " + element.getProvider().getName() + "either doesn't exist or is not enabled in physical network id: " + network.getPhysicalNetworkId()); + // The physicalNetworkId will not get translated into a uuid by the reponse serializer, + // because the serializer would look up the NetworkVO class's table and retrieve the + // network id instead of the physical network id. + // So just throw this exception as is. We may need to TBD by changing the serializer. + throw new CloudRuntimeException("Service provider " + element.getProvider().getName() + "either doesn't exist or is not enabled in physical network id: " + network.getPhysicalNetworkId()); } if (s_logger.isDebugEnabled()) { s_logger.debug("Asking " + element.getName() + " to implemenet " + network); } if (!element.implement(network, offering, dest, context)) { - CloudRuntimeException ex = new CloudRuntimeException("Failed to implement provider " + element.getProvider().getName() + " for network with specified id"); - ex.addProxyObject(network, network.getId(), "networkId"); + CloudRuntimeException ex = new CloudRuntimeException("Failed to implement provider " + element.getProvider().getName() + " for network with specified id"); + ex.addProxyObject(network, network.getId(), "networkId"); throw ex; } } @@ -2148,13 +2149,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (nic.getVmType() == VirtualMachine.Type.User || (nic.getVmType() == VirtualMachine.Type.DomainRouter && getNetwork(networkId).getTrafficType() == TrafficType.Guest)) { _networksDao.setCheckForGc(networkId); } - + txn.commit(); } @Override public void prepare(VirtualMachineProfile vmProfile, DeployDestination dest, ReservationContext context) throws InsufficientCapacityException, - ConcurrentOperationException, ResourceUnavailableException { + ConcurrentOperationException, ResourceUnavailableException { List nics = _nicDao.listByVmId(vmProfile.getId()); // we have to implement default nics first - to ensure that default network elements start up first in multiple @@ -2172,7 +2173,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag for (NicVO nic : nics) { Pair implemented = implementNetwork(nic.getNetworkId(), dest, context); - + NetworkVO network = implemented.second(); NicProfile profile = prepareNic(vmProfile, dest, context, nic.getId(), network); vmProfile.addNic(profile); @@ -2182,13 +2183,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override public NicProfile prepareNic(VirtualMachineProfile vmProfile, DeployDestination dest, ReservationContext context, long nicId, NetworkVO network) - throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException, - ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { - - Integer networkRate = getNetworkRate(network.getId(), vmProfile.getId()); + throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException, + ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { + + Integer networkRate = getNetworkRate(network.getId(), vmProfile.getId()); NetworkGuru guru = _networkGurus.get(network.getGuruName()); NicVO nic = _nicDao.findById(nicId); - + NicProfile profile = null; if (nic.getReservationStrategy() == Nic.ReservationStrategy.Start) { nic.setState(Nic.State.Reserving); @@ -2202,7 +2203,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag URI isolationUri = nic.getIsolationUri(); profile = new NicProfile(nic, network, broadcastUri, isolationUri, - networkRate, isSecurityGroupSupportedInNetwork(network), getNetworkTag(vmProfile.getHypervisorType(), network)); + networkRate, isSecurityGroupSupportedInNetwork(network), getNetworkTag(vmProfile.getHypervisorType(), network)); guru.reserve(profile, network, vmProfile, dest, context); nic.setIp4Address(profile.getIp4Address()); nic.setAddressFormat(profile.getFormat()); @@ -2222,7 +2223,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag updateNic(nic, network.getId(), 1); } else { profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), - networkRate, isSecurityGroupSupportedInNetwork(network), getNetworkTag(vmProfile.getHypervisorType(), network)); + networkRate, isSecurityGroupSupportedInNetwork(network), getNetworkTag(vmProfile.getHypervisorType(), network)); guru.updateNicProfile(profile, network); nic.setState(Nic.State.Reserved); updateNic(nic, network.getId(), 1); @@ -2257,26 +2258,26 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override public void release(VirtualMachineProfile vmProfile, boolean forced) throws - ConcurrentOperationException, ResourceUnavailableException { + ConcurrentOperationException, ResourceUnavailableException { List nics = _nicDao.listByVmId(vmProfile.getId()); for (NicVO nic : nics) { NetworkVO network = _networksDao.findById(nic.getNetworkId()); releaseNic(vmProfile, nic, network); } } - + @Override public NicProfile releaseNic(VirtualMachineProfile vmProfile, NetworkVO network) throws ConcurrentOperationException, ResourceUnavailableException { NicVO nic = _nicDao.findByInstanceIdAndNetworkId(network.getId(), vmProfile.getId()); releaseNic(vmProfile, nic, network); - + NicProfile profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), null, isSecurityGroupSupportedInNetwork(network), getNetworkTag(vmProfile.getVirtualMachine().getHypervisorType(), network)); return profile; } - - + + @Override public NicProfile releaseNic(VirtualMachineProfile vmProfile, NetworkVO network, URI broadcastUri) throws ConcurrentOperationException, ResourceUnavailableException { @@ -2287,7 +2288,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag nic = _nicDao.findByInstanceIdAndNetworkId(network.getId(), vmProfile.getId()); } releaseNic(vmProfile, nic, network); - + NicProfile profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), null, isSecurityGroupSupportedInNetwork(network), getNetworkTag(vmProfile.getVirtualMachine().getHypervisorType(), network)); return profile; @@ -2296,39 +2297,39 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag protected void releaseNic(VirtualMachineProfile vmProfile, NicVO nic, NetworkVO network) throws ConcurrentOperationException, ResourceUnavailableException { - if (nic.getState() == Nic.State.Reserved || nic.getState() == Nic.State.Reserving) { - Nic.State originalState = nic.getState(); - if (nic.getReservationStrategy() == Nic.ReservationStrategy.Start) { - NetworkGuru guru = _networkGurus.get(network.getGuruName()); - nic.setState(Nic.State.Releasing); - _nicDao.update(nic.getId(), nic); + if (nic.getState() == Nic.State.Reserved || nic.getState() == Nic.State.Reserving) { + Nic.State originalState = nic.getState(); + if (nic.getReservationStrategy() == Nic.ReservationStrategy.Start) { + NetworkGuru guru = _networkGurus.get(network.getGuruName()); + nic.setState(Nic.State.Releasing); + _nicDao.update(nic.getId(), nic); NicProfile profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), null, isSecurityGroupSupportedInNetwork(network), getNetworkTag(vmProfile.getHypervisorType(), network)); - if (guru.release(profile, vmProfile, nic.getReservationId())) { - applyProfileToNicForRelease(nic, profile); - nic.setState(Nic.State.Allocated); - if (originalState == Nic.State.Reserved) { - updateNic(nic, network.getId(), -1); - } else { - _nicDao.update(nic.getId(), nic); - } - } - // Perform release on network elements - for (NetworkElement element : _networkElements) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Asking " + element.getName() + " to release " + nic); - } - //NOTE: Context appear to never be used in release method - //implementations. Consider removing it from interface Element - element.release(network, profile, vmProfile, null); - } - - } else { + if (guru.release(profile, vmProfile, nic.getReservationId())) { + applyProfileToNicForRelease(nic, profile); nic.setState(Nic.State.Allocated); - updateNic(nic, network.getId(), -1); + if (originalState == Nic.State.Reserved) { + updateNic(nic, network.getId(), -1); + } else { + _nicDao.update(nic.getId(), nic); + } } + // Perform release on network elements + for (NetworkElement element : _networkElements) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Asking " + element.getName() + " to release " + nic); + } + //NOTE: Context appear to never be used in release method + //implementations. Consider removing it from interface Element + element.release(network, profile, vmProfile, null); + } + + } else { + nic.setState(Nic.State.Allocated); + updateNic(nic, network.getId(), -1); } } + } @Override public List getNics(long vmId) { @@ -2360,12 +2361,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag NicVO nic = _nicDao.findByInstanceIdAndNetworkId(networkId, vm.getId()); NetworkVO network = _networksDao.findById(networkId); Integer networkRate = getNetworkRate(network.getId(), vm.getId()); - + NetworkGuru guru = _networkGurus.get(network.getGuruName()); NicProfile profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), networkRate, isSecurityGroupSupportedInNetwork(network), getNetworkTag(vm.getHypervisorType(), network)); guru.updateNicProfile(profile, network); - + return profile; } @@ -2379,7 +2380,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Verify input parameters IPAddressVO ipVO = _ipAddressDao.findById(ipAddressId); if (ipVO == null) { - throw new InvalidParameterValueException("Unable to find ip address by id"); + throw new InvalidParameterValueException("Unable to find ip address by id", null); } if (ipVO.getAllocatedTime() == null) { @@ -2403,21 +2404,21 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Check for account wide pool. It will have an entry for account_vlan_map. if (_accountVlanMapDao.findAccountVlanMap(ipVO.getAllocatedToAccountId(), ipVO.getVlanId()) != null) { - //see IPaddressVO.java - InvalidParameterValueException ex = new InvalidParameterValueException("Sepcified IP address uuid belongs to Account wide IP pool and cannot be disassociated"); - ex.addProxyObject(ipVO, ipVO.getId(), "systemIpAddrId"); - throw ex; + //see IPaddressVO.java + List idList = new ArrayList(); + idList.add(new IdentityProxy(ipVO, ipVO.getId(), "systemIpAddrId")); + throw new InvalidParameterValueException("Sepcified IP address uuid belongs to Account wide IP pool and cannot be disassociated", idList); } // don't allow releasing system ip address if (ipVO.getSystem()) { - InvalidParameterValueException ex = new InvalidParameterValueException("Can't release system IP address with specified id"); - ex.addProxyObject(ipVO, ipVO.getId(), "systemIpAddrId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy(ipVO, ipVO.getId(), "systemIpAddrId")); + throw new InvalidParameterValueException("Can't release system IP address with specified id", idList); } boolean success = disassociatePublicIpAddress(ipAddressId, userId, caller); - + Long networkId = ipVO.getAssociatedWithNetworkId(); if (success && networkId != null) { Network guestNetwork = getNetwork(networkId); @@ -2454,7 +2455,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public String getNextAvailableMacAddressInNetwork(long networkId) throws InsufficientAddressCapacityException { String mac = _networksDao.getNextAvailableMacAddress(networkId); if (mac == null) { - throw new InsufficientAddressCapacityException("Unable to create another mac address", Network.class, networkId); + throw new InsufficientAddressCapacityException("Unable to create another mac address", Network.class, networkId); } return mac; } @@ -2502,7 +2503,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag removeNic(vm, nic); } } - + @Override public void removeNic(VirtualMachineProfile vm, Network network) { NicVO nic = _nicDao.findByInstanceIdAndNetworkId(network.getId(), vm.getVirtualMachine().getId()); @@ -2510,14 +2511,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } protected void removeNic(VirtualMachineProfile vm, NicVO nic) { - nic.setState(Nic.State.Deallocating); - _nicDao.update(nic.getId(), nic); - NetworkVO network = _networksDao.findById(nic.getNetworkId()); + nic.setState(Nic.State.Deallocating); + _nicDao.update(nic.getId(), nic); + NetworkVO network = _networksDao.findById(nic.getNetworkId()); NicProfile profile = new NicProfile(nic, network, null, null, null, isSecurityGroupSupportedInNetwork(network), getNetworkTag(vm.getHypervisorType(), network)); - NetworkGuru guru = _networkGurus.get(network.getGuruName()); - guru.deallocate(network, profile, vm); - _nicDao.remove(nic.getId()); + NetworkGuru guru = _networkGurus.get(network.getGuruName()); + guru.deallocate(network, profile, vm); + _nicDao.remove(nic.getId()); s_logger.debug("Removed nic id=" + nic.getId()); } @@ -2547,7 +2548,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (cidr == null) { return; } - List networks = _networksDao.listByZone((long) zoneId); + List networks = _networksDao.listByZone(zoneId); Map networkToCidr = new HashMap(); for (NetworkVO network : networks) { if (network.getGuestType() != GuestType.Isolated) { @@ -2564,9 +2565,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag for (long networkId : networkToCidr.keySet()) { String ntwkCidr = networkToCidr.get(networkId); if (NetUtils.isNetworksOverlap(ntwkCidr, cidr)) { - InvalidParameterValueException ex = new InvalidParameterValueException("Warning: The specified existing network has conflict CIDR subnets with new network!"); - ex.addProxyObject("networks", networkId, "networkId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy("networks", networkId, "networkId")); + throw new InvalidParameterValueException("Warning: The specified existing network has conflict CIDR subnets with new network!", idList); } } } @@ -2595,21 +2596,22 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Validate network offering NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId); - if (ntwkOff == null || ntwkOff.isSystemOnly()) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find network offering by specified id"); - if (ntwkOff != null) { - ex.addProxyObject(ntwkOff, networkOfferingId, "networkOfferingId"); - throw ex; - } - throw ex; + if (ntwkOff == null) { + throw new InvalidParameterValueException("Unable to find network offering by specified id", null); } + if (ntwkOff.isSystemOnly()) { + List idList = new ArrayList(); + idList.add(new IdentityProxy(ntwkOff, networkOfferingId, "networkOfferingId")); + throw new InvalidParameterValueException("Network offering with specified id is System-only", idList); + } + // 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"); + throw new InvalidParameterValueException("Unable to find a physical network having the specified physical network id", null); } } @@ -2619,13 +2621,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag DataCenter zone = _dcDao.findById(zoneId); if (zone == null) { - throw new InvalidParameterValueException("Specified zone id was not found"); + throw new InvalidParameterValueException("Specified zone id was not found", null); } - + if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getType())) { - // See DataCenterVO.java - PermissionDeniedException ex = new PermissionDeniedException("Cannot perform this operation since specified Zone is currently disabled"); - ex.addProxyObject(zone, zoneId, "zoneId"); + // See DataCenterVO.java + PermissionDeniedException ex = new PermissionDeniedException("Cannot perform this operation since specified Zone is currently disabled"); + ex.addProxyObject(zone, zoneId, "zoneId"); throw ex; } @@ -2633,7 +2635,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (vpcId != null) { Vpc vpc = _vpcMgr.getActiveVpc(vpcId); if (vpc == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find Enabled VPC "); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find Enabled VPC ", null); ex.addProxyObject("vpc", vpcId, "VPC"); throw ex; } @@ -2648,17 +2650,17 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } else if (aclTypeStr.equalsIgnoreCase(ACLType.Domain.toString())) { aclType = ACLType.Domain; } else { - throw new InvalidParameterValueException("Incorrect aclType specified. Check the API documentation for supported types"); + throw new InvalidParameterValueException("Incorrect aclType specified. Check the API documentation for supported types", null); } // In 3.0 all Shared networks should have aclType == Domain, all Isolated networks aclType==Account if (ntwkOff.getGuestType() == GuestType.Isolated) { if (aclType != ACLType.Account) { - throw new InvalidParameterValueException("AclType should be " + ACLType.Account + " for network of type " + Network.GuestType.Isolated); + throw new InvalidParameterValueException("AclType should be " + ACLType.Account + " for network of type " + Network.GuestType.Isolated, null); } } else if (ntwkOff.getGuestType() == GuestType.Shared) { if (!(aclType == ACLType.Domain || aclType == ACLType.Account)) { throw new InvalidParameterValueException("AclType should be " + ACLType.Domain + " or " + - ACLType.Account + " for network of type " + Network.GuestType.Shared); + ACLType.Account + " for network of type " + Network.GuestType.Shared, null); } } } else { @@ -2671,7 +2673,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Only Admin can create Shared networks if (ntwkOff.getGuestType() == GuestType.Shared && !_accountMgr.isAdmin(caller.getType())) { - throw new InvalidParameterValueException("Only Admins can create network with guest type " + GuestType.Shared); + throw new InvalidParameterValueException("Only Admins can create network with guest type " + GuestType.Shared, null); } // Check if the network is domain specific @@ -2683,25 +2685,25 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // only shared networks can be Domain specific if (ntwkOff.getGuestType() != GuestType.Shared) { - throw new InvalidParameterValueException("Only " + GuestType.Shared + " networks can have aclType=" + ACLType.Domain); + throw new InvalidParameterValueException("Only " + GuestType.Shared + " networks can have aclType=" + ACLType.Domain, null); } if (domainId != null) { if (ntwkOff.getTrafficType() != TrafficType.Guest || ntwkOff.getGuestType() != Network.GuestType.Shared) { throw new InvalidParameterValueException("Domain level networks are supported just for traffic type " - + TrafficType.Guest + " and guest type " + Network.GuestType.Shared); + + TrafficType.Guest + " and guest type " + Network.GuestType.Shared, null); } DomainVO domain = _domainDao.findById(domainId); if (domain == null) { - throw new InvalidParameterValueException("Unable to find domain by specified id"); + throw new InvalidParameterValueException("Unable to find domain by specified id", null); } _accountMgr.checkAccess(caller, domain); } isDomainSpecific = true; } else if (subdomainAccess != null) { - throw new InvalidParameterValueException("Parameter subDomainAccess can be specified only with aclType=Domain"); + throw new InvalidParameterValueException("Parameter subDomainAccess can be specified only with aclType=Domain", null); } Account owner = null; if ((cmd.getAccountName() != null && domainId != null) || cmd.getProjectId() != null) { @@ -2716,28 +2718,28 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // if end ip is not specified, default it to startIp if (startIP != null) { if (!NetUtils.isValidIp(startIP)) { - throw new InvalidParameterValueException("Invalid format for the startIp parameter"); + throw new InvalidParameterValueException("Invalid format for the startIp parameter", null); } if (endIP == null) { endIP = startIP; } else if (!NetUtils.isValidIp(endIP)) { - throw new InvalidParameterValueException("Invalid format for the endIp parameter"); + throw new InvalidParameterValueException("Invalid format for the endIp parameter", null); } } if (startIP != null && endIP != null) { if (!(gateway != null && netmask != null)) { - throw new InvalidParameterValueException("gateway and netmask should be defined when startIP/endIP are passed in"); + throw new InvalidParameterValueException("gateway and netmask should be defined when startIP/endIP are passed in", null); } } String cidr = null; if (gateway != null && netmask != null) { if (!NetUtils.isValidIp(gateway)) { - throw new InvalidParameterValueException("Invalid gateway"); + throw new InvalidParameterValueException("Invalid gateway", null); } if (!NetUtils.isValidNetmask(netmask)) { - throw new InvalidParameterValueException("Invalid netmask"); + throw new InvalidParameterValueException("Invalid netmask", null); } cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask); @@ -2746,15 +2748,15 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Regular user can create Guest Isolated Source Nat enabled network only if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL && (ntwkOff.getTrafficType() != TrafficType.Guest || ntwkOff.getGuestType() != Network.GuestType.Isolated - && areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) { + && areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) { throw new InvalidParameterValueException("Regular user can create a network only from the network" + - " offering having traffic type " + TrafficType.Guest + " and network type " - + Network.GuestType.Isolated + " with a service " + Service.SourceNat.getName() + " enabled"); + " offering having traffic type " + TrafficType.Guest + " and network type " + + Network.GuestType.Isolated + " with a service " + Service.SourceNat.getName() + " enabled", null); } // Don't allow to specify vlan if the caller is a regular user if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL && (ntwkOff.getSpecifyVlan() || vlanId != null)) { - throw new InvalidParameterValueException("Regular user is not allowed to specify vlanId"); + throw new InvalidParameterValueException("Regular user is not allowed to specify vlanId", null); } // For non-root admins check cidr limit - if it's allowed by global config value @@ -2764,12 +2766,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag int cidrSize = Integer.valueOf(cidrPair[1]); if (cidrSize < _cidrLimit) { - throw new InvalidParameterValueException("Cidr size can't be less than " + _cidrLimit); + throw new InvalidParameterValueException("Cidr size can't be less than " + _cidrLimit, null); } } if (cidr != null && networkOfferingIsConfiguredForExternalNetworking(networkOfferingId)) { - throw new InvalidParameterValueException("Cannot specify CIDR when using network offering with external devices!"); + throw new InvalidParameterValueException("Cannot specify CIDR when using network offering with external devices!", null); } // Vlan is created in 2 cases - works in Advance zone only: @@ -2777,14 +2779,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // 2) GuestType is Isolated, but SourceNat service is disabled boolean createVlan = (startIP != null && endIP != null && zone.getNetworkType() == NetworkType.Advanced && ((ntwkOff.getGuestType() == Network.GuestType.Shared) - || (ntwkOff.getGuestType() == GuestType.Isolated && - !areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)))); + || (ntwkOff.getGuestType() == GuestType.Isolated && + !areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)))); // Can add vlan range only to the network which allows it if (createVlan && !ntwkOff.getSpecifyIpRanges()) { - InvalidParameterValueException ex = new InvalidParameterValueException("Network offering with specified id doesn't support adding multiple ip ranges"); - ex.addProxyObject(ntwkOff, ntwkOff.getId(), "networkOfferingId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy(ntwkOff, ntwkOff.getId(), "networkOfferingId")); + throw new InvalidParameterValueException("Network offering with specified id doesn't support adding multiple ip ranges", idList); } Transaction txn = Transaction.currentTxn(); @@ -2809,13 +2811,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag Network network = null; if (vpcId != null) { if (!_configMgr.isOfferingForVpc(ntwkOff)){ - throw new InvalidParameterValueException("Network offering can't be used for VPC networks"); + throw new InvalidParameterValueException("Network offering can't be used for VPC networks", null); } network = createVpcGuestNetwork(networkOfferingId, name, displayText, gateway, cidr, vlanId, networkDomain, owner, sharedDomainId, pNtwk, zoneId, aclType, subdomainAccess, vpcId); } else { if (_configMgr.isOfferingForVpc(ntwkOff)){ - throw new InvalidParameterValueException("Network offering can be used for VPC networks only"); + throw new InvalidParameterValueException("Network offering can be used for VPC networks only", null); } network = createGuestNetwork(networkOfferingId, name, displayText, gateway, cidr, vlanId, networkDomain, owner, sharedDomainId, pNtwk, zoneId, aclType, subdomainAccess, vpcId); @@ -2837,18 +2839,18 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag String cidr, String vlanId, String networkDomain, Account owner, Long domainId, PhysicalNetwork pNtwk, long zoneId, ACLType aclType, Boolean subdomainAccess, long vpcId) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException { - + Vpc vpc = _vpcMgr.getActiveVpc(vpcId); if (networkDomain == null) { networkDomain = vpc.getNetworkDomain(); } //1) Validate if network can be created for VPC _vpcMgr.validateGuestNtkwForVpc(_configMgr.getNetworkOffering(ntwkOffId), cidr, networkDomain, owner, vpc, null); - + //2) Create network Network guestNetwork = createGuestNetwork(ntwkOffId, name, displayText, gateway, cidr, vlanId, networkDomain, owner, domainId, pNtwk, zoneId, aclType, subdomainAccess, vpcId); - + return guestNetwork; } @@ -2865,7 +2867,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.warn("Only guest networks can be created using this method"); return null; } - + boolean updateResourceCount = (!ntwkOff.getSpecifyVlan() && aclType == ACLType.Account); //check resource limits if (updateResourceCount) { @@ -2874,19 +2876,19 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Validate network offering if (ntwkOff.getState() != NetworkOffering.State.Enabled) { - // see NetworkOfferingVO - InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its stat is not " + NetworkOffering.State.Enabled); - ex.addProxyObject(ntwkOff, ntwkOff.getId(), "networkOfferingId"); - throw ex; + // see NetworkOfferingVO + List idList = new ArrayList(); + idList.add(new IdentityProxy(ntwkOff, networkOfferingId, "networkOfferingId")); + throw new InvalidParameterValueException("Can't use specified network offering id as its stat is not " + NetworkOffering.State.Enabled, idList); } // Validate physical network if (pNtwk.getState() != PhysicalNetwork.State.Enabled) { - // see PhysicalNetworkVO.java - InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + - " in incorrect state:" + pNtwk.getState()); - ex.addProxyObject("physical_network", pNtwk.getId(), "physicalNetworkId"); - throw ex; + // see PhysicalNetworkVO.java + List idList = new ArrayList(); + idList.add(new IdentityProxy("physical_network", pNtwk.getId(), "physicalNetworkId")); + throw new InvalidParameterValueException("Specified physical network id is" + + " in incorrect state:" + pNtwk.getState(), idList); } // Validate zone @@ -2894,33 +2896,33 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (zone.getNetworkType() == NetworkType.Basic) { // In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true if (aclType == null || aclType != ACLType.Domain) { - throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone"); + throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone", null); } - + // Only one guest network is supported in Basic zone List guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest); if (!guestNetworks.isEmpty()) { throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " - + NetworkType.Basic); + + NetworkType.Basic, null); } // if zone is basic, only Shared network offerings w/o source nat service are allowed if (!(ntwkOff.getGuestType() == GuestType.Shared && !areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) { throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + - "guestType " + GuestType.Shared + " with disabled " + Service.SourceNat.getName() - + " service are allowed"); + "guestType " + GuestType.Shared + " with disabled " + Service.SourceNat.getName() + + " service are allowed", null); } if (domainId == null || domainId != Domain.ROOT_DOMAIN) { - throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain"); + throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain", null); } if (subdomainAccess == null) { subdomainAccess = true; } else if (!subdomainAccess) { throw new InvalidParameterValueException("Subdomain access should be set to true for the" + - " guest network in the Basic zone"); + " guest network in the Basic zone", null); } if (vlanId == null) { @@ -2928,7 +2930,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } else { if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) { throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + - "the zone of type " + NetworkType.Basic); + "the zone of type " + NetworkType.Basic, null); } } @@ -2940,7 +2942,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag && !areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)); if (!allowCreation) { throw new InvalidParameterValueException("Only Account specific Isolated network with sourceNat " + - "service disabled are allowed in security group enabled zone"); + "service disabled are allowed in security group enabled zone", null); } } } @@ -2949,9 +2951,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag boolean vlanSpecified = (vlanId != null); if (vlanSpecified != ntwkOff.getSpecifyVlan()) { if (vlanSpecified) { - throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false"); + throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false", null); } else { - throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true"); + throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true", null); } } @@ -2960,17 +2962,23 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // For Isolated networks, don't allow to create network with vlan that already exists in the zone if (ntwkOff.getGuestType() == GuestType.Isolated) { if (_networksDao.countByZoneAndUri(zoneId, uri) > 0) { - throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists in zone " + zoneId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("vlan", Long.valueOf(vlanId), "vlanId")); + idList.add(new IdentityProxy("data_center", zoneId, "zoneId")); + throw new InvalidParameterValueException("Network with vlan of specified id already exists in zone with specified id", idList); } } else { //don't allow to create Shared network with Vlan that already exists in the zone for Isolated networks + List idList = new ArrayList(); + idList.add(new IdentityProxy("vlan", Long.valueOf(vlanId), "vlanId")); + idList.add(new IdentityProxy("data_center", zoneId, "zoneId")); if (_networksDao.countByZoneUriAndGuestType(zoneId, uri, GuestType.Isolated) > 0) { - throw new InvalidParameterValueException("Isolated network with vlan " + vlanId + " already exists " + - "in zone " + zoneId); + throw new InvalidParameterValueException("Isolated network with vlan of specified id already exists " + + "in zone with specified id", idList); } } } - + // If networkDomain is not specified, take it from the global configuration if (areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) { Map dnsCapabilities = getNetworkOfferingServiceCapabilities @@ -2978,8 +2986,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification); if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) { if (networkDomain != null) { - throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" - + networkOfferingId + " in zone id=" + zoneId); + List idList = new ArrayList(); + idList.add(new IdentityProxy(ntwkOff, networkOfferingId, "networkOfferingId")); + idList.add(new IdentityProxy("data_center", zoneId, "zoneId")); + throw new InvalidParameterValueException("Domain name change is not supported by network offering of specified id in zone with specified id", idList); } } else { if (networkDomain == null) { @@ -3000,8 +3010,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (!NetUtils.verifyDomainName(networkDomain)) { throw new InvalidParameterValueException( "Invalid network domain. Total length shouldn't exceed 190 chars. Each domain " + - "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " - + "and the hyphen ('-'); can't start or end with \"-\""); + "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " + + "and the hyphen ('-'); can't start or end with \"-\"", null); } } } @@ -3015,19 +3025,19 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag && !areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))); if (cidr == null && cidrRequired) { throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + - " type " + Network.GuestType.Shared + " and network of type " + GuestType.Isolated + " with service " - + Service.SourceNat.getName() + " disabled"); + " type " + Network.GuestType.Shared + " and network of type " + GuestType.Isolated + " with service " + + Service.SourceNat.getName() + " disabled", null); } // No cidr can be specified in Basic zone if (zone.getNetworkType() == NetworkType.Basic && cidr != null) { - throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic); + throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic, null); } // Check if cidr is RFC1918 compliant if the network is Guest Isolated if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) { if (!NetUtils.validateGuestCidr(cidr)) { - throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC1918 compliant"); + throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC1918 compliant", null); } } @@ -3077,7 +3087,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag network = networks.get(0); } } - + if (updateResourceCount) { _resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network); } @@ -3120,22 +3130,22 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Account/domainId parameters and isSystem are mutually exclusive if (isSystem != null && isSystem && (accountName != null || domainId != null)) { - throw new InvalidParameterValueException("System network belongs to system, account and domainId parameters can't be specified"); + throw new InvalidParameterValueException("System network belongs to system, account and domainId parameters can't be specified", null); } if (domainId != null) { DomainVO domain = _domainDao.findById(domainId); if (domain == null) { - // see DomainVO.java - throw new InvalidParameterValueException("Specified domain id doesn't exist in the system"); + // see DomainVO.java + throw new InvalidParameterValueException("Specified domain id doesn't exist in the system", null); } _accountMgr.checkAccess(caller, domain); if (accountName != null) { Account owner = _accountMgr.getActiveAccountByName(accountName, domainId); if (owner == null) { - // see DomainVO.java - throw new InvalidParameterValueException("Unable to find account " + accountName + " in specified domain"); + // see DomainVO.java + throw new InvalidParameterValueException("Unable to find account " + accountName + " in specified domain", null); } _accountMgr.checkAccess(caller, null, true, owner); @@ -3161,13 +3171,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag permittedAccounts.clear(); Project project = _projectMgr.getProject(projectId); if (project == null) { - throw new InvalidParameterValueException("Unable to find project by specified id"); + throw new InvalidParameterValueException("Unable to find project by specified id", null); } if (!_projectMgr.canAccessProjectAccount(caller, project.getProjectAccountId())) { - // getProject() returns type ProjectVO. - InvalidParameterValueException ex = new InvalidParameterValueException("Account " + caller + " cannot access specified project id"); - ex.addProxyObject(project, projectId, "projectId"); - throw ex; + // getProject() returns type ProjectVO. + List idList = new ArrayList(); + idList.add(new IdentityProxy(project, projectId, "projectId")); + throw new InvalidParameterValueException("Account " + caller + " cannot access specified project id", idList); } permittedAccounts.add(project.getProjectAccountId()); } @@ -3194,7 +3204,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag zoneSearch.and("networkType", zoneSearch.entity().getNetworkType(), SearchCriteria.Op.EQ); sb.join("zoneSearch", zoneSearch, sb.entity().getDataCenterId(), zoneSearch.entity().getId(), JoinBuilder.JoinType.INNER); sb.and("removed", sb.entity().getRemoved(), Op.NULL); - + if (tags != null && !tags.isEmpty()) { SearchBuilder tagSearch = _resourceTagDao.createSearchBuilder(); for (int count=0; count < tags.size(); count++) { @@ -3225,9 +3235,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Get domain level networks if (domainId != null) { networksToReturn - .addAll(listDomainLevelNetworks( - buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, - physicalNetworkId, aclType, skipProjectNetworks, restartRequired, specifyIpRanges, vpcId, tags), searchFilter, + .addAll(listDomainLevelNetworks( + buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, + physicalNetworkId, aclType, skipProjectNetworks, restartRequired, specifyIpRanges, vpcId, tags), searchFilter, domainId)); } @@ -3235,12 +3245,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag networksToReturn.addAll(listAccountSpecificNetworks( buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired, specifyIpRanges, vpcId, tags), searchFilter, - permittedAccounts)); + permittedAccounts)); } else if (domainId == null || listAll) { networksToReturn.addAll(listAccountSpecificNetworksByDomainPath( buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired, specifyIpRanges, vpcId, tags), searchFilter, path, - isRecursive)); + isRecursive)); } } else { networksToReturn = _networksDao.search(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, @@ -3255,7 +3265,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag for (String supportedServiceStr : supportedServicesStr) { Service service = Service.getService(supportedServiceStr); if (service == null) { - throw new InvalidParameterValueException("Invalid service specified " + supportedServiceStr); + throw new InvalidParameterValueException("Invalid service specified " + supportedServiceStr, null); } else { suppportedServices[i] = service; } @@ -3270,7 +3280,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag networksToReturn=supportedNetworks; } - + if (canUseForDeploy != null) { List networksForDeploy = new ArrayList(); for (NetworkVO network : networksToReturn) { @@ -3278,10 +3288,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag networksForDeploy.add(network); } } - + networksToReturn=networksForDeploy; } - + return networksToReturn; } @@ -3296,7 +3306,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } else { hasFreeIps = (getAvailableIps(network, null)).size() > 0; } - + return hasFreeIps; } @@ -3354,7 +3364,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (vpcId != null) { sc.addAnd("vpcId", SearchCriteria.Op.EQ, vpcId); } - + if (tags != null && !tags.isEmpty()) { int count = 0; sc.setJoinParameters("tagSearch", "resourceType", TaggedResourceType.Network.toString()); @@ -3428,18 +3438,17 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Verify network id NetworkVO network = _networksDao.findById(networkId); if (network == null) { - // see NetworkVO.java - - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find network with specified id"); - ex.addProxyObject(network, networkId, "networkId"); - throw ex; + // see NetworkVO.java + List idList = new ArrayList(); + idList.add(new IdentityProxy(network, networkId, "networkId")); + throw new InvalidParameterValueException("unable to find network with specified id", idList); } // don't allow to delete system network if (isNetworkSystem(network)) { - InvalidParameterValueException ex = new InvalidParameterValueException("Network with specified id is system and can't be removed"); - ex.addProxyObject(network, network.getId(), "networkId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy(network, network.getId(), "networkId")); + throw new InvalidParameterValueException("Network with specified id is system and can't be removed", idList); } Account owner = _accountMgr.getAccount(network.getAccountId()); @@ -3457,7 +3466,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @DB public boolean shutdownNetwork(long networkId, ReservationContext context, boolean cleanupElements) { boolean result = false; - + NetworkVO network = _networksDao.lockRow(networkId, true); if (network == null) { s_logger.debug("Unable to find network with id: " + networkId); @@ -3575,7 +3584,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return false; } } - + //In Basic zone, make sure that there are no non-removed console proxies and SSVMs using the network DataCenter zone = _configMgr.getZone(network.getDataCenterId()); if (zone.getNetworkType() == NetworkType.Basic) { @@ -3659,7 +3668,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } protected boolean deleteVlansInNetwork(long networkId, long userId, Account callerAccount) { - + //cleanup Public vlans List publicVlans = _vlanDao.listVlansByNetworkId(networkId); boolean result = true; @@ -3669,7 +3678,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag result = false; } } - + //cleanup private vlans int privateIpAllocCount = _privateIpDao.countAllocatedByNetworkId(networkId); if (privateIpAllocCount > 0) { @@ -3735,7 +3744,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag Provider provider = Network.Provider.getProvider(ne.getName()); if (provider == null) { if (ne.getName().equalsIgnoreCase("Ovs") || ne.getName().equalsIgnoreCase("BareMetal") - || ne.getName().equalsIgnoreCase("CiscoNexus1000vVSM")) { + || ne.getName().equalsIgnoreCase("CiscoNexus1000vVSM")) { continue; } throw new CloudRuntimeException("Unable to identify the provider by name " + ne.getName()); @@ -3860,21 +3869,19 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Check if network exists NetworkVO network = _networksDao.findById(networkId); - if (network == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Network with specified id doesn't exist"); - ex.addProxyObject("networks", networkId, "networkId"); - throw ex; + if (network == null) { + throw new InvalidParameterValueException("Couldn't find network by id", null); } // Don't allow to restart network if it's not in Implemented/Setup state if (!(network.getState() == Network.State.Implemented || network.getState() == Network.State.Setup)) { - throw new InvalidParameterValueException("Network is not in the right state to be restarted. Correct states are: " + Network.State.Implemented + ", " + Network.State.Setup); + throw new InvalidParameterValueException("Network is not in the right state to be restarted. Correct states are: " + Network.State.Implemented + ", " + Network.State.Setup, null); } // don't allow clenaup=true for the network in Basic zone DataCenter zone = _configMgr.getZone(network.getDataCenterId()); if (zone.getNetworkType() == NetworkType.Basic && cleanup) { - throw new InvalidParameterValueException("Cleanup can't be true when restart network in Basic zone"); + throw new InvalidParameterValueException("Cleanup can't be true when restart network in Basic zone", null); } _accountMgr.checkAccess(callerAccount, null, true, network); @@ -3896,9 +3903,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Check if network exists NetworkVO network = _networksDao.findById(networkId); if (network == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Network with specified id doesn't exist"); - ex.addProxyObject(network, networkId, "networkId"); - throw ex; + throw new InvalidParameterValueException("Couldn't find network by id", null); } // implement the network @@ -4011,13 +4016,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } } - + //apply network ACLs if (!_networkACLMgr.applyNetworkACLs(networkId, caller)) { s_logger.warn("Failed to reapply network ACLs as a part of of network id=" + networkId + " restart"); success = false; } - + return success; } @@ -4052,8 +4057,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public Map getNetworkServiceCapabilities(long networkId, Service service) { if (!areServicesSupportedInNetwork(networkId, service)) { - // TBD: networkId to uuid. No VO object being passed. So we will need to call - // addProxyObject with hardcoded tablename. Or we should probably look up the correct dao proxy object. + // TBD: networkId to uuid. No VO object being passed. So we will need to call + // addProxyObject with hardcoded tablename. Or we should probably look up the correct dao proxy object. throw new UnsupportedServiceException("Service " + service.getName() + " is not supported in the network id=" + networkId); } @@ -4080,7 +4085,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public Map getNetworkOfferingServiceCapabilities(NetworkOffering offering, Service service) { if (!areServicesSupportedByNetworkOffering(offering.getId(), service)) { - // TBD: We should be sending networkOfferingId and not the offering object itself. + // TBD: We should be sending networkOfferingId and not the offering object itself. throw new UnsupportedServiceException("Service " + service.getName() + " is not supported by the network offering " + offering); } @@ -4089,8 +4094,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // get the Provider for this Service for this offering List providers = _ntwkOfferingSrvcDao.listProvidersForServiceForNetworkOffering(offering.getId(), service); if (providers.isEmpty()) { - // TBD: We should be sending networkOfferingId and not the offering object itself. - throw new InvalidParameterValueException("Service " + service.getName() + " is not supported by the network offering " + offering); + // TBD: We should be sending networkOfferingId and not the offering object itself. + throw new InvalidParameterValueException("Service " + service.getName() + " is not supported by the network offering " + offering, null); } // FIXME - in post 3.0 we are going to support multiple providers for the same service per network offering, so @@ -4105,7 +4110,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag ; if (elementCapabilities == null || !elementCapabilities.containsKey(service)) { - // TBD: We should be sending providerId and not the offering object itself. + // TBD: We should be sending providerId and not the offering object itself. throw new UnsupportedServiceException("Service " + service.getName() + " is not supported by the element=" + element.getName() + " implementing Provider=" + provider); } serviceCapabilities = elementCapabilities.get(service); @@ -4127,13 +4132,15 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } if (networkOfferingId == null) { - throw new InvalidParameterValueException("Unable to find system network offering with traffic type " + trafficType); + throw new InvalidParameterValueException("Unable to find system network offering with traffic type " + trafficType, null); } List networks = _networksDao.listBy(Account.ACCOUNT_ID_SYSTEM, networkOfferingId, zoneId); if (networks == null || networks.isEmpty()) { - // TBD: send uuid instead of zoneId. Hardcode tablename in call to addProxyObject(). - throw new InvalidParameterValueException("Unable to find network with traffic type " + trafficType + " in zone " + zoneId); + // TBD: send uuid instead of zoneId. Hardcode tablename in call to addProxyObject(). + List idList = new ArrayList(); + idList.add(new IdentityProxy("data_center", zoneId, "zoneId")); + throw new InvalidParameterValueException("Unable to find network with traffic type " + trafficType + " in zone with specified id", idList); } return networks.get(0); } @@ -4194,7 +4201,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public String getIpInNetwork(long vmId, long networkId) { Nic guestNic = getNicInNetwork(vmId, networkId); assert (guestNic != null && guestNic.getIp4Address() != null) : "Vm doesn't belong to network associated with " + - "ipAddress or ip4 address is null"; + "ipAddress or ip4 address is null"; return guestNic.getIp4Address(); } @@ -4202,7 +4209,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public String getIpInNetworkIncludingRemoved(long vmId, long networkId) { Nic guestNic = getNicInNetworkIncludingRemoved(vmId, networkId); assert (guestNic != null && guestNic.getIp4Address() != null) : "Vm doesn't belong to network associated with " + - "ipAddress or ip4 address is null"; + "ipAddress or ip4 address is null"; return guestNic.getIp4Address(); } @@ -4217,9 +4224,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag ResourceUnavailableException, ResourceAllocationException { Account owner = _accountMgr.getActiveAccountById(accountId); boolean createNetwork = false; - + if (guestNetwork != null && guestNetwork.getTrafficType() != TrafficType.Guest) { - throw new InvalidParameterValueException("Network " + guestNetwork + " is not of a type " + TrafficType.Guest); + throw new InvalidParameterValueException("Network " + guestNetwork + " is not of a type " + TrafficType.Guest, null); } Transaction txn = Transaction.currentTxn(); @@ -4233,7 +4240,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag guestNetwork = networks.get(0); } else { throw new InvalidParameterValueException("Error, more than 1 Guest Isolated Networks with SourceNAT " + - "service enabled found for this account, cannot assosiate the IP range, please provide the network ID"); + "service enabled found for this account, cannot assosiate the IP range, please provide the network ID", null); } } @@ -4242,13 +4249,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag List requiredOfferings = _networkOfferingDao.listByAvailability(Availability.Required, false); if (requiredOfferings.size() < 1) { throw new CloudRuntimeException("Unable to find network offering with availability=" + - Availability.Required + " to automatically create the network as part of createVlanIpRange"); + Availability.Required + " to automatically create the network as part of createVlanIpRange"); } PhysicalNetwork physicalNetwork = translateZoneIdToPhysicalNetwork(zoneId); - + if (requiredOfferings.get(0).getState() == NetworkOffering.State.Enabled) { s_logger.debug("Creating network for account " + owner + " from the network offering id=" + - requiredOfferings.get(0).getId() + " as a part of createVlanIpRange process"); + requiredOfferings.get(0).getId() + " as a part of createVlanIpRange process"); guestNetwork = createGuestNetwork(requiredOfferings.get(0).getId(), owner.getAccountName() + "-network" , owner.getAccountName() + "-network", null, null, null, null, owner, null, physicalNetwork, zoneId, ACLType.Account, @@ -4256,7 +4263,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (guestNetwork == null) { s_logger.warn("Failed to create default Virtual network for the account " + accountId + "in zone " + zoneId); throw new CloudRuntimeException("Failed to create a Guest Isolated Networks with SourceNAT " + - "service enabled as a part of createVlanIpRange, for the account " + accountId + "in zone " + zoneId); + "service enabled as a part of createVlanIpRange, for the account " + accountId + "in zone " + zoneId); } } else { throw new CloudRuntimeException("Required network offering id=" + requiredOfferings.get(0).getId() @@ -4492,15 +4499,15 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override public List listAllNetworksInAllZonesByType(Network.GuestType type) { - List networks = new ArrayList(); - for (NetworkVO network: _networksDao.listAll()) { - if (!isNetworkSystem(network)) { - networks.add(network); - } - } - return networks; + List networks = new ArrayList(); + for (NetworkVO network: _networksDao.listAll()) { + if (!isNetworkSystem(network)) { + networks.add(network); + } + } + return networks; } - + @DB @Override public IPAddressVO markIpAsUnavailable(long addrId) { @@ -4588,7 +4595,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag VirtualMachine.State.Running, VirtualMachine.State.Migrating, VirtualMachine.State.Stopping); return vms.isEmpty(); } - + @Override @DB @ActionEvent(eventType = EventTypes.EVENT_NETWORK_UPDATE, eventDescription = "updating network", async = true) @@ -4599,28 +4606,29 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // verify input parameters NetworkVO network = _networksDao.findById(networkId); if (network == null) { - // see NetworkVO.java - InvalidParameterValueException ex = new InvalidParameterValueException("Specified network id doesn't exist in the system"); - ex.addProxyObject("networks", networkId, "networkId"); - throw ex; + throw new InvalidParameterValueException("Couldn't find network by id", null); } // don't allow to update network in Destroy state if (network.getState() == Network.State.Destroy) { - throw new InvalidParameterValueException("Don't allow to update network in state " + Network.State.Destroy); + throw new InvalidParameterValueException("Don't allow to update network in state " + Network.State.Destroy, null); } // Don't allow to update system network NetworkOffering offering = _networkOfferingDao.findByIdIncludingRemoved(network.getNetworkOfferingId()); + if (offering == null) { + throw new InvalidParameterValueException("Couldn't find networkOffering by id", null); + } + if (offering.isSystemOnly()) { - throw new InvalidParameterValueException("Can't update system networks"); + throw new InvalidParameterValueException("Can't update system networks", null); } // allow to upgrade only Guest networks if (network.getTrafficType() != Networks.TrafficType.Guest) { - throw new InvalidParameterValueException("Can't allow networks which traffic type is not " + TrafficType.Guest); + throw new InvalidParameterValueException("Can't allow networks which traffic type is not " + TrafficType.Guest, null); } - + _accountMgr.checkAccess(callerAccount, null, true, network); if (name != null) { @@ -4633,28 +4641,30 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // network offering and domain suffix can be updated for Isolated networks only in 3.0 if ((networkOfferingId != null || domainSuffix != null) && network.getGuestType() != GuestType.Isolated) { - throw new InvalidParameterValueException("NetworkOffering and domain suffix upgrade can be perfomed for Isolated networks only"); + throw new InvalidParameterValueException("NetworkOffering and domain suffix upgrade can be perfomed for Isolated networks only", null); } boolean networkOfferingChanged = false; long oldNetworkOfferingId = network.getNetworkOfferingId(); if (networkOfferingId != null) { - NetworkOfferingVO networkOffering = _networkOfferingDao.findById(networkOfferingId); - if (networkOffering == null || networkOffering.isSystemOnly()) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find network offering with specified id"); - ex.addProxyObject(networkOffering, networkOfferingId, "networkOfferingId"); - throw ex; + if (networkOffering == null) { + throw new InvalidParameterValueException("Couldn't find networkOffering by id", null); } - + if (networkOffering.isSystemOnly()) { + List idList = new ArrayList(); + idList.add(new IdentityProxy(networkOffering, networkOfferingId, "networkOfferingId")); + throw new InvalidParameterValueException("NetworkOffering with specified id is System-only", idList); + } + // network offering should be in Enabled state if (networkOffering.getState() != NetworkOffering.State.Enabled) { - InvalidParameterValueException ex = new InvalidParameterValueException("Network offering with specified id is not in " + NetworkOffering.State.Enabled + " state, can't upgrade to it"); - ex.addProxyObject(networkOffering, networkOfferingId, "networkOfferingId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy(networkOffering, networkOfferingId, "networkOfferingId")); + throw new InvalidParameterValueException("Network offering with specified id is not in " + NetworkOffering.State.Enabled + " state, can't upgrade to it", idList); } - + //perform below validation if the network is vpc network if (network.getVpcId() != null) { Vpc vpc = _vpcMgr.getVpc(network.getVpcId()); @@ -4664,18 +4674,18 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (networkOfferingId != oldNetworkOfferingId) { if (networkOfferingIsConfiguredForExternalNetworking(networkOfferingId) != networkOfferingIsConfiguredForExternalNetworking(oldNetworkOfferingId) && !changeCidr) { - throw new InvalidParameterValueException("Can't guarantee guest network CIDR is unchanged after updating network!"); + throw new InvalidParameterValueException("Can't guarantee guest network CIDR is unchanged after updating network!", null); } if (changeCidr) { if (!checkForNonStoppedVmInNetwork(network.getId())) { - InvalidParameterValueException ex = new InvalidParameterValueException("All user vm of network of specified id should be stopped before changing CIDR!"); - ex.addProxyObject(network, networkId, "networkId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy(network, networkId, "networkId")); + throw new InvalidParameterValueException("All user vm of network of specified id should be stopped before changing CIDR!", idList); } } // check if the network is upgradable if (!canUpgrade(network, oldNetworkOfferingId, networkOfferingId)) { - throw new InvalidParameterValueException("Can't upgrade from network offering " + oldNetworkOfferingId + " to " + networkOfferingId + "; check logs for more information"); + throw new InvalidParameterValueException("Can't upgrade from network offering " + oldNetworkOfferingId + " to " + networkOfferingId + "; check logs for more information", null); } restartNetwork = true; networkOfferingChanged = true; @@ -4692,7 +4702,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (!NetUtils.verifyDomainName(domainSuffix)) { throw new InvalidParameterValueException( "Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " - + "and the hyphen ('-'); can't start or end with \"-\""); + + "and the hyphen ('-'); can't start or end with \"-\"", null); } long offeringId = oldNetworkOfferingId; @@ -4703,8 +4713,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag Map dnsCapabilities = getNetworkOfferingServiceCapabilities(_configMgr.getNetworkOffering(offeringId), Service.Dns); String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification); if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) { - // TBD: use uuid instead of networkOfferingId. May need to hardcode tablename in call to addProxyObject(). - throw new InvalidParameterValueException("Domain name change is not supported by the network offering id=" + networkOfferingId); + // TBD: use uuid instead of networkOfferingId. May need to hardcode tablename in call to addProxyObject(). + List idList = new ArrayList(); + idList.add(new IdentityProxy(offering, networkOfferingId, "networkOfferingId")); + throw new InvalidParameterValueException("Domain name change is not supported by network offering with specified id", idList); } network.setNetworkDomain(domainSuffix); @@ -4739,8 +4751,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } } else { - CloudRuntimeException ex = new CloudRuntimeException("Failed to shutdown the network elements and resources as a part of update to network with specified id; network is in wrong state: " + network.getState()); - ex.addProxyObject(network, networkId, "networkId"); + CloudRuntimeException ex = new CloudRuntimeException("Failed to shutdown the network elements and resources as a part of update to network with specified id; network is in wrong state: " + network.getState()); + ex.addProxyObject(network, networkId, "networkId"); throw ex; } } @@ -4750,8 +4762,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag Network.State networkState = _networksDao.findById(networkId).getState(); boolean validStateToImplement = (networkState == Network.State.Implemented || networkState == Network.State.Setup || networkState == Network.State.Allocated); if (restartNetwork && !validStateToImplement) { - CloudRuntimeException ex = new CloudRuntimeException("Failed to implement the network elements and resources as a part of update to network with specified id; network is in wrong state: " + networkState); - ex.addProxyObject(network, networkId, "networkId"); + CloudRuntimeException ex = new CloudRuntimeException("Failed to implement the network elements and resources as a part of update to network with specified id; network is in wrong state: " + networkState); + ex.addProxyObject(network, networkId, "networkId"); throw ex; } @@ -4850,7 +4862,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } Set availableIps = getAvailableIps(network, requestedIp); - + if (availableIps.isEmpty()) { return null; } @@ -4881,7 +4893,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag List ips = _nicDao.listIpAddressInNetwork(network.getId()); Set allPossibleIps = NetUtils.getAllIpsFromCidr(cidr[0], Integer.parseInt(cidr[1])); Set usedIps = new TreeSet(); - + for (String ip : ips) { if (requestedIp != null && requestedIp.equals(ip)) { s_logger.warn("Requested ip address " + requestedIp + " is already in use in network" + network); @@ -4895,7 +4907,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } return allPossibleIps; } - + private String getZoneNetworkDomain(long zoneId) { return _dcDao.findById(zoneId).getDomain(); @@ -5009,7 +5021,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } } - + // if all the rules configured on public IP are revoked then, dis-associate IP with network service provider applyIpAssociations(network, true, continueOnError, publicIps); @@ -5081,7 +5093,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // can upgrade only Isolated networks if (oldNetworkOffering.getGuestType() != GuestType.Isolated) { - throw new InvalidParameterValueException("NetworkOfferingId can be upgraded only for the network of type " + GuestType.Isolated); + throw new InvalidParameterValueException("NetworkOfferingId can be upgraded only for the network of type " + GuestType.Isolated, null); } // security group service should be the same @@ -5191,16 +5203,16 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Check if zone exists if (zoneId == null) { - throw new InvalidParameterValueException("Please specify a valid zone."); + throw new InvalidParameterValueException("Please specify a valid zone.", null); } DataCenterVO zone = _dcDao.findById(zoneId); if (zone == null) { - throw new InvalidParameterValueException("Please specify a valid zone."); + throw new InvalidParameterValueException("Please specify a valid zone.", null); } if (Grouping.AllocationState.Enabled == zone.getAllocationState()) { - // TBD: Send uuid instead of zoneId; may have to hardcode tablename in call to addProxyObject(). + // TBD: Send uuid instead of zoneId; may have to hardcode tablename in call to addProxyObject(). throw new PermissionDeniedException("Cannot create PhysicalNetwork since the Zone is currently enabled, zone Id: " + zoneId); } @@ -5208,7 +5220,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (zoneType == NetworkType.Basic) { if (!_physicalNetworkDao.listByZone(zoneId).isEmpty()) { - // TBD: Send uuid instead of zoneId; may have to hardcode tablename in call to addProxyObject(). + // TBD: Send uuid instead of zoneId; may have to hardcode tablename in call to addProxyObject(). throw new CloudRuntimeException("Cannot add the physical network to basic zone id: " + zoneId + ", there is a physical network already existing in this basic Zone"); } } @@ -5226,7 +5238,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Verify zone type if (zoneType == NetworkType.Basic || (zoneType == NetworkType.Advanced && zone.isSecurityGroupEnabled())) { - throw new InvalidParameterValueException("Can't add vnet range to the physical network in the zone that supports " + zoneType + " network, Security Group enabled: " + zone.isSecurityGroupEnabled()); + throw new InvalidParameterValueException("Can't add vnet range to the physical network in the zone that supports " + zoneType + " network, Security Group enabled: " + zone.isSecurityGroupEnabled(), null); } String[] tokens = vnetRange.split("-"); @@ -5238,12 +5250,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag vnetEnd = Integer.parseInt(tokens[1]); } } catch (NumberFormatException e) { - throw new InvalidParameterValueException("Please specify valid integers for the vlan range."); + throw new InvalidParameterValueException("Please specify valid integers for the vlan range.", null); } if ((vnetStart > vnetEnd) || (vnetStart < 0) || (vnetEnd > 4096)) { s_logger.warn("Invalid vnet range: start range:" + vnetStart + " end range:" + vnetEnd); - throw new InvalidParameterValueException("Vnet range should be between 0-4096 and start range should be lesser than or equal to end range"); + throw new InvalidParameterValueException("Vnet range should be between 0-4096 and start range should be lesser than or equal to end range", null); } } @@ -5252,14 +5264,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag try { broadcastDomainRange = PhysicalNetwork.BroadcastDomainRange.valueOf(broadcastDomainRangeStr.toUpperCase()); } catch (IllegalArgumentException ex) { - throw new InvalidParameterValueException("Unable to resolve broadcastDomainRange '" + broadcastDomainRangeStr + "' to a supported value {Pod or Zone}"); + throw new InvalidParameterValueException("Unable to resolve broadcastDomainRange '" + broadcastDomainRangeStr + "' to a supported value {Pod or Zone}", null); } // in Acton release you can specify only Zone broadcastdomain type in Advance zone, and Pod in Basic if (zoneType == NetworkType.Basic && broadcastDomainRange != null && broadcastDomainRange != BroadcastDomainRange.POD) { - throw new InvalidParameterValueException("Basic zone can have broadcast domain type of value " + BroadcastDomainRange.POD + " only"); + throw new InvalidParameterValueException("Basic zone can have broadcast domain type of value " + BroadcastDomainRange.POD + " only", null); } else if (zoneType == NetworkType.Advanced && broadcastDomainRange != null && broadcastDomainRange != BroadcastDomainRange.ZONE) { - throw new InvalidParameterValueException("Advance zone can have broadcast domain type of value " + BroadcastDomainRange.ZONE + " only"); + throw new InvalidParameterValueException("Advance zone can have broadcast domain type of value " + BroadcastDomainRange.ZONE + " only", null); } } @@ -5331,23 +5343,19 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // verify input parameters PhysicalNetworkVO network = _physicalNetworkDao.findById(id); if (network == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Physical Network with specified id doesn't exist in the system"); - ex.addProxyObject(network, id, "physicalNetworkId"); - throw ex; + throw new InvalidParameterValueException("Couldn't find physical network by id", null); } // if zone is of Basic type, don't allow to add vnet range DataCenter zone = _dcDao.findById(network.getDataCenterId()); if (zone == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Zone with id=" + network.getDataCenterId() + " doesn't exist in the system"); - ex.addProxyObject(zone, network.getDataCenterId(), "dataCenterId"); - throw ex; + throw new InvalidParameterValueException("Couldn't find zone by id", null); } if (newVnetRangeString != null) { if (zone.getNetworkType() == NetworkType.Basic || (zone.getNetworkType() == NetworkType.Advanced && zone.isSecurityGroupEnabled())) { throw new InvalidParameterValueException("Can't add vnet range to the physical network in the zone that supports " + zone.getNetworkType() + " network, Security Group enabled: " - + zone.isSecurityGroupEnabled()); + + zone.isSecurityGroupEnabled(), null); } } @@ -5360,7 +5368,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag try { networkState = PhysicalNetwork.State.valueOf(state); } catch (IllegalArgumentException ex) { - throw new InvalidParameterValueException("Unable to resolve state '" + state + "' to a supported value {Enabled or Disabled}"); + throw new InvalidParameterValueException("Unable to resolve state '" + state + "' to a supported value {Enabled or Disabled}", null); } } @@ -5391,15 +5399,15 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.debug("ISOLATION METHODS:" + network.getIsolationMethods()); // Java does not have unsigned types... if (network.getIsolationMethods().contains("GRE")) { - maxVnet = (int)(Math.pow(2, 32)-1); + maxVnet = (int)(Math.pow(2, 32)-1); } String rangeMessage = " between 0 and " + maxVnet; if (newVnetRange.length < 2) { - throw new InvalidParameterValueException("Please provide valid vnet range" + rangeMessage); + throw new InvalidParameterValueException("Please provide valid vnet range" + rangeMessage, null); } if (newVnetRange[0] == null || newVnetRange[1] == null) { - throw new InvalidParameterValueException("Please provide valid vnet range" + rangeMessage); + throw new InvalidParameterValueException("Please provide valid vnet range" + rangeMessage, null); } try { @@ -5407,14 +5415,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag newEndVnet = Integer.parseInt(newVnetRange[1]); } catch (NumberFormatException e) { s_logger.warn("Unable to parse vnet range:", e); - throw new InvalidParameterValueException("Please provide valid vnet range" + rangeMessage); + throw new InvalidParameterValueException("Please provide valid vnet range" + rangeMessage, null); } if (newStartVnet < 0 || newEndVnet > maxVnet) { - throw new InvalidParameterValueException("Vnet range has to be" + rangeMessage); + throw new InvalidParameterValueException("Vnet range has to be" + rangeMessage, null); } if (newStartVnet > newEndVnet) { - throw new InvalidParameterValueException("Vnet range has to be" + rangeMessage + " and start range should be lesser than or equal to stop range"); + throw new InvalidParameterValueException("Vnet range has to be" + rangeMessage + " and start range should be lesser than or equal to stop range", null); } if (physicalNetworkHasAllocatedVnets(network.getDataCenterId(), network.getId())) { @@ -5424,7 +5432,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // check if vnet is being extended if (newStartVnet.intValue() > existingStartVnet || newEndVnet.intValue() < existingEndVnet) { - throw new InvalidParameterValueException("Can't shrink existing vnet range as it the range has vnets allocated. Only extending existing vnet is supported"); + throw new InvalidParameterValueException("Can't shrink existing vnet range as it the range has vnets allocated. Only extending existing vnet is supported", null); } if (newStartVnet < existingStartVnet) { @@ -5469,13 +5477,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @ActionEvent(eventType = EventTypes.EVENT_PHYSICAL_NETWORK_DELETE, eventDescription = "deleting physical network", async = true) @DB public boolean deletePhysicalNetwork(Long physicalNetworkId) { - // verify input parameters PhysicalNetworkVO pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if (pNetwork == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Physical Network with specified id doesn't exist in the system"); - ex.addProxyObject(pNetwork, physicalNetworkId, "physicalNetworkId"); - throw ex; + throw new InvalidParameterValueException("Couldn't find Physical Network by id", null); } checkIfPhysicalNetworkIsDeletable(physicalNetworkId); @@ -5501,7 +5506,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // delete service providers List providers = _pNSPDao.listBy(physicalNetworkId); - + for(PhysicalNetworkServiceProviderVO provider : providers){ try { deleteNetworkServiceProvider(provider.getId()); @@ -5518,7 +5523,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag _pNTrafficTypeDao.deleteTrafficTypes(physicalNetworkId); boolean success = _physicalNetworkDao.remove(physicalNetworkId); - + txn.commit(); return success; @@ -5601,14 +5606,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (providerName != null) { provider = Network.Provider.getProvider(providerName); if (provider == null) { - throw new InvalidParameterValueException("Invalid Network Service Provider=" + providerName); + throw new InvalidParameterValueException("Invalid Network Service Provider=" + providerName, null); } } if (provider != null) { NetworkElement element = getElementImplementingProvider(providerName); if (element == null) { - throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + providerName + "'"); + throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + providerName + "'", null); } return new ArrayList(element.getCapabilities().keySet()); } else { @@ -5622,7 +5627,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (serviceName != null) { service = Network.Service.getService(serviceName); if (service == null) { - throw new InvalidParameterValueException("Invalid Network Service=" + serviceName); + throw new InvalidParameterValueException("Invalid Network Service=" + serviceName, null); } } @@ -5660,44 +5665,40 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // verify input parameters PhysicalNetworkVO network = _physicalNetworkDao.findById(physicalNetworkId); if (network == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Physical Network with specified id doesn't exist in the system"); - ex.addProxyObject(network, physicalNetworkId, "physicalNetworkId"); - throw ex; + throw new InvalidParameterValueException("Couldn't find Physical Network by id", null); } // verify input parameters if (destinationPhysicalNetworkId != null) { PhysicalNetworkVO destNetwork = _physicalNetworkDao.findById(destinationPhysicalNetworkId); if (destNetwork == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Destination Physical Network with specified id doesn't exist in the system"); - ex.addProxyObject(destNetwork, destinationPhysicalNetworkId, "destinationPhysicalNetworkId"); - throw ex; + throw new InvalidParameterValueException("Couldn't find Destination Physical Network by id", null); } } if (providerName != null) { Provider provider = Network.Provider.getProvider(providerName); if (provider == null) { - throw new InvalidParameterValueException("Invalid Network Service Provider=" + providerName); + throw new InvalidParameterValueException("Invalid Network Service Provider=" + providerName, null); } } if (_pNSPDao.findByServiceProvider(physicalNetworkId, providerName) != null) { - // TBD: send uuid instead of physicalNetworkId. + // TBD: send uuid instead of physicalNetworkId. throw new CloudRuntimeException("The '" + providerName + "' provider already exists on physical network : " + physicalNetworkId); } // check if services can be turned off NetworkElement element = getElementImplementingProvider(providerName); if (element == null) { - throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + providerName + "'"); + throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + providerName + "'", null); } List services = new ArrayList(); if (enabledServices != null) { if (!element.canEnableIndividualServices()) { if (enabledServices.size() != element.getCapabilities().keySet().size()) { - throw new InvalidParameterValueException("Cannot enable subset of Services, Please specify the complete list of Services for this Service Provider '" + providerName + "'"); + throw new InvalidParameterValueException("Cannot enable subset of Services, Please specify the complete list of Services for this Service Provider '" + providerName + "'", null); } } @@ -5706,14 +5707,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag for (String serviceName : enabledServices) { Network.Service service = Network.Service.getService(serviceName); if (service == null || service == Service.Gateway) { - throw new InvalidParameterValueException("Invalid Network Service specified=" + serviceName); + throw new InvalidParameterValueException("Invalid Network Service specified=" + serviceName, null); } else if (service == Service.SourceNat) { addGatewayService = true; } // check if the service is provided by this Provider if (!element.getCapabilities().containsKey(service)) { - throw new InvalidParameterValueException(providerName + " Provider cannot provide this Service specified=" + serviceName); + throw new InvalidParameterValueException(providerName + " Provider cannot provide this Service specified=" + serviceName, null); } services.add(service); } @@ -5776,12 +5777,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag PhysicalNetworkServiceProviderVO provider = _pNSPDao.findById(id); if (provider == null) { - throw new InvalidParameterValueException("Network Service Provider id=" + id + "doesn't exist in the system"); + throw new InvalidParameterValueException("Couldn't find Network Service Provider by id", null); } NetworkElement element = getElementImplementingProvider(provider.getProviderName()); if (element == null) { - throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + provider.getProviderName() + "'"); + throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + provider.getProviderName() + "'", null); } PhysicalNetworkServiceProvider.State state = null; @@ -5789,7 +5790,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag try { state = PhysicalNetworkServiceProvider.State.valueOf(stateStr); } catch (IllegalArgumentException ex) { - throw new InvalidParameterValueException("Unable to resolve state '" + stateStr + "' to a supported value {Enabled or Disabled}"); + throw new InvalidParameterValueException("Unable to resolve state '" + stateStr + "' to a supported value {Enabled or Disabled}", null); } } @@ -5797,7 +5798,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (state != null) { if (state == PhysicalNetworkServiceProvider.State.Shutdown) { - throw new InvalidParameterValueException("Updating the provider state to 'Shutdown' is not supported"); + throw new InvalidParameterValueException("Updating the provider state to 'Shutdown' is not supported", null); } if (s_logger.isDebugEnabled()) { @@ -5823,7 +5824,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (enabledServices != null) { // check if services can be turned of if (!element.canEnableIndividualServices()) { - throw new InvalidParameterValueException("Cannot update set of Services for this Service Provider '" + provider.getProviderName() + "'"); + throw new InvalidParameterValueException("Cannot update set of Services for this Service Provider '" + provider.getProviderName() + "'", null); } // validate Services @@ -5831,7 +5832,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag for (String serviceName : enabledServices) { Network.Service service = Network.Service.getService(serviceName); if (service == null) { - throw new InvalidParameterValueException("Invalid Network Service specified=" + serviceName); + throw new InvalidParameterValueException("Invalid Network Service specified=" + serviceName, null); } services.add(service); } @@ -5852,7 +5853,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag PhysicalNetworkServiceProviderVO provider = _pNSPDao.findById(id); if (provider == null) { - throw new InvalidParameterValueException("Network Service Provider id=" + id + "doesn't exist in the system"); + throw new InvalidParameterValueException("Couldn't find Network Service Provider by id", null); } // check if there are networks using this provider @@ -5870,7 +5871,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } NetworkElement element = getElementImplementingProvider(provider.getProviderName()); if (element == null) { - throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + provider.getProviderName() + "'"); + throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + provider.getProviderName() + "'", null); } if (element != null && element.shutdownProviderInstances(provider, context)) { @@ -5910,14 +5911,18 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } else { pNtwks = _physicalNetworkDao.listByZone(zoneId); } - + if (pNtwks.isEmpty()) { - throw new InvalidParameterValueException("Unable to find physical network in zone id=" + zoneId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("data_center", zoneId, "zoneId")); + throw new InvalidParameterValueException("Unable to find physical network in zone with specified id", idList); } if (pNtwks.size() > 1) { if (tag == null) { - throw new InvalidParameterValueException("More than one physical networks exist in zone id=" + zoneId + " and no tags are specified in order to make a choice"); + List idList = new ArrayList(); + idList.add(new IdentityProxy("data_center", zoneId, "zoneId")); + throw new InvalidParameterValueException("More than one physical networks exist in zone with specified id and no tags are specified in order to make a choice", idList); } Long pNtwkId = null; @@ -5929,7 +5934,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } if (pNtwkId == null) { - throw new InvalidParameterValueException("Unable to find physical network which match the tags " + tag); + throw new InvalidParameterValueException("Unable to find physical network which match the tags " + tag, null); } return pNtwkId; } else { @@ -5941,11 +5946,15 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public PhysicalNetwork translateZoneIdToPhysicalNetwork(long zoneId) { List pNtwks = _physicalNetworkDao.listByZone(zoneId); if (pNtwks.isEmpty()) { - throw new InvalidParameterValueException("Unable to find physical network in zone id=" + zoneId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("data_center", zoneId, "zoneId")); + throw new InvalidParameterValueException("Unable to find physical network in zone with specified id", idList); } if (pNtwks.size() > 1) { - throw new InvalidParameterValueException("More than one physical networks exist in zone id=" + zoneId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("data_center", zoneId, "zoneId")); + throw new InvalidParameterValueException("More than one physical networks exist in zone with specified id", idList); } return pNtwks.get(0); @@ -6011,7 +6020,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // shouldn't even come here as network is being cleaned up after all network elements are shutdown s_logger.warn("Failed to cleanup Firewall rules as a part of network id=" + networkId + " cleanup due to resourceUnavailable ", ex); } - + //revoke all network ACLs for network try { if (_networkACLMgr.revokeAllNetworkACLsForNetwork(networkId, callerUserId, caller)) { @@ -6030,9 +6039,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag List ipsToRelease = _ipAddressDao.listByAssociatedNetwork(networkId, null); for (IPAddressVO ipToRelease : ipsToRelease) { if (ipToRelease.getVpcId() != null) { - IPAddressVO ip = markIpAsUnavailable(ipToRelease.getId()); - assert (ip != null) : "Unable to mark the ip address id=" + ipToRelease.getId() + " as unavailable."; - } + IPAddressVO ip = markIpAsUnavailable(ipToRelease.getId()); + assert (ip != null) : "Unable to mark the ip address id=" + ipToRelease.getId() + " as unavailable."; + } } try { @@ -6085,7 +6094,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag FirewallRuleVO ruleVO = _firewallDao.findById(firewallStaticNatRule.getId()); if (ip == null || !ip.isOneToOneNat() || ip.getAssociatedWithVmId() == null) { - throw new InvalidParameterValueException("Source ip address of the rule id=" + firewallStaticNatRule.getId() + " is not static nat enabled"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(firewallStaticNatRule, firewallStaticNatRule.getId(), "firewallStaticNatRuleId")); + throw new InvalidParameterValueException("Source ip address of the rule with specified id is not static nat enabled", idList); } String dstIp = getIpInNetwork(ip.getAssociatedWithVmId(), firewallStaticNatRule.getNetworkId()); @@ -6151,7 +6162,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.warn("Failed to cleanup firewall rules as a part of shutdownNetworkRules due to ", ex); success = false; } - + //revoke all Network ACLs for the network w/o applying them in the DB List networkACLs = _firewallDao.listByNetworkAndPurpose(networkId, Purpose.NetworkACL); if (s_logger.isDebugEnabled()) { @@ -6173,7 +6184,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.warn("Failed to cleanup network ACLs as a part of shutdownNetworkRules due to ", ex); success = false; } - + // Get all ip addresses, mark as releasing and release them on the backend Network network = getNetwork(networkId); @@ -6224,7 +6235,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // verify input parameters PhysicalNetworkVO network = _physicalNetworkDao.findById(physicalNetworkId); if (network == null) { - throw new InvalidParameterValueException("Physical Network id=" + physicalNetworkId + "doesn't exist in the system"); + throw new InvalidParameterValueException("Couldn't find Physical Network by id", null); } Networks.TrafficType trafficType = null; @@ -6232,7 +6243,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag try { trafficType = Networks.TrafficType.valueOf(trafficTypeStr); } catch (IllegalArgumentException ex) { - throw new InvalidParameterValueException("Unable to resolve trafficType '" + trafficTypeStr + "' to a supported value"); + throw new InvalidParameterValueException("Unable to resolve trafficType '" + trafficTypeStr + "' to a supported value", null); } } @@ -6318,7 +6329,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag PhysicalNetworkTrafficTypeVO trafficType = _pNTrafficTypeDao.findById(id); if (trafficType == null) { - throw new InvalidParameterValueException("Traffic Type with id=" + id + "doesn't exist in the system"); + throw new InvalidParameterValueException("Couldn't find traffic type by id", null); } if (xenLabel != null) { @@ -6350,7 +6361,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag PhysicalNetworkTrafficTypeVO trafficType = _pNTrafficTypeDao.findById(id); if (trafficType == null) { - throw new InvalidParameterValueException("Traffic Type with id=" + id + "doesn't exist in the system"); + throw new InvalidParameterValueException("Couldn't find traffic type by id", null); } // check if there are any networks associated to this physical network with this traffic type @@ -6371,9 +6382,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public List listTrafficTypes(Long physicalNetworkId) { PhysicalNetworkVO network = _physicalNetworkDao.findById(physicalNetworkId); if (network == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Physical Network with specified id doesn't exist in the system"); - ex.addProxyObject(network, physicalNetworkId, "physicalNetworkId"); - throw ex; + throw new InvalidParameterValueException("Couldn't find Physical Network by id", null); } return _pNTrafficTypeDao.listBy(physicalNetworkId); @@ -6385,21 +6394,21 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag List networkList = _physicalNetworkDao.listByZoneAndTrafficType(zoneId, trafficType); if (networkList.isEmpty()) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find the default physical network with traffic=" + trafficType + " in the specified zone id"); - // Since we don't have a DataCenterVO object at our disposal, we just set the table name that the zoneId's corresponding uuid is looked up from, manually. - ex.addProxyObject("data_center", zoneId, "zoneId"); - throw ex; + List idList = new ArrayList(); + // Since we don't have a DataCenterVO object at our disposal, we just set the table name that the zoneId's corresponding uuid is looked up from, manually. + idList.add(new IdentityProxy("data_center", zoneId, "zoneId")); + throw new InvalidParameterValueException("Unable to find the default physical network with traffic=" + trafficType + " in the specified zone id", idList); } if (networkList.size() > 1) { - InvalidParameterValueException ex = new InvalidParameterValueException("More than one physical networks exist in zone id=" + zoneId + " with traffic type=" + trafficType); - ex.addProxyObject("data_center", zoneId, "zoneId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy("data_center", zoneId, "zoneId")); + throw new InvalidParameterValueException("More than one physical networks exist in zone with specified id, with traffic type=" + trafficType, idList); } return networkList.get(0); } - + @Override public String getDefaultManagementTrafficLabel(long zoneId, HypervisorType hypervisorType){ try{ @@ -6408,12 +6417,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if(mgmtTraffic != null){ String label = null; switch(hypervisorType){ - case XenServer : label = mgmtTraffic.getXenNetworkLabel(); - break; - case KVM : label = mgmtTraffic.getKvmNetworkLabel(); - break; - case VMware : label = mgmtTraffic.getVmwareNetworkLabel(); - break; + case XenServer : label = mgmtTraffic.getXenNetworkLabel(); + break; + case KVM : label = mgmtTraffic.getKvmNetworkLabel(); + break; + case VMware : label = mgmtTraffic.getVmwareNetworkLabel(); + break; } return label; } @@ -6424,7 +6433,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } return null; } - + @Override public String getDefaultStorageTrafficLabel(long zoneId, HypervisorType hypervisorType){ try{ @@ -6433,12 +6442,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if(storageTraffic != null){ String label = null; switch(hypervisorType){ - case XenServer : label = storageTraffic.getXenNetworkLabel(); - break; - case KVM : label = storageTraffic.getKvmNetworkLabel(); - break; - case VMware : label = storageTraffic.getVmwareNetworkLabel(); - break; + case XenServer : label = storageTraffic.getXenNetworkLabel(); + break; + case KVM : label = storageTraffic.getKvmNetworkLabel(); + break; + case VMware : label = storageTraffic.getVmwareNetworkLabel(); + break; } return label; } @@ -6632,10 +6641,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override public String getNetworkTag(HypervisorType hType, Network network) { // no network tag for control traffic type - TrafficType effectiveTrafficType = network.getTrafficType(); - if(hType == HypervisorType.VMware && effectiveTrafficType == TrafficType.Control) - effectiveTrafficType = TrafficType.Management; - + TrafficType effectiveTrafficType = network.getTrafficType(); + if(hType == HypervisorType.VMware && effectiveTrafficType == TrafficType.Control) + effectiveTrafficType = TrafficType.Management; + if (effectiveTrafficType == TrafficType.Control) { return null; } @@ -6662,11 +6671,11 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // have to remove this sanity check as VMware control network is management network // we need to retrieve traffic label information through physical network -/* + /* if (network.getTrafficType() == TrafficType.Control) { return null; } -*/ + */ Long physicalNetworkId = network.getPhysicalNetworkId(); if (physicalNetworkId == null) { @@ -6692,11 +6701,15 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public NetworkVO getExclusiveGuestNetwork(long zoneId) { List networks = _networksDao.listBy(Account.ACCOUNT_ID_SYSTEM, zoneId, GuestType.Shared, TrafficType.Guest); if (networks == null || networks.isEmpty()) { - throw new InvalidParameterValueException("Unable to find network with trafficType " + TrafficType.Guest + " and guestType " + GuestType.Shared + " in zone " + zoneId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("data_center", zoneId, "zoneId")); + throw new InvalidParameterValueException("Unable to find network with trafficType " + TrafficType.Guest + " and guestType " + GuestType.Shared + " in zone with specified id", idList); } if (networks.size() > 1) { - throw new InvalidParameterValueException("Found more than 1 network with trafficType " + TrafficType.Guest + " and guestType " + GuestType.Shared + " in zone " + zoneId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("data_center", zoneId, "zoneId")); + throw new InvalidParameterValueException("Found more than 1 network with trafficType " + TrafficType.Guest + " and guestType " + GuestType.Shared + " in zone with specified id", idList); } @@ -6773,7 +6786,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (checkPhysicalNetwork) { if (!_pNSPDao.isServiceProviderEnabled(physicalNetworkId, provider, service)) { throw new UnsupportedServiceException("Provider " + provider + " is either not enabled or doesn't " + - "support service " + service + " in physical network id=" + physicalNetworkId); + "support service " + service + " in physical network id=" + physicalNetworkId); } } @@ -6849,7 +6862,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // check if services can be turned off NetworkElement element = getElementImplementingProvider(provider.getName()); if (element == null) { - throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + provider.getName() + "'"); + throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + provider.getName() + "'", null); } Set enabledServices = new HashSet(); @@ -6859,15 +6872,15 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (!element.canEnableIndividualServices()) { Set requiredServices = new HashSet(); requiredServices.addAll(element.getCapabilities().keySet()); - + if (requiredServices.contains(Network.Service.Gateway)) { requiredServices.remove(Network.Service.Gateway); } - + if (requiredServices.contains(Network.Service.Firewall)) { requiredServices.remove(Network.Service.Firewall); } - + if (enabledServices.contains(Network.Service.Firewall)) { enabledServices.remove(Network.Service.Firewall); } @@ -6886,7 +6899,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag servicesSet.delete(servicesSet.toString().length() - 2, servicesSet.toString().length()); throw new InvalidParameterValueException("Cannot enable subset of Services, Please specify the complete list of Services: " + servicesSet.toString() + " for Service Provider " - + provider.getName()); + + provider.getName(), null); } } for (Service service : enabledServices) { @@ -7007,6 +7020,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } + @Override public IpAddress assignSystemIp(long networkId, Account owner, boolean forElasticLb, boolean forElasticIp) throws InsufficientAddressCapacityException { Network guestNetwork = getNetwork(networkId); @@ -7069,8 +7083,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } + @Override public void allocateDirectIp(NicProfile nic, DataCenter dc, VirtualMachineProfile vm, Network network, String requestedIp) throws InsufficientVirtualNetworkCapcityException, - InsufficientAddressCapacityException { + InsufficientAddressCapacityException { if (nic.getIp4Address() == null) { PublicIp ip = assignPublicIpAddress(dc.getId(), null, vm.getOwner(), VlanType.DirectAttached, network.getId(), requestedIp, false); nic.setIp4Address(ip.getAddress().toString()); @@ -7146,17 +7161,17 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } return null; } - + @Override public List listNetworksByVpc(long vpcId) { return _networksDao.listByVpc(vpcId); } - + @Override public String getDefaultNetworkDomain() { return _networkDomain; } - + @Override public List getNtwkOffDistinctProviders(long networkId) { List providerNames = _ntwkOfferingSrvcDao.getDistinctProviders(networkId); @@ -7175,27 +7190,27 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } return false; } - + @Override @ActionEvent(eventType = EventTypes.EVENT_NET_IP_ASSIGN, eventDescription = "associating Ip", async = true) public IpAddress associateIP(long ipId, Long networkId, Long vpcId) throws InsufficientAddressCapacityException, - ResourceAllocationException, ResourceUnavailableException, ConcurrentOperationException { + ResourceAllocationException, ResourceUnavailableException, ConcurrentOperationException { if (vpcId != null) { return associateIPToVpc(ipId, vpcId); } - + if (networkId != null) { Network network = _networksDao.findById(networkId); if (network == null) { - throw new InvalidParameterValueException("Invalid network id is given"); + throw new InvalidParameterValueException("Invalid network id is given", null); } - + if (network.getVpcId() != null) { - throw new InvalidParameterValueException("Specify vpcId to associate ip address to VPC"); + throw new InvalidParameterValueException("Specify vpcId to associate ip address to VPC", null); } return associateIPToGuestNetwork(ipId, networkId); } - + return null; } @@ -7203,8 +7218,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag List networkList = _physicalNetworkDao.listByZoneAndTrafficType(zoneId, trafficType); if (networkList.isEmpty()) { + List idList = new ArrayList(); + idList.add(new IdentityProxy("data_center", zoneId, "zoneId")); throw new InvalidParameterValueException("Unable to find the default physical network with traffic=" - + trafficType + " in zone id=" + zoneId + ". "); + + trafficType + " in zone with specified id", idList); } if (networkList.size() > 1) { @@ -7214,16 +7231,16 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return networkList.get(0); } - + @Override public void unassignIPFromVpcNetwork(long ipId) { IPAddressVO ip = _ipAddressDao.findById(ipId); Long vpcId = ip.getVpcId(); - + if (vpcId == null) { return; } - + ip.setAssociatedWithNetworkId(null); _ipAddressDao.update(ipId, ip); s_logger.debug("IP address " + ip + " is no longer associated with the network inside vpc id=" + vpcId); @@ -7233,49 +7250,46 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public Network createPrivateNetwork(String networkName, String displayText, long physicalNetworkId, String vlan, String startIp, String endIp, String gateway, String netmask, long networkOwnerId) throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException { - + Account owner = _accountMgr.getAccount(networkOwnerId); - + // Get system network offeirng NetworkOfferingVO ntwkOff = _systemNetworks.get(NetworkOffering.SystemPrivateGatewayNetworkOffering); - + // Validate physical network PhysicalNetwork pNtwk = _physicalNetworkDao.findById(physicalNetworkId); if (pNtwk == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a physical network" + - " having the given id"); - ex.addProxyObject("physical_network", physicalNetworkId, "physicalNetworkId"); - throw ex; + throw new InvalidParameterValueException("Unable to find physical network by id", null); } - + // VALIDATE IP INFO // if end ip is not specified, default it to startIp if (!NetUtils.isValidIp(startIp)) { - throw new InvalidParameterValueException("Invalid format for the startIp parameter"); + throw new InvalidParameterValueException("Invalid format for the startIp parameter", null); } if (endIp == null) { endIp = startIp; } else if (!NetUtils.isValidIp(endIp)) { - throw new InvalidParameterValueException("Invalid format for the endIp parameter"); + throw new InvalidParameterValueException("Invalid format for the endIp parameter", null); } String cidr = null; if (!NetUtils.isValidIp(gateway)) { - throw new InvalidParameterValueException("Invalid gateway"); + throw new InvalidParameterValueException("Invalid gateway", null); } if (!NetUtils.isValidNetmask(netmask)) { - throw new InvalidParameterValueException("Invalid netmask"); + throw new InvalidParameterValueException("Invalid netmask", null); } cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask); - - + + Transaction txn = Transaction.currentTxn(); txn.start(); - + //lock datacenter as we need to get mac address seq from there DataCenterVO dc = _dcDao.lockRow(pNtwk.getDataCenterId(), true); - + //check if we need to create guest network Network privateNetwork = _networksDao.getPrivateNetwork(BroadcastDomainType.Vlan.toUri(vlan).toString(), cidr, networkOwnerId, pNtwk.getDataCenterId()); @@ -7287,44 +7301,44 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } else { s_logger.debug("Private network already exists: " + privateNetwork); } - + //add entry to private_ip_address table PrivateIpVO privateIp = _privateIpDao.findByIpAndSourceNetworkId(privateNetwork.getId(), startIp); if (privateIp != null) { throw new InvalidParameterValueException("Private ip address " + startIp + " already used for private gateway" + - " in zone " + _configMgr.getZone(pNtwk.getDataCenterId()).getName()); + " in zone " + _configMgr.getZone(pNtwk.getDataCenterId()).getName(), null); } - + Long mac = dc.getMacAddress(); Long nextMac = mac + 1; dc.setMacAddress(nextMac); - + privateIp = new PrivateIpVO(startIp, privateNetwork.getId(), nextMac); _privateIpDao.persist(privateIp); - + _dcDao.update(dc.getId(), dc); - + txn.commit(); s_logger.debug("Private network " + privateNetwork + " is created"); return privateNetwork; } - + @Override public boolean setupDns(Network network, Provider provider) { boolean dnsProvided = isProviderSupportServiceInNetwork(network.getId(), Service.Dns, provider ); boolean dhcpProvided =isProviderSupportServiceInNetwork(network.getId(), Service.Dhcp, provider); - + boolean setupDns = dnsProvided || dhcpProvided; return setupDns; } - + @Override public List getPhysicalNtwksSupportingTrafficType(long zoneId, TrafficType trafficType) { - + List pNtwks = _physicalNetworkDao.listByZone(zoneId); - + Iterator it = pNtwks.iterator(); while (it.hasNext()) { PhysicalNetwork pNtwk = it.next(); @@ -7334,7 +7348,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } return pNtwks; } - + @Override public boolean isPrivateGateway(Nic guestNic) { Network network = getNetwork(guestNic.getNetworkId()); diff --git a/server/src/com/cloud/template/TemplateAdapterBase.java b/server/src/com/cloud/template/TemplateAdapterBase.java index b8dfb1de41c..a63f8897b2c 100755 --- a/server/src/com/cloud/template/TemplateAdapterBase.java +++ b/server/src/com/cloud/template/TemplateAdapterBase.java @@ -57,95 +57,97 @@ import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.UserVmVO; public abstract class TemplateAdapterBase implements TemplateAdapter { - private final static Logger s_logger = Logger.getLogger(TemplateAdapterBase.class); - protected String _name; - protected @Inject DomainDao _domainDao; - protected @Inject AccountDao _accountDao; - protected @Inject ConfigurationDao _configDao; - protected @Inject UserDao _userDao; - protected @Inject AccountManager _accountMgr; - protected @Inject DataCenterDao _dcDao; - protected @Inject VMTemplateDao _tmpltDao; - protected @Inject VMTemplateHostDao _tmpltHostDao; - protected @Inject VMTemplateZoneDao _tmpltZoneDao; - protected @Inject UsageEventDao _usageEventDao; - protected @Inject HostDao _hostDao; - protected @Inject ResourceLimitService _resourceLimitMgr; - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - _name = name; - return true; - } + private final static Logger s_logger = Logger.getLogger(TemplateAdapterBase.class); + protected String _name; + protected @Inject DomainDao _domainDao; + protected @Inject AccountDao _accountDao; + protected @Inject ConfigurationDao _configDao; + protected @Inject UserDao _userDao; + protected @Inject AccountManager _accountMgr; + protected @Inject DataCenterDao _dcDao; + protected @Inject VMTemplateDao _tmpltDao; + protected @Inject VMTemplateHostDao _tmpltHostDao; + protected @Inject VMTemplateZoneDao _tmpltZoneDao; + protected @Inject UsageEventDao _usageEventDao; + protected @Inject HostDao _hostDao; + protected @Inject ResourceLimitService _resourceLimitMgr; - @Override - public String getName() { - return _name; - } + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + _name = name; + return true; + } - @Override - public boolean start() { - return true; - } + @Override + public String getName() { + return _name; + } - @Override - public boolean stop() { - return true; - } - - private static boolean isAdmin(short accountType) { - return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || - (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) || - (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || - (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN)); - } + @Override + public boolean start() { + return true; + } - public TemplateProfile prepare(boolean isIso, Long userId, String name, String displayText, Integer bits, + @Override + public boolean stop() { + return true; + } + + private static boolean isAdmin(short accountType) { + return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || + (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) || + (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || + (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN)); + } + + @Override + public TemplateProfile prepare(boolean isIso, Long userId, String name, String displayText, Integer bits, Boolean passwordEnabled, Boolean requiresHVM, String url, Boolean isPublic, Boolean featured, Boolean isExtractable, String format, Long guestOSId, Long zoneId, HypervisorType hypervisorType, String accountName, Long domainId, String chksum, Boolean bootable, Map details) throws ResourceAllocationException { - return prepare(isIso, userId, name, displayText, bits, passwordEnabled, requiresHVM, url, isPublic, featured, isExtractable, format, guestOSId, zoneId, hypervisorType, - chksum, bootable, null, null, details, false); - } - - public TemplateProfile prepare(boolean isIso, long userId, String name, String displayText, Integer bits, - Boolean passwordEnabled, Boolean requiresHVM, String url, Boolean isPublic, Boolean featured, - Boolean isExtractable, String format, Long guestOSId, Long zoneId, HypervisorType hypervisorType, - String chksum, Boolean bootable, String templateTag, Account templateOwner, Map details, Boolean sshkeyEnabled) throws ResourceAllocationException { - //Long accountId = null; - // parameters verification - - if (isPublic == null) { - isPublic = Boolean.FALSE; - } - - if (zoneId.longValue() == -1) { - zoneId = null; - } - - if (isIso) { - if (bootable == null) { - bootable = Boolean.TRUE; - } - GuestOS noneGuestOs = ApiDBUtils.findGuestOSByDisplayName(ApiConstants.ISO_GUEST_OS_NONE); - if ((guestOSId == null || guestOSId == noneGuestOs.getId()) && bootable == true){ - throw new InvalidParameterValueException("Please pass a valid GuestOS Id"); - } - if (bootable == false){ - guestOSId = noneGuestOs.getId(); //Guest os id of None. - } - } else { - if (bits == null) { - bits = Integer.valueOf(64); - } - if (passwordEnabled == null) { - passwordEnabled = false; - } - if (requiresHVM == null) { - requiresHVM = true; - } - } - + return prepare(isIso, userId, name, displayText, bits, passwordEnabled, requiresHVM, url, isPublic, featured, isExtractable, format, guestOSId, zoneId, hypervisorType, + chksum, bootable, null, null, details, false); + } + + @Override + public TemplateProfile prepare(boolean isIso, long userId, String name, String displayText, Integer bits, + Boolean passwordEnabled, Boolean requiresHVM, String url, Boolean isPublic, Boolean featured, + Boolean isExtractable, String format, Long guestOSId, Long zoneId, HypervisorType hypervisorType, + String chksum, Boolean bootable, String templateTag, Account templateOwner, Map details, Boolean sshkeyEnabled) throws ResourceAllocationException { + //Long accountId = null; + // parameters verification + + if (isPublic == null) { + isPublic = Boolean.FALSE; + } + + if (zoneId.longValue() == -1) { + zoneId = null; + } + + if (isIso) { + if (bootable == null) { + bootable = Boolean.TRUE; + } + GuestOS noneGuestOs = ApiDBUtils.findGuestOSByDisplayName(ApiConstants.ISO_GUEST_OS_NONE); + if ((guestOSId == null || guestOSId == noneGuestOs.getId()) && bootable == true){ + throw new InvalidParameterValueException("Please pass a valid GuestOS Id", null); + } + if (bootable == false){ + guestOSId = noneGuestOs.getId(); //Guest os id of None. + } + } else { + if (bits == null) { + bits = Integer.valueOf(64); + } + if (passwordEnabled == null) { + passwordEnabled = false; + } + if (requiresHVM == null) { + requiresHVM = true; + } + } + if (isExtractable == null) { isExtractable = Boolean.FALSE; } @@ -153,201 +155,206 @@ public abstract class TemplateAdapterBase implements TemplateAdapter { sshkeyEnabled = Boolean.FALSE; } - boolean isAdmin = _accountDao.findById(templateOwner.getId()).getType() == Account.ACCOUNT_TYPE_ADMIN; + boolean isAdmin = _accountDao.findById(templateOwner.getId()).getType() == Account.ACCOUNT_TYPE_ADMIN; - if (!isAdmin && zoneId == null) { - throw new InvalidParameterValueException("Please specify a valid zone Id."); - } + if (!isAdmin && zoneId == null) { + throw new InvalidParameterValueException("Please specify a valid zone Id.", null); + } - if (url.toLowerCase().contains("file://")) { - throw new InvalidParameterValueException("File:// type urls are currently unsupported"); - } - - boolean allowPublicUserTemplates = Boolean.parseBoolean(_configDao.getValue("allow.public.user.templates")); - if (!isAdmin && !allowPublicUserTemplates && isPublic) { - throw new InvalidParameterValueException("Only private templates/ISO can be created."); - } + if (url.toLowerCase().contains("file://")) { + throw new InvalidParameterValueException("File:// type urls are currently unsupported", null); + } + + boolean allowPublicUserTemplates = Boolean.parseBoolean(_configDao.getValue("allow.public.user.templates")); + if (!isAdmin && !allowPublicUserTemplates && isPublic) { + throw new InvalidParameterValueException("Only private templates/ISO can be created.", null); + } + + if (!isAdmin || featured == null) { + featured = Boolean.FALSE; + } + + ImageFormat imgfmt = ImageFormat.valueOf(format.toUpperCase()); + if (imgfmt == null) { + throw new IllegalArgumentException("Image format is incorrect " + format + ". Supported formats are " + EnumUtils.listValues(ImageFormat.values())); + } - if (!isAdmin || featured == null) { - featured = Boolean.FALSE; - } - - ImageFormat imgfmt = ImageFormat.valueOf(format.toUpperCase()); - if (imgfmt == null) { - throw new IllegalArgumentException("Image format is incorrect " + format + ". Supported formats are " + EnumUtils.listValues(ImageFormat.values())); - } - // Check that the resource limit for templates/ISOs won't be exceeded UserVO user = _userDao.findById(userId); if (user == null) { throw new IllegalArgumentException("Unable to find user with id " + userId); } - + _resourceLimitMgr.checkResourceLimit(templateOwner, ResourceType.template); - + if (templateOwner.getType() != Account.ACCOUNT_TYPE_ADMIN && zoneId == null) { - throw new IllegalArgumentException("Only admins can create templates in all zones"); + throw new IllegalArgumentException("Only admins can create templates in all zones"); } - + // If a zoneId is specified, make sure it is valid if (zoneId != null) { - DataCenterVO zone = _dcDao.findById(zoneId); - if (zone == null) { - throw new IllegalArgumentException("Please specify a valid zone."); - } - Account caller = UserContext.current().getCaller(); - if(Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getType())){ - throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: "+ zoneId ); - } + DataCenterVO zone = _dcDao.findById(zoneId); + if (zone == null) { + throw new IllegalArgumentException("Please specify a valid zone."); + } + Account caller = UserContext.current().getCaller(); + if(Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getType())){ + throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: "+ zoneId ); + } } - + List systemvmTmplts = _tmpltDao.listAllSystemVMTemplates(); for (VMTemplateVO template : systemvmTmplts) { if (template.getName().equalsIgnoreCase(name) || template.getDisplayText().equalsIgnoreCase(displayText)) { throw new IllegalArgumentException("Cannot use reserved names for templates"); } } - + Long id = _tmpltDao.getNextInSequence(Long.class, "id"); UserContext.current().setEventDetails("Id: " +id+ " name: " + name); - return new TemplateProfile(id, userId, name, displayText, bits, passwordEnabled, requiresHVM, url, isPublic, - featured, isExtractable, imgfmt, guestOSId, zoneId, hypervisorType, templateOwner.getAccountName(), templateOwner.getDomainId(), templateOwner.getAccountId(), chksum, bootable, templateTag, details, sshkeyEnabled); - } - - @Override - public TemplateProfile prepare(RegisterTemplateCmd cmd) throws ResourceAllocationException { - //check if the caller can operate with the template owner + return new TemplateProfile(id, userId, name, displayText, bits, passwordEnabled, requiresHVM, url, isPublic, + featured, isExtractable, imgfmt, guestOSId, zoneId, hypervisorType, templateOwner.getAccountName(), templateOwner.getDomainId(), templateOwner.getAccountId(), chksum, bootable, templateTag, details, sshkeyEnabled); + } + + @Override + public TemplateProfile prepare(RegisterTemplateCmd cmd) throws ResourceAllocationException { + //check if the caller can operate with the template owner Account caller = UserContext.current().getCaller(); Account owner = _accountMgr.getAccount(cmd.getEntityOwnerId()); _accountMgr.checkAccess(caller, null, true, owner); - - return prepare(false, UserContext.current().getCallerUserId(), cmd.getTemplateName(), cmd.getDisplayText(), - cmd.getBits(), cmd.isPasswordEnabled(), cmd.getRequiresHvm(), cmd.getUrl(), cmd.isPublic(), cmd.isFeatured(), - cmd.isExtractable(), cmd.getFormat(), cmd.getOsTypeId(), cmd.getZoneId(), HypervisorType.getType(cmd.getHypervisor()), - cmd.getChecksum(), true, cmd.getTemplateTag(), owner, cmd.getDetails(), cmd.isSshKeyEnabled()); - } - public TemplateProfile prepare(RegisterIsoCmd cmd) throws ResourceAllocationException { - //check if the caller can operate with the template owner - Account caller = UserContext.current().getCaller(); - Account owner = _accountMgr.getAccount(cmd.getEntityOwnerId()); - _accountMgr.checkAccess(caller, null, true, owner); - - return prepare(true, UserContext.current().getCallerUserId(), cmd.getIsoName(), cmd.getDisplayText(), 64, false, - true, cmd.getUrl(), cmd.isPublic(), cmd.isFeatured(), cmd.isExtractable(), ImageFormat.ISO.toString(), cmd.getOsTypeId(), - cmd.getZoneId(), HypervisorType.None, cmd.getChecksum(), cmd.isBootable(), null, owner, null, false); - } - - protected VMTemplateVO persistTemplate(TemplateProfile profile) { - Long zoneId = profile.getZoneId(); - VMTemplateVO template = new VMTemplateVO(profile.getTemplateId(), profile.getName(), profile.getFormat(), profile.getIsPublic(), - profile.getFeatured(), profile.getIsExtractable(), TemplateType.USER, profile.getUrl(), profile.getRequiresHVM(), - profile.getBits(), profile.getAccountId(), profile.getCheckSum(), profile.getDisplayText(), - profile.getPasswordEnabled(), profile.getGuestOsId(), profile.getBootable(), profile.getHypervisorType(), profile.getTemplateTag(), - profile.getDetails(), profile.getSshKeyEnabled()); - - if (zoneId == null || zoneId.longValue() == -1) { + return prepare(false, UserContext.current().getCallerUserId(), cmd.getTemplateName(), cmd.getDisplayText(), + cmd.getBits(), cmd.isPasswordEnabled(), cmd.getRequiresHvm(), cmd.getUrl(), cmd.isPublic(), cmd.isFeatured(), + cmd.isExtractable(), cmd.getFormat(), cmd.getOsTypeId(), cmd.getZoneId(), HypervisorType.getType(cmd.getHypervisor()), + cmd.getChecksum(), true, cmd.getTemplateTag(), owner, cmd.getDetails(), cmd.isSshKeyEnabled()); + } + + @Override + public TemplateProfile prepare(RegisterIsoCmd cmd) throws ResourceAllocationException { + //check if the caller can operate with the template owner + Account caller = UserContext.current().getCaller(); + Account owner = _accountMgr.getAccount(cmd.getEntityOwnerId()); + _accountMgr.checkAccess(caller, null, true, owner); + + return prepare(true, UserContext.current().getCallerUserId(), cmd.getIsoName(), cmd.getDisplayText(), 64, false, + true, cmd.getUrl(), cmd.isPublic(), cmd.isFeatured(), cmd.isExtractable(), ImageFormat.ISO.toString(), cmd.getOsTypeId(), + cmd.getZoneId(), HypervisorType.None, cmd.getChecksum(), cmd.isBootable(), null, owner, null, false); + } + + protected VMTemplateVO persistTemplate(TemplateProfile profile) { + Long zoneId = profile.getZoneId(); + VMTemplateVO template = new VMTemplateVO(profile.getTemplateId(), profile.getName(), profile.getFormat(), profile.getIsPublic(), + profile.getFeatured(), profile.getIsExtractable(), TemplateType.USER, profile.getUrl(), profile.getRequiresHVM(), + profile.getBits(), profile.getAccountId(), profile.getCheckSum(), profile.getDisplayText(), + profile.getPasswordEnabled(), profile.getGuestOsId(), profile.getBootable(), profile.getHypervisorType(), profile.getTemplateTag(), + profile.getDetails(), profile.getSshKeyEnabled()); + + if (zoneId == null || zoneId.longValue() == -1) { List dcs = _dcDao.listAll(); - + if (dcs.isEmpty()) { - throw new CloudRuntimeException("No zones are present in the system, can't add template"); + throw new CloudRuntimeException("No zones are present in the system, can't add template"); } template.setCrossZones(true); - for (DataCenterVO dc: dcs) { - _tmpltDao.addTemplateToZone(template, dc.getId()); - } - + for (DataCenterVO dc: dcs) { + _tmpltDao.addTemplateToZone(template, dc.getId()); + } + } else { - _tmpltDao.addTemplateToZone(template, zoneId); + _tmpltDao.addTemplateToZone(template, zoneId); } - return _tmpltDao.findById(template.getId()); - } - + return _tmpltDao.findById(template.getId()); + } - private Long accountAndUserValidation(Account account, long userId, UserVmVO vmInstanceCheck, VMTemplateVO template, String msg) - throws PermissionDeniedException { - if (account != null) { - if (!isAdmin(account.getType())) { - if ((vmInstanceCheck != null) && (account.getId() != vmInstanceCheck.getAccountId())) { - throw new PermissionDeniedException(msg + ". Permission denied."); - } + private Long accountAndUserValidation(Account account, long userId, UserVmVO vmInstanceCheck, VMTemplateVO template, String msg) + throws PermissionDeniedException { - if ((template != null) - && (!template.isPublicTemplate() && (account.getId() != template.getAccountId()) && (template.getTemplateType() != TemplateType.PERHOST))) { - throw new PermissionDeniedException(msg + ". Permission denied."); - } + if (account != null) { + if (!isAdmin(account.getType())) { + if ((vmInstanceCheck != null) && (account.getId() != vmInstanceCheck.getAccountId())) { + throw new PermissionDeniedException(msg + ". Permission denied."); + } - } else { - if ((vmInstanceCheck != null) && !_domainDao.isChildDomain(account.getDomainId(), vmInstanceCheck.getDomainId())) { - throw new PermissionDeniedException(msg + ". Permission denied."); - } - // FIXME: if template/ISO owner is null we probably need to - // throw some kind of exception + if ((template != null) + && (!template.isPublicTemplate() && (account.getId() != template.getAccountId()) && (template.getTemplateType() != TemplateType.PERHOST))) { + throw new PermissionDeniedException(msg + ". Permission denied."); + } - if (template != null) { - Account templateOwner = _accountDao.findById(template.getAccountId()); - if ((templateOwner != null) && !_domainDao.isChildDomain(account.getDomainId(), templateOwner.getDomainId())) { - throw new PermissionDeniedException(msg + ". Permission denied."); - } - } - } - } + } else { + if ((vmInstanceCheck != null) && !_domainDao.isChildDomain(account.getDomainId(), vmInstanceCheck.getDomainId())) { + throw new PermissionDeniedException(msg + ". Permission denied."); + } + // FIXME: if template/ISO owner is null we probably need to + // throw some kind of exception - return userId; - } - - public TemplateProfile prepareDelete(DeleteTemplateCmd cmd) { - Long templateId = cmd.getId(); - Long userId = UserContext.current().getCallerUserId(); - Account account = UserContext.current().getCaller(); - Long zoneId = cmd.getZoneId(); + if (template != null) { + Account templateOwner = _accountDao.findById(template.getAccountId()); + if ((templateOwner != null) && !_domainDao.isChildDomain(account.getDomainId(), templateOwner.getDomainId())) { + throw new PermissionDeniedException(msg + ". Permission denied."); + } + } + } + } - VMTemplateVO template = _tmpltDao.findById(templateId.longValue()); - if (template == null) { - throw new InvalidParameterValueException("unable to find template with id " + templateId); - } + return userId; + } - userId = accountAndUserValidation(account, userId, null, template, "Unable to delete template "); - - UserVO user = _userDao.findById(userId); - if (user == null) { - throw new InvalidParameterValueException("Please specify a valid user."); - } - - if (template.getFormat() == ImageFormat.ISO) { - throw new InvalidParameterValueException("Please specify a valid template."); - } - - return new TemplateProfile(userId, template, zoneId); - } - - public TemplateProfile prepareDelete(DeleteIsoCmd cmd) { - Long templateId = cmd.getId(); + @Override + public TemplateProfile prepareDelete(DeleteTemplateCmd cmd) { + Long templateId = cmd.getId(); Long userId = UserContext.current().getCallerUserId(); Account account = UserContext.current().getCaller(); Long zoneId = cmd.getZoneId(); - + VMTemplateVO template = _tmpltDao.findById(templateId.longValue()); if (template == null) { - throw new InvalidParameterValueException("unable to find iso with id " + templateId); + throw new InvalidParameterValueException("unable to find template by id", null); } - - userId = accountAndUserValidation(account, userId, null, template, "Unable to delete iso " ); - - UserVO user = _userDao.findById(userId); - if (user == null) { - throw new InvalidParameterValueException("Please specify a valid user."); - } - - if (template.getFormat() != ImageFormat.ISO) { - throw new InvalidParameterValueException("Please specify a valid iso."); - } - - return new TemplateProfile(userId, template, zoneId); - } - abstract public VMTemplateVO create(TemplateProfile profile); - abstract public boolean delete(TemplateProfile profile); + userId = accountAndUserValidation(account, userId, null, template, "Unable to delete template "); + + UserVO user = _userDao.findById(userId); + if (user == null) { + throw new InvalidParameterValueException("Please specify a valid user.", null); + } + + if (template.getFormat() == ImageFormat.ISO) { + throw new InvalidParameterValueException("Please specify a valid template.", null); + } + + return new TemplateProfile(userId, template, zoneId); + } + + @Override + public TemplateProfile prepareDelete(DeleteIsoCmd cmd) { + Long templateId = cmd.getId(); + Long userId = UserContext.current().getCallerUserId(); + Account account = UserContext.current().getCaller(); + Long zoneId = cmd.getZoneId(); + + VMTemplateVO template = _tmpltDao.findById(templateId.longValue()); + if (template == null) { + throw new InvalidParameterValueException("unable to find iso by id", null); + } + + userId = accountAndUserValidation(account, userId, null, template, "Unable to delete iso " ); + + UserVO user = _userDao.findById(userId); + if (user == null) { + throw new InvalidParameterValueException("Please specify a valid user.", null); + } + + if (template.getFormat() != ImageFormat.ISO) { + throw new InvalidParameterValueException("Please specify a valid iso.", null); + } + + return new TemplateProfile(userId, template, zoneId); + } + + @Override + abstract public VMTemplateVO create(TemplateProfile profile); + @Override + abstract public boolean delete(TemplateProfile profile); } diff --git a/server/src/com/cloud/user/AccountManagerImpl.java b/server/src/com/cloud/user/AccountManagerImpl.java index 9e091164797..10094de7c2d 100755 --- a/server/src/com/cloud/user/AccountManagerImpl.java +++ b/server/src/com/cloud/user/AccountManagerImpl.java @@ -102,6 +102,7 @@ import com.cloud.user.Account.State; import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.UserAccountDao; import com.cloud.user.dao.UserDao; +import com.cloud.utils.IdentityProxy; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.Ternary; @@ -264,6 +265,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag return true; } + @Override public AccountVO getSystemAccount() { if (_systemAccount == null) { _systemAccount = _accountDao.findById(Account.ACCOUNT_ID_SYSTEM); @@ -354,7 +356,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (!granted) { assert false : "How can all of the security checkers pass on checking this check: " + entity; - throw new PermissionDeniedException("There's no way to confirm " + caller + " has access to " + entity); + throw new PermissionDeniedException("There's no way to confirm " + caller + " has access to " + entity); } } @@ -445,7 +447,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag @Override public boolean deleteAccount(AccountVO account, long callerUserId, Account caller) { long accountId = account.getId(); - + //delete the account record if (!_accountDao.remove(accountId)) { s_logger.error("Unable to delete account " + accountId); @@ -463,7 +465,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag public boolean cleanupAccount(AccountVO account, long callerUserId, Account caller) { long accountId = account.getId(); boolean accountCleanupNeeded = false; - + try { //cleanup the users from the account List users = _userDao.listByAccount(accountId); @@ -473,10 +475,10 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag accountCleanupNeeded = true; } } - + //delete the account from project accounts _projectAccountDao.removeAccountFromProjects(accountId); - + // delete all vm groups belonging to accont List groups = _vmGroupDao.listByAccountId(accountId); for (InstanceGroupVO group : groups) { @@ -598,7 +600,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag List ipsToRelease = _ipAddressDao.listByAccount(accountId); for (IpAddress ip : ipsToRelease) { s_logger.debug("Releasing ip " + ip + " as a part of account id=" + accountId + " cleanup"); - if (!_networkMgr.disassociatePublicIpAddress(ip.getId(), callerUserId, caller)) { + if (!_networkMgr.disassociatePublicIpAddress(ip.getId(), callerUserId, caller)) { s_logger.warn("Failed to release ip address " + ip + " as a part of account id=" + accountId + " clenaup"); accountCleanupNeeded = true; } @@ -704,37 +706,39 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (domainId == null) { domainId = DomainVO.ROOT_DOMAIN; } - + if (userName.isEmpty()) { - throw new InvalidParameterValueException("Username is empty"); + throw new InvalidParameterValueException("Username is empty", null); } - + if (firstName.isEmpty()) { - throw new InvalidParameterValueException("Firstname is empty"); + throw new InvalidParameterValueException("Firstname is empty", null); } - + if (lastName.isEmpty()) { - throw new InvalidParameterValueException("Lastname is empty"); + throw new InvalidParameterValueException("Lastname is empty", null); } // Validate domain Domain domain = _domainMgr.getDomain(domainId); if (domain == null) { - throw new InvalidParameterValueException("The domain " + domainId + " does not exist; unable to create account"); + throw new InvalidParameterValueException("The domain does not exist; unable to create account", null); } // Check permissions checkAccess(UserContext.current().getCaller(), domain); if (!_userAccountDao.validateUsernameInDomain(userName, domainId)) { - throw new InvalidParameterValueException("The user " + userName + " already exists in domain " + domainId); + List idList = new ArrayList(); + idList.add(new IdentityProxy(domain, domainId, "domainId")); + throw new InvalidParameterValueException("The user " + userName + " already exists in domain with specified id", idList); } if (networkDomain != null) { if (!NetUtils.verifyDomainName(networkDomain)) { throw new InvalidParameterValueException( "Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " - + "and the hyphen ('-'); can't start or end with \"-\""); + + "and the hyphen ('-'); can't start or end with \"-\"", null); } } @@ -778,7 +782,9 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag Account account = _accountDao.findEnabledAccount(accountName, domainId); if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain id=" + domainId + " to create user"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(domain, domainId, "domainId")); + throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain with specified id to create user", idList); } if (!_userAccountDao.validateUsernameInDomain(userName, domainId)) { @@ -807,11 +813,11 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag UserVO user = _userDao.getUser(id); if (user == null) { - throw new InvalidParameterValueException("unable to find user by id"); + throw new InvalidParameterValueException("unable to find user by id", null); } if ((apiKey == null && secretKey != null) || (apiKey != null && secretKey == null)) { - throw new InvalidParameterValueException("Please provide an userApiKey/userSecretKey pair"); + throw new InvalidParameterValueException("Please provide an userApiKey/userSecretKey pair", null); } // If the account is an admin type, return an error. We do not allow this @@ -819,7 +825,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag // don't allow updating project account if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - throw new InvalidParameterValueException("unable to find user by id"); + throw new InvalidParameterValueException("unable to find user by id", null); } if (account != null && (account.getId() == Account.ACCOUNT_ID_SYSTEM)) { @@ -830,37 +836,39 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (firstName != null) { if (firstName.isEmpty()) { - throw new InvalidParameterValueException("Firstname is empty"); + throw new InvalidParameterValueException("Firstname is empty", null); } - + user.setFirstname(firstName); } if (lastName != null) { if (lastName.isEmpty()) { - throw new InvalidParameterValueException("Lastname is empty"); + throw new InvalidParameterValueException("Lastname is empty", null); } - + user.setLastname(lastName); } if (userName != null) { if (userName.isEmpty()) { - throw new InvalidParameterValueException("Username is empty"); + throw new InvalidParameterValueException("Username is empty", null); } - + // don't allow to have same user names in the same domain List duplicatedUsers = _userDao.findUsersByName(userName); for (UserVO duplicatedUser : duplicatedUsers) { if (duplicatedUser.getId() != user.getId()) { Account duplicatedUserAccount = _accountDao.findById(duplicatedUser.getAccountId()); if (duplicatedUserAccount.getDomainId() == account.getDomainId()) { - throw new InvalidParameterValueException("User with name " + userName + " already exists in domain " + duplicatedUserAccount.getDomainId()); + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", duplicatedUserAccount.getDomainId(), "domainId")); + throw new InvalidParameterValueException("User with name " + userName + " already exists in domain with specified id", idList); } } } user.setUsername(userName); } - + if (password != null) { user.setPassword(password); } @@ -888,7 +896,9 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (apiKeyOwner != null) { User usr = apiKeyOwner.first(); if (usr.getId() != id) { - throw new InvalidParameterValueException("The api key:" + apiKey + " exists in the system for user id:" + id + " ,please provide a unique key"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(usr, id, "userId")); + throw new InvalidParameterValueException("The api key:" + apiKey + " exists in the system for user with specified id, please provide a unique key", idList); } else { // allow the updation to take place } @@ -911,19 +921,21 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag // Check if user exists in the system User user = _userDao.findById(userId); if (user == null || user.getRemoved() != null) { - throw new InvalidParameterValueException("Unable to find active user by id " + userId); + throw new InvalidParameterValueException("Unable to find active user by id ", null); } Account account = _accountDao.findById(user.getAccountId()); // don't allow disabling user belonging to project's account if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - throw new InvalidParameterValueException("Unable to find active user by id " + userId); + throw new InvalidParameterValueException("Unable to find active user by id", null); } // If the user is a System user, return an error if (account.getId() == Account.ACCOUNT_ID_SYSTEM) { - throw new InvalidParameterValueException("User id : " + userId + " is a system user, disabling is not allowed"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(user, userId, "userId")); + throw new InvalidParameterValueException("User with specified id is a system user, disabling is not allowed", idList); } checkAccess(caller, null, true, account); @@ -947,18 +959,20 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag // Check if user exists in the system User user = _userDao.findById(userId); if (user == null || user.getRemoved() != null) { - throw new InvalidParameterValueException("Unable to find active user by id " + userId); + throw new InvalidParameterValueException("Unable to find active user by id", null); } Account account = _accountDao.findById(user.getAccountId()); if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - throw new InvalidParameterValueException("Unable to find active user by id " + userId); + throw new InvalidParameterValueException("Unable to find active user by id", null); } // If the user is a System user, return an error if (account.getId() == Account.ACCOUNT_ID_SYSTEM) { - throw new InvalidParameterValueException("User id : " + userId + " is a system user, enabling is not allowed"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(user, userId, "userId")); + throw new InvalidParameterValueException("User with specified id is a system user, enabling is not allowed", idList); } checkAccess(caller, null, true, account); @@ -988,14 +1002,14 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag // Check if user with id exists in the system User user = _userDao.findById(userId); if (user == null || user.getRemoved() != null) { - throw new InvalidParameterValueException("Unable to find user by id"); + throw new InvalidParameterValueException("Unable to find user by id", null); } Account account = _accountDao.findById(user.getAccountId()); // don't allow to lock user of the account of type Project if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - throw new InvalidParameterValueException("Unable to find user by id"); + throw new InvalidParameterValueException("Unable to find user by id", null); } // If the user is a System user, return an error. We do not allow this @@ -1060,7 +1074,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag // don't allow removing Project account if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - throw new InvalidParameterValueException("The specified account does not exist in the system"); + throw new InvalidParameterValueException("The specified account does not exist in the system", null); } checkAccess(caller, null, true, account); @@ -1072,12 +1086,12 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag // Account that manages project(s) can't be removed List managedProjectIds = _projectAccountDao.listAdministratedProjectIds(accountId); if (!managedProjectIds.isEmpty()) { - StringBuilder projectIds = new StringBuilder(); + List idList = new ArrayList(); + idList.add(new IdentityProxy(account, accountId, "accountId")); for (Long projectId : managedProjectIds) { - projectIds.append(projectId + ", "); + idList.add(new IdentityProxy("projects", projectId, "projectId")); } - - throw new InvalidParameterValueException("The account id=" + accountId + " manages project(s) with ids " + projectIds + "and can't be removed"); + throw new InvalidParameterValueException("The account with specified id manages project(s) with specified ids and can't be removed", idList); } return deleteAccount(account, callerUserId, caller); @@ -1095,12 +1109,14 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - throw new InvalidParameterValueException("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", domainId, "domainId")); + throw new InvalidParameterValueException("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain with specified id", idList); } // Don't allow to modify system account if (account.getId() == Account.ACCOUNT_ID_SYSTEM) { - throw new InvalidParameterValueException("Can not modify system account"); + throw new InvalidParameterValueException("Can not modify system account", null); } // Check if user performing the action is allowed to modify this account @@ -1128,14 +1144,16 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - throw new InvalidParameterValueException("Unable to find active account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", domainId, "domainId")); + throw new InvalidParameterValueException("Unable to find active account by accountId: " + accountId + " OR by name: " + accountName + " in domain with specified id", idList); } checkAccess(caller, null, true, account); // don't allow modify system account if (account.getId() == Account.ACCOUNT_ID_SYSTEM) { - throw new InvalidParameterValueException("can not lock system account"); + throw new InvalidParameterValueException("can not lock system account", null); } if (lockAccount(account.getId())) { @@ -1158,7 +1176,9 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - throw new InvalidParameterValueException("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", domainId, "domainId")); + throw new InvalidParameterValueException("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain with specified id", idList); } checkAccess(caller, null, true, account); @@ -1191,34 +1211,34 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag // Check if account exists if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) { s_logger.error("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); - throw new InvalidParameterValueException("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", domainId, "domainId")); + throw new InvalidParameterValueException("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain with specified id", idList); } // Don't allow to modify system account if (account.getId() == Account.ACCOUNT_ID_SYSTEM) { - throw new InvalidParameterValueException("Can not modify system account"); + throw new InvalidParameterValueException("Can not modify system account", null); } // Check if user performing the action is allowed to modify this account checkAccess(UserContext.current().getCaller(), _domainMgr.getDomain(account.getDomainId())); // check if the given account name is unique in this domain for updating - Account duplicateAcccount = _accountDao.findActiveAccount(newAccountName, domainId); - if (duplicateAcccount != null && duplicateAcccount.getId() != account.getId()) {// allow - // same - // account - // to - // update - // itself - throw new InvalidParameterValueException("There already exists an account with the name:" + newAccountName + " in the domain:" + domainId + " with existing account id:" - + duplicateAcccount.getId()); + Account duplicateAccount = _accountDao.findActiveAccount(newAccountName, domainId); + if (duplicateAccount != null && duplicateAccount.getId() != account.getId()) { + // allow same account to update itself + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", domainId, "domainId")); + idList.add(new IdentityProxy(duplicateAccount, duplicateAccount.getId(), "accountId")); + throw new InvalidParameterValueException("There already exists an account with the name:" + newAccountName + " in domain with specified id, with existing account with specified id", idList); } if (networkDomain != null && !networkDomain.isEmpty()) { if (!NetUtils.verifyDomainName(networkDomain)) { throw new InvalidParameterValueException( "Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " - + "and the hyphen ('-'); can't start or end with \"-\""); + + "and the hyphen ('-'); can't start or end with \"-\"", null); } } @@ -1259,18 +1279,20 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag UserVO user = _userDao.findById(id); if (user == null) { - throw new InvalidParameterValueException("The specified user doesn't exist in the system"); + throw new InvalidParameterValueException("The specified user doesn't exist in the system", null); } Account account = _accountDao.findById(user.getAccountId()); // don't allow to delete the user from the account of type Project if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - throw new InvalidParameterValueException("The specified user doesn't exist in the system"); + throw new InvalidParameterValueException("The specified user doesn't exist in the system", null); } if (account.getId() == Account.ACCOUNT_ID_SYSTEM) { - throw new InvalidParameterValueException("Account id : " + user.getAccountId() + " is a system account, delete for user associated with this account is not allowed"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(account, user.getAccountId(), "accountId")); + throw new InvalidParameterValueException("Account with specified id is a system account, delete for user associated with this account is not allowed", idList); } checkAccess(UserContext.current().getCaller(), null, true, account); @@ -1377,18 +1399,18 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag public Account finalizeOwner(Account caller, String accountName, Long domainId, Long projectId) { // don't default the owner to the system account if (caller.getId() == Account.ACCOUNT_ID_SYSTEM && ((accountName == null || domainId == null) && projectId == null)) { - throw new InvalidParameterValueException("Account and domainId are needed for resource creation"); + throw new InvalidParameterValueException("Account and domainId are needed for resource creation", null); } // projectId and account/domainId can't be specified together if ((accountName != null && domainId != null) && projectId != null) { - throw new InvalidParameterValueException("ProjectId and account/domainId can't be specified together"); + throw new InvalidParameterValueException("ProjectId and account/domainId can't be specified together", null); } if (projectId != null) { Project project = _projectMgr.getProject(projectId); if (project == null) { - throw new InvalidParameterValueException("Unable to find project by id=" + projectId); + throw new InvalidParameterValueException("Unable to find project by id", null); } if (!_projectMgr.canAccessProjectAccount(caller, project.getProjectAccountId())) { @@ -1401,12 +1423,14 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (isAdmin(caller.getType()) && accountName != null && domainId != null) { Domain domain = _domainMgr.getDomain(domainId); if (domain == null) { - throw new InvalidParameterValueException("Unable to find the domain by id=" + domainId); + throw new InvalidParameterValueException("Unable to find domain by id", null); } Account owner = _accountDao.findActiveAccount(accountName, domainId); if (owner == null) { - throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", domainId, "domainId")); + throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain with specified id", idList); } checkAccess(caller, domain); @@ -1419,7 +1443,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } } else { if ((accountName == null && domainId != null) || (accountName != null && domainId == null)) { - throw new InvalidParameterValueException("AccountName and domainId must be specified together"); + throw new InvalidParameterValueException("AccountName and domainId must be specified together", null); } // regular user can't create/list resources for other people return caller; @@ -1429,7 +1453,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag @Override public Account getActiveAccountByName(String accountName, Long domainId) { if (accountName == null || domainId == null) { - throw new InvalidParameterValueException("Both accountName and domainId are required for finding active account in the system"); + throw new InvalidParameterValueException("Both accountName and domainId are required for finding active account in the system", null); } else { return _accountDao.findActiveAccount(accountName, domainId); } @@ -1438,7 +1462,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag @Override public Account getActiveAccountById(Long accountId) { if (accountId == null) { - throw new InvalidParameterValueException("AccountId is required by account search"); + throw new InvalidParameterValueException("AccountId is required by account search", null); } else { return _accountDao.findById(accountId); } @@ -1447,7 +1471,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag @Override public Account getAccount(Long accountId) { if (accountId == null) { - throw new InvalidParameterValueException("AccountId is required by account search"); + throw new InvalidParameterValueException("AccountId is required by account search", null); } else { return _accountDao.findByIdIncludingRemoved(accountId); } @@ -1469,11 +1493,11 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (isAdmin(caller.getType())) { if (domainId == null && accountName != null) { - throw new InvalidParameterValueException("accountName and domainId might be specified together"); + throw new InvalidParameterValueException("accountName and domainId might be specified together", null); } else if (domainId != null) { Domain domain = _domainMgr.getDomain(domainId); if (domain == null) { - throw new InvalidParameterValueException("Unable to find the domain by id=" + domainId); + throw new InvalidParameterValueException("Unable to find domain by id", null); } checkAccess(caller, domain); @@ -1481,7 +1505,9 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (accountName != null) { Account owner = getActiveAccountByName(accountName, domainId); if (owner == null) { - throw new InvalidParameterValueException("Unable to find account with name " + accountName + " in domain id=" + domainId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", domainId, "domainId")); + throw new InvalidParameterValueException("Unable to find account with name " + accountName + " in domain with specified id", idList); } permittedAccounts.add(owner.getId()); @@ -1508,10 +1534,12 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag permittedAccounts.clear(); Project project = _projectMgr.getProject(projectId); if (project == null) { - throw new InvalidParameterValueException("Unable to find project by id " + projectId); + throw new InvalidParameterValueException("Unable to find project by id ", null); } if (!_projectMgr.canAccessProjectAccount(caller, project.getProjectAccountId())) { - throw new InvalidParameterValueException("Account " + caller + " can't access project id=" + projectId); + List idList = new ArrayList(); + idList.add(new IdentityProxy(project, projectId, "projectId")); + throw new InvalidParameterValueException("Account " + caller + " can't access project with specified id", idList); } permittedAccounts.add(project.getProjectAccountId()); } @@ -1538,7 +1566,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag // Validate domain Domain domain = _domainMgr.getDomain(domainId); if (domain == null) { - throw new InvalidParameterValueException("The domain " + domainId + " does not exist; unable to create account"); + throw new InvalidParameterValueException("Domain does not exist; unable to create account", null); } if (domain.getState().equals(Domain.State.Inactive)) { @@ -1546,31 +1574,33 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } if ((domainId != DomainVO.ROOT_DOMAIN) && (accountType == Account.ACCOUNT_TYPE_ADMIN)) { - throw new InvalidParameterValueException("Invalid account type " + accountType + " given for an account in domain " + domainId + "; unable to create user."); + List idList = new ArrayList(); + idList.add(new IdentityProxy(domain, domainId, "domainId")); + throw new InvalidParameterValueException("Invalid account type " + accountType + " given for an account in domain with specified id; unable to create user.", idList); } // Validate account/user/domain settings if (_accountDao.findActiveAccount(accountName, domainId) != null) { - throw new InvalidParameterValueException("The specified account: " + accountName + " already exists"); + throw new InvalidParameterValueException("The specified account: " + accountName + " already exists", null); } if (networkDomain != null) { if (!NetUtils.verifyDomainName(networkDomain)) { throw new InvalidParameterValueException( "Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " - + "and the hyphen ('-'); can't start or end with \"-\""); + + "and the hyphen ('-'); can't start or end with \"-\"", null); } } // Verify account type if ((accountType < Account.ACCOUNT_TYPE_NORMAL) || (accountType > Account.ACCOUNT_TYPE_PROJECT)) { - throw new InvalidParameterValueException("Invalid account type " + accountType + " given; unable to create user"); + throw new InvalidParameterValueException("Invalid account type " + accountType + " given; unable to create user", null); } if (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { List dc = _dcDao.findZonesByDomainId(domainId); if (dc.isEmpty()) { - throw new InvalidParameterValueException("The account cannot be created as domain " + domain.getName() + " is not associated with any private Zone"); + throw new InvalidParameterValueException("The account cannot be created as domain " + domain.getName() + " is not associated with any private Zone", null); } } @@ -1808,8 +1838,8 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag public String[] createApiKeyAndSecretKey(RegisterCmd cmd) { Long userId = cmd.getId(); - if (getUserIncludingRemoved(userId) == null) { - throw new InvalidParameterValueException("unable to find user for id : " + userId); + if (getUserIncludingRemoved(userId) == null) { + throw new InvalidParameterValueException("unable to find user by id", null); } // generate both an api key and a secret key, update the user table with the keys, return the keys to the user @@ -1891,7 +1921,9 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (accountId != null) { Account account = _accountDao.findById(accountId); if (account == null || account.getId() == Account.ACCOUNT_ID_SYSTEM) { - throw new InvalidParameterValueException("Unable to find account by id " + accountId); + List idList = new ArrayList(); + idList.add(new IdentityProxy(account, accountId, "accountId")); + throw new InvalidParameterValueException("Unable to find account with specified id", idList); } checkAccess(caller, null, true, account); @@ -1900,7 +1932,9 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (domainId != null) { Domain domain = _domainMgr.getDomain(domainId); if (domain == null) { - throw new InvalidParameterValueException("Domain id=" + domainId + " doesn't exist"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(domain, domainId, "domainId")); + throw new InvalidParameterValueException("Domain with specified id doesn't exist", idList); } checkAccess(caller, domain); @@ -1908,7 +1942,9 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (accountName != null) { Account account = _accountDao.findActiveAccount(accountName, domainId); if (account == null || account.getId() == Account.ACCOUNT_ID_SYSTEM) { - throw new InvalidParameterValueException("Unable to find account by name " + accountName + " in domain " + domainId); + List idList = new ArrayList(); + idList.add(new IdentityProxy(domain, domainId, "domainId")); + throw new InvalidParameterValueException("Unable to find account by name " + accountName + " in domain with specified id", idList); } checkAccess(caller, null, true, account); } @@ -2005,7 +2041,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (domainId != null) { Domain domain = _domainDao.findById(domainId); if (domain == null) { - throw new InvalidParameterValueException("Unable to find domain by id=" + domainId); + throw new InvalidParameterValueException("Unable to find domain by id", null); } checkAccess(caller, domain); @@ -2169,7 +2205,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (domainId != null) { Domain domain = _domainDao.findById(domainId); if (domain == null) { - throw new InvalidParameterValueException("Unable to find domain by id " + domainId); + throw new InvalidParameterValueException("Unable to find domain by id", null); } // check permissions checkAccess(caller, domain); @@ -2177,7 +2213,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (accountName != null) { if (projectId != null) { - throw new InvalidParameterValueException("Account and projectId can't be specified together"); + throw new InvalidParameterValueException("Account and projectId can't be specified together", null); } Account userAccount = null; @@ -2190,7 +2226,9 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (userAccount != null) { permittedAccounts.add(userAccount.getId()); } else { - throw new InvalidParameterValueException("could not find account " + accountName + " in domain " + domainId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", domainId, "domainId")); + throw new InvalidParameterValueException("could not find account " + accountName + " in domain with specified id", idList); } } @@ -2206,7 +2244,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } else { Project project = _projectMgr.getProject(projectId); if (project == null) { - throw new InvalidParameterValueException("Unable to find project by id " + projectId); + throw new InvalidParameterValueException("Unable to find project by id", null); } if (!_projectMgr.canAccessProjectAccount(caller, project.getProjectAccountId())) { throw new PermissionDeniedException("Account " + caller + " can't access project id=" + projectId); diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java index 1ea462c72d2..962d3844a13 100755 --- a/server/src/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/com/cloud/vm/UserVmManagerImpl.java @@ -196,6 +196,7 @@ import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.SSHKeyPairDao; import com.cloud.user.dao.UserDao; import com.cloud.uservm.UserVm; +import com.cloud.utils.IdentityProxy; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.PasswordGenerator; @@ -376,17 +377,19 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // Do parameters input validation if (userVm == null) { - throw new InvalidParameterValueException("unable to find a virtual machine with id " + cmd.getId()); + throw new InvalidParameterValueException("unable to find a virtual machine by id", null); } VMTemplateVO template = _templateDao.findByIdIncludingRemoved(userVm.getTemplateId()); if (template == null || !template.getEnablePassword()) { - throw new InvalidParameterValueException("Fail to reset password for the virtual machine, the template is not password enabled"); + throw new InvalidParameterValueException("Fail to reset password for the virtual machine, the template is not password enabled", null); } if (userVm.getState() == State.Error || userVm.getState() == State.Expunging) { s_logger.error("vm is not in the right state: " + vmId); - throw new InvalidParameterValueException("Vm with id " + vmId + " is not in the right state"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(userVm, vmId, "vmId")); + throw new InvalidParameterValueException("Vm with specified id is not in the right state", idList); } _accountMgr.checkAccess(caller, null, true, userVm); @@ -454,7 +457,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager s_logger.debug("Vm " + vmInstance + " is stopped, not rebooting it as a part of password reset"); return true; } - + if (rebootVirtualMachine(userId, vmId) == null) { s_logger.warn("Failed to reboot the vm " + vmInstance); return false; @@ -514,68 +517,68 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager VolumeVO volume = _volsDao.findById(volumeId); // Check that the volume is a data volume if (volume == null || volume.getVolumeType() != Volume.Type.DATADISK) { - throw new InvalidParameterValueException("Please specify a valid data volume."); + throw new InvalidParameterValueException("Please specify a valid data volume.", null); } // Check that the volume is not currently attached to any VM if (volume.getInstanceId() != null) { - throw new InvalidParameterValueException("Please specify a volume that is not attached to any VM."); + throw new InvalidParameterValueException("Please specify a volume that is not attached to any VM.", null); } // Check that the volume is not destroyed if (volume.getState() == Volume.State.Destroy) { - throw new InvalidParameterValueException("Please specify a volume that is not destroyed."); + throw new InvalidParameterValueException("Please specify a volume that is not destroyed.", null); } // Check that the virtual machine ID is valid and it's a user vm UserVmVO vm = _vmDao.findById(vmId); if (vm == null || vm.getType() != VirtualMachine.Type.User) { - throw new InvalidParameterValueException("Please specify a valid User VM."); + throw new InvalidParameterValueException("Please specify a valid User VM.", null); } // Check that the VM is in the correct state if (vm.getState() != State.Running && vm.getState() != State.Stopped) { - throw new InvalidParameterValueException("Please specify a VM that is either running or stopped."); + throw new InvalidParameterValueException("Please specify a VM that is either running or stopped.", null); } // Check that the device ID is valid if (deviceId != null) { if (deviceId.longValue() == 0) { - throw new InvalidParameterValueException("deviceId can't be 0, which is used by Root device"); + throw new InvalidParameterValueException("deviceId can't be 0, which is used by Root device", null); } } // Check that the VM has less than 6 data volumes attached List existingDataVolumes = _volsDao.findByInstanceAndType(vmId, Volume.Type.DATADISK); if (existingDataVolumes.size() >= 6) { - throw new InvalidParameterValueException("The specified VM already has the maximum number of data disks (6). Please specify another VM."); + throw new InvalidParameterValueException("The specified VM already has the maximum number of data disks (6). Please specify another VM.", null); } // Check that the VM and the volume are in the same zone if (vm.getDataCenterIdToDeployIn() != volume.getDataCenterId()) { - throw new InvalidParameterValueException("Please specify a VM that is in the same zone as the volume."); + throw new InvalidParameterValueException("Please specify a VM that is in the same zone as the volume.", null); } //permission check _accountMgr.checkAccess(caller, null, true, volume, vm); - + //Check if volume is stored on secondary Storage. boolean isVolumeOnSec = false; VolumeHostVO volHostVO = _volumeHostDao.findByVolumeId(volume.getId()); if (volHostVO != null){ - isVolumeOnSec = true; - if( !(volHostVO.getDownloadState() == Status.DOWNLOADED) ){ - throw new InvalidParameterValueException("Volume is not uploaded yet. Please try this operation once the volume is uploaded"); - } + isVolumeOnSec = true; + if( !(volHostVO.getDownloadState() == Status.DOWNLOADED) ){ + throw new InvalidParameterValueException("Volume is not uploaded yet. Please try this operation once the volume is uploaded", null); + } } //If the volume is Ready, check that the volume is stored on shared storage if (!(Volume.State.Allocated.equals(volume.getState()) || Volume.State.UploadOp.equals(volume.getState())) && !_storageMgr.volumeOnSharedStoragePool(volume)) { - throw new InvalidParameterValueException("Please specify a volume that has been created on a shared storage pool."); + throw new InvalidParameterValueException("Please specify a volume that has been created on a shared storage pool.", null); } if ( !(Volume.State.Allocated.equals(volume.getState()) || Volume.State.Ready.equals(volume.getState()) || Volume.State.UploadOp.equals(volume.getState())) ) { - throw new InvalidParameterValueException("Volume state must be in Allocated, Ready or in Uploaded state"); + throw new InvalidParameterValueException("Volume state must be in Allocated, Ready or in Uploaded state", null); } VolumeVO rootVolumeOfVm = null; @@ -589,9 +592,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager HypervisorType rootDiskHyperType = vm.getHypervisorType(); HypervisorType dataDiskHyperType = _volsDao.getHypervisorType(volume.getId()); if (dataDiskHyperType != HypervisorType.None && rootDiskHyperType != dataDiskHyperType) { - throw new InvalidParameterValueException("Can't attach a volume created by: " + dataDiskHyperType + " to a " + rootDiskHyperType + " vm"); + throw new InvalidParameterValueException("Can't attach a volume created by: " + dataDiskHyperType + " to a " + rootDiskHyperType + " vm", null); } - + //allocate deviceId List vols = _volsDao.findByInstance(vmId); if (deviceId != null) { @@ -615,12 +618,12 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } deviceId = Long.parseLong(devIds.iterator().next()); } - + boolean createVolumeOnBackend = true; if (rootVolumeOfVm.getState() == Volume.State.Allocated) { createVolumeOnBackend = false; if(isVolumeOnSec){ - throw new CloudRuntimeException("Cant attach uploaded volume to the vm which is not created. Please start it and then retry"); + throw new CloudRuntimeException("Cant attach uploaded volume to the vm which is not created. Please start it and then retry"); } } @@ -635,34 +638,34 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager ServiceOfferingVO svo = _serviceOfferingDao.findById(vm.getServiceOfferingId()); DiskOfferingVO diskVO = _diskOfferingDao.findById(volume.getDiskOfferingId()); Long clusterId = (rootDiskPool == null ? null : rootDiskPool.getClusterId()); - + if (!isVolumeOnSec){ - volume = _storageMgr.createVolume(volume, vm, rootDiskTmplt, dcVO, pod, clusterId, svo, diskVO, new ArrayList(), volume.getSize(), rootDiskHyperType); + volume = _storageMgr.createVolume(volume, vm, rootDiskTmplt, dcVO, pod, clusterId, svo, diskVO, new ArrayList(), volume.getSize(), rootDiskHyperType); }else { - try { - // Format of data disk should be the same as root disk - if( ! volHostVO.getFormat().getFileExtension().equals(_storageMgr.getSupportedImageFormatForCluster(rootDiskPool.getClusterId())) ){ - throw new InvalidParameterValueException("Failed to attach volume to VM since volumes format " +volHostVO.getFormat().getFileExtension() + " is not compatible with the vm hypervisor type" ); - } - - // Check that there is some shared storage. + try { + // Format of data disk should be the same as root disk + if( ! volHostVO.getFormat().getFileExtension().equals(_storageMgr.getSupportedImageFormatForCluster(rootDiskPool.getClusterId())) ){ + throw new InvalidParameterValueException("Failed to attach volume to VM since volumes format " +volHostVO.getFormat().getFileExtension() + " is not compatible with the vm hypervisor type", null); + } + + // Check that there is some shared storage. StoragePoolVO vmRootVolumePool = _storagePoolDao.findById(rootVolumeOfVm.getPoolId()); List sharedVMPools = _storagePoolDao.findPoolsByTags(vmRootVolumePool.getDataCenterId(), vmRootVolumePool.getPodId(), vmRootVolumePool.getClusterId(), null, true); if (sharedVMPools.size() == 0) { throw new CloudRuntimeException("Cannot attach volume since there are no shared storage pools in the VM's cluster to copy the uploaded volume to."); } - - volume = _storageMgr.copyVolumeFromSecToPrimary(volume, vm, rootDiskTmplt, dcVO, pod, rootDiskPool.getClusterId(), svo, diskVO, new ArrayList(), volume.getSize(), rootDiskHyperType); - } catch (NoTransitionException e) { - throw new CloudRuntimeException("Unable to transition the volume ",e); - } + + volume = _storageMgr.copyVolumeFromSecToPrimary(volume, vm, rootDiskTmplt, dcVO, pod, rootDiskPool.getClusterId(), svo, diskVO, new ArrayList(), volume.getSize(), rootDiskHyperType); + } catch (NoTransitionException e) { + throw new CloudRuntimeException("Unable to transition the volume ",e); + } } if (volume == null) { throw new CloudRuntimeException("Failed to create volume when attaching it to VM: " + vm.getHostName()); } } - + StoragePoolVO vmRootVolumePool = _storagePoolDao.findById(rootVolumeOfVm.getPoolId()); DiskOfferingVO volumeDiskOffering = _diskOfferingDao.findById(volume.getDiskOfferingId()); String[] volumeTags = volumeDiskOffering.getTagsArray(); @@ -695,7 +698,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } } } - + if (moveVolumeNeeded) { // Move the volume to a storage pool in the VM's zone, pod, or cluster try { @@ -767,7 +770,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager Account caller = UserContext.current().getCaller(); if ((cmmd.getId() == null && cmmd.getDeviceId() == null && cmmd.getVirtualMachineId() == null) || (cmmd.getId() != null && (cmmd.getDeviceId() != null || cmmd.getVirtualMachineId() != null)) || (cmmd.getId() == null && (cmmd.getDeviceId() == null || cmmd.getVirtualMachineId() == null))) { - throw new InvalidParameterValueException("Please provide either a volume id, or a tuple(device id, instance id)"); + throw new InvalidParameterValueException("Please provide either a volume id, or a tuple(device id, instance id)", null); } Long volumeId = cmmd.getId(); @@ -789,7 +792,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // Check that the volume ID is valid if (volume == null) { - throw new InvalidParameterValueException("Unable to find volume with ID: " + volumeId); + throw new InvalidParameterValueException("Unable to find volume by ID", null); } // Permissions check @@ -797,23 +800,23 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // Check that the volume is a data volume if (volume.getVolumeType() != Volume.Type.DATADISK) { - throw new InvalidParameterValueException("Please specify a data volume."); + throw new InvalidParameterValueException("Please specify a data volume.", null); } - + // Check that the volume is currently attached to a VM if (vmId == null) { - throw new InvalidParameterValueException("The specified volume is not attached to a VM."); + throw new InvalidParameterValueException("The specified volume is not attached to a VM.", null); } // Check that the volume is stored on shared storage if (volume.getState() != Volume.State.Allocated && !_storageMgr.volumeOnSharedStoragePool(volume)) { - throw new InvalidParameterValueException("Please specify a volume that has been created on a shared storage pool."); + throw new InvalidParameterValueException("Please specify a volume that has been created on a shared storage pool.", null); } // Check that the VM is in the correct state UserVmVO vm = _vmDao.findById(vmId); if (vm.getState() != State.Running && vm.getState() != State.Stopped && vm.getState() != State.Destroyed) { - throw new InvalidParameterValueException("Please specify a VM that is either running or stopped."); + throw new InvalidParameterValueException("Please specify a VM that is either running or stopped.", null); } AsyncJobExecutor asyncExecutor = BaseAsyncJobExecutor.getCurrentExecutor(); @@ -944,14 +947,14 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // Verify input parameters UserVmVO vmInstance = _vmDao.findById(vmId); if (vmInstance == null) { - throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); + throw new InvalidParameterValueException("unable to find virtual machine by id ", null); } _accountMgr.checkAccess(caller, null, true, vmInstance); // Check that the specified service offering ID is valid _itMgr.checkIfCanUpgrade(vmInstance, svcOffId); - + _itMgr.upgradeVmDb(vmId, svcOffId); return _vmDao.findById(vmInstance.getId()); @@ -1004,7 +1007,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager UserVmVO vm = _vmDao.findById(vmId.longValue()); if (vm == null) { - throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); + throw new InvalidParameterValueException("unable to find virtual machine by id ", null); } //check permissions @@ -1014,14 +1017,16 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find vm or vm is removed: " + vmId); } - throw new InvalidParameterValueException("Unable to find vm by id " + vmId); + throw new InvalidParameterValueException("unable to find virtual machine by id ", null); } if (vm.getState() != State.Destroyed) { if (s_logger.isDebugEnabled()) { s_logger.debug("vm is not in the right state: " + vmId); } - throw new InvalidParameterValueException("Vm with id " + vmId + " is not in the right state"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(vm, vmId, "vmId")); + throw new InvalidParameterValueException("Vm with specified id is not in the right state", idList); } if (s_logger.isDebugEnabled()) { @@ -1047,10 +1052,14 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager try { if (!_itMgr.stateTransitTo(vm, VirtualMachine.Event.RecoveryRequested, null)) { s_logger.debug("Unable to recover the vm because it is not in the correct state: " + vmId); - throw new InvalidParameterValueException("Unable to recover the vm because it is not in the correct state: " + vmId); + List idList = new ArrayList(); + idList.add(new IdentityProxy(vm, vmId, "vmId")); + throw new InvalidParameterValueException("Unable to recover the vm with specified id because it is not in the correct state", idList); } } catch (NoTransitionException e) { - throw new InvalidParameterValueException("Unable to recover the vm because it is not in the correct state: " + vmId); + List idList = new ArrayList(); + idList.add(new IdentityProxy(vm, vmId, "vmId")); + throw new InvalidParameterValueException("Unable to recover the vm with specified id because it is not in the correct state", idList); } // Recover the VM's disks @@ -1163,7 +1172,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager ctx.setAccountId(vm.getAccountId()); try { - //expunge the vm + //expunge the vm if (!_itMgr.advanceExpunge(vm, _accountMgr.getSystemUser(), caller)) { s_logger.info("Did not expunge " + vm); return false; @@ -1267,7 +1276,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager String name = cmd.getTemplateName(); if ((name == null) || (name.length() > 32)) { - throw new InvalidParameterValueException("Template name cannot be null and should be less than 32 characters"); + throw new InvalidParameterValueException("Template name cannot be null and should be less than 32 characters", null); } if(cmd.getTemplateTag() != null){ @@ -1296,10 +1305,10 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager Long volumeId = cmd.getVolumeId(); Long snapshotId = cmd.getSnapshotId(); if ((volumeId == null) && (snapshotId == null)) { - throw new InvalidParameterValueException("Failed to create private template record, neither volume ID nor snapshot ID were specified."); + throw new InvalidParameterValueException("Failed to create private template record, neither volume ID nor snapshot ID were specified.", null); } if ((volumeId != null) && (snapshotId != null)) { - throw new InvalidParameterValueException("Failed to create private template record, please specify only one of volume ID (" + volumeId + ") and snapshot ID (" + snapshotId + ")"); + throw new InvalidParameterValueException("Failed to create private template record, please specify only one of volume ID (" + volumeId + ") and snapshot ID (" + snapshotId + ")", null); } HypervisorType hyperType; @@ -1308,7 +1317,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (volumeId != null) { // create template from volume volume = _volsDao.findById(volumeId); if (volume == null) { - throw new InvalidParameterValueException("Failed to create private template record, unable to find volume " + volumeId); + throw new InvalidParameterValueException("Failed to create private template record, unable to find volume by id", null); } //check permissions _accountMgr.checkAccess(caller, null, true, volume); @@ -1326,9 +1335,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } else { // create template from snapshot SnapshotVO snapshot = _snapshotDao.findById(snapshotId); if (snapshot == null) { - throw new InvalidParameterValueException("Failed to create private template record, unable to find snapshot " + snapshotId); + throw new InvalidParameterValueException("Failed to create private template record, unable to find snapshot by id", null); } - + volume = _volsDao.findById(snapshot.getVolumeId()); VolumeVO snapshotVolume = _volsDao.findByIdIncludingRemoved(snapshot.getVolumeId()); @@ -1336,16 +1345,18 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager _accountMgr.checkAccess(caller, null, true, snapshot); if (snapshot.getStatus() != Snapshot.Status.BackedUp) { - throw new InvalidParameterValueException("Snapshot id=" + snapshotId + " is not in " + Snapshot.Status.BackedUp + " state yet and can't be used for template creation"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(snapshot, snapshotId, "snapshotId")); + throw new InvalidParameterValueException("Snapshot with specified id is not in " + Snapshot.Status.BackedUp + " state yet and can't be used for template creation", idList); } -/* + /* // bug #11428. Operation not supported if vmware and snapshots parent volume = ROOT if(snapshot.getHypervisorType() == HypervisorType.VMware && snapshotVolume.getVolumeType() == Type.DATADISK){ throw new UnsupportedServiceException("operation not supported, snapshot with id " + snapshotId + " is created from Data Disk"); } -*/ - + */ + hyperType = snapshot.getHypervisorType(); } @@ -1357,7 +1368,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager Long guestOSId = cmd.getOsTypeId(); GuestOSVO guestOS = _guestOSDao.findById(guestOSId); if (guestOS == null) { - throw new InvalidParameterValueException("GuestOS with ID: " + guestOSId + " does not exist."); + throw new InvalidParameterValueException("Couldn't find GuestOS by id", null); } String uniqueName = Long.valueOf((userId == null) ? 1 : userId).toString() + UUID.nameUUIDFromBytes(name.getBytes()).toString(); @@ -1393,19 +1404,19 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager VMTemplateVO template = _templateDao.persist(privateTemplate); // Increment the number of templates if (template != null) { - if(cmd.getDetails() != null) { - _templateDetailsDao.persist(template.getId(), cmd.getDetails()); - } - + if(cmd.getDetails() != null) { + _templateDetailsDao.persist(template.getId(), cmd.getDetails()); + } + _resourceLimitMgr.incrementResourceCount(templateOwner.getId(), ResourceType.template); } if (template != null){ - return template; + return template; }else { - throw new CloudRuntimeException("Failed to create a template"); + throw new CloudRuntimeException("Failed to create a template"); } - + } @Override @@ -1605,11 +1616,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager txn.commit(); } } - + if (privateTemplate != null){ - return privateTemplate; + return privateTemplate; }else { - throw new CloudRuntimeException("Failed to create a template"); + throw new CloudRuntimeException("Failed to create a template"); } } @@ -1631,10 +1642,10 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // used for vm transitioning to error state private void updateVmStateForFailedVmCreation(Long vmId) { - + UserVmVO vm = _vmDao.findById(vmId); - - + + if (vm != null) { if (vm.getState().equals(State.Stopped)) { s_logger.debug("Destroying vm " + vm + " as it failed to create"); @@ -1721,12 +1732,12 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager vmInstance = _vmDao.findById(id.longValue()); if (vmInstance == null) { - throw new InvalidParameterValueException("unable to find virtual machine with id " + id); + throw new InvalidParameterValueException("unable to find virtual machine by id ", null); } ServiceOffering offering = _serviceOfferingDao.findById(vmInstance.getServiceOfferingId()); if (!offering.getOfferHA() && ha != null && ha) { - throw new InvalidParameterValueException("Can't enable ha for the vm as it's created from the Service offering having HA disabled"); + throw new InvalidParameterValueException("Can't enable ha for the vm as it's created from the Service offering having HA disabled", null); } _accountMgr.checkAccess(UserContext.current().getCaller(), null, true, vmInstance); @@ -1746,7 +1757,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (vm.getState() == State.Error || vm.getState() == State.Expunging) { s_logger.error("vm is not in the right state: " + id); - throw new InvalidParameterValueException("Vm with id " + id + " is not in the right state"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(vm, id, "vmId")); + throw new InvalidParameterValueException("Vm with specified id is not in the right state", idList); } if (userData != null) { @@ -1801,7 +1814,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // Verify input parameters UserVmVO vmInstance = _vmDao.findById(vmId.longValue()); if (vmInstance == null) { - throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); + throw new InvalidParameterValueException("unable to find a virtual machine by id ", null); } _accountMgr.checkAccess(caller, null, true, vmInstance); @@ -1831,7 +1844,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager boolean isNameInUse = _vmGroupDao.isNameInUse(accountId, groupName); if (isNameInUse) { - throw new InvalidParameterValueException("Unable to create vm group, a group with name " + groupName + " already exisits for account " + accountId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("account", accountId, "accountId")); + throw new InvalidParameterValueException("Unable to create vm group, a group with name " + groupName + " already exisits for account with specified id", idList); } return createVmGroup(groupName, accountId); @@ -1870,7 +1885,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // Verify input parameters InstanceGroupVO group = _vmGroupDao.findById(groupId); if ((group == null) || (group.getRemoved() != null)) { - throw new InvalidParameterValueException("unable to find a vm group with id " + groupId); + throw new InvalidParameterValueException("unable to find vm group by id", null); } _accountMgr.checkAccess(caller, null, true, group); @@ -2005,7 +2020,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager Network defaultNetwork = _networkMgr.getExclusiveGuestNetwork(zone.getId()); if (defaultNetwork == null) { - throw new InvalidParameterValueException("Unable to find a default network to start a vm"); + throw new InvalidParameterValueException("Unable to find a default network to start a vm", null); } else { networkList.add(_networkDao.findById(defaultNetwork.getId())); } @@ -2013,7 +2028,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager boolean isVmWare = (template.getHypervisorType() == HypervisorType.VMware || (hypervisor != null && hypervisor == HypervisorType.VMware)); if (securityGroupIdList != null && isVmWare) { - throw new InvalidParameterValueException("Security group feature is not supported for vmWare hypervisor"); + throw new InvalidParameterValueException("Security group feature is not supported for vmWare hypervisor", null); } else if (!isVmWare && _networkMgr.isSecurityGroupSupportedInNetwork(defaultNetwork) && _networkMgr.canAddDefaultSecurityGroup()) { //add the default securityGroup only if no security group is specified if(securityGroupIdList == null || securityGroupIdList.isEmpty()){ @@ -2064,11 +2079,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } else if (securityGroupIdList != null && !securityGroupIdList.isEmpty()) { if (isVmWare) { - throw new InvalidParameterValueException("Security group feature is not supported for vmWare hypervisor"); + throw new InvalidParameterValueException("Security group feature is not supported for vmWare hypervisor", null); } // Only one network can be specified, and it should be security group enabled if (networkIdList.size() > 1) { - throw new InvalidParameterValueException("Only support one network per VM if security group enabled"); + throw new InvalidParameterValueException("Only support one network per VM if security group enabled", null); } NetworkVO network = _networkDao.findById(networkIdList.get(0).longValue()); @@ -2096,11 +2111,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager boolean isSecurityGroupEnabled = _networkMgr.isSecurityGroupSupportedInNetwork(network); if (isSecurityGroupEnabled && networkIdList.size() > 1) { - throw new InvalidParameterValueException("Can't create a vm with multiple networks one of which is Security Group enabled"); + throw new InvalidParameterValueException("Can't create a vm with multiple networks one of which is Security Group enabled", null); } if (network.getTrafficType() != TrafficType.Guest || network.getGuestType() != Network.GuestType.Shared || (network.getGuestType() == Network.GuestType.Shared && !isSecurityGroupEnabled)) { - throw new InvalidParameterValueException("Can specify only Direct Guest Account specific networks when deploy vm in Security Group enabled zone"); + throw new InvalidParameterValueException("Can specify only Direct Guest Account specific networks when deploy vm in Security Group enabled zone", null); } // Perform account permission check @@ -2118,13 +2133,13 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // if network is security group enabled, and no security group is specified, then add the default security group automatically if (isSecurityGroupEnabledNetworkUsed && !isVmWare && _networkMgr.canAddDefaultSecurityGroup()) { - - //add the default securityGroup only if no security group is specified + + //add the default securityGroup only if no security group is specified if(securityGroupIdList == null || securityGroupIdList.isEmpty()){ if (securityGroupIdList == null) { securityGroupIdList = new ArrayList(); } - + SecurityGroup defaultGroup = _securityGroupMgr.getDefaultSecurityGroup(owner.getId()); if (defaultGroup != null) { securityGroupIdList.add(defaultGroup.getId()); @@ -2153,7 +2168,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // Verify that caller can perform actions in behalf of vm owner _accountMgr.checkAccess(caller, null, true, owner); - + if (networkIdList == null || networkIdList.isEmpty()) { NetworkVO defaultNetwork = null; @@ -2165,9 +2180,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager List requiredOfferings = _networkOfferingDao.listByAvailability(Availability.Required, false); if (requiredOfferings.size() < 1) { - throw new InvalidParameterValueException("Unable to find network offering with availability=" + Availability.Required + " to automatically create the network as a part of vm creation"); + throw new InvalidParameterValueException("Unable to find network offering with availability=" + Availability.Required + " to automatically create the network as a part of vm creation", null); } - + PhysicalNetwork physicalNetwork = _networkMgr.translateZoneIdToPhysicalNetwork(zone.getId()); if (requiredOfferings.get(0).getState() == NetworkOffering.State.Enabled) { // get Virtual networks @@ -2175,18 +2190,18 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (virtualNetworks.isEmpty()) { s_logger.debug("Creating network for account " + owner + " from the network offering id=" + - requiredOfferings.get(0).getId() + " as a part of deployVM process"); + requiredOfferings.get(0).getId() + " as a part of deployVM process"); Network newNetwork = _networkMgr.createGuestNetwork(requiredOfferings.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", null, null, null, null, owner, null, physicalNetwork, zone.getId(), ACLType.Account, null, null); defaultNetwork = _networkDao.findById(newNetwork.getId()); } else if (virtualNetworks.size() > 1) { - throw new InvalidParameterValueException("More than 1 default Isolated networks are found for account " + owner + "; please specify networkIds"); + throw new InvalidParameterValueException("More than 1 default Isolated networks are found for account " + owner + "; please specify networkIds", null); } else { defaultNetwork = virtualNetworks.get(0); } } else { - throw new InvalidParameterValueException("Required network offering id=" + requiredOfferings.get(0).getId() + " is not in " + NetworkOffering.State.Enabled); + throw new InvalidParameterValueException("Required network offering id=" + requiredOfferings.get(0).getId() + " is not in " + NetworkOffering.State.Enabled); } networkList.add(defaultNetwork); @@ -2217,11 +2232,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager Long diskSize, List networkList, List securityGroupIdList, String group, String userData, String sshKeyPair, HypervisorType hypervisor, Account caller, Map requestedIps, String defaultNetworkIp, String keyboard) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException, StorageUnavailableException, ResourceAllocationException { _accountMgr.checkAccess(caller, null, true, owner); - + if (owner.getState() == Account.State.disabled) { throw new PermissionDeniedException("The owner of vm to deploy is disabled: " + owner); } - + long accountId = owner.getId(); assert !(requestedIps != null && defaultNetworkIp != null) : "requestedIp list and defaultNetworkIp should never be specified together"; @@ -2248,12 +2263,12 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager //verify security group ids if (securityGroupIdList != null) { for (Long securityGroupId : securityGroupIdList) { - SecurityGroup sg = _securityGroupDao.findById(securityGroupId); + SecurityGroup sg = _securityGroupDao.findById(securityGroupId); if (sg == null) { throw new InvalidParameterValueException("Unable to find security group by id " + securityGroupId); } else { - //verify permissions - _accountMgr.checkAccess(caller, null, true, owner, sg); + //verify permissions + _accountMgr.checkAccess(caller, null, true, owner, sg); } } } @@ -2295,13 +2310,13 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } DiskOfferingVO diskOffering = _diskOfferingDao.findById(diskOfferingId); if (diskOffering == null) { - throw new InvalidParameterValueException("Unable to find disk offering " + diskOfferingId); + throw new InvalidParameterValueException("Unable to find disk offering by id", null); } Long size = null; if (diskOffering.getDiskSize() == 0) { size = diskSize; if (size == null) { - throw new InvalidParameterValueException("Disk offering " + diskOffering + " requires size parameter."); + throw new InvalidParameterValueException("Disk offering " + diskOffering + " requires size parameter.", null); } } rootDiskOffering.first(diskOffering); @@ -2311,13 +2326,13 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (diskOfferingId != null) { DiskOfferingVO diskOffering = _diskOfferingDao.findById(diskOfferingId); if (diskOffering == null) { - throw new InvalidParameterValueException("Unable to find disk offering " + diskOfferingId); + throw new InvalidParameterValueException("Unable to find disk offering by id", null); } Long size = null; if (diskOffering.getDiskSize() == 0) { size = diskSize; if (size == null) { - throw new InvalidParameterValueException("Disk offering " + diskOffering + " requires size parameter."); + throw new InvalidParameterValueException("Disk offering " + diskOffering + " requires size parameter.", null); } } dataDiskOfferings.add(new Pair(diskOffering, size)); @@ -2332,7 +2347,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (sshKeyPair != null && !sshKeyPair.equals("")) { SSHKeyPair pair = _sshKeyPairDao.findByName(owner.getAccountId(), owner.getDomainId(), sshKeyPair); if (pair == null) { - throw new InvalidParameterValueException("A key pair with name '" + sshKeyPair + "' was not found."); + throw new InvalidParameterValueException("A key pair with name '" + sshKeyPair + "' was not found.", null); } sshPublicKey = pair.getPublicKey(); @@ -2345,22 +2360,22 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (network.getDataCenterId() != zone.getId()) { throw new InvalidParameterValueException("Network id=" + network.getId() + " doesn't belong to zone " + zone.getId()); } - + String requestedIp = null; if (requestedIps != null && !requestedIps.isEmpty()) { - requestedIp = requestedIps.get(network.getId()); + requestedIp = requestedIps.get(network.getId()); } NicProfile profile = new NicProfile(requestedIp); - + if (defaultNetworkNumber == 0) { - defaultNetworkNumber++; - // if user requested specific ip for default network, add it - if (defaultNetworkIp != null) { - profile = new NicProfile(defaultNetworkIp); - } - - profile.setDefaultNic(true); + defaultNetworkNumber++; + // if user requested specific ip for default network, add it + if (defaultNetworkIp != null) { + profile = new NicProfile(defaultNetworkIp); + } + + profile.setDefaultNic(true); } networks.add(new Pair(network, profile)); @@ -2371,22 +2386,22 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } if (securityGroupIdList != null && !securityGroupIdList.isEmpty() && !securityGroupEnabled) { - throw new InvalidParameterValueException("Unable to deploy vm with security groups as SecurityGroup service is not enabled for the vm's network"); + throw new InvalidParameterValueException("Unable to deploy vm with security groups as SecurityGroup service is not enabled for the vm's network", null); } // Verify network information - network default network has to be set; and vm can't have more than one default network // This is a part of business logic because default network is required by Agent Manager in order to configure default // gateway for the vm if (defaultNetworkNumber == 0) { - throw new InvalidParameterValueException("At least 1 default network has to be specified for the vm"); + throw new InvalidParameterValueException("At least 1 default network has to be specified for the vm", null); } else if (defaultNetworkNumber > 1) { - throw new InvalidParameterValueException("Only 1 default network per vm is supported"); + throw new InvalidParameterValueException("Only 1 default network per vm is supported", null); } long id = _vmDao.getNextInSequence(Long.class, "id"); String instanceName = VirtualMachineName.getVmName(id, owner.getId(), _instance); - + String uuidName = UUID.randomUUID().toString(); if (hostName == null) { hostName = uuidName; @@ -2394,7 +2409,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // verify hostName (hostname doesn't have to be unique) if (!NetUtils.verifyDomainNameLabel(hostName, true)) { throw new InvalidParameterValueException("Invalid name. Vm name can contain ASCII letters 'a' through 'z', the digits '0' through '9', " - + "and the hyphen ('-'), must be between 1 and 63 characters long, and can't start or end with \"-\" and can't start with digit"); + + "and the hyphen ('-'), must be between 1 and 63 characters long, and can't start or end with \"-\" and can't start with digit", null); } } @@ -2409,7 +2424,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager UserVmVO vm = new UserVmVO(id, instanceName, displayName, template.getId(), hypervisorType, template.getGuestOSId(), offering.getOfferHA(), offering.getLimitCpuUse(), owner.getDomainId(), owner.getId(), offering.getId(), userData, hostName); vm.setUuid(uuidName); - + if (sshPublicKey != null) { vm.setDetail("SSH.PublicKey", sshPublicKey); } @@ -2461,14 +2476,14 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager byte[] decodedUserData = null; if (userData != null) { if (userData.length() >= 2 * MAX_USER_DATA_LENGTH_BYTES) { - throw new InvalidParameterValueException("User data is too long"); + throw new InvalidParameterValueException("User data is too long", null); } decodedUserData = org.apache.commons.codec.binary.Base64.decodeBase64(userData.getBytes()); if (decodedUserData.length > MAX_USER_DATA_LENGTH_BYTES) { - throw new InvalidParameterValueException("User data is too long"); + throw new InvalidParameterValueException("User data is too long", null); } if (decodedUserData.length < 1) { - throw new InvalidParameterValueException("User data is too short"); + throw new InvalidParameterValueException("User data is too short", null); } } } @@ -2485,7 +2500,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager long vmId = cmd.getEntityId(); Long hostId = cmd.getHostId(); UserVmVO vm = _vmDao.findById(vmId); - + Pair> vmParamPair = null; try { vmParamPair = startVirtualMachine(vmId, hostId, additonalParams); @@ -2493,7 +2508,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } finally { updateVmStateForFailedVmCreation(vm.getId()); } - + // Check that the password was passed in and is valid VMTemplateVO template = _templateDao.findByIdIncludingRemoved(vm.getTemplateId()); if (template.getEnablePassword()) { @@ -2521,14 +2536,14 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager Pair isoPathPair = _storageMgr.getAbsoluteIsoPath(template.getId(), vm.getDataCenterIdToDeployIn()); if (template.getTemplateType() == TemplateType.PERHOST) { - isoPath = template.getName(); + isoPath = template.getName(); } else { - if (isoPathPair == null) { - s_logger.warn("Couldn't get absolute iso path"); - return false; - } else { - isoPath = isoPathPair.first(); - } + if (isoPathPair == null) { + s_logger.warn("Couldn't get absolute iso path"); + return false; + } else { + isoPath = isoPathPair.first(); + } } if (template.isBootable()) { @@ -2556,7 +2571,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager @Override public boolean finalizeDeployment(Commands cmds, VirtualMachineProfile profile, DeployDestination dest, ReservationContext context) { - UserVmVO userVm = profile.getVirtualMachine(); + UserVmVO userVm = profile.getVirtualMachine(); List nics = _nicDao.listByVmId(userVm.getId()); for (NicVO nic : nics) { NetworkVO network = _networkDao.findById(nic.getNetworkId()); @@ -2636,7 +2651,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager s_logger.info("Detected that ip changed in the answer, updated nic in the db with new ip " + returnedIp); } } - + //get system ip and create static nat rule for the vm try { _rulesMgr.getSystemIpAndEnableStaticNatForVm(profile.getVirtualMachine(), false); @@ -2644,8 +2659,8 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager s_logger.warn("Failed to get system ip and enable static nat for the vm " + profile.getVirtualMachine() + " due to exception ", ex); return false; } - - return true; + + return true; } @Override @@ -2684,7 +2699,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager UserVmVO vm = _vmDao.findById(vmId); if (vm == null) { - throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); + throw new InvalidParameterValueException("unable to find a virtual machine by id", null); } _accountMgr.checkAccess(caller, null, true, vm); @@ -2703,16 +2718,16 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager @Override public void finalizeStop(VirtualMachineProfile profile, StopAnswer answer) { - //release elastic IP here - IPAddressVO ip = _ipAddressDao.findByAssociatedVmId(profile.getId()); - if (ip != null && ip.getSystem()) { - UserContext ctx = UserContext.current(); - try { - _rulesMgr.disableStaticNat(ip.getId(), ctx.getCaller(), ctx.getCallerUserId(), true); - } catch (Exception ex) { - s_logger.warn("Failed to disable static nat and release system ip " + ip + " as a part of vm " + profile.getVirtualMachine() + " stop due to exception ", ex); - } - } + //release elastic IP here + IPAddressVO ip = _ipAddressDao.findByAssociatedVmId(profile.getId()); + if (ip != null && ip.getSystem()) { + UserContext ctx = UserContext.current(); + try { + _rulesMgr.disableStaticNat(ip.getId(), ctx.getCaller(), ctx.getCallerUserId(), true); + } catch (Exception ex) { + s_logger.warn("Failed to disable static nat and release system ip " + ip + " as a part of vm " + profile.getVirtualMachine() + " stop due to exception ", ex); + } + } } public String generateRandomPassword() { @@ -2729,14 +2744,14 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (callerAccount != null && callerAccount.getRemoved() != null) { throw new InvalidParameterValueException("The account " + callerAccount.getId() + " is removed"); } - + UserVmVO vm = _vmDao.findById(vmId); if (vm == null) { - throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); + throw new InvalidParameterValueException("unable to find a virtual machine by id ", null); } _accountMgr.checkAccess(callerAccount, null, true, vm); - + Account owner = _accountDao.findById(vm.getAccountId()); if (owner == null) { @@ -2746,7 +2761,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (owner.getState() == Account.State.disabled) { throw new PermissionDeniedException("The owner of " + vm + " is disabled: " + vm.getAccountId()); } - + Host destinationHost = null; if(hostId != null){ Account account = UserContext.current().getCaller(); @@ -2773,13 +2788,13 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager _securityGroupMgr.addInstanceToGroups(vmId, groupList); } } - + DataCenterDeployment plan = null; if (destinationHost != null) { s_logger.debug("Destination Host to deploy the VM is specified, specifying a deployment plan to deploy the VM"); plan = new DataCenterDeployment(vm.getDataCenterIdToDeployIn(), destinationHost.getPodId(), destinationHost.getClusterId(), destinationHost.getId(), null, null); } - + //Set parameters Map params = null; VMTemplateVO template = null; @@ -2794,7 +2809,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } if (!validPassword(password)) { - throw new InvalidParameterValueException("A valid password for this virtual machine was not provided."); + throw new InvalidParameterValueException("A valid password for this virtual machine was not provided.", null); } // Check if an SSH key pair was selected for the instance and if so use it to encrypt & save the vm password @@ -2808,7 +2823,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager vm.setDetail("Encrypted.Password", encryptedPasswd); _vmDao.saveDetails(vm); } - + params = new HashMap(); if (additionalParams != null) { params.putAll(additionalParams); @@ -2817,17 +2832,17 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } vm = _itMgr.start(vm, params, callerUser, callerAccount, plan); - + Pair> vmParamPair = new Pair(vm, params); if (vm != null && vm.isUpdateParameters()) { - // this value is not being sent to the backend; need only for api display purposes + // this value is not being sent to the backend; need only for api display purposes if (template.getEnablePassword()) { vm.setPassword((String)vmParamPair.second().get(VirtualMachineProfile.Param.VmPassword)); vm.setUpdateParameters(false); _vmDao.update(vm.getId(), vm); } } - + return vmParamPair; } @@ -2839,8 +2854,8 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // Verify input parameters UserVmVO vm = _vmDao.findById(vmId); if (vm == null || vm.getRemoved() != null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a virtual machine with specified vmId"); - ex.addProxyObject(vm, vmId, "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a virtual machine with specified vmId", null); + ex.addProxyObject(vm, vmId, "vmId"); throw ex; } @@ -2858,8 +2873,8 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager try { status = _itMgr.destroy(vm, userCaller, caller); } catch (OperationTimedoutException e) { - CloudRuntimeException ex = new CloudRuntimeException("Unable to destroy with specified vmId", e); - ex.addProxyObject(vm, vmId, "vmId"); + CloudRuntimeException ex = new CloudRuntimeException("Unable to destroy with specified vmId", e); + ex.addProxyObject(vm, vmId, "vmId"); throw ex; } @@ -2879,22 +2894,22 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager return _vmDao.findById(vmId); } else { - CloudRuntimeException ex = new CloudRuntimeException("Failed to destroy vm with specified vmId"); - ex.addProxyObject(vm, vmId, "vmId"); + CloudRuntimeException ex = new CloudRuntimeException("Failed to destroy vm with specified vmId"); + ex.addProxyObject(vm, vmId, "vmId"); throw ex; } } @Override public List searchForUserVMs(ListVMsCmd cmd) { - Account caller = UserContext.current().getCaller(); - List permittedAccounts = new ArrayList(); - String hypervisor = cmd.getHypervisor(); - boolean listAll = cmd.listAll(); - Long id = cmd.getId(); - Map tags = cmd.getTags(); + Account caller = UserContext.current().getCaller(); + List permittedAccounts = new ArrayList(); + String hypervisor = cmd.getHypervisor(); + boolean listAll = cmd.listAll(); + Long id = cmd.getId(); + Map tags = cmd.getTags(); - Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); + Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, listAll, false); Long domainId = domainIdRecursiveListProject.first(); Boolean isRecursive = domainIdRecursiveListProject.second(); @@ -2917,7 +2932,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (HypervisorType.getType(hypervisor) != HypervisorType.None) { c.addCriteria(Criteria.HYPERVISOR, hypervisor); } else if (hypervisor != null) { - throw new InvalidParameterValueException("Invalid HypervisorType " + hypervisor); + throw new InvalidParameterValueException("Invalid HypervisorType " + hypervisor, null); } // ignore these search requests if it's not an admin @@ -2942,7 +2957,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager SearchBuilder sb = _vmDao.createSearchBuilder(); _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - + Object id = c.getCriteria(Criteria.ID); Object name = c.getCriteria(Criteria.NAME); Object state = c.getCriteria(Criteria.STATE); @@ -2980,7 +2995,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager groupSearch.and("groupId", groupSearch.entity().getGroupId(), SearchCriteria.Op.EQ); sb.join("groupSearch", groupSearch, sb.entity().getId(), groupSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER); } - + if (tags != null && !tags.isEmpty()) { SearchBuilder tagSearch = _resourceTagDao.createSearchBuilder(); for (int count=0; count < tags.size(); count++) { @@ -3013,7 +3028,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // populate the search criteria with the values passed in SearchCriteria sc = sb.create(); _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - + if (tags != null && !tags.isEmpty()) { int count = 0; sc.setJoinParameters("tagSearch", "resourceType", TaggedResourceType.UserVm.toString()); @@ -3023,7 +3038,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager count++; } } - + if (groupId != null && (Long) groupId == -1) { sc.setJoinParameters("vmSearch", "instanceId", (Object) null); } else if (groupId != null) { @@ -3113,8 +3128,8 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager public HypervisorType getHypervisorTypeOfUserVM(long vmId) { UserVmVO userVm = _vmDao.findById(vmId); if (userVm == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a virtual machine with specified id"); - ex.addProxyObject(userVm, vmId, "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a virtual machine with specified id"); + ex.addProxyObject(userVm, vmId, "vmId"); throw ex; } @@ -3146,22 +3161,22 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager VMInstanceVO vm = _vmInstanceDao.findById(vmId); if (vm == null) { - throw new InvalidParameterValueException("Unable to find the VM by id=" + vmId); + throw new InvalidParameterValueException("Unable to find the VM by id", null); } if (vm.getState() != State.Stopped) { - InvalidParameterValueException ex = new InvalidParameterValueException("VM is not Stopped, unable to migrate the vm having the specified id"); - ex.addProxyObject(vm, vmId, "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("VM is not Stopped, unable to migrate the vm having the specified id"); + ex.addProxyObject(vm, vmId, "vmId"); throw ex; } if (vm.getType() != VirtualMachine.Type.User) { throw new InvalidParameterValueException("can only do storage migration on user vm"); } - + List vols = _volsDao.findByInstance(vm.getId()); if (vols.size() > 1) { - throw new InvalidParameterValueException("Data disks attached to the vm, can not migrate. Need to dettach data disks at first"); + throw new InvalidParameterValueException("Data disks attached to the vm, can not migrate. Need to dettach data disks at first"); } HypervisorType destHypervisorType = _clusterDao.findById(destPool.getClusterId()).getHypervisorType(); @@ -3212,13 +3227,13 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } throw new InvalidParameterValueException("Unsupported operation, VM uses Local storage, cannot migrate"); } - + //check if migrating to same host long srcHostId = vm.getHostId(); if(destinationHost.getId() == srcHostId){ throw new InvalidParameterValueException("Cannot migrate VM, VM is already presnt on this host, please specify valid destination host to migrate the VM"); } - + //check if host is UP if(destinationHost.getStatus() != com.cloud.host.Status.Up || destinationHost.getResourceState() != ResourceState.Enabled){ throw new InvalidParameterValueException("Cannot migrate VM, destination host is not in correct state, has status: "+destinationHost.getStatus() + ", state: " +destinationHost.getResourceState()); @@ -3255,7 +3270,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager //VV 1: verify the two users Account caller = UserContext.current().getCaller(); if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN && caller.getType() != Account.ACCOUNT_TYPE_DOMAIN_ADMIN){ // only root admin can assign VMs - throw new InvalidParameterValueException("Only domain admins are allowed to assign VMs and not " + caller.getType()); + throw new InvalidParameterValueException("Only domain admins are allowed to assign VMs and not " + caller.getType()); } //get and check the valid VM @@ -3277,54 +3292,54 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } //don't allow to move the vm from the project if (oldAccount.getType() == Account.ACCOUNT_TYPE_PROJECT) { - InvalidParameterValueException ex = new InvalidParameterValueException("Specified Vm id belongs to the project and can't be moved"); - ex.addProxyObject(vm, cmd.getVmId(), "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Specified Vm id belongs to the project and can't be moved"); + ex.addProxyObject(vm, cmd.getVmId(), "vmId"); throw ex; } Account newAccount = _accountService.getActiveAccountByName(cmd.getAccountName(), cmd.getDomainId()); if (newAccount == null || newAccount.getType() == Account.ACCOUNT_TYPE_PROJECT) { throw new InvalidParameterValueException("Invalid accountid=" + cmd.getAccountName() + " in domain " + cmd.getDomainId()); } - + if (newAccount.getState() == Account.State.disabled) { throw new InvalidParameterValueException("The new account owner " + cmd.getAccountName() + " is disabled."); } - + // make sure the accounts are under same domain if (oldAccount.getDomainId() != newAccount.getDomainId()){ - throw new InvalidParameterValueException("The account should be under same domain for moving VM between two accounts. Old owner domain =" + oldAccount.getDomainId() + - " New owner domain=" + newAccount.getDomainId()); - } - - // make sure the accounts are not same - if (oldAccount.getAccountId() == newAccount.getAccountId()){ - throw new InvalidParameterValueException("The account should be same domain for moving VM between two accounts. Account id =" + oldAccount.getAccountId()); + throw new InvalidParameterValueException("The account should be under same domain for moving VM between two accounts. Old owner domain =" + oldAccount.getDomainId() + + " New owner domain=" + newAccount.getDomainId()); } - + // make sure the accounts are not same + if (oldAccount.getAccountId() == newAccount.getAccountId()){ + throw new InvalidParameterValueException("The account should be same domain for moving VM between two accounts. Account id =" + oldAccount.getAccountId()); + } + + // don't allow to move the vm if there are existing PF/LB/Static Nat rules, or vm is assigned to static Nat ip List pfrules = _portForwardingDao.listByVm(cmd.getVmId()); if (pfrules != null && pfrules.size() > 0){ - throw new InvalidParameterValueException("Remove the Port forwarding rules for this VM before assigning to another user."); + throw new InvalidParameterValueException("Remove the Port forwarding rules for this VM before assigning to another user."); } List snrules = _rulesDao.listStaticNatByVmId(vm.getId()); if (snrules != null && snrules.size() > 0){ - throw new InvalidParameterValueException("Remove the StaticNat rules for this VM before assigning to another user."); + throw new InvalidParameterValueException("Remove the StaticNat rules for this VM before assigning to another user."); } List maps = _loadBalancerVMMapDao.listByInstanceId(vm.getId()); if (maps != null && maps.size() > 0) { - throw new InvalidParameterValueException("Remove the load balancing rules for this VM before assigning to another user."); + throw new InvalidParameterValueException("Remove the load balancing rules for this VM before assigning to another user."); } // check for one on one nat IPAddressVO ip = _ipAddressDao.findByAssociatedVmId(cmd.getVmId()); if (ip != null){ - if (ip.isOneToOneNat()){ - throw new InvalidParameterValueException("Remove the one to one nat rule for this VM for ip " + ip.toString()); - } + if (ip.isOneToOneNat()){ + throw new InvalidParameterValueException("Remove the one to one nat rule for this VM for ip " + ip.toString()); + } } - + DataCenterVO zone = _dcDao.findById(vm.getDataCenterIdToDeployIn()); - + //Remove vm from instance group removeInstanceFromInstanceGroup(cmd.getVmId()); @@ -3354,7 +3369,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager vm.setAccountId(newAccount.getAccountId()); vm.setDomainId(cmd.getDomainId()); _vmDao.persist(vm); - + // OS 2: update volume List volumes = _volsDao.findByInstance(cmd.getVmId()); for (VolumeVO volume : volumes) { @@ -3364,7 +3379,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager _volsDao.persist(volume); _resourceLimitMgr.incrementResourceCount(newAccount.getAccountId(), ResourceType.volume); _usageEventDao.persist(new UsageEventVO(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), - volume.getDiskOfferingId(), volume.getTemplateId(), volume.getSize())); + volume.getDiskOfferingId(), volume.getTemplateId(), volume.getSize())); } _resourceLimitMgr.incrementResourceCount(newAccount.getAccountId(), ResourceType.user_vm); @@ -3380,17 +3395,17 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // OS 3: update the network List networkIdList = cmd.getNetworkIds(); List securityGroupIdList = cmd.getSecurityGroupIdList(); - + if (zone.getNetworkType() == NetworkType.Basic) { - if (networkIdList != null && !networkIdList.isEmpty()) { - throw new InvalidParameterValueException("Can't move vm with network Ids; this is a basic zone VM"); - } - //cleanup the old security groups - _securityGroupMgr.removeInstanceFromGroups(cmd.getVmId()); - //cleanup the network for the oldOwner + if (networkIdList != null && !networkIdList.isEmpty()) { + throw new InvalidParameterValueException("Can't move vm with network Ids; this is a basic zone VM"); + } + //cleanup the old security groups + _securityGroupMgr.removeInstanceFromGroups(cmd.getVmId()); + //cleanup the network for the oldOwner _networkMgr.cleanupNics(vmOldProfile); _networkMgr.expungeNics(vmOldProfile); - //security groups will be recreated for the new account, when the VM is started + //security groups will be recreated for the new account, when the VM is started List networkList = new ArrayList(); // Get default guest network in Basic zone @@ -3434,63 +3449,63 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager securityGroupIdList.add(defaultGroup.getId()); } } - + List> networks = new ArrayList>(); NicProfile profile = new NicProfile(); profile.setDefaultNic(true); networks.add(new Pair(networkList.get(0), profile)); - + VMInstanceVO vmi = _itMgr.findByIdAndType(vm.getType(), vm.getId()); VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmi); _networkMgr.allocate(vmProfile, networks); _securityGroupMgr.addInstanceToGroups(vm.getId(), securityGroupIdList); - + s_logger.debug("AssignVM: Basic zone, adding security groups no " + securityGroupIdList.size() + " to " + vm.getInstanceName() ); } else { if (zone.isSecurityGroupEnabled()) { - throw new InvalidParameterValueException("Not yet implemented for SecurityGroupEnabled advanced networks."); + throw new InvalidParameterValueException("Not yet implemented for SecurityGroupEnabled advanced networks."); } else { if (securityGroupIdList != null && !securityGroupIdList.isEmpty()) { throw new InvalidParameterValueException("Can't move vm with security groups; security group feature is not enabled in this zone"); } - //cleanup the network for the oldOwner + //cleanup the network for the oldOwner _networkMgr.cleanupNics(vmOldProfile); _networkMgr.expungeNics(vmOldProfile); - + Set applicableNetworks = new HashSet(); - + if (networkIdList != null && !networkIdList.isEmpty()){ - // add any additional networks - for (Long networkId : networkIdList) { - NetworkVO network = _networkDao.findById(networkId); - if (network == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find specified network id"); - ex.addProxyObject(network, networkId, "networkId"); - throw ex; - } - - _networkMgr.checkNetworkPermissions(newAccount, network); - - //don't allow to use system networks - NetworkOffering networkOffering = _configMgr.getNetworkOffering(network.getNetworkOfferingId()); - if (networkOffering.isSystemOnly()) { - InvalidParameterValueException ex = new InvalidParameterValueException("Specified Network id is system only and can't be used for vm deployment"); - ex.addProxyObject(network, networkId, "networkId"); - throw ex; - } - applicableNetworks.add(network); - } + // add any additional networks + for (Long networkId : networkIdList) { + NetworkVO network = _networkDao.findById(networkId); + if (network == null) { + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find specified network id"); + ex.addProxyObject(network, networkId, "networkId"); + throw ex; + } + + _networkMgr.checkNetworkPermissions(newAccount, network); + + //don't allow to use system networks + NetworkOffering networkOffering = _configMgr.getNetworkOffering(network.getNetworkOfferingId()); + if (networkOffering.isSystemOnly()) { + InvalidParameterValueException ex = new InvalidParameterValueException("Specified Network id is system only and can't be used for vm deployment"); + ex.addProxyObject(network, networkId, "networkId"); + throw ex; + } + applicableNetworks.add(network); + } } else { - NetworkVO defaultNetwork = null; + NetworkVO defaultNetwork = null; List requiredOfferings = _networkOfferingDao.listByAvailability(Availability.Required, false); if (requiredOfferings.size() < 1) { - throw new InvalidParameterValueException("Unable to find network offering with availability=" - + Availability.Required + " to automatically create the network as a part of vm creation"); + throw new InvalidParameterValueException("Unable to find network offering with availability=" + + Availability.Required + " to automatically create the network as a part of vm creation"); } - + PhysicalNetwork physicalNetwork = _networkMgr.translateZoneIdToPhysicalNetwork(zone.getId()); if (requiredOfferings.get(0).getState() == NetworkOffering.State.Enabled) { // get Virtual networks @@ -3498,20 +3513,20 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (virtualNetworks.isEmpty()) { s_logger.debug("Creating network for account " + newAccount + " from the network offering id=" + - requiredOfferings.get(0).getId() + " as a part of deployVM process"); + requiredOfferings.get(0).getId() + " as a part of deployVM process"); Network newNetwork = _networkMgr.createGuestNetwork(requiredOfferings.get(0).getId(), newAccount.getAccountName() + "-network", newAccount.getAccountName() + "-network", null, null, null, null, newAccount, null, physicalNetwork, zone.getId(), ACLType.Account, null, null); defaultNetwork = _networkDao.findById(newNetwork.getId()); } else if (virtualNetworks.size() > 1) { throw new InvalidParameterValueException("More than 1 default Isolated networks are found " + - "for account " + newAccount + "; please specify networkIds"); + "for account " + newAccount + "; please specify networkIds"); } else { defaultNetwork = virtualNetworks.get(0); } } else { - throw new InvalidParameterValueException("Required network offering id=" + - requiredOfferings.get(0).getId() + " is not in " + NetworkOffering.State.Enabled); + throw new InvalidParameterValueException("Required network offering id=" + + requiredOfferings.get(0).getId() + " is not in " + NetworkOffering.State.Enabled); } applicableNetworks.add(defaultNetwork); @@ -3550,11 +3565,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager long vmId = cmd.getVmId(); UserVmVO vm = _vmDao.findById(vmId); if (vm == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Cann not find VM with ID " + vmId); - ex.addProxyObject(vm, vmId, "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Cann not find VM with ID " + vmId); + ex.addProxyObject(vm, vmId, "vmId"); throw ex; } - + Account owner = _accountDao.findById(vm.getAccountId()); if (owner == null) { throw new InvalidParameterValueException("The owner of " + vm + " does not exist: " + vm.getAccountId()); @@ -3574,8 +3589,8 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager List rootVols = _volsDao.findByInstance(vmId); if (rootVols.isEmpty()) { - InvalidParameterValueException ex = new InvalidParameterValueException("Can not find root volume for VM " + vmId); - ex.addProxyObject(vm, vmId, "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Can not find root volume for VM " + vmId); + ex.addProxyObject(vm, vmId, "vmId"); throw ex; } @@ -3583,9 +3598,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager long templateId = root.getTemplateId(); VMTemplateVO template = _templateDao.findById(templateId); if (template == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Cannot find template for specified volumeid and vmId"); - ex.addProxyObject(vm, vmId, "vmId"); - ex.addProxyObject(root, root.getId(), "volumeId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Cannot find template for specified volumeid and vmId"); + ex.addProxyObject(vm, vmId, "vmId"); + ex.addProxyObject(root, root.getId(), "volumeId"); throw ex; } @@ -3626,7 +3641,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager s_logger.debug("Restore VM " + vmId + " with template " + root.getTemplateId() + " successfully"); return vm; } - + @Override public boolean plugNic(Network network, NicTO nic, VirtualMachineTO vm, ReservationContext context, DeployDestination dest) throws ConcurrentOperationException, ResourceUnavailableException, @@ -3643,8 +3658,8 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager throw new UnsupportedOperationException("Unplug nic is not supported for vm of type " + vm.getType()); } - @Override - public void prepareStop(VirtualMachineProfile profile) { - } - + @Override + public void prepareStop(VirtualMachineProfile profile) { + } + } diff --git a/utils/src/com/cloud/utils/IdentityProxy.java b/utils/src/com/cloud/utils/IdentityProxy.java index 5c75cb9880a..567752e86ab 100644 --- a/utils/src/com/cloud/utils/IdentityProxy.java +++ b/utils/src/com/cloud/utils/IdentityProxy.java @@ -10,7 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.utils; +package com.cloud.utils; + public class IdentityProxy { private String _tableName; @@ -25,11 +26,24 @@ public class IdentityProxy { } public IdentityProxy(String tableName, Long id, String fieldName) { - _tableName = tableName; - _value = id; - _idFieldName = fieldName; + setTableName(tableName); + setValue(id); + setIdFieldName(fieldName); + } + + public IdentityProxy(Object vo, Long id, String fieldName) { + if (vo instanceof String) { + setTableName((String)vo); + } else { + String tablename = AnnotationHelper.getTableName(vo); + if (tablename != null) { + setTableName(tablename); + } + } + setValue(id); + setIdFieldName(fieldName); } - + public String getTableName() { return _tableName; } @@ -45,12 +59,12 @@ public class IdentityProxy { public void setValue(Long value) { _value = value; } - - public void setidFieldName(String value) { - _idFieldName = value; + + public void setIdFieldName(String value) { + _idFieldName = value; } - + public String getidFieldName() { - return _idFieldName; + return _idFieldName; } } From 7c647223f2c05d555c061c6697e4b2d8f7ff2824 Mon Sep 17 00:00:00 2001 From: Alena Prokharchyk Date: Thu, 5 Jul 2012 17:25:51 -0700 Subject: [PATCH 22/26] VPC: don't fail when create/remove static route when VPC VR is in Stopped state --- ...VpcVirtualNetworkApplianceManagerImpl.java | 21 ++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java index 4805df8f1d5..d7fcf9fb708 100644 --- a/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java @@ -43,6 +43,7 @@ import com.cloud.agent.api.to.NetworkACLTO; import com.cloud.agent.api.to.NicTO; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.agent.manager.Commands; +import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenterVO; import com.cloud.deploy.DataCenterDeployment; import com.cloud.deploy.DeployDestination; @@ -100,6 +101,7 @@ import com.cloud.vm.Nic; import com.cloud.vm.NicProfile; import com.cloud.vm.ReservationContext; import com.cloud.vm.VirtualMachine; +import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.VirtualMachineProfile; import com.cloud.vm.VirtualMachineProfile.Param; import com.cloud.vm.dao.VMInstanceDao; @@ -1025,9 +1027,22 @@ public class VpcVirtualNetworkApplianceManagerImpl extends VirtualNetworkApplian return true; } - //send commands to only one router as there is only one in the VPC - return sendStaticRoutes(staticRoutes, routers.get(0)); - + boolean result = true; + for (VirtualRouter router : routers) { + if (router.getState() == State.Running) { + result = result && sendStaticRoutes(staticRoutes, routers.get(0)); + + } else if (router.getState() == State.Stopped || router.getState() == State.Stopping) { + s_logger.debug("Router " + router.getInstanceName() + " is in " + router.getState() + + ", so not sending StaticRoute command to the backend"); + } else { + s_logger.warn("Unable to apply StaticRoute, virtual router is not in the right state " + router.getState()); + + throw new ResourceUnavailableException("Unable to apply StaticRoute on the backend," + + " virtual router is not in the right state", DataCenter.class, router.getDataCenterIdToDeployIn()); + } + } + return result; } protected boolean sendStaticRoutes(List staticRoutes, DomainRouterVO router) From f9d512f163354ab975f3c162c9d0da7fbf539cc4 Mon Sep 17 00:00:00 2001 From: Alena Prokharchyk Date: Thu, 5 Jul 2012 17:33:20 -0700 Subject: [PATCH 23/26] ResourceTags: resourcetags support for Project/Vpc/NetworkACL/StaticRoute --- .../api/commands/ListNetworkACLsCmd.java | 5 +- .../cloud/api/commands/ListProjectsCmd.java | 31 ++++++++++- .../api/commands/ListStaticRoutesCmd.java | 4 +- .../com/cloud/api/commands/ListVPCsCmd.java | 6 +-- .../api/response/NetworkACLResponse.java | 10 ++++ .../cloud/api/response/ProjectResponse.java | 11 +++- .../api/response/StaticRouteResponse.java | 10 ++++ .../com/cloud/api/response/VpcResponse.java | 7 +++ api/src/com/cloud/network/vpc/VpcService.java | 3 +- .../com/cloud/projects/ProjectService.java | 4 +- api/src/com/cloud/server/ResourceTag.java | 6 ++- .../src/com/cloud/api/ApiResponseHelper.java | 38 +++++++++++++ .../network/dao/FirewallRulesDaoImpl.java | 2 + .../network/vpc/Dao/StaticRouteDaoImpl.java | 19 +++++++ .../com/cloud/network/vpc/Dao/VpcDaoImpl.java | 19 +++++++ .../network/vpc/NetworkACLManagerImpl.java | 31 ++++++++++- .../com/cloud/network/vpc/VpcManagerImpl.java | 54 ++++++++++++++++++- .../cloud/projects/ProjectManagerImpl.java | 33 ++++++++++-- .../cloud/projects/dao/ProjectDaoImpl.java | 11 ++-- .../com/cloud/storage/StorageManagerImpl.java | 1 + .../cloud/tags/TaggedResourceManagerImpl.java | 19 ++++++- .../cloud/uuididentity/dao/IdentityDao.java | 4 +- .../uuididentity/dao/IdentityDaoImpl.java | 9 +++- 23 files changed, 310 insertions(+), 27 deletions(-) diff --git a/api/src/com/cloud/api/commands/ListNetworkACLsCmd.java b/api/src/com/cloud/api/commands/ListNetworkACLsCmd.java index e7d37907dad..4d429240506 100644 --- a/api/src/com/cloud/api/commands/ListNetworkACLsCmd.java +++ b/api/src/com/cloud/api/commands/ListNetworkACLsCmd.java @@ -22,7 +22,8 @@ import java.util.List; import org.apache.log4j.Logger; import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListProjectAndAccountResourcesCmd; +import com.cloud.api.BaseCmd.CommandType; +import com.cloud.api.BaseListTaggedResourcesCmd; import com.cloud.api.IdentityMapper; import com.cloud.api.Implementation; import com.cloud.api.Parameter; @@ -31,7 +32,7 @@ import com.cloud.api.response.NetworkACLResponse; import com.cloud.network.rules.FirewallRule; @Implementation(description="Lists all network ACLs", responseObject=NetworkACLResponse.class) -public class ListNetworkACLsCmd extends BaseListProjectAndAccountResourcesCmd { +public class ListNetworkACLsCmd extends BaseListTaggedResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListNetworkACLsCmd.class.getName()); private static final String s_name = "listnetworkaclsresponse"; diff --git a/api/src/com/cloud/api/commands/ListProjectsCmd.java b/api/src/com/cloud/api/commands/ListProjectsCmd.java index 6a40461b5a7..0b0162c9681 100644 --- a/api/src/com/cloud/api/commands/ListProjectsCmd.java +++ b/api/src/com/cloud/api/commands/ListProjectsCmd.java @@ -13,7 +13,11 @@ package com.cloud.api.commands; import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; import java.util.List; +import java.util.Map; import org.apache.log4j.Logger; @@ -24,6 +28,7 @@ import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.response.ListResponse; import com.cloud.api.response.ProjectResponse; +import com.cloud.exception.InvalidParameterValueException; import com.cloud.projects.Project; @Implementation(description="Lists projects and provides detailed information for listed projects", responseObject=ProjectResponse.class, since="3.0.0") @@ -48,6 +53,9 @@ public class ListProjectsCmd extends BaseListAccountResourcesCmd { @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="list projects by state") private String state; + @Parameter(name = ApiConstants.TAGS, type = CommandType.MAP, description = "List projects by tags (key/value pairs)") + private Map tags; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -68,6 +76,25 @@ public class ListProjectsCmd extends BaseListAccountResourcesCmd { public String getCommandName() { return s_name; } + + public Map getTags() { + Map tagsMap = null; + if (tags != null && !tags.isEmpty()) { + tagsMap = new HashMap(); + Collection servicesCollection = tags.values(); + Iterator iter = servicesCollection.iterator(); + while (iter.hasNext()) { + HashMap services = (HashMap) iter.next(); + String key = services.get("key"); + String value = services.get("value"); + if (value == null) { + throw new InvalidParameterValueException("No value is passed in for key " + key); + } + tagsMap.put(key, value); + } + } + return tagsMap; + } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -75,7 +102,9 @@ public class ListProjectsCmd extends BaseListAccountResourcesCmd { @Override public void execute(){ - List projects = _projectService.listProjects(id, name, displayText, state, this.getAccountName(), this.getDomainId(), this.getKeyword(), this.getStartIndex(), this.getPageSizeVal(), this.listAll(), this.isRecursive()); + List projects = _projectService.listProjects(id, name, displayText, state, + this.getAccountName(), this.getDomainId(), this.getKeyword(), this.getStartIndex(), this.getPageSizeVal(), + this.listAll(), this.isRecursive(), getTags()); ListResponse response = new ListResponse(); List projectResponses = new ArrayList(); for (Project project : projects) { diff --git a/api/src/com/cloud/api/commands/ListStaticRoutesCmd.java b/api/src/com/cloud/api/commands/ListStaticRoutesCmd.java index f3e0021bc94..3039bca13b9 100644 --- a/api/src/com/cloud/api/commands/ListStaticRoutesCmd.java +++ b/api/src/com/cloud/api/commands/ListStaticRoutesCmd.java @@ -16,7 +16,7 @@ import java.util.ArrayList; import java.util.List; import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListProjectAndAccountResourcesCmd; +import com.cloud.api.BaseListTaggedResourcesCmd; import com.cloud.api.IdentityMapper; import com.cloud.api.Implementation; import com.cloud.api.Parameter; @@ -29,7 +29,7 @@ import com.cloud.network.vpc.StaticRoute; */ @Implementation(description="Lists all static routes", responseObject=StaticRouteResponse.class) -public class ListStaticRoutesCmd extends BaseListProjectAndAccountResourcesCmd { +public class ListStaticRoutesCmd extends BaseListTaggedResourcesCmd { private static final String s_name = "liststaticroutesresponse"; ///////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/ListVPCsCmd.java b/api/src/com/cloud/api/commands/ListVPCsCmd.java index 26064e79084..e60c6e290f6 100644 --- a/api/src/com/cloud/api/commands/ListVPCsCmd.java +++ b/api/src/com/cloud/api/commands/ListVPCsCmd.java @@ -18,7 +18,7 @@ import java.util.List; import org.apache.log4j.Logger; import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListAccountResourcesCmd; +import com.cloud.api.BaseListTaggedResourcesCmd; import com.cloud.api.IdentityMapper; import com.cloud.api.Implementation; import com.cloud.api.Parameter; @@ -31,7 +31,7 @@ import com.cloud.network.vpc.Vpc; */ @Implementation(description="Lists VPCs", responseObject=VpcResponse.class) -public class ListVPCsCmd extends BaseListAccountResourcesCmd{ +public class ListVPCsCmd extends BaseListTaggedResourcesCmd{ public static final Logger s_logger = Logger.getLogger(ListVPCsCmd.class.getName()); private static final String s_name = "listvpcsresponse"; @@ -137,7 +137,7 @@ public class ListVPCsCmd extends BaseListAccountResourcesCmd{ List vpcs = _vpcService.listVpcs(getId(), getVpcName(), getDisplayText(), getSupportedServices(), getCidr(), getVpcOffId(), getState(), getAccountName(), getDomainId(), this.getKeyword(), this.getStartIndex(), this.getPageSizeVal(), getZoneId(), this.isRecursive(), - this.listAll(), getRestartRequired()); + this.listAll(), getRestartRequired(), getTags()); ListResponse response = new ListResponse(); List offeringResponses = new ArrayList(); for (Vpc vpc : vpcs) { diff --git a/api/src/com/cloud/api/response/NetworkACLResponse.java b/api/src/com/cloud/api/response/NetworkACLResponse.java index 1338d89f57a..f54b05fc9af 100644 --- a/api/src/com/cloud/api/response/NetworkACLResponse.java +++ b/api/src/com/cloud/api/response/NetworkACLResponse.java @@ -12,6 +12,8 @@ // Automatically generated by addcopyright.py at 04/03/2012 package com.cloud.api.response; +import java.util.List; + import com.cloud.api.ApiConstants; import com.cloud.serializer.Param; import com.cloud.utils.IdentityProxy; @@ -45,6 +47,10 @@ public class NetworkACLResponse extends BaseResponse { @SerializedName(ApiConstants.ICMP_CODE) @Param(description = "error code for this icmp message") private Integer icmpCode; + + @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with the network ACLs", + responseObject = ResourceTagResponse.class) + private List tags; public void setId(Long id) { this.id.setValue(id); @@ -81,4 +87,8 @@ public class NetworkACLResponse extends BaseResponse { public void setTrafficType(String trafficType) { this.trafficType = trafficType; } + + public void setTags(List tags) { + this.tags = tags; + } } diff --git a/api/src/com/cloud/api/response/ProjectResponse.java b/api/src/com/cloud/api/response/ProjectResponse.java index 6bcadbb3457..d49abb3182a 100644 --- a/api/src/com/cloud/api/response/ProjectResponse.java +++ b/api/src/com/cloud/api/response/ProjectResponse.java @@ -12,9 +12,11 @@ // Automatically generated by addcopyright.py at 04/03/2012 package com.cloud.api.response; +import java.util.List; + import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; import com.cloud.serializer.Param; +import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; @SuppressWarnings("unused") @@ -40,6 +42,9 @@ public class ProjectResponse extends BaseResponse{ @SerializedName(ApiConstants.STATE) @Param(description="the state of the project") private String state; + + @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with vm", responseObject = ResourceTagResponse.class) + private List tags; public void setId(Long id) { @@ -69,4 +74,8 @@ public class ProjectResponse extends BaseResponse{ public void setState(String state) { this.state = state; } + + public void setTags(List tags) { + this.tags = tags; + } } diff --git a/api/src/com/cloud/api/response/StaticRouteResponse.java b/api/src/com/cloud/api/response/StaticRouteResponse.java index 025be6e0b82..6faef646547 100644 --- a/api/src/com/cloud/api/response/StaticRouteResponse.java +++ b/api/src/com/cloud/api/response/StaticRouteResponse.java @@ -12,6 +12,8 @@ // Automatically generated by addcopyright.py at 04/03/2012 package com.cloud.api.response; +import java.util.List; + import com.cloud.api.ApiConstants; import com.cloud.serializer.Param; import com.cloud.utils.IdentityProxy; @@ -54,6 +56,10 @@ public class StaticRouteResponse extends BaseResponse implements ControlledEntit @SerializedName(ApiConstants.DOMAIN) @Param(description = "the domain associated with the static route") private String domainName; + + @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with static route", + responseObject = ResourceTagResponse.class) + private List tags; public void setId(Long id) { this.id.setValue(id); @@ -99,4 +105,8 @@ public class StaticRouteResponse extends BaseResponse implements ControlledEntit public void setProjectName(String projectName) { this.projectName = projectName; } + + public void setTags(List tags) { + this.tags = tags; + } } diff --git a/api/src/com/cloud/api/response/VpcResponse.java b/api/src/com/cloud/api/response/VpcResponse.java index c2f119749bc..8d27ca4a7c9 100644 --- a/api/src/com/cloud/api/response/VpcResponse.java +++ b/api/src/com/cloud/api/response/VpcResponse.java @@ -79,6 +79,9 @@ public class VpcResponse extends BaseResponse implements ControlledEntityRespons @SerializedName(ApiConstants.NETWORK_DOMAIN) @Param(description="the network domain") private String networkDomain; + + @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with the project", responseObject = ResourceTagResponse.class) + private List tags; public void setId(Long id) { this.id.setValue(id); @@ -160,4 +163,8 @@ public class VpcResponse extends BaseResponse implements ControlledEntityRespons public void setZoneName(String zoneName) { this.zoneName = zoneName; } + + public void setTags(List tags) { + this.tags = tags; + } } diff --git a/api/src/com/cloud/network/vpc/VpcService.java b/api/src/com/cloud/network/vpc/VpcService.java index fec908083fc..bf35d1fcf69 100644 --- a/api/src/com/cloud/network/vpc/VpcService.java +++ b/api/src/com/cloud/network/vpc/VpcService.java @@ -107,13 +107,14 @@ public interface VpcService { * @param isRecursive TODO * @param listAll TODO * @param restartRequired TODO + * @param tags TODO * @param vpc * @return */ public List listVpcs(Long id, String vpcName, String displayText, List supportedServicesStr, String cidr, Long vpcOffId, String state, String accountName, Long domainId, String keyword, Long startIndex, Long pageSizeVal, Long zoneId, Boolean isRecursive, Boolean listAll, - Boolean restartRequired); + Boolean restartRequired, Map tags); /** * @param vpcId diff --git a/api/src/com/cloud/projects/ProjectService.java b/api/src/com/cloud/projects/ProjectService.java index 9e3b6c333fa..ef421e54170 100644 --- a/api/src/com/cloud/projects/ProjectService.java +++ b/api/src/com/cloud/projects/ProjectService.java @@ -13,6 +13,7 @@ package com.cloud.projects; import java.util.List; +import java.util.Map; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.ResourceAllocationException; @@ -55,7 +56,8 @@ public interface ProjectService { */ Project getProject(long id); - List listProjects(Long id, String name, String displayText, String state, String accountName, Long domainId, String keyword, Long startIndex, Long pageSize, boolean listAll, boolean isRecursive); + List listProjects(Long id, String name, String displayText, String state, String accountName, + Long domainId, String keyword, Long startIndex, Long pageSize, boolean listAll, boolean isRecursive, Map tags); ProjectAccount assignAccountToProject(Project project, long accountId, Role accountRole); diff --git a/api/src/com/cloud/server/ResourceTag.java b/api/src/com/cloud/server/ResourceTag.java index c3307b6b17b..02cab333f36 100644 --- a/api/src/com/cloud/server/ResourceTag.java +++ b/api/src/com/cloud/server/ResourceTag.java @@ -30,7 +30,11 @@ public interface ResourceTag extends ControlledEntity{ PortForwardingRule, FirewallRule, SecurityGroup, - PublicIpAddress + PublicIpAddress, + Project, + Vpc, + NetworkACL, + StaticRoute } /** diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index 26245e22076..ce3daa9ccd4 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -3044,6 +3044,15 @@ public class ApiResponseHelper implements ResponseGenerator { response.setDomain(domain.getName()); response.setOwner(ApiDBUtils.getProjectOwner(project.getId()).getAccountName()); + + //set tag information + List tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.Project, project.getId()); + List tagResponses = new ArrayList(); + for (ResourceTag tag : tags) { + ResourceTagResponse tagResponse = createResourceTagResponse(tag, true); + tagResponses.add(tagResponse); + } + response.setTags(tagResponses); response.setObjectName("project"); return response; @@ -3122,6 +3131,16 @@ public class ApiResponseHelper implements ResponseGenerator { response.setIcmpType(networkACL.getIcmpType()); response.setState(stateToSet); + + //set tag information + List tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.NetworkACL, networkACL.getId()); + List tagResponses = new ArrayList(); + for (ResourceTag tag : tags) { + ResourceTagResponse tagResponse = createResourceTagResponse(tag, true); + tagResponses.add(tagResponse); + } + response.setTags(tagResponses); + response.setObjectName("networkacl"); return response; } @@ -3702,6 +3721,16 @@ public class ApiResponseHelper implements ResponseGenerator { response.setNetworks(networkResponses); response.setServices(serviceResponses); + + //set tag information + List tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.Vpc, vpc.getId()); + List tagResponses = new ArrayList(); + for (ResourceTag tag : tags) { + ResourceTagResponse tagResponse = createResourceTagResponse(tag, true); + tagResponses.add(tagResponse); + } + response.setTags(tagResponses); + response.setObjectName("vpc"); return response; } @@ -3743,6 +3772,15 @@ public class ApiResponseHelper implements ResponseGenerator { response.setState(stateToSet); populateAccount(response, result.getAccountId()); populateDomain(response, result.getDomainId()); + + //set tag information + List tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.StaticRoute, result.getId()); + List tagResponses = new ArrayList(); + for (ResourceTag tag : tags) { + ResourceTagResponse tagResponse = createResourceTagResponse(tag, true); + tagResponses.add(tagResponse); + } + response.setTags(tagResponses); response.setObjectName("staticroute"); return response; diff --git a/server/src/com/cloud/network/dao/FirewallRulesDaoImpl.java b/server/src/com/cloud/network/dao/FirewallRulesDaoImpl.java index 6fc0350ec80..a1e3b081c73 100644 --- a/server/src/com/cloud/network/dao/FirewallRulesDaoImpl.java +++ b/server/src/com/cloud/network/dao/FirewallRulesDaoImpl.java @@ -298,6 +298,8 @@ public class FirewallRulesDaoImpl extends GenericDaoBase i _tagsDao.removeBy(id, TaggedResourceType.PortForwardingRule); } else if (entry.getPurpose() == Purpose.Firewall) { _tagsDao.removeBy(id, TaggedResourceType.FirewallRule); + } else if (entry.getPurpose() == Purpose.NetworkACL) { + _tagsDao.removeBy(id, TaggedResourceType.NetworkACL); } } boolean result = super.remove(id); diff --git a/server/src/com/cloud/network/vpc/Dao/StaticRouteDaoImpl.java b/server/src/com/cloud/network/vpc/Dao/StaticRouteDaoImpl.java index d4b195b00e8..9cdca8eeb33 100644 --- a/server/src/com/cloud/network/vpc/Dao/StaticRouteDaoImpl.java +++ b/server/src/com/cloud/network/vpc/Dao/StaticRouteDaoImpl.java @@ -18,6 +18,9 @@ import javax.ejb.Local; import com.cloud.network.vpc.StaticRoute; import com.cloud.network.vpc.StaticRouteVO; +import com.cloud.server.ResourceTag.TaggedResourceType; +import com.cloud.tags.dao.ResourceTagsDaoImpl; +import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.db.DB; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericSearchBuilder; @@ -25,6 +28,7 @@ import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.db.SearchCriteria.Op; +import com.cloud.utils.db.Transaction; /** * @author Alena Prokharchyk @@ -36,6 +40,7 @@ public class StaticRouteDaoImpl extends GenericDaoBase impl protected final SearchBuilder AllFieldsSearch; protected final SearchBuilder NotRevokedSearch; protected final GenericSearchBuilder RoutesByGatewayCount; + ResourceTagsDaoImpl _tagsDao = ComponentLocator.inject(ResourceTagsDaoImpl.class); protected StaticRouteDaoImpl() { super(); @@ -92,4 +97,18 @@ public class StaticRouteDaoImpl extends GenericDaoBase impl sc.setParameters("gatewayId", gatewayId); return customSearch(sc, null).get(0); } + + @Override + @DB + public boolean remove(Long id) { + Transaction txn = Transaction.currentTxn(); + txn.start(); + StaticRouteVO entry = findById(id); + if (entry != null) { + _tagsDao.removeBy(id, TaggedResourceType.StaticRoute); + } + boolean result = super.remove(id); + txn.commit(); + return result; + } } diff --git a/server/src/com/cloud/network/vpc/Dao/VpcDaoImpl.java b/server/src/com/cloud/network/vpc/Dao/VpcDaoImpl.java index e0ea5d920f3..11f5a2e7d0f 100644 --- a/server/src/com/cloud/network/vpc/Dao/VpcDaoImpl.java +++ b/server/src/com/cloud/network/vpc/Dao/VpcDaoImpl.java @@ -18,6 +18,9 @@ import javax.ejb.Local; import com.cloud.network.vpc.Vpc; import com.cloud.network.vpc.VpcVO; +import com.cloud.server.ResourceTag.TaggedResourceType; +import com.cloud.tags.dao.ResourceTagsDaoImpl; +import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.db.DB; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericSearchBuilder; @@ -25,6 +28,7 @@ import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.db.SearchCriteria.Op; +import com.cloud.utils.db.Transaction; /** * @author Alena Prokharchyk @@ -35,6 +39,7 @@ import com.cloud.utils.db.SearchCriteria.Op; public class VpcDaoImpl extends GenericDaoBase implements VpcDao{ final GenericSearchBuilder CountByOfferingId; final SearchBuilder AllFieldsSearch; + ResourceTagsDaoImpl _tagsDao = ComponentLocator.inject(ResourceTagsDaoImpl.class); protected VpcDaoImpl() { super(); @@ -82,5 +87,19 @@ public class VpcDaoImpl extends GenericDaoBase implements VpcDao{ sc.setParameters("state", Vpc.State.Inactive); return listBy(sc, null); } + + @Override + @DB + public boolean remove(Long id) { + Transaction txn = Transaction.currentTxn(); + txn.start(); + VpcVO entry = findById(id); + if (entry != null) { + _tagsDao.removeBy(id, TaggedResourceType.Vpc); + } + boolean result = super.remove(id); + txn.commit(); + return result; + } } diff --git a/server/src/com/cloud/network/vpc/NetworkACLManagerImpl.java b/server/src/com/cloud/network/vpc/NetworkACLManagerImpl.java index faef7115ed9..1906daadb96 100644 --- a/server/src/com/cloud/network/vpc/NetworkACLManagerImpl.java +++ b/server/src/com/cloud/network/vpc/NetworkACLManagerImpl.java @@ -43,6 +43,9 @@ import com.cloud.network.rules.FirewallRule.Purpose; import com.cloud.network.rules.FirewallRule.TrafficType; import com.cloud.network.rules.FirewallRuleVO; import com.cloud.projects.Project.ListProjectResourcesCriteria; +import com.cloud.server.ResourceTag.TaggedResourceType; +import com.cloud.tags.ResourceTagVO; +import com.cloud.tags.dao.ResourceTagDao; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.UserContext; @@ -51,6 +54,7 @@ import com.cloud.utils.component.Inject; import com.cloud.utils.component.Manager; import com.cloud.utils.db.DB; import com.cloud.utils.db.Filter; +import com.cloud.utils.db.JoinBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria.Op; @@ -67,7 +71,6 @@ public class NetworkACLManagerImpl implements Manager,NetworkACLManager{ String _name; private static final Logger s_logger = Logger.getLogger(NetworkACLManagerImpl.class); - @Inject AccountManager _accountMgr; @Inject @@ -78,7 +81,8 @@ public class NetworkACLManagerImpl implements Manager,NetworkACLManager{ NetworkManager _networkMgr; @Inject VpcManager _vpcMgr; - + @Inject + ResourceTagDao _resourceTagDao; @Override public boolean configure(String name, Map params) throws ConfigurationException { @@ -317,6 +321,7 @@ public class NetworkACLManagerImpl implements Manager,NetworkACLManager{ Long networkId = cmd.getNetworkId(); Long id = cmd.getId(); String trafficType = cmd.getTrafficType(); + Map tags = cmd.getTags(); Account caller = UserContext.current().getCaller(); List permittedAccounts = new ArrayList(); @@ -337,6 +342,18 @@ public class NetworkACLManagerImpl implements Manager,NetworkACLManager{ sb.and("network", sb.entity().getNetworkId(), Op.EQ); sb.and("purpose", sb.entity().getPurpose(), Op.EQ); sb.and("trafficType", sb.entity().getTrafficType(), Op.EQ); + + if (tags != null && !tags.isEmpty()) { + SearchBuilder tagSearch = _resourceTagDao.createSearchBuilder(); + for (int count=0; count < tags.size(); count++) { + tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ); + tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ); + tagSearch.cp(); + } + tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ); + sb.groupBy(sb.entity().getId()); + sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER); + } SearchCriteria sc = sb.create(); _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); @@ -352,6 +369,16 @@ public class NetworkACLManagerImpl implements Manager,NetworkACLManager{ if (trafficType != null) { sc.setParameters("trafficType", trafficType); } + + if (tags != null && !tags.isEmpty()) { + int count = 0; + sc.setJoinParameters("tagSearch", "resourceType", TaggedResourceType.NetworkACL.toString()); + for (String key : tags.keySet()) { + sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), key); + sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), tags.get(key)); + count++; + } + } sc.setParameters("purpose", Purpose.NetworkACL); diff --git a/server/src/com/cloud/network/vpc/VpcManagerImpl.java b/server/src/com/cloud/network/vpc/VpcManagerImpl.java index 1ad63f1ffa6..aa1ddc45b82 100644 --- a/server/src/com/cloud/network/vpc/VpcManagerImpl.java +++ b/server/src/com/cloud/network/vpc/VpcManagerImpl.java @@ -70,6 +70,9 @@ import com.cloud.offerings.NetworkOfferingServiceMapVO; import com.cloud.offerings.dao.NetworkOfferingServiceMapDao; import com.cloud.org.Grouping; import com.cloud.projects.Project.ListProjectResourcesCriteria; +import com.cloud.server.ResourceTag.TaggedResourceType; +import com.cloud.tags.ResourceTagVO; +import com.cloud.tags.dao.ResourceTagDao; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.User; @@ -135,6 +138,8 @@ public class VpcManagerImpl implements VpcManager, Manager{ VpcOfferingServiceMapDao _vpcOffServiceDao; @Inject PhysicalNetworkDao _pNtwkDao; + @Inject + ResourceTagDao _resourceTagDao; private final ScheduledExecutorService _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("VpcChecker")); @@ -655,7 +660,7 @@ public class VpcManagerImpl implements VpcManager, Manager{ @Override public List listVpcs(Long id, String vpcName, String displayText, List supportedServicesStr, String cidr, Long vpcOffId, String state, String accountName, Long domainId, String keyword, - Long startIndex, Long pageSizeVal, Long zoneId, Boolean isRecursive, Boolean listAll, Boolean restartRequired) { + Long startIndex, Long pageSizeVal, Long zoneId, Boolean isRecursive, Boolean listAll, Boolean restartRequired, Map tags) { Account caller = UserContext.current().getCaller(); List permittedAccounts = new ArrayList(); @@ -678,7 +683,19 @@ public class VpcManagerImpl implements VpcManager, Manager{ sb.and("zoneId", sb.entity().getZoneId(), SearchCriteria.Op.EQ); sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ); sb.and("restartRequired", sb.entity().isRestartRequired(), SearchCriteria.Op.EQ); - + + if (tags != null && !tags.isEmpty()) { + SearchBuilder tagSearch = _resourceTagDao.createSearchBuilder(); + for (int count=0; count < tags.size(); count++) { + tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ); + tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ); + tagSearch.cp(); + } + tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ); + sb.groupBy(sb.entity().getId()); + sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER); + } + // now set the SC criteria... SearchCriteria sc = sb.create(); _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); @@ -697,6 +714,16 @@ public class VpcManagerImpl implements VpcManager, Manager{ if (displayText != null) { sc.addAnd("displayText", SearchCriteria.Op.LIKE, "%" + displayText + "%"); } + + if (tags != null && !tags.isEmpty()) { + int count = 0; + sc.setJoinParameters("tagSearch", "resourceType", TaggedResourceType.Vpc.toString()); + for (String key : tags.keySet()) { + sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), key); + sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), tags.get(key)); + count++; + } + } if (id != null) { sc.addAnd("id", SearchCriteria.Op.EQ, id); @@ -1422,6 +1449,7 @@ public class VpcManagerImpl implements VpcManager, Manager{ String accountName = cmd.getAccountName(); Account caller = UserContext.current().getCaller(); List permittedAccounts = new ArrayList(); + Map tags = cmd.getTags(); Ternary domainIdRecursiveListProject = new Ternary(domainId, isRecursive, null); @@ -1439,6 +1467,18 @@ public class VpcManagerImpl implements VpcManager, Manager{ sb.and("vpcId", sb.entity().getVpcId(), SearchCriteria.Op.EQ); sb.and("vpcGatewayId", sb.entity().getVpcGatewayId(), SearchCriteria.Op.EQ); + if (tags != null && !tags.isEmpty()) { + SearchBuilder tagSearch = _resourceTagDao.createSearchBuilder(); + for (int count=0; count < tags.size(); count++) { + tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ); + tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ); + tagSearch.cp(); + } + tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ); + sb.groupBy(sb.entity().getId()); + sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER); + } + SearchCriteria sc = sb.create(); _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); @@ -1454,6 +1494,16 @@ public class VpcManagerImpl implements VpcManager, Manager{ sc.addAnd("vpcGatewayId", Op.EQ, vpcId); } + if (tags != null && !tags.isEmpty()) { + int count = 0; + sc.setJoinParameters("tagSearch", "resourceType", TaggedResourceType.StaticRoute.toString()); + for (String key : tags.keySet()) { + sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), key); + sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), tags.get(key)); + count++; + } + } + return _staticRouteDao.search(sc, searchFilter); } diff --git a/server/src/com/cloud/projects/ProjectManagerImpl.java b/server/src/com/cloud/projects/ProjectManagerImpl.java index 9b06e49a58f..52d710af76b 100755 --- a/server/src/com/cloud/projects/ProjectManagerImpl.java +++ b/server/src/com/cloud/projects/ProjectManagerImpl.java @@ -56,6 +56,9 @@ import com.cloud.projects.ProjectAccount.Role; import com.cloud.projects.dao.ProjectAccountDao; import com.cloud.projects.dao.ProjectDao; import com.cloud.projects.dao.ProjectInvitationDao; +import com.cloud.server.ResourceTag.TaggedResourceType; +import com.cloud.tags.ResourceTagVO; +import com.cloud.tags.dao.ResourceTagDao; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.AccountVO; @@ -107,6 +110,8 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ private ConfigurationDao _configDao; @Inject private ProjectInvitationDao _projectInvitationDao; + @Inject + protected ResourceTagDao _resourceTagDao; protected boolean _invitationRequired = false; protected long _invitationTimeOut = 86400000; @@ -343,7 +348,9 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ } @Override - public List listProjects(Long id, String name, String displayText, String state, String accountName, Long domainId, String keyword, Long startIndex, Long pageSize, boolean listAll, boolean isRecursive) { + public List listProjects(Long id, String name, String displayText, String state, + String accountName, Long domainId, String keyword, Long startIndex, Long pageSize, boolean listAll, + boolean isRecursive, Map tags) { Account caller = UserContext.current().getCaller(); Long accountId = null; String path = null; @@ -380,14 +387,12 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ accountId = caller.getId(); } - if (domainId == null && accountId == null && (caller.getType() == Account.ACCOUNT_TYPE_NORMAL || !listAll)) { accountId = caller.getId(); } else if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || (isRecursive && !listAll)) { DomainVO domain = _domainDao.findById(caller.getDomainId()); path = domain.getPath(); } - if (path != null) { SearchBuilder domainSearch = _domainDao.createSearchBuilder(); @@ -401,6 +406,18 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ sb.join("projectAccountSearch", projectAccountSearch, sb.entity().getId(), projectAccountSearch.entity().getProjectId(), JoinBuilder.JoinType.INNER); } + if (tags != null && !tags.isEmpty()) { + SearchBuilder tagSearch = _resourceTagDao.createSearchBuilder(); + for (int count=0; count < tags.size(); count++) { + tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ); + tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ); + tagSearch.cp(); + } + tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ); + sb.groupBy(sb.entity().getId()); + sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER); + } + SearchCriteria sc = sb.create(); if (id != null) { @@ -438,6 +455,16 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ sc.setJoinParameters("domainSearch", "path", path); } + if (tags != null && !tags.isEmpty()) { + int count = 0; + sc.setJoinParameters("tagSearch", "resourceType", TaggedResourceType.Project.toString()); + for (String key : tags.keySet()) { + sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), key); + sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), tags.get(key)); + count++; + } + } + return _projectDao.search(sc, searchFilter); } diff --git a/server/src/com/cloud/projects/dao/ProjectDaoImpl.java b/server/src/com/cloud/projects/dao/ProjectDaoImpl.java index cf9d6618b9e..744a54fc933 100644 --- a/server/src/com/cloud/projects/dao/ProjectDaoImpl.java +++ b/server/src/com/cloud/projects/dao/ProjectDaoImpl.java @@ -20,6 +20,9 @@ import org.apache.log4j.Logger; import com.cloud.projects.Project; import com.cloud.projects.ProjectVO; +import com.cloud.server.ResourceTag.TaggedResourceType; +import com.cloud.tags.dao.ResourceTagsDaoImpl; +import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.db.DB; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericSearchBuilder; @@ -34,6 +37,7 @@ public class ProjectDaoImpl extends GenericDaoBase implements P protected final SearchBuilder AllFieldsSearch; protected GenericSearchBuilder CountByDomain; protected GenericSearchBuilder ProjectAccountSearch; + ResourceTagsDaoImpl _tagsDao = ComponentLocator.inject(ResourceTagsDaoImpl.class); protected ProjectDaoImpl() { AllFieldsSearch = createSearchBuilder(); @@ -69,9 +73,9 @@ public class ProjectDaoImpl extends GenericDaoBase implements P if (!update(projectId, projectToRemove)) { s_logger.warn("Failed to reset name for the project id=" + projectId + " as a part of project remove"); return false; - } else { - - } + } + + _tagsDao.removeBy(projectId, TaggedResourceType.Project); result = super.remove(projectId); txn.commit(); @@ -100,5 +104,4 @@ public class ProjectDaoImpl extends GenericDaoBase implements P sc.setParameters("state", state); return listBy(sc); } - } diff --git a/server/src/com/cloud/storage/StorageManagerImpl.java b/server/src/com/cloud/storage/StorageManagerImpl.java index 33c1df78cf7..21de0a75cbb 100755 --- a/server/src/com/cloud/storage/StorageManagerImpl.java +++ b/server/src/com/cloud/storage/StorageManagerImpl.java @@ -327,6 +327,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag @Inject(adapter = StoragePoolDiscoverer.class) protected Adapters _discoverers; + protected SearchBuilder HostTemplateStatesSearch; protected GenericSearchBuilder UpHostsInPoolSearch; protected SearchBuilder StoragePoolSearch; diff --git a/server/src/com/cloud/tags/TaggedResourceManagerImpl.java b/server/src/com/cloud/tags/TaggedResourceManagerImpl.java index c8aaa3b0deb..ca4dededb10 100644 --- a/server/src/com/cloud/tags/TaggedResourceManagerImpl.java +++ b/server/src/com/cloud/tags/TaggedResourceManagerImpl.java @@ -35,7 +35,10 @@ import com.cloud.network.dao.NetworkDao; import com.cloud.network.dao.RemoteAccessVpnDao; import com.cloud.network.rules.dao.PortForwardingRulesDao; import com.cloud.network.security.dao.SecurityGroupDao; +import com.cloud.network.vpc.Dao.StaticRouteDao; +import com.cloud.network.vpc.Dao.VpcDao; import com.cloud.projects.Project.ListProjectResourcesCriteria; +import com.cloud.projects.dao.ProjectDao; import com.cloud.server.ResourceTag; import com.cloud.server.ResourceTag.TaggedResourceType; import com.cloud.server.TaggedResourceService; @@ -58,6 +61,7 @@ import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; +import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.uuididentity.dao.IdentityDao; import com.cloud.vm.dao.UserVmDao; @@ -102,6 +106,12 @@ public class TaggedResourceManagerImpl implements TaggedResourceService, Manager RemoteAccessVpnDao _vpnDao; @Inject IPAddressDao _publicIpDao; + @Inject + ProjectDao _projectDao; + @Inject + VpcDao _vpcDao; + @Inject + StaticRouteDao _staticRouteDao; @Override public boolean configure(String name, Map params) throws ConfigurationException { @@ -117,6 +127,10 @@ public class TaggedResourceManagerImpl implements TaggedResourceService, Manager _daoMap.put(TaggedResourceType.FirewallRule, _firewallDao); _daoMap.put(TaggedResourceType.SecurityGroup, _securityGroupDao); _daoMap.put(TaggedResourceType.PublicIpAddress, _publicIpDao); + _daoMap.put(TaggedResourceType.Project, _projectDao); + _daoMap.put(TaggedResourceType.Vpc, _vpcDao); + _daoMap.put(TaggedResourceType.NetworkACL, _firewallDao); + _daoMap.put(TaggedResourceType.StaticRoute, _staticRouteDao); return true; } @@ -139,6 +153,9 @@ public class TaggedResourceManagerImpl implements TaggedResourceService, Manager private Long getResourceId(String resourceId, TaggedResourceType resourceType) { GenericDao dao = _daoMap.get(resourceType); + if (dao == null) { + throw new CloudRuntimeException("Dao is not loaded for the resource type " + resourceType); + } Class claz = DbUtil.getEntityBeanType(dao); Long identityId = null; @@ -182,7 +199,7 @@ public class TaggedResourceManagerImpl implements TaggedResourceService, Manager if (tableName == null) { throw new InvalidParameterValueException("Unable to find resource of type " + resourceType + " in the database"); } - pair = _identityDao.getAccountDomainInfo(tableName, resourceId); + pair = _identityDao.getAccountDomainInfo(tableName, resourceId, resourceType); if (pair.first() != null || pair.second() != null) { break; } diff --git a/server/src/com/cloud/uuididentity/dao/IdentityDao.java b/server/src/com/cloud/uuididentity/dao/IdentityDao.java index f963fcbc476..8a5b14db7b4 100644 --- a/server/src/com/cloud/uuididentity/dao/IdentityDao.java +++ b/server/src/com/cloud/uuididentity/dao/IdentityDao.java @@ -13,6 +13,7 @@ package com.cloud.uuididentity.dao; import com.cloud.api.IdentityMapper; +import com.cloud.server.ResourceTag.TaggedResourceType; import com.cloud.utils.Pair; import com.cloud.utils.db.GenericDao; @@ -24,7 +25,8 @@ public interface IdentityDao extends GenericDao { /** * @param tableName * @param identityId + * @param resourceType TODO * @return */ - Pair getAccountDomainInfo(String tableName, Long identityId); + Pair getAccountDomainInfo(String tableName, Long identityId, TaggedResourceType resourceType); } diff --git a/server/src/com/cloud/uuididentity/dao/IdentityDaoImpl.java b/server/src/com/cloud/uuididentity/dao/IdentityDaoImpl.java index a86dbcb0447..fefe70b25bd 100644 --- a/server/src/com/cloud/uuididentity/dao/IdentityDaoImpl.java +++ b/server/src/com/cloud/uuididentity/dao/IdentityDaoImpl.java @@ -25,6 +25,7 @@ import org.apache.log4j.Logger; import com.cloud.api.IdentityMapper; import com.cloud.exception.InvalidParameterValueException; +import com.cloud.server.ResourceTag.TaggedResourceType; import com.cloud.utils.Pair; import com.cloud.utils.db.DB; import com.cloud.utils.db.GenericDaoBase; @@ -97,7 +98,7 @@ public class IdentityDaoImpl extends GenericDaoBase implements @DB @Override - public Pair getAccountDomainInfo(String tableName, Long identityId) { + public Pair getAccountDomainInfo(String tableName, Long identityId, TaggedResourceType resourceType) { assert(tableName != null); PreparedStatement pstmt = null; @@ -118,7 +119,11 @@ public class IdentityDaoImpl extends GenericDaoBase implements //get accountId try { - pstmt = txn.prepareAutoCloseStatement(String.format("SELECT account_id FROM `%s` WHERE id=?", tableName)); + String account = "account_id"; + if (resourceType == TaggedResourceType.Project) { + account = "project_account_id"; + } + pstmt = txn.prepareAutoCloseStatement(String.format("SELECT " + account + " FROM `%s` WHERE id=?", tableName)); pstmt.setLong(1, identityId); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { From 447f018b1398eff4f241bfa491503a7f354c81be Mon Sep 17 00:00:00 2001 From: Alena Prokharchyk Date: Thu, 5 Jul 2012 17:57:36 -0700 Subject: [PATCH 24/26] VPC: fixed CS-15465 - lb creation for ip not associated with any networks --- .../lb/LoadBalancingRulesManagerImpl.java | 44 +++++++++---------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java b/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java index 21331070214..0e7065d5e36 100755 --- a/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java +++ b/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java @@ -711,42 +711,42 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesMa } Long ipAddrId = lb.getSourceIpAddressId(); - IPAddressVO ipAddressVO = null; + IPAddressVO ipVO = null; if (ipAddrId != null) { - ipAddressVO = _ipAddressDao.findById(ipAddrId); + ipVO = _ipAddressDao.findById(ipAddrId); // Validate ip address - if (ipAddressVO == null) { + if (ipVO == null) { throw new InvalidParameterValueException("Unable to create load balance rule; ip id=" + ipAddrId + "" + " doesn't exist in the system"); - } else if (ipAddressVO.isOneToOneNat()) { - throw new NetworkRuleConflictException("Can't do load balance on ip address: " + ipAddressVO.getAddress()); + } else if (ipVO.isOneToOneNat()) { + throw new NetworkRuleConflictException("Can't do load balance on ip address: " + ipVO.getAddress()); } } LoadBalancer result = _elbMgr.handleCreateLoadBalancerRule(lb, lbOwner, lb.getNetworkId()); boolean performedIpAssoc = false; if (result == null) { - IpAddress ip = null; + IpAddress systemIp = null; Network guestNetwork = _networkMgr.getNetwork(lb.getNetworkId()); NetworkOffering off = _configMgr.getNetworkOffering(guestNetwork.getNetworkOfferingId()); - if (off.getElasticLb() && ipAddressVO == null) { - ip = _networkMgr.assignSystemIp(lb.getNetworkId(), lbOwner, true, false); - lb.setSourceIpAddressId(ip.getId()); + if (off.getElasticLb() && ipVO == null) { + systemIp = _networkMgr.assignSystemIp(lb.getNetworkId(), lbOwner, true, false); + lb.setSourceIpAddressId(systemIp.getId()); } try { - if (ipAddressVO != null) { - if (ipAddressVO.getAssociatedWithNetworkId() == null) { + if (ipVO != null) { + if (ipVO.getAssociatedWithNetworkId() == null) { //set networkId just for verification purposes - ipAddressVO.setAssociatedWithNetworkId(lb.getNetworkId()); - _networkMgr.checkIpForService(ipAddressVO, Service.Lb); + ipVO.setAssociatedWithNetworkId(lb.getNetworkId()); + _networkMgr.checkIpForService(ipVO, Service.Lb); s_logger.debug("The ip is not associated with the network id="+ lb.getNetworkId() + " so assigning"); - ipAddressVO = _networkMgr.associateIPToGuestNetwork(ipAddrId, lb.getNetworkId()); + ipVO = _networkMgr.associateIPToGuestNetwork(ipAddrId, lb.getNetworkId()); performedIpAssoc = true; } else { - _networkMgr.checkIpForService(ipAddressVO, Service.Lb); + _networkMgr.checkIpForService(ipVO, Service.Lb); } } @@ -760,17 +760,17 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesMa throw (NetworkRuleConflictException) ex; } } finally { - if (result == null && ip != null) { - s_logger.debug("Releasing system IP address " + ip + " as corresponding lb rule failed to create"); - _networkMgr.handleSystemIpRelease(ip); + if (result == null && systemIp != null) { + s_logger.debug("Releasing system IP address " + systemIp + " as corresponding lb rule failed to create"); + _networkMgr.handleSystemIpRelease(systemIp); } // release ip address if ipassoc was perfored if (performedIpAssoc) { //if the rule is the last one for the ip address assigned to VPC, unassign it from the network - ip = _ipAddressDao.findById(ip.getId()); - if (ip != null && ip.getVpcId() != null && _firewallDao.listByIp(ip.getId()).isEmpty()) { - s_logger.debug("Releasing VPC ip address " + ip + " as LB rule failed to create"); - _networkMgr.unassignIPFromVpcNetwork(ip.getId()); + ipVO = _ipAddressDao.findById(ipVO.getId()); + if (ipVO != null && ipVO.getVpcId() != null && _firewallDao.listByIp(ipVO.getId()).isEmpty()) { + s_logger.debug("Releasing VPC ip address " + ipVO + " as LB rule failed to create"); + _networkMgr.unassignIPFromVpcNetwork(ipVO.getId()); } } } From f2546dd2bd2a49f58261b8ecd3bf6d36e5aab175 Mon Sep 17 00:00:00 2001 From: Alena Prokharchyk Date: Thu, 5 Jul 2012 18:33:23 -0700 Subject: [PATCH 25/26] CS-15459: fixed listTags for userVms --- .../src/com/cloud/tags/TaggedResourceManagerImpl.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/server/src/com/cloud/tags/TaggedResourceManagerImpl.java b/server/src/com/cloud/tags/TaggedResourceManagerImpl.java index ca4dededb10..f05f422dde6 100644 --- a/server/src/com/cloud/tags/TaggedResourceManagerImpl.java +++ b/server/src/com/cloud/tags/TaggedResourceManagerImpl.java @@ -295,14 +295,14 @@ public class TaggedResourceManagerImpl implements TaggedResourceService, Manager if (tableName == null) { throw new InvalidParameterValueException("Unable to find resource of type " + resourceType + " in the database"); } - identiyUUId = _identityDao.getIdentityUuid(tableName, resourceId); - if (identiyUUId != null) { - break; - } + + claz = claz.getSuperclass(); + if (claz == Object.class) { + identiyUUId = _identityDao.getIdentityUuid(tableName, resourceId); + } } catch (Exception ex) { //do nothing here, it might mean uuid field is missing and we have to search further } - claz = claz.getSuperclass(); } if (identiyUUId == null) { From 6eebd7aa0d857e26047572bcfdb6298749401dd8 Mon Sep 17 00:00:00 2001 From: Jessica Wang Date: Thu, 5 Jul 2012 18:33:14 -0700 Subject: [PATCH 26/26] cloudstack 3.0 UI - VPC - create tier action is sync, not async. --- ui/scripts/network.js | 5 +---- ui/scripts/ui-custom/vpc.js | 5 ++--- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/ui/scripts/network.js b/ui/scripts/network.js index 0037eebff28..e484cec7ad4 100644 --- a/ui/scripts/network.js +++ b/ui/scripts/network.js @@ -3231,10 +3231,7 @@ ); } }); - }, - notification: { - poll: pollAsyncJobResult - } + } }, editVpc: { label: 'Edit VPC', diff --git a/ui/scripts/ui-custom/vpc.js b/ui/scripts/ui-custom/vpc.js index 84d0abe58b7..ff39d8d8ae0 100644 --- a/ui/scripts/ui-custom/vpc.js +++ b/ui/scripts/ui-custom/vpc.js @@ -472,14 +472,13 @@ context: context, data: args.data, response: { - success: function(args) { + success: function(args) { var tier = args.data; cloudStack.ui.notifications.add( // Notification { - desc: actions.add.label, - poll: actions.add.notification.poll + desc: actions.add.label }, // Success