From 5de4f05a1c7e7f87d39e5667cac0d3899d630f50 Mon Sep 17 00:00:00 2001 From: alena Date: Mon, 11 Apr 2011 16:40:35 -0700 Subject: [PATCH] bug 9391: removed source_id, source_type from "volumes" table as we don't use them any more status 9391: resolved fixed --- .../cloud/api/response/VolumeResponse.java | 200 +++-- .../com/cloud/network/NetworkManagerImpl.java | 701 +++++++++--------- .../com/cloud/upgrade/dao/Upgrade218to22.java | 20 +- setup/db/create-schema.sql | 2 - setup/db/db/schema-21to22-cleanup.sql | 3 + setup/db/db/schema-21to22.sql | 3 + setup/db/db/schema-222to224-cleanup.sql | 2 + setup/db/db/schema-222to224.sql | 3 - 8 files changed, 465 insertions(+), 469 deletions(-) diff --git a/api/src/com/cloud/api/response/VolumeResponse.java b/api/src/com/cloud/api/response/VolumeResponse.java index 8df95a884f1..7faee11826b 100755 --- a/api/src/com/cloud/api/response/VolumeResponse.java +++ b/api/src/com/cloud/api/response/VolumeResponse.java @@ -24,113 +24,135 @@ import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; public class VolumeResponse extends BaseResponse { - @SerializedName(ApiConstants.ID) @Param(description="ID of the disk volume") + @SerializedName(ApiConstants.ID) + @Param(description = "ID of the disk volume") private Long id; - @SerializedName(ApiConstants.JOB_ID) @Param(description="shows the current pending asynchronous job ID. This tag is not returned if no current pending jobs are acting on the volume") + @SerializedName(ApiConstants.JOB_ID) + @Param(description = "shows the current pending asynchronous job ID. This tag is not returned if no current pending jobs are acting on the volume") private Long jobId; - @SerializedName("jobstatus") @Param(description="shows the current pending asynchronous job status") + @SerializedName("jobstatus") + @Param(description = "shows the current pending asynchronous job status") private Integer jobStatus; - @SerializedName(ApiConstants.NAME) @Param(description="name of the disk volume") + @SerializedName(ApiConstants.NAME) + @Param(description = "name of the disk volume") private String name; - @SerializedName(ApiConstants.ZONE_ID) @Param(description="ID of the availability zone") + @SerializedName(ApiConstants.ZONE_ID) + @Param(description = "ID of the availability zone") private Long zoneId; - @SerializedName("zonename") @Param(description="name of the availability zone") + @SerializedName("zonename") + @Param(description = "name of the availability zone") private String zoneName; - @SerializedName(ApiConstants.TYPE) @Param(description="type of the disk volume (ROOT or DATADISK)") + @SerializedName(ApiConstants.TYPE) + @Param(description = "type of the disk volume (ROOT or DATADISK)") private String volumeType; - @SerializedName(ApiConstants.DEVICE_ID) @Param(description="the ID of the device on user vm the volume is attahed to. This tag is not returned when the volume is detached.") + @SerializedName(ApiConstants.DEVICE_ID) + @Param(description = "the ID of the device on user vm the volume is attahed to. This tag is not returned when the volume is detached.") private Long deviceId; - @SerializedName(ApiConstants.VIRTUAL_MACHINE_ID) @Param(description="id of the virtual machine") + @SerializedName(ApiConstants.VIRTUAL_MACHINE_ID) + @Param(description = "id of the virtual machine") private Long virtualMachineId; - @SerializedName("vmname") @Param(description="name of the virtual machine") + @SerializedName("vmname") + @Param(description = "name of the virtual machine") private String virtualMachineName; - @SerializedName("vmdisplayname") @Param(description="display name of the virtual machine") + @SerializedName("vmdisplayname") + @Param(description = "display name of the virtual machine") private String virtualMachineDisplayName; - @SerializedName("vmstate") @Param(description="state of the virtual machine") + @SerializedName("vmstate") + @Param(description = "state of the virtual machine") private String virtualMachineState; - @SerializedName(ApiConstants.SIZE) @Param(description="size of the disk volume") + @SerializedName(ApiConstants.SIZE) + @Param(description = "size of the disk volume") private Long size; - @SerializedName(ApiConstants.CREATED) @Param(description="the date the disk volume was created") + @SerializedName(ApiConstants.CREATED) + @Param(description = "the date the disk volume was created") private Date created; - @SerializedName(ApiConstants.STATE) @Param(description="the state of the disk volume") + @SerializedName(ApiConstants.STATE) + @Param(description = "the state of the disk volume") private String state; - - @SerializedName(ApiConstants.STATUS) @Param(description="the status of the disk volume") - private String status; - @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account associated with the disk volume") + @SerializedName(ApiConstants.ACCOUNT) + @Param(description = "the account associated with the disk volume") private String accountName; - @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the ID of the domain associated with the disk volume") + @SerializedName(ApiConstants.DOMAIN_ID) + @Param(description = "the ID of the domain associated with the disk volume") private Long domainId; - @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain associated with the disk volume") + @SerializedName(ApiConstants.DOMAIN) + @Param(description = "the domain associated with the disk volume") private String domainName; - @SerializedName("storagetype") @Param(description="shared or local storage") + @SerializedName("storagetype") + @Param(description = "shared or local storage") private String storageType; - @SerializedName("sourceid") @Param(description="Id of the snapshot or diskOffering volume is created from") - private Long sourceId; - - @SerializedName("sourcetype") @Param(description="Type of the source the volume is created from. Can be: Snapshot,DiskOffering") - private String sourceType; - - @SerializedName(ApiConstants.HYPERVISOR) @Param(description="Hypervisor the volume belongs to") + @SerializedName(ApiConstants.HYPERVISOR) + @Param(description = "Hypervisor the volume belongs to") private String hypervisor; - @SerializedName(ApiConstants.DISK_OFFERING_ID) @Param(description="ID of the disk offering") + @SerializedName(ApiConstants.DISK_OFFERING_ID) + @Param(description = "ID of the disk offering") private Long diskOfferingId; - @SerializedName("diskofferingname") @Param(description="name of the disk offering") + @SerializedName("diskofferingname") + @Param(description = "name of the disk offering") private String diskOfferingName; - @SerializedName("diskofferingdisplaytext") @Param(description="the display text of the disk offering") + @SerializedName("diskofferingdisplaytext") + @Param(description = "the display text of the disk offering") private String diskOfferingDisplayText; - @SerializedName("storage") @Param(description="name of the primary storage hosting the disk volume") + @SerializedName("storage") + @Param(description = "name of the primary storage hosting the disk volume") private String storagePoolName; - @SerializedName(ApiConstants.SNAPSHOT_ID) @Param(description="ID of the snapshot from which this volume was created") + @SerializedName(ApiConstants.SNAPSHOT_ID) + @Param(description = "ID of the snapshot from which this volume was created") private Long snapshotId; - @SerializedName("attached") @Param(description="the date the volume was attached to a VM instance") + @SerializedName("attached") + @Param(description = "the date the volume was attached to a VM instance") private Date attached; - @SerializedName("destroyed") @Param(description="the boolean state of whether the volume is destroyed or not") + @SerializedName("destroyed") + @Param(description = "the boolean state of whether the volume is destroyed or not") private Boolean destroyed; - @SerializedName(ApiConstants.SERVICE_OFFERING_ID) @Param(description="ID of the service offering for root disk") + @SerializedName(ApiConstants.SERVICE_OFFERING_ID) + @Param(description = "ID of the service offering for root disk") private Long serviceOfferingId; - @SerializedName("serviceofferingname") @Param(description="name of the service offering for root disk") + @SerializedName("serviceofferingname") + @Param(description = "name of the service offering for root disk") private String serviceOfferingName; - @SerializedName("serviceofferingdisplaytext") @Param(description="the display text of the service offering for root disk") + @SerializedName("serviceofferingdisplaytext") + @Param(description = "the display text of the service offering for root disk") private String serviceOfferingDisplayText; - - @SerializedName("isextractable") @Param(description="true if the volume is extractable, false otherwise") + + @SerializedName("isextractable") + @Param(description = "true if the volume is extractable, false otherwise") private Boolean extractable; - + @Override public Long getObjectId() { - return getId(); + return getId(); } - + @Override public Long getJobId() { return jobId; @@ -140,7 +162,7 @@ public class VolumeResponse extends BaseResponse { public void setJobId(Long jobId) { this.jobId = jobId; } - + @Override public Integer getJobStatus() { return jobStatus; @@ -152,14 +174,14 @@ public class VolumeResponse extends BaseResponse { } public Boolean getDestroyed() { - return destroyed; - } + return destroyed; + } - public void setDestroyed(Boolean destroyed) { - this.destroyed = destroyed; - } + public void setDestroyed(Boolean destroyed) { + this.destroyed = destroyed; + } - public Long getId() { + public Long getId() { return id; } @@ -255,14 +277,6 @@ public class VolumeResponse extends BaseResponse { this.created = created; } - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - public String getAccountName() { return accountName; } @@ -295,22 +309,6 @@ public class VolumeResponse extends BaseResponse { this.storageType = storageType; } - public Long getSourceId() { - return sourceId; - } - - public void setSourceId(Long sourceId) { - this.sourceId = sourceId; - } - - public String getSourceType() { - return sourceType; - } - - public void setSourceType(String sourceType) { - this.sourceType = sourceType; - } - public String getHypervisor() { return hypervisor; } @@ -367,43 +365,43 @@ public class VolumeResponse extends BaseResponse { this.attached = attached; } - public Long getServiceOfferingId() { - return serviceOfferingId; - } + public Long getServiceOfferingId() { + return serviceOfferingId; + } - public void setServiceOfferingId(Long serviceOfferingId) { - this.serviceOfferingId = serviceOfferingId; - } + public void setServiceOfferingId(Long serviceOfferingId) { + this.serviceOfferingId = serviceOfferingId; + } - public String getServiceOfferingName() { - return serviceOfferingName; - } + public String getServiceOfferingName() { + return serviceOfferingName; + } - public void setServiceOfferingName(String serviceOfferingName) { - this.serviceOfferingName = serviceOfferingName; - } + public void setServiceOfferingName(String serviceOfferingName) { + this.serviceOfferingName = serviceOfferingName; + } - public String getServiceOfferingDisplayText() { - return serviceOfferingDisplayText; - } + public String getServiceOfferingDisplayText() { + return serviceOfferingDisplayText; + } - public void setServiceOfferingDisplayText(String serviceOfferingDisplayText) { - this.serviceOfferingDisplayText = serviceOfferingDisplayText; - } + public void setServiceOfferingDisplayText(String serviceOfferingDisplayText) { + this.serviceOfferingDisplayText = serviceOfferingDisplayText; + } - public Boolean getExtractable() { - return extractable; - } + public Boolean getExtractable() { + return extractable; + } + + public void setExtractable(Boolean extractable) { + this.extractable = extractable; + } - public void setExtractable(Boolean extractable) { - this.extractable = extractable; - } - public String getState() { return state; } public void setState(String state) { this.state = state; - } + } } diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index c69d128e080..9777bc839e6 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -203,7 +203,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Inject NetworkDomainDao _networkDomainDao; - private HashMap _systemNetworks = new HashMap(5); + private final HashMap _systemNetworks = new HashMap(5); ScheduledExecutorService _executor; @@ -228,7 +228,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } @DB - public PublicIp fetchNewPublicIp(long dcId, Long podId, Long vlanDbId, Account owner, VlanType vlanUse, Long networkId, boolean sourceNat, boolean assign) throws InsufficientAddressCapacityException { + public PublicIp fetchNewPublicIp(long dcId, Long podId, Long vlanDbId, Account owner, VlanType vlanUse, Long networkId, boolean sourceNat, boolean assign) + throws InsufficientAddressCapacityException { Transaction txn = Transaction.currentTxn(); txn.start(); SearchCriteria sc = null; @@ -277,36 +278,36 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (vlanUse != VlanType.DirectAttached) { addr.setAssociatedWithNetworkId(networkId); } - + _ipAddressDao.update(addr.getId(), addr); - + txn.commit(); long macAddress = NetUtils.createSequenceBasedMacAddress(addr.getMacAddress()); return new PublicIp(addr, _vlanDao.findById(addr.getVlanId()), macAddress); } - + @DB protected void markPublicIpAsAllocated(IPAddressVO addr) { - + assert (addr.getState() == IpAddress.State.Allocating || addr.getState() == IpAddress.State.Free) : "Unable to transition from state " + addr.getState() + " to " + IpAddress.State.Allocated; - + Transaction txn = Transaction.currentTxn(); - + Account owner = _accountMgr.getAccount(addr.getAccountId()); long isSourceNat = (addr.isSourceNat()) ? 1 : 0; - + txn.start(); addr.setState(IpAddress.State.Allocated); _ipAddressDao.update(addr.getId(), addr); - - //Save usage event + + // Save usage event if (owner.getAccountId() != Account.ACCOUNT_ID_SYSTEM) { UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NET_IP_ASSIGN, owner.getId(), addr.getDataCenterId(), addr.getId(), addr.getAddress().toString(), isSourceNat); _usageEventDao.persist(usageEvent); _accountMgr.incrementResourceCount(owner.getId(), ResourceType.public_ip); - } - + } + txn.commit(); } @@ -353,9 +354,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag ip = fetchNewPublicIp(dcId, null, vlanId, owner, VlanType.VirtualNetwork, network.getId(), true, false); sourceNat = ip.ip(); - + markPublicIpAsAllocated(sourceNat); - _ipAddressDao.update(sourceNat.getId(), sourceNat); + _ipAddressDao.update(sourceNat.getId(), sourceNat); } else { // Account already has ip addresses for (IPAddressVO addr : addrs) { @@ -395,7 +396,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag * - non-null if the domainId was passed in in the command. * @return */ - protected Account getAccountForApiCommand(String accountName, Long domainId){ + protected Account getAccountForApiCommand(String accountName, Long domainId) { Account account = UserContext.current().getCaller(); if (_accountMgr.isAdmin(account.getType())) { @@ -426,8 +427,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag List publicIps = new ArrayList(); if (userIps != null && !userIps.isEmpty()) { for (IPAddressVO userIp : userIps) { - PublicIp publicIp = new PublicIp(userIp, _vlanDao.findById(userIp.getVlanId()), NetUtils.createSequenceBasedMacAddress(userIp.getMacAddress())); - publicIps.add(publicIp); + PublicIp publicIp = new PublicIp(userIp, _vlanDao.findById(userIp.getVlanId()), NetUtils.createSequenceBasedMacAddress(userIp.getMacAddress())); + publicIps.add(publicIp); } } @@ -447,14 +448,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (success) { for (IPAddressVO addr : userIps) { - + if (addr.getState() == IpAddress.State.Allocating) { - + addr.setAssociatedWithNetworkId(network.getId()); markPublicIpAsAllocated(addr); - + } else if (addr.getState() == IpAddress.State.Releasing) { - //Cleanup all the resources for ip address if there are any, and only then unassign ip in the system + // Cleanup all the resources for ip address if there are any, and only then unassign ip in the system if (cleanupIpResources(addr.getId(), Account.ACCOUNT_ID_SYSTEM, _accountMgr.getSystemAccount())) { _ipAddressDao.unassignIpAddress(addr.getId()); } else { @@ -478,7 +479,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return _networksDao.listBy(owner.getId(), zoneId, GuestIpType.Virtual); } - @Override @DB @ActionEvent (eventType=EventTypes.EVENT_NET_IP_ASSIGN, eventDescription="allocating Ip", create=true) + @Override + @DB + @ActionEvent(eventType = EventTypes.EVENT_NET_IP_ASSIGN, eventDescription = "allocating Ip", create = true) public IpAddress allocateIP(AssociateIPAddrCmd cmd) throws ResourceAllocationException, InsufficientAddressCapacityException, ConcurrentOperationException { String accountName = cmd.getAccountName(); long domainId = cmd.getDomainId(); @@ -492,17 +495,16 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } _accountMgr.checkAccess(caller, ipOwner); - - if(zoneId != null){ - DataCenterVO zone = _dcDao.findById(zoneId); - if (zone == null) { - throw new InvalidParameterValueException("Can't find zone by id " - + zoneId); - } - - if(Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getType())){ - throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: "+ zoneId ); - } + + if (zoneId != null) { + DataCenterVO zone = _dcDao.findById(zoneId); + if (zone == null) { + throw new InvalidParameterValueException("Can't find zone by id " + zoneId); + } + + if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getType())) { + throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zoneId); + } } long ownerId = ipOwner.getId(); Long networkId = cmd.getNetworkId(); @@ -513,8 +515,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag throw new InvalidParameterValueException("Network id is invalid: " + networkId); } } - - //Check that network belongs to IP owner + + // Check that network belongs to IP owner if (network.getAccountId() != ipOwner.getId()) { throw new InvalidParameterValueException("The owner of the network is not the same as owner of the IP"); } @@ -544,23 +546,23 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag rae.setResourceType("ip"); throw rae; } - + boolean isSourceNat = false; txn.start(); - //First IP address should be source nat + // First IP address should be source nat List addrs = listPublicIpAddressesInVirtualNetwork(ownerId, zoneId, true, networkId); - + if (addrs.isEmpty()) { isSourceNat = true; } - + ip = fetchNewPublicIp(zoneId, null, null, ipOwner, VlanType.VirtualNetwork, network.getId(), isSourceNat, false); if (ip == null) { throw new InsufficientAddressCapacityException("Unable to find available public IP addresses", DataCenter.class, zoneId); } - UserContext.current().setEventDetails("Ip Id: "+ip.getId()); + UserContext.current().setEventDetails("Ip Id: " + ip.getId()); Ip ipAddress = ip.getAddress(); s_logger.debug("Got " + ipAddress + " to assign for account " + ipOwner.getId() + " in zone " + network.getDataCenterId()); @@ -576,7 +578,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return ip; } - @Override @DB @ActionEvent (eventType=EventTypes.EVENT_NET_IP_ASSIGN, eventDescription="associating Ip", async=true) + @Override + @DB + @ActionEvent(eventType = EventTypes.EVENT_NET_IP_ASSIGN, eventDescription = "associating Ip", async = true) public IpAddress associateIP(AssociateIPAddrCmd cmd) throws ResourceAllocationException, ResourceUnavailableException, InsufficientAddressCapacityException, ConcurrentOperationException { Account caller = UserContext.current().getCaller(); Account owner = null; @@ -612,7 +616,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.warn("Failed to associate ip address " + ip); _ipAddressDao.markAsUnavailable(ip.getId()); if (!applyIpAssociations(network, true)) { - //if fail to apply ip assciations again, unassign ip address without updating resource count and generating usage event as there is no need to keep it in the db + // if fail to apply ip assciations again, unassign ip address without updating resource count and + // generating usage event as there is no need to keep it in the db _ipAddressDao.unassignIpAddress(ip.getId()); } } catch (Exception e) { @@ -623,11 +628,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } - @Override @DB + @Override + @DB public boolean releasePublicIpAddress(long addrId, long userId, Account caller) { - + IPAddressVO ip = markIpAsUnavailable(addrId); - + assert (ip != null) : "Unable to mark the ip address id=" + addrId + " as unavailable."; if (ip == null) { return true; @@ -638,14 +644,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } boolean success = true; - - //Cleanup all ip address resources - PF/LB/Static nat rules + + // Cleanup all ip address resources - PF/LB/Static nat rules if (!cleanupIpResources(addrId, userId, caller)) { success = false; s_logger.warn("Failed to release resources for ip address id=" + addrId); } - if (ip.getAssociatedWithNetworkId() != null) { + if (ip.getAssociatedWithNetworkId() != null) { Network network = _networksDao.findById(ip.getAssociatedWithNetworkId()); try { if (!applyIpAssociations(network, true)) { @@ -674,7 +680,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag _configs = _configDao.getConfiguration("Network", params); _networkDomain = _configs.get(Config.GuestDomainSuffix.key()); - + _cidrLimit = NumbersUtil.parseInt(_configs.get(Config.NetworkGuestCidrLimit.key()), 22); NetworkOfferingVO publicNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemPublicNetwork, TrafficType.Public); @@ -689,50 +695,23 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag NetworkOfferingVO storageNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemStorageNetwork, TrafficType.Storage); storageNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(storageNetworkOffering); _systemNetworks.put(NetworkOfferingVO.SystemStorageNetwork, storageNetworkOffering); - NetworkOfferingVO guestNetworkOffering = new NetworkOfferingVO( - NetworkOffering.SystemGuestNetwork, - "System Offering for System-Guest-Network", - TrafficType.Guest, - true, - false, - null, - null, - null, - true, - Availability.Required, - //services - all true except for firewall/lb/vpn and gateway services - true, true, true, false, false,false, false, GuestIpType.Direct); + NetworkOfferingVO guestNetworkOffering = new NetworkOfferingVO(NetworkOffering.SystemGuestNetwork, "System Offering for System-Guest-Network", TrafficType.Guest, true, false, null, null, + null, true, Availability.Required, + // services - all true except for firewall/lb/vpn and gateway services + true, true, true, false, false, false, false, GuestIpType.Direct); guestNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(guestNetworkOffering); _systemNetworks.put(NetworkOfferingVO.SystemGuestNetwork, guestNetworkOffering); - NetworkOfferingVO defaultGuestNetworkOffering = new NetworkOfferingVO( - NetworkOffering.DefaultVirtualizedNetworkOffering, - "Virtual Vlan", - TrafficType.Guest, - false, - false, - null, - null, - null, - true, - Availability.Required, - //services - true, true, true, true,true, true, true, GuestIpType.Virtual); - + NetworkOfferingVO defaultGuestNetworkOffering = new NetworkOfferingVO(NetworkOffering.DefaultVirtualizedNetworkOffering, "Virtual Vlan", TrafficType.Guest, false, false, null, null, null, + true, Availability.Required, + // services + true, true, true, true, true, true, true, GuestIpType.Virtual); + defaultGuestNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultGuestNetworkOffering); - NetworkOfferingVO defaultGuestDirectNetworkOffering = new NetworkOfferingVO( - NetworkOffering.DefaultDirectNetworkOffering, - "Direct", - TrafficType.Guest, - false, - true, - null, - null, - null, - true, - Availability.Optional, - //services - all true except for firewall/lb/vpn and gateway services - true, true, true, false, false,false, false, GuestIpType.Direct); + NetworkOfferingVO defaultGuestDirectNetworkOffering = new NetworkOfferingVO(NetworkOffering.DefaultDirectNetworkOffering, "Direct", TrafficType.Guest, false, true, null, null, null, true, + Availability.Optional, + // services - all true except for firewall/lb/vpn and gateway services + true, true, true, false, false, false, false, GuestIpType.Direct); defaultGuestDirectNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultGuestDirectNetworkOffering); AccountsUsingNetworkSearch = _accountDao.createSearchBuilder(); @@ -814,7 +793,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (associatedNetworkId != null) { sc.setParameters("associatedWithNetworkId", associatedNetworkId); } - + if (sourceNat != null) { sc.addAnd("sourceNat", SearchCriteria.Op.EQ, sourceNat); } @@ -824,13 +803,15 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } @Override - public List setupNetwork(Account owner, NetworkOfferingVO offering, DeploymentPlan plan, String name, String displayText, boolean isShared, boolean isDefault) throws ConcurrentOperationException { + public List setupNetwork(Account owner, NetworkOfferingVO offering, DeploymentPlan plan, String name, String displayText, boolean isShared, boolean isDefault) + throws ConcurrentOperationException { return setupNetwork(owner, offering, null, plan, name, displayText, isShared, isDefault, false, null); } @Override @DB - public List setupNetwork(Account owner, NetworkOfferingVO offering, Network predefined, DeploymentPlan plan, String name, String displayText, boolean isShared, boolean isDefault, boolean errorIfAlreadySetup, Long domainId) throws ConcurrentOperationException { + public List setupNetwork(Account owner, NetworkOfferingVO offering, Network predefined, DeploymentPlan plan, String name, String displayText, boolean isShared, boolean isDefault, + boolean errorIfAlreadySetup, Long domainId) throws ConcurrentOperationException { Transaction.currentTxn(); Account locked = _accountDao.acquireInLockTable(owner.getId()); if (locked == null) { @@ -844,7 +825,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (s_logger.isDebugEnabled()) { s_logger.debug("Found existing network configuration for offering " + offering + ": " + configs.get(0)); } - + if (errorIfAlreadySetup) { throw new InvalidParameterValueException("Found existing network configuration for offering " + offering + ": " + configs.get(0)); } else { @@ -857,7 +838,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (s_logger.isDebugEnabled()) { s_logger.debug("Found existing network configuration for offering " + offering + ": " + configs.get(0)); } - + if (errorIfAlreadySetup) { throw new InvalidParameterValueException("Found existing network configuration for offering " + offering + ": " + configs.get(0)); } else { @@ -890,9 +871,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag related = id; } - NetworkVO vo = new NetworkVO(id, config, offering.getId(), plan.getDataCenterId(), guru.getName(), owner.getDomainId(), owner.getId(), related, name, displayText, isShared, isDefault, predefined.isSecurityGroupEnabled()); + NetworkVO vo = new NetworkVO(id, config, offering.getId(), plan.getDataCenterId(), guru.getName(), owner.getDomainId(), owner.getId(), related, name, displayText, isShared, isDefault, + predefined.isSecurityGroupEnabled()); configs.add(_networksDao.persist(vo, vo.getGuestType() != null)); - + if (domainId != null) { _networksDao.addDomainToNetwork(id, domainId); } @@ -952,13 +934,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (profile == null) { continue; } - + if (requested != null && requested.getMode() == null) { profile.setMode(requested.getMode()); } else { profile.setMode(config.getMode()); } - + NicVO vo = new NicVO(guru.getName(), vm.getId(), config.getId(), vm.getType()); while (deviceIds[deviceId] && deviceId < deviceIds.length) { @@ -991,7 +973,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag Integer networkRate = _configMgr.getNetworkRate(no.getId(), vm.getType()); vm.addNic(new NicProfile(vo, network.first(), vo.getBroadcastUri(), vo.getIsolationUri(), networkRate)); } - + if (nics.size() != networks.size()) { s_logger.warn("Number of nics " + nics.size() + " doesn't match number of requested networks " + networks.size()); throw new CloudRuntimeException("Number of nics " + nics.size() + " doesn't match number of requested networks " + networks.size()); @@ -1051,7 +1033,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag vo.setIsolationUri(profile.getIsolationUri()); vo.setNetmask(profile.getNetmask()); } - + protected void applyProfileToNetwork(NetworkVO network, NetworkProfile profile) { network.setBroadcastUri(profile.getBroadcastUri()); network.setDns1(profile.getDns1()); @@ -1089,7 +1071,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override @DB - public Pair implementNetwork(long networkId, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { + public Pair implementNetwork(long networkId, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, + InsufficientCapacityException { Transaction.currentTxn(); Pair implemented = new Pair(null, null); @@ -1123,13 +1106,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag network.setGateway(result.getGateway()); network.setMode(result.getMode()); _networksDao.update(networkId, network); - - //If network if guest virtual and there is no source nat ip, associate a new one + + // If network if guest virtual and there is no source nat ip, associate a new one if (network.getGuestType() == GuestIpType.Virtual) { List ips = _ipAddressDao.listByAssociatedNetwork(networkId, true); - + if (ips.isEmpty()) { - s_logger.debug("Creating a source natp ip for " + network); + s_logger.debug("Creating a source nat ip for " + network); Account owner = _accountMgr.getAccount(network.getAccountId()); PublicIp sourceNatIp = assignSourceNatIpAddress(owner, network, context.getCaller().getId()); if (sourceNatIp == null) { @@ -1137,21 +1120,21 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } } - + for (NetworkElement element : _networkElements) { if (s_logger.isDebugEnabled()) { - s_logger.debug("Asking " + element.getName() + " to implmenet " + network); + s_logger.debug("Asking " + element.getName() + " to implemenet " + network); } element.implement(network, offering, dest, context); } - - //reapply all the firewall/staticNat/lb rules - s_logger.debug("Applying network rules as a part of network " + network + " implement..."); + + // reapply all the firewall/staticNat/lb rules + s_logger.debug("Applying network rules as a part of network " + network + " implement..."); if (!restartNetwork(networkId, false, context.getAccount())) { s_logger.warn("Failed to reapply network rules as a part of network " + network + " implement"); throw new ResourceUnavailableException("Unable to apply network rules as a part of network " + network + " implement", DataCenter.class, network.getDataCenterId()); - } - + } + network.setState(Network.State.Implemented); _networksDao.update(network.getId(), network); implemented.set(guru, network); @@ -1161,7 +1144,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.debug("Cleaning up because we're unable to implement the network " + network); network.setState(Network.State.Shutdown); _networksDao.update(networkId, network); - + shutdownNetwork(networkId, context); } _networksDao.releaseFromLockTable(networkId); @@ -1173,30 +1156,33 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag Transaction txn = Transaction.currentTxn(); txn.start(); _nicDao.update(nic.getId(), nic); - - if (nic.getVmType() == VirtualMachine.Type.User) { - s_logger.debug("Changing active number of nics for network id=" + networkId + " on " + count); - _networksDao.changeActiveNicsBy(networkId, count); - } + + if (nic.getVmType() == VirtualMachine.Type.User) { + s_logger.debug("Changing active number of nics for network id=" + networkId + " on " + count); + _networksDao.changeActiveNicsBy(networkId, count); + } txn.commit(); } @Override - public void prepare(VirtualMachineProfile vmProfile, DeployDestination dest, ReservationContext context) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException { + public void prepare(VirtualMachineProfile vmProfile, DeployDestination dest, ReservationContext context) throws InsufficientCapacityException, + 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 nics case) + + // we have to implement default nics first - to ensure that default network elements start up first in multiple nics + // case) // (need for setting DNS on Dhcp to domR's Ip4 address) Collections.sort(nics, new Comparator() { - - public int compare(NicVO nic1, NicVO nic2){ + + @Override + public int compare(NicVO nic1, NicVO nic2) { boolean isDefault1 = getNetwork(nic1.getNetworkId()).isDefault(); boolean isDefault2 = getNetwork(nic2.getNetworkId()).isDefault(); - + return (isDefault1 ^ isDefault2) ? ((isDefault1 ^ true) ? 1 : -1) : 0; } }); - + for (NicVO nic : nics) { Pair implemented = implementNetwork(nic.getNetworkId(), dest, context); NetworkGuru guru = implemented.first(); @@ -1289,12 +1275,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } } - + @Override public List getNics(long vmId) { return _nicDao.listByVmId(vmId); } - + @Override public List getNicsIncludingRemoved(VirtualMachine vm) { return _nicDao.listByVmIdIncludingRemoved(vm.getId()); @@ -1320,8 +1306,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return profiles; } - @Override @DB @ActionEvent (eventType=EventTypes.EVENT_NET_IP_RELEASE, eventDescription="disassociating Ip", async=true) - public boolean disassociateIpAddress(DisassociateIPAddrCmd cmd){ + @Override + @DB + @ActionEvent(eventType = EventTypes.EVENT_NET_IP_RELEASE, eventDescription = "disassociating Ip", async = true) + public boolean disassociateIpAddress(DisassociateIPAddrCmd cmd) { Long userId = UserContext.current().getCallerUserId(); Account caller = UserContext.current().getCaller(); @@ -1332,7 +1320,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (ipVO == null) { throw new InvalidParameterValueException("Unable to find ip address by id " + ipAddressId); } - + if (ipVO.getAllocatedTime() == null) { s_logger.debug("Ip Address id= " + ipAddressId + " is not allocated, so do nothing."); return true; @@ -1435,7 +1423,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } - @Override @DB @ActionEvent (eventType=EventTypes.EVENT_NETWORK_CREATE, eventDescription="creating network") + @Override + @DB + @ActionEvent(eventType = EventTypes.EVENT_NETWORK_CREATE, eventDescription = "creating network") public Network createNetwork(CreateNetworkCmd cmd) throws InsufficientCapacityException, ConcurrentOperationException { Long networkOfferingId = cmd.getNetworkOfferingId(); Long zoneId = cmd.getZoneId(); @@ -1452,16 +1442,16 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag Long userId = UserContext.current().getCallerUserId(); Account caller = UserContext.current().getCaller(); boolean isDomainSpecific = false; - + Transaction txn = Transaction.currentTxn(); - + // Check if network offering exists NetworkOfferingVO networkOffering = _networkOfferingDao.findById(networkOfferingId); if (networkOffering == null || networkOffering.isSystemOnly()) { throw new InvalidParameterValueException("Unable to find network offeirng by id " + networkOfferingId); } - - //Check if the network is domain specific + + // Check if the network is domain specific if (cmd.getDomainId() != null && cmd.getAccountName() == null) { if (networkOffering.getTrafficType() != TrafficType.Guest || networkOffering.getGuestType() != GuestIpType.Direct) { throw new InvalidParameterValueException("Domain level networks are supported just for traffic type " + TrafficType.Guest + " and guest Ip type " + GuestIpType.Direct); @@ -1476,41 +1466,41 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag isDomainSpecific = true; } } - + Account owner = null; if (cmd.getAccountName() != null && cmd.getDomainId() != null) { owner = _accountMgr.finalizeOwner(caller, cmd.getAccountName(), cmd.getDomainId()); } else { owner = caller; } - + UserContext.current().setAccountId(owner.getAccountId()); - + // if end ip is not specified, default it to startIp if (endIP == null && startIP != null) { endIP = startIP; } - + // Check if zone exists if (zoneId == null) { throw new InvalidParameterValueException("Please specify a valid zone."); } - DataCenterVO zone = _dcDao.findById(zoneId); + DataCenterVO zone = _dcDao.findById(zoneId); if (zone == null) { throw new InvalidParameterValueException("Please specify a valid zone."); } - - if(Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getType())){ - throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: "+ zoneId ); - } - //Check if network offering is Available + if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getType())) { + throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zoneId); + } + + // Check if network offering is Available if (networkOffering.getAvailability() == Availability.Unavailable) { throw new InvalidParameterValueException("Can't create network; network offering id=" + networkOfferingId + " is " + networkOffering.getAvailability()); } - //If one of the following parameters are defined (starIP/endIP/netmask/gateway), all the rest should be defined too + // If one of the following parameters are defined (starIP/endIP/netmask/gateway), all the rest should be defined too ArrayList networkConfigs = new ArrayList(); networkConfigs.add(gateway); networkConfigs.add(startIP); @@ -1518,54 +1508,55 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag networkConfigs.add(netmask); boolean defineNetworkConfig = false; short configElementsCount = 0; - + for (String networkConfig : networkConfigs) { if (networkConfig != null) { configElementsCount++; } } - + if (configElementsCount > 0 && configElementsCount != networkConfigs.size()) { throw new InvalidParameterValueException("startIP/endIP/netmask/gateway must be specified together"); } else if (configElementsCount == networkConfigs.size()) { defineNetworkConfig = true; } - + String cidr = null; if (gateway != null && netmask != null) { cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask); } - - //Regular user can create guest virtual network only + + // Regular user can create guest virtual network only if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL && (networkOffering.getTrafficType() != TrafficType.Guest || networkOffering.getGuestType() != GuestIpType.Virtual)) { - throw new InvalidParameterValueException("Regular user can create a network only from the network offering having traffic type " + TrafficType.Guest + " and Guest Ip type " + GuestIpType.Virtual); + throw new InvalidParameterValueException("Regular user can create a network only from the network offering having traffic type " + TrafficType.Guest + " and Guest Ip type " + + GuestIpType.Virtual); } - - //Don't allow to specify cidr if the caller is a regular user + + // Don't allow to specify cidr if the caller is a regular user if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL && (cidr != null || vlanId != null)) { throw new InvalidParameterValueException("Regular user is not allowed to specify gateway/netmask/ipRange/vlanId"); } - - //For non-root admins check cidr limit - if it's allowed by global config value + + // For non-root admins check cidr limit - if it's allowed by global config value if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN && cidr != null) { - + String[] cidrPair = cidr.split("\\/"); int cidrSize = Integer.valueOf(cidrPair[1]); - + if (cidrSize < _cidrLimit) { throw new InvalidParameterValueException("Cidr size can't be less than " + _cidrLimit); } } - + txn.start(); - + Long domainId = null; if (isDomainSpecific) { domainId = cmd.getDomainId(); } - + Network network = createNetwork(networkOfferingId, name, displayText, isShared, isDefault, zoneId, gateway, cidr, vlanId, networkDomain, owner, false, domainId); - + // Don't pass owner to create vlan when network offering is of type Direct - done to prevent accountVlanMap entry // creation when vlan is mapped to network if (network.getGuestType() == GuestIpType.Direct) { @@ -1576,28 +1567,29 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // Create vlan ip range _configMgr.createVlanAndPublicIpRange(userId, zoneId, null, startIP, endIP, gateway, netmask, false, vlanId, owner, network.getId()); } - + txn.commit(); - + return network; } - @Override @DB - public Network createNetwork(long networkOfferingId, String name, String displayText, Boolean isShared, Boolean isDefault, Long zoneId, String gateway, String cidr, String vlanId, String networkDomain, Account owner, boolean isSecurityGroupEnabled, Long domainId) - throws ConcurrentOperationException, InsufficientCapacityException { - + @Override + @DB + public Network createNetwork(long networkOfferingId, String name, String displayText, Boolean isShared, Boolean isDefault, Long zoneId, String gateway, String cidr, String vlanId, + String networkDomain, Account owner, boolean isSecurityGroupEnabled, Long domainId) throws ConcurrentOperationException, InsufficientCapacityException { + NetworkOfferingVO networkOffering = _networkOfferingDao.findById(networkOfferingId); DataCenterVO zone = _dcDao.findById(zoneId); - - //Only Direct Account specific networks can be created in Advanced Security Group enabled zone - if (zone.isSecurityGroupEnabled() && (networkOffering.getGuestType() == GuestIpType.Virtual || (isShared != null && isShared))) { + + // Only Direct Account specific networks can be created in Advanced Security Group enabled zone + if (zone.isSecurityGroupEnabled() && (networkOffering.getGuestType() == GuestIpType.Virtual || (isShared != null && isShared))) { throw new InvalidParameterValueException("Virtual Network and Direct Shared Network creation is not allowed if zone is security group enabled"); } - + if (zone.getNetworkType() == NetworkType.Basic) { throw new InvalidParameterValueException("Network creation is not allowed in zone with network type " + NetworkType.Basic); } - + // allow isDefault/isShared to be set only for Direct network if (networkOffering.getGuestType() == GuestIpType.Virtual) { if (isDefault != null && !isDefault) { @@ -1613,12 +1605,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag isDefault = false; } } - - //if network is shared, defult its owner to be system + + // if network is shared, defult its owner to be system if (isShared) { owner = _accountMgr.getSystemAccount(); } - + // Don't allow to create network with vlan that already exists in the system if (vlanId != null) { String uri = "vlan://" + vlanId; @@ -1627,33 +1619,36 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists in zone " + zoneId); } } - + // VlanId can be specified only when network offering supports it if (vlanId != null && !networkOffering.getSpecifyVlan()) { throw new InvalidParameterValueException("Can't specify vlan because network offering doesn't support it"); } - - //Don't allow to create guest virtual network with Vlan specified + + // Don't allow to create guest virtual network with Vlan specified if (networkOffering.getGuestType() == GuestIpType.Virtual && vlanId != null) { throw new InvalidParameterValueException("Can't specify vlan when create network with Guest IP Type " + GuestIpType.Virtual); } - + // If networkDomain is not specified, take it from the global configuration if (networkDomain == null) { - networkDomain = "cs"+Long.toHexString(owner.getId())+_networkDomain; + networkDomain = "cs" + Long.toHexString(owner.getId()) + _networkDomain; } else { - //validate network domain + // validate network domain 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 \"-\""); + 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 \"-\""); } } - - //Cidr for Direct network can't be NULL - 2.2.x limitation, remove after we introduce support for multiple ip ranges with different Cidrs for the same Shared network + + // Cidr for Direct network can't be NULL - 2.2.x limitation, remove after we introduce support for multiple ip ranges + // with different Cidrs for the same Shared network if (cidr == null && networkOffering.getTrafficType() == TrafficType.Guest && networkOffering.getGuestType() == GuestIpType.Direct) { throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required for Direct network creation"); } - - //Check if cidr is RFC1918 compliant if the network is Guest Virtual + + // Check if cidr is RFC1918 compliant if the network is Guest Virtual if (cidr != null && networkOffering.getGuestType() == GuestIpType.Virtual && networkOffering.getTrafficType() == TrafficType.Guest) { if (!NetUtils.validateGuestCidr(cidr)) { throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC1918 compliant"); @@ -1662,7 +1657,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag Transaction txn = Transaction.currentTxn(); txn.start(); - + DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null); NetworkVO userNetwork = new NetworkVO(); userNetwork.setNetworkDomain(networkDomain); @@ -1681,7 +1676,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } } - + List networks = setupNetwork(owner, networkOffering, userNetwork, plan, name, displayText, isShared, isDefault, true, domainId); Network network = null; @@ -1702,7 +1697,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } txn.commit(); - UserContext.current().setEventDetails("Network Id: "+ network.getId()); + UserContext.current().setEventDetails("Network Id: " + network.getId()); return network; } @@ -1749,7 +1744,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } else { accountId = account.getId(); } - + if (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) { DomainVO domain = _domainDao.findById(account.getDomainId()); if (domain != null) { @@ -1776,17 +1771,16 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag SearchBuilder zoneSearch = _dcDao.createSearchBuilder(); zoneSearch.and("networkType", zoneSearch.entity().getNetworkType(), SearchCriteria.Op.EQ); sb.join("zoneSearch", zoneSearch, sb.entity().getDataCenterId(), zoneSearch.entity().getId(), JoinBuilder.JoinType.INNER); - - + if (path != null) { - //for domain admin we should show only subdomains information + // for domain admin we should show only subdomains information SearchBuilder domainSearch = _domainDao.createSearchBuilder(); domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); } sb.and("removed", sb.entity().getRemoved(), Op.NULL); - + SearchCriteria sc = sb.create(); if (!isSystem) { @@ -1821,17 +1815,17 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag sc.addAnd("guestType", SearchCriteria.Op.EQ, type); } - if (!isSystem) { - if (accountName != null && domainId != null) { + if (!isSystem) { + if (accountName != null && domainId != null) { if (isShared == null) { sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); - //sc.addOr("isShared", SearchCriteria.Op.EQ, true); + // sc.addOr("isShared", SearchCriteria.Op.EQ, true); } else if (!isShared) { sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); } else { sc.addAnd("isShared", SearchCriteria.Op.EQ, true); } - + if (isShared == null || isShared) { List allNetworks = _networksDao.listNetworksBy(true); for (NetworkVO network : allNetworks) { @@ -1842,13 +1836,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } } - + } else if (isShared != null) { sc.addAnd("isShared", SearchCriteria.Op.EQ, isShared); - } + } } - - //find list of shared networks to avoid + + // find list of shared networks to avoid if (domainId != null && accountName == null) { List allNetworks = _networksDao.listNetworksBy(true); for (NetworkVO network : allNetworks) { @@ -1858,11 +1852,11 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } sc.addAnd("isShared", SearchCriteria.Op.EQ, true); } - + for (Long avoidNetwork : avoidNetworks) { sc.addAnd("id", SearchCriteria.Op.NOTIN, avoidNetwork); } - + for (Long allowerdSharedNetwork : allowedSharedNetworks) { sc.addOr("id", SearchCriteria.Op.IN, allowerdSharedNetwork); } @@ -1874,7 +1868,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (trafficType != null) { sc.addAnd("trafficType", SearchCriteria.Op.EQ, trafficType); } - + if (!isSystem && path != null && (isShared == null || !isShared)) { sc.setJoinParameters("domainSearch", "path", path + "%"); } @@ -1884,17 +1878,18 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return networks; } - @Override @ActionEvent (eventType=EventTypes.EVENT_NETWORK_DELETE, eventDescription="deleting network", async=true) - public boolean deleteNetwork(long networkId){ - - Account caller = UserContext.current().getCaller(); + @Override + @ActionEvent(eventType = EventTypes.EVENT_NETWORK_DELETE, eventDescription = "deleting network", async = true) + public boolean deleteNetwork(long networkId) { + + Account caller = UserContext.current().getCaller(); // Verify network id NetworkVO network = _networksDao.findById(networkId); if (network == null) { throw new InvalidParameterValueException("unable to find network " + networkId); } - + Account owner = _accountMgr.getAccount(network.getAccountId()); // Perform permission check @@ -1908,14 +1903,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag User callerUser = _accountMgr.getActiveUser(UserContext.current().getCallerUserId()); ReservationContext context = new ReservationContextImpl(null, null, callerUser, owner); - + return destroyNetwork(networkId, context); } @Override @DB public void shutdownNetwork(long networkId, ReservationContext context) { - + Transaction txn = Transaction.currentTxn(); txn.start(); NetworkVO network = _networksDao.lockRow(networkId, true); @@ -1927,7 +1922,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.debug("Network is not implemented: " + network); return; } - + network.setState(Network.State.Shutdown); _networksDao.update(network.getId(), network); txn.commit(); @@ -1938,7 +1933,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (s_logger.isDebugEnabled()) { s_logger.debug("Sending network shutdown to " + element.getName()); } - + element.shutdown(network, context); } catch (ResourceUnavailableException e) { s_logger.warn("Unable to complete shutdown of the network due to element: " + element.getName(), e); @@ -1960,13 +1955,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag NetworkGuru guru = _networkGurus.get(network.getGuruName()); NetworkProfile profile = convertNetworkToNetworkProfile(network.getId()); guru.shutdown(profile, _networkOfferingDao.findById(network.getNetworkOfferingId())); - + applyProfileToNetwork(network, profile); - + network.setState(Network.State.Allocated); _networksDao.update(network.getId(), network); _networksDao.clearCheckForGc(networkId); - + } else { network.setState(Network.State.Implemented); _networksDao.update(network.getId(), network); @@ -1974,26 +1969,27 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag txn.commit(); } - @Override @DB + @Override + @DB public boolean destroyNetwork(long networkId, ReservationContext context) { Account callerAccount = _accountMgr.getAccount(context.getCaller().getAccountId()); - + NetworkVO network = _networksDao.findById(networkId); if (network == null) { s_logger.debug("Unable to find network with id: " + networkId); return false; } - - //Don't allow to delete network via api call when it has vms assigned to it + + // Don't allow to delete network via api call when it has vms assigned to it int nicCount = getActiveNicsInNetwork(networkId); if (nicCount > 0) { s_logger.debug("Unable to remove the network id=" + networkId + " as it has active Nics."); return false; } - - //Make sure that there are no user vms in the network that are not Expunged/Error + + // Make sure that there are no user vms in the network that are not Expunged/Error List userVms = _vmDao.listByNetworkId(networkId); - + for (UserVmVO vm : userVms) { if (!(vm.getState() == VirtualMachine.State.Error || (vm.getState() == VirtualMachine.State.Expunging && vm.getRemoved() != null))) { s_logger.warn("Can't delete the network, not all user vms are expunged. Vm " + vm + " is in " + vm.getState() + " state"); @@ -2058,12 +2054,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return success; } - + private boolean cleanupNetworkResources(long networkId, Account caller, long callerUserId) { boolean success = true; Network network = getNetwork(networkId); - - //remove all PF/Static Nat rules for the network + + // remove all PF/Static Nat rules for the network try { if (_rulesMgr.revokeAllRulesForNetwork(networkId, callerUserId, caller)) { s_logger.debug("Successfully cleaned up portForwarding/staticNat rules for network id=" + networkId); @@ -2073,26 +2069,26 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } catch (ResourceUnavailableException ex) { success = false; - //shouldn't even come here as network is being cleaned up after all network elements are shutdown + // shouldn't even come here as network is being cleaned up after all network elements are shutdown s_logger.warn("Failed to release portForwarding/StaticNat rules as a part of network id=" + networkId + " cleanup due to resourceUnavailable ", ex); } - - //remove all LB rules for the network + + // remove all LB rules for the network if (_lbMgr.removeAllLoadBalanacersForNetwork(networkId, caller, callerUserId)) { s_logger.debug("Successfully cleaned up load balancing rules for network id=" + networkId); } else { - //shouldn't even come here as network is being cleaned up after all network elements are shutdown + // shouldn't even come here as network is being cleaned up after all network elements are shutdown success = false; s_logger.warn("Failed to cleanup LB rules as a part of network id=" + networkId + " cleanup"); } - - //release all ip addresses + + // release all ip addresses List ipsToRelease = _ipAddressDao.listByAssociatedNetwork(networkId, null); for (IPAddressVO ipToRelease : ipsToRelease) { IPAddressVO ip = markIpAsUnavailable(ipToRelease.getId()); assert (ip != null) : "Unable to mark the ip address id=" + ipToRelease.getId() + " as unavailable."; } - + try { if (!applyIpAssociations(network, true)) { s_logger.warn("Unable to apply ip address associations for " + network); @@ -2101,7 +2097,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } catch (ResourceUnavailableException e) { throw new CloudRuntimeException("We should never get to here because we used true when applyIpAssociations", e); } - + return success; } @@ -2172,19 +2168,19 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag _lastNetworkIdsToFree = stillFree; for (Long networkId : shutdownList) { - - //If network is removed, unset gc flag for it + + // If network is removed, unset gc flag for it if (getNetwork(networkId) == null) { s_logger.debug("Network id=" + networkId + " is removed, so clearing up corresponding gc check"); _networksDao.clearCheckForGc(networkId); } else { try { - + User caller = _accountMgr.getSystemUser(); Account owner = _accountMgr.getAccount(getNetwork(networkId).getAccountId()); - + ReservationContext context = new ReservationContextImpl(null, null, caller, owner); - + shutdownNetwork(networkId, context); } catch (Exception e) { s_logger.warn("Unable to shutdown network: " + networkId); @@ -2196,118 +2192,117 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } } - - - @Override @ActionEvent (eventType=EventTypes.EVENT_NETWORK_RESTART, eventDescription="restarting network", async=true) + @Override + @ActionEvent(eventType = EventTypes.EVENT_NETWORK_RESTART, eventDescription = "restarting network", async = true) public boolean restartNetwork(RestartNetworkCmd cmd) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { // This method restarts all network elements belonging to the network and re-applies all the rules Long networkId = cmd.getNetworkId(); - + User caller = _accountMgr.getActiveUser(UserContext.current().getCallerUserId()); Account callerAccount = _accountMgr.getActiveAccount(caller.getAccountId()); - - //Check if network exists + + // Check if network exists NetworkVO network = _networksDao.findById(networkId); if (network == null) { throw new InvalidParameterValueException("Network with id=" + networkId + " doesn't exist"); } - - //Don't allow to restart network if it's not in Implemented/Setup state + + // 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); } - + _accountMgr.checkAccess(callerAccount, network); - + boolean success = true; - //Restart network - network elements restart is required + // Restart network - network elements restart is required success = restartNetwork(networkId, true, callerAccount); - + if (success) { s_logger.debug("Network id=" + networkId + " is restarted successfully."); } else { s_logger.warn("Network id=" + networkId + " failed to restart."); } - + return success; } - + @Override - public boolean startNetwork(long networkId, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException{ - - //Check if network exists + public boolean startNetwork(long networkId, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { + + // Check if network exists NetworkVO network = _networksDao.findById(networkId); if (network == null) { throw new InvalidParameterValueException("Network with id=" + networkId + " doesn't exist"); } - - //implement the network + + // implement the network s_logger.debug("Starting network " + network + "..."); Pair implementedNetwork = implementNetwork(networkId, dest, context); if (implementedNetwork.first() == null) { s_logger.warn("Failed to start the network " + network); return false; } else { - return true; + return true; } } - + private boolean restartNetwork(long networkId, boolean restartElements, Account caller) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { boolean success = true; - + NetworkVO network = _networksDao.findById(networkId); - + s_logger.debug("Restarting network " + networkId + "..."); - + if (restartElements) { s_logger.debug("Restarting network elements for the network " + network); for (NetworkElement element : _networkElements) { - //stop and start the network element + // stop and start the network element if (!element.restart(network, null)) { s_logger.warn("Failed to restart network element(s) as a part of network id" + networkId + " restart"); success = false; - } + } } } - - //associate all ip addresses + + // associate all ip addresses if (!applyIpAssociations(network, false)) { s_logger.warn("Failed to apply ip addresses as a part of network id" + networkId + " restart"); success = false; } - - //apply port forwarding rules + + // apply port forwarding rules if (!_rulesMgr.applyPortForwardingRulesForNetwork(networkId, false, caller)) { s_logger.warn("Failed to reapply port forwarding rule(s) as a part of network id=" + networkId + " restart"); success = false; } - - //apply static nat rules + + // apply static nat rules if (!_rulesMgr.applyStaticNatRulesForNetwork(networkId, false, caller)) { s_logger.warn("Failed to reapply static nat rule(s) as a part of network id=" + networkId + " restart"); success = false; } - - //apply load balancer rules + + // apply load balancer rules if (!_lbMgr.applyLoadBalancersForNetwork(networkId)) { s_logger.warn("Failed to reapply load balancer rules as a part of network id=" + networkId + " restart"); success = false; } - - //apply vpn rules + + // apply vpn rules List vpnsToReapply = _vpnMgr.listRemoteAccessVpns(networkId); if (vpnsToReapply != null) { for (RemoteAccessVpn vpn : vpnsToReapply) { - //Start remote access vpn per ip + // Start remote access vpn per ip if (_vpnMgr.startRemoteAccessVpn(vpn.getServerAddressId()) == null) { s_logger.warn("Failed to reapply vpn rules as a part of network id=" + networkId + " restart"); success = false; } } } - + return success; } @@ -2365,27 +2360,26 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } return zoneCapabilities; } - - + @Override public Map> getNetworkCapabilities(long networkId) { Network network = getNetwork(networkId); if (network == null) { throw new InvalidParameterValueException("Unable to find network by id " + networkId); } - + Map> zoneCapabilities = getZoneCapabilities(network.getDataCenterId()); Map> networkCapabilities = new HashMap>(); - + for (Service service : zoneCapabilities.keySet()) { if (isServiceSupported(networkId, service)) { networkCapabilities.put(service, zoneCapabilities.get(service)); } } - + return networkCapabilities; } - + @Override public Map getServiceCapability(long zoneId, Service service) { Map> networkCapabilities = getZoneCapabilities(zoneId); @@ -2414,14 +2408,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } return networks.get(0); } - + @Override public NetworkVO getNetworkWithSecurityGroupEnabled(Long zoneId) { List networks = _networksDao.listByZoneSecurityGroup(zoneId); if (networks == null || networks.isEmpty()) { return null; } - + if (networks.size() > 1) { s_logger.debug("There are multiple network with security group enabled? select one of them..."); } @@ -2466,22 +2460,23 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public Nic getNicInNetwork(long vmId, long networkId) { return _nicDao.findByInstanceIdAndNetworkId(networkId, vmId); } - - + @Override public Nic getNicInNetworkIncludingRemoved(long vmId, long networkId) { return _nicDao.findByInstanceIdAndNetworkIdIncludingRemoved(networkId, vmId); } - @Override @DB - public boolean associateIpAddressListToAccount(long userId, long accountId, long zoneId, Long vlanId, Network network) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException { + @Override + @DB + public boolean associateIpAddressListToAccount(long userId, long accountId, long zoneId, Long vlanId, Network network) throws InsufficientCapacityException, ConcurrentOperationException, + ResourceUnavailableException { Account owner = _accountMgr.getActiveAccount(accountId); boolean createNetwork = false; - - Transaction txn= Transaction.currentTxn(); - + + Transaction txn = Transaction.currentTxn(); + txn.start(); - + if (network == null) { List networks = getVirtualNetworksOwnedByAccountInZone(owner.getAccountName(), owner.getDomainId(), zoneId); if (networks.size() == 0) { @@ -2490,7 +2485,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag network = networks.get(0); } } - + // create new Virtual network for the user if it doesn't exist if (createNetwork) { List offerings = _configMgr.listNetworkOfferings(TrafficType.Guest, false); @@ -2499,17 +2494,17 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (network == null) { s_logger.warn("Failed to create default Virtual network for the account " + accountId + "in zone " + zoneId); return false; - } + } } - - //Check if there is a source nat ip address for this account; if not - we have to allocate one + + // Check if there is a source nat ip address for this account; if not - we have to allocate one boolean allocateSourceNat = false; List sourceNat = _ipAddressDao.listByAssociatedNetwork(network.getId(), true); if (sourceNat.isEmpty()) { allocateSourceNat = true; } - - //update all ips with a network id, mark them as allocated and update resourceCount/usage + + // update all ips with a network id, mark them as allocated and update resourceCount/usage List ips = _ipAddressDao.listByVlanId(vlanId); boolean isSourceNatAllocated = false; for (IPAddressVO addr : ips) { @@ -2528,7 +2523,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag markPublicIpAsAllocated(addr); } } - + txn.commit(); return true; } @@ -2608,11 +2603,11 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public boolean zoneIsConfiguredForExternalNetworking(long zoneId) { DataCenterVO zone = _dcDao.findById(zoneId); - return (zone.getGatewayProvider() != null && zone.getGatewayProvider().equals(Network.Provider.JuniperSRX.getName()) && zone.getFirewallProvider().equals(Network.Provider.JuniperSRX.getName()) && zone.getLoadBalancerProvider().equals( - Network.Provider.F5BigIp.getName())); + return (zone.getGatewayProvider() != null && zone.getGatewayProvider().equals(Network.Provider.JuniperSRX.getName()) + && zone.getFirewallProvider().equals(Network.Provider.JuniperSRX.getName()) && zone.getLoadBalancerProvider().equals(Network.Provider.F5BigIp.getName())); } - + @Override public boolean isServiceSupported(long networkId, Network.Service service) { Network network = getNetwork(networkId); @@ -2632,13 +2627,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } else if (service == Service.Gateway) { return offering.isGatewayService(); } - + return false; } - + private boolean cleanupIpResources(long ipId, long userId, Account caller) { boolean success = true; - + try { s_logger.debug("Revoking all PF/StaticNat rules as a part of public IP id=" + ipId + " release..."); if (!_rulesMgr.revokeAllRulesForIp(ipId, userId, caller)) { @@ -2655,9 +2650,11 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.warn("Unable to revoke all the load balancer rules for ip id=" + ipId + " as a part of ip release"); success = false; } - - //remote access vpn can be enabled only for static nat ip, so this part should never be executed under normal conditions - //only when ip address failed to be cleaned up as a part of account destroy and was marked as Releasing, this part of the code would be triggered + + // remote access vpn can be enabled only for static nat ip, so this part should never be executed under normal + // conditions + // only when ip address failed to be cleaned up as a part of account destroy and was marked as Releasing, this part of + // the code would be triggered s_logger.debug("Cleaning up remote access vpns as a part of public IP id=" + ipId + " release..."); try { _vpnMgr.destroyRemoteAccessVpn(ipId); @@ -2665,24 +2662,24 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.warn("Unable to destroy remote access vpn for ip id=" + ipId + " as a part of ip release", e); success = false; } - + return success; } - + @Override public String getIpOfNetworkElementInVirtualNetwork(long accountId, long dataCenterId) { - - List virtualNetworks = _networksDao.listBy(accountId, dataCenterId , GuestIpType.Virtual); - + + List virtualNetworks = _networksDao.listBy(accountId, dataCenterId, GuestIpType.Virtual); + if (virtualNetworks.isEmpty()) { s_logger.trace("Unable to find default Virtual network account id=" + accountId); return null; } - + NetworkVO virtualNetwork = virtualNetworks.get(0); - + NicVO networkElementNic = _nicDao.findByNetworkIdAndType(virtualNetwork.getId(), Type.DomainRouter); - + if (networkElementNic != null) { return networkElementNic.getIp4Address(); } else { @@ -2690,51 +2687,51 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return null; } } - + @Override public List listNetworksForAccount(long accountId, long zoneId, GuestIpType guestType, Boolean isDefault) { List accountNetworks = new ArrayList(); List zoneNetworks = _networksDao.listByZone(zoneId); - + for (NetworkVO network : zoneNetworks) { NetworkOfferingVO no = _networkOfferingDao.findById(network.getNetworkOfferingId()); if (!no.isSystemOnly()) { if (network.getIsShared() || !_networksDao.listBy(accountId, network.getId()).isEmpty()) { if ((guestType == null || guestType == network.getGuestType()) && (isDefault == null || isDefault == network.isDefault)) { - accountNetworks.add(network); - } + accountNetworks.add(network); + } } } } return accountNetworks; } - + @DB private IPAddressVO markIpAsUnavailable(long addrId) { Transaction txn = Transaction.currentTxn(); - + IPAddressVO ip = _ipAddressDao.findById(addrId); - + if (ip.getState() != State.Releasing) { txn.start(); - + ip = _ipAddressDao.markAsUnavailable(addrId); - + _accountMgr.decrementResourceCount(_ipAddressDao.findById(addrId).getAccountId(), ResourceType.public_ip); - + long isSourceNat = (ip.isSourceNat()) ? 1 : 0; - + if (ip.getAccountId() != Account.ACCOUNT_ID_SYSTEM) { UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NET_IP_RELEASE, ip.getAccountId(), ip.getDataCenterId(), addrId, ip.getAddress().addr(), isSourceNat); _usageEventDao.persist(usageEvent); } - + txn.commit(); } - + return ip; } - + @Override public boolean isNetworkAvailableInDomain(long networkId, long domainId) { boolean result = false; @@ -2744,8 +2741,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.trace("Network id=" + networkId + " is not shared"); return false; } - - + List networkDomainMap = _networkDomainDao.listDomainNetworkMapByNetworkId(networkId); if (networkDomainMap.isEmpty()) { s_logger.trace("Network id=" + networkId + " is shared, but not domain specific"); @@ -2753,11 +2749,11 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } else { networkDomainId = networkDomainMap.get(0).getDomainId(); } - + if (domainId == networkDomainId.longValue()) { return true; } - + Domain domain = _domainDao.findById(domainId); while (domain.getParent() != null) { if (domain.getParent().longValue() == networkDomainId) { @@ -2765,10 +2761,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } domain = _domainDao.findById(domain.getParent()); } - + return result; } - + @Override public Long getDedicatedNetworkDomain(long networkId) { List networkMaps = _networkDomainDao.listDomainNetworkMapByNetworkId(networkId); @@ -2778,35 +2774,36 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return null; } } - - @Override @ActionEvent (eventType=EventTypes.EVENT_NETWORK_UPDATE, eventDescription="updating network", async=false) + + @Override + @ActionEvent(eventType = EventTypes.EVENT_NETWORK_UPDATE, eventDescription = "updating network", async = false) public Network updateNetwork(long networkId, String name, String displayText, Account caller) { - - //verify input parameters + + // verify input parameters NetworkVO network = _networksDao.findById(networkId); if (network == null) { throw new InvalidParameterValueException("Network id=" + networkId + "doesn't exist in the system"); } - - //Don't allow to update system network + + // Don't allow to update system network NetworkOffering offering = _networkOfferingDao.findByIdIncludingRemoved(network.getNetworkOfferingId()); if (offering.isSystemOnly()) { throw new InvalidParameterValueException("Can't update system networks"); } - + _accountMgr.checkAccess(caller, network); - + if (name != null) { network.setName(name); } - + if (displayText != null) { network.setDisplayText(displayText); } - + _networksDao.update(networkId, network); - + return network; - + } } diff --git a/server/src/com/cloud/upgrade/dao/Upgrade218to22.java b/server/src/com/cloud/upgrade/dao/Upgrade218to22.java index aba3a1a79da..bc3a4aff6c4 100644 --- a/server/src/com/cloud/upgrade/dao/Upgrade218to22.java +++ b/server/src/com/cloud/upgrade/dao/Upgrade218to22.java @@ -1000,18 +1000,16 @@ public class Upgrade218to22 implements DbUpgrade { } pstmt.close(); } - - // Update hypervisor type for user vm to be consistent with original 2.2.4 - pstmt = conn.prepareStatement("UPDATE vm_instance SET hypervisor_type='XenServer' WHERE hypervisor_type='xenserver'"); - pstmt.executeUpdate(); - pstmt.close(); - - // Set account=systemAccount and domain=ROOT for CPVM/SSVM - pstmt = conn.prepareStatement("UPDATE vm_instance SET account_id=1, domain_id=1 WHERE type='ConsoleProxy' or type='SecondaryStorageVm'"); - pstmt.executeUpdate(); - pstmt.close(); - } + // Update hypervisor type for user vm to be consistent with original 2.2.4 + pstmt = conn.prepareStatement("UPDATE vm_instance SET hypervisor_type='XenServer' WHERE hypervisor_type='xenserver'"); + pstmt.executeUpdate(); + pstmt.close(); + + // Set account=systemAccount and domain=ROOT for CPVM/SSVM + pstmt = conn.prepareStatement("UPDATE vm_instance SET account_id=1, domain_id=1 WHERE type='ConsoleProxy' or type='SecondaryStorageVm'"); + pstmt.executeUpdate(); + pstmt.close(); } catch (SQLException e) { throw new CloudRuntimeException("Can't update data center ", e); } diff --git a/setup/db/create-schema.sql b/setup/db/create-schema.sql index 566bb97f802..980d6ad0f11 100755 --- a/setup/db/create-schema.sql +++ b/setup/db/create-schema.sql @@ -389,8 +389,6 @@ CREATE TABLE `cloud`.`volumes` ( `updated` datetime COMMENT 'Date updated for attach/detach', `removed` datetime COMMENT 'Date removed. not null if removed', `state` varchar(32) COMMENT 'State machine', - `source_id` bigint unsigned COMMENT 'id for the source', - `source_type` varchar(32) COMMENT 'source from which the volume is created -- snapshot, diskoffering, template, blank', `chain_info` text COMMENT 'save possible disk chain info in primary storage', PRIMARY KEY (`id`), INDEX `i_volumes__removed`(`removed`), diff --git a/setup/db/db/schema-21to22-cleanup.sql b/setup/db/db/schema-21to22-cleanup.sql index 512526d6bde..b10ec054981 100644 --- a/setup/db/db/schema-21to22-cleanup.sql +++ b/setup/db/db/schema-21to22-cleanup.sql @@ -114,3 +114,6 @@ ALTER TABLE `cloud`.`user_ip_address` ADD UNIQUE (`public_ip_address`, `source_n ALTER TABLE `cloud`.`user_ip_address` ADD CONSTRAINT `fk_user_ip_address__source_network_id` FOREIGN KEY (`source_network_id`) REFERENCES `networks`(`id`); ALTER TABLE `cloud`.`user_ip_address` ADD CONSTRAINT `fk_user_ip_address__network_id` FOREIGN KEY (`network_id`) REFERENCES `networks`(`id`); +ALTER TABLE `cloud`.`vm_instance` ADD CONSTRAINT `fk_vm_instance__account_id` FOREIGN KEY `fk_vm_instance__account_id` (`account_id`) REFERENCES `account` (`id`); +ALTER TABLE `cloud`.`vm_instance` ADD CONSTRAINT `fk_vm_instance__service_offering_id` FOREIGN KEY `fk_vm_instance__service_offering_id` (`service_offering_id`) REFERENCES `service_offering` (`id`); + diff --git a/setup/db/db/schema-21to22.sql b/setup/db/db/schema-21to22.sql index c6acdcac798..bb09f82f2e5 100755 --- a/setup/db/db/schema-21to22.sql +++ b/setup/db/db/schema-21to22.sql @@ -976,3 +976,6 @@ UPDATE vm_template SET hypervisor_type='XenServer' WHERE hypervisor_type IS NULL UPDATE vm_template SET hypervisor_type='KVM' WHERE hypervisor_type IS NULL AND format='QCOW2'; UPDATE vm_template SET hypervisor_type='VmWare' WHERE hypervisor_type IS NULL AND format='OVA'; UPDATE vm_template SET hypervisor_type='None' WHERE hypervisor_type IS NULL AND format='ISO'; + +ALTER TABLE `cloud`.`volumes` ADD COLUMN `source_id` bigint unsigned COMMENT 'id for the source'; +ALTER TABLE `cloud`.`volumes` ADD COLUMN `source_type` varchar(32) COMMENT 'source from which the volume is created -- snapshot, diskoffering, template, blank'; diff --git a/setup/db/db/schema-222to224-cleanup.sql b/setup/db/db/schema-222to224-cleanup.sql index 9f0db667038..67f58184d7c 100644 --- a/setup/db/db/schema-222to224-cleanup.sql +++ b/setup/db/db/schema-222to224-cleanup.sql @@ -7,6 +7,8 @@ DELETE FROM `cloud`.`configuration` WHERE name in ('direct.attach.security.group ALTER TABLE `cloud`.`volumes` DROP COLUMN `status`; ALTER TABLE `cloud`.`volumes` DROP COLUMN `resource_type`; +ALTER TABLE `cloud`.`volumes` DROP COLUMN `source_id`; +ALTER TABLE `cloud`.`volumes` DROP COLUMN `source_type`; ALTER TABLE `cloud`.`user_vm` DROP COLUMN guest_ip_address; ALTER TABLE `cloud`.`user_vm` DROP COLUMN guest_mac_address; diff --git a/setup/db/db/schema-222to224.sql b/setup/db/db/schema-222to224.sql index c6489b7e189..7dc1b1b697f 100644 --- a/setup/db/db/schema-222to224.sql +++ b/setup/db/db/schema-222to224.sql @@ -130,6 +130,3 @@ DELETE FROM `sequence` WHERE name='snapshots_seq'; UPDATE `cloud`.`service_offering` s, `cloud`.`disk_offering` d SET s.ha_enabled=1 where s.id=d.id and d.system_use=1; -ALTER TABLE `cloud`.`vm_instance` ADD CONSTRAINT `fk_vm_instance__account_id` FOREIGN KEY `fk_vm_instance__account_id` (`account_id`) REFERENCES `account` (`id`); -ALTER TABLE `cloud`.`vm_instance` ADD CONSTRAINT `fk_vm_instance__service_offering_id` FOREIGN KEY `fk_vm_instance__service_offering_id` (`service_offering_id`) REFERENCES `service_offering` (`id`); -