diff --git a/api/src/com/cloud/api/commands/ListLoadBalancerRulesCmd.java b/api/src/com/cloud/api/commands/ListLoadBalancerRulesCmd.java index 5228bab1df1..9bded66ae8b 100644 --- a/api/src/com/cloud/api/commands/ListLoadBalancerRulesCmd.java +++ b/api/src/com/cloud/api/commands/ListLoadBalancerRulesCmd.java @@ -16,8 +16,8 @@ * */ -package com.cloud.api.commands; - +package com.cloud.api.commands; + import java.util.ArrayList; import java.util.List; @@ -31,37 +31,40 @@ import com.cloud.api.response.ListResponse; import com.cloud.api.response.LoadBalancerResponse; import com.cloud.network.rules.LoadBalancer; -@Implementation(description="Lists load balancer rules.", responseObject=LoadBalancerResponse.class) -public class ListLoadBalancerRulesCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger (ListLoadBalancerRulesCmd.class.getName()); - - private static final String s_name = "listloadbalancerrulesresponse"; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// +@Implementation(description = "Lists load balancer rules.", responseObject = LoadBalancerResponse.class) +public class ListLoadBalancerRulesCmd extends BaseListCmd { + public static final Logger s_logger = Logger.getLogger(ListLoadBalancerRulesCmd.class.getName()); - @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="the account of the load balancer rule. Must be used with the domainId parameter.") + private static final String s_name = "listloadbalancerrulesresponse"; + + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "the account of the load balancer rule. Must be used with the domainId parameter.") private String accountName; - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the domain ID of the load balancer rule. If used with the account parameter, lists load balancer rules for the account in the specified domain.") + @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.LONG, description = "the domain ID of the load balancer rule. If used with the account parameter, lists load balancer rules for the account in the specified domain.") private Long domainId; - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the ID of the load balancer rule") + @Parameter(name = ApiConstants.ID, type = CommandType.LONG, description = "the ID of the load balancer rule") private Long id; - @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the name of the load balancer rule") + @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "the name of the load balancer rule") private String loadBalancerRuleName; - @Parameter(name=ApiConstants.PUBLIC_IP_ID, type=CommandType.LONG, description="the public IP address id of the load balancer rule ") + @Parameter(name = ApiConstants.PUBLIC_IP_ID, type = CommandType.LONG, description = "the public IP address id of the load balancer rule ") private Long publicIpId; - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, description="the ID of the virtual machine of the load balancer rule") + @Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID, type = CommandType.LONG, description = "the ID of the virtual machine of the load balancer rule") private Long virtualMachineId; - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// + @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.LONG, description = "the availability zone ID") + private Long zoneId; + + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// public String getAccountName() { return accountName; @@ -87,17 +90,21 @@ public class ListLoadBalancerRulesCmd extends BaseListCmd { return virtualMachineId; } - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// + public Long getZoneId() { + return zoneId; + } + + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// @Override - public String getCommandName() { - return s_name; + public String getCommandName() { + return s_name; } @Override - public void execute(){ + public void execute() { List loadBalancers = _lbService.searchForLoadBalancers(this); ListResponse response = new ListResponse(); List lbResponses = new ArrayList(); @@ -111,5 +118,5 @@ public class ListLoadBalancerRulesCmd extends BaseListCmd { response.setResponses(lbResponses); response.setResponseName(getCommandName()); this.setResponseObject(response); - } -} + } +} diff --git a/api/src/com/cloud/api/response/LoadBalancerResponse.java b/api/src/com/cloud/api/response/LoadBalancerResponse.java index 738697f3c1d..dba80678786 100644 --- a/api/src/com/cloud/api/response/LoadBalancerResponse.java +++ b/api/src/com/cloud/api/response/LoadBalancerResponse.java @@ -22,42 +22,58 @@ import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; public class LoadBalancerResponse extends BaseResponse { - @SerializedName("id") @Param(description="the load balancer rule ID") + @SerializedName("id") + @Param(description = "the load balancer rule ID") private Long id; - @SerializedName("name") @Param(description="the name of the load balancer") + @SerializedName("name") + @Param(description = "the name of the load balancer") private String name; - @SerializedName("description") @Param(description="the description of the load balancer") + @SerializedName("description") + @Param(description = "the description of the load balancer") private String description; - - @SerializedName(ApiConstants.PUBLIC_IP_ID) @Param(description="the public ip address id") + + @SerializedName(ApiConstants.PUBLIC_IP_ID) + @Param(description = "the public ip address id") private Long publicIpId; - @SerializedName(ApiConstants.PUBLIC_IP) @Param(description="the public ip address") + @SerializedName(ApiConstants.PUBLIC_IP) + @Param(description = "the public ip address") private String publicIp; - @SerializedName("publicport") @Param(description="the public port") + @SerializedName("publicport") + @Param(description = "the public port") private String publicPort; - @SerializedName("privateport") @Param(description="the private port") + @SerializedName("privateport") + @Param(description = "the private port") private String privatePort; - @SerializedName("algorithm") @Param(description="the load balancer algorithm (source, roundrobin, leastconn)") + @SerializedName("algorithm") + @Param(description = "the load balancer algorithm (source, roundrobin, leastconn)") private String algorithm; - @SerializedName("account") @Param(description="the account of the load balancer rule") + @SerializedName("account") + @Param(description = "the account of the load balancer rule") private String accountName; - @SerializedName("domainid") @Param(description="the domain ID of the load balancer rule") + @SerializedName("domainid") + @Param(description = "the domain ID of the load balancer rule") private Long domainId; - @SerializedName("domain") @Param(description="the domain of the load balancer rule") + @SerializedName("domain") + @Param(description = "the domain of the load balancer rule") private String domainName; - - @SerializedName("state") @Param(description="the state of the rule") + + @SerializedName("state") + @Param(description = "the state of the rule") private String state; + @SerializedName(ApiConstants.ZONE_ID) + @Param(description = "the id of the zone the rule belongs to") + private Long zoneId; + public Long getId() { return id; } @@ -153,5 +169,12 @@ public class LoadBalancerResponse extends BaseResponse { public void setPublicIpId(Long publicIpId) { this.publicIpId = publicIpId; } - + + public Long getZoneId() { + return zoneId; + } + + public void setZoneId(Long zoneId) { + this.zoneId = zoneId; + } } diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index aaa6b6a9734..7ea788cbd29 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -97,6 +97,7 @@ import com.cloud.exception.InvalidParameterValueException; import com.cloud.host.Host; import com.cloud.host.HostStats; import com.cloud.host.HostVO; +import com.cloud.network.IPAddressVO; import com.cloud.network.IpAddress; import com.cloud.network.Network; import com.cloud.network.Network.Capability; @@ -207,13 +208,13 @@ public class ApiResponseHelper implements ResponseGenerator { return userResponse; } - //this method is used for response generation via createAccount (which creates an account + user) + + // this method is used for response generation via createAccount (which creates an account + user) @Override public AccountResponse createUserAccountResponse(UserAccount user) { - return createAccountResponse(ApiDBUtils.findAccountById(user.getAccountId())); + return createAccountResponse(ApiDBUtils.findAccountById(user.getAccountId())); } - @Override public AccountResponse createAccountResponse(Account account) { boolean accountIsAdmin = (account.getType() == Account.ACCOUNT_TYPE_ADMIN); @@ -311,10 +312,10 @@ public class ApiResponseHelper implements ResponseGenerator { accountResponse.setVmRunning(vmRunning); accountResponse.setObjectName("account"); - //adding all the users for an account as part of the response obj + // adding all the users for an account as part of the response obj List usersForAccount = ApiDBUtils.listUsersByAccount(account.getAccountId()); List userResponseList = new ArrayList(); - for(UserVO user : usersForAccount) { + for (UserVO user : usersForAccount) { UserResponse userResponse = new UserResponse(); userResponse.setAccountName(account.getAccountName()); userResponse.setAccountType(account.getType()); @@ -330,10 +331,10 @@ public class ApiResponseHelper implements ResponseGenerator { userResponse.setState(user.getState().toString()); userResponse.setTimezone(user.getTimezone()); userResponse.setUsername(user.getUsername()); - + userResponseList.add(userResponse); } - + accountResponse.setUsers(userResponseList); return accountResponse; } @@ -362,7 +363,7 @@ public class ApiResponseHelper implements ResponseGenerator { diskOfferingResponse.setName(offering.getName()); diskOfferingResponse.setDisplayText(offering.getDisplayText()); diskOfferingResponse.setCreated(offering.getCreated()); - diskOfferingResponse.setDiskSize(offering.getDiskSize()/1024); + diskOfferingResponse.setDiskSize(offering.getDiskSize() / 1024); if (offering.getDomainId() != null) { diskOfferingResponse.setDomain(ApiDBUtils.findDomainById(offering.getDomainId()).getName()); diskOfferingResponse.setDomainId(offering.getDomainId()); @@ -409,8 +410,8 @@ public class ApiResponseHelper implements ResponseGenerator { offeringResponse.setStorageType(offering.getUseLocalStorage() ? "local" : "shared"); offeringResponse.setOfferHa(offering.getOfferHA()); offeringResponse.setTags(offering.getTags()); - if(offering.getDomainId() != null){ - offeringResponse.setDomain(ApiDBUtils.findDomainById(offering.getDomainId()).getName()); + if (offering.getDomainId() != null) { + offeringResponse.setDomain(ApiDBUtils.findDomainById(offering.getDomainId()).getName()); offeringResponse.setDomainId(offering.getDomainId()); } offeringResponse.setHostTag(offering.getHostTag()); @@ -447,7 +448,7 @@ public class ApiResponseHelper implements ResponseGenerator { String snapshotTypeStr = snapshot.getType().name(); snapshotResponse.setSnapshotType(snapshotTypeStr); snapshotResponse.setVolumeId(snapshot.getVolumeId()); - if( volume != null ) { + if (volume != null) { snapshotResponse.setVolumeName(volume.getName()); snapshotResponse.setVolumeType(volume.getVolumeType().name()); } @@ -565,9 +566,9 @@ public class ApiResponseHelper implements ResponseGenerator { } hostResponse.setEvents(events); } - + hostResponse.setAllocationState(host.getHostAllocationState().toString()); - + hostResponse.setObjectName("host"); return hostResponse; @@ -592,12 +593,12 @@ public class ApiResponseHelper implements ResponseGenerator { vlanResponse.setGateway(vlan.getVlanGateway()); vlanResponse.setNetmask(vlan.getVlanNetmask()); - //get start ip and end ip of corresponding vlan + // get start ip and end ip of corresponding vlan String ipRange = vlan.getIpRange(); - String[] range = ipRange.split("-"); + String[] range = ipRange.split("-"); vlanResponse.setStartIp(range[0]); vlanResponse.setEndIp(range[1]); - + vlanResponse.setNetworkId(vlan.getNetworkId()); Account owner = ApiDBUtils.getVlanAccount(vlan.getId()); if (owner != null) { @@ -605,7 +606,7 @@ public class ApiResponseHelper implements ResponseGenerator { vlanResponse.setDomainId(owner.getDomainId()); vlanResponse.setDomainName(ApiDBUtils.findDomainById(owner.getDomainId()).getName()); } - + vlanResponse.setObjectName("vlan"); return vlanResponse; } @@ -636,36 +637,36 @@ public class ApiResponseHelper implements ResponseGenerator { ipResponse.setForVirtualNetwork(forVirtualNetworks); ipResponse.setStaticNat(ipAddress.isOneToOneNat()); - + if (ipAddress.getAssociatedWithVmId() != null) { UserVm vm = ApiDBUtils.findUserVmById(ipAddress.getAssociatedWithVmId()); ipResponse.setVirtualMachineId(vm.getId()); ipResponse.setVirtualMachineName(vm.getName()); ipResponse.setVirtualMachineDisplayName(vm.getDisplayName()); } - + ipResponse.setAssociatedNetworkId(ipAddress.getAssociatedWithNetworkId()); - - //Network id the ip is associated withif associated networkId is null, try to get this information from vlan - Long associatedNetworkId = ipAddress.getAssociatedWithNetworkId(); + + // Network id the ip is associated withif associated networkId is null, try to get this information from vlan + Long associatedNetworkId = ipAddress.getAssociatedWithNetworkId(); Long vlanNetworkId = ApiDBUtils.getVlanNetworkId(ipAddress.getVlanId()); if (associatedNetworkId == null) { associatedNetworkId = vlanNetworkId; } - + ipResponse.setAssociatedNetworkId(associatedNetworkId); - - //Network id the ip belongs to + + // Network id the ip belongs to Long networkId; if (vlanNetworkId != null) { networkId = vlanNetworkId; } else { networkId = ApiDBUtils.getPublicNetworkIdByZone(zoneId); } - + ipResponse.setNetworkId(networkId); ipResponse.setState(ipAddress.getState().toString()); - + // show this info to admin only Account account = UserContext.current().getCaller(); if ((account == null) || account.getType() == Account.ACCOUNT_TYPE_ADMIN) { @@ -682,8 +683,11 @@ public class ApiResponseHelper implements ResponseGenerator { lbResponse.setId(loadBalancer.getId()); lbResponse.setName(loadBalancer.getName()); lbResponse.setDescription(loadBalancer.getDescription()); - lbResponse.setPublicIpId(loadBalancer.getSourceIpAddressId()); - lbResponse.setPublicIp(ApiDBUtils.findIpAddressById(loadBalancer.getSourceIpAddressId()).getAddress().addr()); + + IPAddressVO publicIp = ApiDBUtils.findIpAddressById(loadBalancer.getSourceIpAddressId()); + + lbResponse.setPublicIpId(publicIp.getId()); + lbResponse.setPublicIp(publicIp.getAddress().addr()); lbResponse.setPublicPort(Integer.toString(loadBalancer.getSourcePortStart())); lbResponse.setPrivatePort(Integer.toString(loadBalancer.getDefaultPortStart())); lbResponse.setAlgorithm(loadBalancer.getAlgorithm()); @@ -700,6 +704,9 @@ public class ApiResponseHelper implements ResponseGenerator { lbResponse.setDomainId(accountTemp.getDomainId()); lbResponse.setDomainName(ApiDBUtils.findDomainById(accountTemp.getDomainId()).getName()); } + + lbResponse.setZoneId(publicIp.getDataCenterId()); + lbResponse.setObjectName("loadbalancer"); return lbResponse; } @@ -780,7 +787,7 @@ public class ApiResponseHelper implements ResponseGenerator { volResponse.setVirtualMachineName(vm.getName()); UserVm userVm = ApiDBUtils.findUserVmById(vm.getId()); volResponse.setVirtualMachineDisplayName(userVm.getDisplayName()); - + volResponse.setVirtualMachineState(vm.getState().toString()); } @@ -833,15 +840,15 @@ public class ApiResponseHelper implements ResponseGenerator { Long poolId = volume.getPoolId(); String poolName = (poolId == null) ? "none" : ApiDBUtils.findStoragePoolById(poolId).getName(); volResponse.setStoragePoolName(poolName); -// volResponse.setSourceId(volume.getSourceId()); -// if (volume.getSourceType() != null) { -// volResponse.setSourceType(volume.getSourceType().toString()); -// } + // volResponse.setSourceId(volume.getSourceId()); + // if (volume.getSourceType() != null) { + // volResponse.setSourceType(volume.getSourceType().toString()); + // } volResponse.setHypervisor(ApiDBUtils.getVolumeHyperType(volume.getId()).toString()); volResponse.setAttached(volume.getAttached()); volResponse.setDestroyed(volume.getState() == Volume.State.Destroy); - VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId()); - boolean isExtractable = template != null&& template.isExtractable()&& !(template.getTemplateType()== TemplateType.SYSTEM); + VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId()); + boolean isExtractable = template != null && template.isExtractable() && !(template.getTemplateType() == TemplateType.SYSTEM); volResponse.setExtractable(isExtractable); volResponse.setObjectName("volume"); return volResponse; @@ -933,17 +940,17 @@ public class ApiResponseHelper implements ResponseGenerator { response.setPrivatePort(Integer.toString(fwRule.getDestinationPortStart())); response.setProtocol(fwRule.getProtocol()); response.setPublicPort(Integer.toString(fwRule.getSourcePortStart())); - + IpAddress ip = ApiDBUtils.findIpAddressById(fwRule.getSourceIpAddressId()); response.setPublicIpAddressId(ip.getId()); response.setPublicIpAddress(ip.getAddress().addr()); - + if (ip != null && fwRule.getDestinationIpAddress() != null) { UserVm vm = ApiDBUtils.findUserVmById(fwRule.getVirtualMachineId()); - if(vm != null){ - response.setVirtualMachineId(vm.getId()); - response.setVirtualMachineName(vm.getName()); - response.setVirtualMachineDisplayName(vm.getDisplayName()); + if (vm != null) { + response.setVirtualMachineId(vm.getId()); + response.setVirtualMachineName(vm.getName()); + response.setVirtualMachineDisplayName(vm.getDisplayName()); } } FirewallRule.State state = fwRule.getState(); @@ -961,17 +968,17 @@ public class ApiResponseHelper implements ResponseGenerator { IpForwardingRuleResponse response = new IpForwardingRuleResponse(); response.setId(fwRule.getId()); response.setProtocol(fwRule.getProtocol()); - + IpAddress ip = ApiDBUtils.findIpAddressById(fwRule.getSourceIpAddressId()); response.setPublicIpAddressId(ip.getId()); response.setPublicIpAddress(ip.getAddress().addr()); - + if (ip != null && fwRule.getDestIpAddress() != null) { UserVm vm = ApiDBUtils.findUserVmById(ip.getAssociatedWithVmId()); - if(vm != null){//vm might be destroyed - response.setVirtualMachineId(vm.getId()); - response.setVirtualMachineName(vm.getName()); - response.setVirtualMachineDisplayName(vm.getDisplayName()); + if (vm != null) {// vm might be destroyed + response.setVirtualMachineId(vm.getId()); + response.setVirtualMachineName(vm.getName()); + response.setVirtualMachineDisplayName(vm.getDisplayName()); } } FirewallRule.State state = fwRule.getState(); @@ -979,7 +986,7 @@ public class ApiResponseHelper implements ResponseGenerator { if (state.equals(FirewallRule.State.Revoke)) { stateToSet = "Deleting"; } - + response.setStartPort(fwRule.getSourcePortStart()); response.setEndPort(fwRule.getSourcePortEnd()); response.setProtocol(fwRule.getProtocol()); @@ -989,16 +996,16 @@ public class ApiResponseHelper implements ResponseGenerator { } @Override - public List createUserVmResponse(String objectName, UserVm...userVms) { + public List createUserVmResponse(String objectName, UserVm... userVms) { Account caller = UserContext.current().getCaller(); Map dataCenters = new HashMap(); Map hosts = new HashMap(); Map templates = new HashMap(); Map serviceOfferings = new HashMap(); Map networks = new HashMap(); - + List vmResponses = new ArrayList(); - + for (UserVm userVm : userVms) { UserVmResponse userVmResponse = new UserVmResponse(); Account acct = ApiDBUtils.findAccountById(Long.valueOf(userVm.getAccountId())); @@ -1036,37 +1043,36 @@ public class ApiResponseHelper implements ResponseGenerator { zone = ApiDBUtils.findZoneById(userVm.getDataCenterId()); dataCenters.put(zone.getId(), zone); } - + userVmResponse.setZoneId(zone.getId()); userVmResponse.setZoneName(zone.getName()); - // if user is an admin, display host id if (((caller == null) || (caller.getType() == Account.ACCOUNT_TYPE_ADMIN)) && (userVm.getHostId() != null)) { Host host = hosts.get(userVm.getHostId()); - + if (host == null) { host = ApiDBUtils.findHostById(userVm.getHostId()); hosts.put(host.getId(), host); } - + userVmResponse.setHostId(host.getId()); userVmResponse.setHostName(host.getName()); } - if(userVm.getHypervisorType() != null){ + if (userVm.getHypervisorType() != null) { userVmResponse.setHypervisor(userVm.getHypervisorType().toString()); } - + // Template Info VMTemplateVO template = templates.get(userVm.getTemplateId()); if (template == null) { - template = ApiDBUtils.findTemplateById(userVm.getTemplateId()); + template = ApiDBUtils.findTemplateById(userVm.getTemplateId()); if (template != null) { templates.put(template.getId(), template); } } - + if (template != null) { userVmResponse.setTemplateId(userVm.getTemplateId()); userVmResponse.setTemplateName(template.getName()); @@ -1086,7 +1092,7 @@ public class ApiResponseHelper implements ResponseGenerator { // ISO Info VMTemplateVO iso = templates.get(userVm.getIsoId()); if (iso == null) { - iso = ApiDBUtils.findTemplateById(userVm.getIsoId()); + iso = ApiDBUtils.findTemplateById(userVm.getIsoId()); if (iso != null) { templates.put(iso.getId(), iso); } @@ -1099,12 +1105,12 @@ public class ApiResponseHelper implements ResponseGenerator { // Service Offering Info ServiceOffering offering = serviceOfferings.get(userVm.getServiceOfferingId()); - + if (offering == null) { offering = ApiDBUtils.findServiceOfferingById(userVm.getServiceOfferingId()); serviceOfferings.put(offering.getId(), offering); } - + userVmResponse.setServiceOfferingId(offering.getId()); userVmResponse.setServiceOfferingName(offering.getName()); userVmResponse.setCpuNumber(offering.getCpu()); @@ -1143,7 +1149,7 @@ public class ApiResponseHelper implements ResponseGenerator { if (zone.isSecurityGroupEnabled()) { List securityGroups = ApiDBUtils.getSecurityGroupsForVm(userVm.getId()); List securityGroupResponse = new ArrayList(); - for(SecurityGroupVO grp : securityGroups) { + for (SecurityGroupVO grp : securityGroups) { SecurityGroupResponse resp = new SecurityGroupResponse(); resp.setId(grp.getId()); resp.setName(grp.getName()); @@ -1151,10 +1157,10 @@ public class ApiResponseHelper implements ResponseGenerator { resp.setObjectName("securitygroup"); securityGroupResponse.add(resp); } - + userVmResponse.setSecurityGroupList(securityGroupResponse); } - + List nicProfiles = ApiDBUtils.getNics(userVm); List nicResponses = new ArrayList(); for (NicProfile singleNicProfile : nicProfiles) { @@ -1171,15 +1177,15 @@ public class ApiResponseHelper implements ResponseGenerator { if (singleNicProfile.getIsolationUri() != null) { nicResponse.setIsolationUri(singleNicProfile.getIsolationUri().toString()); } - } - - //Long networkId = singleNicProfile.getNetworkId(); + } + + // Long networkId = singleNicProfile.getNetworkId(); Network network = networks.get(singleNicProfile.getNetworkId()); if (network == null) { network = ApiDBUtils.findNetworkById(singleNicProfile.getNetworkId()); networks.put(singleNicProfile.getNetworkId(), network); } - + nicResponse.setTrafficType(network.getTrafficType().toString()); nicResponse.setType(network.getGuestType().toString()); nicResponse.setIsDefault(singleNicProfile.isDefaultNic()); @@ -1189,8 +1195,8 @@ public class ApiResponseHelper implements ResponseGenerator { userVmResponse.setNics(nicResponses); userVmResponse.setObjectName(objectName); vmResponses.add(userVmResponse); - } - + } + return vmResponses; } @@ -1219,27 +1225,27 @@ public class ApiResponseHelper implements ResponseGenerator { List nicProfiles = ApiDBUtils.getNics(router); for (NicProfile singleNicProfile : nicProfiles) { - Network network = ApiDBUtils.findNetworkById(singleNicProfile.getNetworkId()); - if (network != null) { - if (network.getTrafficType() == TrafficType.Public) { - routerResponse.setPublicIp(singleNicProfile.getIp4Address()); - routerResponse.setPublicMacAddress(singleNicProfile.getMacAddress()); - routerResponse.setPublicNetmask(singleNicProfile.getNetmask()); - routerResponse.setGateway(singleNicProfile.getGateway()); - routerResponse.setPublicNetworkId(singleNicProfile.getNetworkId()); - } else if (network.getTrafficType() == TrafficType.Control) { - routerResponse.setLinkLocalIp(singleNicProfile.getIp4Address()); - routerResponse.setLinkLocalMacAddress(singleNicProfile.getMacAddress()); - routerResponse.setLinkLocalMacAddress(singleNicProfile.getNetmask()); - routerResponse.setLinkLocalNetworkId(singleNicProfile.getNetworkId()); - } else if (network.getTrafficType() == TrafficType.Guest) { - routerResponse.setGuestIpAddress(singleNicProfile.getIp4Address()); - routerResponse.setGuestMacAddress(singleNicProfile.getMacAddress()); - routerResponse.setGuestNetmask(singleNicProfile.getNetmask()); - routerResponse.setGuestNetworkId(singleNicProfile.getNetworkId()); - routerResponse.setNetworkDomain(network.getNetworkDomain()); - } - } + Network network = ApiDBUtils.findNetworkById(singleNicProfile.getNetworkId()); + if (network != null) { + if (network.getTrafficType() == TrafficType.Public) { + routerResponse.setPublicIp(singleNicProfile.getIp4Address()); + routerResponse.setPublicMacAddress(singleNicProfile.getMacAddress()); + routerResponse.setPublicNetmask(singleNicProfile.getNetmask()); + routerResponse.setGateway(singleNicProfile.getGateway()); + routerResponse.setPublicNetworkId(singleNicProfile.getNetworkId()); + } else if (network.getTrafficType() == TrafficType.Control) { + routerResponse.setLinkLocalIp(singleNicProfile.getIp4Address()); + routerResponse.setLinkLocalMacAddress(singleNicProfile.getMacAddress()); + routerResponse.setLinkLocalMacAddress(singleNicProfile.getNetmask()); + routerResponse.setLinkLocalNetworkId(singleNicProfile.getNetworkId()); + } else if (network.getTrafficType() == TrafficType.Guest) { + routerResponse.setGuestIpAddress(singleNicProfile.getIp4Address()); + routerResponse.setGuestMacAddress(singleNicProfile.getMacAddress()); + routerResponse.setGuestNetmask(singleNicProfile.getNetmask()); + routerResponse.setGuestNetworkId(singleNicProfile.getNetworkId()); + routerResponse.setNetworkDomain(network.getNetworkDomain()); + } + } } DataCenter zone = ApiDBUtils.findZoneById(router.getDataCenterId()); if (zone != null) { @@ -1302,37 +1308,37 @@ public class ApiResponseHelper implements ResponseGenerator { List nicProfiles = ApiDBUtils.getNics(systemVM); for (NicProfile singleNicProfile : nicProfiles) { - Network network = ApiDBUtils.findNetworkById(singleNicProfile.getNetworkId()); - if (network != null) { - TrafficType trafficType = TrafficType.Public; - if(zone.getNetworkType() == NetworkType.Basic || zone.isSecurityGroupEnabled()) { - trafficType = TrafficType.Guest; - } - if (network.getTrafficType() == trafficType) { - vmResponse.setPublicIp(singleNicProfile.getIp4Address()); - vmResponse.setPublicMacAddress(singleNicProfile.getMacAddress()); - vmResponse.setPublicNetmask(singleNicProfile.getNetmask()); - } else if (network.getTrafficType() == TrafficType.Management) { - vmResponse.setPrivateIp(singleNicProfile.getIp4Address()); - vmResponse.setPrivateMacAddress(singleNicProfile.getMacAddress()); - vmResponse.setPrivateNetmask(singleNicProfile.getNetmask()); - } else if (network.getTrafficType() == TrafficType.Control) { - vmResponse.setLinkLocalIp(singleNicProfile.getIp4Address()); - vmResponse.setLinkLocalMacAddress(singleNicProfile.getMacAddress()); - vmResponse.setLinkLocalNetmask(singleNicProfile.getNetmask()); - } - } + Network network = ApiDBUtils.findNetworkById(singleNicProfile.getNetworkId()); + if (network != null) { + TrafficType trafficType = TrafficType.Public; + if (zone.getNetworkType() == NetworkType.Basic || zone.isSecurityGroupEnabled()) { + trafficType = TrafficType.Guest; + } + if (network.getTrafficType() == trafficType) { + vmResponse.setPublicIp(singleNicProfile.getIp4Address()); + vmResponse.setPublicMacAddress(singleNicProfile.getMacAddress()); + vmResponse.setPublicNetmask(singleNicProfile.getNetmask()); + } else if (network.getTrafficType() == TrafficType.Management) { + vmResponse.setPrivateIp(singleNicProfile.getIp4Address()); + vmResponse.setPrivateMacAddress(singleNicProfile.getMacAddress()); + vmResponse.setPrivateNetmask(singleNicProfile.getNetmask()); + } else if (network.getTrafficType() == TrafficType.Control) { + vmResponse.setLinkLocalIp(singleNicProfile.getIp4Address()); + vmResponse.setLinkLocalMacAddress(singleNicProfile.getMacAddress()); + vmResponse.setLinkLocalNetmask(singleNicProfile.getNetmask()); + } + } } } vmResponse.setObjectName("systemvm"); return vmResponse; } - + @Override public User findUserById(Long userId) { return ApiDBUtils.findUserById(userId); } - + @Override public UserVm findUserVmById(Long vmId) { return ApiDBUtils.findUserVmById(vmId); @@ -1343,23 +1349,23 @@ public class ApiResponseHelper implements ResponseGenerator { public VolumeVO findVolumeById(Long volumeId) { return ApiDBUtils.findVolumeById(volumeId); } - + @Override public Account findAccountByNameDomain(String accountName, Long domainId) { - return ApiDBUtils.findAccountByNameDomain(accountName, domainId); + return ApiDBUtils.findAccountByNameDomain(accountName, domainId); } - + @Override public VirtualMachineTemplate findTemplateById(Long templateId) { return ApiDBUtils.findTemplateById(templateId); } - + @Override public VpnUsersResponse createVpnUserResponse(VpnUser vpnUser) { VpnUsersResponse vpnResponse = new VpnUsersResponse(); vpnResponse.setId(vpnUser.getId()); vpnResponse.setUserName(vpnUser.getUsername()); - + Account accountTemp = ApiDBUtils.findAccountById(vpnUser.getAccountId()); if (accountTemp != null) { vpnResponse.setAccountName(accountTemp.getAccountName()); @@ -1370,7 +1376,7 @@ public class ApiResponseHelper implements ResponseGenerator { vpnResponse.setObjectName("vpnuser"); return vpnResponse; } - + @Override public RemoteAccessVpnResponse createRemoteAccessVpnResponse(RemoteAccessVpn vpn) { RemoteAccessVpnResponse vpnResponse = new RemoteAccessVpnResponse(); @@ -1379,15 +1385,15 @@ public class ApiResponseHelper implements ResponseGenerator { vpnResponse.setIpRange(vpn.getIpRange()); vpnResponse.setPresharedKey(vpn.getIpsecPresharedKey()); vpnResponse.setDomainId(vpn.getDomainId()); - + Account accountTemp = ApiDBUtils.findAccountById(vpn.getAccountId()); if (accountTemp != null) { vpnResponse.setAccountName(accountTemp.getAccountName()); vpnResponse.setDomainName(ApiDBUtils.findDomainById(accountTemp.getDomainId()).getName()); - } + } vpnResponse.setState(vpn.getState().toString()); vpnResponse.setObjectName("remoteaccessvpn"); - + return vpnResponse; } @@ -1402,13 +1408,13 @@ public class ApiResponseHelper implements ResponseGenerator { response.setFormat(result.getFormat()); response.setOsTypeId(result.getGuestOSId()); response.setOsTypeName(ApiDBUtils.findGuestOSById(result.getGuestOSId()).getDisplayName()); - - if(result.getFormat() == ImageFormat.ISO){ // Templates are always bootable - response.setBootable(result.isBootable()); - }else{ - response.setHypervisor(result.getHypervisorType().toString());// hypervisors are associated with templates + + if (result.getFormat() == ImageFormat.ISO) { // Templates are always bootable + response.setBootable(result.isBootable()); + } else { + response.setHypervisor(result.getHypervisorType().toString());// hypervisors are associated with templates } - + // add account ID and name Account owner = ApiDBUtils.findAccountById(result.getAccountId()); if (owner != null) { @@ -1421,10 +1427,10 @@ public class ApiResponseHelper implements ResponseGenerator { } @Override - public void createTemplateResponse(List responses, Pair templateZonePair, boolean isAdmin, Account account) { + public void createTemplateResponse(List responses, Pair templateZonePair, boolean isAdmin, Account account) { List templateHostRefsForTemplate = ApiDBUtils.listTemplateHostBy(templateZonePair.first(), templateZonePair.second()); VMTemplateVO template = ApiDBUtils.findTemplateById(templateZonePair.first()); - + for (VMTemplateHostVO templateHostRef : templateHostRefsForTemplate) { TemplateResponse templateResponse = new TemplateResponse(); @@ -1434,9 +1440,9 @@ public class ApiResponseHelper implements ResponseGenerator { templateResponse.setPublic(template.isPublicTemplate()); templateResponse.setCreated(templateHostRef.getCreated()); - templateResponse.setReady(templateHostRef.getDownloadState()==Status.DOWNLOADED); + templateResponse.setReady(templateHostRef.getDownloadState() == Status.DOWNLOADED); templateResponse.setFeatured(template.isFeatured()); - templateResponse.setExtractable(template.isExtractable() && !(template.getTemplateType()== TemplateType.SYSTEM)); + templateResponse.setExtractable(template.isExtractable() && !(template.getTemplateType() == TemplateType.SYSTEM)); templateResponse.setPasswordEnabled(template.getEnablePassword()); templateResponse.setCrossZones(template.isCrossZones()); templateResponse.setFormat(template.getFormat()); @@ -1444,7 +1450,7 @@ public class ApiResponseHelper implements ResponseGenerator { templateResponse.setTemplateType(template.getTemplateType().toString()); } templateResponse.setHypervisor(template.getHypervisorType().toString()); - + GuestOS os = ApiDBUtils.findGuestOSById(template.getGuestOSId()); if (os != null) { templateResponse.setOsTypeId(os.getId()); @@ -1453,7 +1459,7 @@ public class ApiResponseHelper implements ResponseGenerator { templateResponse.setOsTypeId(-1L); templateResponse.setOsTypeName(""); } - + // add account ID and name Account owner = ApiDBUtils.findAccountById(template.getAccountId()); if (owner != null) { @@ -1461,18 +1467,18 @@ public class ApiResponseHelper implements ResponseGenerator { templateResponse.setDomainId(owner.getDomainId()); templateResponse.setDomainName(ApiDBUtils.findDomainById(owner.getDomainId()).getName()); } - + HostVO host = ApiDBUtils.findHostById(templateHostRef.getHostId()); DataCenterVO datacenter = ApiDBUtils.findZoneById(host.getDataCenterId()); - + // Add the zone ID templateResponse.setZoneId(host.getDataCenterId()); templateResponse.setZoneName(datacenter.getName()); - + // If the user is an admin, add the template download status if (isAdmin || account.getId() == template.getAccountId()) { // add download status - if (templateHostRef.getDownloadState()!=Status.DOWNLOADED) { + if (templateHostRef.getDownloadState() != Status.DOWNLOADED) { String templateStatus = "Processing"; if (templateHostRef.getDownloadState() == VMTemplateHostVO.Status.DOWNLOAD_IN_PROGRESS) { if (templateHostRef.getDownloadPercent() == 100) { @@ -1490,17 +1496,17 @@ public class ApiResponseHelper implements ResponseGenerator { templateResponse.setStatus("Successfully Installed"); } } - + Long templateSize = templateHostRef.getSize(); if (templateSize > 0) { templateResponse.setSize(templateSize); } - + templateResponse.setObjectName("template"); responses.add(templateResponse); } } - + @Override public ListResponse createTemplateResponse2(VirtualMachineTemplate template, Long zoneId) { ListResponse response = new ListResponse(); @@ -1542,7 +1548,7 @@ public class ApiResponseHelper implements ResponseGenerator { templateResponse.setOsTypeId(-1L); templateResponse.setOsTypeName(""); } - + Account owner = ApiDBUtils.findAccountById(template.getAccountId()); if (owner != null) { templateResponse.setAccountId(owner.getId()); @@ -1561,7 +1567,7 @@ public class ApiResponseHelper implements ResponseGenerator { response.setResponses(responses); return response; } - + @Override public ListResponse createIsoResponses(VirtualMachineTemplate template, Long zoneId) { ListResponse response = new ListResponse(); @@ -1572,7 +1578,7 @@ public class ApiResponseHelper implements ResponseGenerator { zones = new ArrayList(); zones.add(ApiDBUtils.findZoneById(zoneId)); } else { - zones = ApiDBUtils.listZones(); + zones = ApiDBUtils.listZones(); } for (DataCenterVO zone : zones) { @@ -1592,7 +1598,7 @@ public class ApiResponseHelper implements ResponseGenerator { templateResponse.setBootable(template.isBootable()); templateResponse.setOsTypeId(template.getGuestOSId()); templateResponse.setOsTypeName(ApiDBUtils.findGuestOSById(template.getGuestOSId()).getDisplayName()); - + Account owner = ApiDBUtils.findAccountById(template.getAccountId()); if (owner != null) { templateResponse.setAccountId(owner.getId()); @@ -1610,11 +1616,11 @@ public class ApiResponseHelper implements ResponseGenerator { response.setResponses(responses); return response; } - + @Override public ListResponse createSecurityGroupResponses(List networkGroups) { List groupResultObjs = SecurityGroupResultObject.transposeNetworkGroups(networkGroups); - + ListResponse response = new ListResponse(); List netGrpResponses = new ArrayList(); for (SecurityGroupResultObject networkGroup : groupResultObjs) { @@ -1627,7 +1633,7 @@ public class ApiResponseHelper implements ResponseGenerator { netGrpResponse.setDomainName(ApiDBUtils.findDomainById(networkGroup.getDomainId()).getName()); List ingressRules = networkGroup.getIngressRules(); - if ((ingressRules != null) && !ingressRules.isEmpty()) { + if ((ingressRules != null) && !ingressRules.isEmpty()) { List ingressRulesResponse = new ArrayList(); for (IngressRuleResultObject ingressRule : ingressRules) { @@ -1662,7 +1668,7 @@ public class ApiResponseHelper implements ResponseGenerator { response.setResponses(netGrpResponses); return response; } - + @Override public SecurityGroupResponse createSecurityGroupResponse(SecurityGroup group) { SecurityGroupResponse response = new SecurityGroupResponse(); @@ -1675,27 +1681,27 @@ public class ApiResponseHelper implements ResponseGenerator { response.setObjectName("securitygroup"); return response; - + } - + @Override public ExtractResponse createExtractResponse(Long uploadId, Long id, Long zoneId, Long accountId, String mode) { UploadVO uploadInfo = ApiDBUtils.findUploadById(uploadId); ExtractResponse response = new ExtractResponse(); response.setObjectName("template"); response.setId(id); - response.setName(ApiDBUtils.findTemplateById(id).getName()); + response.setName(ApiDBUtils.findTemplateById(id).getName()); response.setZoneId(zoneId); response.setZoneName(ApiDBUtils.findZoneById(zoneId).getName()); response.setMode(mode); response.setUploadId(uploadId); response.setState(uploadInfo.getUploadState().toString()); - response.setAccountId(accountId); - //FIX ME - Need to set the url once the gson jar is upgraded since it is throwing an error right now. - //response.setUrl(uploadInfo.getUploadUrl()); + response.setAccountId(accountId); + // FIX ME - Need to set the url once the gson jar is upgraded since it is throwing an error right now. + // response.setUrl(uploadInfo.getUploadUrl()); response.setUrl(uploadInfo.getUploadUrl().replaceAll("/", "%2F")); return response; - + } @Override @@ -1714,7 +1720,7 @@ public class ApiResponseHelper implements ResponseGenerator { templateResponse.setPasswordEnabled(template.getEnablePassword()); templateResponse.setZoneId(destZoneId); templateResponse.setZoneName(ApiDBUtils.findZoneById(destZoneId).getName()); - + GuestOS os = ApiDBUtils.findGuestOSById(template.getGuestOSId()); if (os != null) { templateResponse.setOsTypeId(os.getId()); @@ -1723,7 +1729,7 @@ public class ApiResponseHelper implements ResponseGenerator { templateResponse.setOsTypeId(-1L); templateResponse.setOsTypeName(""); } - + // add account ID and name Account owner = ApiDBUtils.findAccountById(template.getAccountId()); if (owner != null) { @@ -1731,19 +1737,19 @@ public class ApiResponseHelper implements ResponseGenerator { templateResponse.setDomainId(owner.getDomainId()); templateResponse.setDomainName(ApiDBUtils.findDomainById(owner.getDomainId()).getName()); } - - //set status + + // set status Account account = UserContext.current().getCaller(); boolean isAdmin = false; if ((account == null) || (account.getType() == Account.ACCOUNT_TYPE_ADMIN) || (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)) { isAdmin = true; } - - //Return download status for admin users + + // Return download status for admin users VMTemplateHostVO templateHostRef = ApiDBUtils.findTemplateHostRef(template.getId(), destZoneId); - + if (isAdmin || template.getAccountId() == account.getId()) { - if (templateHostRef.getDownloadState()!=Status.DOWNLOADED) { + if (templateHostRef.getDownloadState() != Status.DOWNLOADED) { String templateStatus = "Processing"; if (templateHostRef.getDownloadState() == VMTemplateHostVO.Status.DOWNLOAD_IN_PROGRESS) { if (templateHostRef.getDownloadPercent() == 100) { @@ -1761,17 +1767,17 @@ public class ApiResponseHelper implements ResponseGenerator { templateResponse.setStatus("Successfully Installed"); } } - + templateResponse.setReady(templateHostRef != null && templateHostRef.getDownloadState() == VMTemplateHostVO.Status.DOWNLOADED); - + } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to copy template"); } - + templateResponse.setObjectName("template"); return templateResponse; } - + @Override public TemplateResponse createIsoResponse3(VirtualMachineTemplate iso, Long destZoneId) { TemplateResponse isoResponse = new TemplateResponse(); @@ -1786,7 +1792,7 @@ public class ApiResponseHelper implements ResponseGenerator { isoResponse.setCreated(iso.getCreated()); isoResponse.setZoneId(destZoneId); isoResponse.setZoneName(ApiDBUtils.findZoneById(destZoneId).getName()); - + GuestOS os = ApiDBUtils.findGuestOSById(iso.getGuestOSId()); if (os != null) { isoResponse.setOsTypeId(os.getId()); @@ -1795,7 +1801,7 @@ public class ApiResponseHelper implements ResponseGenerator { isoResponse.setOsTypeId(-1L); isoResponse.setOsTypeName(""); } - + // add account ID and name Account owner = ApiDBUtils.findAccountById(iso.getAccountId()); if (owner != null) { @@ -1803,19 +1809,19 @@ public class ApiResponseHelper implements ResponseGenerator { isoResponse.setDomainId(owner.getDomainId()); isoResponse.setDomainName(ApiDBUtils.findDomainById(owner.getDomainId()).getName()); } - - //set status + + // set status Account account = UserContext.current().getCaller(); boolean isAdmin = false; if ((account == null) || (account.getType() == Account.ACCOUNT_TYPE_ADMIN) || (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)) { isAdmin = true; } - - //Return download status for admin users + + // Return download status for admin users VMTemplateHostVO templateHostRef = ApiDBUtils.findTemplateHostRef(iso.getId(), destZoneId); - + if (isAdmin || iso.getAccountId() == account.getId()) { - if (templateHostRef.getDownloadState()!=Status.DOWNLOADED) { + if (templateHostRef.getDownloadState() != Status.DOWNLOADED) { String templateStatus = "Processing"; if (templateHostRef.getDownloadState() == VMTemplateHostVO.Status.DOWNLOAD_IN_PROGRESS) { if (templateHostRef.getDownloadPercent() == 100) { @@ -1833,9 +1839,9 @@ public class ApiResponseHelper implements ResponseGenerator { isoResponse.setStatus("Successfully Installed"); } } - + isoResponse.setReady(templateHostRef.getDownloadState() == VMTemplateHostVO.Status.DOWNLOADED); - + } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to copy iso"); } @@ -1860,9 +1866,9 @@ public class ApiResponseHelper implements ResponseGenerator { if (job.getInstanceType() != null && job.getInstanceId() != null) { jobResponse.setJobInstanceId(job.getInstanceId()); jobResponse.setJobInstanceType(job.getInstanceType().toString()); - } + } jobResponse.setJobProcStatus(job.getProcessStatus()); - jobResponse.setJobResult((ResponseObject)ApiSerializerHelper.fromSerializedString(job.getResult())); + jobResponse.setJobResult((ResponseObject) ApiSerializerHelper.fromSerializedString(job.getResult())); jobResponse.setJobResultCode(job.getResultCode()); jobResponse.setJobStatus(job.getStatus()); jobResponse.setUserId(job.getUserId()); @@ -1870,7 +1876,7 @@ public class ApiResponseHelper implements ResponseGenerator { jobResponse.setObjectName("asyncjobs"); return jobResponse; } - + @Override public TemplateResponse createTemplateResponse(VirtualMachineTemplate template, Long snapshotId, Long volumeId) { TemplateResponse response = new TemplateResponse(); @@ -1919,7 +1925,7 @@ public class ApiResponseHelper implements ResponseGenerator { return response; } - + @Override public EventResponse createEventResponse(Event event) { EventResponse responseEvent = new EventResponse(); @@ -1941,22 +1947,22 @@ public class ApiResponseHelper implements ResponseGenerator { responseEvent.setObjectName("event"); return responseEvent; } - + @Override - public ListResponse createIsoResponse(Set> isoZonePairSet, boolean isAdmin, Account account, Boolean isBootable) { + public ListResponse createIsoResponse(Set> isoZonePairSet, boolean isAdmin, Account account, Boolean isBootable) { ListResponse response = new ListResponse(); List isoResponses = new ArrayList(); - - for (Pair isoZonePair : isoZonePairSet) { - VMTemplateVO iso = ApiDBUtils.findTemplateById(isoZonePair.first()); - if ( (isBootable == null || !isBootable) && iso.getTemplateType() == TemplateType.PERHOST ) { + + for (Pair isoZonePair : isoZonePairSet) { + VMTemplateVO iso = ApiDBUtils.findTemplateById(isoZonePair.first()); + if ((isBootable == null || !isBootable) && iso.getTemplateType() == TemplateType.PERHOST) { TemplateResponse isoResponse = new TemplateResponse(); isoResponse.setId(iso.getId()); isoResponse.setName(iso.getName()); isoResponse.setDisplayText(iso.getDisplayText()); isoResponse.setPublic(iso.isPublicTemplate()); - isoResponse.setExtractable(iso.isExtractable() && !(iso.getTemplateType()== TemplateType.PERHOST)); + isoResponse.setExtractable(iso.isExtractable() && !(iso.getTemplateType() == TemplateType.PERHOST)); isoResponse.setReady(true); isoResponse.setBootable(iso.isBootable()); isoResponse.setFeatured(iso.isFeatured()); @@ -1967,27 +1973,26 @@ public class ApiResponseHelper implements ResponseGenerator { Account owner = ApiDBUtils.findAccountById(iso.getAccountId()); if (owner != null) { isoResponse.setAccount(owner.getAccountName()); - isoResponse.setDomainId(owner.getDomainId()); + isoResponse.setDomainId(owner.getDomainId()); isoResponse.setDomainName(ApiDBUtils.findDomainById(owner.getDomainId()).getName()); } isoResponse.setObjectName("iso"); isoResponses.add(isoResponse); response.setResponses(isoResponses); - - if(isBootable != null && !isBootable) - { - continue; //fetch only non-bootable isos and return (for now only xen tools iso) + + if (isBootable != null && !isBootable) { + continue; // fetch only non-bootable isos and return (for now only xen tools iso) } } - + List isoHosts = ApiDBUtils.listTemplateHostBy(iso.getId(), isoZonePair.second()); - for (VMTemplateHostVO isoHost : isoHosts) { + for (VMTemplateHostVO isoHost : isoHosts) { TemplateResponse isoResponse = new TemplateResponse(); isoResponse.setId(iso.getId()); isoResponse.setName(iso.getName()); isoResponse.setDisplayText(iso.getDisplayText()); isoResponse.setPublic(iso.isPublicTemplate()); - isoResponse.setExtractable(iso.isExtractable() && !(iso.getTemplateType()== TemplateType.PERHOST)); + isoResponse.setExtractable(iso.isExtractable() && !(iso.getTemplateType() == TemplateType.PERHOST)); isoResponse.setCreated(isoHost.getCreated()); isoResponse.setReady(isoHost.getDownloadState() == Status.DOWNLOADED); isoResponse.setBootable(iso.isBootable()); @@ -1995,7 +2000,7 @@ public class ApiResponseHelper implements ResponseGenerator { isoResponse.setCrossZones(iso.isCrossZones()); isoResponse.setPublic(iso.isPublicTemplate()); - // TODO: implement + // TODO: implement GuestOS os = ApiDBUtils.findGuestOSById(iso.getGuestOSId()); if (os != null) { isoResponse.setOsTypeId(os.getId()); @@ -2004,18 +2009,18 @@ public class ApiResponseHelper implements ResponseGenerator { isoResponse.setOsTypeId(-1L); isoResponse.setOsTypeName(""); } - + // add account ID and name Account owner = ApiDBUtils.findAccountById(iso.getAccountId()); if (owner != null) { isoResponse.setAccount(owner.getAccountName()); isoResponse.setDomainId(owner.getDomainId()); - // TODO: implement + // TODO: implement isoResponse.setDomainName(ApiDBUtils.findDomainById(owner.getDomainId()).getName()); } - + // Add the zone ID - // TODO: implement + // TODO: implement HostVO host = ApiDBUtils.findHostById(isoHost.getHostId()); DataCenterVO datacenter = ApiDBUtils.findZoneById(host.getDataCenterId()); isoResponse.setZoneId(host.getDataCenterId()); @@ -2024,7 +2029,7 @@ public class ApiResponseHelper implements ResponseGenerator { // If the user is an admin, add the template download status if (isAdmin || account.getId() == iso.getAccountId()) { // add download status - if (isoHost.getDownloadState()!=Status.DOWNLOADED) { + if (isoHost.getDownloadState() != Status.DOWNLOADED) { String isoStatus = "Processing"; if (isoHost.getDownloadState() == VMTemplateHostVO.Status.DOWNLOADED) { isoStatus = "Download Complete"; @@ -2047,24 +2052,24 @@ public class ApiResponseHelper implements ResponseGenerator { if (isoSize > 0) { isoResponse.setSize(isoSize); } - + isoResponse.setObjectName("iso"); isoResponses.add(isoResponse); } } - + response.setResponses(isoResponses); return response; } - - private List sumCapacities(List hostCapacities) { + + private List sumCapacities(List hostCapacities) { Map totalCapacityMap = new HashMap(); Map usedCapacityMap = new HashMap(); - + Set poolIdsToIgnore = new HashSet(); Criteria c = new Criteria(); - // TODO: implement + // TODO: implement List allStoragePools = ApiDBUtils.searchForStoragePools(c); for (StoragePoolVO pool : allStoragePools) { StoragePoolType poolType = pool.getPoolType(); @@ -2072,7 +2077,7 @@ public class ApiResponseHelper implements ResponseGenerator { poolIdsToIgnore.add(pool.getId()); } } - + // collect all the capacity types, sum allocated/used and sum total...get one capacity number for each for (Capacity capacity : hostCapacities) { if (poolIdsToIgnore.contains(capacity.getHostOrPoolId())) { @@ -2081,7 +2086,7 @@ public class ApiResponseHelper implements ResponseGenerator { short capacityType = capacity.getCapacityType(); String key = capacity.getCapacityType() + "_" + capacity.getDataCenterId(); String keyForPodTotal = key + "_-1"; - + boolean sumPodCapacity = false; if (capacity.getPodId() != null) { key += "_" + capacity.getPodId(); @@ -2100,16 +2105,22 @@ public class ApiResponseHelper implements ResponseGenerator { if (usedCapacity == null) { usedCapacity = new Long(capacity.getUsedCapacity()); } else { - usedCapacity = new Long(capacity.getUsedCapacity() + usedCapacity); + usedCapacity = new Long(capacity.getUsedCapacity() + usedCapacity); } - - if (capacityType == Capacity.CAPACITY_TYPE_CPU || capacityType == Capacity.CAPACITY_TYPE_MEMORY){ // Reserved Capacity accounts for stopped vms that have been stopped within an interval - usedCapacity += capacity.getReservedCapacity(); + + if (capacityType == Capacity.CAPACITY_TYPE_CPU || capacityType == Capacity.CAPACITY_TYPE_MEMORY) { // Reserved + // Capacity + // accounts for + // stopped vms + // that have been + // stopped within + // an interval + usedCapacity += capacity.getReservedCapacity(); } totalCapacityMap.put(key, totalCapacity); usedCapacityMap.put(key, usedCapacity); - + if (sumPodCapacity) { totalCapacity = totalCapacityMap.get(keyForPodTotal); usedCapacity = usedCapacityMap.get(keyForPodTotal); @@ -2125,11 +2136,20 @@ public class ApiResponseHelper implements ResponseGenerator { } else { usedCapacity = new Long(capacity.getUsedCapacity() + usedCapacity); } - - if (capacityType == Capacity.CAPACITY_TYPE_CPU || capacityType == Capacity.CAPACITY_TYPE_MEMORY){ // Reserved Capacity accounts for stopped vms that have been stopped within an interval - usedCapacity += capacity.getReservedCapacity(); + + if (capacityType == Capacity.CAPACITY_TYPE_CPU || capacityType == Capacity.CAPACITY_TYPE_MEMORY) { // Reserved + // Capacity + // accounts + // for + // stopped + // vms that + // have been + // stopped + // within an + // interval + usedCapacity += capacity.getReservedCapacity(); } - + totalCapacityMap.put(keyForPodTotal, totalCapacity); usedCapacityMap.put(keyForPodTotal, usedCapacity); } @@ -2152,9 +2172,8 @@ public class ApiResponseHelper implements ResponseGenerator { summedCapacities.add(summedCapacity); } return summedCapacities; - } - - + } + @Override public List createCapacityResponse(List result, DecimalFormat format) { List capacityResponses = new ArrayList(); @@ -2175,8 +2194,8 @@ public class ApiResponseHelper implements ResponseGenerator { capacityResponse.setZoneId(summedCapacity.getDataCenterId()); capacityResponse.setZoneName(ApiDBUtils.findZoneById(summedCapacity.getDataCenterId()).getName()); if (summedCapacity.getTotalCapacity() != 0) { - //float computed = ((float)summedCapacity.getUsedCapacity() / (float)summedCapacity.getTotalCapacity() * 100f); - capacityResponse.setPercentUsed(format.format((float)summedCapacity.getUsedCapacity() / (float)summedCapacity.getTotalCapacity() * 100f)); + // float computed = ((float)summedCapacity.getUsedCapacity() / (float)summedCapacity.getTotalCapacity() * 100f); + capacityResponse.setPercentUsed(format.format((float) summedCapacity.getUsedCapacity() / (float) summedCapacity.getTotalCapacity() * 100f)); } else { capacityResponse.setPercentUsed(format.format(0L)); } @@ -2184,7 +2203,7 @@ public class ApiResponseHelper implements ResponseGenerator { capacityResponse.setObjectName("capacity"); capacityResponses.add(capacityResponse); } - + return capacityResponses; } @@ -2193,7 +2212,7 @@ public class ApiResponseHelper implements ResponseGenerator { Long templateOwnerDomain = null; VirtualMachineTemplate template = ApiDBUtils.findTemplateById(id); if (isAdmin) { - // FIXME: we have just template id and need to get template owner from that + // FIXME: we have just template id and need to get template owner from that Account templateOwner = ApiDBUtils.findAccountById(template.getAccountId()); if (templateOwner != null) { templateOwnerDomain = templateOwner.getDomainId(); @@ -2211,21 +2230,21 @@ public class ApiResponseHelper implements ResponseGenerator { response.setObjectName("templatepermission"); return response; } - + @Override - public AsyncJobResponse queryJobResult(QueryAsyncJobResultCmd cmd) throws InvalidParameterValueException{ + public AsyncJobResponse queryJobResult(QueryAsyncJobResultCmd cmd) throws InvalidParameterValueException { AsyncJobResult result = ApiDBUtils._asyncMgr.queryAsyncJobResult(cmd); AsyncJobResponse response = new AsyncJobResponse(); response.setId(result.getJobId()); response.setJobStatus(result.getJobStatus()); response.setJobProcStatus(result.getProcessStatus()); response.setJobResultCode(result.getResultCode()); - response.setJobResult((ResponseObject)ApiSerializerHelper.fromSerializedString(result.getResult())); + response.setJobResult((ResponseObject) ApiSerializerHelper.fromSerializedString(result.getResult())); Object resultObject = result.getResultObject(); if (resultObject != null) { Class clz = resultObject.getClass(); - if(clz.isPrimitive() || clz.getSuperclass() == Number.class || clz == String.class || clz == Date.class) { + if (clz.isPrimitive() || clz.getSuperclass() == Number.class || clz == String.class || clz == Date.class) { response.setJobResultType("text"); } else { response.setJobResultType("object"); @@ -2234,15 +2253,13 @@ public class ApiResponseHelper implements ResponseGenerator { return response; } - - - + @Override public SecurityGroupResponse createSecurityGroupResponseFromIngressRule(List ingressRules) { SecurityGroupResponse response = new SecurityGroupResponse(); if ((ingressRules != null) && !ingressRules.isEmpty()) { - SecurityGroup securityGroup = ApiDBUtils.findNetworkGroupById(ingressRules.get(0).getSecurityGroupId()); + SecurityGroup securityGroup = ApiDBUtils.findNetworkGroupById(ingressRules.get(0).getSecurityGroupId()); response.setId(securityGroup.getId()); response.setName(securityGroup.getName()); response.setDescription(securityGroup.getDescription()); @@ -2280,7 +2297,7 @@ public class ApiResponseHelper implements ResponseGenerator { } return response; } - + @Override public NetworkOfferingResponse createNetworkOfferingResponse(NetworkOffering offering) { NetworkOfferingResponse response = new NetworkOfferingResponse(); @@ -2294,19 +2311,19 @@ public class ApiResponseHelper implements ResponseGenerator { response.setSpecifyVlan(offering.getSpecifyVlan()); response.setAvailability(offering.getAvailability().toString()); response.setNetworkRate(ApiDBUtils.getNetworkRate(offering.getId())); - + if (offering.getGuestType() != null) { response.setGuestIpType(offering.getGuestType().toString()); } - + response.setObjectName("networkoffering"); return response; } - + @Override public NetworkResponse createNetworkResponse(Network network) { - //need to get network profile in order to retrieve dns information from there - NetworkProfile profile = ApiDBUtils.getNetworkProfile(network.getId()); + // need to get network profile in order to retrieve dns information from there + NetworkProfile profile = ApiDBUtils.getNetworkProfile(network.getId()); NetworkResponse response = new NetworkResponse(); response.setId(network.getId()); response.setName(network.getName()); @@ -2317,31 +2334,31 @@ public class ApiResponseHelper implements ResponseGenerator { if (network.getBroadcastUri() != null) { response.setBroadcastUri(network.getBroadcastUri().toString()); } - + if (network.getTrafficType() != null) { response.setTrafficType(network.getTrafficType().name()); } - + if (network.getGuestType() != null) { response.setType(network.getGuestType().name()); } - - //get start ip and end ip of corresponding vlan - List vlan= ApiDBUtils.listVlanByNetworkId(network.getId()); + + // get start ip and end ip of corresponding vlan + List vlan = ApiDBUtils.listVlanByNetworkId(network.getId()); if (vlan != null && !vlan.isEmpty()) { Vlan singleVlan = vlan.get(0); String ipRange = singleVlan.getIpRange(); - String[] range = ipRange.split("-"); + String[] range = ipRange.split("-"); response.setStartIp(range[0]); response.setEndIp(range[1]); response.setGateway(singleVlan.getVlanGateway()); response.setNetmask(singleVlan.getVlanNetmask()); response.setVlan(singleVlan.getVlanTag()); } - + response.setZoneId(network.getDataCenterId()); - - //populate network offering information + + // populate network offering information NetworkOffering networkOffering = ApiDBUtils.findNetworkOfferingById(network.getNetworkOfferingId()); if (networkOffering != null) { response.setNetworkOfferingId(networkOffering.getId()); @@ -2350,27 +2367,27 @@ public class ApiResponseHelper implements ResponseGenerator { response.setIsSystem(networkOffering.isSystemOnly()); response.setNetworkOfferingAvailability(networkOffering.getAvailability().toString()); } - + response.setIsShared(network.getIsShared()); response.setIsDefault(network.isDefault()); response.setState(network.getState().toString()); response.setRelated(network.getRelated()); response.setNetworkDomain(network.getNetworkDomain()); - + response.setDns1(profile.getDns1()); response.setDns2(profile.getDns2()); - + response.setIsSecurityGroupEnabled(network.isSecurityGroupEnabled()); - - //populate capability - Map> serviceCapabilitiesMap = ApiDBUtils.getNetworkCapabilities(network.getId()); + + // populate capability + Map> serviceCapabilitiesMap = ApiDBUtils.getNetworkCapabilities(network.getId()); List serviceResponses = new ArrayList(); if (serviceCapabilitiesMap != null) { for (Service service : serviceCapabilitiesMap.keySet()) { ServiceResponse serviceResponse = new ServiceResponse(); serviceResponse.setName(service.getName()); - - //set list of capabilities for the service + + // set list of capabilities for the service List capabilityResponses = new ArrayList(); Map serviceCapabilities = serviceCapabilitiesMap.get(service); if (serviceCapabilities != null) { @@ -2384,13 +2401,13 @@ public class ApiResponseHelper implements ResponseGenerator { } serviceResponse.setCapabilities(capabilityResponses); } - + serviceResponse.setObjectName("service"); serviceResponses.add(serviceResponse); } } response.setServices(serviceResponses); - + Account account = ApiDBUtils.findAccountById(network.getAccountId()); if (account != null && !network.getIsShared()) { response.setAccountName(account.getAccountName()); @@ -2398,14 +2415,14 @@ public class ApiResponseHelper implements ResponseGenerator { response.setDomainId(domain.getId()); response.setDomain(domain.getName()); } - + Long dedicatedDomainId = ApiDBUtils.getDedicatedNetworkDomain(network.getId()); if (dedicatedDomainId != null) { Domain domain = ApiDBUtils.findDomainById(dedicatedDomainId); response.setDomainId(dedicatedDomainId); response.setDomain(domain.getName()); - } - + } + response.setObjectName("network"); return response; } diff --git a/server/src/com/cloud/api/response/ApiResponseSerializer.java b/server/src/com/cloud/api/response/ApiResponseSerializer.java index 7a2655d6948..331bc91e113 100644 --- a/server/src/com/cloud/api/response/ApiResponseSerializer.java +++ b/server/src/com/cloud/api/response/ApiResponseSerializer.java @@ -29,15 +29,16 @@ public class ApiResponseSerializer { return toXMLSerializedString(result); } } - + private static final Pattern s_unicodeEscapePattern = Pattern.compile("\\\\u([0-9A-Fa-f]{4})"); + public static String unescape(String escaped) { - String str = escaped; - Matcher matcher = s_unicodeEscapePattern.matcher(str); - while(matcher.find()) { - str = str.replaceAll("\\" + matcher.group(0), Character.toString((char)Integer.parseInt(matcher.group(1), 16))); - } - return str; + String str = escaped; + Matcher matcher = s_unicodeEscapePattern.matcher(str); + while (matcher.find()) { + str = str.replaceAll("\\" + matcher.group(0), Character.toString((char) Integer.parseInt(matcher.group(1), 16))); + } + return str; } private static String toJSONSerializedString(ResponseObject result) { @@ -47,14 +48,15 @@ public class ApiResponseSerializer { sb.append("{ \"" + result.getResponseName() + "\" : "); if (result instanceof ListResponse) { - List responses = ((ListResponse)result).getResponses(); + List responses = ((ListResponse) result).getResponses(); if ((responses != null) && !responses.isEmpty()) { - int count = responses.size(); - String jsonStr = gson.toJson(responses.get(0));; + + Integer count = ((ListResponse) result).getCount(); + String jsonStr = gson.toJson(responses.get(0)); jsonStr = unescape(jsonStr); - - if (((ListResponse)result).getCount() != null) { - sb.append("{ \"" + ApiConstants.COUNT + "\":" + ((ListResponse)result).getCount() + " ,\"" + responses.get(0).getObjectName() + "\" : [ " + jsonStr); + + if (count != null && count != 0) { + sb.append("{ \"" + ApiConstants.COUNT + "\":" + ((ListResponse) result).getCount() + " ,\"" + responses.get(0).getObjectName() + "\" : [ " + jsonStr); } for (int i = 1; i < count; i++) { jsonStr = gson.toJson(responses.get(i)); @@ -66,18 +68,18 @@ public class ApiResponseSerializer { sb.append("{ }"); } } else if (result instanceof SuccessResponse) { - sb.append("{ \"success\" : \""+((SuccessResponse)result).getSuccess()+"\"} "); + sb.append("{ \"success\" : \"" + ((SuccessResponse) result).getSuccess() + "\"} "); } else if (result instanceof ExceptionResponse) { - sb.append("{\"errorcode\" : "+((ExceptionResponse)result).getErrorCode() + ", \"errortext\" : \""+ ((ExceptionResponse)result).getErrorText() +"\"} "); - }else { + sb.append("{\"errorcode\" : " + ((ExceptionResponse) result).getErrorCode() + ", \"errortext\" : \"" + ((ExceptionResponse) result).getErrorText() + "\"} "); + } else { String jsonStr = gson.toJson(result); if ((jsonStr != null) && !"".equals(jsonStr)) { - jsonStr = unescape(jsonStr); - if (result instanceof AsyncJobResponse || result instanceof CreateCmdResponse) { - sb.append(jsonStr); - } else { - sb.append(" { \"" + result.getObjectName() + "\" : " + jsonStr + " } "); - } + jsonStr = unescape(jsonStr); + if (result instanceof AsyncJobResponse || result instanceof CreateCmdResponse) { + sb.append(jsonStr); + } else { + sb.append(" { \"" + result.getObjectName() + "\" : " + jsonStr + " } "); + } } else { sb.append("{ }"); } @@ -91,49 +93,51 @@ public class ApiResponseSerializer { private static String toXMLSerializedString(ResponseObject result) { StringBuilder sb = new StringBuilder(); sb.append(""); - sb.append("<" + result.getResponseName() + " cloud-stack-version=\""+ApiDBUtils.getVersion()+ "\">"); + sb.append("<" + result.getResponseName() + " cloud-stack-version=\"" + ApiDBUtils.getVersion() + "\">"); if (result instanceof ListResponse) { - if (((ListResponse)result).getCount() != null) { - sb.append("<" + ApiConstants.COUNT + ">" + ((ListResponse)result).getCount() + ""); + Integer count = ((ListResponse) result).getCount(); + + if (count != null && count != 0) { + sb.append("<" + ApiConstants.COUNT + ">" + ((ListResponse) result).getCount() + ""); } - List responses = ((ListResponse)result).getResponses(); + List responses = ((ListResponse) result).getResponses(); if ((responses != null) && !responses.isEmpty()) { for (ResponseObject obj : responses) { serializeResponseObjXML(sb, obj); } - } + } } else { if (result instanceof CreateCmdResponse || result instanceof AsyncJobResponse) { serializeResponseObjFieldsXML(sb, result); } else { serializeResponseObjXML(sb, result); - } + } } - + sb.append(""); return sb.toString(); } - - private static void serializeResponseObjXML(StringBuilder sb, ResponseObject obj){ - if (!(obj instanceof SuccessResponse)&& !(obj instanceof ExceptionResponse)){ + + private static void serializeResponseObjXML(StringBuilder sb, ResponseObject obj) { + if (!(obj instanceof SuccessResponse) && !(obj instanceof ExceptionResponse)) { sb.append("<" + obj.getObjectName() + ">"); } - serializeResponseObjFieldsXML(sb, obj); - if (!(obj instanceof SuccessResponse) && !(obj instanceof ExceptionResponse)){ + serializeResponseObjFieldsXML(sb, obj); + if (!(obj instanceof SuccessResponse) && !(obj instanceof ExceptionResponse)) { sb.append(""); } } - private static void serializeResponseObjFieldsXML(StringBuilder sb, ResponseObject obj){ + private static void serializeResponseObjFieldsXML(StringBuilder sb, ResponseObject obj) { boolean isAsync = false; if (obj instanceof AsyncJobResponse) isAsync = true; - + Field[] fields = obj.getClass().getDeclaredFields(); for (Field field : fields) { if ((field.getModifiers() & Modifier.TRANSIENT) != 0) { - continue; // skip transient fields + continue; // skip transient fields } SerializedName serializedName = field.getAnnotation(SerializedName.class); @@ -141,14 +145,14 @@ public class ApiResponseSerializer { continue; // skip fields w/o serialized name } - String propName = field.getName(); + String propName = field.getName(); Method method = getGetMethod(obj, propName); if (method != null) { try { Object fieldValue = method.invoke(obj); if (fieldValue != null) { if (fieldValue instanceof ResponseObject) { - ResponseObject subObj = (ResponseObject)fieldValue; + ResponseObject subObj = (ResponseObject) fieldValue; if (isAsync) { sb.append(""); } @@ -156,20 +160,20 @@ public class ApiResponseSerializer { if (isAsync) { sb.append(""); } - } else if (fieldValue instanceof List){ - List subResponseList = (List)fieldValue; - for (Object value: subResponseList) { - if (value instanceof ResponseObject){ - ResponseObject subObj = (ResponseObject)value; + } else if (fieldValue instanceof List) { + List subResponseList = (List) fieldValue; + for (Object value : subResponseList) { + if (value instanceof ResponseObject) { + ResponseObject subObj = (ResponseObject) value; if (serializedName != null) { subObj.setObjectName(serializedName.value()); } serializeResponseObjXML(sb, subObj); } } - - }else if (fieldValue instanceof Date) { - sb.append("<" + serializedName.value() + ">" + BaseCmd.getDateString((Date)fieldValue) + ""); + + } else if (fieldValue instanceof Date) { + sb.append("<" + serializedName.value() + ">" + BaseCmd.getDateString((Date) fieldValue) + ""); } else { sb.append("<" + serializedName.value() + ">" + escapeSpecialXmlChars(fieldValue.toString()) + ""); } @@ -191,12 +195,10 @@ public class ApiResponseSerializer { try { method = o.getClass().getMethod(methodName); } catch (SecurityException e1) { - s_logger.error("Security exception in getting ResponseObject " + o.getClass().getName() + " get method for property: " - + propName); + s_logger.error("Security exception in getting ResponseObject " + o.getClass().getName() + " get method for property: " + propName); } catch (NoSuchMethodException e1) { if (s_logger.isTraceEnabled()) { - s_logger.trace("ResponseObject " + o.getClass().getName() + " does not have " + methodName - + "() method for property: " + propName + s_logger.trace("ResponseObject " + o.getClass().getName() + " does not have " + methodName + "() method for property: " + propName + ", will check is-prefixed method to see if it is boolean property"); } } @@ -208,11 +210,9 @@ public class ApiResponseSerializer { try { method = o.getClass().getMethod(methodName); } catch (SecurityException e1) { - s_logger.error("Security exception in getting ResponseObject " + o.getClass().getName() + " get method for property: " - + propName); + s_logger.error("Security exception in getting ResponseObject " + o.getClass().getName() + " get method for property: " + propName); } catch (NoSuchMethodException e1) { - s_logger.warn("ResponseObject " + o.getClass().getName() + " does not have " + methodName + "() method for property: " - + propName); + s_logger.warn("ResponseObject " + o.getClass().getName() + " does not have " + methodName + "() method for property: " + propName); } return method; } @@ -229,11 +229,11 @@ public class ApiResponseSerializer { return sb.toString(); } - + private static String escapeSpecialXmlChars(String originalString) { char[] origChars = originalString.toCharArray(); StringBuilder resultString = new StringBuilder(); - + for (char singleChar : origChars) { if (singleChar == '"') { resultString.append("""); diff --git a/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java b/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java index d558f6ac5d2..ae6fcca0a8d 100644 --- a/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java +++ b/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java @@ -107,13 +107,20 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesManager, EventDao _eventDao; @Inject LoadBalancerVMMapDao _lb2VmMapDao; - @Inject UserVmDao _vmDao; - @Inject AccountDao _accountDao; - @Inject DomainDao _domainDao; - @Inject NicDao _nicDao; - @Inject UsageEventDao _usageEventDao; + @Inject + UserVmDao _vmDao; + @Inject + AccountDao _accountDao; + @Inject + DomainDao _domainDao; + @Inject + NicDao _nicDao; + @Inject + UsageEventDao _usageEventDao; - @Override @DB @ActionEvent (eventType=EventTypes.EVENT_ASSIGN_TO_LOAD_BALANCER_RULE, eventDescription="assigning to load balancer", async=true) + @Override + @DB + @ActionEvent(eventType = EventTypes.EVENT_ASSIGN_TO_LOAD_BALANCER_RULE, eventDescription = "assigning to load balancer", async = true) public boolean assignToLoadBalancer(long loadBalancerId, List instanceIds) { UserContext ctx = UserContext.current(); Account caller = ctx.getCaller(); @@ -128,25 +135,25 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesManager, for (LoadBalancerVMMapVO mappedInstance : mappedInstances) { mappedInstanceIds.add(Long.valueOf(mappedInstance.getInstanceId())); } - + List vmsToAdd = new ArrayList(); - + for (Long instanceId : instanceIds) { if (mappedInstanceIds.contains(instanceId)) { throw new InvalidParameterValueException("VM " + instanceId + " is already mapped to load balancer."); } - + UserVm vm = _vmDao.findById(instanceId); if (vm == null || vm.getState() == State.Destroyed || vm.getState() == State.Expunging) { throw new InvalidParameterValueException("Invalid instance id: " + instanceId); } - + _rulesMgr.checkRuleAndUserVm(loadBalancer, vm, caller); - + if (vm.getAccountId() != loadBalancer.getAccountId()) { throw new PermissionDeniedException("Cannot add virtual machines that do not belong to the same owner."); } - + // Let's check to make sure the vm has a nic in the same network as the load balancing rule. List nics = _networkMgr.getNics(vm.getId()); Nic nicInSameNetwork = null; @@ -156,26 +163,26 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesManager, break; } } - + if (nicInSameNetwork == null) { throw new InvalidParameterValueException("VM " + instanceId + " cannot be added because it doesn't belong in the same network."); } - + if (s_logger.isDebugEnabled()) { s_logger.debug("Adding " + vm + " to the load balancer pool"); } vmsToAdd.add(vm); } - + Transaction txn = Transaction.currentTxn(); txn.start(); - + for (UserVm vm : vmsToAdd) { LoadBalancerVMMapVO map = new LoadBalancerVMMapVO(loadBalancer.getId(), vm.getId(), false); map = _lb2VmMapDao.persist(map); } txn.commit(); - + try { loadBalancer.setState(FirewallRule.State.Add); _lbDao.persist(loadBalancer); @@ -184,51 +191,50 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesManager, s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e); return false; } - + return true; } - - @Override @ActionEvent (eventType=EventTypes.EVENT_REMOVE_FROM_LOAD_BALANCER_RULE, eventDescription="removing from load balancer", async=true) + @Override + @ActionEvent(eventType = EventTypes.EVENT_REMOVE_FROM_LOAD_BALANCER_RULE, eventDescription = "removing from load balancer", async = true) public boolean removeFromLoadBalancer(long loadBalancerId, List instanceIds) { return removeFromLoadBalancerInternal(loadBalancerId, instanceIds); } - + private boolean removeFromLoadBalancerInternal(long loadBalancerId, List instanceIds) { UserContext caller = UserContext.current(); LoadBalancerVO loadBalancer = _lbDao.findById(Long.valueOf(loadBalancerId)); if (loadBalancer == null) { throw new InvalidParameterException("Invalid load balancer value: " + loadBalancerId); - } - + } + _accountMgr.checkAccess(caller.getCaller(), loadBalancer); - + try { loadBalancer.setState(FirewallRule.State.Add); _lbDao.persist(loadBalancer); - + for (long instanceId : instanceIds) { LoadBalancerVMMapVO map = _lb2VmMapDao.findByLoadBalancerIdAndVmId(loadBalancerId, instanceId); map.setRevoke(true); _lb2VmMapDao.persist(map); s_logger.debug("Set load balancer rule for revoke: rule id " + loadBalancerId + ", vmId " + instanceId); } - + if (!applyLoadBalancerConfig(loadBalancerId)) { s_logger.warn("Failed to remove load balancer rule id " + loadBalancerId + " for vms " + instanceIds); throw new CloudRuntimeException("Failed to remove load balancer rule id " + loadBalancerId + " for vms " + instanceIds); } - + } catch (ResourceUnavailableException e) { s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e); return false; } - + return true; } - @Override public boolean removeVmFromLoadBalancers(long instanceId) { boolean success = true; @@ -236,11 +242,11 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesManager, if (maps == null || maps.isEmpty()) { return true; } - + Map> lbsToReconfigure = new HashMap>(); - - //first set all existing lb mappings with Revoke state - for (LoadBalancerVMMapVO map: maps) { + + // first set all existing lb mappings with Revoke state + for (LoadBalancerVMMapVO map : maps) { long lbId = map.getLoadBalancerId(); List instances = lbsToReconfigure.get(lbId); if (instances == null) { @@ -248,13 +254,13 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesManager, } instances.add(map.getInstanceId()); lbsToReconfigure.put(lbId, instances); - + map.setRevoke(true); _lb2VmMapDao.persist(map); s_logger.debug("Set load balancer rule for revoke: rule id " + map.getLoadBalancerId() + ", vmId " + instanceId); } - - //Reapply all lbs that had the vm assigned + + // Reapply all lbs that had the vm assigned if (lbsToReconfigure != null) { for (Map.Entry> lb : lbsToReconfigure.entrySet()) { if (!removeFromLoadBalancerInternal(lb.getKey(), lb.getValue())) { @@ -264,30 +270,29 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesManager, } return success; } - - @Override @ActionEvent (eventType=EventTypes.EVENT_LOAD_BALANCER_DELETE, eventDescription="deleting load balancer", async=true) + @Override + @ActionEvent(eventType = EventTypes.EVENT_LOAD_BALANCER_DELETE, eventDescription = "deleting load balancer", async = true) public boolean deleteLoadBalancerRule(long loadBalancerId, boolean apply) { UserContext ctx = UserContext.current(); Account caller = ctx.getCaller(); - + LoadBalancerVO rule = _lbDao.findById(loadBalancerId); if (rule == null) { throw new InvalidParameterValueException("Unable to find load balancer rule " + loadBalancerId); } - + _accountMgr.checkAccess(caller, rule); - - return deleteLoadBalancerRule(loadBalancerId, apply, caller, ctx.getCallerUserId()); + + return deleteLoadBalancerRule(loadBalancerId, apply, caller, ctx.getCallerUserId()); } - - - @DB + + @DB private boolean deleteLoadBalancerRule(long loadBalancerId, boolean apply, Account caller, long callerUserId) { LoadBalancerVO lb = _lbDao.findById(loadBalancerId); Transaction txn = Transaction.currentTxn(); boolean generateUsageEvent = false; - + txn.start(); if (lb.getState() == FirewallRule.State.Staged) { if (s_logger.isDebugEnabled()) { @@ -299,43 +304,43 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesManager, _lbDao.persist(lb); generateUsageEvent = true; } - + List maps = _lb2VmMapDao.listByLoadBalancerId(loadBalancerId); if (maps != null) { for (LoadBalancerVMMapVO map : maps) { map.setRevoke(true); _lb2VmMapDao.persist(map); s_logger.debug("Set load balancer rule for revoke: rule id " + loadBalancerId + ", vmId " + map.getInstanceId()); - } + } } - + if (generateUsageEvent) { - //Generate usage event right after all rules were marked for revoke - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_LOAD_BALANCER_DELETE, lb.getAccountId(), 0 , lb.getId(), null); + // Generate usage event right after all rules were marked for revoke + UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_LOAD_BALANCER_DELETE, lb.getAccountId(), 0, lb.getId(), null); _usageEventDao.persist(usageEvent); } - + txn.commit(); - + if (apply) { try { if (!applyLoadBalancerConfig(loadBalancerId)) { s_logger.warn("Unable to apply the load balancer config"); return false; - } + } } catch (ResourceUnavailableException e) { s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e); return false; } } - - _rulesDao.remove(lb.getId()); + + _rulesDao.remove(lb.getId()); s_logger.debug("Load balancer with id " + lb.getId() + " is removed successfully"); return true; } - - @Override @ActionEvent (eventType=EventTypes.EVENT_LOAD_BALANCER_CREATE, eventDescription="creating load balancer") + @Override + @ActionEvent(eventType = EventTypes.EVENT_LOAD_BALANCER_CREATE, eventDescription = "creating load balancer") public LoadBalancer createLoadBalancerRule(LoadBalancer lb) throws NetworkRuleConflictException { UserContext caller = UserContext.current(); @@ -373,22 +378,22 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesManager, if ((lb.getAlgorithm() == null) || !NetUtils.isValidAlgorithm(lb.getAlgorithm())) { throw new InvalidParameterValueException("Invalid algorithm: " + lb.getAlgorithm()); } - + Long networkId = ipAddr.getAssociatedWithNetworkId(); if (networkId == null) { throw new InvalidParameterValueException("Unable to create load balancer rule ; ip id=" + ipId + " is not associated with any network"); } - + _accountMgr.checkAccess(caller.getCaller(), ipAddr); - - //verify that lb service is supported by the network + + // verify that lb service is supported by the network if (!_networkMgr.isServiceSupported(networkId, Service.Lb)) { throw new InvalidParameterValueException("LB service is not supported in network id=" + networkId); } - - LoadBalancerVO newRule = new LoadBalancerVO(lb.getXid(), lb.getName(), lb.getDescription(), lb.getSourceIpAddressId(), lb.getSourcePortEnd(), - lb.getDefaultPortStart(), lb.getAlgorithm(), networkId, ipAddr.getAccountId(), ipAddr.getDomainId()); + + LoadBalancerVO newRule = new LoadBalancerVO(lb.getXid(), lb.getName(), lb.getDescription(), lb.getSourceIpAddressId(), lb.getSourcePortEnd(), lb.getDefaultPortStart(), lb.getAlgorithm(), + networkId, ipAddr.getAccountId(), ipAddr.getDomainId()); newRule = _lbDao.persist(newRule); @@ -397,8 +402,8 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesManager, if (!_rulesDao.setStateToAdd(newRule)) { throw new CloudRuntimeException("Unable to update the state to add for " + newRule); } - s_logger.debug("Load balancer " + newRule.getId() + " for Ip address id=" + ipId + ", public port " + srcPortStart + ", private port " + defPortStart+ " is added successfully."); - UserContext.current().setEventDetails("Load balancer Id: "+newRule.getId()); + s_logger.debug("Load balancer " + newRule.getId() + " for Ip address id=" + ipId + ", public port " + srcPortStart + ", private port " + defPortStart + " is added successfully."); + UserContext.current().setEventDetails("Load balancer Id: " + newRule.getId()); UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_LOAD_BALANCER_CREATE, ipAddr.getAllocatedToAccountId(), ipAddr.getDataCenterId(), newRule.getId(), null); _usageEventDao.persist(usageEvent); return newRule; @@ -415,80 +420,80 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesManager, public boolean applyLoadBalancerConfig(long lbRuleId) throws ResourceUnavailableException { List lbs = new ArrayList(1); lbs.add(_lbDao.findById(lbRuleId)); - return applyLoadBalancerRules(lbs); + return applyLoadBalancerRules(lbs); } - + @Override public boolean applyLoadBalancersForNetwork(long networkId) throws ResourceUnavailableException { List lbs = _lbDao.listByNetworkId(networkId); - + if (lbs != null) { - return applyLoadBalancerRules(lbs); + return applyLoadBalancerRules(lbs); } else { - s_logger.info("Network id=" + networkId + " doesn't have load balancer rules, nothing to apply"); + s_logger.info("Network id=" + networkId + " doesn't have load balancer rules, nothing to apply"); return true; } } - + @DB - private boolean applyLoadBalancerRules(List lbs) throws ResourceUnavailableException{ + private boolean applyLoadBalancerRules(List lbs) throws ResourceUnavailableException { Transaction txn = Transaction.currentTxn(); List rules = new ArrayList(); for (LoadBalancerVO lb : lbs) { List dstList = getExistingDestinations(lb.getId()); - + if (dstList != null && !dstList.isEmpty()) { LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, dstList); rules.add(loadBalancing); } } - + if (!_networkMgr.applyRules(rules, false)) { s_logger.debug("LB rules are not completely applied"); return false; - } - + } + for (LoadBalancerVO lb : lbs) { txn.start(); if (lb.getState() == FirewallRule.State.Revoke) { _lbDao.remove(lb.getId()); s_logger.debug("LB " + lb.getId() + " is successfully removed"); - } else if (lb.getState() == FirewallRule.State.Add) { + } else if (lb.getState() == FirewallRule.State.Add) { lb.setState(FirewallRule.State.Active); s_logger.debug("LB rule " + lb.getId() + " state is set to Active"); _lbDao.persist(lb); - } - - //remove LB-Vm mappings that were state to revoke + } + + // remove LB-Vm mappings that were state to revoke List lbVmMaps = _lb2VmMapDao.listByLoadBalancerId(lb.getId(), true); List instanceIds = new ArrayList(); - + for (LoadBalancerVMMapVO lbVmMap : lbVmMaps) { instanceIds.add(lbVmMap.getInstanceId()); } - + if (!instanceIds.isEmpty()) { _lb2VmMapDao.remove(lb.getId(), instanceIds, null); s_logger.debug("Load balancer rule id " + lb.getId() + " is removed for vms " + instanceIds); } - + if (_lb2VmMapDao.listByLoadBalancerId(lb.getId()).isEmpty()) { lb.setState(FirewallRule.State.Add); _lbDao.persist(lb); s_logger.debug("LB rule " + lb.getId() + " state is set to Add as there are no more active LB-VM mappings"); } - + txn.commit(); } return true; } @Override - public boolean removeAllLoadBalanacersForIp(long ipId, Account caller, long callerUserId) { + public boolean removeAllLoadBalanacersForIp(long ipId, Account caller, long callerUserId) { List rules = _rulesDao.listByIpAndPurposeAndNotRevoked(ipId, Purpose.LoadBalancing); if (rules != null) - s_logger.debug("Found " + rules.size() + " lb rules to cleanup"); - for (FirewallRule rule : rules) { + s_logger.debug("Found " + rules.size() + " lb rules to cleanup"); + for (FirewallRule rule : rules) { boolean result = deleteLoadBalancerRule(rule.getId(), true, caller, callerUserId); if (result == false) { s_logger.warn("Unable to remove load balancer rule " + rule.getId()); @@ -497,13 +502,13 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesManager, } return true; } - + @Override - public boolean removeAllLoadBalanacersForNetwork(long networkId, Account caller, long callerUserId) { + public boolean removeAllLoadBalanacersForNetwork(long networkId, Account caller, long callerUserId) { List rules = _rulesDao.listByNetworkAndPurposeAndNotRevoked(networkId, Purpose.LoadBalancing); if (rules != null) - s_logger.debug("Found " + rules.size() + " lb rules to cleanup"); - for (FirewallRule rule : rules) { + s_logger.debug("Found " + rules.size() + " lb rules to cleanup"); + for (FirewallRule rule : rules) { boolean result = deleteLoadBalancerRule(rule.getId(), true, caller, callerUserId); if (result == false) { s_logger.warn("Unable to remove load balancer rule " + rule.getId()); @@ -512,13 +517,13 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesManager, } return true; } - + @Override public List getExistingDestinations(long lbId) { List dstList = new ArrayList(); List lbVmMaps = _lb2VmMapDao.listByLoadBalancerId(lbId); LoadBalancerVO lb = _lbDao.findById(lbId); - + String dstIp = null; for (LoadBalancerVMMapVO lbVmMap : lbVmMaps) { UserVm vm = _vmDao.findById(lbVmMap.getInstanceId()); @@ -526,7 +531,7 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesManager, dstIp = nic.getIp4Address(); LbDestination lbDst = new LbDestination(lb.getDefaultPortStart(), lb.getDefaultPortEnd(), dstIp, lbVmMap.isRevoke()); dstList.add(lbDst); - } + } return dstList; } @@ -551,30 +556,30 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesManager, return _name; } - @Override @ActionEvent (eventType=EventTypes.EVENT_LOAD_BALANCER_UPDATE, eventDescription="updating load balancer", async=true) + @Override + @ActionEvent(eventType = EventTypes.EVENT_LOAD_BALANCER_UPDATE, eventDescription = "updating load balancer", async = true) public LoadBalancer updateLoadBalancerRule(UpdateLoadBalancerRuleCmd cmd) { Long lbRuleId = cmd.getId(); String name = cmd.getLoadBalancerName(); String description = cmd.getDescription(); String algorithm = cmd.getAlgorithm(); LoadBalancerVO lb = _lbDao.findById(lbRuleId); - - + if (name != null) { lb.setName(name); } - + if (description != null) { lb.setDescription(description); } - + if (algorithm != null) { lb.setAlgorithm(algorithm); } - + _lbDao.update(lbRuleId, lb); - - //If algorithm is changed, have to reapply the lb config + + // If algorithm is changed, have to reapply the lb config if (algorithm != null) { try { lb.setState(FirewallRule.State.Add); @@ -584,10 +589,10 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesManager, s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e); } } - + return lb; } - + @Override public List listLoadBalancerInstances(ListLoadBalancerRuleInstancesCmd cmd) throws PermissionDeniedException { Account caller = UserContext.current().getCaller(); @@ -602,7 +607,7 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesManager, if (loadBalancer == null) { return null; } - + _accountMgr.checkAccess(caller, loadBalancer); List loadBalancerInstances = new ArrayList(); @@ -633,7 +638,7 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesManager, boolean isApplied = appliedInstanceIdList.contains(userVm.getId()); if ((isApplied && applied) || (!isApplied && !applied)) { loadBalancerInstances.add(userVm); - } + } } return loadBalancerInstances; @@ -643,12 +648,13 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesManager, public List searchForLoadBalancers(ListLoadBalancerRulesCmd cmd) throws InvalidParameterValueException, PermissionDeniedException { Account caller = UserContext.current().getCaller(); Long ipId = cmd.getPublicIpId(); + Long zoneId = cmd.getZoneId(); String path = null; - + Pair accountDomainPair = _accountMgr.finalizeAccountDomainForList(caller, cmd.getAccountName(), cmd.getDomainId()); String accountName = accountDomainPair.first(); Long domainId = accountDomainPair.second(); - + if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) { Domain domain = _accountMgr.getDomain(caller.getDomainId()); path = domain.getPath(); @@ -673,14 +679,20 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesManager, lbVMSearch.and("instanceId", lbVMSearch.entity().getInstanceId(), SearchCriteria.Op.EQ); sb.join("lbVMSearch", lbVMSearch, sb.entity().getId(), lbVMSearch.entity().getLoadBalancerId(), 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); } + if (zoneId != null) { + SearchBuilder ipSearch = _ipAddressDao.createSearchBuilder(); + ipSearch.and("zoneId", ipSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); + sb.join("ipSearch", ipSearch, sb.entity().getSourceIpAddressId(), ipSearch.entity().getId(), JoinBuilder.JoinType.INNER); + } + SearchCriteria sc = sb.create(); if (keyword != null) { SearchCriteria ssc = _lbDao.createSearchCriteria(); @@ -705,7 +717,7 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesManager, if (instanceId != null) { sc.setJoinParameters("lbVMSearch", "instanceId", instanceId); } - + if (domainId != null) { sc.setParameters("domainId", domainId); if (accountName != null) { @@ -713,14 +725,18 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesManager, sc.setParameters("accountId", account.getId()); } } - + if (path != null) { sc.setJoinParameters("domainSearch", "path", path + "%"); } + if (zoneId != null) { + sc.setJoinParameters("ipSearch", "zoneId", zoneId); + } + return _lbDao.search(sc, searchFilter); } - + @Override public List listByNetworkId(long networkId) { List lbs = _lbDao.listByNetworkId(networkId); @@ -732,7 +748,7 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesManager, } return lbRules; } - + @Override public LoadBalancerVO findById(long lbId) { return _lbDao.findById(lbId);