diff --git a/.gitignore b/.gitignore index f50f2e3c9e6..d6f5d1c8feb 100644 --- a/.gitignore +++ b/.gitignore @@ -86,3 +86,4 @@ engine/storage/integration-test/test-output tools/apidoc/log/ log/ plugins/network-elements/juniper-contrail/logs/ +scripts/vm/hypervisor/xenserver/vhd-util diff --git a/LICENSE.header b/LICENSE.header new file mode 100644 index 00000000000..60b675e3101 --- /dev/null +++ b/LICENSE.header @@ -0,0 +1,16 @@ +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you under the Apache License, Version 2.0 (the +"License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, +software distributed under the License is distributed on an +"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, either express or implied. See the License for the +specific language governing permissions and limitations +under the License. diff --git a/agent/conf/agent.properties b/agent/conf/agent.properties index 5f5f3682afd..a7376b68947 100644 --- a/agent/conf/agent.properties +++ b/agent/conf/agent.properties @@ -114,3 +114,7 @@ domr.scripts.dir=scripts/network/domr/kvm # for examples:"Conroe" "Penryn", "Nehalem", "Westmere", "pentiumpro" and so # on,run virsh capabilities for more details. # guest.cpu.model= +# +# vm.memballoon.disable=true +# Disable memory ballooning on vm guests for overcommit, by default overcommit +# feature enables balloon and sets currentMemory to a minimum value. diff --git a/agent/pom.xml b/agent/pom.xml index 4e5caae80df..2036ae0ca39 100644 --- a/agent/pom.xml +++ b/agent/pom.xml @@ -115,38 +115,5 @@ - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - - org.apache.maven.plugins - - - maven-antrun-plugin - - [1.7,) - - run - - - - - - - - - - - - diff --git a/agent/src/com/cloud/agent/AgentShell.java b/agent/src/com/cloud/agent/AgentShell.java index 87004f9a1e4..210a8600fad 100644 --- a/agent/src/com/cloud/agent/AgentShell.java +++ b/agent/src/com/cloud/agent/AgentShell.java @@ -304,7 +304,7 @@ public class AgentShell implements IAgentShell, Daemon { // For KVM agent, do it specially here File file = new File("/etc/cloudstack/agent/log4j-cloud.xml"); - if(!file.exists()) { + if (!file.exists()) { file = PropertiesUtil.findConfigFile("log4j-cloud.xml"); } diff --git a/agent/src/com/cloud/agent/resource/DummyResource.java b/agent/src/com/cloud/agent/resource/DummyResource.java index 816f6ede569..73f8ef1a1e9 100755 --- a/agent/src/com/cloud/agent/resource/DummyResource.java +++ b/agent/src/com/cloud/agent/resource/DummyResource.java @@ -180,8 +180,8 @@ public class DummyResource implements ServerResource { return true; } - public void setParams(Map _params) { - this._params = _params; + public void setParams(Map params) { + this._params = params; } @Override diff --git a/scripts/network/domr/createipAlias.sh b/api/resources/META-INF/cloudstack/api-config/module.properties old mode 100755 new mode 100644 similarity index 74% rename from scripts/network/domr/createipAlias.sh rename to api/resources/META-INF/cloudstack/api-config/module.properties index c35658e6679..3b2a85d2743 --- a/scripts/network/domr/createipAlias.sh +++ b/api/resources/META-INF/cloudstack/api-config/module.properties @@ -1,4 +1,3 @@ -#!/usr/bin/env bash # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information @@ -15,12 +14,5 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. - - -usage() { - printf " %s routerip \n" $(basename $0) >&2 -} - -set -x -cert="/root/.ssh/id_rsa.cloud" -ssh -p 3922 -q -o StrictHostKeyChecking=no -i $cert root@$1 "/root/createIpAlias.sh $2" +name=api-config +parent=core diff --git a/api/resources/META-INF/cloudstack/api-config/spring-api-config-context.xml b/api/resources/META-INF/cloudstack/api-config/spring-api-config-context.xml new file mode 100644 index 00000000000..2cd12663072 --- /dev/null +++ b/api/resources/META-INF/cloudstack/api-config/spring-api-config-context.xml @@ -0,0 +1,32 @@ + + + + + + diff --git a/api/src/com/cloud/agent/api/to/IpAddressTO.java b/api/src/com/cloud/agent/api/to/IpAddressTO.java index 5f31313eba9..1169820e19a 100644 --- a/api/src/com/cloud/agent/api/to/IpAddressTO.java +++ b/api/src/com/cloud/agent/api/to/IpAddressTO.java @@ -33,6 +33,8 @@ public class IpAddressTO { private Integer networkRate; private TrafficType trafficType; private String networkName; + private Integer nicDevId; + private boolean newNic; public IpAddressTO(long accountId, String ipAddress, boolean add, boolean firstIP, boolean sourceNat, String broadcastUri, String vlanGateway, String vlanNetmask, String vifMacAddress, Integer networkRate, boolean isOneToOneNat) { @@ -116,4 +118,19 @@ public class IpAddressTO { return networkRate; } + public Integer getNicDevId() { + return nicDevId; + } + + public void setNicDevId(Integer nicDevId) { + this.nicDevId = nicDevId; + } + + public boolean isNewNic() { + return newNic; + } + + public void setNewNic(boolean newNic) { + this.newNic = newNic; + } } diff --git a/api/src/com/cloud/agent/api/to/NfsTO.java b/api/src/com/cloud/agent/api/to/NfsTO.java index ee6c3e3566d..1c9ee38e017 100644 --- a/api/src/com/cloud/agent/api/to/NfsTO.java +++ b/api/src/com/cloud/agent/api/to/NfsTO.java @@ -44,8 +44,8 @@ public class NfsTO implements DataStoreTO { return _url; } - public void setUrl(String _url) { - this._url = _url; + public void setUrl(String url) { + this._url = url; } @Override @@ -53,8 +53,8 @@ public class NfsTO implements DataStoreTO { return _role; } - public void setRole(DataStoreRole _role) { - this._role = _role; + public void setRole(DataStoreRole role) { + this._role = role; } @Override diff --git a/api/src/com/cloud/agent/api/to/VolumeTO.java b/api/src/com/cloud/agent/api/to/VolumeTO.java index eb1d9181cdf..2ad5e0b26f7 100644 --- a/api/src/com/cloud/agent/api/to/VolumeTO.java +++ b/api/src/com/cloud/agent/api/to/VolumeTO.java @@ -129,15 +129,15 @@ public class VolumeTO implements InternalIdentity { public String getChainInfo() { return chainInfo; } - + public void setChainInfo(String chainInfo) { - this.chainInfo = chainInfo; + this.chainInfo = chainInfo; } public String getOsType() { return guestOsType; } - + public void setPath(String path) { this.path = path; } diff --git a/api/src/com/cloud/alert/Alert.java b/api/src/com/cloud/alert/Alert.java index 6555b6fded1..f77442068d6 100644 --- a/api/src/com/cloud/alert/Alert.java +++ b/api/src/com/cloud/alert/Alert.java @@ -39,5 +39,6 @@ public interface Alert extends Identity, InternalIdentity { Date getResolved(); boolean getArchived(); + String getName(); } diff --git a/api/src/com/cloud/deploy/DeployDestination.java b/api/src/com/cloud/deploy/DeployDestination.java index 05625d60b0f..4ded5ebe7a1 100644 --- a/api/src/com/cloud/deploy/DeployDestination.java +++ b/api/src/com/cloud/deploy/DeployDestination.java @@ -16,6 +16,7 @@ // under the License. package com.cloud.deploy; +import java.io.Serializable; import java.util.Map; import com.cloud.dc.DataCenter; @@ -26,7 +27,9 @@ import com.cloud.storage.StoragePool; import com.cloud.storage.Volume; import com.cloud.utils.NumbersUtil; -public class DeployDestination { +public class DeployDestination implements Serializable { + private static final long serialVersionUID = 7113840781939014695L; + DataCenter _dc; Pod _pod; Cluster _cluster; @@ -76,28 +79,28 @@ public class DeployDestination { @Override public boolean equals(Object obj) { DeployDestination that = (DeployDestination)obj; - if (this._dc == null || that._dc == null) { + if (_dc == null || that._dc == null) { return false; } - if (this._dc.getId() != that._dc.getId()) { + if (_dc.getId() != that._dc.getId()) { return false; } - if (this._pod == null || that._pod == null) { + if (_pod == null || that._pod == null) { return false; } - if (this._pod.getId() != that._pod.getId()) { + if (_pod.getId() != that._pod.getId()) { return false; } - if (this._cluster == null || that._cluster == null) { + if (_cluster == null || that._cluster == null) { return false; } - if (this._cluster.getId() != that._cluster.getId()) { + if (_cluster.getId() != that._cluster.getId()) { return false; } - if (this._host == null || that._host == null) { + if (_host == null || that._host == null) { return false; } - return this._host.getId() == that._host.getId(); + return _host.getId() == that._host.getId(); } @Override diff --git a/api/src/com/cloud/deploy/DeploymentPlanner.java b/api/src/com/cloud/deploy/DeploymentPlanner.java index 6916a5bc350..eb62cb178bb 100644 --- a/api/src/com/cloud/deploy/DeploymentPlanner.java +++ b/api/src/com/cloud/deploy/DeploymentPlanner.java @@ -16,6 +16,7 @@ // under the License. package com.cloud.deploy; +import java.io.Serializable; import java.util.Collection; import java.util.HashSet; import java.util.Set; @@ -89,7 +90,9 @@ public interface DeploymentPlanner extends Adapter { Shared, Dedicated; } - public static class ExcludeList { + public static class ExcludeList implements Serializable { + private static final long serialVersionUID = -482175549460148301L; + private Set _dcIds; private Set _podIds; private Set _clusterIds; @@ -99,22 +102,22 @@ public interface DeploymentPlanner extends Adapter { public ExcludeList() { } - public ExcludeList(Set _dcIds, Set _podIds, Set _clusterIds, Set _hostIds, Set _poolIds) { - if (_dcIds != null) { - this._dcIds = new HashSet(_dcIds); + public ExcludeList(Set dcIds, Set podIds, Set clusterIds, Set hostIds, Set poolIds) { + if (dcIds != null) { + this._dcIds = new HashSet(dcIds); } - if (_podIds != null) { - this._podIds = new HashSet(_podIds); + if (podIds != null) { + this._podIds = new HashSet(podIds); } - if (_clusterIds != null) { - this._clusterIds = new HashSet(_clusterIds); + if (clusterIds != null) { + this._clusterIds = new HashSet(clusterIds); } - if (_hostIds != null) { - this._hostIds = new HashSet(_hostIds); + if (hostIds != null) { + this._hostIds = new HashSet(hostIds); } - if (_poolIds != null) { - this._poolIds = new HashSet(_poolIds); + if (poolIds != null) { + this._poolIds = new HashSet(poolIds); } } @@ -173,6 +176,12 @@ public interface DeploymentPlanner extends Adapter { _poolIds.add(poolId); } + public void removePool(long poolId) { + if (_poolIds != null) { + _poolIds.remove(poolId); + } + } + public void addDataCenter(long dataCenterId) { if (_dcIds == null) { _dcIds = new HashSet(); diff --git a/api/src/com/cloud/deploy/HAPlanner.java b/api/src/com/cloud/deploy/HAPlanner.java new file mode 100644 index 00000000000..aeb5083c522 --- /dev/null +++ b/api/src/com/cloud/deploy/HAPlanner.java @@ -0,0 +1,21 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.deploy; + + +public interface HAPlanner extends DeploymentPlanner { +} \ No newline at end of file diff --git a/api/src/com/cloud/event/EventTypes.java b/api/src/com/cloud/event/EventTypes.java index d3c29e93028..e88f0104ea7 100755 --- a/api/src/com/cloud/event/EventTypes.java +++ b/api/src/com/cloud/event/EventTypes.java @@ -455,7 +455,11 @@ public class EventTypes { //Alert generation public static final String ALERT_GENERATE = "ALERT.GENERATE"; - + // OpenDaylight + public static final String EVENT_EXTERNAL_OPENDAYLIGHT_ADD_CONTROLLER = "PHYSICAL.ODLCONTROLLER.ADD"; + public static final String EVENT_EXTERNAL_OPENDAYLIGHT_DELETE_CONTROLLER = "PHYSICAL.ODLCONTROLLER.DELETE"; + public static final String EVENT_EXTERNAL_OPENDAYLIGHT_CONFIGURE_CONTROLLER = "PHYSICAL.ODLCONTROLLER.CONFIGURE"; + static { // TODO: need a way to force author adding event types to declare the entity details as well, with out braking @@ -761,6 +765,11 @@ public class EventTypes { entityEventDetails.put(EVENT_AUTOSCALEVMGROUP_DISABLE, AutoScaleVmGroup.class.getName()); entityEventDetails.put(EVENT_GUEST_VLAN_RANGE_DEDICATE, GuestVlan.class.getName()); entityEventDetails.put(EVENT_DEDICATED_GUEST_VLAN_RANGE_RELEASE, GuestVlan.class.getName()); + + // OpenDaylight + entityEventDetails.put(EVENT_EXTERNAL_OPENDAYLIGHT_ADD_CONTROLLER, "OpenDaylightController"); + entityEventDetails.put(EVENT_EXTERNAL_OPENDAYLIGHT_DELETE_CONTROLLER, "OpenDaylightController"); + entityEventDetails.put(EVENT_EXTERNAL_OPENDAYLIGHT_CONFIGURE_CONTROLLER, "OpenDaylightController"); } public static String getEntityForEvent(String eventName) { diff --git a/api/src/com/cloud/exception/CloudException.java b/api/src/com/cloud/exception/CloudException.java index f898719028b..f35249b0732 100644 --- a/api/src/com/cloud/exception/CloudException.java +++ b/api/src/com/cloud/exception/CloudException.java @@ -27,6 +27,7 @@ import com.cloud.utils.exception.CSExceptionErrorCode; */ public class CloudException extends Exception { + private static final long serialVersionUID = 8784427323859682503L; // This holds a list of uuids and their names. Add uuid:fieldname pairs protected ArrayList idList = new ArrayList(); @@ -58,10 +59,10 @@ public class CloudException extends Exception { } public void setCSErrorCode(int cserrcode) { - this.csErrorCode = cserrcode; + csErrorCode = cserrcode; } public int getCSErrorCode() { - return this.csErrorCode; + return csErrorCode; } } diff --git a/api/src/com/cloud/exception/OperationTimedoutException.java b/api/src/com/cloud/exception/OperationTimedoutException.java index d531c326c37..fe27408eb4e 100644 --- a/api/src/com/cloud/exception/OperationTimedoutException.java +++ b/api/src/com/cloud/exception/OperationTimedoutException.java @@ -28,7 +28,15 @@ public class OperationTimedoutException extends CloudException { long _agentId; long _seqId; int _time; - Command[] _cmds; + + // TODO + // I did a reference search on usage of getCommands() and found none + // + // to prevent serialization problems across boundaries, I'm disabling serialization of _cmds here + // getCommands() will still be available within the same serialization boundary, but it will be lost + // when exception is propagated across job boundaries. + // + transient Command[] _cmds; boolean _isActive; public OperationTimedoutException(Command[] cmds, long agentId, long seqId, int time, boolean isActive) { diff --git a/api/src/com/cloud/host/Host.java b/api/src/com/cloud/host/Host.java index 9d811255e14..689ed12b64e 100755 --- a/api/src/com/cloud/host/Host.java +++ b/api/src/com/cloud/host/Host.java @@ -78,6 +78,11 @@ public interface Host extends StateObject, Identity, InternalIdentity { */ String getPrivateIpAddress(); + /** + * @return the ip address of the host. + */ + String getStorageUrl(); + /** * @return the ip address of the host attached to the storage network. */ diff --git a/api/src/com/cloud/hypervisor/HypervisorGuru.java b/api/src/com/cloud/hypervisor/HypervisorGuru.java index 03493726176..4a35cecb887 100644 --- a/api/src/com/cloud/hypervisor/HypervisorGuru.java +++ b/api/src/com/cloud/hypervisor/HypervisorGuru.java @@ -75,4 +75,6 @@ public interface HypervisorGuru extends Adapter { * */ List finalizeExpungeNics(VirtualMachine vm, List nics); + + List finalizeExpungeVolumes(VirtualMachine vm); } diff --git a/api/src/com/cloud/network/Network.java b/api/src/com/cloud/network/Network.java index d19c999f16e..62151a4f0c0 100644 --- a/api/src/com/cloud/network/Network.java +++ b/api/src/com/cloud/network/Network.java @@ -16,6 +16,7 @@ // under the License. package com.cloud.network; +import java.io.Serializable; import java.net.URI; import java.util.ArrayList; import java.util.List; @@ -33,7 +34,7 @@ import com.cloud.utils.fsm.StateObject; /** * owned by an account. */ -public interface Network extends ControlledEntity, StateObject, InternalIdentity, Identity { +public interface Network extends ControlledEntity, StateObject, InternalIdentity, Identity, Serializable { public enum GuestType { Shared, Isolated @@ -47,9 +48,9 @@ public interface Network extends ControlledEntity, StateObject, I public static final Service Dns = new Service("Dns", Capability.AllowDnsSuffixModification); public static final Service Gateway = new Service("Gateway"); public static final Service Firewall = new Service("Firewall", Capability.SupportedProtocols, Capability.MultipleIps, Capability.TrafficStatistics, - Capability.SupportedTrafficDirection, Capability.SupportedEgressProtocols); + Capability.SupportedTrafficDirection, Capability.SupportedEgressProtocols); public static final Service Lb = new Service("Lb", Capability.SupportedLBAlgorithms, Capability.SupportedLBIsolation, Capability.SupportedProtocols, - Capability.TrafficStatistics, Capability.LoadBalancingSupportedIps, Capability.SupportedStickinessMethods, Capability.ElasticLb, Capability.LbSchemes); + Capability.TrafficStatistics, Capability.LoadBalancingSupportedIps, Capability.SupportedStickinessMethods, Capability.ElasticLb, Capability.LbSchemes); public static final Service UserData = new Service("UserData"); public static final Service SourceNat = new Service("SourceNat", Capability.SupportedSourceNatTypes, Capability.RedundantRouter); public static final Service StaticNat = new Service("StaticNat", Capability.ElasticIp); @@ -111,7 +112,7 @@ public interface Network extends ControlledEntity, StateObject, I private static List supportedProviders = new ArrayList(); public static final Provider VirtualRouter = new Provider("VirtualRouter", false); - public static final Provider JuniperContrail = new Provider("JuniperContrail", false); + public static final Provider JuniperContrailRouter = new Provider("JuniperContrailRouter", false); public static final Provider JuniperSRX = new Provider("JuniperSRX", true); public static final Provider PaloAlto = new Provider("PaloAlto", true); public static final Provider F5BigIp = new Provider("F5BigIp", true); @@ -128,6 +129,7 @@ public interface Network extends ControlledEntity, StateObject, I public static final Provider CiscoVnmc = new Provider("CiscoVnmc", true); // add new Ovs provider public static final Provider Ovs = new Provider("Ovs", false); + public static final Provider Opendaylight = new Provider("Opendaylight", false); private final String name; private final boolean isExternal; @@ -213,7 +215,7 @@ public interface Network extends ControlledEntity, StateObject, I Allocated("Indicates the network configuration is in allocated but not setup"), Setup("Indicates the network configuration is setup"), Implementing( "Indicates the network configuration is being implemented"), Implemented("Indicates the network configuration is in use"), Shutdown( - "Indicates the network configuration is being destroyed"), Destroy("Indicates that the network is destroyed"); + "Indicates the network configuration is being destroyed"), Destroy("Indicates that the network is destroyed"); protected static final StateMachine2 s_fsm = new StateMachine2(); @@ -223,7 +225,7 @@ public interface Network extends ControlledEntity, StateObject, I s_fsm.addTransition(State.Implementing, Event.OperationFailed, State.Shutdown); s_fsm.addTransition(State.Implemented, Event.DestroyNetwork, State.Shutdown); s_fsm.addTransition(State.Shutdown, Event.OperationSucceeded, State.Allocated); - s_fsm.addTransition(State.Shutdown, Event.OperationFailed, State.Implemented); + s_fsm.addTransition(State.Shutdown, Event.OperationFailed, State.Shutdown); s_fsm.addTransition(State.Setup, Event.DestroyNetwork, State.Destroy); s_fsm.addTransition(State.Allocated, Event.DestroyNetwork, State.Destroy); } diff --git a/api/src/com/cloud/network/NetworkModel.java b/api/src/com/cloud/network/NetworkModel.java index fcb6a2e58f4..f6555db565e 100644 --- a/api/src/com/cloud/network/NetworkModel.java +++ b/api/src/com/cloud/network/NetworkModel.java @@ -60,6 +60,8 @@ public interface NetworkModel { */ List listPublicIpsAssignedToGuestNtwk(long accountId, long associatedNetworkId, Boolean sourceNat); + List listPublicIpsAssignedToGuestNtwk(long associatedNetworkId, Boolean sourceNat); + List getSystemAccountNetworkOfferings(String... offeringNames); List getNics(long vmId); diff --git a/api/src/com/cloud/network/NetworkService.java b/api/src/com/cloud/network/NetworkService.java index 57e95c947cd..1731b119d5e 100755 --- a/api/src/com/cloud/network/NetworkService.java +++ b/api/src/com/cloud/network/NetworkService.java @@ -62,9 +62,9 @@ public interface NetworkService { Network createGuestNetwork(CreateNetworkCmd cmd) throws InsufficientCapacityException, ConcurrentOperationException, ResourceAllocationException; - List searchForNetworks(ListNetworksCmd cmd); + Pair, Integer> searchForNetworks(ListNetworksCmd cmd); - boolean deleteNetwork(long networkId); + boolean deleteNetwork(long networkId, boolean forced); boolean restartNetwork(RestartNetworkCmd cmd, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; @@ -110,7 +110,7 @@ public interface NetworkService { long findPhysicalNetworkId(long zoneId, String tag, TrafficType trafficType); - PhysicalNetworkTrafficType addTrafficTypeToPhysicalNetwork(Long physicalNetworkId, String trafficType, String xenLabel, String kvmLabel, String vmwareLabel, + PhysicalNetworkTrafficType addTrafficTypeToPhysicalNetwork(Long physicalNetworkId, String trafficType, String isolationMethod, String xenLabel, String kvmLabel, String vmwareLabel, String simulatorLabel, String vlan, String hypervLabel); PhysicalNetworkTrafficType getPhysicalNetworkTrafficType(Long id); @@ -168,7 +168,7 @@ public interface NetworkService { InsufficientCapacityException; /* Requests an IP address for the guest nic */ - NicSecondaryIp allocateSecondaryGuestIP(Account account, long zoneId, Long nicId, Long networkId, String ipaddress) throws InsufficientAddressCapacityException; + NicSecondaryIp allocateSecondaryGuestIP(long nicId, String ipaddress) throws InsufficientAddressCapacityException; boolean releaseSecondaryIpFromNic(long ipAddressId); diff --git a/api/src/com/cloud/network/Networks.java b/api/src/com/cloud/network/Networks.java index e15ed463657..1e4d2294641 100755 --- a/api/src/com/cloud/network/Networks.java +++ b/api/src/com/cloud/network/Networks.java @@ -31,7 +31,7 @@ public class Networks { None, DcGlobal, // global to data center HostLocal; - public static String DummyPrivateIp = "169.254.1.1"; + public static final String DummyPrivateIp = "169.254.1.1"; } /** @@ -94,7 +94,22 @@ public class Networks { return uri.getSchemeSpecificPart(); } }, - Mido("mido", String.class), Pvlan("pvlan", String.class), Vxlan("vxlan", Long.class), UnDecided(null, null); + Mido("mido", String.class), Pvlan("pvlan", String.class), + Vxlan("vxlan", Long.class) { + @Override + public URI toUri(T value) { + try { + if (value.toString().contains("://")) + return new URI(value.toString()); + else + return new URI("vxlan://" + value.toString()); + } catch (URISyntaxException e) { + throw new CloudRuntimeException( + "Unable to convert to broadcast URI: " + value); + } + } + }, + UnDecided(null, null), OpenDaylight("opendaylight", String.class); private final String scheme; private final Class type; diff --git a/api/src/com/cloud/network/OvsProvider.java b/api/src/com/cloud/network/OvsProvider.java index e20491a3a2d..dfa40912417 100644 --- a/api/src/com/cloud/network/OvsProvider.java +++ b/api/src/com/cloud/network/OvsProvider.java @@ -20,7 +20,7 @@ import org.apache.cloudstack.api.Identity; import org.apache.cloudstack.api.InternalIdentity; public interface OvsProvider extends InternalIdentity, Identity { - public boolean isEnabled(); + public boolean isEnabled(); - public long getNspId(); + public long getNspId(); } diff --git a/api/src/com/cloud/network/PhysicalNetwork.java b/api/src/com/cloud/network/PhysicalNetwork.java index cfa236d3898..8cc214e894b 100644 --- a/api/src/com/cloud/network/PhysicalNetwork.java +++ b/api/src/com/cloud/network/PhysicalNetwork.java @@ -33,7 +33,7 @@ public interface PhysicalNetwork extends Identity, InternalIdentity { } public enum IsolationMethod { - VLAN, L3, GRE, STT, VNS, MIDO, SSP, VXLAN; + VLAN, L3, GRE, STT, VNS, MIDO, SSP, VXLAN, ODL, L3VPN; } public enum BroadcastDomainRange { diff --git a/api/src/com/cloud/network/VirtualNetworkApplianceService.java b/api/src/com/cloud/network/VirtualNetworkApplianceService.java index 96162f31949..a9d9c527f40 100644 --- a/api/src/com/cloud/network/VirtualNetworkApplianceService.java +++ b/api/src/com/cloud/network/VirtualNetworkApplianceService.java @@ -69,5 +69,5 @@ public interface VirtualNetworkApplianceService { List upgradeRouterTemplate(UpgradeRouterTemplateCmd cmd); - public static final String _minVRVersion = "4.2.0"; + public static final String MinVRVersion = "4.3.0"; } diff --git a/api/src/com/cloud/network/as/AutoScalePolicy.java b/api/src/com/cloud/network/as/AutoScalePolicy.java index 8452ba1492c..56ea3f5f7f7 100644 --- a/api/src/com/cloud/network/as/AutoScalePolicy.java +++ b/api/src/com/cloud/network/as/AutoScalePolicy.java @@ -32,8 +32,8 @@ public interface AutoScalePolicy extends ControlledEntity, InternalIdentity { public int getDuration(); public int getQuietTime(); - - public Date getLastQuiteTime(); + + public Date getLastQuiteTime(); public String getAction(); diff --git a/api/src/com/cloud/network/as/AutoScaleVmGroup.java b/api/src/com/cloud/network/as/AutoScaleVmGroup.java index 15f7bea9a4d..e8b328fc267 100644 --- a/api/src/com/cloud/network/as/AutoScaleVmGroup.java +++ b/api/src/com/cloud/network/as/AutoScaleVmGroup.java @@ -47,7 +47,7 @@ public interface AutoScaleVmGroup extends ControlledEntity, InternalIdentity { int getInterval(); - Date getLastInterval(); + Date getLastInterval(); String getState(); diff --git a/api/src/com/cloud/network/as/Counter.java b/api/src/com/cloud/network/as/Counter.java index 99b3364419a..286bf517c79 100644 --- a/api/src/com/cloud/network/as/Counter.java +++ b/api/src/com/cloud/network/as/Counter.java @@ -34,5 +34,5 @@ public interface Counter extends InternalIdentity, Identity { String getValue(); Source getSource(); - + } diff --git a/api/src/com/cloud/network/element/NetworkElement.java b/api/src/com/cloud/network/element/NetworkElement.java index e7988bf08da..951732f727c 100644 --- a/api/src/com/cloud/network/element/NetworkElement.java +++ b/api/src/com/cloud/network/element/NetworkElement.java @@ -22,7 +22,6 @@ import java.util.Set; import com.cloud.deploy.DeployDestination; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InsufficientNetworkCapacityException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network; import com.cloud.network.Network.Capability; @@ -67,7 +66,6 @@ public interface NetworkElement extends Adapter { * @return * @throws ConcurrentOperationException * @throws ResourceUnavailableException - * @throws InsufficientNetworkCapacityException */ boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; diff --git a/api/src/com/cloud/network/element/UserDataServiceProvider.java b/api/src/com/cloud/network/element/UserDataServiceProvider.java index ad485a5b7ab..45ab0d877a3 100644 --- a/api/src/com/cloud/network/element/UserDataServiceProvider.java +++ b/api/src/com/cloud/network/element/UserDataServiceProvider.java @@ -33,5 +33,5 @@ public interface UserDataServiceProvider extends NetworkElement { boolean saveUserData(Network network, NicProfile nic, VirtualMachineProfile vm) throws ResourceUnavailableException; - boolean saveSSHKey(Network network, NicProfile nic, VirtualMachineProfile vm, String SSHPublicKey) throws ResourceUnavailableException; + boolean saveSSHKey(Network network, NicProfile nic, VirtualMachineProfile vm, String sshPublicKey) throws ResourceUnavailableException; } diff --git a/api/src/com/cloud/network/element/VirtualRouterElementService.java b/api/src/com/cloud/network/element/VirtualRouterElementService.java index c8d45cafe53..f8e015088db 100644 --- a/api/src/com/cloud/network/element/VirtualRouterElementService.java +++ b/api/src/com/cloud/network/element/VirtualRouterElementService.java @@ -31,12 +31,13 @@ import com.cloud.utils.component.PluggableService; public interface VirtualRouterElementService extends PluggableService { VirtualRouterProvider configure(ConfigureVirtualRouterElementCmd cmd); - OvsProvider configure(ConfigureOvsElementCmd cmd); + OvsProvider configure(ConfigureOvsElementCmd cmd); + VirtualRouterProvider addElement(Long nspId, Type providerType); VirtualRouterProvider getCreatedElement(long id); List searchForVirtualRouterElement(ListVirtualRouterElementsCmd cmd); - List searchForOvsElement(ListOvsElementsCmd cmd); + List searchForOvsElement(ListOvsElementsCmd cmd); } diff --git a/api/src/com/cloud/network/firewall/FirewallService.java b/api/src/com/cloud/network/firewall/FirewallService.java index 3413c4d4fb8..917bda3de6d 100644 --- a/api/src/com/cloud/network/firewall/FirewallService.java +++ b/api/src/com/cloud/network/firewall/FirewallService.java @@ -44,7 +44,7 @@ public interface FirewallService { boolean applyEgressFirewallRules(FirewallRule rule, Account caller) throws ResourceUnavailableException; - boolean applyIngressFirewallRules(long Ipid, Account caller) throws ResourceUnavailableException; + boolean applyIngressFirewallRules(long ipId, Account caller) throws ResourceUnavailableException; FirewallRule getFirewallRule(long ruleId); diff --git a/api/src/com/cloud/network/lb/LoadBalancingRulesService.java b/api/src/com/cloud/network/lb/LoadBalancingRulesService.java index e62b45cbb1c..cd0a276c73c 100644 --- a/api/src/com/cloud/network/lb/LoadBalancingRulesService.java +++ b/api/src/com/cloud/network/lb/LoadBalancingRulesService.java @@ -101,7 +101,7 @@ public interface LoadBalancingRulesService { boolean applyLoadBalancerConfig(long lbRuleId) throws ResourceUnavailableException; - boolean assignCertToLoadBalancer(long lbRuleId, Long CertId); + boolean assignCertToLoadBalancer(long lbRuleId, Long certId); boolean removeCertFromLoadBalancer(long lbRuleId); @@ -145,7 +145,7 @@ public interface LoadBalancingRulesService { List searchForLBHealthCheckPolicies(ListLBHealthCheckPoliciesCmd cmd); - LoadBalancer findById(long LoadBalancer); + LoadBalancer findById(long loadBalancer); public void updateLBHealthChecks(Scheme scheme) throws ResourceUnavailableException; diff --git a/api/src/com/cloud/network/rules/FirewallRule.java b/api/src/com/cloud/network/rules/FirewallRule.java index 4cfa42b3770..274242ad394 100644 --- a/api/src/com/cloud/network/rules/FirewallRule.java +++ b/api/src/com/cloud/network/rules/FirewallRule.java @@ -36,7 +36,8 @@ public interface FirewallRule extends ControlledEntity, Identity, InternalIdenti Staged, // Rule been created but has never got through network rule conflict detection. Rules in this state can not be sent to network elements. Add, // Add means the rule has been created and has gone through network rule conflict detection. Active, // Rule has been sent to the network elements and reported to be active. - Revoke // Revoke means this rule has been revoked. If this rule has been sent to the network elements, the rule will be deleted from database. + Revoke, // Revoke means this rule has been revoked. If this rule has been sent to the network elements, the rule will be deleted from database. + Deleting // rule has been revoked and is scheduled for deletion } enum TrafficType { diff --git a/api/src/com/cloud/network/security/SecurityGroupService.java b/api/src/com/cloud/network/security/SecurityGroupService.java index 1ee504fb9a4..d8b3346f54a 100644 --- a/api/src/com/cloud/network/security/SecurityGroupService.java +++ b/api/src/com/cloud/network/security/SecurityGroupService.java @@ -47,5 +47,5 @@ public interface SecurityGroupService { public List authorizeSecurityGroupEgress(AuthorizeSecurityGroupEgressCmd cmd); - public boolean securityGroupRulesForVmSecIp(Long nicId, Long networkId, String secondaryIp, boolean ruleAction); + public boolean securityGroupRulesForVmSecIp(long nicId, String secondaryIp, boolean ruleAction); } diff --git a/api/src/com/cloud/network/vpc/NetworkACLService.java b/api/src/com/cloud/network/vpc/NetworkACLService.java index db37833e4f0..4d1188018b5 100644 --- a/api/src/com/cloud/network/vpc/NetworkACLService.java +++ b/api/src/com/cloud/network/vpc/NetworkACLService.java @@ -47,7 +47,7 @@ public interface NetworkACLService { * @param cmd * @return */ - Pair,Integer> listNetworkACLs(ListNetworkACLListsCmd cmd); + Pair, Integer> listNetworkACLs(ListNetworkACLListsCmd cmd); /** * Delete specified network ACL. Deletion fails if the list is not empty diff --git a/api/src/com/cloud/network/vpc/StaticRoute.java b/api/src/com/cloud/network/vpc/StaticRoute.java index ccdbec899b8..5707ca14024 100644 --- a/api/src/com/cloud/network/vpc/StaticRoute.java +++ b/api/src/com/cloud/network/vpc/StaticRoute.java @@ -25,7 +25,8 @@ public interface StaticRoute extends ControlledEntity, Identity, InternalIdentit Staged, // route been created but has never got through network rule conflict detection. Routes in this state can not be sent to VPC virtual router. Add, // Add means the route has been created and has gone through network rule conflict detection. Active, // Route has been sent to the VPC router and reported to be active. - Revoke // Revoke means this route has been revoked. If this route has been sent to the VPC router, the route will be deleted from database. + Revoke, // Revoke means this route has been revoked. If this route has been sent to the VPC router, the route will be deleted from database. + Deleting // rule has been revoked and is scheduled for deletion } /** diff --git a/api/src/com/cloud/offering/DiskOffering.java b/api/src/com/cloud/offering/DiskOffering.java index 2227fd711c9..4641b9a4ad8 100644 --- a/api/src/com/cloud/offering/DiskOffering.java +++ b/api/src/com/cloud/offering/DiskOffering.java @@ -36,7 +36,7 @@ public interface DiskOffering extends InfrastructureEntity, Identity, InternalId public enum DiskCacheMode { NONE("none"), WRITEBACK("writeback"), WRITETHROUGH("writethrough"); - + private final String _diskCacheMode; DiskCacheMode(String cacheMode) { diff --git a/api/src/com/cloud/region/ha/GlobalLoadBalancerRule.java b/api/src/com/cloud/region/ha/GlobalLoadBalancerRule.java index c5fd9aed2b6..bb311f36e6f 100644 --- a/api/src/com/cloud/region/ha/GlobalLoadBalancerRule.java +++ b/api/src/com/cloud/region/ha/GlobalLoadBalancerRule.java @@ -53,8 +53,8 @@ public interface GlobalLoadBalancerRule extends Identity, InternalIdentity, Cont tcp, udp, http; public static boolean isValidServiceType(String serviceType) { if (tcp.name().equalsIgnoreCase(serviceType) || - udp.name().equalsIgnoreCase(serviceType) || - http.name().equalsIgnoreCase(serviceType)) { + udp.name().equalsIgnoreCase(serviceType) || + http.name().equalsIgnoreCase(serviceType)) { return true; } return false; diff --git a/api/src/com/cloud/server/ResourceTag.java b/api/src/com/cloud/server/ResourceTag.java index 6d18834c6b5..a08c3e4fede 100644 --- a/api/src/com/cloud/server/ResourceTag.java +++ b/api/src/com/cloud/server/ResourceTag.java @@ -46,22 +46,28 @@ public interface ResourceTag extends ControlledEntity, Identity, InternalIdentit ServiceOffering(false, true), Storage(false, true), PrivateGateway(false, true), - NetworkACLList(false, true); + NetworkACLList(false, true), + VpnGateway(false, true), + CustomerGateway(false, true), + VpnConnection(false, true), + User(true, true), + DiskOffering(false, true), + AutoScaleVmProfile(false, true); ResourceObjectType(boolean resourceTagsSupport, boolean resourceMetadataSupport) { this.resourceTagsSupport = resourceTagsSupport; - this.metadataSupport = resourceMetadataSupport; + metadataSupport = resourceMetadataSupport; } private final boolean resourceTagsSupport; private final boolean metadataSupport; public boolean resourceTagsSupport() { - return this.resourceTagsSupport; + return resourceTagsSupport; } public boolean resourceMetadataSupport() { - return this.metadataSupport; + return metadataSupport; } } diff --git a/api/src/com/cloud/storage/DataStoreRole.java b/api/src/com/cloud/storage/DataStoreRole.java index 0a62a569e55..cc20cc0ce96 100644 --- a/api/src/com/cloud/storage/DataStoreRole.java +++ b/api/src/com/cloud/storage/DataStoreRole.java @@ -24,13 +24,13 @@ public enum DataStoreRole { Primary("primary"), Image("image"), ImageCache("imagecache"), Backup("backup"); public boolean isImageStore() { - return (this.role.equalsIgnoreCase("image") || this.role.equalsIgnoreCase("imagecache")) ? true : false; + return (role.equalsIgnoreCase("image") || role.equalsIgnoreCase("imagecache")) ? true : false; } private final String role; DataStoreRole(String type) { - this.role = type; + role = type; } public static DataStoreRole getRole(String role) { diff --git a/api/src/com/cloud/storage/Storage.java b/api/src/com/cloud/storage/Storage.java index f1868a7a1b3..2175c9b1a0c 100755 --- a/api/src/com/cloud/storage/Storage.java +++ b/api/src/com/cloud/storage/Storage.java @@ -28,6 +28,8 @@ public class Storage { OVA(true, true, true, "ova"), VHDX(true, true, true, "vhdx"), BAREMETAL(false, false, false, "BAREMETAL"), + VMDK(true, true, false, "vmdk"), + VDI(true, true, false, "vdi"), TAR(false, false, false, "tar"); private final boolean thinProvisioned; diff --git a/api/src/com/cloud/storage/StorageService.java b/api/src/com/cloud/storage/StorageService.java index ac3c385695f..7fc1e16ff3a 100644 --- a/api/src/com/cloud/storage/StorageService.java +++ b/api/src/com/cloud/storage/StorageService.java @@ -17,8 +17,8 @@ package com.cloud.storage; import java.net.UnknownHostException; +import java.util.Map; -import org.apache.cloudstack.api.command.admin.storage.AddImageStoreCmd; import org.apache.cloudstack.api.command.admin.storage.CancelPrimaryStorageMaintenanceCmd; import org.apache.cloudstack.api.command.admin.storage.CreateSecondaryStagingStoreCmd; import org.apache.cloudstack.api.command.admin.storage.CreateStoragePoolCmd; @@ -92,19 +92,23 @@ public interface StorageService { boolean deleteSecondaryStagingStore(DeleteSecondaryStagingStoreCmd cmd); - ImageStore discoverImageStore(AddImageStoreCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException; + public ImageStore discoverImageStore(String name, String url, String providerName, Long dcId, Map details) throws IllegalArgumentException, DiscoveryException, + InvalidParameterValueException; - /** - * Prepare NFS secondary storage for object store migration - * - * @param cmd - * - the command specifying secondaryStorageId - * @return the storage pool - * @throws ResourceUnavailableException - * TODO - * @throws InsufficientCapacityException - * TODO + + /** + * Migrate existing NFS to use object store. + * @param name object store name. + * @param url object store url. + * @param providerName object store provider Name. + * @param details object store other details + * @return Object store created. + * @throws IllegalArgumentException + * @throws DiscoveryException + * @throws InvalidParameterValueException */ - public ImageStore prepareSecondaryStorageForObjectStoreMigration(Long storeId) throws ResourceUnavailableException, InsufficientCapacityException; + public ImageStore migrateToObjectStore(String name, String url, String providerName, Map details) throws IllegalArgumentException, DiscoveryException, + InvalidParameterValueException; + } diff --git a/api/src/com/cloud/storage/Volume.java b/api/src/com/cloud/storage/Volume.java index bb5ee08b512..84f0872f909 100755 --- a/api/src/com/cloud/storage/Volume.java +++ b/api/src/com/cloud/storage/Volume.java @@ -189,7 +189,5 @@ public interface Volume extends ControlledEntity, Identity, InternalIdentity, Ba Long getVmSnapshotChainSize(); - void setHypervisorSnapshotReserve(Integer hypervisorSnapshotReserve); - Integer getHypervisorSnapshotReserve(); } diff --git a/api/src/com/cloud/storage/VolumeApiService.java b/api/src/com/cloud/storage/VolumeApiService.java index db23c1be227..09ac3ee2cbb 100644 --- a/api/src/com/cloud/storage/VolumeApiService.java +++ b/api/src/com/cloud/storage/VolumeApiService.java @@ -18,8 +18,6 @@ */ package com.cloud.storage; -import java.net.URISyntaxException; - import org.apache.cloudstack.api.command.user.volume.AttachVolumeCmd; import org.apache.cloudstack.api.command.user.volume.CreateVolumeCmd; import org.apache.cloudstack.api.command.user.volume.DetachVolumeCmd; @@ -29,8 +27,6 @@ import org.apache.cloudstack.api.command.user.volume.ResizeVolumeCmd; import org.apache.cloudstack.api.command.user.volume.UploadVolumeCmd; import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InternalErrorException; -import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceAllocationException; import com.cloud.user.Account; @@ -42,7 +38,6 @@ public interface VolumeApiService { * the API command wrapping the criteria (account/domainId [admin only], zone, diskOffering, snapshot, * name) * @return the volume object - * @throws PermissionDeniedException */ Volume allocVolume(CreateVolumeCmd cmd) throws ResourceAllocationException; @@ -96,9 +91,6 @@ public interface VolumeApiService { * the command specifying url (where the volume needs to be extracted to), zoneId (zone where the volume * exists), * id (the id of the volume) - * @throws URISyntaxException - * @throws InternalErrorException - * @throws PermissionDeniedException * */ String extractVolume(ExtractVolumeCmd cmd); diff --git a/api/src/com/cloud/storage/snapshot/SnapshotApiService.java b/api/src/com/cloud/storage/snapshot/SnapshotApiService.java index 4f135107f07..91c08307bb8 100644 --- a/api/src/com/cloud/storage/snapshot/SnapshotApiService.java +++ b/api/src/com/cloud/storage/snapshot/SnapshotApiService.java @@ -24,7 +24,6 @@ import org.apache.cloudstack.api.command.user.snapshot.ListSnapshotPoliciesCmd; import org.apache.cloudstack.api.command.user.snapshot.ListSnapshotsCmd; import com.cloud.api.commands.ListRecurringSnapshotScheduleCmd; -import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceAllocationException; import com.cloud.storage.Snapshot; import com.cloud.storage.Volume; @@ -39,7 +38,6 @@ public interface SnapshotApiService { * @param cmd * the command containing the search criteria (order by, limit, etc.) * @return list of snapshots - * @throws PermissionDeniedException */ Pair, Integer> listSnapshots(ListSnapshotsCmd cmd); diff --git a/api/src/com/cloud/user/ResourceLimitService.java b/api/src/com/cloud/user/ResourceLimitService.java index f8923b708a9..de2773a955c 100644 --- a/api/src/com/cloud/user/ResourceLimitService.java +++ b/api/src/com/cloud/user/ResourceLimitService.java @@ -139,9 +139,8 @@ public interface ResourceLimitService { */ public long getResourceCount(Account account, ResourceType type); - /** - * Checks if a limit has been exceeded for an account depending on the displayResource flag + * Checks if a limit has been exceeded for an account if displayResource flag is on * * @param account * @param type @@ -153,9 +152,8 @@ public interface ResourceLimitService { */ void checkResourceLimit(Account account, ResourceType type, Boolean displayResource, long... count) throws ResourceAllocationException; - /** - * Increments the resource count depending on the displayResource flag + * Increments the resource count if displayResource flag is on * * @param accountId * @param type @@ -165,7 +163,7 @@ public interface ResourceLimitService { void incrementResourceCount(long accountId, ResourceType type, Boolean displayResource, Long... delta); /** - * Increments/Decrements the resource count depending on the displayResource flag + * Increments/Decrements the resource count depending on the displayResource flag is turned on or off respectively * * @param accountId * @param type @@ -174,5 +172,13 @@ public interface ResourceLimitService { */ void changeResourceCount(long accountId, ResourceType type, Boolean displayResource, Long... delta); + /** + * Decrements the resource count if displayResource flag is on + * + * @param accountId + * @param type + * @param displayResource + * @param delta + */ void decrementResourceCount(long accountId, ResourceType type, Boolean displayResource, Long... delta); } diff --git a/api/src/com/cloud/vm/DiskProfile.java b/api/src/com/cloud/vm/DiskProfile.java index d08b710f071..5fdacf2a755 100644 --- a/api/src/com/cloud/vm/DiskProfile.java +++ b/api/src/com/cloud/vm/DiskProfile.java @@ -71,9 +71,9 @@ public class DiskProfile { null); this.hyperType = hyperType; } - + public DiskProfile(DiskProfile dp) { - + } /** @@ -156,17 +156,17 @@ public class DiskProfile { public HypervisorType getHypervisorType() { return this.hyperType; } - + public void setPath(String path) { - this.path = path; + this.path = path; } - + public String getPath() { - return this.path; + return this.path; } - + public void setSize(long size) { - this.size = size; + this.size = size; } public void setBytesReadRate(Long bytesReadRate) { diff --git a/api/src/com/cloud/vm/NicProfile.java b/api/src/com/cloud/vm/NicProfile.java index ab18ca094f9..4dd7f68ee33 100644 --- a/api/src/com/cloud/vm/NicProfile.java +++ b/api/src/com/cloud/vm/NicProfile.java @@ -16,6 +16,7 @@ // under the License. package com.cloud.vm; +import java.io.Serializable; import java.net.URI; import org.apache.cloudstack.api.InternalIdentity; @@ -27,7 +28,9 @@ import com.cloud.network.Networks.Mode; import com.cloud.network.Networks.TrafficType; import com.cloud.vm.Nic.ReservationStrategy; -public class NicProfile implements InternalIdentity { +public class NicProfile implements InternalIdentity, Serializable { + private static final long serialVersionUID = 4997005771736090304L; + long id; long networkId; BroadcastDomainType broadcastType; @@ -57,6 +60,7 @@ public class NicProfile implements InternalIdentity { String name; String requestedIpv4; String requestedIpv6; + String uuid; public String getDns1() { return dns1; @@ -142,6 +146,10 @@ public class NicProfile implements InternalIdentity { this.format = format; } + public void setUuid(String uuid) { + this.uuid = uuid; + } + public void setTrafficType(TrafficType trafficType) { this.trafficType = trafficType; } @@ -215,29 +223,34 @@ public class NicProfile implements InternalIdentity { return strategy; } + public String getUuid() { + return uuid; + } + public NicProfile(Nic nic, Network network, URI broadcastUri, URI isolationUri, Integer networkRate, boolean isSecurityGroupEnabled, String name) { - this.id = nic.getId(); - this.networkId = network.getId(); - this.gateway = nic.getGateway(); - this.mode = network.getMode(); - this.broadcastType = network.getBroadcastDomainType(); - this.trafficType = network.getTrafficType(); - this.ip4Address = nic.getIp4Address(); - this.format = nic.getAddressFormat(); - this.ip6Address = nic.getIp6Address(); - this.macAddress = nic.getMacAddress(); - this.reservationId = nic.getReservationId(); - this.strategy = nic.getReservationStrategy(); - this.deviceId = nic.getDeviceId(); - this.defaultNic = nic.isDefaultNic(); + id = nic.getId(); + networkId = network.getId(); + gateway = nic.getGateway(); + mode = network.getMode(); + broadcastType = network.getBroadcastDomainType(); + trafficType = network.getTrafficType(); + ip4Address = nic.getIp4Address(); + format = nic.getAddressFormat(); + ip6Address = nic.getIp6Address(); + macAddress = nic.getMacAddress(); + reservationId = nic.getReservationId(); + strategy = nic.getReservationStrategy(); + deviceId = nic.getDeviceId(); + defaultNic = nic.isDefaultNic(); this.broadcastUri = broadcastUri; this.isolationUri = isolationUri; - this.netmask = nic.getNetmask(); + netmask = nic.getNetmask(); this.isSecurityGroupEnabled = isSecurityGroupEnabled; - this.vmId = nic.getInstanceId(); + vmId = nic.getInstanceId(); this.name = name; - this.ip6Cidr = nic.getIp6Cidr(); - this.ip6Gateway = nic.getIp6Gateway(); + ip6Cidr = nic.getIp6Cidr(); + ip6Gateway = nic.getIp6Gateway(); + uuid = nic.getUuid(); if (networkRate != null) { this.networkRate = networkRate; @@ -245,7 +258,7 @@ public class NicProfile implements InternalIdentity { } public NicProfile(ReservationStrategy strategy, String ip4Address, String macAddress, String gateway, String netmask) { - this.format = AddressFormat.Ip4; + format = AddressFormat.Ip4; this.ip4Address = ip4Address; this.macAddress = macAddress; this.gateway = gateway; @@ -274,11 +287,11 @@ public class NicProfile implements InternalIdentity { } public boolean isSecurityGroupEnabled() { - return this.isSecurityGroupEnabled; + return isSecurityGroupEnabled; } public void setSecurityGroupEnabled(boolean enabled) { - this.isSecurityGroupEnabled = enabled; + isSecurityGroupEnabled = enabled; } public String getRequestedIpv4() { @@ -286,36 +299,36 @@ public class NicProfile implements InternalIdentity { } public void deallocate() { - this.gateway = null; - this.mode = null; - this.format = null; - this.broadcastType = null; - this.trafficType = null; - this.ip4Address = null; - this.ip6Address = null; - this.macAddress = null; - this.reservationId = null; - this.strategy = null; - this.deviceId = null; - this.broadcastUri = null; - this.isolationUri = null; - this.netmask = null; - this.dns1 = null; - this.dns2 = null; + gateway = null; + mode = null; + format = null; + broadcastType = null; + trafficType = null; + ip4Address = null; + ip6Address = null; + macAddress = null; + reservationId = null; + strategy = null; + deviceId = null; + broadcastUri = null; + isolationUri = null; + netmask = null; + dns1 = null; + dns2 = null; } @Override public String toString() { return new StringBuilder("NicProfile[").append(id) - .append("-") - .append(vmId) - .append("-") - .append(reservationId) - .append("-") - .append(ip4Address) - .append("-") - .append(broadcastUri) - .toString(); + .append("-") + .append(vmId) + .append("-") + .append(reservationId) + .append("-") + .append(ip4Address) + .append("-") + .append(broadcastUri) + .toString(); } public String getIp6Gateway() { diff --git a/api/src/com/cloud/vm/UserVmService.java b/api/src/com/cloud/vm/UserVmService.java index 5306bf92e57..51a8fdfbe38 100755 --- a/api/src/com/cloud/vm/UserVmService.java +++ b/api/src/com/cloud/vm/UserVmService.java @@ -19,8 +19,6 @@ package com.cloud.vm; import java.util.List; import java.util.Map; -import javax.naming.InsufficientResourcesException; - import org.apache.cloudstack.api.BaseCmd.HTTPMethod; import org.apache.cloudstack.api.command.admin.vm.AssignVMCmd; import org.apache.cloudstack.api.command.admin.vm.ExpungeVMCmd; @@ -197,12 +195,11 @@ public interface UserVmService { * @throws ResourceUnavailableException * if the resources required to deploy the VM is not currently * available. - * @throws InsufficientResourcesException */ UserVm createBasicSecurityGroupVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List securityGroupIdList, - Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, HTTPMethod httpmethod, - String userData, String sshKeyPair, Map requestedIps, IpAddresses defaultIp, Boolean displayVm, String keyboard, - List affinityGroupIdList, Map customParameter, String customId) throws InsufficientCapacityException, + Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, HTTPMethod httpmethod, + String userData, String sshKeyPair, Map requestedIps, IpAddresses defaultIp, Boolean displayVm, String keyboard, + List affinityGroupIdList, Map customParameter, String customId) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException; /** @@ -271,12 +268,11 @@ public interface UserVmService { * @throws ResourceUnavailableException * if the resources required to deploy the VM is not currently * available. - * @throws InsufficientResourcesException */ UserVm createAdvancedSecurityGroupVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List networkIdList, - List securityGroupIdList, Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, - HTTPMethod httpmethod, String userData, String sshKeyPair, Map requestedIps, IpAddresses defaultIps, Boolean displayVm, String keyboard, - List affinityGroupIdList, Map customParameters, String customId) throws InsufficientCapacityException, + List securityGroupIdList, Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, + HTTPMethod httpmethod, String userData, String sshKeyPair, Map requestedIps, IpAddresses defaultIps, Boolean displayVm, String keyboard, + List affinityGroupIdList, Map customParameters, String customId) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException; /** @@ -343,14 +339,13 @@ public interface UserVmService { * @throws ResourceUnavailableException * if the resources required to deploy the VM is not currently * available. - * @throws InsufficientResourcesException */ UserVm createAdvancedVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List networkIdList, Account owner, - String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, HTTPMethod httpmethod, String userData, - String sshKeyPair, Map requestedIps, IpAddresses defaultIps, Boolean displayVm, String keyboard, List affinityGroupIdList, - Map customParameters, String customId) + String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, HTTPMethod httpmethod, String userData, + String sshKeyPair, Map requestedIps, IpAddresses defaultIps, Boolean displayVm, String keyboard, List affinityGroupIdList, + Map customParameters, String customId) - throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException; + throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException; /** * Starts the virtual machine created from createVirtualMachine. @@ -466,4 +461,12 @@ public interface UserVmService { UserVm expungeVm(long vmId) throws ResourceUnavailableException, ConcurrentOperationException; + /** + * Finds and returns an encrypted password for a VM. + * + * @param userVmId + * @return Base64 encoded userdata + */ + String getVmUserData(long vmId); + } diff --git a/api/src/com/cloud/vm/VirtualMachine.java b/api/src/com/cloud/vm/VirtualMachine.java index 331b8a3fff9..d6e70a8a6cf 100755 --- a/api/src/com/cloud/vm/VirtualMachine.java +++ b/api/src/com/cloud/vm/VirtualMachine.java @@ -29,11 +29,11 @@ import com.cloud.utils.fsm.StateObject; /** * VirtualMachine describes the properties held by a virtual machine - * + * */ public interface VirtualMachine extends RunningOn, ControlledEntity, Identity, InternalIdentity, StateObject { - public enum PowerState { + public enum PowerState { PowerUnknown, PowerOn, PowerOff, } @@ -115,7 +115,7 @@ public interface VirtualMachine extends RunningOn, ControlledEntity, Identity, I s_fsm.addTransition(State.Expunging, VirtualMachine.Event.ExpungeOperation, State.Expunging); s_fsm.addTransition(State.Error, VirtualMachine.Event.DestroyRequested, State.Expunging); s_fsm.addTransition(State.Error, VirtualMachine.Event.ExpungeOperation, State.Expunging); - + s_fsm.addTransition(State.Stopping, VirtualMachine.Event.FollowAgentPowerOnReport, State.Running); s_fsm.addTransition(State.Stopped, VirtualMachine.Event.FollowAgentPowerOnReport, State.Running); s_fsm.addTransition(State.Running, VirtualMachine.Event.FollowAgentPowerOnReport, State.Running); @@ -124,8 +124,9 @@ public interface VirtualMachine extends RunningOn, ControlledEntity, Identity, I s_fsm.addTransition(State.Stopping, VirtualMachine.Event.FollowAgentPowerOffReport, State.Stopped); s_fsm.addTransition(State.Running, VirtualMachine.Event.FollowAgentPowerOffReport, State.Stopped); s_fsm.addTransition(State.Migrating, VirtualMachine.Event.FollowAgentPowerOffReport, State.Stopped); + s_fsm.addTransition(State.Stopped, VirtualMachine.Event.FollowAgentPowerOffReport, State.Stopped); } - + public static boolean isVmStarted(State oldState, Event e, State newState) { if (oldState == State.Starting && newState == State.Running) { return true; @@ -192,10 +193,10 @@ public interface VirtualMachine extends RunningOn, ControlledEntity, Identity, I AgentReportMigrated, RevertRequested, SnapshotRequested, - + // added for new VMSync logic FollowAgentPowerOnReport, - FollowAgentPowerOffReport, + FollowAgentPowerOffReport, }; public enum Type { @@ -206,7 +207,7 @@ public interface VirtualMachine extends RunningOn, ControlledEntity, Identity, I * VM with this type. UserBareMetal should treat exactly as User. */ UserBareMetal(false), - + /* * General VM type for queuing VM orchestration work */ @@ -264,7 +265,7 @@ public interface VirtualMachine extends RunningOn, ControlledEntity, Identity, I /** * returns the guest OS ID - * + * * @return guestOSId */ long getGuestOSId(); @@ -303,7 +304,7 @@ public interface VirtualMachine extends RunningOn, ControlledEntity, Identity, I Date getCreated(); long getServiceOfferingId(); - + Long getDiskOfferingId(); Type getType(); diff --git a/api/src/com/cloud/vm/VirtualMachineName.java b/api/src/com/cloud/vm/VirtualMachineName.java index c5fc3de5ab1..4bbcb64ebca 100755 --- a/api/src/com/cloud/vm/VirtualMachineName.java +++ b/api/src/com/cloud/vm/VirtualMachineName.java @@ -26,6 +26,19 @@ import com.cloud.dc.Vlan; public class VirtualMachineName { public static final String SEPARATOR = "-"; + public static boolean isValidCloudStackVmName(String name, String instance) { + String[] parts = name.split(SEPARATOR); + if (parts.length <= 1) { + return false; + } + + if (!parts[parts.length - 1].equals(instance)) { + return false; + } + + return true; + } + public static String getVnetName(long vnetId) { StringBuilder vnet = new StringBuilder(); Formatter formatter = new Formatter(vnet); diff --git a/api/src/org/apache/cloudstack/alert/AlertService.java b/api/src/org/apache/cloudstack/alert/AlertService.java index 2143fe8d23f..2e98aea407a 100644 --- a/api/src/org/apache/cloudstack/alert/AlertService.java +++ b/api/src/org/apache/cloudstack/alert/AlertService.java @@ -1,4 +1,3 @@ - // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -28,7 +27,7 @@ public interface AlertService { private static Set defaultAlertTypes = new HashSet(); private final String name; private final short type; - + private AlertType(short type, String name, boolean isDefault) { this.name = name; this.type = type; @@ -36,12 +35,13 @@ public interface AlertService { defaultAlertTypes.add(this); } } - + public static final AlertType ALERT_TYPE_MEMORY = new AlertType(Capacity.CAPACITY_TYPE_MEMORY, "ALERT.MEMORY", true); public static final AlertType ALERT_TYPE_CPU = new AlertType(Capacity.CAPACITY_TYPE_CPU, "ALERT.CPU", true); public static final AlertType ALERT_TYPE_STORAGE = new AlertType(Capacity.CAPACITY_TYPE_STORAGE, "ALERT.STORAGE", true); public static final AlertType ALERT_TYPE_STORAGE_ALLOCATED = new AlertType(Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED, "ALERT.STORAGE.ALLOCATED", true); - public static final AlertType ALERT_TYPE_VIRTUAL_NETWORK_PUBLIC_IP = new AlertType(Capacity.CAPACITY_TYPE_VIRTUAL_NETWORK_PUBLIC_IP, "ALERT.NETWORK.PUBLICIP", true); + public static final AlertType ALERT_TYPE_VIRTUAL_NETWORK_PUBLIC_IP = new AlertType(Capacity.CAPACITY_TYPE_VIRTUAL_NETWORK_PUBLIC_IP, "ALERT.NETWORK.PUBLICIP", + true); public static final AlertType ALERT_TYPE_PRIVATE_IP = new AlertType(Capacity.CAPACITY_TYPE_PRIVATE_IP, "ALERT.NETWORK.PRIVATEIP", true); public static final AlertType ALERT_TYPE_SECONDARY_STORAGE = new AlertType(Capacity.CAPACITY_TYPE_SECONDARY_STORAGE, "ALERT.STORAGE.SECONDARY", true); public static final AlertType ALERT_TYPE_HOST = new AlertType((short)7, "ALERT.COMPUTE.HOST", true); @@ -51,10 +51,10 @@ public interface AlertService { public static final AlertType ALERT_TYPE_ROUTING = new AlertType((short)11, "ALERT.NETWORK.ROUTING", true); public static final AlertType ALERT_TYPE_STORAGE_MISC = new AlertType((short)12, "ALERT.STORAGE.MISC", true); public static final AlertType ALERT_TYPE_USAGE_SERVER = new AlertType((short)13, "ALERT.USAGE", true); - public static final AlertType ALERT_TYPE_MANAGMENT_NODE = new AlertType((short)14, "ALERT.MANAGEMENT", true); + public static final AlertType ALERT_TYPE_MANAGMENT_NODE = new AlertType((short)14, "ALERT.MANAGEMENT", true); public static final AlertType ALERT_TYPE_DOMAIN_ROUTER_MIGRATE = new AlertType((short)15, "ALERT.NETWORK.DOMAINROUTERMIGRATE", true); public static final AlertType ALERT_TYPE_CONSOLE_PROXY_MIGRATE = new AlertType((short)16, "ALERT.SERVICE.CONSOLEPROXYMIGRATE", true); - public static final AlertType ALERT_TYPE_USERVM_MIGRATE = new AlertType((short)17, "ALERT.USERVM.MIGRATE", true); + public static final AlertType ALERT_TYPE_USERVM_MIGRATE = new AlertType((short)17, "ALERT.USERVM.MIGRATE", true); public static final AlertType ALERT_TYPE_VLAN = new AlertType((short)18, "ALERT.NETWORK.VLAN", true); public static final AlertType ALERT_TYPE_SSVM = new AlertType((short)19, "ALERT.SERVICE.SSVM", true); public static final AlertType ALERT_TYPE_USAGE_SERVER_RESULT = new AlertType((short)20, "ALERT.USAGE.RESULT", true); @@ -69,7 +69,7 @@ public interface AlertService { public short getType() { return type; } - + public String getName() { return name; } @@ -82,7 +82,7 @@ public interface AlertService { } return null; } - + @Override public String toString() { return String.valueOf(this.getType()); @@ -97,7 +97,7 @@ public interface AlertService { } } } - + boolean generateAlert(AlertType alertType, long dataCenterId, Long podId, String msg); } diff --git a/api/src/org/apache/cloudstack/api/ApiConstants.java b/api/src/org/apache/cloudstack/api/ApiConstants.java index a132e548258..d500303bcac 100755 --- a/api/src/org/apache/cloudstack/api/ApiConstants.java +++ b/api/src/org/apache/cloudstack/api/ApiConstants.java @@ -72,7 +72,6 @@ public class ApiConstants { public static final String DISPLAY_VM = "displayvm"; public static final String DISPLAY_OFFERING = "displayoffering"; public static final String DISPLAY_VOLUME = "displayvolume"; - public static final String CUSTOM_PARAMETERS = "customparameters"; public static final String DNS1 = "dns1"; public static final String DNS2 = "dns2"; public static final String IP6_DNS1 = "ip6dns1"; @@ -210,6 +209,7 @@ public class ApiConstants { public static final String SENT_BYTES = "sentbytes"; public static final String SERVICE_OFFERING_ID = "serviceofferingid"; public static final String SHOW_CAPACITIES = "showcapacities"; + public static final String SHOW_REMOVED = "showremoved"; public static final String SIZE = "size"; public static final String SNAPSHOT_ID = "snapshotid"; public static final String SNAPSHOT_POLICY_ID = "snapshotpolicyid"; @@ -344,6 +344,7 @@ public class ApiConstants { public static final String CAPACITY_IOPS = "capacityiops"; public static final String NETWORK_SPEED = "networkspeed"; public static final String BROADCAST_DOMAIN_RANGE = "broadcastdomainrange"; + public static final String ISOLATION_METHOD = "isolationmethod"; public static final String ISOLATION_METHODS = "isolationmethods"; public static final String PHYSICAL_NETWORK_ID = "physicalnetworkid"; public static final String DEST_PHYSICAL_NETWORK_ID = "destinationphysicalnetworkid"; @@ -412,11 +413,11 @@ public class ApiConstants { // Ovs controller public static final String OVS_DEVICE_ID = "ovsdeviceid"; public static final String OVS_DEVICE_NAME = "ovsdevicename"; - // OpenDaylight controller - public static final String ODL_DEVICE_ID = "odldeviceid"; - public static final String ODL_DEVICE_NAME = "odldevicename"; - public static final String ODL_TRANSPORT_ZONE_UUID = "transportzoneuuid"; - public static final String ODL_GATEWAYSERVICE_UUID = "l3gatewayserviceuuid"; + // OpenDaylight controller + public static final String ODL_DEVICE_ID = "odldeviceid"; + public static final String ODL_DEVICE_NAME = "odldevicename"; + public static final String ODL_TRANSPORT_ZONE_UUID = "transportzoneuuid"; + public static final String ODL_GATEWAYSERVICE_UUID = "l3gatewayserviceuuid"; public static final String EXTERNAL_SWITCH_MGMT_DEVICE_ID = "vsmdeviceid"; public static final String EXTERNAL_SWITCH_MGMT_DEVICE_NAME = "vsmdevicename"; @@ -554,6 +555,6 @@ public class ApiConstants { } public enum VMDetails { - all, group, nics, stats, secgrp, tmpl, servoff, iso, volume, min, affgrp; + all, group, nics, stats, secgrp, tmpl, servoff, diskoff, iso, volume, min, affgrp; } } diff --git a/api/src/org/apache/cloudstack/api/BaseAsyncCreateCustomIdCmd.java b/api/src/org/apache/cloudstack/api/BaseAsyncCreateCustomIdCmd.java index 0f75653e35d..8680d7f11de 100644 --- a/api/src/org/apache/cloudstack/api/BaseAsyncCreateCustomIdCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseAsyncCreateCustomIdCmd.java @@ -16,9 +16,10 @@ // under the License. package org.apache.cloudstack.api; - -public abstract class BaseAsyncCreateCustomIdCmd extends BaseAsyncCreateCmd{ - @Parameter(name=ApiConstants.CUSTOM_ID, type=CommandType.STRING, description="an optional field, in case you want to set a custom id to the resource. Allowed to Root Admins only") +public abstract class BaseAsyncCreateCustomIdCmd extends BaseAsyncCreateCmd { + @Parameter(name = ApiConstants.CUSTOM_ID, + type = CommandType.STRING, + description = "an optional field, in case you want to set a custom id to the resource. Allowed to Root Admins only") private String customId; public String getCustomId() { diff --git a/api/src/org/apache/cloudstack/api/BaseAsyncCustomIdCmd.java b/api/src/org/apache/cloudstack/api/BaseAsyncCustomIdCmd.java index 95be24f5483..18264da1aa2 100644 --- a/api/src/org/apache/cloudstack/api/BaseAsyncCustomIdCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseAsyncCustomIdCmd.java @@ -16,9 +16,10 @@ // under the License. package org.apache.cloudstack.api; - public abstract class BaseAsyncCustomIdCmd extends BaseAsyncCmd { - @Parameter(name=ApiConstants.CUSTOM_ID, type=CommandType.STRING, description="an optional field, in case you want to set a custom id to the resource. Allowed to Root Admins only") + @Parameter(name = ApiConstants.CUSTOM_ID, + type = CommandType.STRING, + description = "an optional field, in case you want to set a custom id to the resource. Allowed to Root Admins only") private String customId; public String getCustomId() { diff --git a/api/src/org/apache/cloudstack/api/BaseCmd.java b/api/src/org/apache/cloudstack/api/BaseCmd.java index 86a7c726d6c..4229ec9302b 100644 --- a/api/src/org/apache/cloudstack/api/BaseCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseCmd.java @@ -26,6 +26,8 @@ import java.util.regex.Pattern; import javax.inject.Inject; +import org.apache.log4j.Logger; + import org.apache.cloudstack.affinity.AffinityGroupService; import org.apache.cloudstack.alert.AlertService; import org.apache.cloudstack.network.element.InternalLoadBalancerElementService; @@ -33,7 +35,6 @@ import org.apache.cloudstack.network.lb.ApplicationLoadBalancerService; import org.apache.cloudstack.network.lb.InternalLoadBalancerVMService; import org.apache.cloudstack.query.QueryService; import org.apache.cloudstack.usage.UsageService; -import org.apache.log4j.Logger; import com.cloud.configuration.ConfigurationService; import com.cloud.domain.Domain; @@ -94,7 +95,7 @@ public abstract class BaseCmd { public static final DateFormat INPUT_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); public static final DateFormat NEW_INPUT_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static Pattern newInputDateFormat = Pattern.compile("[\\d]+-[\\d]+-[\\d]+ [\\d]+:[\\d]+:[\\d]+"); - private static final DateFormat _outputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); + private static final DateFormat s_outputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); private Object _responseObject = null; private Map fullUrlParams; @@ -153,8 +154,6 @@ public abstract class BaseCmd { @Inject public ResourceLimitService _resourceLimitService; @Inject - public IdentityService _identityService; - @Inject public StorageNetworkService _storageNetworkService; @Inject public TaggedResourceService _taggedResourceService; @@ -191,12 +190,11 @@ public abstract class BaseCmd { public InternalLoadBalancerVMService _internalLbSvc; @Inject public NetworkModel _ntwkModel; - @Inject + @Inject public AlertService _alertSvc; - - public abstract void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException, NetworkRuleConflictException; + public abstract void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, + ResourceAllocationException, NetworkRuleConflictException; public void configure() { } @@ -258,8 +256,8 @@ public abstract class BaseCmd { return ""; } String formattedString = null; - synchronized (_outputFormat) { - formattedString = _outputFormat.format(date); + synchronized (s_outputFormat) { + formattedString = s_outputFormat.format(date); } return formattedString; } @@ -359,11 +357,11 @@ public abstract class BaseCmd { } public void setFullUrlParams(Map map) { - this.fullUrlParams = map; + fullUrlParams = map; } public Map getFullUrlParams() { - return this.fullUrlParams; + return fullUrlParams; } public Long finalyzeAccountId(String accountName, Long domainId, Long projectId, boolean enabledOnly) { diff --git a/api/src/org/apache/cloudstack/api/BaseCustomIdCmd.java b/api/src/org/apache/cloudstack/api/BaseCustomIdCmd.java index df59b44a56a..8ae746f319e 100644 --- a/api/src/org/apache/cloudstack/api/BaseCustomIdCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseCustomIdCmd.java @@ -18,7 +18,9 @@ package org.apache.cloudstack.api; public abstract class BaseCustomIdCmd extends BaseCmd { - @Parameter(name=ApiConstants.CUSTOM_ID, type=CommandType.STRING, description="an optional field, in case you want to set a custom id to the resource. Allowed to Root Admins only") + @Parameter(name = ApiConstants.CUSTOM_ID, + type = CommandType.STRING, + description = "an optional field, in case you want to set a custom id to the resource. Allowed to Root Admins only") private String customId; public String getCustomId() { diff --git a/api/src/org/apache/cloudstack/api/BaseListCmd.java b/api/src/org/apache/cloudstack/api/BaseListCmd.java index dfb3f3b6ba5..c1a4b4c440f 100644 --- a/api/src/org/apache/cloudstack/api/BaseListCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseListCmd.java @@ -20,8 +20,8 @@ import com.cloud.exception.InvalidParameterValueException; public abstract class BaseListCmd extends BaseCmd { - private static Long MAX_PAGESIZE = null; - public static Long PAGESIZE_UNLIMITED = -1L; + private static Long s_maxPageSize = null; + public static Long s_pageSizeUnlimited = -1L; // /////////////////////////////////////////////////// // ///////// BaseList API parameters ///////////////// @@ -53,11 +53,11 @@ public abstract class BaseListCmd extends BaseCmd { } public Integer getPageSize() { - if (pageSize != null && MAX_PAGESIZE.longValue() != PAGESIZE_UNLIMITED && pageSize.longValue() > MAX_PAGESIZE.longValue()) { - throw new InvalidParameterValueException("Page size can't exceed max allowed page size value: " + MAX_PAGESIZE.longValue()); + if (pageSize != null && s_maxPageSize.longValue() != s_pageSizeUnlimited && pageSize.longValue() > s_maxPageSize.longValue()) { + throw new InvalidParameterValueException("Page size can't exceed max allowed page size value: " + s_maxPageSize.longValue()); } - if (pageSize != null && pageSize.longValue() == PAGESIZE_UNLIMITED && page != null) { + if (pageSize != null && pageSize.longValue() == s_pageSizeUnlimited && page != null) { throw new InvalidParameterValueException("Can't specify page parameter when pagesize is -1 (Unlimited)"); } @@ -66,11 +66,11 @@ public abstract class BaseListCmd extends BaseCmd { @Override public void configure() { - if (MAX_PAGESIZE == null) { - if (_configService.getDefaultPageSize().longValue() != PAGESIZE_UNLIMITED) { - MAX_PAGESIZE = _configService.getDefaultPageSize(); + if (s_maxPageSize == null) { + if (_configService.getDefaultPageSize().longValue() != s_pageSizeUnlimited) { + s_maxPageSize = _configService.getDefaultPageSize(); } else { - MAX_PAGESIZE = PAGESIZE_UNLIMITED; + s_maxPageSize = s_pageSizeUnlimited; } } } @@ -82,12 +82,12 @@ public abstract class BaseListCmd extends BaseCmd { } public Long getPageSizeVal() { - Long defaultPageSize = MAX_PAGESIZE; + Long defaultPageSize = s_maxPageSize; Integer pageSizeInt = getPageSize(); if (pageSizeInt != null) { defaultPageSize = pageSizeInt.longValue(); } - if (defaultPageSize.longValue() == PAGESIZE_UNLIMITED) { + if (defaultPageSize.longValue() == s_pageSizeUnlimited) { defaultPageSize = null; } diff --git a/api/src/org/apache/cloudstack/api/BaseListTemplateOrIsoPermissionsCmd.java b/api/src/org/apache/cloudstack/api/BaseListTemplateOrIsoPermissionsCmd.java index c9725a55ee4..48c1e02cfd5 100644 --- a/api/src/org/apache/cloudstack/api/BaseListTemplateOrIsoPermissionsCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseListTemplateOrIsoPermissionsCmd.java @@ -27,8 +27,8 @@ import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; public class BaseListTemplateOrIsoPermissionsCmd extends BaseCmd { - public Logger s_logger = getLogger(); - protected String s_name = "listtemplatepermissionsresponse"; + public Logger logger = getLogger(); + protected static final String s_name = "listtemplatepermissionsresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -58,6 +58,10 @@ public class BaseListTemplateOrIsoPermissionsCmd extends BaseCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } + protected Logger getLogger() { + return Logger.getLogger(BaseUpdateTemplateOrIsoPermissionsCmd.class); + } + @Override public String getCommandName() { return s_name; @@ -71,10 +75,6 @@ public class BaseListTemplateOrIsoPermissionsCmd extends BaseCmd { return "templateOrIso"; } - protected Logger getLogger() { - return Logger.getLogger(BaseUpdateTemplateOrIsoPermissionsCmd.class.getName()); - } - @Override public void execute() { List accountNames = _templateService.listTemplatePermissions(this); @@ -84,6 +84,6 @@ public class BaseListTemplateOrIsoPermissionsCmd extends BaseCmd { TemplatePermissionsResponse response = _responseGenerator.createTemplatePermissionsResponse(accountNames, id, isAdmin); response.setResponseName(getCommandName()); - this.setResponseObject(response); + setResponseObject(response); } } diff --git a/api/src/org/apache/cloudstack/api/BaseUpdateTemplateOrIsoPermissionsCmd.java b/api/src/org/apache/cloudstack/api/BaseUpdateTemplateOrIsoPermissionsCmd.java index 5d054398772..77e5a15b09e 100644 --- a/api/src/org/apache/cloudstack/api/BaseUpdateTemplateOrIsoPermissionsCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseUpdateTemplateOrIsoPermissionsCmd.java @@ -27,13 +27,21 @@ import org.apache.cloudstack.api.response.TemplateResponse; import com.cloud.exception.InvalidParameterValueException; public abstract class BaseUpdateTemplateOrIsoPermissionsCmd extends BaseCmd { - public Logger s_logger = getLogger(); - protected String s_name = getResponseName(); + public Logger _logger = getLogger(); + protected String _name = getResponseName(); // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// + protected Logger getLogger() { + return Logger.getLogger(BaseUpdateTemplateOrIsoPermissionsCmd.class); + } + + protected String getResponseName() { + return "updatetemplateorisopermissionsresponse"; + } + @Parameter(name = ApiConstants.ACCOUNTS, type = CommandType.LIST, collectionType = CommandType.STRING, @@ -109,15 +117,7 @@ public abstract class BaseUpdateTemplateOrIsoPermissionsCmd extends BaseCmd { @Override public String getCommandName() { - return s_name; - } - - protected String getResponseName() { - return "updatetemplateorisopermissionsresponse"; - } - - protected Logger getLogger() { - return Logger.getLogger(BaseUpdateTemplateOrIsoPermissionsCmd.class.getName()); + return _name; } @Override @@ -125,7 +125,7 @@ public abstract class BaseUpdateTemplateOrIsoPermissionsCmd extends BaseCmd { boolean result = _templateService.updateTemplateOrIsoPermissions(this); if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); - this.setResponseObject(response); + setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update template/iso permissions"); } diff --git a/api/src/org/apache/cloudstack/api/ResponseGenerator.java b/api/src/org/apache/cloudstack/api/ResponseGenerator.java index e7a1b350632..1cb53886a7c 100644 --- a/api/src/org/apache/cloudstack/api/ResponseGenerator.java +++ b/api/src/org/apache/cloudstack/api/ResponseGenerator.java @@ -290,7 +290,7 @@ public interface ResponseGenerator { //ListResponse createSecurityGroupResponses(List networkGroups); - SecurityGroupResponse createSecurityGroupResponseFromSecurityGroupRule(List SecurityRules); + SecurityGroupResponse createSecurityGroupResponseFromSecurityGroupRule(List securityRules); SecurityGroupResponse createSecurityGroupResponse(SecurityGroup group); @@ -355,7 +355,7 @@ public interface ResponseGenerator { VirtualRouterProviderResponse createVirtualRouterProviderResponse(VirtualRouterProvider result); - OvsProviderResponse createOvsProviderResponse(OvsProvider result); + OvsProviderResponse createOvsProviderResponse(OvsProvider result); StorageNetworkIpRangeResponse createStorageNetworkIpRangeResponse(StorageNetworkIpRange result); diff --git a/api/src/org/apache/cloudstack/api/ServerApiException.java b/api/src/org/apache/cloudstack/api/ServerApiException.java index 81184e3f4f3..a8bb2ed71c9 100644 --- a/api/src/org/apache/cloudstack/api/ServerApiException.java +++ b/api/src/org/apache/cloudstack/api/ServerApiException.java @@ -82,4 +82,8 @@ public class ServerApiException extends CloudRuntimeException { _description = description; } + @Override + public String getMessage() { + return _description; + } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/alert/GenerateAlertCmd.java b/api/src/org/apache/cloudstack/api/command/admin/alert/GenerateAlertCmd.java index b23a3be9dea..620c5ed8faa 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/alert/GenerateAlertCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/alert/GenerateAlertCmd.java @@ -31,7 +31,7 @@ import org.apache.log4j.Logger; import com.cloud.event.EventTypes; -@APICommand(name = "generateAlert", description = "Generates an alert", responseObject = SuccessResponse.class, since="4.3") +@APICommand(name = "generateAlert", description = "Generates an alert", responseObject = SuccessResponse.class, since = "4.3") public class GenerateAlertCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(GenerateAlertCmd.class.getName()); @@ -42,19 +42,19 @@ public class GenerateAlertCmd extends BaseAsyncCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @Parameter(name = ApiConstants.TYPE, type = CommandType.SHORT, description = "Type of the alert", required=true) + @Parameter(name = ApiConstants.TYPE, type = CommandType.SHORT, description = "Type of the alert", required = true) private Short type; - @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "Name of the alert", required=true) + @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "Name of the alert", required = true) private String name; - - @Parameter(name = ApiConstants.DESCRIPTION, type = CommandType.STRING, description = "Alert description", required=true) + + @Parameter(name = ApiConstants.DESCRIPTION, type = CommandType.STRING, description = "Alert description", required = true) private String description; - - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, description="Zone id for which alert is generated") + + @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, description = "Zone id for which alert is generated") private Long zoneId; - - @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType=PodResponse.class, description="Pod id for which alert is generated") + + @Parameter(name = ApiConstants.POD_ID, type = CommandType.UUID, entityType = PodResponse.class, description = "Pod id for which alert is generated") private Long podId; // /////////////////////////////////////////////////// @@ -87,14 +87,11 @@ public class GenerateAlertCmd extends BaseAsyncCmd { public Long getPodId() { return podId; } - // /////////////////////////////////////////////////// // ///////////// API Implementation/////////////////// // /////////////////////////////////////////////////// - - @Override public void execute() { AlertType alertType = AlertService.AlertType.generateAlert(getType(), getName()); diff --git a/api/src/org/apache/cloudstack/api/command/admin/config/ListCfgsByCmd.java b/api/src/org/apache/cloudstack/api/command/admin/config/ListCfgsByCmd.java index 2c31dfdc745..517807d4a78 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/config/ListCfgsByCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/config/ListCfgsByCmd.java @@ -55,25 +55,25 @@ public class ListCfgsByCmd extends BaseListCmd { type = CommandType.UUID, entityType = ZoneResponse.class, description = "the ID of the Zone to update the parameter value for corresponding zone") - private Long zone_id; + private Long zoneId; @Parameter(name = ApiConstants.CLUSTER_ID, type = CommandType.UUID, entityType = ClusterResponse.class, description = "the ID of the Cluster to update the parameter value for corresponding cluster") - private Long cluster_id; + private Long clusterId; @Parameter(name = ApiConstants.STORAGE_ID, type = CommandType.UUID, entityType = StoragePoolResponse.class, description = "the ID of the Storage pool to update the parameter value for corresponding storage pool") - private Long storagepool_id; + private Long storagePoolId; @Parameter(name = ApiConstants.ACCOUNT_ID, type = CommandType.UUID, entityType = AccountResponse.class, description = "the ID of the Account to update the parameter value for corresponding account") - private Long account_id; + private Long accountId; // /////////////////////////////////////////////////// // ///////////////// Accessors /////////////////////// @@ -88,19 +88,19 @@ public class ListCfgsByCmd extends BaseListCmd { } public Long getZoneId() { - return zone_id; + return zoneId; } public Long getClusterId() { - return cluster_id; + return clusterId; } public Long getStoragepoolId() { - return storagepool_id; + return storagePoolId; } public Long getAccountId() { - return account_id; + return accountId; } @Override @@ -108,7 +108,7 @@ public class ListCfgsByCmd extends BaseListCmd { Long defaultPageSize = 500L; Integer pageSizeInt = getPageSize(); if (pageSizeInt != null) { - if (pageSizeInt.longValue() == PAGESIZE_UNLIMITED) { + if (pageSizeInt.longValue() == s_pageSizeUnlimited) { defaultPageSize = null; } else { defaultPageSize = pageSizeInt.longValue(); @@ -151,6 +151,6 @@ public class ListCfgsByCmd extends BaseListCmd { response.setResponses(configResponses, result.second()); response.setResponseName(getCommandName()); - this.setResponseObject(response); + setResponseObject(response); } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/config/UpdateCfgCmd.java b/api/src/org/apache/cloudstack/api/command/admin/config/UpdateCfgCmd.java index fe6e3d65538..9bc9b3cbb5c 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/config/UpdateCfgCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/config/UpdateCfgCmd.java @@ -52,25 +52,25 @@ public class UpdateCfgCmd extends BaseCmd { type = CommandType.UUID, entityType = ZoneResponse.class, description = "the ID of the Zone to update the parameter value for corresponding zone") - private Long zone_id; + private Long zoneId; @Parameter(name = ApiConstants.CLUSTER_ID, type = CommandType.UUID, entityType = ClusterResponse.class, description = "the ID of the Cluster to update the parameter value for corresponding cluster") - private Long cluster_id; + private Long clusterId; @Parameter(name = ApiConstants.STORAGE_ID, type = CommandType.UUID, entityType = StoragePoolResponse.class, description = "the ID of the Storage pool to update the parameter value for corresponding storage pool") - private Long storagepool_id; + private Long storagePoolId; @Parameter(name = ApiConstants.ACCOUNT_ID, type = CommandType.UUID, entityType = AccountResponse.class, description = "the ID of the Account to update the parameter value for corresponding account") - private Long account_id; + private Long accountId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -85,19 +85,19 @@ public class UpdateCfgCmd extends BaseCmd { } public Long getZoneId() { - return zone_id; + return zoneId; } public Long getClusterId() { - return cluster_id; + return clusterId; } public Long getStoragepoolId() { - return storagepool_id; + return storagePoolId; } public Long getAccountId() { - return account_id; + return accountId; } ///////////////////////////////////////////////////// diff --git a/api/src/org/apache/cloudstack/api/command/admin/host/AddSecondaryStorageCmd.java b/api/src/org/apache/cloudstack/api/command/admin/host/AddSecondaryStorageCmd.java index 61f6f49091c..b573bea3e84 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/host/AddSecondaryStorageCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/host/AddSecondaryStorageCmd.java @@ -24,7 +24,6 @@ import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.command.admin.storage.AddImageStoreCmd; import org.apache.cloudstack.api.response.ImageStoreResponse; import org.apache.cloudstack.api.response.ZoneResponse; @@ -74,20 +73,15 @@ public class AddSecondaryStorageCmd extends BaseCmd { } @Override - public void execute() { - AddImageStoreCmd cmd = new AddImageStoreCmd(); - cmd.setUrl(this.getUrl()); - cmd.setZoneId(this.getZoneId()); - cmd.setProviderName("NFS"); - - try { - ImageStore result = _storageService.discoverImageStore(cmd); + public void execute(){ + try{ + ImageStore result = _storageService.discoverImageStore(null, getUrl(), "NFS", getZoneId(), null); ImageStoreResponse storeResponse = null; - if (result != null) { - storeResponse = _responseGenerator.createImageStoreResponse(result); - storeResponse.setResponseName(getCommandName()); - storeResponse.setObjectName("secondarystorage"); - this.setResponseObject(storeResponse); + if (result != null ) { + storeResponse = _responseGenerator.createImageStoreResponse(result); + storeResponse.setResponseName(getCommandName()); + storeResponse.setObjectName("secondarystorage"); + setResponseObject(storeResponse); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add secondary storage"); } diff --git a/api/src/org/apache/cloudstack/api/command/admin/internallb/ListInternalLoadBalancerElementsCmd.java b/api/src/org/apache/cloudstack/api/command/admin/internallb/ListInternalLoadBalancerElementsCmd.java index df7135af211..a42a0b306af 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/internallb/ListInternalLoadBalancerElementsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/internallb/ListInternalLoadBalancerElementsCmd.java @@ -45,7 +45,7 @@ import com.cloud.network.VirtualRouterProvider; since = "4.2.0") public class ListInternalLoadBalancerElementsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListInternalLoadBalancerElementsCmd.class.getName()); - private static final String _name = "listinternalloadbalancerelementsresponse"; + private static final String Name = "listinternalloadbalancerelementsresponse"; @Inject private InternalLoadBalancerElementService _service; @@ -86,7 +86,7 @@ public class ListInternalLoadBalancerElementsCmd extends BaseListCmd { @Override public String getCommandName() { - return _name; + return Name; } @Override diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/CreateNetworkOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/CreateNetworkOfferingCmd.java index bdf047233ad..5614295f905 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/network/CreateNetworkOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/CreateNetworkOfferingCmd.java @@ -44,7 +44,7 @@ import com.cloud.user.Account; @APICommand(name = "createNetworkOffering", description = "Creates a network offering.", responseObject = NetworkOfferingResponse.class, since = "3.0.0") public class CreateNetworkOfferingCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateNetworkOfferingCmd.class.getName()); - private static final String _name = "createnetworkofferingresponse"; + private static final String Name = "createnetworkofferingresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -164,7 +164,7 @@ public class CreateNetworkOfferingCmd extends BaseCmd { } public static String getName() { - return _name; + return Name; } public Long getServiceOfferingId() { @@ -281,7 +281,7 @@ public class CreateNetworkOfferingCmd extends BaseCmd { ///////////////////////////////////////////////////// @Override public String getCommandName() { - return _name; + return Name; } @Override @@ -295,7 +295,7 @@ public class CreateNetworkOfferingCmd extends BaseCmd { if (result != null) { NetworkOfferingResponse response = _responseGenerator.createNetworkOfferingResponse(result); response.setResponseName(getCommandName()); - this.setResponseObject(response); + setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create network offering"); } diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/ListNetworkServiceProvidersCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/ListNetworkServiceProvidersCmd.java index 25d5d0fd631..5a1235b7b61 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/network/ListNetworkServiceProvidersCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/ListNetworkServiceProvidersCmd.java @@ -39,7 +39,7 @@ import com.cloud.utils.Pair; since = "3.0.0") public class ListNetworkServiceProvidersCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListNetworkServiceProvidersCmd.class.getName()); - private static final String _name = "listnetworkserviceprovidersresponse"; + private static final String Name = "listnetworkserviceprovidersresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -79,7 +79,7 @@ public class ListNetworkServiceProvidersCmd extends BaseListCmd { ///////////////////////////////////////////////////// @Override public String getCommandName() { - return _name; + return Name; } @Override diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/ListStorageNetworkIpRangeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/ListStorageNetworkIpRangeCmd.java index 0b17666e3c7..89cba471041 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/network/ListStorageNetworkIpRangeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/ListStorageNetworkIpRangeCmd.java @@ -43,7 +43,7 @@ import com.cloud.user.Account; public class ListStorageNetworkIpRangeCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListStorageNetworkIpRangeCmd.class); - String s_name = "liststoragenetworkiprangeresponse"; + String _name = "liststoragenetworkiprangeresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -105,7 +105,7 @@ public class ListStorageNetworkIpRangeCmd extends BaseListCmd { @Override public String getCommandName() { - return s_name; + return _name; } @Override diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/ListSupportedNetworkServicesCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/ListSupportedNetworkServicesCmd.java index 240c03362cb..342f9b04d88 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/network/ListSupportedNetworkServicesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/ListSupportedNetworkServicesCmd.java @@ -39,7 +39,7 @@ import com.cloud.user.Account; since = "3.0.0") public class ListSupportedNetworkServicesCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListSupportedNetworkServicesCmd.class.getName()); - private static final String _name = "listsupportednetworkservicesresponse"; + private static final String Name = "listsupportednetworkservicesresponse"; @Parameter(name = ApiConstants.PROVIDER, type = CommandType.STRING, description = "network service provider name") private String providerName; @@ -72,7 +72,7 @@ public class ListSupportedNetworkServicesCmd extends BaseListCmd { ///////////////////////////////////////////////////// @Override public String getCommandName() { - return _name; + return Name; } @Override diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/UpdateNetworkOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/UpdateNetworkOfferingCmd.java index aaff5a1c46b..957450f78f7 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/network/UpdateNetworkOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/UpdateNetworkOfferingCmd.java @@ -32,7 +32,7 @@ import com.cloud.user.Account; @APICommand(name = "updateNetworkOffering", description = "Updates a network offering.", responseObject = NetworkOfferingResponse.class) public class UpdateNetworkOfferingCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdateNetworkOfferingCmd.class.getName()); - private static final String _name = "updatenetworkofferingresponse"; + private static final String Name = "updatenetworkofferingresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -109,7 +109,7 @@ public class UpdateNetworkOfferingCmd extends BaseCmd { ///////////////////////////////////////////////////// @Override public String getCommandName() { - return _name; + return Name; } @Override diff --git a/api/src/org/apache/cloudstack/api/command/admin/offering/CreateServiceOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/offering/CreateServiceOfferingCmd.java index 7dd87e1761c..6f9693cbcb0 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/offering/CreateServiceOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/offering/CreateServiceOfferingCmd.java @@ -36,7 +36,7 @@ import com.cloud.user.Account; @APICommand(name = "createServiceOffering", description = "Creates a service offering.", responseObject = ServiceOfferingResponse.class) public class CreateServiceOfferingCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateServiceOfferingCmd.class.getName()); - private static final String _name = "createserviceofferingresponse"; + private static final String Name = "createserviceofferingresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -220,7 +220,7 @@ public class CreateServiceOfferingCmd extends BaseCmd { @Override public String getCommandName() { - return _name; + return Name; } @Override diff --git a/api/src/org/apache/cloudstack/api/command/admin/resource/ListAlertsCmd.java b/api/src/org/apache/cloudstack/api/command/admin/resource/ListAlertsCmd.java index 2fc4084e0ab..397b00a034e 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/resource/ListAlertsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/resource/ListAlertsCmd.java @@ -46,8 +46,8 @@ public class ListAlertsCmd extends BaseListCmd { @Parameter(name = ApiConstants.TYPE, type = CommandType.STRING, description = "list by alert type") private String type; - - @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "list by alert name", since="4.3") + + @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "list by alert name", since = "4.3") private String name; // /////////////////////////////////////////////////// @@ -61,7 +61,7 @@ public class ListAlertsCmd extends BaseListCmd { public String getType() { return type; } - + public String getName() { return name; } diff --git a/api/src/org/apache/cloudstack/api/command/admin/router/ConfigureOvsElementCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/ConfigureOvsElementCmd.java index 26cfb31a69d..75b08b1fab5 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/router/ConfigureOvsElementCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/router/ConfigureOvsElementCmd.java @@ -41,92 +41,92 @@ import com.cloud.user.Account; @APICommand(name = "configureOvsElement", responseObject = OvsProviderResponse.class, description = "Configures an ovs element.") public class ConfigureOvsElementCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger - .getLogger(ConfigureOvsElementCmd.class.getName()); - private static final String s_name = "configureovselementresponse"; - @Inject - private List _service; + public static final Logger s_logger = Logger + .getLogger(ConfigureOvsElementCmd.class.getName()); + private static final String s_name = "configureovselementresponse"; + @Inject + private List _service; - // /////////////////////////////////////////////////// - // ////////////// API parameters ///////////////////// - // /////////////////////////////////////////////////// + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// - @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = OvsProviderResponse.class, required = true, description = "the ID of the ovs provider") - private Long id; + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = OvsProviderResponse.class, required = true, description = "the ID of the ovs provider") + private Long id; - @Parameter(name = ApiConstants.ENABLED, type = CommandType.BOOLEAN, required = true, description = "Enabled/Disabled the service provider") - private Boolean enabled; + @Parameter(name = ApiConstants.ENABLED, type = CommandType.BOOLEAN, required = true, description = "Enabled/Disabled the service provider") + private Boolean enabled; - // /////////////////////////////////////////////////// - // ///////////////// Accessors /////////////////////// - // /////////////////////////////////////////////////// - public void setId(Long id) { - this.id = id; - } + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// + public void setId(Long id) { + this.id = id; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setEnabled(Boolean enabled) { - this.enabled = enabled; - } + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } - public Boolean getEnabled() { - return enabled; - } + public Boolean getEnabled() { + return enabled; + } - // /////////////////////////////////////////////////// - // ///////////// API Implementation/////////////////// - // /////////////////////////////////////////////////// + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// - @Override - public String getCommandName() { - return s_name; - } + @Override + public String getCommandName() { + return s_name; + } - public static String getResultObjectName() { - return "boolean"; - } + public static String getResultObjectName() { + return "boolean"; + } - @Override - public long getEntityOwnerId() { - return Account.ACCOUNT_ID_SYSTEM; - } + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } - @Override - public String getEventType() { - return EventTypes.EVENT_NETWORK_ELEMENT_CONFIGURE; - } + @Override + public String getEventType() { + return EventTypes.EVENT_NETWORK_ELEMENT_CONFIGURE; + } - @Override - public String getEventDescription() { - return "configuring ovs provider: " + id; - } + @Override + public String getEventDescription() { + return "configuring ovs provider: " + id; + } - @Override - public ApiCommandJobType getInstanceType() { - return ApiCommandJobType.None; - } + @Override + public ApiCommandJobType getInstanceType() { + return ApiCommandJobType.None; + } - @Override - public Long getInstanceId() { - return id; - } + @Override + public Long getInstanceId() { + return id; + } - @Override - public void execute() throws ConcurrentOperationException, - ResourceUnavailableException, InsufficientCapacityException { - CallContext.current().setEventDetails("Ovs element: " + id); - OvsProvider result = _service.get(0).configure(this); - if (result != null) { - OvsProviderResponse ovsResponse = _responseGenerator - .createOvsProviderResponse(result); - ovsResponse.setResponseName(getCommandName()); - this.setResponseObject(ovsResponse); - } else { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, - "Failed to configure the ovs provider"); - } - } + @Override + public void execute() throws ConcurrentOperationException, + ResourceUnavailableException, InsufficientCapacityException { + CallContext.current().setEventDetails("Ovs element: " + id); + OvsProvider result = _service.get(0).configure(this); + if (result != null) { + OvsProviderResponse ovsResponse = _responseGenerator + .createOvsProviderResponse(result); + ovsResponse.setResponseName(getCommandName()); + this.setResponseObject(ovsResponse); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, + "Failed to configure the ovs provider"); + } + } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/router/ListOvsElementsCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/ListOvsElementsCmd.java index 9f5feeedc26..d5f73fd742a 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/router/ListOvsElementsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/router/ListOvsElementsCmd.java @@ -41,62 +41,64 @@ import com.cloud.network.element.VirtualRouterElementService; @APICommand(name = "listOvsElements", description = "Lists all available ovs elements.", responseObject = OvsProviderResponse.class) public class ListOvsElementsCmd extends BaseListCmd { - public static final Logger s_logger = Logger - .getLogger(ListNetworkOfferingsCmd.class.getName()); - private static final String _name = "listovselementsresponse"; - @Inject - private List _service; - // /////////////////////////////////////////////////// - // ////////////// API parameters ///////////////////// - // /////////////////////////////////////////////////// - @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = OvsProviderResponse.class, description = "list ovs elements by id") - private Long id; + public static final Logger s_logger = Logger + .getLogger(ListNetworkOfferingsCmd.class.getName()); + private static final String Name = "listovselementsresponse"; + @Inject + private List _service; + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = OvsProviderResponse.class, description = "list ovs elements by id") + private Long id; - @Parameter(name = ApiConstants.NSP_ID, type = CommandType.UUID, entityType = ProviderResponse.class, description = "list ovs elements by network service provider id") - private Long nspId; + @Parameter(name = ApiConstants.NSP_ID, type = CommandType.UUID, entityType = ProviderResponse.class, description = "list ovs elements by network service provider id") + private Long nspId; - @Parameter(name = ApiConstants.ENABLED, type = CommandType.BOOLEAN, description = "list network offerings by enabled state") - private Boolean enabled; + @Parameter(name = ApiConstants.ENABLED, type = CommandType.BOOLEAN, description = "list network offerings by enabled state") + private Boolean enabled; - // /////////////////////////////////////////////////// - // ///////////////// Accessors /////////////////////// - // /////////////////////////////////////////////////// + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setNspId(Long nspId) { - this.nspId = nspId; - } + public void setNspId(Long nspId) { + this.nspId = nspId; + } - public Long getNspId() { - return nspId; - } + public Long getNspId() { + return nspId; + } - public void setEnabled(Boolean enabled) { - this.enabled = enabled; - } + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } - public Boolean getEnabled() { - return enabled; - } + public Boolean getEnabled() { + return enabled; + } - @Override - public String getCommandName() { - return _name; - } - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException { + @Override + public String getCommandName() { + return Name; + } + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, + ResourceAllocationException { List providers = _service.get(0).searchForOvsElement(this); ListResponse response = new ListResponse(); List providerResponses = new ArrayList(); for (OvsProvider provider : providers) { - OvsProviderResponse providerResponse = _responseGenerator.createOvsProviderResponse(provider); + OvsProviderResponse providerResponse = _responseGenerator.createOvsProviderResponse(provider); providerResponses.add(providerResponse); } response.setResponses(providerResponses); diff --git a/api/src/org/apache/cloudstack/api/command/admin/router/ListVirtualRouterElementsCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/ListVirtualRouterElementsCmd.java index 4f04018833c..6f1792145be 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/router/ListVirtualRouterElementsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/router/ListVirtualRouterElementsCmd.java @@ -43,7 +43,7 @@ import com.cloud.network.element.VirtualRouterElementService; @APICommand(name = "listVirtualRouterElements", description = "Lists all available virtual router elements.", responseObject = VirtualRouterProviderResponse.class) public class ListVirtualRouterElementsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListNetworkOfferingsCmd.class.getName()); - private static final String _name = "listvirtualrouterelementsresponse"; + private static final String Name = "listvirtualrouterelementsresponse"; // TODO, VirtualRouterElementServer is not singleton in system! @Inject @@ -94,7 +94,7 @@ public class ListVirtualRouterElementsCmd extends BaseListCmd { @Override public String getCommandName() { - return _name; + return Name; } @Override diff --git a/api/src/org/apache/cloudstack/api/command/admin/router/UpgradeRouterTemplateCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/UpgradeRouterTemplateCmd.java index 3a20a515b8c..49477452142 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/router/UpgradeRouterTemplateCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/router/UpgradeRouterTemplateCmd.java @@ -26,7 +26,6 @@ import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseResponse; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.AccountResponse; import org.apache.cloudstack.api.response.ClusterResponse; import org.apache.cloudstack.api.response.DomainResponse; import org.apache.cloudstack.api.response.DomainRouterResponse; @@ -65,11 +64,9 @@ public class UpgradeRouterTemplateCmd extends org.apache.cloudstack.api.BaseCmd @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, description = "upgrades all routers within the specified zone") private Long zoneId; - @Parameter(name = ApiConstants.ACCOUNT_ID, - type = CommandType.UUID, - entityType = AccountResponse.class, - description = "upgrades all routers owned by the specified account") - private Long accountId; + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, + description="upgrades all routers owned by the specified account") + private String account; @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, @@ -97,8 +94,8 @@ public class UpgradeRouterTemplateCmd extends org.apache.cloudstack.api.BaseCmd return zoneId; } - public Long getAccountId() { - return accountId; + public String getAccount() { + return account; } public Long getDomainId() { @@ -134,7 +131,7 @@ public class UpgradeRouterTemplateCmd extends org.apache.cloudstack.api.BaseCmd if (result != null) { ListResponse response = _responseGenerator.createUpgradeRouterTemplateResponse(result); response.setResponseName(getCommandName()); - this.setResponseObject(response); + setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to upgrade router template"); } diff --git a/api/src/org/apache/cloudstack/api/command/admin/storage/AddImageStoreCmd.java b/api/src/org/apache/cloudstack/api/command/admin/storage/AddImageStoreCmd.java index 5dcedff2392..5e5bd3dcde5 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/storage/AddImageStoreCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/storage/AddImageStoreCmd.java @@ -95,7 +95,7 @@ public class AddImageStoreCmd extends BaseCmd { } public String getProviderName() { - return this.providerName; + return providerName; } public void setUrl(String url) { @@ -129,15 +129,15 @@ public class AddImageStoreCmd extends BaseCmd { } @Override - public void execute() { - try { - ImageStore result = _storageService.discoverImageStore(this); + public void execute(){ + try{ + ImageStore result = _storageService.discoverImageStore(getName(), getUrl(), getProviderName(), getZoneId(), getDetails()); ImageStoreResponse storeResponse = null; if (result != null) { storeResponse = _responseGenerator.createImageStoreResponse(result); storeResponse.setResponseName(getCommandName()); storeResponse.setObjectName("imagestore"); - this.setResponseObject(storeResponse); + setResponseObject(storeResponse); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add secondary storage"); } diff --git a/api/src/org/apache/cloudstack/api/command/admin/storage/AddS3Cmd.java b/api/src/org/apache/cloudstack/api/command/admin/storage/AddS3Cmd.java index cc6680bcac4..32897e4d59d 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/storage/AddS3Cmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/storage/AddS3Cmd.java @@ -56,7 +56,7 @@ import com.cloud.storage.ImageStore; public final class AddS3Cmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(AddS3Cmd.class.getName()); - private static String COMMAND_NAME = "adds3response"; + private static final String COMMAND_NAME = "adds3response"; @Parameter(name = S3_ACCESS_KEY, type = STRING, required = true, description = "S3 access key") private String accessKey; @@ -65,60 +65,54 @@ public final class AddS3Cmd extends BaseCmd { private String secretKey; @Parameter(name = S3_END_POINT, type = STRING, required = false, description = "S3 host name") - private String endPoint = null; + private final String endPoint = null; @Parameter(name = S3_BUCKET_NAME, type = STRING, required = true, description = "name of the template storage bucket") private String bucketName; @Parameter(name = S3_HTTPS_FLAG, type = BOOLEAN, required = false, description = "connect to the S3 endpoint via HTTPS?") - private Boolean httpsFlag = null; + private final Boolean httpsFlag = null; @Parameter(name = S3_CONNECTION_TIMEOUT, type = INTEGER, required = false, description = "connection timeout (milliseconds)") - private Integer connectionTimeout = null; + private final Integer connectionTimeout = null; @Parameter(name = S3_MAX_ERROR_RETRY, type = INTEGER, required = false, description = "maximum number of times to retry on error") - private Integer maxErrorRetry = null; + private final Integer maxErrorRetry = null; @Parameter(name = S3_SOCKET_TIMEOUT, type = INTEGER, required = false, description = "socket timeout (milliseconds)") - private Integer socketTimeout = null; + private final Integer socketTimeout = null; @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { - AddImageStoreCmd cmd = new AddImageStoreCmd() { - @Override - public Map getDetails() { - Map dm = new HashMap(); - dm.put(ApiConstants.S3_ACCESS_KEY, getAccessKey()); - dm.put(ApiConstants.S3_SECRET_KEY, getSecretKey()); - dm.put(ApiConstants.S3_END_POINT, getEndPoint()); - dm.put(ApiConstants.S3_BUCKET_NAME, getBucketName()); - if (getHttpsFlag() != null) { - dm.put(ApiConstants.S3_HTTPS_FLAG, getHttpsFlag().toString()); - } - if (getConnectionTimeout() != null) { - dm.put(ApiConstants.S3_CONNECTION_TIMEOUT, getConnectionTimeout().toString()); - } - if (getMaxErrorRetry() != null) { - dm.put(ApiConstants.S3_MAX_ERROR_RETRY, getMaxErrorRetry().toString()); - } - if (getSocketTimeout() != null) { - dm.put(ApiConstants.S3_SOCKET_TIMEOUT, getSocketTimeout().toString()); - } - return dm; - } - }; - cmd.setProviderName("S3"); + Map dm = new HashMap(); + dm.put(ApiConstants.S3_ACCESS_KEY, getAccessKey()); + dm.put(ApiConstants.S3_SECRET_KEY, getSecretKey()); + dm.put(ApiConstants.S3_END_POINT, getEndPoint()); + dm.put(ApiConstants.S3_BUCKET_NAME, getBucketName()); + if (getHttpsFlag() != null) { + dm.put(ApiConstants.S3_HTTPS_FLAG, getHttpsFlag().toString()); + } + if (getConnectionTimeout() != null) { + dm.put(ApiConstants.S3_CONNECTION_TIMEOUT, getConnectionTimeout().toString()); + } + if (getMaxErrorRetry() != null) { + dm.put(ApiConstants.S3_MAX_ERROR_RETRY, getMaxErrorRetry().toString()); + } + if (getSocketTimeout() != null) { + dm.put(ApiConstants.S3_SOCKET_TIMEOUT, getSocketTimeout().toString()); + } - try { - ImageStore result = _storageService.discoverImageStore(cmd); + + try{ + ImageStore result = _storageService.discoverImageStore(null, null, "S3", null, dm); ImageStoreResponse storeResponse = null; if (result != null) { storeResponse = _responseGenerator.createImageStoreResponse(result); storeResponse.setResponseName(getCommandName()); storeResponse.setObjectName("secondarystorage"); - this.setResponseObject(storeResponse); + setResponseObject(storeResponse); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add S3 secondary storage"); } @@ -141,35 +135,35 @@ public final class AddS3Cmd extends BaseCmd { final AddS3Cmd thatAddS3Cmd = (AddS3Cmd)thatObject; - if (this.httpsFlag != null ? !this.httpsFlag.equals(thatAddS3Cmd.httpsFlag) : thatAddS3Cmd.httpsFlag != null) { + if (httpsFlag != null ? !httpsFlag.equals(thatAddS3Cmd.httpsFlag) : thatAddS3Cmd.httpsFlag != null) { return false; } - if (this.accessKey != null ? !this.accessKey.equals(thatAddS3Cmd.accessKey) : thatAddS3Cmd.accessKey != null) { + if (accessKey != null ? !accessKey.equals(thatAddS3Cmd.accessKey) : thatAddS3Cmd.accessKey != null) { return false; } - if (this.connectionTimeout != null ? !this.connectionTimeout.equals(thatAddS3Cmd.connectionTimeout) : thatAddS3Cmd.connectionTimeout != null) { + if (connectionTimeout != null ? !connectionTimeout.equals(thatAddS3Cmd.connectionTimeout) : thatAddS3Cmd.connectionTimeout != null) { return false; } - if (this.endPoint != null ? !this.endPoint.equals(thatAddS3Cmd.endPoint) : thatAddS3Cmd.endPoint != null) { + if (endPoint != null ? !endPoint.equals(thatAddS3Cmd.endPoint) : thatAddS3Cmd.endPoint != null) { return false; } - if (this.maxErrorRetry != null ? !this.maxErrorRetry.equals(thatAddS3Cmd.maxErrorRetry) : thatAddS3Cmd.maxErrorRetry != null) { + if (maxErrorRetry != null ? !maxErrorRetry.equals(thatAddS3Cmd.maxErrorRetry) : thatAddS3Cmd.maxErrorRetry != null) { return false; } - if (this.secretKey != null ? !this.secretKey.equals(thatAddS3Cmd.secretKey) : thatAddS3Cmd.secretKey != null) { + if (secretKey != null ? !secretKey.equals(thatAddS3Cmd.secretKey) : thatAddS3Cmd.secretKey != null) { return false; } - if (this.socketTimeout != null ? !this.socketTimeout.equals(thatAddS3Cmd.socketTimeout) : thatAddS3Cmd.socketTimeout != null) { + if (socketTimeout != null ? !socketTimeout.equals(thatAddS3Cmd.socketTimeout) : thatAddS3Cmd.socketTimeout != null) { return false; } - if (this.bucketName != null ? !this.bucketName.equals(thatAddS3Cmd.bucketName) : thatAddS3Cmd.bucketName != null) { + if (bucketName != null ? !bucketName.equals(thatAddS3Cmd.bucketName) : thatAddS3Cmd.bucketName != null) { return false; } @@ -180,14 +174,14 @@ public final class AddS3Cmd extends BaseCmd { @Override public int hashCode() { - int result = this.accessKey != null ? this.accessKey.hashCode() : 0; - result = 31 * result + (this.secretKey != null ? this.secretKey.hashCode() : 0); - result = 31 * result + (this.endPoint != null ? this.endPoint.hashCode() : 0); - result = 31 * result + (this.bucketName != null ? this.bucketName.hashCode() : 0); - result = 31 * result + (this.httpsFlag != null && this.httpsFlag == true ? 1 : 0); - result = 31 * result + (this.connectionTimeout != null ? this.connectionTimeout.hashCode() : 0); - result = 31 * result + (this.maxErrorRetry != null ? this.maxErrorRetry.hashCode() : 0); - result = 31 * result + (this.socketTimeout != null ? this.socketTimeout.hashCode() : 0); + int result = accessKey != null ? accessKey.hashCode() : 0; + result = 31 * result + (secretKey != null ? secretKey.hashCode() : 0); + result = 31 * result + (endPoint != null ? endPoint.hashCode() : 0); + result = 31 * result + (bucketName != null ? bucketName.hashCode() : 0); + result = 31 * result + (httpsFlag != null && httpsFlag == true ? 1 : 0); + result = 31 * result + (connectionTimeout != null ? connectionTimeout.hashCode() : 0); + result = 31 * result + (maxErrorRetry != null ? maxErrorRetry.hashCode() : 0); + result = 31 * result + (socketTimeout != null ? socketTimeout.hashCode() : 0); return result; @@ -204,35 +198,35 @@ public final class AddS3Cmd extends BaseCmd { } public String getAccessKey() { - return this.accessKey; + return accessKey; } public String getSecretKey() { - return this.secretKey; + return secretKey; } public String getEndPoint() { - return this.endPoint; + return endPoint; } public String getBucketName() { - return this.bucketName; + return bucketName; } public Boolean getHttpsFlag() { - return this.httpsFlag; + return httpsFlag; } public Integer getConnectionTimeout() { - return this.connectionTimeout; + return connectionTimeout; } public Integer getMaxErrorRetry() { - return this.maxErrorRetry; + return maxErrorRetry; } public Integer getSocketTimeout() { - return this.socketTimeout; + return socketTimeout; } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/storage/UpdateCloudToUseObjectStoreCmd.java b/api/src/org/apache/cloudstack/api/command/admin/storage/UpdateCloudToUseObjectStoreCmd.java new file mode 100644 index 00000000000..983a01c7fbe --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/admin/storage/UpdateCloudToUseObjectStoreCmd.java @@ -0,0 +1,142 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command.admin.storage; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ImageStoreResponse; + +import com.cloud.exception.DiscoveryException; +import com.cloud.storage.ImageStore; +import com.cloud.user.Account; + +@APICommand(name = "updateCloudToUseObjectStore", description = "Migrate current NFS secondary storages to use object store.", responseObject = ImageStoreResponse.class, since = "4.3.0") +public class UpdateCloudToUseObjectStoreCmd extends BaseCmd { + public static final Logger s_logger = Logger.getLogger(UpdateCloudToUseObjectStoreCmd.class.getName()); + private static final String s_name = "updatecloudtouseobjectstoreresponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the name for the image store") + private String name; + + @Parameter(name=ApiConstants.URL, type=CommandType.STRING, description="the URL for the image store") + private String url; + + @Parameter(name=ApiConstants.PROVIDER, type=CommandType.STRING, + required=true, description="the image store provider name") + private String providerName; + + @Parameter(name=ApiConstants.DETAILS, type=CommandType.MAP, description="the details for the image store. Example: details[0].key=accesskey&details[0].value=s389ddssaa&details[1].key=secretkey&details[1].value=8dshfsss") + private Map details; + + + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + + public String getUrl() { + return url; + } + + public String getName() { + return name; + } + + public Map getDetails() { + Map detailsMap = null; + if (details != null && !details.isEmpty()) { + detailsMap = new HashMap(); + Collection props = details.values(); + Iterator iter = props.iterator(); + while (iter.hasNext()) { + HashMap detail = (HashMap) iter.next(); + String key = detail.get("key"); + String value = detail.get("value"); + detailsMap.put(key, value); + } + } + return detailsMap; + } + + public String getProviderName() { + return providerName; + } + + public void setUrl(String url) { + this.url = url; + } + + + public void setProviderName(String providerName) { + this.providerName = providerName; + } + + public void setDetails(Map details) { + this.details = details; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + + @Override + public void execute(){ + try{ + ImageStore result = _storageService.migrateToObjectStore(getName(), getUrl(), getProviderName(), getDetails()); + ImageStoreResponse storeResponse = null; + if (result != null ) { + storeResponse = _responseGenerator.createImageStoreResponse(result); + storeResponse.setResponseName(getCommandName()); + storeResponse.setObjectName("imagestore"); + setResponseObject(storeResponse); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add secondary storage"); + } + } catch (DiscoveryException ex) { + s_logger.warn("Exception: ", ex); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); + } + } +} diff --git a/api/src/org/apache/cloudstack/api/command/admin/swift/AddSwiftCmd.java b/api/src/org/apache/cloudstack/api/command/admin/swift/AddSwiftCmd.java index 3b684f41a63..173c95e2c0d 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/swift/AddSwiftCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/swift/AddSwiftCmd.java @@ -27,7 +27,6 @@ import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.command.admin.storage.AddImageStoreCmd; import org.apache.cloudstack.api.response.ImageStoreResponse; import com.cloud.exception.DiscoveryException; @@ -91,27 +90,19 @@ public class AddSwiftCmd extends BaseCmd { @Override public void execute() { - AddImageStoreCmd cmd = new AddImageStoreCmd() { - @Override - public Map getDetails() { - Map dm = new HashMap(); - dm.put(ApiConstants.ACCOUNT, getAccount()); - dm.put(ApiConstants.USERNAME, getUsername()); - dm.put(ApiConstants.KEY, getKey()); - return dm; - } - }; - cmd.setProviderName("Swift"); - cmd.setUrl(this.getUrl()); + Map dm = new HashMap(); + dm.put(ApiConstants.ACCOUNT, getAccount()); + dm.put(ApiConstants.USERNAME, getUsername()); + dm.put(ApiConstants.KEY, getKey()); - try { - ImageStore result = _storageService.discoverImageStore(cmd); + try{ + ImageStore result = _storageService.discoverImageStore(null, getUrl(), "Swift", null, dm); ImageStoreResponse storeResponse = null; if (result != null) { storeResponse = _responseGenerator.createImageStoreResponse(result); storeResponse.setResponseName(getCommandName()); storeResponse.setObjectName("secondarystorage"); - this.setResponseObject(storeResponse); + setResponseObject(storeResponse); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add Swift secondary storage"); } diff --git a/api/src/org/apache/cloudstack/api/command/admin/systemvm/ScaleSystemVMCmd.java b/api/src/org/apache/cloudstack/api/command/admin/systemvm/ScaleSystemVMCmd.java index 247df1eaed5..370815d625c 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/systemvm/ScaleSystemVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/systemvm/ScaleSystemVMCmd.java @@ -16,7 +16,10 @@ // under the License. package org.apache.cloudstack.api.command.admin.systemvm; -import org.apache.log4j.Logger; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -28,6 +31,7 @@ import org.apache.cloudstack.api.command.user.vm.UpgradeVMCmd; import org.apache.cloudstack.api.response.ServiceOfferingResponse; import org.apache.cloudstack.api.response.SystemVmResponse; import org.apache.cloudstack.context.CallContext; +import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -39,15 +43,8 @@ import com.cloud.offering.ServiceOffering; import com.cloud.user.Account; import com.cloud.vm.VirtualMachine; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -@APICommand(name = "scaleSystemVm", - responseObject = SystemVmResponse.class, - description = "Scale the service offering for a system vm (console proxy or secondary storage). " + "The system vm must be in a \"Stopped\" state for " - + "this command to take effect.") +@APICommand(name = "scaleSystemVm", responseObject = SystemVmResponse.class, description = "Scale the service offering for a system vm (console proxy or secondary storage). " + + "The system vm must be in a \"Stopped\" state for " + "this command to take effect.") public class ScaleSystemVMCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(UpgradeVMCmd.class.getName()); private static final String s_name = "changeserviceforsystemvmresponse"; @@ -59,17 +56,11 @@ public class ScaleSystemVMCmd extends BaseAsyncCmd { @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = SystemVmResponse.class, required = true, description = "The ID of the system vm") private Long id; - @Parameter(name = ApiConstants.SERVICE_OFFERING_ID, - type = CommandType.UUID, - entityType = ServiceOfferingResponse.class, - required = true, - description = "the service offering ID to apply to the system vm") + @Parameter(name = ApiConstants.SERVICE_OFFERING_ID, type = CommandType.UUID, entityType = ServiceOfferingResponse.class, required = true, description = "the service offering ID to apply to the system vm") private Long serviceOfferingId; - @Parameter(name=ApiConstants.CUSTOM_PARAMETERS, - type = CommandType.MAP, - description = "name value pairs of custom parameters for cpu, memory and cpunumber. example customparameters[i].name=value") - private Map customParameters; + @Parameter(name = ApiConstants.DETAILS, type = CommandType.MAP, description = "name value pairs of custom parameters for cpu, memory and cpunumber. example details[i].name=value") + private Map details; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -83,13 +74,13 @@ public class ScaleSystemVMCmd extends BaseAsyncCmd { return serviceOfferingId; } - public Map getCustomParameters() { - Map customparameterMap = new HashMap(); - if (customParameters != null && customParameters.size() != 0) { - Collection parameterCollection = customParameters.values(); + public Map getDetails() { + Map customparameterMap = new HashMap(); + if (details != null && details.size() != 0) { + Collection parameterCollection = details.values(); Iterator iter = parameterCollection.iterator(); while (iter.hasNext()) { - HashMap value = (HashMap) iter.next(); + HashMap value = (HashMap)iter.next(); for (String key : value.keySet()) { customparameterMap.put(key, value.get(key)); } diff --git a/api/src/org/apache/cloudstack/api/command/admin/systemvm/UpgradeSystemVMCmd.java b/api/src/org/apache/cloudstack/api/command/admin/systemvm/UpgradeSystemVMCmd.java index a49828be89f..da0564e9e67 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/systemvm/UpgradeSystemVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/systemvm/UpgradeSystemVMCmd.java @@ -16,7 +16,10 @@ // under the License. package org.apache.cloudstack.api.command.admin.systemvm; -import org.apache.log4j.Logger; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -28,21 +31,15 @@ import org.apache.cloudstack.api.command.user.vm.UpgradeVMCmd; import org.apache.cloudstack.api.response.ServiceOfferingResponse; import org.apache.cloudstack.api.response.SystemVmResponse; import org.apache.cloudstack.context.CallContext; +import org.apache.log4j.Logger; import com.cloud.exception.InvalidParameterValueException; import com.cloud.offering.ServiceOffering; import com.cloud.user.Account; import com.cloud.vm.VirtualMachine; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -@APICommand(name = "changeServiceForSystemVm", - responseObject = SystemVmResponse.class, - description = "Changes the service offering for a system vm (console proxy or secondary storage). " + "The system vm must be in a \"Stopped\" state for " - + "this command to take effect.") +@APICommand(name = "changeServiceForSystemVm", responseObject = SystemVmResponse.class, description = "Changes the service offering for a system vm (console proxy or secondary storage). " + + "The system vm must be in a \"Stopped\" state for " + "this command to take effect.") public class UpgradeSystemVMCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpgradeVMCmd.class.getName()); private static final String s_name = "changeserviceforsystemvmresponse"; @@ -54,17 +51,11 @@ public class UpgradeSystemVMCmd extends BaseCmd { @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = SystemVmResponse.class, required = true, description = "The ID of the system vm") private Long id; - @Parameter(name = ApiConstants.SERVICE_OFFERING_ID, - type = CommandType.UUID, - entityType = ServiceOfferingResponse.class, - required = true, - description = "the service offering ID to apply to the system vm") + @Parameter(name = ApiConstants.SERVICE_OFFERING_ID, type = CommandType.UUID, entityType = ServiceOfferingResponse.class, required = true, description = "the service offering ID to apply to the system vm") private Long serviceOfferingId; - @Parameter(name=ApiConstants.CUSTOM_PARAMETERS, - type = CommandType.MAP, - description = "name value pairs of custom parameters for cpu, memory and cpunumber. example customparameters[i].name=value") - private Map customParameters; + @Parameter(name = ApiConstants.DETAILS, type = CommandType.MAP, description = "name value pairs of custom parameters for cpu, memory and cpunumber. example details[i].name=value") + private Map details; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -78,13 +69,13 @@ public class UpgradeSystemVMCmd extends BaseCmd { return serviceOfferingId; } - public Map getCustomParameters() { - Map customparameterMap = new HashMap(); - if (customParameters != null && customParameters.size() !=0){ - Collection parameterCollection = customParameters.values(); + public Map getDetails() { + Map customparameterMap = new HashMap(); + if (details != null && details.size() != 0) { + Collection parameterCollection = details.values(); Iterator iter = parameterCollection.iterator(); while (iter.hasNext()) { - HashMap value = (HashMap) iter.next(); + HashMap value = (HashMap)iter.next(); for (String key : value.keySet()) { customparameterMap.put(key, value.get(key)); } diff --git a/api/src/org/apache/cloudstack/api/command/admin/usage/AddTrafficTypeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/usage/AddTrafficTypeCmd.java index e6e18cb9ffa..0fcb8f87e54 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/usage/AddTrafficTypeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/usage/AddTrafficTypeCmd.java @@ -77,6 +77,10 @@ public class AddTrafficTypeCmd extends BaseAsyncCreateCmd { @Parameter(name = ApiConstants.VLAN, type = CommandType.STRING, description = "The VLAN id to be used for Management traffic by VMware host") private String vlan; + @Parameter(name=ApiConstants.ISOLATION_METHOD, type=CommandType.STRING, description="Used if physical network has multiple isolation types and traffic type is public." + + " Choose which isolation method. Valid options currently 'vlan' or 'vxlan', defaults to 'vlan'.") + private String isolationMethod; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -118,6 +122,14 @@ public class AddTrafficTypeCmd extends BaseAsyncCreateCmd { return vlan; } + public String getIsolationMethod() { + if (isolationMethod != null && !isolationMethod.isEmpty()) { + return isolationMethod; + } else { + return "vlan"; + } + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -148,7 +160,7 @@ public class AddTrafficTypeCmd extends BaseAsyncCreateCmd { @Override public void create() throws ResourceAllocationException { PhysicalNetworkTrafficType result = - _networkService.addTrafficTypeToPhysicalNetwork(getPhysicalNetworkId(), getTrafficType(), getXenLabel(), getKvmLabel(), getVmwareLabel(), + _networkService.addTrafficTypeToPhysicalNetwork(getPhysicalNetworkId(), getTrafficType(), getIsolationMethod(), getXenLabel(), getKvmLabel(), getVmwareLabel(), getSimulatorLabel(), getVlan(), getHypervLabel()); if (result != null) { setEntityId(result.getId()); diff --git a/api/src/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypeImplementorsCmd.java b/api/src/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypeImplementorsCmd.java index 3a1dfba61c8..159608ec589 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypeImplementorsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypeImplementorsCmd.java @@ -43,7 +43,7 @@ import com.cloud.utils.Pair; since = "3.0.0") public class ListTrafficTypeImplementorsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListTrafficTypeImplementorsCmd.class); - private static final String _name = "listtraffictypeimplementorsresponse"; + private static final String Name = "listtraffictypeimplementorsresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -87,6 +87,6 @@ public class ListTrafficTypeImplementorsCmd extends BaseListCmd { @Override public String getCommandName() { - return _name; + return Name; } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypesCmd.java b/api/src/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypesCmd.java index 378058f04f7..47ba781cdef 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypesCmd.java @@ -37,7 +37,7 @@ import com.cloud.utils.Pair; @APICommand(name = "listTrafficTypes", description = "Lists traffic types of a given physical network.", responseObject = ProviderResponse.class, since = "3.0.0") public class ListTrafficTypesCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListTrafficTypesCmd.class.getName()); - private static final String _name = "listtraffictypesresponse"; + private static final String Name = "listtraffictypesresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -66,7 +66,7 @@ public class ListTrafficTypesCmd extends BaseListCmd { ///////////////////////////////////////////////////// @Override public String getCommandName() { - return _name; + return Name; } @Override diff --git a/api/src/org/apache/cloudstack/api/command/admin/vlan/CreateVlanIpRangeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vlan/CreateVlanIpRangeCmd.java index dbaac6e742a..cd3dd7ea9bf 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/vlan/CreateVlanIpRangeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vlan/CreateVlanIpRangeCmd.java @@ -147,6 +147,9 @@ public class CreateVlanIpRangeCmd extends BaseCmd { } public String getVlan() { + if (vlan == null || vlan.isEmpty()) { + vlan = "untagged"; + } return vlan; } diff --git a/api/src/org/apache/cloudstack/api/command/admin/vm/GetVMUserDataCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vm/GetVMUserDataCmd.java new file mode 100644 index 00000000000..0e527149821 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/admin/vm/GetVMUserDataCmd.java @@ -0,0 +1,81 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.cloudstack.api.command.admin.vm; + +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.VMUserDataResponse; +import org.apache.log4j.Logger; + +import com.cloud.user.Account; +import com.cloud.uservm.UserVm; + +@APICommand(name = "getVirtualMachineUserData", description = "Returns user data associated with the VM", responseObject = VMUserDataResponse.class, since = "4.4") +public class GetVMUserDataCmd extends BaseCmd { + public static final Logger s_logger = Logger.getLogger(GetVMUserDataCmd.class); + private static final String s_name = "getvirtualmachineuserdataresponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID, type = CommandType.UUID, entityType = UserVmResponse.class, required = true, description = "The ID of the virtual machine") + private Long vmId; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public long getId() { + return vmId; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public void execute() { + String userData = _userVmService.getVmUserData(getId()); + VMUserDataResponse resp = new VMUserDataResponse(); + resp.setVmId(_entityMgr.findById(UserVm.class, getId()).getUuid()); + resp.setUserData(userData); + resp.setObjectName("virtualmachineuserdata"); + resp.setResponseName(getCommandName()); + this.setResponseObject(resp); + } + + @Override + public long getEntityOwnerId() { + UserVm userVm = _entityMgr.findById(UserVm.class, getId()); + if (userVm != null) { + return userVm.getAccountId(); + } + + return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked + } + + @Override + public String getCommandName() { + return s_name; + } +} diff --git a/api/src/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmd.java index e3c04337f73..96d5c6acece 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmd.java @@ -42,7 +42,7 @@ import com.cloud.user.Account; @APICommand(name = "createVPCOffering", description = "Creates VPC offering", responseObject = VpcOfferingResponse.class) public class CreateVPCOfferingCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(CreateVPCOfferingCmd.class.getName()); - private static final String _name = "createvpcofferingresponse"; + private static final String Name = "createvpcofferingresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -150,7 +150,7 @@ public class CreateVPCOfferingCmd extends BaseAsyncCreateCmd { @Override public String getCommandName() { - return _name; + return Name; } @Override diff --git a/api/src/org/apache/cloudstack/api/command/admin/vpc/UpdateVPCOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vpc/UpdateVPCOfferingCmd.java index 05b6f9d6fbd..3526b4b3ac9 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/vpc/UpdateVPCOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vpc/UpdateVPCOfferingCmd.java @@ -33,7 +33,7 @@ import com.cloud.user.Account; @APICommand(name = "updateVPCOffering", description = "Updates VPC offering", responseObject = VpcOfferingResponse.class) public class UpdateVPCOfferingCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(UpdateVPCOfferingCmd.class.getName()); - private static final String _name = "updatevpcofferingresponse"; + private static final String Name = "updatevpcofferingresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -76,7 +76,7 @@ public class UpdateVPCOfferingCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// @Override public String getCommandName() { - return _name; + return Name; } @Override diff --git a/api/src/org/apache/cloudstack/api/command/user/affinitygroup/ListAffinityGroupsCmd.java b/api/src/org/apache/cloudstack/api/command/user/affinitygroup/ListAffinityGroupsCmd.java index 367dec91ce7..0761a643452 100644 --- a/api/src/org/apache/cloudstack/api/command/user/affinitygroup/ListAffinityGroupsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/affinitygroup/ListAffinityGroupsCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.affinitygroup; import org.apache.log4j.Logger; - import org.apache.cloudstack.affinity.AffinityGroupResponse; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandJobType; @@ -79,9 +78,9 @@ public class ListAffinityGroupsCmd extends BaseListAccountResourcesCmd { @Override public void execute() { - ListResponse response = - _queryService.listAffinityGroups(id, affinityGroupName, affinityGroupType, virtualMachineId, this.getAccountName(), this.getDomainId(), this.isRecursive(), - this.listAll(), this.getStartIndex(), this.getPageSizeVal()); + ListResponse response = _queryService.listAffinityGroups(id, affinityGroupName, + affinityGroupType, virtualMachineId, this.getAccountName(), this.getDomainId(), this.isRecursive(), + this.listAll(), this.getStartIndex(), this.getPageSizeVal(), this.getKeyword()); response.setResponseName(getCommandName()); this.setResponseObject(response); diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/ListAutoScaleVmProfilesCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/ListAutoScaleVmProfilesCmd.java index 651f98703e8..34c2543b9c6 100644 --- a/api/src/org/apache/cloudstack/api/command/user/autoscale/ListAutoScaleVmProfilesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/ListAutoScaleVmProfilesCmd.java @@ -19,15 +19,15 @@ package org.apache.cloudstack.api.command.user.autoscale; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; - import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.AutoScaleVmProfileResponse; import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ServiceOfferingResponse; import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.log4j.Logger; import com.cloud.network.as.AutoScaleVmProfile; @@ -47,6 +47,9 @@ public class ListAutoScaleVmProfilesCmd extends BaseListProjectAndAccountResourc @Parameter(name = ApiConstants.TEMPLATE_ID, type = CommandType.UUID, entityType = TemplateResponse.class, description = "the templateid of the autoscale vm profile") private Long templateId; + @Parameter(name = ApiConstants.SERVICE_OFFERING_ID, type = CommandType.UUID, entityType = ServiceOfferingResponse.class, description = "list profiles by service offering id") + private Long serviceOffId; + @Parameter(name = ApiConstants.OTHER_DEPLOY_PARAMS, type = CommandType.STRING, description = "the otherdeployparameters of the autoscale vm profile") private String otherDeployParams; @@ -66,6 +69,10 @@ public class ListAutoScaleVmProfilesCmd extends BaseListProjectAndAccountResourc return otherDeployParams; } + public Long getServiceOfferingId() { + return serviceOffId; + } + // /////////////////////////////////////////////////// // ///////////// API Implementation/////////////////// // /////////////////////////////////////////////////// diff --git a/api/src/org/apache/cloudstack/api/command/user/iso/ListIsosCmd.java b/api/src/org/apache/cloudstack/api/command/user/iso/ListIsosCmd.java index 3e66e52249f..95b771fcc43 100644 --- a/api/src/org/apache/cloudstack/api/command/user/iso/ListIsosCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/iso/ListIsosCmd.java @@ -73,6 +73,9 @@ public class ListIsosCmd extends BaseListTaggedResourcesCmd { @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, description = "the ID of the zone") private Long zoneId; + @Parameter(name=ApiConstants.SHOW_REMOVED, type=CommandType.BOOLEAN, description="show removed ISOs as well") + private Boolean showRemoved; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -109,6 +112,10 @@ public class ListIsosCmd extends BaseListTaggedResourcesCmd { return zoneId; } + public Boolean getShowRemoved() { + return (showRemoved != null ? showRemoved : false); + } + public boolean listInReadyState() { Account account = CallContext.current().getCallingAccount(); // It is account specific if account is admin type and domainId and accountName are not null diff --git a/api/src/org/apache/cloudstack/api/command/user/loadbalancer/AssignCertToLoadBalancerCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/AssignCertToLoadBalancerCmd.java index 4ea4a588cea..4b0ea544c5e 100644 --- a/api/src/org/apache/cloudstack/api/command/user/loadbalancer/AssignCertToLoadBalancerCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/AssignCertToLoadBalancerCmd.java @@ -1,3 +1,4 @@ + // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -42,7 +43,7 @@ public class AssignCertToLoadBalancerCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(AssignCertToLoadBalancerCmd.class.getName()); - private static final String s_name = "assignCertToLoadBalancer"; + private static final String s_name = "assigncerttoloadbalancerresponse"; @Parameter(name = ApiConstants.LBID, type = CommandType.UUID, diff --git a/api/src/org/apache/cloudstack/api/command/user/loadbalancer/RemoveCertFromLoadBalancerCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/RemoveCertFromLoadBalancerCmd.java index e92d20801c4..ea420f31bf5 100644 --- a/api/src/org/apache/cloudstack/api/command/user/loadbalancer/RemoveCertFromLoadBalancerCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/RemoveCertFromLoadBalancerCmd.java @@ -41,7 +41,7 @@ public class RemoveCertFromLoadBalancerCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(RemoveCertFromLoadBalancerCmd.class.getName()); - private static final String s_name = "removeCertFromLoadBalancer"; + private static final String s_name = "removecertfromloadbalancerresponse"; @Parameter(name = ApiConstants.LBID, type = CommandType.UUID, diff --git a/api/src/org/apache/cloudstack/api/command/user/network/DeleteNetworkCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/DeleteNetworkCmd.java index a48e01b0d36..808051ecdef 100644 --- a/api/src/org/apache/cloudstack/api/command/user/network/DeleteNetworkCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/DeleteNetworkCmd.java @@ -45,6 +45,10 @@ public class DeleteNetworkCmd extends BaseAsyncCmd { @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = NetworkResponse.class, required = true, description = "the ID of the network") private Long id; + @Parameter(name = ApiConstants.FORCED, type = CommandType.BOOLEAN, required = false, description = "Force delete a network." + + " Network will be marked as 'Destroy' even when commands to shutdown and cleanup to the backend fails.") + private Boolean forced; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -53,6 +57,10 @@ public class DeleteNetworkCmd extends BaseAsyncCmd { return id; } + public boolean isForced() { + return (forced != null) ? forced : false; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -65,7 +73,7 @@ public class DeleteNetworkCmd extends BaseAsyncCmd { @Override public void execute() { CallContext.current().setEventDetails("Network Id: " + id); - boolean result = _networkService.deleteNetwork(id); + boolean result = _networkService.deleteNetwork(id, isForced()); if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); diff --git a/api/src/org/apache/cloudstack/api/command/user/network/ListNetworkACLListsCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/ListNetworkACLListsCmd.java index 56aad945101..2e50bb8cf22 100644 --- a/api/src/org/apache/cloudstack/api/command/user/network/ListNetworkACLListsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/ListNetworkACLListsCmd.java @@ -23,7 +23,6 @@ import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseListCmd; import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.ListResponse; @@ -34,7 +33,7 @@ import org.apache.cloudstack.api.response.VpcResponse; import com.cloud.network.vpc.NetworkACL; import com.cloud.utils.Pair; -@APICommand(name = "listNetworkACLLists", description="Lists all network ACLs", responseObject=NetworkACLResponse.class) +@APICommand(name = "listNetworkACLLists", description = "Lists all network ACLs", responseObject = NetworkACLResponse.class) public class ListNetworkACLListsCmd extends BaseListProjectAndAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListNetworkACLListsCmd.class.getName()); @@ -85,8 +84,8 @@ public class ListNetworkACLListsCmd extends BaseListProjectAndAccountResourcesCm } @Override - public void execute(){ - Pair,Integer> result = _networkACLService.listNetworkACLs(this); + public void execute() { + Pair, Integer> result = _networkACLService.listNetworkACLs(this); ListResponse response = new ListResponse(); List aclResponses = new ArrayList(); @@ -96,6 +95,6 @@ public class ListNetworkACLListsCmd extends BaseListProjectAndAccountResourcesCm } response.setResponses(aclResponses, result.second()); response.setResponseName(getCommandName()); - this.setResponseObject(response); + setResponseObject(response); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/network/ListNetworkACLsCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/ListNetworkACLsCmd.java index 99c620ca14d..7f8aef4cd77 100644 --- a/api/src/org/apache/cloudstack/api/command/user/network/ListNetworkACLsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/ListNetworkACLsCmd.java @@ -25,7 +25,6 @@ import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.NetworkACLItemResponse; import org.apache.cloudstack.api.response.NetworkACLResponse; @@ -43,8 +42,8 @@ public class ListNetworkACLsCmd extends BaseListTaggedResourcesCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = NetworkACLItemResponse.class, - description="Lists network ACL Item with the specified ID") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = NetworkACLItemResponse.class, + description = "Lists network ACL Item with the specified ID") private Long id; @Parameter(name = ApiConstants.NETWORK_ID, type = CommandType.UUID, entityType = NetworkResponse.class, description = "list network ACL Items by network Id") @@ -111,6 +110,6 @@ public class ListNetworkACLsCmd extends BaseListTaggedResourcesCmd { } response.setResponses(aclResponses, result.second()); response.setResponseName(getCommandName()); - this.setResponseObject(response); + setResponseObject(response); } } diff --git a/api/src/org/apache/cloudstack/api/command/user/network/ListNetworkOfferingsCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/ListNetworkOfferingsCmd.java index 2c2b1e17a8f..552a64a63b2 100644 --- a/api/src/org/apache/cloudstack/api/command/user/network/ListNetworkOfferingsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/ListNetworkOfferingsCmd.java @@ -35,7 +35,7 @@ import com.cloud.offering.NetworkOffering; @APICommand(name = "listNetworkOfferings", description = "Lists all available network offerings.", responseObject = NetworkOfferingResponse.class) public class ListNetworkOfferingsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListNetworkOfferingsCmd.class.getName()); - private static final String _name = "listnetworkofferingsresponse"; + private static final String Name = "listnetworkofferingsresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -181,7 +181,7 @@ public class ListNetworkOfferingsCmd extends BaseListCmd { ///////////////////////////////////////////////////// @Override public String getCommandName() { - return _name; + return Name; } @Override diff --git a/api/src/org/apache/cloudstack/api/command/user/network/ListNetworksCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/ListNetworksCmd.java index fa27a4ad212..111fac31174 100644 --- a/api/src/org/apache/cloudstack/api/command/user/network/ListNetworksCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/ListNetworksCmd.java @@ -19,8 +19,6 @@ package org.apache.cloudstack.api.command.user.network; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; - import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; @@ -30,13 +28,15 @@ import org.apache.cloudstack.api.response.NetworkResponse; import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import org.apache.cloudstack.api.response.VpcResponse; import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.log4j.Logger; import com.cloud.network.Network; +import com.cloud.utils.Pair; @APICommand(name = "listNetworks", description = "Lists all available networks.", responseObject = NetworkResponse.class) public class ListNetworksCmd extends BaseListTaggedResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListNetworksCmd.class.getName()); - private static final String _name = "listnetworksresponse"; + private static final String Name = "listnetworksresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -53,24 +53,16 @@ public class ListNetworksCmd extends BaseListTaggedResourcesCmd { @Parameter(name = ApiConstants.IS_SYSTEM, type = CommandType.BOOLEAN, description = "true if network is system, false otherwise") private Boolean isSystem; - @Parameter(name = ApiConstants.ACL_TYPE, - type = CommandType.STRING, - description = "list networks by ACL (access control list) type. Supported values are Account and Domain") + @Parameter(name = ApiConstants.ACL_TYPE, type = CommandType.STRING, description = "list networks by ACL (access control list) type. Supported values are Account and Domain") private String aclType; @Parameter(name = ApiConstants.TRAFFIC_TYPE, type = CommandType.STRING, description = "type of the traffic") private String trafficType; - @Parameter(name = ApiConstants.PHYSICAL_NETWORK_ID, - type = CommandType.UUID, - entityType = PhysicalNetworkResponse.class, - description = "list networks by physical network id") + @Parameter(name = ApiConstants.PHYSICAL_NETWORK_ID, type = CommandType.UUID, entityType = PhysicalNetworkResponse.class, description = "list networks by physical network id") private Long physicalNetworkId; - @Parameter(name = ApiConstants.SUPPORTED_SERVICES, - type = CommandType.LIST, - collectionType = CommandType.STRING, - description = "list networks supporting certain services") + @Parameter(name = ApiConstants.SUPPORTED_SERVICES, type = CommandType.LIST, collectionType = CommandType.STRING, description = "list networks supporting certain services") private List supportedServices; @Parameter(name = ApiConstants.RESTART_REQUIRED, type = CommandType.BOOLEAN, description = "list networks by restartRequired") @@ -149,20 +141,19 @@ public class ListNetworksCmd extends BaseListTaggedResourcesCmd { ///////////////////////////////////////////////////// @Override public String getCommandName() { - return _name; + return Name; } @Override public void execute() { - List networks = _networkService.searchForNetworks(this); + Pair, Integer> networks = _networkService.searchForNetworks(this); ListResponse response = new ListResponse(); List networkResponses = new ArrayList(); - for (Network network : networks) { + for (Network network : networks.first()) { NetworkResponse networkResponse = _responseGenerator.createNetworkResponse(network); networkResponses.add(networkResponse); } - - response.setResponses(networkResponses); + response.setResponses(networkResponses, networks.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/org/apache/cloudstack/api/command/user/template/CopyTemplateCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/CopyTemplateCmd.java index 78bfc186d1c..87f94f72aa1 100644 --- a/api/src/org/apache/cloudstack/api/command/user/template/CopyTemplateCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/template/CopyTemplateCmd.java @@ -59,8 +59,7 @@ public class CopyTemplateCmd extends BaseAsyncCmd { @Parameter(name = ApiConstants.SOURCE_ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, - required = true, - description = "ID of the zone the template is currently hosted on.") + description = "ID of the zone the template is currently hosted on. If not specified and template is cross-zone, then we will sync this template to region wide image store.") private Long sourceZoneId; ///////////////////////////////////////////////////// @@ -137,7 +136,7 @@ public class CopyTemplateCmd extends BaseAsyncCmd { } response.setResponseName(getCommandName()); - this.setResponseObject(response); + setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to copy template"); } diff --git a/api/src/org/apache/cloudstack/api/command/user/template/ListTemplatesCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/ListTemplatesCmd.java index 7e347f3e32f..d393c6a5fdf 100644 --- a/api/src/org/apache/cloudstack/api/command/user/template/ListTemplatesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/template/ListTemplatesCmd.java @@ -65,6 +65,9 @@ public class ListTemplatesCmd extends BaseListTaggedResourcesCmd { @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, description = "list templates by zoneId") private Long zoneId; + @Parameter(name=ApiConstants.SHOW_REMOVED, type=CommandType.BOOLEAN, description="show removed templates as well") + private Boolean showRemoved; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -89,6 +92,10 @@ public class ListTemplatesCmd extends BaseListTaggedResourcesCmd { return zoneId; } + public Boolean getShowRemoved() { + return (showRemoved != null ? showRemoved : false); + } + public boolean listInReadyState() { Account account = CallContext.current().getCallingAccount(); diff --git a/api/src/org/apache/cloudstack/api/command/user/vm/AddIpToVmNicCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/AddIpToVmNicCmd.java index 09a912293db..439879add9b 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vm/AddIpToVmNicCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/AddIpToVmNicCmd.java @@ -16,8 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.vm; -import org.apache.log4j.Logger; - import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandJobType; import org.apache.cloudstack.api.ApiConstants; @@ -28,6 +26,7 @@ import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.NicResponse; import org.apache.cloudstack.api.response.NicSecondaryIpResponse; import org.apache.cloudstack.context.CallContext; +import org.apache.log4j.Logger; import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter.NetworkType; @@ -39,10 +38,10 @@ import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network; -import com.cloud.user.Account; import com.cloud.utils.net.NetUtils; import com.cloud.vm.Nic; import com.cloud.vm.NicSecondaryIp; +import com.cloud.vm.VirtualMachine; @APICommand(name = "addIpToNic", description = "Assigns secondary IP to NIC", responseObject = NicSecondaryIpResponse.class) public class AddIpToVmNicCmd extends BaseAsyncCmd { @@ -52,11 +51,7 @@ public class AddIpToVmNicCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @Parameter(name = ApiConstants.NIC_ID, - type = CommandType.UUID, - entityType = NicResponse.class, - required = true, - description = "the ID of the nic to which you want to assign private IP") + @Parameter(name = ApiConstants.NIC_ID, type = CommandType.UUID, entityType = NicResponse.class, required = true, description = "the ID of the nic to which you want to assign private IP") private Long nicId; @Parameter(name = ApiConstants.IP_ADDRESS, type = CommandType.STRING, required = false, description = "Secondary IP Address") @@ -70,36 +65,19 @@ public class AddIpToVmNicCmd extends BaseAsyncCmd { return "nic_secondary_ips"; } - public String getAccountName() { - return CallContext.current().getCallingAccount().getAccountName(); - } - - public long getDomainId() { - return CallContext.current().getCallingAccount().getDomainId(); - } - - private long getZoneId() { - Network ntwk = _entityMgr.findById(Network.class, getNetworkId()); - if (ntwk == null) { - throw new InvalidParameterValueException("Can't find zone id for specified"); - } - return ntwk.getDataCenterId(); - } - - public Long getNetworkId() { + private long getNetworkId() { Nic nic = _entityMgr.findById(Nic.class, nicId); if (nic == null) { throw new InvalidParameterValueException("Can't find network id for specified nic"); } - Long networkId = nic.getNetworkId(); - return networkId; + return nic.getNetworkId(); } - public Long getNicId() { + public long getNicId() { return nicId; } - public String getIpaddress() { + private String getIpaddress() { if (ipAddr != null) { return ipAddr; } else { @@ -107,18 +85,12 @@ public class AddIpToVmNicCmd extends BaseAsyncCmd { } } - public NetworkType getNetworkType() { + private NetworkType getNetworkType() { Network ntwk = _entityMgr.findById(Network.class, getNetworkId()); DataCenter dc = _entityMgr.findById(DataCenter.class, ntwk.getDataCenterId()); return dc.getNetworkType(); } - @Override - public long getEntityOwnerId() { - Account caller = CallContext.current().getCallingAccount(); - return caller.getAccountId(); - } - @Override public String getEventType() { return EventTypes.EVENT_NET_IP_ASSIGN; @@ -126,7 +98,7 @@ public class AddIpToVmNicCmd extends BaseAsyncCmd { @Override public String getEventDescription() { - return "associating ip to nic id: " + getNetworkId() + " in zone " + getZoneId(); + return "associating ip to nic id=" + getNicId() + " belonging to network id=" + getNetworkId(); } ///////////////////////////////////////////////////// @@ -156,9 +128,9 @@ public class AddIpToVmNicCmd extends BaseAsyncCmd { } try { - result = _networkService.allocateSecondaryGuestIP(_accountService.getAccount(getEntityOwnerId()), getZoneId(), getNicId(), getNetworkId(), getIpaddress()); + result = _networkService.allocateSecondaryGuestIP(getNicId(), getIpaddress()); } catch (InsufficientAddressCapacityException e) { - throw new InvalidParameterValueException("Allocating guest ip for nic failed"); + throw new InvalidParameterValueException("Allocating guest ip for nic failed : " + e.getMessage()); } if (result != null) { @@ -166,7 +138,7 @@ public class AddIpToVmNicCmd extends BaseAsyncCmd { if (getNetworkType() == NetworkType.Basic) { // add security group rules for the secondary ip addresses boolean success = false; - success = _securityGroupService.securityGroupRulesForVmSecIp(getNicId(), getNetworkId(), secondaryIp, true); + success = _securityGroupService.securityGroupRulesForVmSecIp(getNicId(), secondaryIp, true); if (success == false) { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to set security group rules for the secondary ip"); } @@ -197,4 +169,16 @@ public class AddIpToVmNicCmd extends BaseAsyncCmd { return ApiCommandJobType.IpAddress; } + @Override + public long getEntityOwnerId() { + Nic nic = _entityMgr.findById(Nic.class, nicId); + if (nic == null) { + throw new InvalidParameterValueException("Can't find nic for id specified"); + } + long vmId = nic.getInstanceId(); + VirtualMachine vm = _entityMgr.findById(VirtualMachine.class, vmId); + + return vm.getAccountId(); + } + } diff --git a/api/src/org/apache/cloudstack/api/command/user/vm/DeployVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/DeployVMCmd.java index fee6db25c87..eb19db43866 100755 --- a/api/src/org/apache/cloudstack/api/command/user/vm/DeployVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/DeployVMCmd.java @@ -24,9 +24,6 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import org.apache.cloudstack.api.BaseAsyncCreateCustomIdCmd; -import org.apache.log4j.Logger; - import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.affinity.AffinityGroupResponse; import org.apache.cloudstack.api.ACL; @@ -34,7 +31,7 @@ import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandJobType; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseAsyncCreateCustomIdCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.DiskOfferingResponse; @@ -48,6 +45,7 @@ import org.apache.cloudstack.api.response.TemplateResponse; import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.cloudstack.context.CallContext; +import org.apache.log4j.Logger; import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter.NetworkType; @@ -67,9 +65,7 @@ import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; import com.cloud.uservm.UserVm; -@APICommand(name = "deployVirtualMachine", - description = "Creates and automatically starts a virtual machine based on a service offering, disk offering, and template.", - responseObject = UserVmResponse.class) +@APICommand(name = "deployVirtualMachine", description = "Creates and automatically starts a virtual machine based on a service offering, disk offering, and template.", responseObject = UserVmResponse.class) public class DeployVMCmd extends BaseAsyncCreateCustomIdCmd { public static final Logger s_logger = Logger.getLogger(DeployVMCmd.class.getName()); @@ -79,27 +75,15 @@ public class DeployVMCmd extends BaseAsyncCreateCustomIdCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @Parameter(name = ApiConstants.ZONE_ID, - type = CommandType.UUID, - entityType = ZoneResponse.class, - required = true, - description = "availability zone for the virtual machine") + @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, required = true, description = "availability zone for the virtual machine") private Long zoneId; @ACL - @Parameter(name = ApiConstants.SERVICE_OFFERING_ID, - type = CommandType.UUID, - entityType = ServiceOfferingResponse.class, - required = true, - description = "the ID of the service offering for the virtual machine") + @Parameter(name = ApiConstants.SERVICE_OFFERING_ID, type = CommandType.UUID, entityType = ServiceOfferingResponse.class, required = true, description = "the ID of the service offering for the virtual machine") private Long serviceOfferingId; @ACL - @Parameter(name = ApiConstants.TEMPLATE_ID, - type = CommandType.UUID, - entityType = TemplateResponse.class, - required = true, - description = "the ID of the template for the virtual machine") + @Parameter(name = ApiConstants.TEMPLATE_ID, type = CommandType.UUID, entityType = TemplateResponse.class, required = true, description = "the ID of the template for the virtual machine") private Long templateId; @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "host name for the virtual machine") @@ -112,31 +96,21 @@ public class DeployVMCmd extends BaseAsyncCreateCustomIdCmd { @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "an optional account for the virtual machine. Must be used with domainId.") private String accountName; - @Parameter(name = ApiConstants.DOMAIN_ID, - type = CommandType.UUID, - entityType = DomainResponse.class, - description = "an optional domainId for the virtual machine. If the account parameter is used, domainId must also be used.") + @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, entityType = DomainResponse.class, description = "an optional domainId for the virtual machine. If the account parameter is used, domainId must also be used.") private Long domainId; //Network information @ACL(accessType = AccessType.UseNetwork) - @Parameter(name = ApiConstants.NETWORK_IDS, - type = CommandType.LIST, - collectionType = CommandType.UUID, - entityType = NetworkResponse.class, - description = "list of network ids used by virtual machine. Can't be specified with ipToNetworkList parameter") + @Parameter(name = ApiConstants.NETWORK_IDS, type = CommandType.LIST, collectionType = CommandType.UUID, entityType = NetworkResponse.class, description = "list of network ids used by virtual machine. Can't be specified with ipToNetworkList parameter") private List networkIds; //DataDisk information @ACL - @Parameter(name = ApiConstants.DISK_OFFERING_ID, - type = CommandType.UUID, - entityType = DiskOfferingResponse.class, - description = "the ID of the disk offering for the virtual machine. If the template is of ISO format," - + " the diskOfferingId is for the root disk volume. Otherwise this parameter is used to indicate the " - + "offering for the data disk volume. If the templateId parameter passed is from a Template object," - + " the diskOfferingId refers to a DATA Disk Volume created. If the templateId parameter passed is " - + "from an ISO object, the diskOfferingId refers to a ROOT Disk Volume created.") + @Parameter(name = ApiConstants.DISK_OFFERING_ID, type = CommandType.UUID, entityType = DiskOfferingResponse.class, description = "the ID of the disk offering for the virtual machine. If the template is of ISO format," + + " the diskOfferingId is for the root disk volume. Otherwise this parameter is used to indicate the " + + "offering for the data disk volume. If the templateId parameter passed is from a Template object," + + " the diskOfferingId refers to a DATA Disk Volume created. If the templateId parameter passed is " + + "from an ISO object, the diskOfferingId refers to a ROOT Disk Volume created.") private Long diskOfferingId; @Parameter(name = ApiConstants.SIZE, type = CommandType.LONG, description = "the arbitrary size for the DATADISK volume. Mutually exclusive with diskOfferingId") @@ -148,43 +122,27 @@ public class DeployVMCmd extends BaseAsyncCreateCustomIdCmd { @Parameter(name = ApiConstants.HYPERVISOR, type = CommandType.STRING, description = "the hypervisor on which to deploy the virtual machine") private String hypervisor; - @Parameter(name = ApiConstants.USER_DATA, - type = CommandType.STRING, - description = "an optional binary data that can be sent to the virtual machine upon a successful deployment. This binary data must be base64 encoded before adding it to the request. Using HTTP GET (via querystring), you can send up to 2KB of data after base64 encoding. Using HTTP POST(via POST body), you can send up to 32K of data after base64 encoding.", - length = 32768) + @Parameter(name = ApiConstants.USER_DATA, type = CommandType.STRING, description = "an optional binary data that can be sent to the virtual machine upon a successful deployment. This binary data must be base64 encoded before adding it to the request. Using HTTP GET (via querystring), you can send up to 2KB of data after base64 encoding. Using HTTP POST(via POST body), you can send up to 32K of data after base64 encoding.", length = 32768) private String userData; @Parameter(name = ApiConstants.SSH_KEYPAIR, type = CommandType.STRING, description = "name of the ssh key pair used to login to the virtual machine") private String sshKeyPairName; - @Parameter(name = ApiConstants.HOST_ID, - type = CommandType.UUID, - entityType = HostResponse.class, - description = "destination Host ID to deploy the VM to - parameter available for root admin only") + @Parameter(name = ApiConstants.HOST_ID, type = CommandType.UUID, entityType = HostResponse.class, description = "destination Host ID to deploy the VM to - parameter available for root admin only") private Long hostId; @ACL - @Parameter(name = ApiConstants.SECURITY_GROUP_IDS, - type = CommandType.LIST, - collectionType = CommandType.UUID, - entityType = SecurityGroupResponse.class, - description = "comma separated list of security groups id that going to be applied to the virtual machine. " - + "Should be passed only when vm is created from a zone with Basic Network support." + " Mutually exclusive with securitygroupnames parameter") + @Parameter(name = ApiConstants.SECURITY_GROUP_IDS, type = CommandType.LIST, collectionType = CommandType.UUID, entityType = SecurityGroupResponse.class, description = "comma separated list of security groups id that going to be applied to the virtual machine. " + + "Should be passed only when vm is created from a zone with Basic Network support." + " Mutually exclusive with securitygroupnames parameter") private List securityGroupIdList; @ACL - @Parameter(name = ApiConstants.SECURITY_GROUP_NAMES, - type = CommandType.LIST, - collectionType = CommandType.STRING, - entityType = SecurityGroupResponse.class, - description = "comma separated list of security groups names that going to be applied to the virtual machine." - + " Should be passed only when vm is created from a zone with Basic Network support. " + "Mutually exclusive with securitygroupids parameter") + @Parameter(name = ApiConstants.SECURITY_GROUP_NAMES, type = CommandType.LIST, collectionType = CommandType.STRING, entityType = SecurityGroupResponse.class, description = "comma separated list of security groups names that going to be applied to the virtual machine." + + " Should be passed only when vm is created from a zone with Basic Network support. " + "Mutually exclusive with securitygroupids parameter") private List securityGroupNameList; - @Parameter(name = ApiConstants.IP_NETWORK_LIST, - type = CommandType.MAP, - description = "ip to network mapping. Can't be specified with networkIds parameter." - + " Example: iptonetworklist[0].ip=10.10.10.11&iptonetworklist[0].ipv6=fc00:1234:5678::abcd&iptonetworklist[0].networkid=uuid - requests to use ip 10.10.10.11 in network id=uuid") + @Parameter(name = ApiConstants.IP_NETWORK_LIST, type = CommandType.MAP, description = "ip to network mapping. Can't be specified with networkIds parameter." + + " Example: iptonetworklist[0].ip=10.10.10.11&iptonetworklist[0].ipv6=fc00:1234:5678::abcd&iptonetworklist[0].networkid=uuid - requests to use ip 10.10.10.11 in network id=uuid") private Map ipToNetworkList; @Parameter(name = ApiConstants.IP_ADDRESS, type = CommandType.STRING, description = "the ip address for default vm's network") @@ -193,48 +151,30 @@ public class DeployVMCmd extends BaseAsyncCreateCustomIdCmd { @Parameter(name = ApiConstants.IP6_ADDRESS, type = CommandType.STRING, description = "the ipv6 address for default vm's network") private String ip6Address; - @Parameter(name = ApiConstants.KEYBOARD, - type = CommandType.STRING, - description = "an optional keyboard device type for the virtual machine. valid value can be one of de,de-ch,es,fi,fr,fr-be,fr-ch,is,it,jp,nl-be,no,pt,uk,us") + @Parameter(name = ApiConstants.KEYBOARD, type = CommandType.STRING, description = "an optional keyboard device type for the virtual machine. valid value can be one of de,de-ch,es,fi,fr,fr-be,fr-ch,is,it,jp,nl-be,no,pt,uk,us") private String keyboard; @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, entityType = ProjectResponse.class, description = "Deploy vm for the project") private Long projectId; - @Parameter(name = ApiConstants.START_VM, - type = CommandType.BOOLEAN, - description = "true if network offering supports specifying ip ranges; defaulted to true if not specified") + @Parameter(name = ApiConstants.START_VM, type = CommandType.BOOLEAN, description = "true if network offering supports specifying ip ranges; defaulted to true if not specified") private Boolean startVm; @ACL - @Parameter(name = ApiConstants.AFFINITY_GROUP_IDS, - type = CommandType.LIST, - collectionType = CommandType.UUID, - entityType = AffinityGroupResponse.class, - description = "comma separated list of affinity groups id that are going to be applied to the virtual machine." - + " Mutually exclusive with affinitygroupnames parameter") + @Parameter(name = ApiConstants.AFFINITY_GROUP_IDS, type = CommandType.LIST, collectionType = CommandType.UUID, entityType = AffinityGroupResponse.class, description = "comma separated list of affinity groups id that are going to be applied to the virtual machine." + + " Mutually exclusive with affinitygroupnames parameter") private List affinityGroupIdList; @ACL - @Parameter(name = ApiConstants.AFFINITY_GROUP_NAMES, - type = CommandType.LIST, - collectionType = CommandType.STRING, - entityType = AffinityGroupResponse.class, - description = "comma separated list of affinity groups names that are going to be applied to the virtual machine." - + "Mutually exclusive with affinitygroupids parameter") + @Parameter(name = ApiConstants.AFFINITY_GROUP_NAMES, type = CommandType.LIST, collectionType = CommandType.STRING, entityType = AffinityGroupResponse.class, description = "comma separated list of affinity groups names that are going to be applied to the virtual machine." + + "Mutually exclusive with affinitygroupids parameter") private List affinityGroupNameList; - @Parameter(name = ApiConstants.DISPLAY_VM, - type = CommandType.BOOLEAN, - since = "4.2", - description = "an optional field, whether to the display the vm to the end user or not.") + @Parameter(name = ApiConstants.DISPLAY_VM, type = CommandType.BOOLEAN, since = "4.2", description = "an optional field, whether to the display the vm to the end user or not.") private Boolean displayVm; - @Parameter(name = ApiConstants.CUSTOM_PARAMETERS, - type = CommandType.MAP, - since= "4.3", - description = "used to specify the custom parameters.") - private Map customParameters; + @Parameter(name = ApiConstants.DETAILS, type = CommandType.MAP, since = "4.3", description = "used to specify the custom parameters.") + private Map details; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -262,13 +202,13 @@ public class DeployVMCmd extends BaseAsyncCreateCustomIdCmd { return domainId; } - public Map getCustomParameters() { - Map customparameterMap = new HashMap(); - if (customParameters != null && customParameters.size() !=0){ - Collection parameterCollection = customParameters.values(); + public Map getDetails() { + Map customparameterMap = new HashMap(); + if (details != null && details.size() != 0) { + Collection parameterCollection = details.values(); Iterator iter = parameterCollection.iterator(); while (iter.hasNext()) { - HashMap value = (HashMap) iter.next(); + HashMap value = (HashMap)iter.next(); for (String key : value.keySet()) { customparameterMap.put(key, value.get(key)); } @@ -289,7 +229,6 @@ public class DeployVMCmd extends BaseAsyncCreateCustomIdCmd { return displayVm; } - public List getSecurityGroupIdList() { if (securityGroupNameList != null && securityGroupIdList != null) { throw new InvalidParameterValueException("securitygroupids parameter is mutually exclusive with securitygroupnames parameter"); @@ -556,27 +495,23 @@ public class DeployVMCmd extends BaseAsyncCreateCustomIdCmd { if (getNetworkIds() != null) { throw new InvalidParameterValueException("Can't specify network Ids in Basic zone"); } else { - vm = - _userVmService.createBasicSecurityGroupVirtualMachine(zone, serviceOffering, template, getSecurityGroupIdList(), owner, name, displayName, - diskOfferingId, size, group, getHypervisor(), getHttpMethod(), userData, sshKeyPairName, getIpToNetworkMap(), addrs, displayVm, keyboard, - getAffinityGroupIdList(), getCustomParameters(), getCustomId()); + vm = _userVmService.createBasicSecurityGroupVirtualMachine(zone, serviceOffering, template, getSecurityGroupIdList(), owner, name, displayName, diskOfferingId, + size, group, getHypervisor(), getHttpMethod(), userData, sshKeyPairName, getIpToNetworkMap(), addrs, displayVm, keyboard, getAffinityGroupIdList(), + getDetails(), getCustomId()); } } else { if (zone.isSecurityGroupEnabled()) { - vm = - _userVmService.createAdvancedSecurityGroupVirtualMachine(zone, serviceOffering, template, getNetworkIds(), getSecurityGroupIdList(), owner, name, - displayName, diskOfferingId, size, group, getHypervisor(), getHttpMethod(), userData, sshKeyPairName, getIpToNetworkMap(), addrs, displayVm, - keyboard, getAffinityGroupIdList(), getCustomParameters(), getCustomId()); + vm = _userVmService.createAdvancedSecurityGroupVirtualMachine(zone, serviceOffering, template, getNetworkIds(), getSecurityGroupIdList(), owner, name, + displayName, diskOfferingId, size, group, getHypervisor(), getHttpMethod(), userData, sshKeyPairName, getIpToNetworkMap(), addrs, displayVm, keyboard, + getAffinityGroupIdList(), getDetails(), getCustomId()); } else { if (getSecurityGroupIdList() != null && !getSecurityGroupIdList().isEmpty()) { throw new InvalidParameterValueException("Can't create vm with security groups; security group feature is not enabled per zone"); } - vm = - _userVmService.createAdvancedVirtualMachine(zone, serviceOffering, template, getNetworkIds(), owner, name, displayName, diskOfferingId, size, - group, getHypervisor(), getHttpMethod(), userData, sshKeyPairName, getIpToNetworkMap(), addrs, displayVm, keyboard, getAffinityGroupIdList(), - getCustomParameters(), getCustomId()); - + vm = _userVmService.createAdvancedVirtualMachine(zone, serviceOffering, template, getNetworkIds(), owner, name, displayName, diskOfferingId, size, group, + getHypervisor(), getHttpMethod(), userData, sshKeyPairName, getIpToNetworkMap(), addrs, displayVm, keyboard, getAffinityGroupIdList(), getDetails(), + getCustomId()); } } @@ -601,5 +536,4 @@ public class DeployVMCmd extends BaseAsyncCreateCustomIdCmd { throw new ServerApiException(ApiErrorCode.RESOURCE_ALLOCATION_ERROR, ex.getMessage()); } } - } diff --git a/api/src/org/apache/cloudstack/api/command/user/vm/ListNicsCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/ListNicsCmd.java index 8cb95756367..95d4990bf57 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vm/ListNicsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/ListNicsCmd.java @@ -19,8 +19,6 @@ package org.apache.cloudstack.api.command.user.vm; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; - import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandJobType; import org.apache.cloudstack.api.ApiConstants; @@ -29,9 +27,11 @@ import org.apache.cloudstack.api.BaseListCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.NetworkResponse; import org.apache.cloudstack.api.response.NicResponse; import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.cloudstack.context.CallContext; +import org.apache.log4j.Logger; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -55,6 +55,9 @@ public class ListNicsCmd extends BaseListCmd { @Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID, type = CommandType.UUID, entityType = UserVmResponse.class, required = true, description = "the ID of the vm") private Long vmId; + @Parameter(name = ApiConstants.NETWORK_ID, type = CommandType.UUID, entityType = NetworkResponse.class, description = "list nic of the specific vm's network") + private Long networkId; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -79,6 +82,10 @@ public class ListNicsCmd extends BaseListCmd { return vmId; } + public Long getNetworkId() { + return networkId; + } + @Override public long getEntityOwnerId() { Account caller = CallContext.current().getCallingAccount(); diff --git a/api/src/org/apache/cloudstack/api/command/user/vm/ListVMsCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/ListVMsCmd.java index 3f161c1698d..28637fbbb35 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vm/ListVMsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/ListVMsCmd.java @@ -95,7 +95,7 @@ public class ListVMsCmd extends BaseListTaggedResourcesCmd { type = CommandType.LIST, collectionType = CommandType.STRING, description = "comma separated list of host details requested, " - + "value can be a list of [all, group, nics, stats, secgrp, tmpl, servoff, iso, volume, min, affgrp]." + + "value can be a list of [all, group, nics, stats, secgrp, tmpl, servoff, diskoff, iso, volume, min, affgrp]." + " If no parameter is passed in, the details will be defaulted to all") private List viewDetails; diff --git a/api/src/org/apache/cloudstack/api/command/user/vm/RemoveIpFromVmNicCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/RemoveIpFromVmNicCmd.java index 9b86577f8e3..24582472b53 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vm/RemoveIpFromVmNicCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/RemoveIpFromVmNicCmd.java @@ -142,7 +142,7 @@ public class RemoveIpFromVmNicCmd extends BaseAsyncCmd { if (getNetworkType() == NetworkType.Basic) { //remove the security group rules for this secondary ip boolean success = false; - success = _securityGroupService.securityGroupRulesForVmSecIp(nicSecIp.getNicId(), nicSecIp.getNetworkId(), nicSecIp.getIp4Address(), false); + success = _securityGroupService.securityGroupRulesForVmSecIp(nicSecIp.getNicId(), nicSecIp.getIp4Address(), false); if (success == false) { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to set security group rules for the secondary ip"); } diff --git a/api/src/org/apache/cloudstack/api/command/user/vm/ScaleVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/ScaleVMCmd.java index 08a4a5673dc..d23430095d2 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vm/ScaleVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/ScaleVMCmd.java @@ -16,20 +16,24 @@ // under the License. package org.apache.cloudstack.api.command.user.vm; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; import java.util.List; - -import org.apache.log4j.Logger; +import java.util.Map; import org.apache.cloudstack.api.ACL; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.ServiceOfferingResponse; import org.apache.cloudstack.api.response.SuccessResponse; import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -39,12 +43,6 @@ import com.cloud.exception.VirtualMachineMigrationException; import com.cloud.user.Account; import com.cloud.uservm.UserVm; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - - @APICommand(name = "scaleVirtualMachine", description = "Scales the virtual machine to a new service offering.", responseObject = SuccessResponse.class) public class ScaleVMCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ScaleVMCmd.class.getName()); @@ -59,17 +57,11 @@ public class ScaleVMCmd extends BaseAsyncCmd { private Long id; @ACL - @Parameter(name = ApiConstants.SERVICE_OFFERING_ID, - type = CommandType.UUID, - entityType = ServiceOfferingResponse.class, - required = true, - description = "the ID of the service offering for the virtual machine") + @Parameter(name = ApiConstants.SERVICE_OFFERING_ID, type = CommandType.UUID, entityType = ServiceOfferingResponse.class, required = true, description = "the ID of the service offering for the virtual machine") private Long serviceOfferingId; - @Parameter(name=ApiConstants.CUSTOM_PARAMETERS, - type = CommandType.MAP, - description = "name value pairs of custom parameters for cpu, memory and cpunumber. example customparameters[i].name=value") - private Map customParameters; + @Parameter(name = ApiConstants.DETAILS, type = BaseCmd.CommandType.MAP, description = "name value pairs of custom parameters for cpu,memory and cpunumber. example details[i].name=value") + private Map details; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -84,15 +76,15 @@ public class ScaleVMCmd extends BaseAsyncCmd { } //instead of reading a map directly we are using collections. - //it is because customParameters.values() cannot be cast to a map. + //it is because details.values() cannot be cast to a map. //it gives a exception - public Map getCustomParameters() { - Map customparameterMap = new HashMap(); - if (customParameters != null && customParameters.size() !=0){ - Collection parameterCollection = customParameters.values(); + public Map getDetails() { + Map customparameterMap = new HashMap(); + if (details != null && details.size() != 0) { + Collection parameterCollection = details.values(); Iterator iter = parameterCollection.iterator(); while (iter.hasNext()) { - HashMap value = (HashMap) iter.next(); + HashMap value = (HashMap)iter.next(); for (String key : value.keySet()) { customparameterMap.put(key, value.get(key)); } diff --git a/api/src/org/apache/cloudstack/api/command/user/vm/UpdateVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/UpdateVMCmd.java index 967d8f4d525..e0ca787b6d6 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vm/UpdateVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/UpdateVMCmd.java @@ -16,13 +16,12 @@ // under the License. package org.apache.cloudstack.api.command.user.vm; -import org.apache.cloudstack.api.BaseCustomIdCmd; import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.BaseCustomIdCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.GuestOSResponse; @@ -143,7 +142,7 @@ public class UpdateVMCmd extends BaseCustomIdCmd { if (result != null) { UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", result).get(0); response.setResponseName(getCommandName()); - this.setResponseObject(response); + setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update vm"); } diff --git a/api/src/org/apache/cloudstack/api/command/user/vm/UpgradeVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/UpgradeVMCmd.java index 43497811b13..12ab711afce 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vm/UpgradeVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/UpgradeVMCmd.java @@ -16,7 +16,10 @@ // under the License. package org.apache.cloudstack.api.command.user.vm; -import org.apache.log4j.Logger; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -27,6 +30,7 @@ import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.ServiceOfferingResponse; import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.cloudstack.context.CallContext; +import org.apache.log4j.Logger; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceAllocationException; @@ -34,13 +38,8 @@ import com.cloud.offering.ServiceOffering; import com.cloud.user.Account; import com.cloud.uservm.UserVm; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - @APICommand(name = "changeServiceForVirtualMachine", responseObject = UserVmResponse.class, description = "Changes the service offering for a virtual machine. " - + "The virtual machine must be in a \"Stopped\" state for " + "this command to take effect.") + + "The virtual machine must be in a \"Stopped\" state for " + "this command to take effect.") public class UpgradeVMCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpgradeVMCmd.class.getName()); private static final String s_name = "changeserviceforvirtualmachineresponse"; @@ -52,17 +51,11 @@ public class UpgradeVMCmd extends BaseCmd { @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = UserVmResponse.class, required = true, description = "The ID of the virtual machine") private Long id; - @Parameter(name = ApiConstants.SERVICE_OFFERING_ID, - type = CommandType.UUID, - entityType = ServiceOfferingResponse.class, - required = true, - description = "the service offering ID to apply to the virtual machine") + @Parameter(name = ApiConstants.SERVICE_OFFERING_ID, type = CommandType.UUID, entityType = ServiceOfferingResponse.class, required = true, description = "the service offering ID to apply to the virtual machine") private Long serviceOfferingId; - @Parameter(name=ApiConstants.CUSTOM_PARAMETERS, - type = CommandType.MAP, - description = "name value pairs of custom parameters for cpu, memory and cpunumber. example customparameters[i].name=value") - private Map customParameters; + @Parameter(name = ApiConstants.DETAILS, type = CommandType.MAP, description = "name value pairs of custom parameters for cpu, memory and cpunumber. example details[i].name=value") + private Map details; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -76,13 +69,13 @@ public class UpgradeVMCmd extends BaseCmd { return serviceOfferingId; } - public Map getCustomParameters() { - Map customparameterMap = new HashMap(); - if (customParameters != null && customParameters.size() !=0){ - Collection parameterCollection = customParameters.values(); + public Map getDetails() { + Map customparameterMap = new HashMap(); + if (details != null && details.size() != 0) { + Collection parameterCollection = details.values(); Iterator iter = parameterCollection.iterator(); while (iter.hasNext()) { - HashMap value = (HashMap) iter.next(); + HashMap value = (HashMap)iter.next(); for (String key : value.keySet()) { customparameterMap.put(key, value.get(key)); } diff --git a/api/src/org/apache/cloudstack/api/command/user/volume/AddResourceDetailCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/AddResourceDetailCmd.java index 69d1ca7c2ee..618be7f3958 100644 --- a/api/src/org/apache/cloudstack/api/command/user/volume/AddResourceDetailCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/AddResourceDetailCmd.java @@ -21,13 +21,12 @@ import java.util.HashMap; import java.util.Iterator; import java.util.Map; -import org.apache.log4j.Logger; - import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.server.ResourceTag; @@ -35,7 +34,7 @@ import com.cloud.server.ResourceTag; @APICommand(name = "addResourceDetail", description = "Adds detail for the Resource.", responseObject = SuccessResponse.class) public class AddResourceDetailCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(AddResourceDetailCmd.class.getName()); - private static final String s_name = "addResourceDetailresponse"; + private static final String s_name = "addresourcedetailresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -47,11 +46,7 @@ public class AddResourceDetailCmd extends BaseAsyncCmd { @Parameter(name = ApiConstants.RESOURCE_TYPE, type = CommandType.STRING, required = true, description = "type of the resource") private String resourceType; - @Parameter(name = ApiConstants.RESOURCE_ID, - type = CommandType.STRING, - required = true, - collectionType = CommandType.STRING, - description = "resource id to create the details for") + @Parameter(name = ApiConstants.RESOURCE_ID, type = CommandType.STRING, required = true, collectionType = CommandType.STRING, description = "resource id to create the details for") private String resourceId; ///////////////////////////////////////////////////// diff --git a/api/src/org/apache/cloudstack/api/command/user/volume/CreateVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/CreateVolumeCmd.java index cb7b13a6a7e..c6457c60eb3 100644 --- a/api/src/org/apache/cloudstack/api/command/user/volume/CreateVolumeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/CreateVolumeCmd.java @@ -100,7 +100,10 @@ public class CreateVolumeCmd extends BaseAsyncCreateCustomIdCmd { @Parameter(name = ApiConstants.DISPLAY_VOLUME, type = CommandType.BOOLEAN, description = "an optional field, whether to display the volume to the end user or not.") private Boolean displayVolume; - @Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID, type = CommandType.UUID, entityType = UserVmResponse.class, description = "the ID of the virtual machine; to be used with snapshot Id, VM to which the volume gets attached after creation") + @Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID, + type = CommandType.UUID, + entityType = UserVmResponse.class, + description = "the ID of the virtual machine; to be used with snapshot Id, VM to which the volume gets attached after creation") private Long virtualMachineId; ///////////////////////////////////////////////////// diff --git a/api/src/org/apache/cloudstack/api/command/user/volume/ResizeVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/ResizeVolumeCmd.java index 0cc8039200d..e69194438bf 100644 --- a/api/src/org/apache/cloudstack/api/command/user/volume/ResizeVolumeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/ResizeVolumeCmd.java @@ -16,8 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.volume; -import org.apache.log4j.Logger; - import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandJobType; import org.apache.cloudstack.api.ApiConstants; @@ -28,6 +26,7 @@ import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.DiskOfferingResponse; import org.apache.cloudstack.api.response.VolumeResponse; import org.apache.cloudstack.context.CallContext; +import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -47,7 +46,7 @@ public class ResizeVolumeCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @Parameter(name = ApiConstants.ID, entityType = VolumeResponse.class, type = CommandType.UUID, description = "the ID of the disk volume") + @Parameter(name = ApiConstants.ID, entityType = VolumeResponse.class, required = true, type = CommandType.UUID, description = "the ID of the disk volume") private Long id; @Parameter(name = ApiConstants.SIZE, type = CommandType.LONG, required = false, description = "New volume size in G") diff --git a/api/src/org/apache/cloudstack/api/command/user/volume/UpdateVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/UpdateVolumeCmd.java index 7233b4fb5d3..b57f2b489d6 100644 --- a/api/src/org/apache/cloudstack/api/command/user/volume/UpdateVolumeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/UpdateVolumeCmd.java @@ -16,14 +16,13 @@ // under the License. package org.apache.cloudstack.api.command.user.volume; -import org.apache.cloudstack.api.BaseAsyncCustomIdCmd; import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandJobType; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseAsyncCustomIdCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.StoragePoolResponse; @@ -145,7 +144,7 @@ public class UpdateVolumeCmd extends BaseAsyncCustomIdCmd { if (result != null) { VolumeResponse response = _responseGenerator.createVolumeResponse(result); response.setResponseName(getCommandName()); - this.setResponseObject(response); + setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update volume"); } diff --git a/api/src/org/apache/cloudstack/api/command/user/vpc/CreateVPCCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/CreateVPCCmd.java index f12d15b5f0e..d4c52b8e42a 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vpc/CreateVPCCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/CreateVPCCmd.java @@ -47,44 +47,44 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd { // /////////////////////////////////////////////////// @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "the account associated with the VPC. " + - "Must be used with the domainId parameter.") + "Must be used with the domainId parameter.") private String accountName; @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, entityType = DomainResponse.class, - description = "the domain ID associated with the VPC. " + - "If used with the account parameter returns the VPC associated with the account for the specified domain.") + description = "the domain ID associated with the VPC. " + + "If used with the account parameter returns the VPC associated with the account for the specified domain.") private Long domainId; @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, entityType = ProjectResponse.class, - description = "create VPC for the project") + description = "create VPC for the project") private Long projectId; @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, - required = true, description = "the ID of the availability zone") + required = true, description = "the ID of the availability zone") private Long zoneId; @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "the name of the VPC") private String vpcName; @Parameter(name = ApiConstants.DISPLAY_TEXT, type = CommandType.STRING, required = true, description = "the display text of " + - "the VPC") + "the VPC") private String displayText; @Parameter(name = ApiConstants.CIDR, type = CommandType.STRING, required = true, description = "the cidr of the VPC. All VPC " + - "guest networks' cidrs should be within this CIDR") + "guest networks' cidrs should be within this CIDR") private String cidr; @Parameter(name = ApiConstants.VPC_OFF_ID, type = CommandType.UUID, entityType = VpcOfferingResponse.class, - required = true, description = "the ID of the VPC offering") + required = true, description = "the ID of the VPC offering") private Long vpcOffering; @Parameter(name = ApiConstants.NETWORK_DOMAIN, type = CommandType.STRING, - description = "VPC network domain. All networks inside the VPC will belong to this domain") + description = "VPC network domain. All networks inside the VPC will belong to this domain") private String networkDomain; @Parameter(name = ApiConstants.START, type = CommandType.BOOLEAN, - description = "If set to false, the VPC won't start (VPC VR will not get allocated) until its first network gets implemented. " + - "True by default.", since = "4.3") + description = "If set to false, the VPC won't start (VPC VR will not get allocated) until its first network gets implemented. " + + "True by default.", since = "4.3") private Boolean start; // /////////////////////////////////////////////////// diff --git a/api/src/org/apache/cloudstack/api/command/user/vpc/ListVPCOfferingsCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/ListVPCOfferingsCmd.java index 85051cfdf61..e3d0bc606f5 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vpc/ListVPCOfferingsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/ListVPCOfferingsCmd.java @@ -33,7 +33,7 @@ import com.cloud.network.vpc.VpcOffering; @APICommand(name = "listVPCOfferings", description = "Lists VPC offerings", responseObject = VpcOfferingResponse.class) public class ListVPCOfferingsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListVPCOfferingsCmd.class.getName()); - private static final String _name = "listvpcofferingsresponse"; + private static final String Name = "listvpcofferingsresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -109,7 +109,7 @@ public class ListVPCOfferingsCmd extends BaseListCmd { @Override public String getCommandName() { - return _name; + return Name; } } diff --git a/api/src/org/apache/cloudstack/api/command/user/vpc/RestartVPCCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/RestartVPCCmd.java index ce144512f39..eb048ceea0b 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vpc/RestartVPCCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/RestartVPCCmd.java @@ -37,7 +37,7 @@ import com.cloud.user.Account; @APICommand(name = "restartVPC", description = "Restarts a VPC", responseObject = VpcResponse.class) public class RestartVPCCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(RestartVPCCmd.class.getName()); - private static final String _name = "restartvpcresponse"; + private static final String Name = "restartvpcresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -59,7 +59,7 @@ public class RestartVPCCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// @Override public String getCommandName() { - return _name; + return Name; } @Override diff --git a/api/src/org/apache/cloudstack/api/command/user/vpc/UpdateVPCCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/UpdateVPCCmd.java index 73585247976..5732c652214 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vpc/UpdateVPCCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/UpdateVPCCmd.java @@ -33,7 +33,7 @@ import com.cloud.user.Account; @APICommand(name = "updateVPC", description = "Updates a VPC", responseObject = VpcResponse.class) public class UpdateVPCCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(UpdateVPCCmd.class.getName()); - private static final String _name = "updatevpcresponse"; + private static final String Name = "updatevpcresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -69,7 +69,7 @@ public class UpdateVPCCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// @Override public String getCommandName() { - return _name; + return Name; } @Override diff --git a/api/src/org/apache/cloudstack/api/response/AlertResponse.java b/api/src/org/apache/cloudstack/api/response/AlertResponse.java index a2554c3b095..2016bcf5e00 100644 --- a/api/src/org/apache/cloudstack/api/response/AlertResponse.java +++ b/api/src/org/apache/cloudstack/api/response/AlertResponse.java @@ -42,8 +42,9 @@ public class AlertResponse extends BaseResponse { + "MANAGMENT_NODE = 13: lost connection to default route (to the gateway), " + "DOMAIN_ROUTER_MIGRATE = 14, CONSOLE_PROXY_MIGRATE = 15, USERVM_MIGRATE = 16, VLAN = 17, SSVM = 18, " + "USAGE_SERVER_RESULT = 19") private Short alertType; - - @SerializedName(ApiConstants.NAME) @Param(description="the name of the alert", since="4.3") + + @SerializedName(ApiConstants.NAME) + @Param(description = "the name of the alert", since = "4.3") private String alertName; @SerializedName(ApiConstants.DESCRIPTION) @@ -69,7 +70,7 @@ public class AlertResponse extends BaseResponse { public void setLastSent(Date lastSent) { this.lastSent = lastSent; } - + public void setName(String name) { this.alertName = name; } diff --git a/api/src/org/apache/cloudstack/api/response/CapabilitiesResponse.java b/api/src/org/apache/cloudstack/api/response/CapabilitiesResponse.java index 4840c60528f..c8de5873367 100644 --- a/api/src/org/apache/cloudstack/api/response/CapabilitiesResponse.java +++ b/api/src/org/apache/cloudstack/api/response/CapabilitiesResponse.java @@ -63,7 +63,7 @@ public class CapabilitiesResponse extends BaseResponse { @SerializedName("kvmsnapshotenabled") @Param(description = "true if snapshot is supported for KVM host, false otherwise") - private boolean KVMSnapshotEnabled; + private boolean kvmSnapshotEnabled; @SerializedName("apilimitmax") @Param(description = "Max allowed number of api requests within the specified interval") @@ -101,8 +101,8 @@ public class CapabilitiesResponse extends BaseResponse { this.regionSecondaryEnabled = regionSecondaryEnabled; } - public void setKVMSnapshotEnabled(boolean KVMSnapshotEnabled) { - this.KVMSnapshotEnabled = KVMSnapshotEnabled; + public void setKVMSnapshotEnabled(boolean kvmSnapshotEnabled) { + this.kvmSnapshotEnabled = kvmSnapshotEnabled; } public void setApiLimitInterval(Integer apiLimitInterval) { diff --git a/api/src/org/apache/cloudstack/api/response/DiskOfferingResponse.java b/api/src/org/apache/cloudstack/api/response/DiskOfferingResponse.java index 3917cb5eaf3..ebc22428326 100644 --- a/api/src/org/apache/cloudstack/api/response/DiskOfferingResponse.java +++ b/api/src/org/apache/cloudstack/api/response/DiskOfferingResponse.java @@ -97,7 +97,8 @@ public class DiskOfferingResponse extends BaseResponse { @Param(description = "io requests write rate of the disk offering") private Long iopsWriteRate; - @SerializedName("cacheMode") @Param(description="the cache mode to use for this disk offering. none, writeback or writethrough") + @SerializedName("cacheMode") + @Param(description = "the cache mode to use for this disk offering. none, writeback or writethrough") private String cacheMode; @SerializedName("displayoffering") diff --git a/api/src/org/apache/cloudstack/api/response/NicResponse.java b/api/src/org/apache/cloudstack/api/response/NicResponse.java index 7089f884a51..3dd8b297a2b 100644 --- a/api/src/org/apache/cloudstack/api/response/NicResponse.java +++ b/api/src/org/apache/cloudstack/api/response/NicResponse.java @@ -18,14 +18,13 @@ package org.apache.cloudstack.api.response; import java.util.List; -import com.google.gson.annotations.SerializedName; - import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseResponse; import org.apache.cloudstack.api.EntityReference; import com.cloud.serializer.Param; import com.cloud.vm.Nic; +import com.google.gson.annotations.SerializedName; @SuppressWarnings("unused") @EntityReference(value = Nic.class) @@ -95,6 +94,10 @@ public class NicResponse extends BaseResponse { @Param(description = "the Secondary ipv4 addr of nic") private List secondaryIps; + @SerializedName(ApiConstants.DEVICE_ID) + @Param(description = "device id for the network when plugged into the virtual machine", since = "4.4") + private String deviceId; + public String getId() { return id; } @@ -159,6 +162,10 @@ public class NicResponse extends BaseResponse { this.ip6Address = ip6Address; } + public void setDeviceId(String deviceId) { + this.deviceId = deviceId; + } + @Override public int hashCode() { final int prime = 31; diff --git a/api/src/org/apache/cloudstack/api/response/OvsProviderResponse.java b/api/src/org/apache/cloudstack/api/response/OvsProviderResponse.java index 223576d001d..ac5b9e309c8 100644 --- a/api/src/org/apache/cloudstack/api/response/OvsProviderResponse.java +++ b/api/src/org/apache/cloudstack/api/response/OvsProviderResponse.java @@ -27,67 +27,67 @@ import com.google.gson.annotations.SerializedName; @EntityReference(value = OvsProvider.class) @SuppressWarnings("unused") public class OvsProviderResponse extends BaseResponse implements - ControlledEntityResponse { - @SerializedName(ApiConstants.ID) - @Param(description = "the id of the ovs") - private String id; - @SerializedName(ApiConstants.NSP_ID) - @Param(description = "the physical network service provider id of the provider") - private String nspId; - @SerializedName(ApiConstants.ENABLED) - @Param(description = "Enabled/Disabled the service provider") - private Boolean enabled; - @SerializedName(ApiConstants.ACCOUNT) - @Param(description = "the account associated with the provider") - private String accountName; - @SerializedName(ApiConstants.PROJECT_ID) - @Param(description = "the project id of the ipaddress") - private String projectId; - @SerializedName(ApiConstants.PROJECT) - @Param(description = "the project name of the address") - private String projectName; - @SerializedName(ApiConstants.DOMAIN_ID) - @Param(description = "the domain ID associated with the provider") - private String domainId; + ControlledEntityResponse { + @SerializedName(ApiConstants.ID) + @Param(description = "the id of the ovs") + private String id; + @SerializedName(ApiConstants.NSP_ID) + @Param(description = "the physical network service provider id of the provider") + private String nspId; + @SerializedName(ApiConstants.ENABLED) + @Param(description = "Enabled/Disabled the service provider") + private Boolean enabled; + @SerializedName(ApiConstants.ACCOUNT) + @Param(description = "the account associated with the provider") + private String accountName; + @SerializedName(ApiConstants.PROJECT_ID) + @Param(description = "the project id of the ipaddress") + private String projectId; + @SerializedName(ApiConstants.PROJECT) + @Param(description = "the project name of the address") + private String projectName; + @SerializedName(ApiConstants.DOMAIN_ID) + @Param(description = "the domain ID associated with the provider") + private String domainId; - @SerializedName(ApiConstants.DOMAIN) - @Param(description = "the domain associated with the provider") - private String domainName; + @SerializedName(ApiConstants.DOMAIN) + @Param(description = "the domain associated with the provider") + private String domainName; - @Override - public void setAccountName(String accountName) { - this.accountName = accountName; - } + @Override + public void setAccountName(String accountName) { + this.accountName = accountName; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - @Override - public void setDomainId(String domainId) { - this.domainId = domainId; - } + @Override + public void setDomainId(String domainId) { + this.domainId = domainId; + } - @Override - public void setDomainName(String domainName) { - this.domainName = domainName; - } + @Override + public void setDomainName(String domainName) { + this.domainName = domainName; + } - @Override - public void setProjectId(String projectId) { - this.projectId = projectId; - } + @Override + public void setProjectId(String projectId) { + this.projectId = projectId; + } - @Override - public void setProjectName(String projectName) { - this.projectName = projectName; - } + @Override + public void setProjectName(String projectName) { + this.projectName = projectName; + } - public void setNspId(String nspId) { - this.nspId = nspId; - } + public void setNspId(String nspId) { + this.nspId = nspId; + } - public void setEnabled(Boolean enabled) { - this.enabled = enabled; - } + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } } diff --git a/api/src/org/apache/cloudstack/api/response/ProviderResponse.java b/api/src/org/apache/cloudstack/api/response/ProviderResponse.java index 5d6ec0d5ca3..4d410837476 100644 --- a/api/src/org/apache/cloudstack/api/response/ProviderResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ProviderResponse.java @@ -18,14 +18,13 @@ package org.apache.cloudstack.api.response; import java.util.List; -import com.google.gson.annotations.SerializedName; - import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseResponse; import org.apache.cloudstack.api.EntityReference; import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; @EntityReference(value = PhysicalNetworkServiceProvider.class) @SuppressWarnings("unused") diff --git a/api/src/org/apache/cloudstack/api/response/ServiceOfferingResponse.java b/api/src/org/apache/cloudstack/api/response/ServiceOfferingResponse.java index c8dee140323..526e52b71a5 100644 --- a/api/src/org/apache/cloudstack/api/response/ServiceOfferingResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ServiceOfferingResponse.java @@ -100,7 +100,7 @@ public class ServiceOfferingResponse extends BaseResponse { @SerializedName(ApiConstants.SYSTEM_VM_TYPE) @Param(description = "is this a the systemvm type for system vm offering") - private String vm_type; + private String vmType; @SerializedName(ApiConstants.NETWORKRATE) @Param(description = "data transfer rate in megabits per second allowed.") @@ -170,11 +170,11 @@ public class ServiceOfferingResponse extends BaseResponse { } public String getSystemVmType() { - return vm_type; + return vmType; } public void setSystemVmType(String vmtype) { - vm_type = vmtype; + vmType = vmtype; } public String getDisplayText() { diff --git a/api/src/org/apache/cloudstack/api/response/UserVmResponse.java b/api/src/org/apache/cloudstack/api/response/UserVmResponse.java index 3ca2a1c81b1..26ecb5bb088 100644 --- a/api/src/org/apache/cloudstack/api/response/UserVmResponse.java +++ b/api/src/org/apache/cloudstack/api/response/UserVmResponse.java @@ -21,8 +21,6 @@ import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; -import com.google.gson.annotations.SerializedName; - import org.apache.cloudstack.affinity.AffinityGroupResponse; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseResponse; @@ -32,6 +30,7 @@ import com.cloud.network.router.VirtualRouter; import com.cloud.serializer.Param; import com.cloud.uservm.UserVm; import com.cloud.vm.VirtualMachine; +import com.google.gson.annotations.SerializedName; @SuppressWarnings("unused") @EntityReference(value = {VirtualMachine.class, UserVm.class, VirtualRouter.class}) @@ -140,6 +139,14 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp @Param(description = "the name of the service offering of the virtual machine") private String serviceOfferingName; + @SerializedName(ApiConstants.DISK_OFFERING_ID) + @Param(description = "the ID of the disk offering of the virtual machine") + private String diskOfferingId; + + @SerializedName("diskofferingname") + @Param(description = "the name of the disk offering of the virtual machine") + private String diskOfferingName; + @SerializedName("forvirtualnetwork") @Param(description = "the virtual network for the service offering") private Boolean forVirtualNetwork; @@ -229,7 +236,7 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp private Set tags; @SerializedName(ApiConstants.DETAILS) - @Param(description = "Template details in key/value pairs.", since = "4.2.1") + @Param(description = "Vm details in key/value pairs.", since = "4.2.1") private Map details; @SerializedName(ApiConstants.SSH_KEYPAIR) @@ -247,10 +254,15 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp @SerializedName(ApiConstants.IS_DYNAMICALLY_SCALABLE) @Param(description = "true if vm contains XS/VMWare tools inorder to support dynamic scaling of VM cpu/memory.") private Boolean isDynamicallyScalable; + @SerializedName(ApiConstants.SERVICE_STATE) @Param(description = "State of the Service from LB rule") private String serviceState; + @SerializedName(ApiConstants.OS_TYPE_ID) + @Param(description = "OS type id of the vm", since = "4.4") + private Long osTypeId; + public UserVmResponse() { securityGroupList = new LinkedHashSet(); nics = new LinkedHashSet(); @@ -383,6 +395,14 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp return serviceOfferingName; } + public String getDiskOfferingId() { + return diskOfferingId; + } + + public String getDiskOfferingName() { + return diskOfferingName; + } + public Boolean getForVirtualNetwork() { return forVirtualNetwork; } @@ -602,6 +622,14 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp this.serviceOfferingName = serviceOfferingName; } + public void setDiskOfferingId(String diskOfferingId) { + this.diskOfferingId = diskOfferingId; + } + + public void setDiskOfferingName(String diskOfferingName) { + this.diskOfferingName = diskOfferingName; + } + public void setCpuNumber(Integer cpuNumber) { this.cpuNumber = cpuNumber; } @@ -715,4 +743,8 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp public void setDetails(Map details) { this.details = details; } + + public void setOsTypeId(Long osTypeId) { + this.osTypeId = osTypeId; + } } diff --git a/api/src/org/apache/cloudstack/api/response/VMUserDataResponse.java b/api/src/org/apache/cloudstack/api/response/VMUserDataResponse.java new file mode 100644 index 00000000000..1b739e56442 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/response/VMUserDataResponse.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.cloudstack.api.response; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; + +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; + +public class VMUserDataResponse extends BaseResponse { + @SerializedName(ApiConstants.VIRTUAL_MACHINE_ID) + @Param(description = "the ID of the virtual machine") + private String vmId; + + @SerializedName(ApiConstants.USER_DATA) + @Param(description = "Base 64 encoded VM user data") + private String userData; + + public void setUserData(String userData) { + this.userData = userData; + } + + public void setVmId(String vmId) { + this.vmId = vmId; + } + +} diff --git a/api/src/org/apache/cloudstack/config/ApiServiceConfiguration.java b/api/src/org/apache/cloudstack/config/ApiServiceConfiguration.java new file mode 100644 index 00000000000..94c0a55de6a --- /dev/null +++ b/api/src/org/apache/cloudstack/config/ApiServiceConfiguration.java @@ -0,0 +1,40 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.config; + +import javax.ejb.Local; + +import org.apache.cloudstack.framework.config.ConfigKey; +import org.apache.cloudstack.framework.config.Configurable; + +@Local(value = {ApiServiceConfiguration.class}) +public class ApiServiceConfiguration implements Configurable { + public static final ConfigKey ManagementHostIPAdr = new ConfigKey("Advanced", String.class, "host", "localhost", "The ip address of management server", true); + public static final ConfigKey ApiServletPath = new ConfigKey("Advanced", String.class, "endpointe.url", "http://localhost:8080/client/api", + "API end point. Can be used by CS components/services deployed remotely, for sending CS API requests", true); + + @Override + public String getConfigComponentName() { + return ApiServiceConfiguration.class.getSimpleName(); + } + + @Override + public ConfigKey[] getConfigKeys() { + return new ConfigKey[] {ManagementHostIPAdr, ApiServletPath}; + } + +} diff --git a/api/src/org/apache/cloudstack/context/CallContext.java b/api/src/org/apache/cloudstack/context/CallContext.java index 2d5aea45eb1..dbeb5c7ea21 100644 --- a/api/src/org/apache/cloudstack/context/CallContext.java +++ b/api/src/org/apache/cloudstack/context/CallContext.java @@ -42,10 +42,10 @@ public class CallContext { private static final Logger s_logger = Logger.getLogger(CallContext.class); private static ManagedThreadLocal s_currentContext = new ManagedThreadLocal(); private static ManagedThreadLocal> s_currentContextStack = new ManagedThreadLocal>() { - @Override - protected Stack initialValue() { - return new Stack(); - } + @Override + protected Stack initialValue() { + return new Stack(); + } }; private String contextId; @@ -76,9 +76,9 @@ public class CallContext { protected CallContext(User user, Account account, String contextId) { this.user = user; - this.userId = user.getId(); + userId = user.getId(); this.account = account; - this.accountId = account.getId(); + accountId = account.getId(); this.contextId = contextId; } @@ -119,7 +119,7 @@ public class CallContext { /** * This method should only be called if you can propagate the context id * from another CallContext. - * + * * @param callingUser calling user * @param callingAccount calling account * @param contextId context id propagated from another call context @@ -132,7 +132,6 @@ public class CallContext { protected static CallContext register(User callingUser, Account callingAccount, Long userId, Long accountId, String contextId) { /* Unit tests will have multiple times of setup/tear-down call to this, remove assertions to all unit test to run - assert s_currentContext.get() == null : "There's a context already so what does this new register context mean? " + s_currentContext.get().toString(); if (s_currentContext.get() != null) { // FIXME: This should be removed soon. I added this check only to surface all the places that have this problem. throw new CloudRuntimeException("There's a context already so what does this new register context mean? " + s_currentContext.get().toString()); @@ -149,9 +148,9 @@ public class CallContext { if (s_logger.isTraceEnabled()) { s_logger.trace("Registered: " + callingContext); } - + s_currentContextStack.get().push(callingContext); - + return callingContext; } @@ -197,7 +196,7 @@ public class CallContext { } return register(user, account); } - + public static CallContext register(long callingUserId, long callingAccountId, String contextId) throws CloudAuthenticationException { Account account = s_entityMgr.findById(Account.class, callingAccountId); if (account == null) { @@ -215,7 +214,7 @@ public class CallContext { // NOOP } } - + public static CallContext unregister() { CallContext context = s_currentContext.get(); if (context == null) { @@ -274,7 +273,7 @@ public class CallContext { public String getEventDetails() { return eventDetails; } - + public String getEventType() { return eventType; } @@ -282,7 +281,7 @@ public class CallContext { public void setEventType(String eventType) { this.eventType = eventType; } - + public String getEventDescription() { return eventDescription; } diff --git a/api/src/org/apache/cloudstack/network/ExternalNetworkDeviceManager.java b/api/src/org/apache/cloudstack/network/ExternalNetworkDeviceManager.java index 32f13f80f22..e73f5263a4f 100644 --- a/api/src/org/apache/cloudstack/network/ExternalNetworkDeviceManager.java +++ b/api/src/org/apache/cloudstack/network/ExternalNetworkDeviceManager.java @@ -45,6 +45,7 @@ public interface ExternalNetworkDeviceManager extends Manager { public static final NetworkDevice PaloAltoFirewall = new NetworkDevice("PaloAltoFirewall", Network.Provider.PaloAlto.getName()); public static final NetworkDevice NiciraNvp = new NetworkDevice("NiciraNvp", Network.Provider.NiciraNvp.getName()); public static final NetworkDevice CiscoVnmc = new NetworkDevice("CiscoVnmc", Network.Provider.CiscoVnmc.getName()); + public static final NetworkDevice OpenDaylightController = new NetworkDevice("OpenDaylightController", Network.Provider.Opendaylight.getName()); public NetworkDevice(String deviceName, String ntwkServiceprovider) { _name = deviceName; diff --git a/api/src/org/apache/cloudstack/query/QueryService.java b/api/src/org/apache/cloudstack/query/QueryService.java index 792ed04c3da..65a6b064b7c 100644 --- a/api/src/org/apache/cloudstack/query/QueryService.java +++ b/api/src/org/apache/cloudstack/query/QueryService.java @@ -18,10 +18,6 @@ package org.apache.cloudstack.query; import java.util.List; -import org.apache.cloudstack.affinity.AffinityGroupResponse; -import org.apache.cloudstack.api.command.admin.host.ListHostsCmd; -import org.apache.cloudstack.api.command.admin.internallb.ListInternalLBVMsCmd; -import org.apache.cloudstack.api.command.admin.router.ListRoutersCmd; import org.apache.cloudstack.api.command.admin.storage.ListImageStoresCmd; import org.apache.cloudstack.api.command.admin.storage.ListSecondaryStagingStoresCmd; import org.apache.cloudstack.api.command.admin.storage.ListStoragePoolsCmd; @@ -43,6 +39,10 @@ import org.apache.cloudstack.api.command.user.vmgroup.ListVMGroupsCmd; import org.apache.cloudstack.api.command.user.volume.ListResourceDetailsCmd; import org.apache.cloudstack.api.command.user.volume.ListVolumesCmd; import org.apache.cloudstack.api.command.user.zone.ListZonesByCmd; +import org.apache.cloudstack.affinity.AffinityGroupResponse; +import org.apache.cloudstack.api.command.admin.host.ListHostsCmd; +import org.apache.cloudstack.api.command.admin.internallb.ListInternalLBVMsCmd; +import org.apache.cloudstack.api.command.admin.router.ListRoutersCmd; import org.apache.cloudstack.api.response.AccountResponse; import org.apache.cloudstack.api.response.AsyncJobResponse; import org.apache.cloudstack.api.response.DiskOfferingResponse; @@ -118,8 +118,9 @@ public interface QueryService { public ListResponse listIsos(ListIsosCmd cmd); - public ListResponse listAffinityGroups(Long affinityGroupId, String affinityGroupName, String affinityGroupType, Long vmId, - String accountName, Long domainId, boolean isRecursive, boolean listAll, Long startIndex, Long pageSize); + public ListResponse listAffinityGroups(Long affinityGroupId, String affinityGroupName, + String affinityGroupType, Long vmId, String accountName, Long domainId, boolean isRecursive, + boolean listAll, Long startIndex, Long pageSize, String keyword); public List listResourceDetails(ListResourceDetailsCmd cmd); diff --git a/api/test/com/cloud/network/NetworksTest.java b/api/test/com/cloud/network/NetworksTest.java index 849b1b4f73f..c9102d3a02a 100644 --- a/api/test/com/cloud/network/NetworksTest.java +++ b/api/test/com/cloud/network/NetworksTest.java @@ -22,6 +22,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import com.cloud.dc.Vlan; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.IsolationType; import com.cloud.utils.exception.CloudRuntimeException; @@ -55,6 +56,20 @@ public class NetworksTest { Assert.assertEquals("id2 should be \"2\"", "2", id2); } + @Test + public void vlanValueTest() throws URISyntaxException { + String uri1 = "vlan://1"; + String uri2 = "1"; + String vtag = BroadcastDomainType.Vlan.getValueFrom(BroadcastDomainType.fromString(uri1)); + Assert.assertEquals("vtag should be \"1\"", "1", vtag); + BroadcastDomainType tiep1 = BroadcastDomainType.getTypeOf(uri1); + Assert.assertEquals("the type of uri1 should be 'Vlan'", BroadcastDomainType.Vlan, tiep1); + BroadcastDomainType tiep2 = BroadcastDomainType.getTypeOf(uri2); + Assert.assertEquals("the type of uri1 should be 'Undecided'", BroadcastDomainType.UnDecided, tiep2); + BroadcastDomainType tiep3 = BroadcastDomainType.getTypeOf(Vlan.UNTAGGED); + Assert.assertEquals("the type of uri1 should be 'vlan'", BroadcastDomainType.Native, tiep3); + } + @Test public void vlanIsolationTypeTest() throws URISyntaxException { String uri1 = "vlan://1"; diff --git a/api/test/org/apache/cloudstack/api/command/test/AddIpToVmNicTest.java b/api/test/org/apache/cloudstack/api/command/test/AddIpToVmNicTest.java index 195486aedd0..6f5ab3e1cd9 100644 --- a/api/test/org/apache/cloudstack/api/command/test/AddIpToVmNicTest.java +++ b/api/test/org/apache/cloudstack/api/command/test/AddIpToVmNicTest.java @@ -25,7 +25,6 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Matchers; import org.mockito.Mockito; - import org.apache.cloudstack.api.ResponseGenerator; import org.apache.cloudstack.api.command.user.vm.AddIpToVmNicCmd; import org.apache.cloudstack.api.command.user.vm.RemoveIpFromVmNicCmd; @@ -39,7 +38,6 @@ import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.NetworkService; -import com.cloud.user.Account; import com.cloud.vm.NicSecondaryIp; public class AddIpToVmNicTest extends TestCase { @@ -67,7 +65,8 @@ public class AddIpToVmNicTest extends TestCase { AddIpToVmNicCmd ipTonicCmd = Mockito.mock(AddIpToVmNicCmd.class); NicSecondaryIp secIp = Mockito.mock(NicSecondaryIp.class); - Mockito.when(networkService.allocateSecondaryGuestIP(Matchers.any(Account.class), Matchers.anyLong(), Matchers.anyLong(), Matchers.anyLong(), Matchers.anyString())) + Mockito.when( + networkService.allocateSecondaryGuestIP(Matchers.anyLong(), Matchers.anyString())) .thenReturn(secIp); ipTonicCmd._networkService = networkService; @@ -86,7 +85,8 @@ public class AddIpToVmNicTest extends TestCase { NetworkService networkService = Mockito.mock(NetworkService.class); AddIpToVmNicCmd ipTonicCmd = Mockito.mock(AddIpToVmNicCmd.class); - Mockito.when(networkService.allocateSecondaryGuestIP(Matchers.any(Account.class), Matchers.anyLong(), Matchers.anyLong(), Matchers.anyLong(), Matchers.anyString())) + Mockito.when( + networkService.allocateSecondaryGuestIP(Matchers.anyLong(), Matchers.anyString())) .thenReturn(null); ipTonicCmd._networkService = networkService; diff --git a/api/test/org/apache/cloudstack/api/command/test/AddSecondaryStorageCmdTest.java b/api/test/org/apache/cloudstack/api/command/test/AddSecondaryStorageCmdTest.java index d0b2d85f8d5..d68cfb4ca67 100644 --- a/api/test/org/apache/cloudstack/api/command/test/AddSecondaryStorageCmdTest.java +++ b/api/test/org/apache/cloudstack/api/command/test/AddSecondaryStorageCmdTest.java @@ -16,6 +16,12 @@ // under the License. package org.apache.cloudstack.api.command.test; +import static org.mockito.Matchers.anyLong; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.anyString; + +import java.util.Map; + import junit.framework.Assert; import junit.framework.TestCase; @@ -56,7 +62,8 @@ public class AddSecondaryStorageCmdTest extends TestCase { ImageStore store = Mockito.mock(ImageStore.class); - Mockito.when(resourceService.discoverImageStore(addImageStoreCmd)).thenReturn(store); + Mockito.when(resourceService.discoverImageStore(anyString(), anyString(), anyString(), anyLong(), (Map)anyObject())) + .thenReturn(store); ResponseGenerator responseGenerator = Mockito.mock(ResponseGenerator.class); addImageStoreCmd._responseGenerator = responseGenerator; @@ -83,7 +90,8 @@ public class AddSecondaryStorageCmdTest extends TestCase { StorageService resourceService = Mockito.mock(StorageService.class); addImageStoreCmd._storageService = resourceService; - Mockito.when(resourceService.discoverImageStore(addImageStoreCmd)).thenReturn(null); + Mockito.when(resourceService.discoverImageStore(anyString(), anyString(), anyString(), anyLong(), (Map)anyObject())) + .thenReturn(null); try { addImageStoreCmd.execute(); diff --git a/awsapi/pom.xml b/awsapi/pom.xml index 3d269eda69a..4a6c89c9e5f 100644 --- a/awsapi/pom.xml +++ b/awsapi/pom.xml @@ -142,7 +142,7 @@ org.opensaml - opensaml + opensaml1 @@ -162,7 +162,7 @@ org.opensaml - opensaml + opensaml1 @@ -178,7 +178,7 @@ org.opensaml - opensaml + opensaml1 @@ -194,7 +194,7 @@ org.opensaml - opensaml + opensaml1 @@ -210,7 +210,7 @@ org.opensaml - opensaml + opensaml1 @@ -223,7 +223,6 @@ org.slf4j slf4j-api - 1.6.1 runtime @@ -271,8 +270,6 @@ org.bouncycastle bcprov-jdk16 - - 1.45 runtime @@ -317,6 +314,16 @@ + + org.apache.maven.plugins + maven-checkstyle-plugin + + + cloudstack-checkstyle + none + + + org.apache.maven.plugins maven-surefire-plugin @@ -408,47 +415,6 @@ - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - org.apache.maven.plugins - maven-antrun-plugin - [1.7,) - - run - - - - - - - - - org.apache.maven.plugins - maven-dependency-plugin - [2.0,) - - copy-dependencies - - - - - - - - - - - - diff --git a/awsapi/src/com/amazon/ec2/AmazonEC2MessageReceiverInOut.java b/awsapi/src/com/amazon/ec2/AmazonEC2MessageReceiverInOut.java index e04952a5684..302644c772e 100644 --- a/awsapi/src/com/amazon/ec2/AmazonEC2MessageReceiverInOut.java +++ b/awsapi/src/com/amazon/ec2/AmazonEC2MessageReceiverInOut.java @@ -59,7 +59,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describePlacementGroupsResponse289 = - skel.describePlacementGroups(wrappedParam); + skel.describePlacementGroups(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describePlacementGroupsResponse289, false); } else @@ -73,7 +73,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab createSecurityGroupResponse291 = - skel.createSecurityGroup(wrappedParam); + skel.createSecurityGroup(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), createSecurityGroupResponse291, false); } else @@ -87,7 +87,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab resetNetworkInterfaceAttributeResponse293 = - skel.resetNetworkInterfaceAttribute(wrappedParam); + skel.resetNetworkInterfaceAttribute(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), resetNetworkInterfaceAttributeResponse293, false); } else @@ -101,7 +101,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab createDhcpOptionsResponse295 = - skel.createDhcpOptions(wrappedParam); + skel.createDhcpOptions(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), createDhcpOptionsResponse295, false); } else @@ -115,7 +115,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab createRouteTableResponse297 = - skel.createRouteTable(wrappedParam); + skel.createRouteTable(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), createRouteTableResponse297, false); } else @@ -129,7 +129,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeSubnetsResponse299 = - skel.describeSubnets(wrappedParam); + skel.describeSubnets(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeSubnetsResponse299, false); } else @@ -143,7 +143,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab deactivateLicenseResponse301 = - skel.deactivateLicense(wrappedParam); + skel.deactivateLicense(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), deactivateLicenseResponse301, false); } else @@ -157,7 +157,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab deleteVpcResponse303 = - skel.deleteVpc(wrappedParam); + skel.deleteVpc(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), deleteVpcResponse303, false); } else @@ -171,7 +171,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab cancelSpotInstanceRequestsResponse305 = - skel.cancelSpotInstanceRequests(wrappedParam); + skel.cancelSpotInstanceRequests(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), cancelSpotInstanceRequestsResponse305, false); } else @@ -185,7 +185,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab createSubnetResponse307 = - skel.createSubnet(wrappedParam); + skel.createSubnet(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), createSubnetResponse307, false); } else @@ -199,7 +199,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab deleteVpnGatewayResponse309 = - skel.deleteVpnGateway(wrappedParam); + skel.deleteVpnGateway(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), deleteVpnGatewayResponse309, false); } else @@ -213,7 +213,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab createNetworkAclEntryResponse311 = - skel.createNetworkAclEntry(wrappedParam); + skel.createNetworkAclEntry(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), createNetworkAclEntryResponse311, false); } else @@ -227,7 +227,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab requestSpotInstancesResponse313 = - skel.requestSpotInstances(wrappedParam); + skel.requestSpotInstances(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), requestSpotInstancesResponse313, false); } else @@ -241,7 +241,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeVolumeAttributeResponse315 = - skel.describeVolumeAttribute(wrappedParam); + skel.describeVolumeAttribute(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeVolumeAttributeResponse315, false); } else @@ -255,7 +255,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab associateDhcpOptionsResponse317 = - skel.associateDhcpOptions(wrappedParam); + skel.associateDhcpOptions(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), associateDhcpOptionsResponse317, false); } else @@ -269,7 +269,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeTagsResponse319 = - skel.describeTags(wrappedParam); + skel.describeTags(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeTagsResponse319, false); } else @@ -283,7 +283,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab importKeyPairResponse321 = - skel.importKeyPair(wrappedParam); + skel.importKeyPair(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), importKeyPairResponse321, false); } else @@ -297,7 +297,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab deleteNetworkInterfaceResponse323 = - skel.deleteNetworkInterface(wrappedParam); + skel.deleteNetworkInterface(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), deleteNetworkInterfaceResponse323, false); } else @@ -311,7 +311,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeVpcsResponse325 = - skel.describeVpcs(wrappedParam); + skel.describeVpcs(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeVpcsResponse325, false); } else @@ -325,7 +325,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeLicensesResponse327 = - skel.describeLicenses(wrappedParam); + skel.describeLicenses(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeLicensesResponse327, false); } else @@ -339,7 +339,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab bundleInstanceResponse329 = - skel.bundleInstance(wrappedParam); + skel.bundleInstance(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), bundleInstanceResponse329, false); } else @@ -353,7 +353,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeVpnConnectionsResponse331 = - skel.describeVpnConnections(wrappedParam); + skel.describeVpnConnections(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeVpnConnectionsResponse331, false); } else @@ -367,7 +367,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeImagesResponse333 = - skel.describeImages(wrappedParam); + skel.describeImages(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeImagesResponse333, false); } else @@ -381,7 +381,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab createInternetGatewayResponse335 = - skel.createInternetGateway(wrappedParam); + skel.createInternetGateway(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), createInternetGatewayResponse335, false); } else @@ -395,7 +395,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab disassociateRouteTableResponse337 = - skel.disassociateRouteTable(wrappedParam); + skel.disassociateRouteTable(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), disassociateRouteTableResponse337, false); } else @@ -409,7 +409,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab replaceNetworkAclEntryResponse339 = - skel.replaceNetworkAclEntry(wrappedParam); + skel.replaceNetworkAclEntry(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), replaceNetworkAclEntryResponse339, false); } else @@ -423,7 +423,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab authorizeSecurityGroupIngressResponse341 = - skel.authorizeSecurityGroupIngress(wrappedParam); + skel.authorizeSecurityGroupIngress(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), authorizeSecurityGroupIngressResponse341, false); } else @@ -437,7 +437,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeSnapshotAttributeResponse343 = - skel.describeSnapshotAttribute(wrappedParam); + skel.describeSnapshotAttribute(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeSnapshotAttributeResponse343, false); } else @@ -451,7 +451,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab createVpnGatewayResponse345 = - skel.createVpnGateway(wrappedParam); + skel.createVpnGateway(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), createVpnGatewayResponse345, false); } else @@ -465,7 +465,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab resetInstanceAttributeResponse347 = - skel.resetInstanceAttribute(wrappedParam); + skel.resetInstanceAttribute(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), resetInstanceAttributeResponse347, false); } else @@ -479,7 +479,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab createTagsResponse349 = - skel.createTags(wrappedParam); + skel.createTags(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), createTagsResponse349, false); } else @@ -493,7 +493,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab authorizeSecurityGroupEgressResponse351 = - skel.authorizeSecurityGroupEgress(wrappedParam); + skel.authorizeSecurityGroupEgress(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), authorizeSecurityGroupEgressResponse351, false); } else @@ -507,7 +507,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab associateAddressResponse353 = - skel.associateAddress(wrappedParam); + skel.associateAddress(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), associateAddressResponse353, false); } else @@ -521,7 +521,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeImageAttributeResponse355 = - skel.describeImageAttribute(wrappedParam); + skel.describeImageAttribute(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeImageAttributeResponse355, false); } else @@ -535,7 +535,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeSpotPriceHistoryResponse357 = - skel.describeSpotPriceHistory(wrappedParam); + skel.describeSpotPriceHistory(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeSpotPriceHistoryResponse357, false); } else @@ -549,7 +549,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab modifySnapshotAttributeResponse359 = - skel.modifySnapshotAttribute(wrappedParam); + skel.modifySnapshotAttribute(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), modifySnapshotAttributeResponse359, false); } else @@ -563,7 +563,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeSpotInstanceRequestsResponse361 = - skel.describeSpotInstanceRequests(wrappedParam); + skel.describeSpotInstanceRequests(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeSpotInstanceRequestsResponse361, false); } else @@ -577,7 +577,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab importInstanceResponse363 = - skel.importInstance(wrappedParam); + skel.importInstance(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), importInstanceResponse363, false); } else @@ -591,7 +591,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeKeyPairsResponse365 = - skel.describeKeyPairs(wrappedParam); + skel.describeKeyPairs(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeKeyPairsResponse365, false); } else @@ -605,7 +605,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab revokeSecurityGroupIngressResponse367 = - skel.revokeSecurityGroupIngress(wrappedParam); + skel.revokeSecurityGroupIngress(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), revokeSecurityGroupIngressResponse367, false); } else @@ -619,7 +619,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab createPlacementGroupResponse369 = - skel.createPlacementGroup(wrappedParam); + skel.createPlacementGroup(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), createPlacementGroupResponse369, false); } else @@ -633,7 +633,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab deleteNetworkAclEntryResponse371 = - skel.deleteNetworkAclEntry(wrappedParam); + skel.deleteNetworkAclEntry(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), deleteNetworkAclEntryResponse371, false); } else @@ -647,7 +647,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab activateLicenseResponse373 = - skel.activateLicense(wrappedParam); + skel.activateLicense(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), activateLicenseResponse373, false); } else @@ -661,7 +661,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab deleteRouteTableResponse375 = - skel.deleteRouteTable(wrappedParam); + skel.deleteRouteTable(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), deleteRouteTableResponse375, false); } else @@ -675,7 +675,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab unmonitorInstancesResponse377 = - skel.unmonitorInstances(wrappedParam); + skel.unmonitorInstances(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), unmonitorInstancesResponse377, false); } else @@ -689,7 +689,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab startInstancesResponse379 = - skel.startInstances(wrappedParam); + skel.startInstances(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), startInstancesResponse379, false); } else @@ -703,7 +703,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab confirmProductInstanceResponse381 = - skel.confirmProductInstance(wrappedParam); + skel.confirmProductInstance(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), confirmProductInstanceResponse381, false); } else @@ -717,7 +717,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeNetworkInterfaceAttributeResponse383 = - skel.describeNetworkInterfaceAttribute(wrappedParam); + skel.describeNetworkInterfaceAttribute(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeNetworkInterfaceAttributeResponse383, false); } else @@ -731,7 +731,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab runInstancesResponse385 = - skel.runInstances(wrappedParam); + skel.runInstances(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), runInstancesResponse385, false); } else @@ -745,7 +745,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab createReservedInstancesListingResponse387 = - skel.createReservedInstancesListing(wrappedParam); + skel.createReservedInstancesListing(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), createReservedInstancesListingResponse387, false); } else @@ -759,7 +759,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab createCustomerGatewayResponse389 = - skel.createCustomerGateway(wrappedParam); + skel.createCustomerGateway(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), createCustomerGatewayResponse389, false); } else @@ -773,7 +773,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab createNetworkAclResponse391 = - skel.createNetworkAcl(wrappedParam); + skel.createNetworkAcl(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), createNetworkAclResponse391, false); } else @@ -787,7 +787,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab resetImageAttributeResponse393 = - skel.resetImageAttribute(wrappedParam); + skel.resetImageAttribute(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), resetImageAttributeResponse393, false); } else @@ -801,7 +801,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab modifyVolumeAttributeResponse395 = - skel.modifyVolumeAttribute(wrappedParam); + skel.modifyVolumeAttribute(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), modifyVolumeAttributeResponse395, false); } else @@ -815,7 +815,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeReservedInstancesResponse397 = - skel.describeReservedInstances(wrappedParam); + skel.describeReservedInstances(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeReservedInstancesResponse397, false); } else @@ -829,7 +829,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab resetSnapshotAttributeResponse399 = - skel.resetSnapshotAttribute(wrappedParam); + skel.resetSnapshotAttribute(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), resetSnapshotAttributeResponse399, false); } else @@ -843,7 +843,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab deleteVolumeResponse401 = - skel.deleteVolume(wrappedParam); + skel.deleteVolume(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), deleteVolumeResponse401, false); } else @@ -857,7 +857,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeAvailabilityZonesResponse403 = - skel.describeAvailabilityZones(wrappedParam); + skel.describeAvailabilityZones(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeAvailabilityZonesResponse403, false); } else @@ -871,7 +871,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab createVpnConnectionResponse405 = - skel.createVpnConnection(wrappedParam); + skel.createVpnConnection(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), createVpnConnectionResponse405, false); } else @@ -885,7 +885,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab cancelBundleTaskResponse407 = - skel.cancelBundleTask(wrappedParam); + skel.cancelBundleTask(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), cancelBundleTaskResponse407, false); } else @@ -899,7 +899,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab replaceNetworkAclAssociationResponse409 = - skel.replaceNetworkAclAssociation(wrappedParam); + skel.replaceNetworkAclAssociation(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), replaceNetworkAclAssociationResponse409, false); } else @@ -913,7 +913,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab detachVpnGatewayResponse411 = - skel.detachVpnGateway(wrappedParam); + skel.detachVpnGateway(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), detachVpnGatewayResponse411, false); } else @@ -927,7 +927,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeSnapshotsResponse413 = - skel.describeSnapshots(wrappedParam); + skel.describeSnapshots(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeSnapshotsResponse413, false); } else @@ -941,7 +941,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab deleteSubnetResponse415 = - skel.deleteSubnet(wrappedParam); + skel.deleteSubnet(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), deleteSubnetResponse415, false); } else @@ -955,7 +955,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeBundleTasksResponse417 = - skel.describeBundleTasks(wrappedParam); + skel.describeBundleTasks(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeBundleTasksResponse417, false); } else @@ -969,7 +969,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab createKeyPairResponse419 = - skel.createKeyPair(wrappedParam); + skel.createKeyPair(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), createKeyPairResponse419, false); } else @@ -983,7 +983,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab createImageResponse421 = - skel.createImage(wrappedParam); + skel.createImage(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), createImageResponse421, false); } else @@ -997,7 +997,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab enableVgwRoutePropagationResponse423 = - skel.enableVgwRoutePropagation(wrappedParam); + skel.enableVgwRoutePropagation(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), enableVgwRoutePropagationResponse423, false); } else @@ -1011,7 +1011,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab unassignPrivateIpAddressesResponse425 = - skel.unassignPrivateIpAddresses(wrappedParam); + skel.unassignPrivateIpAddresses(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), unassignPrivateIpAddressesResponse425, false); } else @@ -1025,7 +1025,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab deregisterImageResponse427 = - skel.deregisterImage(wrappedParam); + skel.deregisterImage(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), deregisterImageResponse427, false); } else @@ -1039,7 +1039,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab deleteVpnConnectionRouteResponse429 = - skel.deleteVpnConnectionRoute(wrappedParam); + skel.deleteVpnConnectionRoute(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), deleteVpnConnectionRouteResponse429, false); } else @@ -1053,7 +1053,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab modifyImageAttributeResponse431 = - skel.modifyImageAttribute(wrappedParam); + skel.modifyImageAttribute(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), modifyImageAttributeResponse431, false); } else @@ -1067,7 +1067,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab cancelConversionTaskResponse433 = - skel.cancelConversionTask(wrappedParam); + skel.cancelConversionTask(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), cancelConversionTaskResponse433, false); } else @@ -1081,7 +1081,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeVolumesResponse435 = - skel.describeVolumes(wrappedParam); + skel.describeVolumes(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeVolumesResponse435, false); } else @@ -1095,7 +1095,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab cancelReservedInstancesListingResponse437 = - skel.cancelReservedInstancesListing(wrappedParam); + skel.cancelReservedInstancesListing(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), cancelReservedInstancesListingResponse437, false); } else @@ -1109,7 +1109,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab getPasswordDataResponse439 = - skel.getPasswordData(wrappedParam); + skel.getPasswordData(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), getPasswordDataResponse439, false); } else @@ -1123,7 +1123,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab allocateAddressResponse441 = - skel.allocateAddress(wrappedParam); + skel.allocateAddress(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), allocateAddressResponse441, false); } else @@ -1137,7 +1137,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab deleteSecurityGroupResponse443 = - skel.deleteSecurityGroup(wrappedParam); + skel.deleteSecurityGroup(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), deleteSecurityGroupResponse443, false); } else @@ -1151,7 +1151,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab deletePlacementGroupResponse445 = - skel.deletePlacementGroup(wrappedParam); + skel.deletePlacementGroup(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), deletePlacementGroupResponse445, false); } else @@ -1165,7 +1165,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab disassociateAddressResponse447 = - skel.disassociateAddress(wrappedParam); + skel.disassociateAddress(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), disassociateAddressResponse447, false); } else @@ -1179,7 +1179,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab deleteDhcpOptionsResponse449 = - skel.deleteDhcpOptions(wrappedParam); + skel.deleteDhcpOptions(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), deleteDhcpOptionsResponse449, false); } else @@ -1193,7 +1193,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeSpotDatafeedSubscriptionResponse451 = - skel.describeSpotDatafeedSubscription(wrappedParam); + skel.describeSpotDatafeedSubscription(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeSpotDatafeedSubscriptionResponse451, false); } else @@ -1207,7 +1207,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeNetworkAclsResponse453 = - skel.describeNetworkAcls(wrappedParam); + skel.describeNetworkAcls(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeNetworkAclsResponse453, false); } else @@ -1221,7 +1221,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab enableVolumeIOResponse455 = - skel.enableVolumeIO(wrappedParam); + skel.enableVolumeIO(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), enableVolumeIOResponse455, false); } else @@ -1235,7 +1235,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab attachVpnGatewayResponse457 = - skel.attachVpnGateway(wrappedParam); + skel.attachVpnGateway(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), attachVpnGatewayResponse457, false); } else @@ -1249,7 +1249,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeInternetGatewaysResponse459 = - skel.describeInternetGateways(wrappedParam); + skel.describeInternetGateways(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeInternetGatewaysResponse459, false); } else @@ -1263,7 +1263,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeDhcpOptionsResponse461 = - skel.describeDhcpOptions(wrappedParam); + skel.describeDhcpOptions(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeDhcpOptionsResponse461, false); } else @@ -1277,7 +1277,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab createSpotDatafeedSubscriptionResponse463 = - skel.createSpotDatafeedSubscription(wrappedParam); + skel.createSpotDatafeedSubscription(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), createSpotDatafeedSubscriptionResponse463, false); } else @@ -1291,7 +1291,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeReservedInstancesListingsResponse465 = - skel.describeReservedInstancesListings(wrappedParam); + skel.describeReservedInstancesListings(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeReservedInstancesListingsResponse465, false); } else @@ -1305,7 +1305,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeInstanceStatusResponse467 = - skel.describeInstanceStatus(wrappedParam); + skel.describeInstanceStatus(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeInstanceStatusResponse467, false); } else @@ -1319,7 +1319,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab modifyNetworkInterfaceAttributeResponse469 = - skel.modifyNetworkInterfaceAttribute(wrappedParam); + skel.modifyNetworkInterfaceAttribute(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), modifyNetworkInterfaceAttributeResponse469, false); } else @@ -1333,7 +1333,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab disableVgwRoutePropagationResponse471 = - skel.disableVgwRoutePropagation(wrappedParam); + skel.disableVgwRoutePropagation(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), disableVgwRoutePropagationResponse471, false); } else @@ -1347,7 +1347,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeVolumeStatusResponse473 = - skel.describeVolumeStatus(wrappedParam); + skel.describeVolumeStatus(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeVolumeStatusResponse473, false); } else @@ -1361,7 +1361,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab detachNetworkInterfaceResponse475 = - skel.detachNetworkInterface(wrappedParam); + skel.detachNetworkInterface(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), detachNetworkInterfaceResponse475, false); } else @@ -1375,7 +1375,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeSecurityGroupsResponse477 = - skel.describeSecurityGroups(wrappedParam); + skel.describeSecurityGroups(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeSecurityGroupsResponse477, false); } else @@ -1389,7 +1389,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeInstancesResponse479 = - skel.describeInstances(wrappedParam); + skel.describeInstances(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeInstancesResponse479, false); } else @@ -1403,7 +1403,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeNetworkInterfacesResponse481 = - skel.describeNetworkInterfaces(wrappedParam); + skel.describeNetworkInterfaces(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeNetworkInterfacesResponse481, false); } else @@ -1417,7 +1417,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab deleteKeyPairResponse483 = - skel.deleteKeyPair(wrappedParam); + skel.deleteKeyPair(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), deleteKeyPairResponse483, false); } else @@ -1431,7 +1431,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab createSnapshotResponse485 = - skel.createSnapshot(wrappedParam); + skel.createSnapshot(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), createSnapshotResponse485, false); } else @@ -1445,7 +1445,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeVpnGatewaysResponse487 = - skel.describeVpnGateways(wrappedParam); + skel.describeVpnGateways(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeVpnGatewaysResponse487, false); } else @@ -1459,7 +1459,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab deleteTagsResponse489 = - skel.deleteTags(wrappedParam); + skel.deleteTags(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), deleteTagsResponse489, false); } else @@ -1473,7 +1473,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab deleteSnapshotResponse491 = - skel.deleteSnapshot(wrappedParam); + skel.deleteSnapshot(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), deleteSnapshotResponse491, false); } else @@ -1487,7 +1487,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab deleteCustomerGatewayResponse493 = - skel.deleteCustomerGateway(wrappedParam); + skel.deleteCustomerGateway(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), deleteCustomerGatewayResponse493, false); } else @@ -1501,7 +1501,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab createVolumeResponse495 = - skel.createVolume(wrappedParam); + skel.createVolume(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), createVolumeResponse495, false); } else @@ -1515,7 +1515,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab cancelExportTaskResponse497 = - skel.cancelExportTask(wrappedParam); + skel.cancelExportTask(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), cancelExportTaskResponse497, false); } else @@ -1529,7 +1529,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab registerImageResponse499 = - skel.registerImage(wrappedParam); + skel.registerImage(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), registerImageResponse499, false); } else @@ -1543,7 +1543,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab detachVolumeResponse501 = - skel.detachVolume(wrappedParam); + skel.detachVolume(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), detachVolumeResponse501, false); } else @@ -1557,7 +1557,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab stopInstancesResponse503 = - skel.stopInstances(wrappedParam); + skel.stopInstances(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), stopInstancesResponse503, false); } else @@ -1571,7 +1571,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab createRouteResponse505 = - skel.createRoute(wrappedParam); + skel.createRoute(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), createRouteResponse505, false); } else @@ -1585,7 +1585,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab releaseAddressResponse507 = - skel.releaseAddress(wrappedParam); + skel.releaseAddress(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), releaseAddressResponse507, false); } else @@ -1599,7 +1599,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeRouteTablesResponse509 = - skel.describeRouteTables(wrappedParam); + skel.describeRouteTables(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeRouteTablesResponse509, false); } else @@ -1613,7 +1613,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeCustomerGatewaysResponse511 = - skel.describeCustomerGateways(wrappedParam); + skel.describeCustomerGateways(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeCustomerGatewaysResponse511, false); } else @@ -1627,7 +1627,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab deleteNetworkAclResponse513 = - skel.deleteNetworkAcl(wrappedParam); + skel.deleteNetworkAcl(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), deleteNetworkAclResponse513, false); } else @@ -1641,7 +1641,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab deleteRouteResponse515 = - skel.deleteRoute(wrappedParam); + skel.deleteRoute(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), deleteRouteResponse515, false); } else @@ -1655,7 +1655,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab rebootInstancesResponse517 = - skel.rebootInstances(wrappedParam); + skel.rebootInstances(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), rebootInstancesResponse517, false); } else @@ -1669,7 +1669,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab modifyInstanceAttributeResponse519 = - skel.modifyInstanceAttribute(wrappedParam); + skel.modifyInstanceAttribute(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), modifyInstanceAttributeResponse519, false); } else @@ -1683,7 +1683,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab terminateInstancesResponse521 = - skel.terminateInstances(wrappedParam); + skel.terminateInstances(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), terminateInstancesResponse521, false); } else @@ -1697,7 +1697,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab createVpnConnectionRouteResponse523 = - skel.createVpnConnectionRoute(wrappedParam); + skel.createVpnConnectionRoute(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), createVpnConnectionRouteResponse523, false); } else @@ -1711,7 +1711,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeConversionTasksResponse525 = - skel.describeConversionTasks(wrappedParam); + skel.describeConversionTasks(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeConversionTasksResponse525, false); } else @@ -1725,7 +1725,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeAddressesResponse527 = - skel.describeAddresses(wrappedParam); + skel.describeAddresses(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeAddressesResponse527, false); } else @@ -1739,7 +1739,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeInstanceAttributeResponse529 = - skel.describeInstanceAttribute(wrappedParam); + skel.describeInstanceAttribute(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeInstanceAttributeResponse529, false); } else @@ -1753,7 +1753,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab attachInternetGatewayResponse531 = - skel.attachInternetGateway(wrappedParam); + skel.attachInternetGateway(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), attachInternetGatewayResponse531, false); } else @@ -1767,7 +1767,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab createVpcResponse533 = - skel.createVpc(wrappedParam); + skel.createVpc(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), createVpcResponse533, false); } else @@ -1781,7 +1781,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab replaceRouteTableAssociationResponse535 = - skel.replaceRouteTableAssociation(wrappedParam); + skel.replaceRouteTableAssociation(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), replaceRouteTableAssociationResponse535, false); } else @@ -1795,7 +1795,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab associateRouteTableResponse537 = - skel.associateRouteTable(wrappedParam); + skel.associateRouteTable(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), associateRouteTableResponse537, false); } else @@ -1809,7 +1809,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab detachInternetGatewayResponse539 = - skel.detachInternetGateway(wrappedParam); + skel.detachInternetGateway(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), detachInternetGatewayResponse539, false); } else @@ -1823,7 +1823,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab purchaseReservedInstancesOfferingResponse541 = - skel.purchaseReservedInstancesOffering(wrappedParam); + skel.purchaseReservedInstancesOffering(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), purchaseReservedInstancesOfferingResponse541, false); } else @@ -1837,7 +1837,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab importVolumeResponse543 = - skel.importVolume(wrappedParam); + skel.importVolume(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), importVolumeResponse543, false); } else @@ -1851,7 +1851,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeExportTasksResponse545 = - skel.describeExportTasks(wrappedParam); + skel.describeExportTasks(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeExportTasksResponse545, false); } else @@ -1865,7 +1865,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab createInstanceExportTaskResponse547 = - skel.createInstanceExportTask(wrappedParam); + skel.createInstanceExportTask(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), createInstanceExportTaskResponse547, false); } else @@ -1879,7 +1879,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab assignPrivateIpAddressesResponse549 = - skel.assignPrivateIpAddresses(wrappedParam); + skel.assignPrivateIpAddresses(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), assignPrivateIpAddressesResponse549, false); } else @@ -1893,7 +1893,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab reportInstanceStatusResponse551 = - skel.reportInstanceStatus(wrappedParam); + skel.reportInstanceStatus(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), reportInstanceStatusResponse551, false); } else @@ -1907,7 +1907,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeReservedInstancesOfferingsResponse553 = - skel.describeReservedInstancesOfferings(wrappedParam); + skel.describeReservedInstancesOfferings(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeReservedInstancesOfferingsResponse553, false); } else @@ -1921,7 +1921,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab deleteVpnConnectionResponse555 = - skel.deleteVpnConnection(wrappedParam); + skel.deleteVpnConnection(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), deleteVpnConnectionResponse555, false); } else @@ -1935,7 +1935,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab deleteInternetGatewayResponse557 = - skel.deleteInternetGateway(wrappedParam); + skel.deleteInternetGateway(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), deleteInternetGatewayResponse557, false); } else @@ -1949,7 +1949,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab deleteSpotDatafeedSubscriptionResponse559 = - skel.deleteSpotDatafeedSubscription(wrappedParam); + skel.deleteSpotDatafeedSubscription(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), deleteSpotDatafeedSubscriptionResponse559, false); } else @@ -1963,7 +1963,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab attachNetworkInterfaceResponse561 = - skel.attachNetworkInterface(wrappedParam); + skel.attachNetworkInterface(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), attachNetworkInterfaceResponse561, false); } else @@ -1977,7 +1977,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab createNetworkInterfaceResponse563 = - skel.createNetworkInterface(wrappedParam); + skel.createNetworkInterface(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), createNetworkInterfaceResponse563, false); } else @@ -1991,7 +1991,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab revokeSecurityGroupEgressResponse565 = - skel.revokeSecurityGroupEgress(wrappedParam); + skel.revokeSecurityGroupEgress(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), revokeSecurityGroupEgressResponse565, false); } else @@ -2005,7 +2005,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab monitorInstancesResponse567 = - skel.monitorInstances(wrappedParam); + skel.monitorInstances(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), monitorInstancesResponse567, false); } else @@ -2019,7 +2019,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab replaceRouteResponse569 = - skel.replaceRoute(wrappedParam); + skel.replaceRoute(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), replaceRouteResponse569, false); } else @@ -2033,7 +2033,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab attachVolumeResponse571 = - skel.attachVolume(wrappedParam); + skel.attachVolume(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), attachVolumeResponse571, false); } else @@ -2047,7 +2047,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab getConsoleOutputResponse573 = - skel.getConsoleOutput(wrappedParam); + skel.getConsoleOutput(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), getConsoleOutputResponse573, false); } else @@ -2061,7 +2061,7 @@ public class AmazonEC2MessageReceiverInOut extends org.apache.axis2.receivers.Ab describeRegionsResponse575 = - skel.describeRegions(wrappedParam); + skel.describeRegions(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), describeRegionsResponse575, false); diff --git a/awsapi/src/com/amazon/ec2/UserDataType.java b/awsapi/src/com/amazon/ec2/UserDataType.java index 4b04afd4b55..2f84fbef788 100644 --- a/awsapi/src/com/amazon/ec2/UserDataType.java +++ b/awsapi/src/com/amazon/ec2/UserDataType.java @@ -482,7 +482,7 @@ public class UserDataType implements org.apache.axis2.databinding.ADBBean { // handle attribute "version" java.lang.String tempAttribVersion = - reader.getAttributeValue(null, "version"); + reader.getAttributeValue(null, "version"); if (tempAttribVersion != null) { java.lang.String content = tempAttribVersion; @@ -499,7 +499,7 @@ public class UserDataType implements org.apache.axis2.databinding.ADBBean { // handle attribute "encoding" java.lang.String tempAttribEncoding = - reader.getAttributeValue(null, "encoding"); + reader.getAttributeValue(null, "encoding"); if (tempAttribEncoding != null) { java.lang.String content = tempAttribEncoding; diff --git a/awsapi/src/com/amazon/ec2/client/AmazonEC2Stub.java b/awsapi/src/com/amazon/ec2/client/AmazonEC2Stub.java index b6698a8aa0f..0da7d69465b 100644 --- a/awsapi/src/com/amazon/ec2/client/AmazonEC2Stub.java +++ b/awsapi/src/com/amazon/ec2/client/AmazonEC2Stub.java @@ -1131,9 +1131,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribePlacementGroupsResponse describePlacementGroups( - com.amazon.ec2.client.AmazonEC2Stub.DescribePlacementGroups describePlacementGroups0) + com.amazon.ec2.client.AmazonEC2Stub.DescribePlacementGroups describePlacementGroups0) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -1234,11 +1234,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribePlacementGroups( - com.amazon.ec2.client.AmazonEC2Stub.DescribePlacementGroups describePlacementGroups0, + com.amazon.ec2.client.AmazonEC2Stub.DescribePlacementGroups describePlacementGroups0, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[0].getName()); _operationClient.getOptions().setAction("DescribePlacementGroups"); @@ -1366,9 +1366,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.CreateSecurityGroupResponse createSecurityGroup( - com.amazon.ec2.client.AmazonEC2Stub.CreateSecurityGroup createSecurityGroup2) + com.amazon.ec2.client.AmazonEC2Stub.CreateSecurityGroup createSecurityGroup2) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -1468,11 +1468,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startcreateSecurityGroup( - com.amazon.ec2.client.AmazonEC2Stub.CreateSecurityGroup createSecurityGroup2, + com.amazon.ec2.client.AmazonEC2Stub.CreateSecurityGroup createSecurityGroup2, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[1].getName()); _operationClient.getOptions().setAction("CreateSecurityGroup"); @@ -1600,9 +1600,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.ResetNetworkInterfaceAttributeResponse resetNetworkInterfaceAttribute( - com.amazon.ec2.client.AmazonEC2Stub.ResetNetworkInterfaceAttribute resetNetworkInterfaceAttribute4) + com.amazon.ec2.client.AmazonEC2Stub.ResetNetworkInterfaceAttribute resetNetworkInterfaceAttribute4) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -1703,11 +1703,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startresetNetworkInterfaceAttribute( - com.amazon.ec2.client.AmazonEC2Stub.ResetNetworkInterfaceAttribute resetNetworkInterfaceAttribute4, + com.amazon.ec2.client.AmazonEC2Stub.ResetNetworkInterfaceAttribute resetNetworkInterfaceAttribute4, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[2].getName()); _operationClient.getOptions().setAction("ResetNetworkInterfaceAttribute"); @@ -1835,9 +1835,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.CreateDhcpOptionsResponse createDhcpOptions( - com.amazon.ec2.client.AmazonEC2Stub.CreateDhcpOptions createDhcpOptions6) + com.amazon.ec2.client.AmazonEC2Stub.CreateDhcpOptions createDhcpOptions6) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -1937,11 +1937,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startcreateDhcpOptions( - com.amazon.ec2.client.AmazonEC2Stub.CreateDhcpOptions createDhcpOptions6, + com.amazon.ec2.client.AmazonEC2Stub.CreateDhcpOptions createDhcpOptions6, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[3].getName()); _operationClient.getOptions().setAction("CreateDhcpOptions"); @@ -2069,9 +2069,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.CreateRouteTableResponse createRouteTable( - com.amazon.ec2.client.AmazonEC2Stub.CreateRouteTable createRouteTable8) + com.amazon.ec2.client.AmazonEC2Stub.CreateRouteTable createRouteTable8) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -2171,11 +2171,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startcreateRouteTable( - com.amazon.ec2.client.AmazonEC2Stub.CreateRouteTable createRouteTable8, + com.amazon.ec2.client.AmazonEC2Stub.CreateRouteTable createRouteTable8, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[4].getName()); _operationClient.getOptions().setAction("CreateRouteTable"); @@ -2303,9 +2303,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeSubnetsResponse describeSubnets( - com.amazon.ec2.client.AmazonEC2Stub.DescribeSubnets describeSubnets10) + com.amazon.ec2.client.AmazonEC2Stub.DescribeSubnets describeSubnets10) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -2405,11 +2405,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeSubnets( - com.amazon.ec2.client.AmazonEC2Stub.DescribeSubnets describeSubnets10, + com.amazon.ec2.client.AmazonEC2Stub.DescribeSubnets describeSubnets10, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[5].getName()); _operationClient.getOptions().setAction("DescribeSubnets"); @@ -2536,9 +2536,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DeactivateLicenseResponse deactivateLicense( - com.amazon.ec2.client.AmazonEC2Stub.DeactivateLicense deactivateLicense12) + com.amazon.ec2.client.AmazonEC2Stub.DeactivateLicense deactivateLicense12) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -2638,11 +2638,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdeactivateLicense( - com.amazon.ec2.client.AmazonEC2Stub.DeactivateLicense deactivateLicense12, + com.amazon.ec2.client.AmazonEC2Stub.DeactivateLicense deactivateLicense12, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[6].getName()); _operationClient.getOptions().setAction("DeactivateLicense"); @@ -2770,9 +2770,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DeleteVpcResponse deleteVpc( - com.amazon.ec2.client.AmazonEC2Stub.DeleteVpc deleteVpc14) + com.amazon.ec2.client.AmazonEC2Stub.DeleteVpc deleteVpc14) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -2872,11 +2872,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdeleteVpc( - com.amazon.ec2.client.AmazonEC2Stub.DeleteVpc deleteVpc14, + com.amazon.ec2.client.AmazonEC2Stub.DeleteVpc deleteVpc14, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[7].getName()); _operationClient.getOptions().setAction("DeleteVpc"); @@ -3003,9 +3003,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.CancelSpotInstanceRequestsResponse cancelSpotInstanceRequests( - com.amazon.ec2.client.AmazonEC2Stub.CancelSpotInstanceRequests cancelSpotInstanceRequests16) + com.amazon.ec2.client.AmazonEC2Stub.CancelSpotInstanceRequests cancelSpotInstanceRequests16) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -3106,11 +3106,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startcancelSpotInstanceRequests( - com.amazon.ec2.client.AmazonEC2Stub.CancelSpotInstanceRequests cancelSpotInstanceRequests16, + com.amazon.ec2.client.AmazonEC2Stub.CancelSpotInstanceRequests cancelSpotInstanceRequests16, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[8].getName()); _operationClient.getOptions().setAction("CancelSpotInstanceRequests"); @@ -3238,9 +3238,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.CreateSubnetResponse createSubnet( - com.amazon.ec2.client.AmazonEC2Stub.CreateSubnet createSubnet18) + com.amazon.ec2.client.AmazonEC2Stub.CreateSubnet createSubnet18) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -3340,11 +3340,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startcreateSubnet( - com.amazon.ec2.client.AmazonEC2Stub.CreateSubnet createSubnet18, + com.amazon.ec2.client.AmazonEC2Stub.CreateSubnet createSubnet18, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[9].getName()); _operationClient.getOptions().setAction("CreateSubnet"); @@ -3471,9 +3471,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DeleteVpnGatewayResponse deleteVpnGateway( - com.amazon.ec2.client.AmazonEC2Stub.DeleteVpnGateway deleteVpnGateway20) + com.amazon.ec2.client.AmazonEC2Stub.DeleteVpnGateway deleteVpnGateway20) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -3573,11 +3573,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdeleteVpnGateway( - com.amazon.ec2.client.AmazonEC2Stub.DeleteVpnGateway deleteVpnGateway20, + com.amazon.ec2.client.AmazonEC2Stub.DeleteVpnGateway deleteVpnGateway20, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[10].getName()); _operationClient.getOptions().setAction("DeleteVpnGateway"); @@ -3705,9 +3705,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.CreateNetworkAclEntryResponse createNetworkAclEntry( - com.amazon.ec2.client.AmazonEC2Stub.CreateNetworkAclEntry createNetworkAclEntry22) + com.amazon.ec2.client.AmazonEC2Stub.CreateNetworkAclEntry createNetworkAclEntry22) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -3807,11 +3807,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startcreateNetworkAclEntry( - com.amazon.ec2.client.AmazonEC2Stub.CreateNetworkAclEntry createNetworkAclEntry22, + com.amazon.ec2.client.AmazonEC2Stub.CreateNetworkAclEntry createNetworkAclEntry22, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[11].getName()); _operationClient.getOptions().setAction("CreateNetworkAclEntry"); @@ -3939,9 +3939,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.RequestSpotInstancesResponse requestSpotInstances( - com.amazon.ec2.client.AmazonEC2Stub.RequestSpotInstances requestSpotInstances24) + com.amazon.ec2.client.AmazonEC2Stub.RequestSpotInstances requestSpotInstances24) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -4041,11 +4041,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startrequestSpotInstances( - com.amazon.ec2.client.AmazonEC2Stub.RequestSpotInstances requestSpotInstances24, + com.amazon.ec2.client.AmazonEC2Stub.RequestSpotInstances requestSpotInstances24, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[12].getName()); _operationClient.getOptions().setAction("RequestSpotInstances"); @@ -4173,9 +4173,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeVolumeAttributeResponse describeVolumeAttribute( - com.amazon.ec2.client.AmazonEC2Stub.DescribeVolumeAttribute describeVolumeAttribute26) + com.amazon.ec2.client.AmazonEC2Stub.DescribeVolumeAttribute describeVolumeAttribute26) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -4276,11 +4276,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeVolumeAttribute( - com.amazon.ec2.client.AmazonEC2Stub.DescribeVolumeAttribute describeVolumeAttribute26, + com.amazon.ec2.client.AmazonEC2Stub.DescribeVolumeAttribute describeVolumeAttribute26, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[13].getName()); _operationClient.getOptions().setAction("DescribeVolumeAttribute"); @@ -4408,9 +4408,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.AssociateDhcpOptionsResponse associateDhcpOptions( - com.amazon.ec2.client.AmazonEC2Stub.AssociateDhcpOptions associateDhcpOptions28) + com.amazon.ec2.client.AmazonEC2Stub.AssociateDhcpOptions associateDhcpOptions28) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -4510,11 +4510,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startassociateDhcpOptions( - com.amazon.ec2.client.AmazonEC2Stub.AssociateDhcpOptions associateDhcpOptions28, + com.amazon.ec2.client.AmazonEC2Stub.AssociateDhcpOptions associateDhcpOptions28, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[14].getName()); _operationClient.getOptions().setAction("AssociateDhcpOptions"); @@ -4642,9 +4642,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeTagsResponse describeTags( - com.amazon.ec2.client.AmazonEC2Stub.DescribeTags describeTags30) + com.amazon.ec2.client.AmazonEC2Stub.DescribeTags describeTags30) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -4744,11 +4744,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeTags( - com.amazon.ec2.client.AmazonEC2Stub.DescribeTags describeTags30, + com.amazon.ec2.client.AmazonEC2Stub.DescribeTags describeTags30, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[15].getName()); _operationClient.getOptions().setAction("DescribeTags"); @@ -4875,9 +4875,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.ImportKeyPairResponse importKeyPair( - com.amazon.ec2.client.AmazonEC2Stub.ImportKeyPair importKeyPair32) + com.amazon.ec2.client.AmazonEC2Stub.ImportKeyPair importKeyPair32) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -4977,11 +4977,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startimportKeyPair( - com.amazon.ec2.client.AmazonEC2Stub.ImportKeyPair importKeyPair32, + com.amazon.ec2.client.AmazonEC2Stub.ImportKeyPair importKeyPair32, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[16].getName()); _operationClient.getOptions().setAction("ImportKeyPair"); @@ -5108,9 +5108,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DeleteNetworkInterfaceResponse deleteNetworkInterface( - com.amazon.ec2.client.AmazonEC2Stub.DeleteNetworkInterface deleteNetworkInterface34) + com.amazon.ec2.client.AmazonEC2Stub.DeleteNetworkInterface deleteNetworkInterface34) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -5211,11 +5211,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdeleteNetworkInterface( - com.amazon.ec2.client.AmazonEC2Stub.DeleteNetworkInterface deleteNetworkInterface34, + com.amazon.ec2.client.AmazonEC2Stub.DeleteNetworkInterface deleteNetworkInterface34, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[17].getName()); _operationClient.getOptions().setAction("DeleteNetworkInterface"); @@ -5343,9 +5343,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeVpcsResponse describeVpcs( - com.amazon.ec2.client.AmazonEC2Stub.DescribeVpcs describeVpcs36) + com.amazon.ec2.client.AmazonEC2Stub.DescribeVpcs describeVpcs36) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -5445,11 +5445,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeVpcs( - com.amazon.ec2.client.AmazonEC2Stub.DescribeVpcs describeVpcs36, + com.amazon.ec2.client.AmazonEC2Stub.DescribeVpcs describeVpcs36, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[18].getName()); _operationClient.getOptions().setAction("DescribeVpcs"); @@ -5576,9 +5576,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeLicensesResponse describeLicenses( - com.amazon.ec2.client.AmazonEC2Stub.DescribeLicenses describeLicenses38) + com.amazon.ec2.client.AmazonEC2Stub.DescribeLicenses describeLicenses38) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -5678,11 +5678,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeLicenses( - com.amazon.ec2.client.AmazonEC2Stub.DescribeLicenses describeLicenses38, + com.amazon.ec2.client.AmazonEC2Stub.DescribeLicenses describeLicenses38, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[19].getName()); _operationClient.getOptions().setAction("DescribeLicenses"); @@ -5810,9 +5810,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.BundleInstanceResponse bundleInstance( - com.amazon.ec2.client.AmazonEC2Stub.BundleInstance bundleInstance40) + com.amazon.ec2.client.AmazonEC2Stub.BundleInstance bundleInstance40) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -5912,11 +5912,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startbundleInstance( - com.amazon.ec2.client.AmazonEC2Stub.BundleInstance bundleInstance40, + com.amazon.ec2.client.AmazonEC2Stub.BundleInstance bundleInstance40, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[20].getName()); _operationClient.getOptions().setAction("BundleInstance"); @@ -6043,9 +6043,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeVpnConnectionsResponse describeVpnConnections( - com.amazon.ec2.client.AmazonEC2Stub.DescribeVpnConnections describeVpnConnections42) + com.amazon.ec2.client.AmazonEC2Stub.DescribeVpnConnections describeVpnConnections42) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -6146,11 +6146,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeVpnConnections( - com.amazon.ec2.client.AmazonEC2Stub.DescribeVpnConnections describeVpnConnections42, + com.amazon.ec2.client.AmazonEC2Stub.DescribeVpnConnections describeVpnConnections42, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[21].getName()); _operationClient.getOptions().setAction("DescribeVpnConnections"); @@ -6278,9 +6278,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeImagesResponse describeImages( - com.amazon.ec2.client.AmazonEC2Stub.DescribeImages describeImages44) + com.amazon.ec2.client.AmazonEC2Stub.DescribeImages describeImages44) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -6380,11 +6380,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeImages( - com.amazon.ec2.client.AmazonEC2Stub.DescribeImages describeImages44, + com.amazon.ec2.client.AmazonEC2Stub.DescribeImages describeImages44, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[22].getName()); _operationClient.getOptions().setAction("DescribeImages"); @@ -6511,9 +6511,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.CreateInternetGatewayResponse createInternetGateway( - com.amazon.ec2.client.AmazonEC2Stub.CreateInternetGateway createInternetGateway46) + com.amazon.ec2.client.AmazonEC2Stub.CreateInternetGateway createInternetGateway46) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -6613,11 +6613,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startcreateInternetGateway( - com.amazon.ec2.client.AmazonEC2Stub.CreateInternetGateway createInternetGateway46, + com.amazon.ec2.client.AmazonEC2Stub.CreateInternetGateway createInternetGateway46, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[23].getName()); _operationClient.getOptions().setAction("CreateInternetGateway"); @@ -6745,9 +6745,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DisassociateRouteTableResponse disassociateRouteTable( - com.amazon.ec2.client.AmazonEC2Stub.DisassociateRouteTable disassociateRouteTable48) + com.amazon.ec2.client.AmazonEC2Stub.DisassociateRouteTable disassociateRouteTable48) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -6848,11 +6848,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdisassociateRouteTable( - com.amazon.ec2.client.AmazonEC2Stub.DisassociateRouteTable disassociateRouteTable48, + com.amazon.ec2.client.AmazonEC2Stub.DisassociateRouteTable disassociateRouteTable48, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[24].getName()); _operationClient.getOptions().setAction("DisassociateRouteTable"); @@ -6980,9 +6980,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.ReplaceNetworkAclEntryResponse replaceNetworkAclEntry( - com.amazon.ec2.client.AmazonEC2Stub.ReplaceNetworkAclEntry replaceNetworkAclEntry50) + com.amazon.ec2.client.AmazonEC2Stub.ReplaceNetworkAclEntry replaceNetworkAclEntry50) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -7083,11 +7083,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startreplaceNetworkAclEntry( - com.amazon.ec2.client.AmazonEC2Stub.ReplaceNetworkAclEntry replaceNetworkAclEntry50, + com.amazon.ec2.client.AmazonEC2Stub.ReplaceNetworkAclEntry replaceNetworkAclEntry50, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[25].getName()); _operationClient.getOptions().setAction("ReplaceNetworkAclEntry"); @@ -7215,9 +7215,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.AuthorizeSecurityGroupIngressResponse authorizeSecurityGroupIngress( - com.amazon.ec2.client.AmazonEC2Stub.AuthorizeSecurityGroupIngress authorizeSecurityGroupIngress52) + com.amazon.ec2.client.AmazonEC2Stub.AuthorizeSecurityGroupIngress authorizeSecurityGroupIngress52) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -7318,11 +7318,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startauthorizeSecurityGroupIngress( - com.amazon.ec2.client.AmazonEC2Stub.AuthorizeSecurityGroupIngress authorizeSecurityGroupIngress52, + com.amazon.ec2.client.AmazonEC2Stub.AuthorizeSecurityGroupIngress authorizeSecurityGroupIngress52, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[26].getName()); _operationClient.getOptions().setAction("AuthorizeSecurityGroupIngress"); @@ -7450,9 +7450,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeSnapshotAttributeResponse describeSnapshotAttribute( - com.amazon.ec2.client.AmazonEC2Stub.DescribeSnapshotAttribute describeSnapshotAttribute54) + com.amazon.ec2.client.AmazonEC2Stub.DescribeSnapshotAttribute describeSnapshotAttribute54) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -7553,11 +7553,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeSnapshotAttribute( - com.amazon.ec2.client.AmazonEC2Stub.DescribeSnapshotAttribute describeSnapshotAttribute54, + com.amazon.ec2.client.AmazonEC2Stub.DescribeSnapshotAttribute describeSnapshotAttribute54, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[27].getName()); _operationClient.getOptions().setAction("DescribeSnapshotAttribute"); @@ -7685,9 +7685,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.CreateVpnGatewayResponse createVpnGateway( - com.amazon.ec2.client.AmazonEC2Stub.CreateVpnGateway createVpnGateway56) + com.amazon.ec2.client.AmazonEC2Stub.CreateVpnGateway createVpnGateway56) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -7787,11 +7787,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startcreateVpnGateway( - com.amazon.ec2.client.AmazonEC2Stub.CreateVpnGateway createVpnGateway56, + com.amazon.ec2.client.AmazonEC2Stub.CreateVpnGateway createVpnGateway56, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[28].getName()); _operationClient.getOptions().setAction("CreateVpnGateway"); @@ -7919,9 +7919,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.ResetInstanceAttributeResponse resetInstanceAttribute( - com.amazon.ec2.client.AmazonEC2Stub.ResetInstanceAttribute resetInstanceAttribute58) + com.amazon.ec2.client.AmazonEC2Stub.ResetInstanceAttribute resetInstanceAttribute58) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -8022,11 +8022,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startresetInstanceAttribute( - com.amazon.ec2.client.AmazonEC2Stub.ResetInstanceAttribute resetInstanceAttribute58, + com.amazon.ec2.client.AmazonEC2Stub.ResetInstanceAttribute resetInstanceAttribute58, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[29].getName()); _operationClient.getOptions().setAction("ResetInstanceAttribute"); @@ -8154,9 +8154,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.CreateTagsResponse createTags( - com.amazon.ec2.client.AmazonEC2Stub.CreateTags createTags60) + com.amazon.ec2.client.AmazonEC2Stub.CreateTags createTags60) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -8256,11 +8256,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startcreateTags( - com.amazon.ec2.client.AmazonEC2Stub.CreateTags createTags60, + com.amazon.ec2.client.AmazonEC2Stub.CreateTags createTags60, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[30].getName()); _operationClient.getOptions().setAction("CreateTags"); @@ -8387,9 +8387,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.AuthorizeSecurityGroupEgressResponse authorizeSecurityGroupEgress( - com.amazon.ec2.client.AmazonEC2Stub.AuthorizeSecurityGroupEgress authorizeSecurityGroupEgress62) + com.amazon.ec2.client.AmazonEC2Stub.AuthorizeSecurityGroupEgress authorizeSecurityGroupEgress62) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -8490,11 +8490,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startauthorizeSecurityGroupEgress( - com.amazon.ec2.client.AmazonEC2Stub.AuthorizeSecurityGroupEgress authorizeSecurityGroupEgress62, + com.amazon.ec2.client.AmazonEC2Stub.AuthorizeSecurityGroupEgress authorizeSecurityGroupEgress62, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[31].getName()); _operationClient.getOptions().setAction("AuthorizeSecurityGroupEgress"); @@ -8622,9 +8622,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.AssociateAddressResponse associateAddress( - com.amazon.ec2.client.AmazonEC2Stub.AssociateAddress associateAddress64) + com.amazon.ec2.client.AmazonEC2Stub.AssociateAddress associateAddress64) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -8724,11 +8724,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startassociateAddress( - com.amazon.ec2.client.AmazonEC2Stub.AssociateAddress associateAddress64, + com.amazon.ec2.client.AmazonEC2Stub.AssociateAddress associateAddress64, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[32].getName()); _operationClient.getOptions().setAction("AssociateAddress"); @@ -8856,9 +8856,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeImageAttributeResponse describeImageAttribute( - com.amazon.ec2.client.AmazonEC2Stub.DescribeImageAttribute describeImageAttribute66) + com.amazon.ec2.client.AmazonEC2Stub.DescribeImageAttribute describeImageAttribute66) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -8959,11 +8959,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeImageAttribute( - com.amazon.ec2.client.AmazonEC2Stub.DescribeImageAttribute describeImageAttribute66, + com.amazon.ec2.client.AmazonEC2Stub.DescribeImageAttribute describeImageAttribute66, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[33].getName()); _operationClient.getOptions().setAction("DescribeImageAttribute"); @@ -9091,9 +9091,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeSpotPriceHistoryResponse describeSpotPriceHistory( - com.amazon.ec2.client.AmazonEC2Stub.DescribeSpotPriceHistory describeSpotPriceHistory68) + com.amazon.ec2.client.AmazonEC2Stub.DescribeSpotPriceHistory describeSpotPriceHistory68) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -9194,11 +9194,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeSpotPriceHistory( - com.amazon.ec2.client.AmazonEC2Stub.DescribeSpotPriceHistory describeSpotPriceHistory68, + com.amazon.ec2.client.AmazonEC2Stub.DescribeSpotPriceHistory describeSpotPriceHistory68, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[34].getName()); _operationClient.getOptions().setAction("DescribeSpotPriceHistory"); @@ -9326,9 +9326,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.ModifySnapshotAttributeResponse modifySnapshotAttribute( - com.amazon.ec2.client.AmazonEC2Stub.ModifySnapshotAttribute modifySnapshotAttribute70) + com.amazon.ec2.client.AmazonEC2Stub.ModifySnapshotAttribute modifySnapshotAttribute70) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -9429,11 +9429,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startmodifySnapshotAttribute( - com.amazon.ec2.client.AmazonEC2Stub.ModifySnapshotAttribute modifySnapshotAttribute70, + com.amazon.ec2.client.AmazonEC2Stub.ModifySnapshotAttribute modifySnapshotAttribute70, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[35].getName()); _operationClient.getOptions().setAction("ModifySnapshotAttribute"); @@ -9561,9 +9561,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeSpotInstanceRequestsResponse describeSpotInstanceRequests( - com.amazon.ec2.client.AmazonEC2Stub.DescribeSpotInstanceRequests describeSpotInstanceRequests72) + com.amazon.ec2.client.AmazonEC2Stub.DescribeSpotInstanceRequests describeSpotInstanceRequests72) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -9664,11 +9664,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeSpotInstanceRequests( - com.amazon.ec2.client.AmazonEC2Stub.DescribeSpotInstanceRequests describeSpotInstanceRequests72, + com.amazon.ec2.client.AmazonEC2Stub.DescribeSpotInstanceRequests describeSpotInstanceRequests72, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[36].getName()); _operationClient.getOptions().setAction("DescribeSpotInstanceRequests"); @@ -9796,9 +9796,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.ImportInstanceResponse importInstance( - com.amazon.ec2.client.AmazonEC2Stub.ImportInstance importInstance74) + com.amazon.ec2.client.AmazonEC2Stub.ImportInstance importInstance74) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -9898,11 +9898,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startimportInstance( - com.amazon.ec2.client.AmazonEC2Stub.ImportInstance importInstance74, + com.amazon.ec2.client.AmazonEC2Stub.ImportInstance importInstance74, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[37].getName()); _operationClient.getOptions().setAction("ImportInstance"); @@ -10029,9 +10029,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeKeyPairsResponse describeKeyPairs( - com.amazon.ec2.client.AmazonEC2Stub.DescribeKeyPairs describeKeyPairs76) + com.amazon.ec2.client.AmazonEC2Stub.DescribeKeyPairs describeKeyPairs76) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -10131,11 +10131,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeKeyPairs( - com.amazon.ec2.client.AmazonEC2Stub.DescribeKeyPairs describeKeyPairs76, + com.amazon.ec2.client.AmazonEC2Stub.DescribeKeyPairs describeKeyPairs76, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[38].getName()); _operationClient.getOptions().setAction("DescribeKeyPairs"); @@ -10263,9 +10263,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.RevokeSecurityGroupIngressResponse revokeSecurityGroupIngress( - com.amazon.ec2.client.AmazonEC2Stub.RevokeSecurityGroupIngress revokeSecurityGroupIngress78) + com.amazon.ec2.client.AmazonEC2Stub.RevokeSecurityGroupIngress revokeSecurityGroupIngress78) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -10366,11 +10366,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startrevokeSecurityGroupIngress( - com.amazon.ec2.client.AmazonEC2Stub.RevokeSecurityGroupIngress revokeSecurityGroupIngress78, + com.amazon.ec2.client.AmazonEC2Stub.RevokeSecurityGroupIngress revokeSecurityGroupIngress78, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[39].getName()); _operationClient.getOptions().setAction("RevokeSecurityGroupIngress"); @@ -10498,9 +10498,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.CreatePlacementGroupResponse createPlacementGroup( - com.amazon.ec2.client.AmazonEC2Stub.CreatePlacementGroup createPlacementGroup80) + com.amazon.ec2.client.AmazonEC2Stub.CreatePlacementGroup createPlacementGroup80) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -10600,11 +10600,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startcreatePlacementGroup( - com.amazon.ec2.client.AmazonEC2Stub.CreatePlacementGroup createPlacementGroup80, + com.amazon.ec2.client.AmazonEC2Stub.CreatePlacementGroup createPlacementGroup80, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[40].getName()); _operationClient.getOptions().setAction("CreatePlacementGroup"); @@ -10732,9 +10732,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DeleteNetworkAclEntryResponse deleteNetworkAclEntry( - com.amazon.ec2.client.AmazonEC2Stub.DeleteNetworkAclEntry deleteNetworkAclEntry82) + com.amazon.ec2.client.AmazonEC2Stub.DeleteNetworkAclEntry deleteNetworkAclEntry82) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -10834,11 +10834,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdeleteNetworkAclEntry( - com.amazon.ec2.client.AmazonEC2Stub.DeleteNetworkAclEntry deleteNetworkAclEntry82, + com.amazon.ec2.client.AmazonEC2Stub.DeleteNetworkAclEntry deleteNetworkAclEntry82, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[41].getName()); _operationClient.getOptions().setAction("DeleteNetworkAclEntry"); @@ -10966,9 +10966,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.ActivateLicenseResponse activateLicense( - com.amazon.ec2.client.AmazonEC2Stub.ActivateLicense activateLicense84) + com.amazon.ec2.client.AmazonEC2Stub.ActivateLicense activateLicense84) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -11068,11 +11068,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startactivateLicense( - com.amazon.ec2.client.AmazonEC2Stub.ActivateLicense activateLicense84, + com.amazon.ec2.client.AmazonEC2Stub.ActivateLicense activateLicense84, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[42].getName()); _operationClient.getOptions().setAction("ActivateLicense"); @@ -11199,9 +11199,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DeleteRouteTableResponse deleteRouteTable( - com.amazon.ec2.client.AmazonEC2Stub.DeleteRouteTable deleteRouteTable86) + com.amazon.ec2.client.AmazonEC2Stub.DeleteRouteTable deleteRouteTable86) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -11301,11 +11301,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdeleteRouteTable( - com.amazon.ec2.client.AmazonEC2Stub.DeleteRouteTable deleteRouteTable86, + com.amazon.ec2.client.AmazonEC2Stub.DeleteRouteTable deleteRouteTable86, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[43].getName()); _operationClient.getOptions().setAction("DeleteRouteTable"); @@ -11433,9 +11433,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.UnmonitorInstancesResponse unmonitorInstances( - com.amazon.ec2.client.AmazonEC2Stub.UnmonitorInstances unmonitorInstances88) + com.amazon.ec2.client.AmazonEC2Stub.UnmonitorInstances unmonitorInstances88) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -11535,11 +11535,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startunmonitorInstances( - com.amazon.ec2.client.AmazonEC2Stub.UnmonitorInstances unmonitorInstances88, + com.amazon.ec2.client.AmazonEC2Stub.UnmonitorInstances unmonitorInstances88, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[44].getName()); _operationClient.getOptions().setAction("UnmonitorInstances"); @@ -11667,9 +11667,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.StartInstancesResponse startInstances( - com.amazon.ec2.client.AmazonEC2Stub.StartInstances startInstances90) + com.amazon.ec2.client.AmazonEC2Stub.StartInstances startInstances90) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -11769,11 +11769,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startstartInstances( - com.amazon.ec2.client.AmazonEC2Stub.StartInstances startInstances90, + com.amazon.ec2.client.AmazonEC2Stub.StartInstances startInstances90, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[45].getName()); _operationClient.getOptions().setAction("StartInstances"); @@ -11900,9 +11900,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.ConfirmProductInstanceResponse confirmProductInstance( - com.amazon.ec2.client.AmazonEC2Stub.ConfirmProductInstance confirmProductInstance92) + com.amazon.ec2.client.AmazonEC2Stub.ConfirmProductInstance confirmProductInstance92) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -12003,11 +12003,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startconfirmProductInstance( - com.amazon.ec2.client.AmazonEC2Stub.ConfirmProductInstance confirmProductInstance92, + com.amazon.ec2.client.AmazonEC2Stub.ConfirmProductInstance confirmProductInstance92, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[46].getName()); _operationClient.getOptions().setAction("ConfirmProductInstance"); @@ -12135,9 +12135,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeNetworkInterfaceAttributeResponse describeNetworkInterfaceAttribute( - com.amazon.ec2.client.AmazonEC2Stub.DescribeNetworkInterfaceAttribute describeNetworkInterfaceAttribute94) + com.amazon.ec2.client.AmazonEC2Stub.DescribeNetworkInterfaceAttribute describeNetworkInterfaceAttribute94) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -12238,11 +12238,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeNetworkInterfaceAttribute( - com.amazon.ec2.client.AmazonEC2Stub.DescribeNetworkInterfaceAttribute describeNetworkInterfaceAttribute94, + com.amazon.ec2.client.AmazonEC2Stub.DescribeNetworkInterfaceAttribute describeNetworkInterfaceAttribute94, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[47].getName()); _operationClient.getOptions().setAction("DescribeNetworkInterfaceAttribute"); @@ -12370,9 +12370,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.RunInstancesResponse runInstances( - com.amazon.ec2.client.AmazonEC2Stub.RunInstances runInstances96) + com.amazon.ec2.client.AmazonEC2Stub.RunInstances runInstances96) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -12472,11 +12472,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startrunInstances( - com.amazon.ec2.client.AmazonEC2Stub.RunInstances runInstances96, + com.amazon.ec2.client.AmazonEC2Stub.RunInstances runInstances96, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[48].getName()); _operationClient.getOptions().setAction("RunInstances"); @@ -12603,9 +12603,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.CreateReservedInstancesListingResponse createReservedInstancesListing( - com.amazon.ec2.client.AmazonEC2Stub.CreateReservedInstancesListing createReservedInstancesListing98) + com.amazon.ec2.client.AmazonEC2Stub.CreateReservedInstancesListing createReservedInstancesListing98) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -12706,11 +12706,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startcreateReservedInstancesListing( - com.amazon.ec2.client.AmazonEC2Stub.CreateReservedInstancesListing createReservedInstancesListing98, + com.amazon.ec2.client.AmazonEC2Stub.CreateReservedInstancesListing createReservedInstancesListing98, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[49].getName()); _operationClient.getOptions().setAction("CreateReservedInstancesListing"); @@ -12838,9 +12838,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.CreateCustomerGatewayResponse createCustomerGateway( - com.amazon.ec2.client.AmazonEC2Stub.CreateCustomerGateway createCustomerGateway100) + com.amazon.ec2.client.AmazonEC2Stub.CreateCustomerGateway createCustomerGateway100) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -12940,11 +12940,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startcreateCustomerGateway( - com.amazon.ec2.client.AmazonEC2Stub.CreateCustomerGateway createCustomerGateway100, + com.amazon.ec2.client.AmazonEC2Stub.CreateCustomerGateway createCustomerGateway100, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[50].getName()); _operationClient.getOptions().setAction("CreateCustomerGateway"); @@ -13072,9 +13072,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.CreateNetworkAclResponse createNetworkAcl( - com.amazon.ec2.client.AmazonEC2Stub.CreateNetworkAcl createNetworkAcl102) + com.amazon.ec2.client.AmazonEC2Stub.CreateNetworkAcl createNetworkAcl102) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -13174,11 +13174,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startcreateNetworkAcl( - com.amazon.ec2.client.AmazonEC2Stub.CreateNetworkAcl createNetworkAcl102, + com.amazon.ec2.client.AmazonEC2Stub.CreateNetworkAcl createNetworkAcl102, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[51].getName()); _operationClient.getOptions().setAction("CreateNetworkAcl"); @@ -13306,9 +13306,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.ResetImageAttributeResponse resetImageAttribute( - com.amazon.ec2.client.AmazonEC2Stub.ResetImageAttribute resetImageAttribute104) + com.amazon.ec2.client.AmazonEC2Stub.ResetImageAttribute resetImageAttribute104) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -13408,11 +13408,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startresetImageAttribute( - com.amazon.ec2.client.AmazonEC2Stub.ResetImageAttribute resetImageAttribute104, + com.amazon.ec2.client.AmazonEC2Stub.ResetImageAttribute resetImageAttribute104, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[52].getName()); _operationClient.getOptions().setAction("ResetImageAttribute"); @@ -13540,9 +13540,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.ModifyVolumeAttributeResponse modifyVolumeAttribute( - com.amazon.ec2.client.AmazonEC2Stub.ModifyVolumeAttribute modifyVolumeAttribute106) + com.amazon.ec2.client.AmazonEC2Stub.ModifyVolumeAttribute modifyVolumeAttribute106) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -13642,11 +13642,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startmodifyVolumeAttribute( - com.amazon.ec2.client.AmazonEC2Stub.ModifyVolumeAttribute modifyVolumeAttribute106, + com.amazon.ec2.client.AmazonEC2Stub.ModifyVolumeAttribute modifyVolumeAttribute106, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[53].getName()); _operationClient.getOptions().setAction("ModifyVolumeAttribute"); @@ -13774,9 +13774,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeReservedInstancesResponse describeReservedInstances( - com.amazon.ec2.client.AmazonEC2Stub.DescribeReservedInstances describeReservedInstances108) + com.amazon.ec2.client.AmazonEC2Stub.DescribeReservedInstances describeReservedInstances108) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -13877,11 +13877,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeReservedInstances( - com.amazon.ec2.client.AmazonEC2Stub.DescribeReservedInstances describeReservedInstances108, + com.amazon.ec2.client.AmazonEC2Stub.DescribeReservedInstances describeReservedInstances108, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[54].getName()); _operationClient.getOptions().setAction("DescribeReservedInstances"); @@ -14009,9 +14009,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.ResetSnapshotAttributeResponse resetSnapshotAttribute( - com.amazon.ec2.client.AmazonEC2Stub.ResetSnapshotAttribute resetSnapshotAttribute110) + com.amazon.ec2.client.AmazonEC2Stub.ResetSnapshotAttribute resetSnapshotAttribute110) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -14112,11 +14112,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startresetSnapshotAttribute( - com.amazon.ec2.client.AmazonEC2Stub.ResetSnapshotAttribute resetSnapshotAttribute110, + com.amazon.ec2.client.AmazonEC2Stub.ResetSnapshotAttribute resetSnapshotAttribute110, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[55].getName()); _operationClient.getOptions().setAction("ResetSnapshotAttribute"); @@ -14244,9 +14244,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DeleteVolumeResponse deleteVolume( - com.amazon.ec2.client.AmazonEC2Stub.DeleteVolume deleteVolume112) + com.amazon.ec2.client.AmazonEC2Stub.DeleteVolume deleteVolume112) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -14346,11 +14346,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdeleteVolume( - com.amazon.ec2.client.AmazonEC2Stub.DeleteVolume deleteVolume112, + com.amazon.ec2.client.AmazonEC2Stub.DeleteVolume deleteVolume112, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[56].getName()); _operationClient.getOptions().setAction("DeleteVolume"); @@ -14477,9 +14477,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeAvailabilityZonesResponse describeAvailabilityZones( - com.amazon.ec2.client.AmazonEC2Stub.DescribeAvailabilityZones describeAvailabilityZones114) + com.amazon.ec2.client.AmazonEC2Stub.DescribeAvailabilityZones describeAvailabilityZones114) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -14580,11 +14580,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeAvailabilityZones( - com.amazon.ec2.client.AmazonEC2Stub.DescribeAvailabilityZones describeAvailabilityZones114, + com.amazon.ec2.client.AmazonEC2Stub.DescribeAvailabilityZones describeAvailabilityZones114, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[57].getName()); _operationClient.getOptions().setAction("DescribeAvailabilityZones"); @@ -14712,9 +14712,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.CreateVpnConnectionResponse createVpnConnection( - com.amazon.ec2.client.AmazonEC2Stub.CreateVpnConnection createVpnConnection116) + com.amazon.ec2.client.AmazonEC2Stub.CreateVpnConnection createVpnConnection116) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -14814,11 +14814,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startcreateVpnConnection( - com.amazon.ec2.client.AmazonEC2Stub.CreateVpnConnection createVpnConnection116, + com.amazon.ec2.client.AmazonEC2Stub.CreateVpnConnection createVpnConnection116, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[58].getName()); _operationClient.getOptions().setAction("CreateVpnConnection"); @@ -14946,9 +14946,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.CancelBundleTaskResponse cancelBundleTask( - com.amazon.ec2.client.AmazonEC2Stub.CancelBundleTask cancelBundleTask118) + com.amazon.ec2.client.AmazonEC2Stub.CancelBundleTask cancelBundleTask118) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -15048,11 +15048,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startcancelBundleTask( - com.amazon.ec2.client.AmazonEC2Stub.CancelBundleTask cancelBundleTask118, + com.amazon.ec2.client.AmazonEC2Stub.CancelBundleTask cancelBundleTask118, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[59].getName()); _operationClient.getOptions().setAction("CancelBundleTask"); @@ -15180,9 +15180,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.ReplaceNetworkAclAssociationResponse replaceNetworkAclAssociation( - com.amazon.ec2.client.AmazonEC2Stub.ReplaceNetworkAclAssociation replaceNetworkAclAssociation120) + com.amazon.ec2.client.AmazonEC2Stub.ReplaceNetworkAclAssociation replaceNetworkAclAssociation120) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -15283,11 +15283,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startreplaceNetworkAclAssociation( - com.amazon.ec2.client.AmazonEC2Stub.ReplaceNetworkAclAssociation replaceNetworkAclAssociation120, + com.amazon.ec2.client.AmazonEC2Stub.ReplaceNetworkAclAssociation replaceNetworkAclAssociation120, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[60].getName()); _operationClient.getOptions().setAction("ReplaceNetworkAclAssociation"); @@ -15415,9 +15415,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DetachVpnGatewayResponse detachVpnGateway( - com.amazon.ec2.client.AmazonEC2Stub.DetachVpnGateway detachVpnGateway122) + com.amazon.ec2.client.AmazonEC2Stub.DetachVpnGateway detachVpnGateway122) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -15517,11 +15517,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdetachVpnGateway( - com.amazon.ec2.client.AmazonEC2Stub.DetachVpnGateway detachVpnGateway122, + com.amazon.ec2.client.AmazonEC2Stub.DetachVpnGateway detachVpnGateway122, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[61].getName()); _operationClient.getOptions().setAction("DetachVpnGateway"); @@ -15649,9 +15649,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeSnapshotsResponse describeSnapshots( - com.amazon.ec2.client.AmazonEC2Stub.DescribeSnapshots describeSnapshots124) + com.amazon.ec2.client.AmazonEC2Stub.DescribeSnapshots describeSnapshots124) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -15751,11 +15751,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeSnapshots( - com.amazon.ec2.client.AmazonEC2Stub.DescribeSnapshots describeSnapshots124, + com.amazon.ec2.client.AmazonEC2Stub.DescribeSnapshots describeSnapshots124, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[62].getName()); _operationClient.getOptions().setAction("DescribeSnapshots"); @@ -15883,9 +15883,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DeleteSubnetResponse deleteSubnet( - com.amazon.ec2.client.AmazonEC2Stub.DeleteSubnet deleteSubnet126) + com.amazon.ec2.client.AmazonEC2Stub.DeleteSubnet deleteSubnet126) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -15985,11 +15985,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdeleteSubnet( - com.amazon.ec2.client.AmazonEC2Stub.DeleteSubnet deleteSubnet126, + com.amazon.ec2.client.AmazonEC2Stub.DeleteSubnet deleteSubnet126, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[63].getName()); _operationClient.getOptions().setAction("DeleteSubnet"); @@ -16116,9 +16116,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeBundleTasksResponse describeBundleTasks( - com.amazon.ec2.client.AmazonEC2Stub.DescribeBundleTasks describeBundleTasks128) + com.amazon.ec2.client.AmazonEC2Stub.DescribeBundleTasks describeBundleTasks128) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -16218,11 +16218,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeBundleTasks( - com.amazon.ec2.client.AmazonEC2Stub.DescribeBundleTasks describeBundleTasks128, + com.amazon.ec2.client.AmazonEC2Stub.DescribeBundleTasks describeBundleTasks128, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[64].getName()); _operationClient.getOptions().setAction("DescribeBundleTasks"); @@ -16350,9 +16350,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.CreateKeyPairResponse createKeyPair( - com.amazon.ec2.client.AmazonEC2Stub.CreateKeyPair createKeyPair130) + com.amazon.ec2.client.AmazonEC2Stub.CreateKeyPair createKeyPair130) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -16452,11 +16452,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startcreateKeyPair( - com.amazon.ec2.client.AmazonEC2Stub.CreateKeyPair createKeyPair130, + com.amazon.ec2.client.AmazonEC2Stub.CreateKeyPair createKeyPair130, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[65].getName()); _operationClient.getOptions().setAction("CreateKeyPair"); @@ -16583,9 +16583,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.CreateImageResponse createImage( - com.amazon.ec2.client.AmazonEC2Stub.CreateImage createImage132) + com.amazon.ec2.client.AmazonEC2Stub.CreateImage createImage132) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -16685,11 +16685,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startcreateImage( - com.amazon.ec2.client.AmazonEC2Stub.CreateImage createImage132, + com.amazon.ec2.client.AmazonEC2Stub.CreateImage createImage132, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[66].getName()); _operationClient.getOptions().setAction("CreateImage"); @@ -16816,9 +16816,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.EnableVgwRoutePropagationResponse enableVgwRoutePropagation( - com.amazon.ec2.client.AmazonEC2Stub.EnableVgwRoutePropagation enableVgwRoutePropagation134) + com.amazon.ec2.client.AmazonEC2Stub.EnableVgwRoutePropagation enableVgwRoutePropagation134) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -16919,11 +16919,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startenableVgwRoutePropagation( - com.amazon.ec2.client.AmazonEC2Stub.EnableVgwRoutePropagation enableVgwRoutePropagation134, + com.amazon.ec2.client.AmazonEC2Stub.EnableVgwRoutePropagation enableVgwRoutePropagation134, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[67].getName()); _operationClient.getOptions().setAction("EnableVgwRoutePropagation"); @@ -17051,9 +17051,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.UnassignPrivateIpAddressesResponse unassignPrivateIpAddresses( - com.amazon.ec2.client.AmazonEC2Stub.UnassignPrivateIpAddresses unassignPrivateIpAddresses136) + com.amazon.ec2.client.AmazonEC2Stub.UnassignPrivateIpAddresses unassignPrivateIpAddresses136) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -17154,11 +17154,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startunassignPrivateIpAddresses( - com.amazon.ec2.client.AmazonEC2Stub.UnassignPrivateIpAddresses unassignPrivateIpAddresses136, + com.amazon.ec2.client.AmazonEC2Stub.UnassignPrivateIpAddresses unassignPrivateIpAddresses136, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[68].getName()); _operationClient.getOptions().setAction("UnassignPrivateIpAddresses"); @@ -17286,9 +17286,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DeregisterImageResponse deregisterImage( - com.amazon.ec2.client.AmazonEC2Stub.DeregisterImage deregisterImage138) + com.amazon.ec2.client.AmazonEC2Stub.DeregisterImage deregisterImage138) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -17388,11 +17388,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startderegisterImage( - com.amazon.ec2.client.AmazonEC2Stub.DeregisterImage deregisterImage138, + com.amazon.ec2.client.AmazonEC2Stub.DeregisterImage deregisterImage138, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[69].getName()); _operationClient.getOptions().setAction("DeregisterImage"); @@ -17519,9 +17519,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DeleteVpnConnectionRouteResponse deleteVpnConnectionRoute( - com.amazon.ec2.client.AmazonEC2Stub.DeleteVpnConnectionRoute deleteVpnConnectionRoute140) + com.amazon.ec2.client.AmazonEC2Stub.DeleteVpnConnectionRoute deleteVpnConnectionRoute140) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -17622,11 +17622,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdeleteVpnConnectionRoute( - com.amazon.ec2.client.AmazonEC2Stub.DeleteVpnConnectionRoute deleteVpnConnectionRoute140, + com.amazon.ec2.client.AmazonEC2Stub.DeleteVpnConnectionRoute deleteVpnConnectionRoute140, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[70].getName()); _operationClient.getOptions().setAction("DeleteVpnConnectionRoute"); @@ -17754,9 +17754,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.ModifyImageAttributeResponse modifyImageAttribute( - com.amazon.ec2.client.AmazonEC2Stub.ModifyImageAttribute modifyImageAttribute142) + com.amazon.ec2.client.AmazonEC2Stub.ModifyImageAttribute modifyImageAttribute142) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -17856,11 +17856,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startmodifyImageAttribute( - com.amazon.ec2.client.AmazonEC2Stub.ModifyImageAttribute modifyImageAttribute142, + com.amazon.ec2.client.AmazonEC2Stub.ModifyImageAttribute modifyImageAttribute142, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[71].getName()); _operationClient.getOptions().setAction("ModifyImageAttribute"); @@ -17988,9 +17988,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.CancelConversionTaskResponse cancelConversionTask( - com.amazon.ec2.client.AmazonEC2Stub.CancelConversionTask cancelConversionTask144) + com.amazon.ec2.client.AmazonEC2Stub.CancelConversionTask cancelConversionTask144) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -18090,11 +18090,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startcancelConversionTask( - com.amazon.ec2.client.AmazonEC2Stub.CancelConversionTask cancelConversionTask144, + com.amazon.ec2.client.AmazonEC2Stub.CancelConversionTask cancelConversionTask144, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[72].getName()); _operationClient.getOptions().setAction("CancelConversionTask"); @@ -18222,9 +18222,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeVolumesResponse describeVolumes( - com.amazon.ec2.client.AmazonEC2Stub.DescribeVolumes describeVolumes146) + com.amazon.ec2.client.AmazonEC2Stub.DescribeVolumes describeVolumes146) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -18324,11 +18324,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeVolumes( - com.amazon.ec2.client.AmazonEC2Stub.DescribeVolumes describeVolumes146, + com.amazon.ec2.client.AmazonEC2Stub.DescribeVolumes describeVolumes146, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[73].getName()); _operationClient.getOptions().setAction("DescribeVolumes"); @@ -18455,9 +18455,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.CancelReservedInstancesListingResponse cancelReservedInstancesListing( - com.amazon.ec2.client.AmazonEC2Stub.CancelReservedInstancesListing cancelReservedInstancesListing148) + com.amazon.ec2.client.AmazonEC2Stub.CancelReservedInstancesListing cancelReservedInstancesListing148) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -18558,11 +18558,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startcancelReservedInstancesListing( - com.amazon.ec2.client.AmazonEC2Stub.CancelReservedInstancesListing cancelReservedInstancesListing148, + com.amazon.ec2.client.AmazonEC2Stub.CancelReservedInstancesListing cancelReservedInstancesListing148, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[74].getName()); _operationClient.getOptions().setAction("CancelReservedInstancesListing"); @@ -18690,9 +18690,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.GetPasswordDataResponse getPasswordData( - com.amazon.ec2.client.AmazonEC2Stub.GetPasswordData getPasswordData150) + com.amazon.ec2.client.AmazonEC2Stub.GetPasswordData getPasswordData150) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -18792,11 +18792,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startgetPasswordData( - com.amazon.ec2.client.AmazonEC2Stub.GetPasswordData getPasswordData150, + com.amazon.ec2.client.AmazonEC2Stub.GetPasswordData getPasswordData150, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[75].getName()); _operationClient.getOptions().setAction("GetPasswordData"); @@ -18923,9 +18923,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.AllocateAddressResponse allocateAddress( - com.amazon.ec2.client.AmazonEC2Stub.AllocateAddress allocateAddress152) + com.amazon.ec2.client.AmazonEC2Stub.AllocateAddress allocateAddress152) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -19025,11 +19025,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startallocateAddress( - com.amazon.ec2.client.AmazonEC2Stub.AllocateAddress allocateAddress152, + com.amazon.ec2.client.AmazonEC2Stub.AllocateAddress allocateAddress152, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[76].getName()); _operationClient.getOptions().setAction("AllocateAddress"); @@ -19156,9 +19156,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DeleteSecurityGroupResponse deleteSecurityGroup( - com.amazon.ec2.client.AmazonEC2Stub.DeleteSecurityGroup deleteSecurityGroup154) + com.amazon.ec2.client.AmazonEC2Stub.DeleteSecurityGroup deleteSecurityGroup154) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -19258,11 +19258,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdeleteSecurityGroup( - com.amazon.ec2.client.AmazonEC2Stub.DeleteSecurityGroup deleteSecurityGroup154, + com.amazon.ec2.client.AmazonEC2Stub.DeleteSecurityGroup deleteSecurityGroup154, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[77].getName()); _operationClient.getOptions().setAction("DeleteSecurityGroup"); @@ -19390,9 +19390,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DeletePlacementGroupResponse deletePlacementGroup( - com.amazon.ec2.client.AmazonEC2Stub.DeletePlacementGroup deletePlacementGroup156) + com.amazon.ec2.client.AmazonEC2Stub.DeletePlacementGroup deletePlacementGroup156) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -19492,11 +19492,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdeletePlacementGroup( - com.amazon.ec2.client.AmazonEC2Stub.DeletePlacementGroup deletePlacementGroup156, + com.amazon.ec2.client.AmazonEC2Stub.DeletePlacementGroup deletePlacementGroup156, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[78].getName()); _operationClient.getOptions().setAction("DeletePlacementGroup"); @@ -19624,9 +19624,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DisassociateAddressResponse disassociateAddress( - com.amazon.ec2.client.AmazonEC2Stub.DisassociateAddress disassociateAddress158) + com.amazon.ec2.client.AmazonEC2Stub.DisassociateAddress disassociateAddress158) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -19726,11 +19726,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdisassociateAddress( - com.amazon.ec2.client.AmazonEC2Stub.DisassociateAddress disassociateAddress158, + com.amazon.ec2.client.AmazonEC2Stub.DisassociateAddress disassociateAddress158, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[79].getName()); _operationClient.getOptions().setAction("DisassociateAddress"); @@ -19858,9 +19858,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DeleteDhcpOptionsResponse deleteDhcpOptions( - com.amazon.ec2.client.AmazonEC2Stub.DeleteDhcpOptions deleteDhcpOptions160) + com.amazon.ec2.client.AmazonEC2Stub.DeleteDhcpOptions deleteDhcpOptions160) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -19960,11 +19960,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdeleteDhcpOptions( - com.amazon.ec2.client.AmazonEC2Stub.DeleteDhcpOptions deleteDhcpOptions160, + com.amazon.ec2.client.AmazonEC2Stub.DeleteDhcpOptions deleteDhcpOptions160, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[80].getName()); _operationClient.getOptions().setAction("DeleteDhcpOptions"); @@ -20092,9 +20092,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeSpotDatafeedSubscriptionResponse describeSpotDatafeedSubscription( - com.amazon.ec2.client.AmazonEC2Stub.DescribeSpotDatafeedSubscription describeSpotDatafeedSubscription162) + com.amazon.ec2.client.AmazonEC2Stub.DescribeSpotDatafeedSubscription describeSpotDatafeedSubscription162) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -20195,11 +20195,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeSpotDatafeedSubscription( - com.amazon.ec2.client.AmazonEC2Stub.DescribeSpotDatafeedSubscription describeSpotDatafeedSubscription162, + com.amazon.ec2.client.AmazonEC2Stub.DescribeSpotDatafeedSubscription describeSpotDatafeedSubscription162, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[81].getName()); _operationClient.getOptions().setAction("DescribeSpotDatafeedSubscription"); @@ -20327,9 +20327,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeNetworkAclsResponse describeNetworkAcls( - com.amazon.ec2.client.AmazonEC2Stub.DescribeNetworkAcls describeNetworkAcls164) + com.amazon.ec2.client.AmazonEC2Stub.DescribeNetworkAcls describeNetworkAcls164) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -20429,11 +20429,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeNetworkAcls( - com.amazon.ec2.client.AmazonEC2Stub.DescribeNetworkAcls describeNetworkAcls164, + com.amazon.ec2.client.AmazonEC2Stub.DescribeNetworkAcls describeNetworkAcls164, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[82].getName()); _operationClient.getOptions().setAction("DescribeNetworkAcls"); @@ -20561,9 +20561,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.EnableVolumeIOResponse enableVolumeIO( - com.amazon.ec2.client.AmazonEC2Stub.EnableVolumeIO enableVolumeIO166) + com.amazon.ec2.client.AmazonEC2Stub.EnableVolumeIO enableVolumeIO166) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -20663,11 +20663,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startenableVolumeIO( - com.amazon.ec2.client.AmazonEC2Stub.EnableVolumeIO enableVolumeIO166, + com.amazon.ec2.client.AmazonEC2Stub.EnableVolumeIO enableVolumeIO166, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[83].getName()); _operationClient.getOptions().setAction("EnableVolumeIO"); @@ -20794,9 +20794,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.AttachVpnGatewayResponse attachVpnGateway( - com.amazon.ec2.client.AmazonEC2Stub.AttachVpnGateway attachVpnGateway168) + com.amazon.ec2.client.AmazonEC2Stub.AttachVpnGateway attachVpnGateway168) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -20896,11 +20896,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startattachVpnGateway( - com.amazon.ec2.client.AmazonEC2Stub.AttachVpnGateway attachVpnGateway168, + com.amazon.ec2.client.AmazonEC2Stub.AttachVpnGateway attachVpnGateway168, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[84].getName()); _operationClient.getOptions().setAction("AttachVpnGateway"); @@ -21028,9 +21028,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeInternetGatewaysResponse describeInternetGateways( - com.amazon.ec2.client.AmazonEC2Stub.DescribeInternetGateways describeInternetGateways170) + com.amazon.ec2.client.AmazonEC2Stub.DescribeInternetGateways describeInternetGateways170) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -21131,11 +21131,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeInternetGateways( - com.amazon.ec2.client.AmazonEC2Stub.DescribeInternetGateways describeInternetGateways170, + com.amazon.ec2.client.AmazonEC2Stub.DescribeInternetGateways describeInternetGateways170, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[85].getName()); _operationClient.getOptions().setAction("DescribeInternetGateways"); @@ -21263,9 +21263,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeDhcpOptionsResponse describeDhcpOptions( - com.amazon.ec2.client.AmazonEC2Stub.DescribeDhcpOptions describeDhcpOptions172) + com.amazon.ec2.client.AmazonEC2Stub.DescribeDhcpOptions describeDhcpOptions172) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -21365,11 +21365,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeDhcpOptions( - com.amazon.ec2.client.AmazonEC2Stub.DescribeDhcpOptions describeDhcpOptions172, + com.amazon.ec2.client.AmazonEC2Stub.DescribeDhcpOptions describeDhcpOptions172, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[86].getName()); _operationClient.getOptions().setAction("DescribeDhcpOptions"); @@ -21497,9 +21497,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.CreateSpotDatafeedSubscriptionResponse createSpotDatafeedSubscription( - com.amazon.ec2.client.AmazonEC2Stub.CreateSpotDatafeedSubscription createSpotDatafeedSubscription174) + com.amazon.ec2.client.AmazonEC2Stub.CreateSpotDatafeedSubscription createSpotDatafeedSubscription174) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -21600,11 +21600,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startcreateSpotDatafeedSubscription( - com.amazon.ec2.client.AmazonEC2Stub.CreateSpotDatafeedSubscription createSpotDatafeedSubscription174, + com.amazon.ec2.client.AmazonEC2Stub.CreateSpotDatafeedSubscription createSpotDatafeedSubscription174, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[87].getName()); _operationClient.getOptions().setAction("CreateSpotDatafeedSubscription"); @@ -21732,9 +21732,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeReservedInstancesListingsResponse describeReservedInstancesListings( - com.amazon.ec2.client.AmazonEC2Stub.DescribeReservedInstancesListings describeReservedInstancesListings176) + com.amazon.ec2.client.AmazonEC2Stub.DescribeReservedInstancesListings describeReservedInstancesListings176) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -21835,11 +21835,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeReservedInstancesListings( - com.amazon.ec2.client.AmazonEC2Stub.DescribeReservedInstancesListings describeReservedInstancesListings176, + com.amazon.ec2.client.AmazonEC2Stub.DescribeReservedInstancesListings describeReservedInstancesListings176, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[88].getName()); _operationClient.getOptions().setAction("DescribeReservedInstancesListings"); @@ -21967,9 +21967,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeInstanceStatusResponse describeInstanceStatus( - com.amazon.ec2.client.AmazonEC2Stub.DescribeInstanceStatus describeInstanceStatus178) + com.amazon.ec2.client.AmazonEC2Stub.DescribeInstanceStatus describeInstanceStatus178) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -22070,11 +22070,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeInstanceStatus( - com.amazon.ec2.client.AmazonEC2Stub.DescribeInstanceStatus describeInstanceStatus178, + com.amazon.ec2.client.AmazonEC2Stub.DescribeInstanceStatus describeInstanceStatus178, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[89].getName()); _operationClient.getOptions().setAction("DescribeInstanceStatus"); @@ -22202,9 +22202,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.ModifyNetworkInterfaceAttributeResponse modifyNetworkInterfaceAttribute( - com.amazon.ec2.client.AmazonEC2Stub.ModifyNetworkInterfaceAttribute modifyNetworkInterfaceAttribute180) + com.amazon.ec2.client.AmazonEC2Stub.ModifyNetworkInterfaceAttribute modifyNetworkInterfaceAttribute180) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -22305,11 +22305,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startmodifyNetworkInterfaceAttribute( - com.amazon.ec2.client.AmazonEC2Stub.ModifyNetworkInterfaceAttribute modifyNetworkInterfaceAttribute180, + com.amazon.ec2.client.AmazonEC2Stub.ModifyNetworkInterfaceAttribute modifyNetworkInterfaceAttribute180, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[90].getName()); _operationClient.getOptions().setAction("ModifyNetworkInterfaceAttribute"); @@ -22437,9 +22437,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DisableVgwRoutePropagationResponse disableVgwRoutePropagation( - com.amazon.ec2.client.AmazonEC2Stub.DisableVgwRoutePropagation disableVgwRoutePropagation182) + com.amazon.ec2.client.AmazonEC2Stub.DisableVgwRoutePropagation disableVgwRoutePropagation182) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -22540,11 +22540,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdisableVgwRoutePropagation( - com.amazon.ec2.client.AmazonEC2Stub.DisableVgwRoutePropagation disableVgwRoutePropagation182, + com.amazon.ec2.client.AmazonEC2Stub.DisableVgwRoutePropagation disableVgwRoutePropagation182, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[91].getName()); _operationClient.getOptions().setAction("DisableVgwRoutePropagation"); @@ -22672,9 +22672,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeVolumeStatusResponse describeVolumeStatus( - com.amazon.ec2.client.AmazonEC2Stub.DescribeVolumeStatus describeVolumeStatus184) + com.amazon.ec2.client.AmazonEC2Stub.DescribeVolumeStatus describeVolumeStatus184) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -22774,11 +22774,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeVolumeStatus( - com.amazon.ec2.client.AmazonEC2Stub.DescribeVolumeStatus describeVolumeStatus184, + com.amazon.ec2.client.AmazonEC2Stub.DescribeVolumeStatus describeVolumeStatus184, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[92].getName()); _operationClient.getOptions().setAction("DescribeVolumeStatus"); @@ -22906,9 +22906,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DetachNetworkInterfaceResponse detachNetworkInterface( - com.amazon.ec2.client.AmazonEC2Stub.DetachNetworkInterface detachNetworkInterface186) + com.amazon.ec2.client.AmazonEC2Stub.DetachNetworkInterface detachNetworkInterface186) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -23009,11 +23009,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdetachNetworkInterface( - com.amazon.ec2.client.AmazonEC2Stub.DetachNetworkInterface detachNetworkInterface186, + com.amazon.ec2.client.AmazonEC2Stub.DetachNetworkInterface detachNetworkInterface186, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[93].getName()); _operationClient.getOptions().setAction("DetachNetworkInterface"); @@ -23141,9 +23141,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeSecurityGroupsResponse describeSecurityGroups( - com.amazon.ec2.client.AmazonEC2Stub.DescribeSecurityGroups describeSecurityGroups188) + com.amazon.ec2.client.AmazonEC2Stub.DescribeSecurityGroups describeSecurityGroups188) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -23244,11 +23244,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeSecurityGroups( - com.amazon.ec2.client.AmazonEC2Stub.DescribeSecurityGroups describeSecurityGroups188, + com.amazon.ec2.client.AmazonEC2Stub.DescribeSecurityGroups describeSecurityGroups188, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[94].getName()); _operationClient.getOptions().setAction("DescribeSecurityGroups"); @@ -23376,9 +23376,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeInstancesResponse describeInstances( - com.amazon.ec2.client.AmazonEC2Stub.DescribeInstances describeInstances190) + com.amazon.ec2.client.AmazonEC2Stub.DescribeInstances describeInstances190) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -23478,11 +23478,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeInstances( - com.amazon.ec2.client.AmazonEC2Stub.DescribeInstances describeInstances190, + com.amazon.ec2.client.AmazonEC2Stub.DescribeInstances describeInstances190, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[95].getName()); _operationClient.getOptions().setAction("DescribeInstances"); @@ -23610,9 +23610,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeNetworkInterfacesResponse describeNetworkInterfaces( - com.amazon.ec2.client.AmazonEC2Stub.DescribeNetworkInterfaces describeNetworkInterfaces192) + com.amazon.ec2.client.AmazonEC2Stub.DescribeNetworkInterfaces describeNetworkInterfaces192) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -23713,11 +23713,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeNetworkInterfaces( - com.amazon.ec2.client.AmazonEC2Stub.DescribeNetworkInterfaces describeNetworkInterfaces192, + com.amazon.ec2.client.AmazonEC2Stub.DescribeNetworkInterfaces describeNetworkInterfaces192, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[96].getName()); _operationClient.getOptions().setAction("DescribeNetworkInterfaces"); @@ -23845,9 +23845,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DeleteKeyPairResponse deleteKeyPair( - com.amazon.ec2.client.AmazonEC2Stub.DeleteKeyPair deleteKeyPair194) + com.amazon.ec2.client.AmazonEC2Stub.DeleteKeyPair deleteKeyPair194) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -23947,11 +23947,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdeleteKeyPair( - com.amazon.ec2.client.AmazonEC2Stub.DeleteKeyPair deleteKeyPair194, + com.amazon.ec2.client.AmazonEC2Stub.DeleteKeyPair deleteKeyPair194, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[97].getName()); _operationClient.getOptions().setAction("DeleteKeyPair"); @@ -24078,9 +24078,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.CreateSnapshotResponse createSnapshot( - com.amazon.ec2.client.AmazonEC2Stub.CreateSnapshot createSnapshot196) + com.amazon.ec2.client.AmazonEC2Stub.CreateSnapshot createSnapshot196) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -24180,11 +24180,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startcreateSnapshot( - com.amazon.ec2.client.AmazonEC2Stub.CreateSnapshot createSnapshot196, + com.amazon.ec2.client.AmazonEC2Stub.CreateSnapshot createSnapshot196, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[98].getName()); _operationClient.getOptions().setAction("CreateSnapshot"); @@ -24311,9 +24311,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeVpnGatewaysResponse describeVpnGateways( - com.amazon.ec2.client.AmazonEC2Stub.DescribeVpnGateways describeVpnGateways198) + com.amazon.ec2.client.AmazonEC2Stub.DescribeVpnGateways describeVpnGateways198) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -24413,11 +24413,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeVpnGateways( - com.amazon.ec2.client.AmazonEC2Stub.DescribeVpnGateways describeVpnGateways198, + com.amazon.ec2.client.AmazonEC2Stub.DescribeVpnGateways describeVpnGateways198, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[99].getName()); _operationClient.getOptions().setAction("DescribeVpnGateways"); @@ -24545,9 +24545,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DeleteTagsResponse deleteTags( - com.amazon.ec2.client.AmazonEC2Stub.DeleteTags deleteTags200) + com.amazon.ec2.client.AmazonEC2Stub.DeleteTags deleteTags200) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -24647,11 +24647,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdeleteTags( - com.amazon.ec2.client.AmazonEC2Stub.DeleteTags deleteTags200, + com.amazon.ec2.client.AmazonEC2Stub.DeleteTags deleteTags200, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[100].getName()); _operationClient.getOptions().setAction("DeleteTags"); @@ -24778,9 +24778,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DeleteSnapshotResponse deleteSnapshot( - com.amazon.ec2.client.AmazonEC2Stub.DeleteSnapshot deleteSnapshot202) + com.amazon.ec2.client.AmazonEC2Stub.DeleteSnapshot deleteSnapshot202) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -24880,11 +24880,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdeleteSnapshot( - com.amazon.ec2.client.AmazonEC2Stub.DeleteSnapshot deleteSnapshot202, + com.amazon.ec2.client.AmazonEC2Stub.DeleteSnapshot deleteSnapshot202, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[101].getName()); _operationClient.getOptions().setAction("DeleteSnapshot"); @@ -25011,9 +25011,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DeleteCustomerGatewayResponse deleteCustomerGateway( - com.amazon.ec2.client.AmazonEC2Stub.DeleteCustomerGateway deleteCustomerGateway204) + com.amazon.ec2.client.AmazonEC2Stub.DeleteCustomerGateway deleteCustomerGateway204) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -25113,11 +25113,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdeleteCustomerGateway( - com.amazon.ec2.client.AmazonEC2Stub.DeleteCustomerGateway deleteCustomerGateway204, + com.amazon.ec2.client.AmazonEC2Stub.DeleteCustomerGateway deleteCustomerGateway204, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[102].getName()); _operationClient.getOptions().setAction("DeleteCustomerGateway"); @@ -25245,9 +25245,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.CreateVolumeResponse createVolume( - com.amazon.ec2.client.AmazonEC2Stub.CreateVolume createVolume206) + com.amazon.ec2.client.AmazonEC2Stub.CreateVolume createVolume206) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -25347,11 +25347,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startcreateVolume( - com.amazon.ec2.client.AmazonEC2Stub.CreateVolume createVolume206, + com.amazon.ec2.client.AmazonEC2Stub.CreateVolume createVolume206, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[103].getName()); _operationClient.getOptions().setAction("CreateVolume"); @@ -25478,9 +25478,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.CancelExportTaskResponse cancelExportTask( - com.amazon.ec2.client.AmazonEC2Stub.CancelExportTask cancelExportTask208) + com.amazon.ec2.client.AmazonEC2Stub.CancelExportTask cancelExportTask208) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -25580,11 +25580,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startcancelExportTask( - com.amazon.ec2.client.AmazonEC2Stub.CancelExportTask cancelExportTask208, + com.amazon.ec2.client.AmazonEC2Stub.CancelExportTask cancelExportTask208, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[104].getName()); _operationClient.getOptions().setAction("CancelExportTask"); @@ -25712,9 +25712,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.RegisterImageResponse registerImage( - com.amazon.ec2.client.AmazonEC2Stub.RegisterImage registerImage210) + com.amazon.ec2.client.AmazonEC2Stub.RegisterImage registerImage210) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -25814,11 +25814,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startregisterImage( - com.amazon.ec2.client.AmazonEC2Stub.RegisterImage registerImage210, + com.amazon.ec2.client.AmazonEC2Stub.RegisterImage registerImage210, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[105].getName()); _operationClient.getOptions().setAction("RegisterImage"); @@ -25945,9 +25945,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DetachVolumeResponse detachVolume( - com.amazon.ec2.client.AmazonEC2Stub.DetachVolume detachVolume212) + com.amazon.ec2.client.AmazonEC2Stub.DetachVolume detachVolume212) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -26047,11 +26047,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdetachVolume( - com.amazon.ec2.client.AmazonEC2Stub.DetachVolume detachVolume212, + com.amazon.ec2.client.AmazonEC2Stub.DetachVolume detachVolume212, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[106].getName()); _operationClient.getOptions().setAction("DetachVolume"); @@ -26178,9 +26178,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.StopInstancesResponse stopInstances( - com.amazon.ec2.client.AmazonEC2Stub.StopInstances stopInstances214) + com.amazon.ec2.client.AmazonEC2Stub.StopInstances stopInstances214) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -26280,11 +26280,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startstopInstances( - com.amazon.ec2.client.AmazonEC2Stub.StopInstances stopInstances214, + com.amazon.ec2.client.AmazonEC2Stub.StopInstances stopInstances214, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[107].getName()); _operationClient.getOptions().setAction("StopInstances"); @@ -26411,9 +26411,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.CreateRouteResponse createRoute( - com.amazon.ec2.client.AmazonEC2Stub.CreateRoute createRoute216) + com.amazon.ec2.client.AmazonEC2Stub.CreateRoute createRoute216) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -26513,11 +26513,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startcreateRoute( - com.amazon.ec2.client.AmazonEC2Stub.CreateRoute createRoute216, + com.amazon.ec2.client.AmazonEC2Stub.CreateRoute createRoute216, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[108].getName()); _operationClient.getOptions().setAction("CreateRoute"); @@ -26644,9 +26644,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.ReleaseAddressResponse releaseAddress( - com.amazon.ec2.client.AmazonEC2Stub.ReleaseAddress releaseAddress218) + com.amazon.ec2.client.AmazonEC2Stub.ReleaseAddress releaseAddress218) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -26746,11 +26746,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startreleaseAddress( - com.amazon.ec2.client.AmazonEC2Stub.ReleaseAddress releaseAddress218, + com.amazon.ec2.client.AmazonEC2Stub.ReleaseAddress releaseAddress218, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[109].getName()); _operationClient.getOptions().setAction("ReleaseAddress"); @@ -26877,9 +26877,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeRouteTablesResponse describeRouteTables( - com.amazon.ec2.client.AmazonEC2Stub.DescribeRouteTables describeRouteTables220) + com.amazon.ec2.client.AmazonEC2Stub.DescribeRouteTables describeRouteTables220) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -26979,11 +26979,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeRouteTables( - com.amazon.ec2.client.AmazonEC2Stub.DescribeRouteTables describeRouteTables220, + com.amazon.ec2.client.AmazonEC2Stub.DescribeRouteTables describeRouteTables220, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[110].getName()); _operationClient.getOptions().setAction("DescribeRouteTables"); @@ -27111,9 +27111,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeCustomerGatewaysResponse describeCustomerGateways( - com.amazon.ec2.client.AmazonEC2Stub.DescribeCustomerGateways describeCustomerGateways222) + com.amazon.ec2.client.AmazonEC2Stub.DescribeCustomerGateways describeCustomerGateways222) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -27214,11 +27214,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeCustomerGateways( - com.amazon.ec2.client.AmazonEC2Stub.DescribeCustomerGateways describeCustomerGateways222, + com.amazon.ec2.client.AmazonEC2Stub.DescribeCustomerGateways describeCustomerGateways222, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[111].getName()); _operationClient.getOptions().setAction("DescribeCustomerGateways"); @@ -27346,9 +27346,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DeleteNetworkAclResponse deleteNetworkAcl( - com.amazon.ec2.client.AmazonEC2Stub.DeleteNetworkAcl deleteNetworkAcl224) + com.amazon.ec2.client.AmazonEC2Stub.DeleteNetworkAcl deleteNetworkAcl224) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -27448,11 +27448,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdeleteNetworkAcl( - com.amazon.ec2.client.AmazonEC2Stub.DeleteNetworkAcl deleteNetworkAcl224, + com.amazon.ec2.client.AmazonEC2Stub.DeleteNetworkAcl deleteNetworkAcl224, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[112].getName()); _operationClient.getOptions().setAction("DeleteNetworkAcl"); @@ -27580,9 +27580,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DeleteRouteResponse deleteRoute( - com.amazon.ec2.client.AmazonEC2Stub.DeleteRoute deleteRoute226) + com.amazon.ec2.client.AmazonEC2Stub.DeleteRoute deleteRoute226) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -27682,11 +27682,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdeleteRoute( - com.amazon.ec2.client.AmazonEC2Stub.DeleteRoute deleteRoute226, + com.amazon.ec2.client.AmazonEC2Stub.DeleteRoute deleteRoute226, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[113].getName()); _operationClient.getOptions().setAction("DeleteRoute"); @@ -27813,9 +27813,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.RebootInstancesResponse rebootInstances( - com.amazon.ec2.client.AmazonEC2Stub.RebootInstances rebootInstances228) + com.amazon.ec2.client.AmazonEC2Stub.RebootInstances rebootInstances228) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -27915,11 +27915,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startrebootInstances( - com.amazon.ec2.client.AmazonEC2Stub.RebootInstances rebootInstances228, + com.amazon.ec2.client.AmazonEC2Stub.RebootInstances rebootInstances228, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[114].getName()); _operationClient.getOptions().setAction("RebootInstances"); @@ -28046,9 +28046,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.ModifyInstanceAttributeResponse modifyInstanceAttribute( - com.amazon.ec2.client.AmazonEC2Stub.ModifyInstanceAttribute modifyInstanceAttribute230) + com.amazon.ec2.client.AmazonEC2Stub.ModifyInstanceAttribute modifyInstanceAttribute230) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -28149,11 +28149,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startmodifyInstanceAttribute( - com.amazon.ec2.client.AmazonEC2Stub.ModifyInstanceAttribute modifyInstanceAttribute230, + com.amazon.ec2.client.AmazonEC2Stub.ModifyInstanceAttribute modifyInstanceAttribute230, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[115].getName()); _operationClient.getOptions().setAction("ModifyInstanceAttribute"); @@ -28281,9 +28281,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.TerminateInstancesResponse terminateInstances( - com.amazon.ec2.client.AmazonEC2Stub.TerminateInstances terminateInstances232) + com.amazon.ec2.client.AmazonEC2Stub.TerminateInstances terminateInstances232) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -28383,11 +28383,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startterminateInstances( - com.amazon.ec2.client.AmazonEC2Stub.TerminateInstances terminateInstances232, + com.amazon.ec2.client.AmazonEC2Stub.TerminateInstances terminateInstances232, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[116].getName()); _operationClient.getOptions().setAction("TerminateInstances"); @@ -28515,9 +28515,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.CreateVpnConnectionRouteResponse createVpnConnectionRoute( - com.amazon.ec2.client.AmazonEC2Stub.CreateVpnConnectionRoute createVpnConnectionRoute234) + com.amazon.ec2.client.AmazonEC2Stub.CreateVpnConnectionRoute createVpnConnectionRoute234) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -28618,11 +28618,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startcreateVpnConnectionRoute( - com.amazon.ec2.client.AmazonEC2Stub.CreateVpnConnectionRoute createVpnConnectionRoute234, + com.amazon.ec2.client.AmazonEC2Stub.CreateVpnConnectionRoute createVpnConnectionRoute234, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[117].getName()); _operationClient.getOptions().setAction("CreateVpnConnectionRoute"); @@ -28750,9 +28750,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeConversionTasksResponse describeConversionTasks( - com.amazon.ec2.client.AmazonEC2Stub.DescribeConversionTasks describeConversionTasks236) + com.amazon.ec2.client.AmazonEC2Stub.DescribeConversionTasks describeConversionTasks236) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -28853,11 +28853,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeConversionTasks( - com.amazon.ec2.client.AmazonEC2Stub.DescribeConversionTasks describeConversionTasks236, + com.amazon.ec2.client.AmazonEC2Stub.DescribeConversionTasks describeConversionTasks236, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[118].getName()); _operationClient.getOptions().setAction("DescribeConversionTasks"); @@ -28985,9 +28985,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeAddressesResponse describeAddresses( - com.amazon.ec2.client.AmazonEC2Stub.DescribeAddresses describeAddresses238) + com.amazon.ec2.client.AmazonEC2Stub.DescribeAddresses describeAddresses238) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -29087,11 +29087,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeAddresses( - com.amazon.ec2.client.AmazonEC2Stub.DescribeAddresses describeAddresses238, + com.amazon.ec2.client.AmazonEC2Stub.DescribeAddresses describeAddresses238, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[119].getName()); _operationClient.getOptions().setAction("DescribeAddresses"); @@ -29219,9 +29219,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeInstanceAttributeResponse describeInstanceAttribute( - com.amazon.ec2.client.AmazonEC2Stub.DescribeInstanceAttribute describeInstanceAttribute240) + com.amazon.ec2.client.AmazonEC2Stub.DescribeInstanceAttribute describeInstanceAttribute240) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -29322,11 +29322,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeInstanceAttribute( - com.amazon.ec2.client.AmazonEC2Stub.DescribeInstanceAttribute describeInstanceAttribute240, + com.amazon.ec2.client.AmazonEC2Stub.DescribeInstanceAttribute describeInstanceAttribute240, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[120].getName()); _operationClient.getOptions().setAction("DescribeInstanceAttribute"); @@ -29454,9 +29454,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.AttachInternetGatewayResponse attachInternetGateway( - com.amazon.ec2.client.AmazonEC2Stub.AttachInternetGateway attachInternetGateway242) + com.amazon.ec2.client.AmazonEC2Stub.AttachInternetGateway attachInternetGateway242) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -29556,11 +29556,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startattachInternetGateway( - com.amazon.ec2.client.AmazonEC2Stub.AttachInternetGateway attachInternetGateway242, + com.amazon.ec2.client.AmazonEC2Stub.AttachInternetGateway attachInternetGateway242, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[121].getName()); _operationClient.getOptions().setAction("AttachInternetGateway"); @@ -29688,9 +29688,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.CreateVpcResponse createVpc( - com.amazon.ec2.client.AmazonEC2Stub.CreateVpc createVpc244) + com.amazon.ec2.client.AmazonEC2Stub.CreateVpc createVpc244) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -29790,11 +29790,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startcreateVpc( - com.amazon.ec2.client.AmazonEC2Stub.CreateVpc createVpc244, + com.amazon.ec2.client.AmazonEC2Stub.CreateVpc createVpc244, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[122].getName()); _operationClient.getOptions().setAction("CreateVpc"); @@ -29921,9 +29921,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.ReplaceRouteTableAssociationResponse replaceRouteTableAssociation( - com.amazon.ec2.client.AmazonEC2Stub.ReplaceRouteTableAssociation replaceRouteTableAssociation246) + com.amazon.ec2.client.AmazonEC2Stub.ReplaceRouteTableAssociation replaceRouteTableAssociation246) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -30024,11 +30024,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startreplaceRouteTableAssociation( - com.amazon.ec2.client.AmazonEC2Stub.ReplaceRouteTableAssociation replaceRouteTableAssociation246, + com.amazon.ec2.client.AmazonEC2Stub.ReplaceRouteTableAssociation replaceRouteTableAssociation246, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[123].getName()); _operationClient.getOptions().setAction("ReplaceRouteTableAssociation"); @@ -30156,9 +30156,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.AssociateRouteTableResponse associateRouteTable( - com.amazon.ec2.client.AmazonEC2Stub.AssociateRouteTable associateRouteTable248) + com.amazon.ec2.client.AmazonEC2Stub.AssociateRouteTable associateRouteTable248) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -30258,11 +30258,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startassociateRouteTable( - com.amazon.ec2.client.AmazonEC2Stub.AssociateRouteTable associateRouteTable248, + com.amazon.ec2.client.AmazonEC2Stub.AssociateRouteTable associateRouteTable248, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[124].getName()); _operationClient.getOptions().setAction("AssociateRouteTable"); @@ -30390,9 +30390,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DetachInternetGatewayResponse detachInternetGateway( - com.amazon.ec2.client.AmazonEC2Stub.DetachInternetGateway detachInternetGateway250) + com.amazon.ec2.client.AmazonEC2Stub.DetachInternetGateway detachInternetGateway250) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -30492,11 +30492,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdetachInternetGateway( - com.amazon.ec2.client.AmazonEC2Stub.DetachInternetGateway detachInternetGateway250, + com.amazon.ec2.client.AmazonEC2Stub.DetachInternetGateway detachInternetGateway250, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[125].getName()); _operationClient.getOptions().setAction("DetachInternetGateway"); @@ -30624,9 +30624,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.PurchaseReservedInstancesOfferingResponse purchaseReservedInstancesOffering( - com.amazon.ec2.client.AmazonEC2Stub.PurchaseReservedInstancesOffering purchaseReservedInstancesOffering252) + com.amazon.ec2.client.AmazonEC2Stub.PurchaseReservedInstancesOffering purchaseReservedInstancesOffering252) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -30727,11 +30727,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startpurchaseReservedInstancesOffering( - com.amazon.ec2.client.AmazonEC2Stub.PurchaseReservedInstancesOffering purchaseReservedInstancesOffering252, + com.amazon.ec2.client.AmazonEC2Stub.PurchaseReservedInstancesOffering purchaseReservedInstancesOffering252, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[126].getName()); _operationClient.getOptions().setAction("PurchaseReservedInstancesOffering"); @@ -30859,9 +30859,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.ImportVolumeResponse importVolume( - com.amazon.ec2.client.AmazonEC2Stub.ImportVolume importVolume254) + com.amazon.ec2.client.AmazonEC2Stub.ImportVolume importVolume254) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -30961,11 +30961,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startimportVolume( - com.amazon.ec2.client.AmazonEC2Stub.ImportVolume importVolume254, + com.amazon.ec2.client.AmazonEC2Stub.ImportVolume importVolume254, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[127].getName()); _operationClient.getOptions().setAction("ImportVolume"); @@ -31092,9 +31092,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeExportTasksResponse describeExportTasks( - com.amazon.ec2.client.AmazonEC2Stub.DescribeExportTasks describeExportTasks256) + com.amazon.ec2.client.AmazonEC2Stub.DescribeExportTasks describeExportTasks256) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -31194,11 +31194,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeExportTasks( - com.amazon.ec2.client.AmazonEC2Stub.DescribeExportTasks describeExportTasks256, + com.amazon.ec2.client.AmazonEC2Stub.DescribeExportTasks describeExportTasks256, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[128].getName()); _operationClient.getOptions().setAction("DescribeExportTasks"); @@ -31326,9 +31326,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.CreateInstanceExportTaskResponse createInstanceExportTask( - com.amazon.ec2.client.AmazonEC2Stub.CreateInstanceExportTask createInstanceExportTask258) + com.amazon.ec2.client.AmazonEC2Stub.CreateInstanceExportTask createInstanceExportTask258) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -31429,11 +31429,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startcreateInstanceExportTask( - com.amazon.ec2.client.AmazonEC2Stub.CreateInstanceExportTask createInstanceExportTask258, + com.amazon.ec2.client.AmazonEC2Stub.CreateInstanceExportTask createInstanceExportTask258, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[129].getName()); _operationClient.getOptions().setAction("CreateInstanceExportTask"); @@ -31561,9 +31561,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.AssignPrivateIpAddressesResponse assignPrivateIpAddresses( - com.amazon.ec2.client.AmazonEC2Stub.AssignPrivateIpAddresses assignPrivateIpAddresses260) + com.amazon.ec2.client.AmazonEC2Stub.AssignPrivateIpAddresses assignPrivateIpAddresses260) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -31664,11 +31664,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startassignPrivateIpAddresses( - com.amazon.ec2.client.AmazonEC2Stub.AssignPrivateIpAddresses assignPrivateIpAddresses260, + com.amazon.ec2.client.AmazonEC2Stub.AssignPrivateIpAddresses assignPrivateIpAddresses260, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[130].getName()); _operationClient.getOptions().setAction("AssignPrivateIpAddresses"); @@ -31796,9 +31796,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.ReportInstanceStatusResponse reportInstanceStatus( - com.amazon.ec2.client.AmazonEC2Stub.ReportInstanceStatus reportInstanceStatus262) + com.amazon.ec2.client.AmazonEC2Stub.ReportInstanceStatus reportInstanceStatus262) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -31898,11 +31898,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startreportInstanceStatus( - com.amazon.ec2.client.AmazonEC2Stub.ReportInstanceStatus reportInstanceStatus262, + com.amazon.ec2.client.AmazonEC2Stub.ReportInstanceStatus reportInstanceStatus262, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[131].getName()); _operationClient.getOptions().setAction("ReportInstanceStatus"); @@ -32030,9 +32030,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeReservedInstancesOfferingsResponse describeReservedInstancesOfferings( - com.amazon.ec2.client.AmazonEC2Stub.DescribeReservedInstancesOfferings describeReservedInstancesOfferings264) + com.amazon.ec2.client.AmazonEC2Stub.DescribeReservedInstancesOfferings describeReservedInstancesOfferings264) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -32133,11 +32133,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeReservedInstancesOfferings( - com.amazon.ec2.client.AmazonEC2Stub.DescribeReservedInstancesOfferings describeReservedInstancesOfferings264, + com.amazon.ec2.client.AmazonEC2Stub.DescribeReservedInstancesOfferings describeReservedInstancesOfferings264, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[132].getName()); _operationClient.getOptions().setAction("DescribeReservedInstancesOfferings"); @@ -32265,9 +32265,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DeleteVpnConnectionResponse deleteVpnConnection( - com.amazon.ec2.client.AmazonEC2Stub.DeleteVpnConnection deleteVpnConnection266) + com.amazon.ec2.client.AmazonEC2Stub.DeleteVpnConnection deleteVpnConnection266) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -32367,11 +32367,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdeleteVpnConnection( - com.amazon.ec2.client.AmazonEC2Stub.DeleteVpnConnection deleteVpnConnection266, + com.amazon.ec2.client.AmazonEC2Stub.DeleteVpnConnection deleteVpnConnection266, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[133].getName()); _operationClient.getOptions().setAction("DeleteVpnConnection"); @@ -32499,9 +32499,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DeleteInternetGatewayResponse deleteInternetGateway( - com.amazon.ec2.client.AmazonEC2Stub.DeleteInternetGateway deleteInternetGateway268) + com.amazon.ec2.client.AmazonEC2Stub.DeleteInternetGateway deleteInternetGateway268) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -32601,11 +32601,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdeleteInternetGateway( - com.amazon.ec2.client.AmazonEC2Stub.DeleteInternetGateway deleteInternetGateway268, + com.amazon.ec2.client.AmazonEC2Stub.DeleteInternetGateway deleteInternetGateway268, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[134].getName()); _operationClient.getOptions().setAction("DeleteInternetGateway"); @@ -32733,9 +32733,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DeleteSpotDatafeedSubscriptionResponse deleteSpotDatafeedSubscription( - com.amazon.ec2.client.AmazonEC2Stub.DeleteSpotDatafeedSubscription deleteSpotDatafeedSubscription270) + com.amazon.ec2.client.AmazonEC2Stub.DeleteSpotDatafeedSubscription deleteSpotDatafeedSubscription270) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -32836,11 +32836,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdeleteSpotDatafeedSubscription( - com.amazon.ec2.client.AmazonEC2Stub.DeleteSpotDatafeedSubscription deleteSpotDatafeedSubscription270, + com.amazon.ec2.client.AmazonEC2Stub.DeleteSpotDatafeedSubscription deleteSpotDatafeedSubscription270, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[135].getName()); _operationClient.getOptions().setAction("DeleteSpotDatafeedSubscription"); @@ -32968,9 +32968,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.AttachNetworkInterfaceResponse attachNetworkInterface( - com.amazon.ec2.client.AmazonEC2Stub.AttachNetworkInterface attachNetworkInterface272) + com.amazon.ec2.client.AmazonEC2Stub.AttachNetworkInterface attachNetworkInterface272) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -33071,11 +33071,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startattachNetworkInterface( - com.amazon.ec2.client.AmazonEC2Stub.AttachNetworkInterface attachNetworkInterface272, + com.amazon.ec2.client.AmazonEC2Stub.AttachNetworkInterface attachNetworkInterface272, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[136].getName()); _operationClient.getOptions().setAction("AttachNetworkInterface"); @@ -33203,9 +33203,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.CreateNetworkInterfaceResponse createNetworkInterface( - com.amazon.ec2.client.AmazonEC2Stub.CreateNetworkInterface createNetworkInterface274) + com.amazon.ec2.client.AmazonEC2Stub.CreateNetworkInterface createNetworkInterface274) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -33306,11 +33306,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startcreateNetworkInterface( - com.amazon.ec2.client.AmazonEC2Stub.CreateNetworkInterface createNetworkInterface274, + com.amazon.ec2.client.AmazonEC2Stub.CreateNetworkInterface createNetworkInterface274, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[137].getName()); _operationClient.getOptions().setAction("CreateNetworkInterface"); @@ -33438,9 +33438,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.RevokeSecurityGroupEgressResponse revokeSecurityGroupEgress( - com.amazon.ec2.client.AmazonEC2Stub.RevokeSecurityGroupEgress revokeSecurityGroupEgress276) + com.amazon.ec2.client.AmazonEC2Stub.RevokeSecurityGroupEgress revokeSecurityGroupEgress276) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -33541,11 +33541,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startrevokeSecurityGroupEgress( - com.amazon.ec2.client.AmazonEC2Stub.RevokeSecurityGroupEgress revokeSecurityGroupEgress276, + com.amazon.ec2.client.AmazonEC2Stub.RevokeSecurityGroupEgress revokeSecurityGroupEgress276, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[138].getName()); _operationClient.getOptions().setAction("RevokeSecurityGroupEgress"); @@ -33673,9 +33673,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.MonitorInstancesResponse monitorInstances( - com.amazon.ec2.client.AmazonEC2Stub.MonitorInstances monitorInstances278) + com.amazon.ec2.client.AmazonEC2Stub.MonitorInstances monitorInstances278) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -33775,11 +33775,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startmonitorInstances( - com.amazon.ec2.client.AmazonEC2Stub.MonitorInstances monitorInstances278, + com.amazon.ec2.client.AmazonEC2Stub.MonitorInstances monitorInstances278, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[139].getName()); _operationClient.getOptions().setAction("MonitorInstances"); @@ -33907,9 +33907,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.ReplaceRouteResponse replaceRoute( - com.amazon.ec2.client.AmazonEC2Stub.ReplaceRoute replaceRoute280) + com.amazon.ec2.client.AmazonEC2Stub.ReplaceRoute replaceRoute280) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -34009,11 +34009,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startreplaceRoute( - com.amazon.ec2.client.AmazonEC2Stub.ReplaceRoute replaceRoute280, + com.amazon.ec2.client.AmazonEC2Stub.ReplaceRoute replaceRoute280, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[140].getName()); _operationClient.getOptions().setAction("ReplaceRoute"); @@ -34140,9 +34140,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.AttachVolumeResponse attachVolume( - com.amazon.ec2.client.AmazonEC2Stub.AttachVolume attachVolume282) + com.amazon.ec2.client.AmazonEC2Stub.AttachVolume attachVolume282) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -34242,11 +34242,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startattachVolume( - com.amazon.ec2.client.AmazonEC2Stub.AttachVolume attachVolume282, + com.amazon.ec2.client.AmazonEC2Stub.AttachVolume attachVolume282, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[141].getName()); _operationClient.getOptions().setAction("AttachVolume"); @@ -34373,9 +34373,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.GetConsoleOutputResponse getConsoleOutput( - com.amazon.ec2.client.AmazonEC2Stub.GetConsoleOutput getConsoleOutput284) + com.amazon.ec2.client.AmazonEC2Stub.GetConsoleOutput getConsoleOutput284) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -34475,11 +34475,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startgetConsoleOutput( - com.amazon.ec2.client.AmazonEC2Stub.GetConsoleOutput getConsoleOutput284, + com.amazon.ec2.client.AmazonEC2Stub.GetConsoleOutput getConsoleOutput284, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[142].getName()); _operationClient.getOptions().setAction("GetConsoleOutput"); @@ -34607,9 +34607,9 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { public com.amazon.ec2.client.AmazonEC2Stub.DescribeRegionsResponse describeRegions( - com.amazon.ec2.client.AmazonEC2Stub.DescribeRegions describeRegions286) + com.amazon.ec2.client.AmazonEC2Stub.DescribeRegions describeRegions286) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -34709,11 +34709,11 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { */ public void startdescribeRegions( - com.amazon.ec2.client.AmazonEC2Stub.DescribeRegions describeRegions286, + com.amazon.ec2.client.AmazonEC2Stub.DescribeRegions describeRegions286, - final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) + final com.amazon.ec2.client.AmazonEC2CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[143].getName()); _operationClient.getOptions().setAction("DescribeRegions"); @@ -207841,7 +207841,7 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { // handle attribute "version" java.lang.String tempAttribVersion = - reader.getAttributeValue(null, "version"); + reader.getAttributeValue(null, "version"); if (tempAttribVersion != null) { java.lang.String content = tempAttribVersion; @@ -207858,7 +207858,7 @@ public class AmazonEC2Stub extends org.apache.axis2.client.Stub { // handle attribute "encoding" java.lang.String tempAttribEncoding = - reader.getAttributeValue(null, "encoding"); + reader.getAttributeValue(null, "encoding"); if (tempAttribEncoding != null) { java.lang.String content = tempAttribEncoding; diff --git a/awsapi/src/com/amazon/s3/AmazonS3MessageReceiverInOut.java b/awsapi/src/com/amazon/s3/AmazonS3MessageReceiverInOut.java index 0e8c332e142..4b9c0a4f4ff 100644 --- a/awsapi/src/com/amazon/s3/AmazonS3MessageReceiverInOut.java +++ b/awsapi/src/com/amazon/s3/AmazonS3MessageReceiverInOut.java @@ -59,7 +59,7 @@ public class AmazonS3MessageReceiverInOut extends org.apache.axis2.receivers.Abs getBucketLoggingStatusResponse33 = - skel.getBucketLoggingStatus(wrappedParam); + skel.getBucketLoggingStatus(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), getBucketLoggingStatusResponse33, false); } else @@ -73,7 +73,7 @@ public class AmazonS3MessageReceiverInOut extends org.apache.axis2.receivers.Abs copyObjectResponse35 = - skel.copyObject(wrappedParam); + skel.copyObject(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), copyObjectResponse35, false); } else @@ -87,7 +87,7 @@ public class AmazonS3MessageReceiverInOut extends org.apache.axis2.receivers.Abs getBucketAccessControlPolicyResponse37 = - skel.getBucketAccessControlPolicy(wrappedParam); + skel.getBucketAccessControlPolicy(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), getBucketAccessControlPolicyResponse37, false); } else @@ -101,7 +101,7 @@ public class AmazonS3MessageReceiverInOut extends org.apache.axis2.receivers.Abs listBucketResponse39 = - skel.listBucket(wrappedParam); + skel.listBucket(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), listBucketResponse39, false); } else @@ -115,7 +115,7 @@ public class AmazonS3MessageReceiverInOut extends org.apache.axis2.receivers.Abs putObjectResponse41 = - skel.putObject(wrappedParam); + skel.putObject(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), putObjectResponse41, false); } else @@ -129,7 +129,7 @@ public class AmazonS3MessageReceiverInOut extends org.apache.axis2.receivers.Abs createBucketResponse43 = - skel.createBucket(wrappedParam); + skel.createBucket(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), createBucketResponse43, false); } else @@ -143,7 +143,7 @@ public class AmazonS3MessageReceiverInOut extends org.apache.axis2.receivers.Abs listAllMyBucketsResponse45 = - skel.listAllMyBuckets(wrappedParam); + skel.listAllMyBuckets(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), listAllMyBucketsResponse45, false); } else @@ -157,7 +157,7 @@ public class AmazonS3MessageReceiverInOut extends org.apache.axis2.receivers.Abs getObjectResponse47 = - skel.getObject(wrappedParam); + skel.getObject(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), getObjectResponse47, false); } else @@ -171,7 +171,7 @@ public class AmazonS3MessageReceiverInOut extends org.apache.axis2.receivers.Abs deleteBucketResponse49 = - skel.deleteBucket(wrappedParam); + skel.deleteBucket(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), deleteBucketResponse49, false); } else @@ -185,7 +185,7 @@ public class AmazonS3MessageReceiverInOut extends org.apache.axis2.receivers.Abs setBucketLoggingStatusResponse51 = - skel.setBucketLoggingStatus(wrappedParam); + skel.setBucketLoggingStatus(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), setBucketLoggingStatusResponse51, false); } else @@ -199,7 +199,7 @@ public class AmazonS3MessageReceiverInOut extends org.apache.axis2.receivers.Abs getObjectAccessControlPolicyResponse53 = - skel.getObjectAccessControlPolicy(wrappedParam); + skel.getObjectAccessControlPolicy(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), getObjectAccessControlPolicyResponse53, false); } else @@ -213,7 +213,7 @@ public class AmazonS3MessageReceiverInOut extends org.apache.axis2.receivers.Abs deleteObjectResponse55 = - skel.deleteObject(wrappedParam); + skel.deleteObject(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), deleteObjectResponse55, false); } else @@ -227,7 +227,7 @@ public class AmazonS3MessageReceiverInOut extends org.apache.axis2.receivers.Abs setBucketAccessControlPolicyResponse57 = - skel.setBucketAccessControlPolicy(wrappedParam); + skel.setBucketAccessControlPolicy(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), setBucketAccessControlPolicyResponse57, false); } else @@ -241,7 +241,7 @@ public class AmazonS3MessageReceiverInOut extends org.apache.axis2.receivers.Abs setObjectAccessControlPolicyResponse59 = - skel.setObjectAccessControlPolicy(wrappedParam); + skel.setObjectAccessControlPolicy(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), setObjectAccessControlPolicyResponse59, false); } else @@ -255,7 +255,7 @@ public class AmazonS3MessageReceiverInOut extends org.apache.axis2.receivers.Abs putObjectInlineResponse61 = - skel.putObjectInline(wrappedParam); + skel.putObjectInline(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), putObjectInlineResponse61, false); } else @@ -269,7 +269,7 @@ public class AmazonS3MessageReceiverInOut extends org.apache.axis2.receivers.Abs getObjectExtendedResponse63 = - skel.getObjectExtended(wrappedParam); + skel.getObjectExtended(wrappedParam); envelope = toEnvelope(getSOAPFactory(msgContext), getObjectExtendedResponse63, false); diff --git a/awsapi/src/com/amazon/s3/MetadataDirective.java b/awsapi/src/com/amazon/s3/MetadataDirective.java index b3766861cc7..a558f60e09f 100644 --- a/awsapi/src/com/amazon/s3/MetadataDirective.java +++ b/awsapi/src/com/amazon/s3/MetadataDirective.java @@ -333,7 +333,7 @@ public class MetadataDirective implements org.apache.axis2.databinding.ADBBean { public static MetadataDirective fromValue(java.lang.String value) throws java.lang.IllegalArgumentException { MetadataDirective enumeration = (MetadataDirective) - _table_.get(value); + _table_.get(value); if (enumeration == null) throw new java.lang.IllegalArgumentException(); diff --git a/awsapi/src/com/amazon/s3/MfaDeleteStatus.java b/awsapi/src/com/amazon/s3/MfaDeleteStatus.java index 63e982762e4..a050d8c1a16 100644 --- a/awsapi/src/com/amazon/s3/MfaDeleteStatus.java +++ b/awsapi/src/com/amazon/s3/MfaDeleteStatus.java @@ -333,7 +333,7 @@ public class MfaDeleteStatus implements org.apache.axis2.databinding.ADBBean { public static MfaDeleteStatus fromValue(java.lang.String value) throws java.lang.IllegalArgumentException { MfaDeleteStatus enumeration = (MfaDeleteStatus) - _table_.get(value); + _table_.get(value); if (enumeration == null) throw new java.lang.IllegalArgumentException(); diff --git a/awsapi/src/com/amazon/s3/Payer.java b/awsapi/src/com/amazon/s3/Payer.java index ea33c567b43..61b7b7f0d1f 100644 --- a/awsapi/src/com/amazon/s3/Payer.java +++ b/awsapi/src/com/amazon/s3/Payer.java @@ -333,7 +333,7 @@ public class Payer implements org.apache.axis2.databinding.ADBBean { public static Payer fromValue(java.lang.String value) throws java.lang.IllegalArgumentException { Payer enumeration = (Payer) - _table_.get(value); + _table_.get(value); if (enumeration == null) throw new java.lang.IllegalArgumentException(); diff --git a/awsapi/src/com/amazon/s3/Permission.java b/awsapi/src/com/amazon/s3/Permission.java index 1fad5a7ceea..736fd64ffdb 100644 --- a/awsapi/src/com/amazon/s3/Permission.java +++ b/awsapi/src/com/amazon/s3/Permission.java @@ -345,7 +345,7 @@ public class Permission implements org.apache.axis2.databinding.ADBBean { public static Permission fromValue(java.lang.String value) throws java.lang.IllegalArgumentException { Permission enumeration = (Permission) - _table_.get(value); + _table_.get(value); if (enumeration == null) throw new java.lang.IllegalArgumentException(); diff --git a/awsapi/src/com/amazon/s3/StorageClass.java b/awsapi/src/com/amazon/s3/StorageClass.java index 56f7edacec7..d10c069ed52 100644 --- a/awsapi/src/com/amazon/s3/StorageClass.java +++ b/awsapi/src/com/amazon/s3/StorageClass.java @@ -333,7 +333,7 @@ public class StorageClass implements org.apache.axis2.databinding.ADBBean { public static StorageClass fromValue(java.lang.String value) throws java.lang.IllegalArgumentException { StorageClass enumeration = (StorageClass) - _table_.get(value); + _table_.get(value); if (enumeration == null) throw new java.lang.IllegalArgumentException(); diff --git a/awsapi/src/com/amazon/s3/VersioningStatus.java b/awsapi/src/com/amazon/s3/VersioningStatus.java index 74b3de09564..c05604feec6 100644 --- a/awsapi/src/com/amazon/s3/VersioningStatus.java +++ b/awsapi/src/com/amazon/s3/VersioningStatus.java @@ -333,7 +333,7 @@ public class VersioningStatus implements org.apache.axis2.databinding.ADBBean { public static VersioningStatus fromValue(java.lang.String value) throws java.lang.IllegalArgumentException { VersioningStatus enumeration = (VersioningStatus) - _table_.get(value); + _table_.get(value); if (enumeration == null) throw new java.lang.IllegalArgumentException(); diff --git a/awsapi/src/com/amazon/s3/client/AmazonS3Stub.java b/awsapi/src/com/amazon/s3/client/AmazonS3Stub.java index 06ba65517d5..ad740f08df7 100644 --- a/awsapi/src/com/amazon/s3/client/AmazonS3Stub.java +++ b/awsapi/src/com/amazon/s3/client/AmazonS3Stub.java @@ -235,9 +235,9 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { public com.amazon.s3.client.AmazonS3Stub.GetBucketLoggingStatusResponse getBucketLoggingStatus( - com.amazon.s3.client.AmazonS3Stub.GetBucketLoggingStatus getBucketLoggingStatus0) + com.amazon.s3.client.AmazonS3Stub.GetBucketLoggingStatus getBucketLoggingStatus0) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -335,11 +335,11 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { */ public void startgetBucketLoggingStatus( - com.amazon.s3.client.AmazonS3Stub.GetBucketLoggingStatus getBucketLoggingStatus0, + com.amazon.s3.client.AmazonS3Stub.GetBucketLoggingStatus getBucketLoggingStatus0, - final com.amazon.s3.client.AmazonS3CallbackHandler callback) + final com.amazon.s3.client.AmazonS3CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[0].getName()); _operationClient.getOptions().setAction("http://s3.amazonaws.com/doc/2006-03-01/AmazonS3/GetBucketLoggingStatusRequest"); @@ -471,9 +471,9 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { public com.amazon.s3.client.AmazonS3Stub.CopyObjectResponse copyObject( - com.amazon.s3.client.AmazonS3Stub.CopyObject copyObject2) + com.amazon.s3.client.AmazonS3Stub.CopyObject copyObject2) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -571,11 +571,11 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { */ public void startcopyObject( - com.amazon.s3.client.AmazonS3Stub.CopyObject copyObject2, + com.amazon.s3.client.AmazonS3Stub.CopyObject copyObject2, - final com.amazon.s3.client.AmazonS3CallbackHandler callback) + final com.amazon.s3.client.AmazonS3CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[1].getName()); _operationClient.getOptions().setAction("http://s3.amazonaws.com/doc/2006-03-01/AmazonS3/CopyObjectRequest"); @@ -706,9 +706,9 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { public com.amazon.s3.client.AmazonS3Stub.GetBucketAccessControlPolicyResponse getBucketAccessControlPolicy( - com.amazon.s3.client.AmazonS3Stub.GetBucketAccessControlPolicy getBucketAccessControlPolicy4) + com.amazon.s3.client.AmazonS3Stub.GetBucketAccessControlPolicy getBucketAccessControlPolicy4) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -807,11 +807,11 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { */ public void startgetBucketAccessControlPolicy( - com.amazon.s3.client.AmazonS3Stub.GetBucketAccessControlPolicy getBucketAccessControlPolicy4, + com.amazon.s3.client.AmazonS3Stub.GetBucketAccessControlPolicy getBucketAccessControlPolicy4, - final com.amazon.s3.client.AmazonS3CallbackHandler callback) + final com.amazon.s3.client.AmazonS3CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[2].getName()); _operationClient.getOptions().setAction("http://s3.amazonaws.com/doc/2006-03-01/AmazonS3/GetBucketAccessControlPolicyRequest"); @@ -943,9 +943,9 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { public com.amazon.s3.client.AmazonS3Stub.ListBucketResponse listBucket( - com.amazon.s3.client.AmazonS3Stub.ListBucket listBucket6) + com.amazon.s3.client.AmazonS3Stub.ListBucket listBucket6) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -1043,11 +1043,11 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { */ public void startlistBucket( - com.amazon.s3.client.AmazonS3Stub.ListBucket listBucket6, + com.amazon.s3.client.AmazonS3Stub.ListBucket listBucket6, - final com.amazon.s3.client.AmazonS3CallbackHandler callback) + final com.amazon.s3.client.AmazonS3CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[3].getName()); _operationClient.getOptions().setAction("http://s3.amazonaws.com/doc/2006-03-01/AmazonS3/ListBucketRequest"); @@ -1178,9 +1178,9 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { public com.amazon.s3.client.AmazonS3Stub.PutObjectResponse putObject( - com.amazon.s3.client.AmazonS3Stub.PutObject putObject8) + com.amazon.s3.client.AmazonS3Stub.PutObject putObject8) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -1278,11 +1278,11 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { */ public void startputObject( - com.amazon.s3.client.AmazonS3Stub.PutObject putObject8, + com.amazon.s3.client.AmazonS3Stub.PutObject putObject8, - final com.amazon.s3.client.AmazonS3CallbackHandler callback) + final com.amazon.s3.client.AmazonS3CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[4].getName()); _operationClient.getOptions().setAction("http://s3.amazonaws.com/doc/2006-03-01/AmazonS3/PutObjectRequest"); @@ -1413,9 +1413,9 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { public com.amazon.s3.client.AmazonS3Stub.CreateBucketResponse createBucket( - com.amazon.s3.client.AmazonS3Stub.CreateBucket createBucket10) + com.amazon.s3.client.AmazonS3Stub.CreateBucket createBucket10) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -1513,11 +1513,11 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { */ public void startcreateBucket( - com.amazon.s3.client.AmazonS3Stub.CreateBucket createBucket10, + com.amazon.s3.client.AmazonS3Stub.CreateBucket createBucket10, - final com.amazon.s3.client.AmazonS3CallbackHandler callback) + final com.amazon.s3.client.AmazonS3CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[5].getName()); _operationClient.getOptions().setAction("http://s3.amazonaws.com/doc/2006-03-01/AmazonS3/CreateBucketRequest"); @@ -1648,9 +1648,9 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { public com.amazon.s3.client.AmazonS3Stub.ListAllMyBucketsResponse listAllMyBuckets( - com.amazon.s3.client.AmazonS3Stub.ListAllMyBuckets listAllMyBuckets12) + com.amazon.s3.client.AmazonS3Stub.ListAllMyBuckets listAllMyBuckets12) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -1748,11 +1748,11 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { */ public void startlistAllMyBuckets( - com.amazon.s3.client.AmazonS3Stub.ListAllMyBuckets listAllMyBuckets12, + com.amazon.s3.client.AmazonS3Stub.ListAllMyBuckets listAllMyBuckets12, - final com.amazon.s3.client.AmazonS3CallbackHandler callback) + final com.amazon.s3.client.AmazonS3CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[6].getName()); _operationClient.getOptions().setAction("http://s3.amazonaws.com/doc/2006-03-01/AmazonS3/ListAllMyBucketsRequest"); @@ -1883,9 +1883,9 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { public com.amazon.s3.client.AmazonS3Stub.GetObjectResponse getObject( - com.amazon.s3.client.AmazonS3Stub.GetObject getObject14) + com.amazon.s3.client.AmazonS3Stub.GetObject getObject14) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -1983,11 +1983,11 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { */ public void startgetObject( - com.amazon.s3.client.AmazonS3Stub.GetObject getObject14, + com.amazon.s3.client.AmazonS3Stub.GetObject getObject14, - final com.amazon.s3.client.AmazonS3CallbackHandler callback) + final com.amazon.s3.client.AmazonS3CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[7].getName()); _operationClient.getOptions().setAction("http://s3.amazonaws.com/doc/2006-03-01/AmazonS3/GetObjectRequest"); @@ -2118,9 +2118,9 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { public com.amazon.s3.client.AmazonS3Stub.DeleteBucketResponse deleteBucket( - com.amazon.s3.client.AmazonS3Stub.DeleteBucket deleteBucket16) + com.amazon.s3.client.AmazonS3Stub.DeleteBucket deleteBucket16) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -2218,11 +2218,11 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { */ public void startdeleteBucket( - com.amazon.s3.client.AmazonS3Stub.DeleteBucket deleteBucket16, + com.amazon.s3.client.AmazonS3Stub.DeleteBucket deleteBucket16, - final com.amazon.s3.client.AmazonS3CallbackHandler callback) + final com.amazon.s3.client.AmazonS3CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[8].getName()); _operationClient.getOptions().setAction("http://s3.amazonaws.com/doc/2006-03-01/AmazonS3/DeleteBucketRequest"); @@ -2353,9 +2353,9 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { public com.amazon.s3.client.AmazonS3Stub.SetBucketLoggingStatusResponse setBucketLoggingStatus( - com.amazon.s3.client.AmazonS3Stub.SetBucketLoggingStatus setBucketLoggingStatus18) + com.amazon.s3.client.AmazonS3Stub.SetBucketLoggingStatus setBucketLoggingStatus18) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -2453,11 +2453,11 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { */ public void startsetBucketLoggingStatus( - com.amazon.s3.client.AmazonS3Stub.SetBucketLoggingStatus setBucketLoggingStatus18, + com.amazon.s3.client.AmazonS3Stub.SetBucketLoggingStatus setBucketLoggingStatus18, - final com.amazon.s3.client.AmazonS3CallbackHandler callback) + final com.amazon.s3.client.AmazonS3CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[9].getName()); _operationClient.getOptions().setAction("http://s3.amazonaws.com/doc/2006-03-01/AmazonS3/SetBucketLoggingStatusRequest"); @@ -2589,9 +2589,9 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { public com.amazon.s3.client.AmazonS3Stub.GetObjectAccessControlPolicyResponse getObjectAccessControlPolicy( - com.amazon.s3.client.AmazonS3Stub.GetObjectAccessControlPolicy getObjectAccessControlPolicy20) + com.amazon.s3.client.AmazonS3Stub.GetObjectAccessControlPolicy getObjectAccessControlPolicy20) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -2690,11 +2690,11 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { */ public void startgetObjectAccessControlPolicy( - com.amazon.s3.client.AmazonS3Stub.GetObjectAccessControlPolicy getObjectAccessControlPolicy20, + com.amazon.s3.client.AmazonS3Stub.GetObjectAccessControlPolicy getObjectAccessControlPolicy20, - final com.amazon.s3.client.AmazonS3CallbackHandler callback) + final com.amazon.s3.client.AmazonS3CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[10].getName()); _operationClient.getOptions().setAction("http://s3.amazonaws.com/doc/2006-03-01/AmazonS3/GetObjectAccessControlPolicyRequest"); @@ -2826,9 +2826,9 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { public com.amazon.s3.client.AmazonS3Stub.DeleteObjectResponse deleteObject( - com.amazon.s3.client.AmazonS3Stub.DeleteObject deleteObject22) + com.amazon.s3.client.AmazonS3Stub.DeleteObject deleteObject22) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -2926,11 +2926,11 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { */ public void startdeleteObject( - com.amazon.s3.client.AmazonS3Stub.DeleteObject deleteObject22, + com.amazon.s3.client.AmazonS3Stub.DeleteObject deleteObject22, - final com.amazon.s3.client.AmazonS3CallbackHandler callback) + final com.amazon.s3.client.AmazonS3CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[11].getName()); _operationClient.getOptions().setAction("http://s3.amazonaws.com/doc/2006-03-01/AmazonS3/DeleteObjectRequest"); @@ -3061,9 +3061,9 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { public com.amazon.s3.client.AmazonS3Stub.SetBucketAccessControlPolicyResponse setBucketAccessControlPolicy( - com.amazon.s3.client.AmazonS3Stub.SetBucketAccessControlPolicy setBucketAccessControlPolicy24) + com.amazon.s3.client.AmazonS3Stub.SetBucketAccessControlPolicy setBucketAccessControlPolicy24) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -3162,11 +3162,11 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { */ public void startsetBucketAccessControlPolicy( - com.amazon.s3.client.AmazonS3Stub.SetBucketAccessControlPolicy setBucketAccessControlPolicy24, + com.amazon.s3.client.AmazonS3Stub.SetBucketAccessControlPolicy setBucketAccessControlPolicy24, - final com.amazon.s3.client.AmazonS3CallbackHandler callback) + final com.amazon.s3.client.AmazonS3CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[12].getName()); _operationClient.getOptions().setAction("http://s3.amazonaws.com/doc/2006-03-01/AmazonS3/SetBucketAccessControlPolicyRequest"); @@ -3298,9 +3298,9 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { public com.amazon.s3.client.AmazonS3Stub.SetObjectAccessControlPolicyResponse setObjectAccessControlPolicy( - com.amazon.s3.client.AmazonS3Stub.SetObjectAccessControlPolicy setObjectAccessControlPolicy26) + com.amazon.s3.client.AmazonS3Stub.SetObjectAccessControlPolicy setObjectAccessControlPolicy26) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -3399,11 +3399,11 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { */ public void startsetObjectAccessControlPolicy( - com.amazon.s3.client.AmazonS3Stub.SetObjectAccessControlPolicy setObjectAccessControlPolicy26, + com.amazon.s3.client.AmazonS3Stub.SetObjectAccessControlPolicy setObjectAccessControlPolicy26, - final com.amazon.s3.client.AmazonS3CallbackHandler callback) + final com.amazon.s3.client.AmazonS3CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[13].getName()); _operationClient.getOptions().setAction("http://s3.amazonaws.com/doc/2006-03-01/AmazonS3/SetObjectAccessControlPolicyRequest"); @@ -3535,9 +3535,9 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { public com.amazon.s3.client.AmazonS3Stub.PutObjectInlineResponse putObjectInline( - com.amazon.s3.client.AmazonS3Stub.PutObjectInline putObjectInline28) + com.amazon.s3.client.AmazonS3Stub.PutObjectInline putObjectInline28) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -3635,11 +3635,11 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { */ public void startputObjectInline( - com.amazon.s3.client.AmazonS3Stub.PutObjectInline putObjectInline28, + com.amazon.s3.client.AmazonS3Stub.PutObjectInline putObjectInline28, - final com.amazon.s3.client.AmazonS3CallbackHandler callback) + final com.amazon.s3.client.AmazonS3CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[14].getName()); _operationClient.getOptions().setAction("http://s3.amazonaws.com/doc/2006-03-01/AmazonS3/PutObjectInlineRequest"); @@ -3770,9 +3770,9 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { public com.amazon.s3.client.AmazonS3Stub.GetObjectExtendedResponse getObjectExtended( - com.amazon.s3.client.AmazonS3Stub.GetObjectExtended getObjectExtended30) + com.amazon.s3.client.AmazonS3Stub.GetObjectExtended getObjectExtended30) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; @@ -3870,11 +3870,11 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { */ public void startgetObjectExtended( - com.amazon.s3.client.AmazonS3Stub.GetObjectExtended getObjectExtended30, + com.amazon.s3.client.AmazonS3Stub.GetObjectExtended getObjectExtended30, - final com.amazon.s3.client.AmazonS3CallbackHandler callback) + final com.amazon.s3.client.AmazonS3CallbackHandler callback) - throws java.rmi.RemoteException { + throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[15].getName()); _operationClient.getOptions().setAction("http://s3.amazonaws.com/doc/2006-03-01/AmazonS3/GetObjectExtendedRequest"); @@ -18445,7 +18445,7 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { public static Permission fromValue(java.lang.String value) throws java.lang.IllegalArgumentException { Permission enumeration = (Permission) - _table_.get(value); + _table_.get(value); if (enumeration == null) throw new java.lang.IllegalArgumentException(); @@ -23125,7 +23125,7 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { public static MetadataDirective fromValue(java.lang.String value) throws java.lang.IllegalArgumentException { MetadataDirective enumeration = (MetadataDirective) - _table_.get(value); + _table_.get(value); if (enumeration == null) throw new java.lang.IllegalArgumentException(); @@ -29108,7 +29108,7 @@ public class AmazonS3Stub extends org.apache.axis2.client.Stub { public static StorageClass fromValue(java.lang.String value) throws java.lang.IllegalArgumentException { StorageClass enumeration = (StorageClass) - _table_.get(value); + _table_.get(value); if (enumeration == null) throw new java.lang.IllegalArgumentException(); diff --git a/awsapi/src/com/cloud/bridge/service/EC2RestServlet.java b/awsapi/src/com/cloud/bridge/service/EC2RestServlet.java index fd2919dc117..9ac5c4e3206 100644 --- a/awsapi/src/com/cloud/bridge/service/EC2RestServlet.java +++ b/awsapi/src/com/cloud/bridge/service/EC2RestServlet.java @@ -582,12 +582,12 @@ public class EC2RestServlet extends HttpServlet { credentialDao.setCertificateId( accessKey[0], null ); */txn = TransactionLegacy.open(TransactionLegacy.AWSAPI_DB); - UserCredentialsVO user = ucDao.getByAccessKey(accessKey[0]); - user.setCertUniqueId(null); - ucDao.update(user.getId(), user); - response.setStatus(200); - endResponse(response, "User certificate deleted successfully"); - txn.commit(); + UserCredentialsVO user = ucDao.getByAccessKey(accessKey[0]); + user.setCertUniqueId(null); + ucDao.update(user.getId(), user); + response.setStatus(200); + endResponse(response, "User certificate deleted successfully"); + txn.commit(); } else response.setStatus(404); @@ -834,7 +834,7 @@ public class EC2RestServlet extends HttpServlet { // -> execute the request RevokeSecurityGroupIngressResponse EC2response = - EC2SoapServiceImpl.toRevokeSecurityGroupIngressResponse(ServiceProvider.getInstance().getEC2Engine().revokeSecurityGroup(EC2request)); + EC2SoapServiceImpl.toRevokeSecurityGroupIngressResponse(ServiceProvider.getInstance().getEC2Engine().revokeSecurityGroup(EC2request)); serializeResponse(response, EC2response); } @@ -919,7 +919,7 @@ public class EC2RestServlet extends HttpServlet { // -> execute the request AuthorizeSecurityGroupIngressResponse EC2response = - EC2SoapServiceImpl.toAuthorizeSecurityGroupIngressResponse(ServiceProvider.getInstance().getEC2Engine().authorizeSecurityGroup(EC2request)); + EC2SoapServiceImpl.toAuthorizeSecurityGroupIngressResponse(ServiceProvider.getInstance().getEC2Engine().authorizeSecurityGroup(EC2request)); serializeResponse(response, EC2response); } @@ -1016,7 +1016,7 @@ public class EC2RestServlet extends HttpServlet { // -> execute the request CreateSecurityGroupResponse EC2response = - EC2SoapServiceImpl.toCreateSecurityGroupResponse(ServiceProvider.getInstance().getEC2Engine().createSecurityGroup(groupName, groupDescription)); + EC2SoapServiceImpl.toCreateSecurityGroupResponse(ServiceProvider.getInstance().getEC2Engine().createSecurityGroup(groupName, groupDescription)); serializeResponse(response, EC2response); } @@ -1032,7 +1032,7 @@ public class EC2RestServlet extends HttpServlet { // -> execute the request DeleteSecurityGroupResponse EC2response = - EC2SoapServiceImpl.toDeleteSecurityGroupResponse(ServiceProvider.getInstance().getEC2Engine().deleteSecurityGroup(groupName)); + EC2SoapServiceImpl.toDeleteSecurityGroupResponse(ServiceProvider.getInstance().getEC2Engine().deleteSecurityGroup(groupName)); serializeResponse(response, EC2response); } @@ -1170,7 +1170,7 @@ public class EC2RestServlet extends HttpServlet { // -> execute the request ModifyImageAttributeResponse EC2response = - EC2SoapServiceImpl.toModifyImageAttributeResponse(ServiceProvider.getInstance().getEC2Engine().modifyImageAttribute(ec2request)); + EC2SoapServiceImpl.toModifyImageAttributeResponse(ServiceProvider.getInstance().getEC2Engine().modifyImageAttribute(ec2request)); serializeResponse(response, EC2response); } @@ -1235,7 +1235,7 @@ public class EC2RestServlet extends HttpServlet { // -> execute the request ResetImageAttributeResponse EC2response = - EC2SoapServiceImpl.toResetImageAttributeResponse(ServiceProvider.getInstance().getEC2Engine().modifyImageAttribute(ec2request)); + EC2SoapServiceImpl.toResetImageAttributeResponse(ServiceProvider.getInstance().getEC2Engine().modifyImageAttribute(ec2request)); serializeResponse(response, EC2response); } @@ -1447,7 +1447,7 @@ public class EC2RestServlet extends HttpServlet { // -> execute the request DescribeAvailabilityZonesResponse EC2response = - EC2SoapServiceImpl.toDescribeAvailabilityZonesResponse(ServiceProvider.getInstance().getEC2Engine().describeAvailabilityZones(EC2request)); + EC2SoapServiceImpl.toDescribeAvailabilityZonesResponse(ServiceProvider.getInstance().getEC2Engine().describeAvailabilityZones(EC2request)); serializeResponse(response, EC2response); } @@ -1503,7 +1503,7 @@ public class EC2RestServlet extends HttpServlet { } DescribeImageAttributeResponse EC2response = - EC2SoapServiceImpl.toDescribeImageAttributeResponse(ServiceProvider.getInstance().getEC2Engine().describeImageAttribute(ec2request)); + EC2SoapServiceImpl.toDescribeImageAttributeResponse(ServiceProvider.getInstance().getEC2Engine().describeImageAttribute(ec2request)); serializeResponse(response, EC2response); } @@ -1681,7 +1681,7 @@ public class EC2RestServlet extends HttpServlet { // -> execute the request DescribeInstanceAttributeResponse EC2response = - EC2SoapServiceImpl.toDescribeInstanceAttributeResponse(ServiceProvider.getInstance().getEC2Engine().describeInstances(EC2request)); + EC2SoapServiceImpl.toDescribeInstanceAttributeResponse(ServiceProvider.getInstance().getEC2Engine().describeInstances(EC2request)); serializeResponse(response, EC2response); } @@ -1711,7 +1711,7 @@ public class EC2RestServlet extends HttpServlet { // -> execute the request ModifyInstanceAttributeResponse EC2response = - EC2SoapServiceImpl.toModifyInstanceAttributeResponse(ServiceProvider.getInstance().getEC2Engine().modifyInstanceAttribute(ec2Request)); + EC2SoapServiceImpl.toModifyInstanceAttributeResponse(ServiceProvider.getInstance().getEC2Engine().modifyInstanceAttribute(ec2Request)); serializeResponse(response, EC2response); } @@ -1770,7 +1770,7 @@ public class EC2RestServlet extends HttpServlet { // -> execute the request EC2Engine engine = ServiceProvider.getInstance().getEC2Engine(); DescribeVolumesResponse EC2response = - EC2SoapServiceImpl.toDescribeVolumesResponse(ServiceProvider.getInstance().getEC2Engine().describeVolumes(EC2request), engine); + EC2SoapServiceImpl.toDescribeVolumesResponse(ServiceProvider.getInstance().getEC2Engine().describeVolumes(EC2request), engine); serializeResponse(response, EC2response); } @@ -1992,7 +1992,7 @@ public class EC2RestServlet extends HttpServlet { * parameter to see if the signature has expired and if so the request fails. */ private boolean authenticateRequest(HttpServletRequest request, HttpServletResponse response) throws SignatureException, IOException, InstantiationException, - IllegalAccessException, ClassNotFoundException, SQLException, ParseException { + IllegalAccessException, ClassNotFoundException, SQLException, ParseException { String cloudSecretKey = null; String cloudAccessKey = null; String signature = null; diff --git a/awsapi/src/com/cloud/bridge/service/controller/s3/ServiceProvider.java b/awsapi/src/com/cloud/bridge/service/controller/s3/ServiceProvider.java index e00408e1edf..4b8c7581535 100644 --- a/awsapi/src/com/cloud/bridge/service/controller/s3/ServiceProvider.java +++ b/awsapi/src/com/cloud/bridge/service/controller/s3/ServiceProvider.java @@ -121,7 +121,7 @@ public class ServiceProvider extends ManagerBase { long mhostId = 0; if (mhost != null) mhostId = mhost.getId() != null ? mhost.getId().longValue() : 0L; - return mhostId; + return mhostId; } /** diff --git a/awsapi/src/com/cloud/bridge/service/core/ec2/EC2Engine.java b/awsapi/src/com/cloud/bridge/service/core/ec2/EC2Engine.java index ccac6749479..ef7539f7350 100644 --- a/awsapi/src/com/cloud/bridge/service/core/ec2/EC2Engine.java +++ b/awsapi/src/com/cloud/bridge/service/core/ec2/EC2Engine.java @@ -66,6 +66,7 @@ import com.cloud.stack.models.CloudStackPasswordData; import com.cloud.stack.models.CloudStackResourceLimit; import com.cloud.stack.models.CloudStackResourceTag; import com.cloud.stack.models.CloudStackSecurityGroup; +import com.cloud.stack.models.CloudStackServiceOffering; import com.cloud.stack.models.CloudStackSnapshot; import com.cloud.stack.models.CloudStackTemplate; import com.cloud.stack.models.CloudStackTemplatePermission; @@ -126,7 +127,7 @@ public class EC2Engine extends ManagerBase { FileInputStream ec2PropFile = null; try { EC2Prop.load(new FileInputStream(propertiesFile)); - ec2PropFile = new FileInputStream( propertiesFile ); + ec2PropFile = new FileInputStream(propertiesFile); EC2Prop.load(ec2PropFile); } catch (FileNotFoundException e) { @@ -371,12 +372,12 @@ public class EC2Engine extends ManagerBase { CloudStackSecurityGroup resp = null; if (ipPerm.getProtocol().equalsIgnoreCase("icmp")) { resp = - getApi().authorizeSecurityGroupIngress(null, constructList(ipPerm.getIpRangeSet()), null, null, ipPerm.getIcmpCode(), ipPerm.getIcmpType(), - ipPerm.getProtocol(), null, request.getName(), null, secGroupList); + getApi().authorizeSecurityGroupIngress(null, constructList(ipPerm.getIpRangeSet()), null, null, ipPerm.getIcmpCode(), ipPerm.getIcmpType(), + ipPerm.getProtocol(), null, request.getName(), null, secGroupList); } else { resp = - getApi().authorizeSecurityGroupIngress(null, constructList(ipPerm.getIpRangeSet()), null, ipPerm.getToPort().longValue(), null, null, - ipPerm.getProtocol(), null, request.getName(), ipPerm.getFromPort().longValue(), secGroupList); + getApi().authorizeSecurityGroupIngress(null, constructList(ipPerm.getIpRangeSet()), null, ipPerm.getToPort().longValue(), null, null, + ipPerm.getProtocol(), null, request.getName(), ipPerm.getFromPort().longValue(), secGroupList); } if (resp != null) { List ingressRules = resp.getIngressRules(); @@ -815,7 +816,7 @@ public class EC2Engine extends ManagerBase { CloudStackIpAddress cloudIp = cloudIps.get(0); List vmList = - getApi().listVirtualMachines(null, null, true, null, null, null, null, request.getInstanceId(), null, null, null, null, null, null, null, null, null); + getApi().listVirtualMachines(null, null, true, null, null, null, null, request.getInstanceId(), null, null, null, null, null, null, null, null, null); if (vmList == null || vmList.size() == 0) { throw new Exception("Instance not found"); } @@ -972,8 +973,8 @@ public class EC2Engine extends ManagerBase { String osTypeId = imageSet[0].getOsTypeId(); CloudStackTemplate resp = - getApi().createTemplate((request.getDescription() == null ? "" : request.getDescription()), request.getName(), osTypeId, null, null, null, null, null, - null, volumeId); + getApi().createTemplate((request.getDescription() == null ? "" : request.getDescription()), request.getName(), osTypeId, null, null, null, null, null, + null, volumeId); if (resp == null || resp.getId() == null) { throw new Exception("Image couldn't be created"); } @@ -1003,9 +1004,9 @@ public class EC2Engine extends ManagerBase { EC2CreateImageResponse image = new EC2CreateImageResponse(); try { List templates = - getApi().registerTemplate((request.getDescription() == null ? request.getName() : request.getDescription()), request.getFormat(), - request.getHypervisor(), request.getName(), toOSTypeId(request.getOsTypeName()), request.getLocation(), toZoneId(request.getZoneName(), null), null, - null, null, null, null, null, null, null, null); + getApi().registerTemplate((request.getDescription() == null ? request.getName() : request.getDescription()), request.getFormat(), + request.getHypervisor(), request.getName(), toOSTypeId(request.getOsTypeName()), request.getLocation(), toZoneId(request.getZoneName(), null), null, + null, null, null, null, null, null, null, null); if (templates != null) { // technically we will only ever register a single template... for (CloudStackTemplate template : templates) { @@ -1226,7 +1227,7 @@ public class EC2Engine extends ManagerBase { // -> no volume name is given in the Amazon request but is required in the cloud API CloudStackVolume vol = - getApi().createVolume(UUID.randomUUID().toString(), null, diskOfferingId, null, size, snapshotId, toZoneId(request.getZoneName(), null)); + getApi().createVolume(UUID.randomUUID().toString(), null, diskOfferingId, null, size, snapshotId, toZoneId(request.getZoneName(), null)); if (vol != null) { resp.setAttached(vol.getAttached()); resp.setCreated(vol.getCreated()); @@ -1414,7 +1415,7 @@ public class EC2Engine extends ManagerBase { if (request.getInstanceType() != null) { instanceType = request.getInstanceType(); } - CloudStackServiceOfferingVO svcOffering = getCSServiceOfferingId(instanceType); + CloudStackServiceOffering svcOffering = getCSServiceOfferingId(instanceType); if (svcOffering == null) { logger.info("No ServiceOffering found to be defined by name, please contact the administrator " + instanceType); throw new Exception("instanceType not found"); @@ -1449,8 +1450,8 @@ public class EC2Engine extends ManagerBase { for (int i = 0; i < createInstances; i++) { try { CloudStackUserVm resp = - getApi().deployVirtualMachine(svcOffering.getId(), request.getTemplateId(), zoneId, null, null, null, null, null, null, null, - request.getKeyName(), null, null, groupIds, groupNames, request.getSize().longValue(), request.getUserData()); + getApi().deployVirtualMachine(svcOffering.getId(), request.getTemplateId(), zoneId, null, null, null, null, null, null, null, + request.getKeyName(), null, null, groupIds, groupNames, request.getSize().longValue(), request.getUserData()); EC2Instance vm = new EC2Instance(); vm.setId(resp.getId().toString()); vm.setName(resp.getName()); @@ -1609,7 +1610,7 @@ public class EC2Engine extends ManagerBase { if (request.getInstanceType() != null) { String instanceType = request.getInstanceType(); - CloudStackServiceOfferingVO svcOffering = getCSServiceOfferingId(instanceType); + CloudStackServiceOffering svcOffering = getCSServiceOfferingId(instanceType); if (svcOffering == null) throw new Exception("instanceType not found"); CloudStackUserVm userVm = getApi().changeServiceForVirtualMachine(instanceId, svcOffering.getId()); @@ -1673,7 +1674,7 @@ public class EC2Engine extends ManagerBase { * @param ifs - filter out unwanted instances */ private EC2DescribeInstancesResponse listVirtualMachines(String[] virtualMachineIds, EC2InstanceFilterSet ifs, List resourceTags) - throws Exception { + throws Exception { EC2DescribeInstancesResponse instances = new EC2DescribeInstancesResponse(); if (null == virtualMachineIds || 0 == virtualMachineIds.length) { @@ -1697,7 +1698,7 @@ public class EC2Engine extends ManagerBase { * @param instanceId - if interested in volumes for a specific instance, null if instance is not important */ private EC2DescribeVolumesResponse listVolumes(String volumeId, String instanceId, EC2DescribeVolumesResponse volumes, List resourceTagSet) - throws Exception { + throws Exception { List vols = getApi().listVolumes(null, null, null, volumeId, null, null, null, null, null, instanceId, null, resourceTagSet); if (vols != null && vols.size() > 0) { @@ -1783,11 +1784,12 @@ public class EC2Engine extends ManagerBase { * */ - private CloudStackServiceOfferingVO getCSServiceOfferingId(String instanceType) throws Exception { + private CloudStackServiceOffering getCSServiceOfferingId(String instanceType) throws Exception { try { if (instanceType == null) instanceType = "m1.small"; // default value - return scvoDao.getSvcOfferingByName(instanceType); + List serviceOfferings = getApi().listServiceOfferings(null, null, false, null, instanceType, null, null); + return serviceOfferings.get(0); } catch (Exception e) { logger.error("Error while retrieving ServiceOffering information by name - ", e); throw new Exception("No ServiceOffering found to be defined by name"); @@ -1888,11 +1890,11 @@ public class EC2Engine extends ManagerBase { * EC2Instance objects loaded. */ private EC2DescribeInstancesResponse lookupInstances(String instanceId, EC2DescribeInstancesResponse instances, List resourceTagSet) - throws Exception { + throws Exception { String instId = instanceId != null ? instanceId : null; List vms = - getApi().listVirtualMachines(null, null, true, null, null, null, null, instId, null, null, null, null, null, null, null, null, resourceTagSet); + getApi().listVirtualMachines(null, null, true, null, null, null, null, instId, null, null, null, null, null, null, null, null, resourceTagSet); if (vms != null && vms.size() > 0) { for (CloudStackUserVm cloudVm : vms) { @@ -2308,7 +2310,7 @@ public class EC2Engine extends ManagerBase { */ private CloudStackNetwork createDefaultGuestNetwork(String zoneId, CloudStackNetworkOffering offering, CloudStackAccount owner) throws Exception { return getApi().createNetwork(owner.getName() + "-network", owner.getName() + "-network", offering.getId(), zoneId, owner.getName(), owner.getDomainId(), true, - null, null, null, null, null, null, null, null); + null, null, null, null, null, null, null, null); } /** @@ -2695,8 +2697,8 @@ public class EC2Engine extends ManagerBase { if (errorMessage.contains("Object vm_instance(uuid:") && errorMessage.contains(") does not exist")) { throw new EC2ServiceException(ClientError.InvalidInstanceID_NotFound, "Specified Instance ID does not exist"); } else if (errorMessage.contains("Unable to find security group by name") || errorMessage.contains("Unable to find security group") || - (errorMessage.contains("Object security_group(uuid:") && errorMessage.contains(") does not exist")) || - errorMessage.contains("Unable to find group by name ")) { + (errorMessage.contains("Object security_group(uuid:") && errorMessage.contains(") does not exist")) || + errorMessage.contains("Unable to find group by name ")) { throw new EC2ServiceException(ClientError.InvalidGroup_NotFound, "Specified Security Group does not exist"); } else if (errorMessage.contains("Invalid port numbers")) { throw new EC2ServiceException(ClientError.InvalidPermission_Malformed, "Specified Port value is invalid"); @@ -2715,7 +2717,7 @@ public class EC2Engine extends ManagerBase { } else if (errorMessage.contains("Object snapshots(uuid:") && errorMessage.contains(") does not exist")) { throw new EC2ServiceException(ClientError.InvalidSnapshot_NotFound, "Specified Snapshot ID doesn't exist"); } else if ((errorMessage.contains("A key pair with name '") && errorMessage.contains("' does not exist")) || - (errorMessage.contains("A key pair with name '") && errorMessage.contains("' was not found"))) { + (errorMessage.contains("A key pair with name '") && errorMessage.contains("' was not found"))) { throw new EC2ServiceException(ClientError.InvalidKeyPair_NotFound, "Specified Key pair name is invalid"); } else if (errorMessage.contains("A key pair with name '") && errorMessage.contains("' already exists")) { throw new EC2ServiceException(ClientError.InvalidKeyPair_Duplicate, "Specified Key pair already exists"); @@ -2742,7 +2744,7 @@ public class EC2Engine extends ManagerBase { } else if (errorMessage.contains("Unable to find tags by parameters specified")) { throw new EC2ServiceException(ClientError.InvalidParameterValue, "Specified resourceTag for the specified resourceId doesn't exist"); } else if (errorMessage.contains("Failed to enable static nat for the ip address with specified ipId " - + "as vm with specified vmId is already associated with specified currentIp")) { + + "as vm with specified vmId is already associated with specified currentIp")) { throw new EC2ServiceException(ClientError.InvalidParameterValue, "Specified publicIp is already associated to the specified VM"); } else if (errorMessage.contains("Specified IP address id is not associated with any vm Id")) { throw new EC2ServiceException(ClientError.InvalidParameterValue, "Specified publicIp is not associated to any VM"); @@ -2790,7 +2792,7 @@ public class EC2Engine extends ManagerBase { throw new EC2ServiceException(ClientError.InvalidAMIID_NotFound, "Specified ImageId is unavailable"); } else if (errorMessage.contains("cannot stop VM") && errorMessage.contains("when it is in state Starting")) { throw new EC2ServiceException(ClientError.IncorrectInstanceState, - "Unable to stop. One or more of the specified instances is in an incorrect state 'pending'"); + "Unable to stop. One or more of the specified instances is in an incorrect state 'pending'"); } else if (errorMessage.contains("Failed to authorize security group ingress rule(s)")) { throw new EC2ServiceException(ClientError.InvalidParameterValue, "Specified Ip-permission is invalid" + " or the Ip-permission already exists"); } else if (errorMessage.contains("Failed to reboot vm instance")) { @@ -2805,7 +2807,7 @@ public class EC2Engine extends ManagerBase { throw new EC2ServiceException(ClientError.VolumeLimitExceeded, "You have reached the limit on the number of volumes that can be created"); } else if (errorMessage.contains("Maximum number of resources of type 'public_ip' for account") && errorMessage.contains("has been exceeded")) { throw new EC2ServiceException(ClientError.AddressLimitExceeded, - "You have reached the limit on the number of elastic ip addresses your account can have"); + "You have reached the limit on the number of elastic ip addresses your account can have"); } else if (errorMessage.contains("Unable to apply save userdata entry on router")) { throw new EC2ServiceException(ClientError.InvalidParameterValue, "The value supplied for parameter UserData is invalid"); } else { @@ -2853,7 +2855,7 @@ public class EC2Engine extends ManagerBase { throw new EC2ServiceException(ServerError.InternalError, "Unable to start the instance that was stopped during image creation"); } else if (errorMessage.contains("One or more of instanceIds specified is in stopped state")) { throw new EC2ServiceException(ClientError.IncorrectInstanceState, - "Unable to reboot. One or more of the specified instances is in an incorrect state 'stopped'"); + "Unable to reboot. One or more of the specified instances is in an incorrect state 'stopped'"); } else if (errorMessage.contains("Specified ipAddress doesn't exist")) { throw new EC2ServiceException(ClientError.InvalidParameterValue, "Specified publicIp doesn't exist"); } else if (errorMessage.contains("Min Count is greater than the number of instances left to allocate")) { @@ -2872,7 +2874,7 @@ public class EC2Engine extends ManagerBase { throw new EC2ServiceException(ClientError.InvalidInstanceID_NotFound, "One or more of the specified instanceId not found"); } else if (errorMessage.contains("Cannot modify, instance should be in stopped state")) { throw new EC2ServiceException(ClientError.IncorrectInstanceState, - "Unable to modify instance attribute. Specified instance is not in the correct state 'stopped'"); + "Unable to modify instance attribute. Specified instance is not in the correct state 'stopped'"); } else { throw new EC2ServiceException(ServerError.InternalError, "An unexpected error occured"); } diff --git a/client/WEB-INF/classes/resources/messages.properties b/client/WEB-INF/classes/resources/messages.properties index df09cf2de62..54721cde655 100644 --- a/client/WEB-INF/classes/resources/messages.properties +++ b/client/WEB-INF/classes/resources/messages.properties @@ -18,9 +18,24 @@ message.select.compute.offering=Please select a compute offering to associate wi message.select.disk.offering=(Optional) Select an additional disk offering to attach to this instance. label.home=Home label.use.default.language=Use default language +label.port=Port +label.remove.ldap=Remove LDAP +message.remove.ldap=Are you sure you want to delete the LDAP configuration? +label.configure.ldap=Configure LDAP +message.configure.ldap=Please confirm you would like to configure LDAP. +label.ldap.configuration=LDAP Configuration +label.ldap.port=LDAP port +label.create.nfs.secondary.staging.store=Create NFS secondary staging store +label.volatile=Volatile +label.planner.mode=Planner mode +label.deployment.planner=Deployment planner +label.quiesce.vm=Quiesce VM +label.smb.username=SMB Username +label.smb.password=SMB Password +label.smb.domain=SMB Domain label.hypervisors=Hypervisors label.home=Home -label.sockets=Sockets +label.sockets=CPU Sockets label.root.disk.size=Root disk size label.s3.nfs.server=S3 NFS Server label.s3.nfs.path=S3 NFS Path @@ -695,6 +710,7 @@ label.lang.arabic=Arabic label.lang.brportugese=Brazilian Portugese label.lang.catalan=Catalan label.lang.chinese=Chinese (Simplified) +label.lang.dutch=Dutch (Netherlands) label.lang.english=English label.lang.french=French label.lang.german=German @@ -702,6 +718,7 @@ label.lang.italian=Italian label.lang.japanese=Japanese label.lang.korean=Korean label.lang.norwegian=Norwegian +label.lang.polish=Polish label.lang.russian=Russian label.lang.spanish=Spanish label.last.disconnected=Last Disconnected @@ -1256,6 +1273,11 @@ label.zoneWizard.trafficType.management=Management\: Traffic between CloudStack\ label.zoneWizard.trafficType.public=Public\: Traffic between the internet and virtual machines in the cloud. label.zoneWizard.trafficType.storage=Storage\: Traffic between primary and secondary storage servers, such as VM templates and snapshots label.ldap.group.name=LDAP Group +label.openDaylight=OpenDaylight +label.opendaylight.controllers=OpenDaylight Controllers +label.opendaylight.controllerdetail=OpenDaylight Controller Details +label.add.OpenDaylight.device=Add OpenDaylight Controller +label.delete.OpenDaylight.device=Delete OpenDaylight Controller managed.state=Managed State message.acquire.new.ip.vpc=Please confirm that you would like to acquire a new IP for this VPC. message.acquire.new.ip=Please confirm that you would like to acquire a new IP for this network. diff --git a/client/WEB-INF/classes/resources/messages_es.properties b/client/WEB-INF/classes/resources/messages_es.properties index 3620047a275..31a9c93646c 100644 --- a/client/WEB-INF/classes/resources/messages_es.properties +++ b/client/WEB-INF/classes/resources/messages_es.properties @@ -22,6 +22,7 @@ error.session.expired=Su sesi\u00c3\u00b3n ha caducado. error.unresolved.internet.name=El nombre de Internet no se puede resolver. extractable=extra\u00c3\u00adble force.delete.domain.warning=Advertencia\: Si elige esta opci\u00c3\u00b3n, la supresi\u00c3\u00b3n de todos los dominios secundarios y todas las cuentas asociadas y sus recursos. +<<<<<<< HEAD force.delete=Fuerza Borrar force.remove=Fuerza Retire force.remove.host.warning=Advertencia\: Si elige esta opci\u00c3\u00b3n, CloudStack para detener la fuerza todas las m\u00c3\u00a1quinas virtuales en ejecuci\u00c3\u00b3n antes de retirar este host del cl\u00c3\u00baster. @@ -31,25 +32,38 @@ ICMP.code=ICMP C\u00c3\u00b3digo ICMP.type=Tipo ICMP image.directory=Directorio de la imagen inline=en l\u00c3\u00adnea +======= +force.delete=Forzar el borrado +force.remove=Forzar el retiro +force.remove.host.warning=Advertencia\: Si elige esta opci\u00f3n, CloudStack para detener la fuerza todas las m\u00e1quinas virtuales en ejecuci\u00f3n antes de retirar este host del cl\u00faster. +force.stop=Forzar la detenci\u00f3n +force.stop.instance.warning=Advertencia\: Forzar la dertenci\u00f3n de esta instancia deber\u00ed\u00ada ser su \u00faltima opci\u00f3n. Puede conducir a la p\u00e9rdida de datos, as\u00ed\u00ad como un comportamiento incoherente del Estado de la m\u00e1quina virtual. +ICMP.code=C\u00f3digo ICMP +ICMP.type=Tipo ICMP +image.directory=Directorio de im\u00e1genes +inline=alineado +label.about=Acerca de +label.about.app=Acerca de CloudStack +>>>>>>> 4e449ff... Add Dutch (Netherlands, Polish languages in Web UI Change Japanese code (ja -> ja_JP) Update transifex sync config label.account=Cuenta label.account.id=ID de la cuenta -label.account.name=Nombre de la cuenta +label.account.name=Nombre de cuenta label.accounts=Cuentas label.account.specific=espec\u00c3\u00adficas de la cuenta -label.acquire.new.ip=adquirir nuevas IP +label.acquire.new.ip=Adquirir nueva IP label.action.attach.disk=Conecte el disco -label.action.attach.disk.processing=disco Fijaci\u00c3\u00b3n .... -label.action.attach.iso=Adjuntar ISO -label.action.attach.iso.processing=Colocaci\u00c3\u00b3n de la norma ISO .... -label.action.cancel.maintenance.mode=Cancelar modo de mantenimiento -label.action.cancel.maintenance.mode.processing=Cancelaci\u00c3\u00b3n del modo de mantenimiento .... -label.action.change.password=Cambiar contrase\u00c3\u00b1a -label.action.change.service=Cambio de Servicio -label.action.change.service.processing=Cambio de servicio .... -label.action.copy.ISO=Copia de la ISO -label.action.copy.ISO.processing=hacer frente ISO .... -label.action.copy.template=Copia de plantilla -label.action.copy.template.processing=hacer frente plantilla .... +label.action.attach.disk.processing=Conectando el disco.... +label.action.attach.iso=Conectar ISO +label.action.attach.iso.processing=Conectando el ISO.... +label.action.cancel.maintenance.mode=Cancelar el modo de mantenimiento +label.action.cancel.maintenance.mode.processing=Cancelando el modo de mantenimiento.... +label.action.change.password=Cambiar la contrase\u00f1a +label.action.change.service=Cambiar el Servicio +label.action.change.service.processing=Cambiando el servicio.... +label.action.copy.ISO=Copiar ISO +label.action.copy.ISO.processing=Copiando ISO .... +label.action.copy.template=Copiear la plantilla +label.action.copy.template.processing=Copiando la plantilla .... label.action.create.template=Crear plantilla label.action.create.template.from.vm=Crear plantilla de VM label.action.create.template.from.volume=Crear plantilla de volumen @@ -250,6 +264,9 @@ label.alert=Alerta label.algorithm=Algoritmo label.allocated=Asignados label.api.key=clave de API +label.app.name=CloudStack +label.archive.alerts=Archivar alertas +label.archive.events=Archivar sucesos label.assign=Asignar label.assign.to.load.balancer=instancia de Asignaci\u00c3\u00b3n de equilibrador de carga label.associated.network.id=ID de red asociados @@ -263,9 +280,13 @@ label.basic.mode=Modo b\u00c3\u00a1sico label.bootable=arranque label.broadcast.domain.type=Tipo de dominio de difusi\u00c3\u00b3n label.by.account=Por Cuenta +label.by.alert.type=Por tipo de alerta label.by.availability=Por Disponibilidad +label.by.date.end=Por fecha (finalizaci\u00f3n) +label.by.date.start=Por fecha (inicio) label.by.domain=Por dominio label.by.end.date=Por Fecha de finalizaci\u00c3\u00b3n +label.by.event.type=Por tipo de suceso label.by.level=por Nivel label.by.pod=Por Pod label.by.role=por funci\u00c3\u00b3n @@ -300,6 +321,7 @@ label.cpu=CPU label.cpu.utilized=CPU Utilizado label.created=creaci\u00c3\u00b3n label.cross.zones=Cruz Zonas +label.custom.disk.iops=IOPS personalizadas label.custom.disk.size=Personal Disk Size label.daily=diario label.data.disk.offering=Datos Disco Offering @@ -307,7 +329,9 @@ label.date=Fecha label.day.of.month=D\u00c3\u00ada del mes label.day.of.week=d\u00c3\u00ada de la semana label.default.use=Usar por defecto +label.delete.alerts=Eliminar alertas label.delete=Eliminar +label.delete.events=Eliminar sucesos label.deleting.failed=No se pudo eliminar label.deleting.processing=Eliminar .... label.description=Descripci\u00c3\u00b3n @@ -319,6 +343,9 @@ label.DHCP.server.type=Tipo de servidor DHCP label.disabled=personas de movilidad reducida label.disabling.vpn.access=Desactivaci\u00c3\u00b3n de VPN de acceso label.disk.allocated=disco asignado +label.disk.iops.max=IOPS m\u00e1ximas +label.disk.iops.min=IOPS m\u00ednimas +label.disk.iops.total=Total de IOPS label.disk.offering=disco Ofrenda label.disk.size.gb=tama\u00c3\u00b1o de disco (en GB) label.disk.size=tama\u00c3\u00b1o de disco @@ -335,6 +362,7 @@ label.domain.suffix=DNS sufijo de dominio (es decir, xyz.com) label.double.quotes.are.not.allowed=comillas dobles no se permite label.download.progress=Progreso de la descarga label.edit=Editar +label.egress.default.policy=Directiva de salida predeterminada label.email=correo electr\u00c3\u00b3nico label.enabling.vpn.access=Habilitaci\u00c3\u00b3n de Acceso VPN label.enabling.vpn=Habilitaci\u00c3\u00b3n VPN @@ -374,6 +402,8 @@ label.host.name=nombre de host label.hosts=Ej\u00c3\u00a9rcitos label.hourly=por hora label.hypervisor=Hypervisor +label.hypervisors=Hipervisores +label.hypervisor.snapshot.reserve=Reserva de instant\u00e1neas de hipervisores label.hypervisor.type=Tipo Hypervisor label.id=ID label.info=Informaci\u00c3\u00b3n @@ -576,7 +606,10 @@ label.resource=Recursos label.resources=Recursos label.role=Papel label.root.disk.offering=Root Disco Offering +label.routing=Enrutamiento label.running.vms=Ejecuci\u00c3\u00b3n de m\u00c3\u00a1quinas virtuales +label.s3.nfs.path=Ruta NFS S3 +label.s3.nfs.server=Servidor NFS S3 label.s3.secret_key=clave secreta label.saturday=s\u00c3\u00a1bado label.save=Guardar @@ -594,6 +627,7 @@ label.select.a.zone=Seleccione una zona. label.sent=Enviados label.server=Servidor label.service.offering=Oferta de Servicio +label.service.state=Estado del servicio label.session.expired=Session Caducado label.shared=compartidas label.SharedMountPoint=SharedMountPoint @@ -605,6 +639,7 @@ label.snapshot.name=Nombre de instant\u00c3\u00a1neas label.snapshot.schedule=Lista de instant\u00c3\u00a1neas label.snapshot.s=Instant\u00c3\u00a1nea (s) label.snapshots=instant\u00c3\u00a1neas +label.sockets=Sockets label.source.nat=NAT Fuente label.specify.vlan=Especifique VLAN label.specify.vxlan=Especifique VXLAN @@ -636,6 +671,7 @@ label.submit=Enviar label.submitted.by=[Enviado por\: ] label.succeeded=Sucesor label.sunday=domingo +label.switch.type=Cambiar el tipo label.system.capacity=Capacidad de todo el sistema label.system.vm=Sistema de VM label.system.vms=Sistema de m\u00c3\u00a1quinas virtuales @@ -680,6 +716,7 @@ label.vcenter.host=vCenter anfitri\u00c3\u00b3n label.vcenter.password=vCenter Contrase\u00c3\u00b1a label.vcenter.username=vCenter Nombre de usuario label.version=Versi\u00c3\u00b3n +label.view.secondary.ips=Ver las IP secundarias label.virtual.appliances=Virtual Appliances label.virtual.appliance=Virtual Appliance label.virtual.machines=Maquinas virtuales @@ -854,6 +891,7 @@ message.step.4.continue=Por favor seleccione al menos una red social para contin message.step.4.desc=Por favor, seleccione la red primaria que la instancia virtual estar\u00c3\u00a1 conectado. message.update.os.preference=Por favor seleccione un sistema operativo de preferencia para este equipo. Todas las instancias virtuales con preferencias similares ser\u00c3\u00a1n los primeros asignados a este equipo antes de elegir otro. message.update.ssl=Por favor, env\u00c3\u00ade una nueva X.509 compatible con certificado SSL que se actualizar\u00c3\u00a1 a cada instancia virtual de la consola del servidor proxy\: +message.validate.invalid.characters=Se han hallado caracteres no v\u00e1lidos. Por favor, corr\u00edjalos. message.virtual.network.desc=Una red dedicada virtualizados para su cuenta. El dominio de difusi\u00c3\u00b3n est\u00c3\u00a1 contenida dentro de una VLAN y todos los acceso a la red p\u00c3\u00bablica se encamina a cabo por un router virtual. message.vm.create.template.confirm=Crear plantilla de la m\u00c3\u00a1quina virtual se reiniciar\u00c3\u00a1 autom\u00c3\u00a1ticamente. message.volume.create.template.confirm=Por favor, confirme que desea crear una plantilla para este volumen de disco. Creaci\u00c3\u00b3n de la plantilla puede oscilar entre varios minutos m\u00c3\u00a1s, dependiendo del tama\u00c3\u00b1o del volumen. diff --git a/client/WEB-INF/classes/resources/messages_fr_FR.properties b/client/WEB-INF/classes/resources/messages_fr_FR.properties index db624221ddf..42335bc7b45 100644 --- a/client/WEB-INF/classes/resources/messages_fr_FR.properties +++ b/client/WEB-INF/classes/resources/messages_fr_FR.properties @@ -641,6 +641,7 @@ label.lang.arabic=Arabe label.lang.brportugese=Portuguais Br\u00e9sil label.lang.catalan=Catalan label.lang.chinese=Chinois (simplifi\u00e9) +label.lang.dutch=N\u00e9erlandais label.lang.english=Anglais label.lang.french=Fran\u00e7ais label.lang.german=Allemand @@ -648,6 +649,7 @@ label.lang.italian=Italien label.lang.japanese=Japonais label.lang.korean=Cor\u00e9en label.lang.norwegian=Norv\u00e9gien +label.lang.polish=Polonais label.lang.russian=Russe label.lang.spanish=Espagnol label.last.disconnected=Derni\u00e8re D\u00e9connexion diff --git a/client/WEB-INF/classes/resources/messages_ja.properties b/client/WEB-INF/classes/resources/messages_ja_JP.properties similarity index 100% rename from client/WEB-INF/classes/resources/messages_ja.properties rename to client/WEB-INF/classes/resources/messages_ja_JP.properties diff --git a/client/WEB-INF/classes/resources/messages_nl_NL.properties b/client/WEB-INF/classes/resources/messages_nl_NL.properties new file mode 100644 index 00000000000..b1bfadb42af --- /dev/null +++ b/client/WEB-INF/classes/resources/messages_nl_NL.properties @@ -0,0 +1,1216 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +changed.item.properties=Item eigenschappen gewijzigd +confirm.enable.s3=Vul de volgende informatie in om ondersteuning voor S3-aangestuurde Secundaire Opslag te activeren +confirm.enable.swift=Vul de volgende informatie in om ondersteuning voor Swift te activeren +error.could.not.enable.zone=Kon zone niet activeren +error.installWizard.message=Er ging iets mis; je kunt teruggaan om de eventuele fouten te herstellen +error.invalid.username.password=Ongeldige gebruikersnaam of wachtwoord +error.login=Uw gebruikersnaam/wachtwoord komt niet overeen met onze gegevens +error.menu.select=Kan actie niet uitvoeren omdat geen items zijn geselecteerd +error.mgmt.server.inaccessible=The Management Server is niet toegankelijk. Probeer het later opnieuw. +error.password.not.match=De wachtwoord velden komen niet overeen +error.please.specify.physical.network.tags=Netwerk aanbiedingen zijn niet beschikbaar totdat u labels voor het fysieke netwerk specificeert. +error.session.expired=Uw sessie is verlopen +error.something.went.wrong.please.correct.the.following=Er is iets mis gegaan; Corrigeer het volgende +error.unable.to.reach.management.server=Niet in staat om de Management Server te bereiken +error.unresolved.internet.name=Uw internet naam kan niet worden omgezet. +extractable=Uitpakbaar +force.delete.domain.warning=Waarschuwing\: Wanneer u deze optie selecteert zullen alle onderliggende domeinen, hun gekoppelde accounts en hun verbruik worden verwijderd. +force.delete=Geforceerd verwijderen +force.remove=Geforceerd loskoppelen +force.remove.host.warning=Waarschuwing\: Wanneer u deze optie selecteert zal CloudStack alle draaiende virtuele machines geforceerd stoppen voordat de host van het cluster wordt verwijderd. +force.stop=Geforceerd stoppen +force.stop.instance.warning=Waarschuwing\: Een instantie geforceerd stoppen zou uw laatste optie moeten zijn. Het kan leiden tot dataverlies en inconsistent gedrag van de staat van de virtuele machine. +ICMP.code=ICMP Code +ICMP.type=ICMP Type +image.directory=Afbeelding Directory +inline=Inline +instances.actions.reboot.label=Herstart instantie +label.accept.project.invitation=Accepteer project uitnodiging +label.account=Account +label.account.and.security.group=Account, Security group +label.account.id=Account ID +label.account.name=Account Naam +label.accounts=Accounts +label.account.specific=Account-specifiek +label.acquire.new.ip=Bemachtig nieuw IP +label.action.attach.disk.processing=Schijf wordt toegevoegd.... +label.action.attach.disk=Schijf toevoegen +label.action.attach.iso=ISO toevoegen +label.action.attach.iso.processing=ISO wordt toegevoegd.... +label.action.cancel.maintenance.mode=Annuleer Onderhoudsmodus +label.action.cancel.maintenance.mode.processing=Onderhoudsmodus wordt geannuleerd.... +label.action.change.password=Wijzig Wachtwoord +label.action.change.service.processing=Service wordt gewijzigd.... +label.action.change.service=Wijzig Service +label.action.copy.ISO=Kopieer ISO +label.action.copy.ISO.processing=Kopi\u00ebren ISO.... +label.action.copy.template=Kopieer Template +label.action.copy.template.processing=Bezig met kopi\u00ebren Template.... +label.action.create.template=Cre\u00eber Template +label.action.create.template.from.vm=Cre\u00eber Template vanaf VM +label.action.create.template.from.volume=Cre\u00eber Template van Volume +label.action.create.template.processing=Bezig met aanmaken Template.... +label.action.create.vm=Cre\u00eber VM +label.action.create.vm.processing=Bezig met aanmaken VM.... +label.action.create.volume=Cre\u00eber Volume +label.action.create.volume.processing=Bezig met cre\u00ebren volume.... +label.action.delete.account.processing=Bezig met verwijderen account.... +label.action.delete.account=Verwijder account +label.action.delete.cluster.processing=Bezig met verwijderen van Cluster.... +label.action.delete.cluster=Verwijder Cluster +label.action.delete.disk.offering.processing=Bezig met verwijderen van Schijf Aanbieding.... +label.action.delete.disk.offering=Verwijder Schijf Aanbieding +label.action.delete.domain.processing=Bezig met verwijderen van Domein.... +label.action.delete.domain=Verwijder Domein +label.action.delete.firewall.processing=Bezig met verwijderen van Firewall.... +label.action.delete.firewall=Verwijder firewall regel +label.action.delete.ingress.rule.processing=Bezig met verwijderen van Inkomende Regel.... +label.action.delete.ingress.rule=Verwijder Inkomende Regel +label.action.delete.IP.range.processing=Bezig met verwijderen van IP Range.... +label.action.delete.IP.range=Verwijder IP Range +label.action.delete.ISO.processing=Bezig met verwijderen van ISO.... +label.action.delete.ISO=Verwijder ISO +label.action.delete.load.balancer.processing=Bezig met verwijderen van Load Balancer.... +label.action.delete.load.balancer=Verwijder load balancer regel +label.action.delete.network.processing=Bezig met verwijderen van Netwerk.... +label.action.delete.network=Verwijder Netwerk +label.action.delete.nexusVswitch=Verwijder Nexus 1000v +label.action.delete.physical.network=Verwijder fysiek netwerk +label.action.delete.pod.processing=Bezig met verwijderen van Pod.... +label.action.delete.pod=Verwijder Pod +label.action.delete.primary.storage.processing=Bezig met verwijderen van Primaire Opslag.... +label.action.delete.primary.storage=Verwijder Primaire Opslag +label.action.delete.secondary.storage.processing=Bezig met verwijderen van Secundaire Opslag.... +label.action.delete.secondary.storage=Verwijder Secundaire Opslag +label.action.delete.security.group.processing=Bezig met verwijderen van Security Group.... +label.action.delete.security.group=Verwijder Security Group +label.action.delete.service.offering.processing=Bezig met verwijderen van Service Aanbieding.... +label.action.delete.service.offering=Verwijder Service Aanbieding +label.action.delete.snapshot.processing=Bezig met verwijderen van Snapshot.... +label.action.delete.snapshot=Verwijder Snapshot +label.action.delete.system.service.offering=Verwijder Systeem Service Aanbieding +label.action.delete.template.processing=Bezig met verwijderen van Template.... +label.action.delete.template=Verwijder Template +label.action.delete.user.processing=Bezig met verwijderen Gebruiker.... +label.action.delete.user=Verwijder Gebruiker +label.action.delete.volume.processing=Bezig met verwijderen van Volume.... +label.action.delete.volume=Verwijder Volume +label.action.delete.zone.processing=Bezig met verwijderen van Zone.... +label.action.delete.zone=Verwijder Zone +label.action.destroy.instance.processing=Bezig met vernietigen van Instantie.... +label.action.destroy.instance=Verwijder Instantie +label.action.destroy.systemvm.processing=Bezig met vernietigen van Systeem VM.... +label.action.destroy.systemvm=Vernietig Systeem VM +label.action.detach.disk=Ontkoppel Schijf +label.action.detach.disk.processing=Bezig met ontkoppelen van Schijf.... +label.action.detach.iso=Ontkoppel ISO +label.action.detach.iso.processing=Bezig met ontkoppelen van ISO.... +label.action.disable.account=Deactiveer account +label.action.disable.account.processing=Bezig met deactiveren van account.... +label.action.disable.cluster=Deactiveer Cluster +label.action.disable.cluster.processing=Bezig met deactiveren van Cluster.... +label.action.disable.nexusVswitch=Deactiveer Nexus 1000v +label.action.disable.physical.network=Deactiveer fysiek netwerk +label.action.disable.pod=Deactiveer Pod +label.action.disable.pod.processing=Bezig met deactiveren van Pod.... +label.action.disable.static.NAT=Deactiveer Static NAT +label.action.disable.static.NAT.processing=Bezig met deactiveren van Static NAT.... +label.action.disable.user=Deactiveer Gebruiker +label.action.disable.user.processing=Bezig met deactiveren van Gebruiker.... +label.action.disable.zone=Deactiveer Zone +label.action.disable.zone.processing=Bezig met deactiveren van Zone.... +label.action.download.ISO=Download ISO +label.action.download.template=Download Template +label.action.download.volume=Download Volume +label.action.download.volume.processing=Bezig met downloaden van Volume.... +label.action.edit.account=Wijzig account +label.action.edit.disk.offering=Wijzig schijf aanbieding +label.action.edit.domain=Wijzig Domein +label.action.edit.global.setting=Wijzig Algemene Instellingen +label.action.edit.host=Wijzig Host +label.action.edit.instance=Wijzig Instantie +label.action.edit.ISO=Wijzig ISO +label.action.edit.network.offering=Wijzig Netwerk Aanbieding +label.action.edit.network.processing=Bezig met wijzigen van Netwerk... +label.action.edit.network=Wijzig Netwerk +label.action.edit.pod=Wijzig Pod +label.action.edit.primary.storage=Wijzig Primaire Opslag +label.action.edit.resource.limits=Wijzig verbruikslimieten +label.action.edit.service.offering=Wijzig Service Aanbieding +label.action.edit.template=Wijzig Template +label.action.edit.user=Wijzig Gebruiker +label.action.edit.zone=Wijzig Zone +label.action.enable.account=Activeer account +label.action.enable.account.processing=Bezig met activeren van account.... +label.action.enable.cluster=Activeer Cluster +label.action.enable.cluster.processing=Bezig met activeren van Cluster.... +label.action.enable.maintenance.mode=Activeer onderhoudsmodus +label.action.enable.maintenance.mode.processing=Bezig met activeren van Onderhoudsmodus +label.action.enable.nexusVswitch=Activeer Nexus 1000v +label.action.enable.physical.network=Activeer fysiek netwerk +label.action.enable.pod=Activeer Pod +label.action.enable.pod.processing=Bezig met activeren van Pod.... +label.action.enable.static.NAT=Activeer Static NAT +label.action.enable.static.NAT.processing=Bezig met activeren van Static NAT.... +label.action.enable.user=Activeer Gebruiker +label.action.enable.user.processing=Bezig met activeren van Gebruiker.... +label.action.enable.zone=Activeer Zone +label.action.enable.zone.processing=Bezig met activeren van Zone.... +label.action.force.reconnect=Forceer opnieuw verbinden +label.action.force.reconnect.processing=Bezig met opnieuw verbinden.... +label.action.generate.keys=Genereer Sleutels +label.action.generate.keys.processing=Bezig met generen van Sleutels.... +label.action.list.nexusVswitch=Toon Nexus 1000v +label.action.lock.account=Account op slot zetten +label.action.lock.account.processing=Bezig met account op slot zetten.... +label.action.manage.cluster=Beheer Cluster +label.action.manage.cluster.processing=Bezig met beheren van Cluster.... +label.action.migrate.instance=Migreer Instantie +label.action.migrate.instance.processing=Bezig met migreren van Instantie.... +label.action.migrate.router=MIgreer Router +label.action.migrate.router.processing=Bezig met migreren van Router.... +label.action.migrate.systemvm=Migreer Systeem VM +label.action.migrate.systemvm.processing=Bezig met migreren van Systeem VM.... +label.action.reboot.instance=Herstart Instantie +label.action.reboot.instance.processing=Bezig met herstarten van Instantie.... +label.action.reboot.router=Herstart Router +label.action.reboot.router.processing=Bezig met herstarten van Router.... +label.action.reboot.systemvm=Herstart Systeem VM +label.action.reboot.systemvm.processing=Bezig met herstarten van Systeem VM.... +label.action.recurring.snapshot=Terugkerende Snapshots +label.action.register.iso=Registreer ISO +label.action.register.template=Registreer Template +label.action.release.ip=Ontkoppel IP +label.action.release.ip.processing=Bezig met ontkoppelen van IP.... +label.action.remove.host.processing=Bezig met verwijderen van Host.... +label.action.remove.host=Verwijder Host +label.action.reset.password.processing=Bezig met resetten van wachtwoord.... +label.action.reset.password=Reset Wachtwoord +label.action.resize.volume.processing=Bezig met aanpassen van de grootte van het Volume +label.action.resize.volume=Wijzig de grootte van het volume +label.action.resource.limits=Verbruikslimieten +label.action.restore.instance=Herstel Instantie +label.action.restore.instance.processing=Bezig met herstellen van Instantie.... +label.actions=Acties +label.action.start.instance.processing=Bezig met starten van Instantie.... +label.action.start.instance=Start Instantie +label.action.start.router.processing=Start Router.... +label.action.start.router=Start Router +label.action.start.systemvm.processing=Bezig met starten van Systeem VM.... +label.action.start.systemvm=Start Systeem VM +label.action.stop.instance.processing=Bezig met stoppen van Instantie.... +label.action.stop.instance=Stop Instantie +label.action.stop.router.processing=Bezig met stoppen van Router.... +label.action.stop.router=Stop Router +label.action.stop.systemvm.processing=Bezig met stoppen van Systeem VM.... +label.action.stop.systemvm=Stop Systeem VM +label.action.take.snapshot=Neem Snapshot +label.action.take.snapshot.processing=Bezig met nemen van Snapshot.... +label.action.unmanage.cluster.processing=Bezig met uitschakelen van Clusterbeheer.... +label.action.unmanage.cluster=Schakel Clusterbeheer uit +label.action.update.OS.preference.processing=Bezig met wijzigen van OS voorkeuren.... +label.action.update.OS.preference=Wijzig OS voorkeuren +label.action.update.resource.count.processing=Bezig met updaten van verbruikslimieten.... +label.action.update.resource.count=Update Verbruikslimieten +label.action.vmsnapshot.create=Neem Snapshot van de VM +label.action.vmsnapshot.delete=Verwijder Snapshot van de VM +label.action.vmsnapshot.revert=Draai Snapshot van de VM terug +label.activate.project=Activeer Project +label.active.sessions=Actieve Sessies +label.add.accounts.to=Voeg accounts toe aan +label.add.accounts=Voeg accounts toe +label.add.account.to.project=Voeg account aan project toe +label.add.account=Voeg Account toe +label.add.ACL=Voeg ACL toe +label.add.BigSwitchVns.device=Voeg BigSwitch Vns Controller toe +label.add.by.cidr=Voeg toe door middel van CIDR +label.add.by.group=Voeg toe door middel van Groep +label.add.by=Voeg toe door middel van +label.add.cluster=Voeg Cluster toe +label.add.compute.offering=Voeg Compute aanbieding toe +label.add.direct.iprange=Voeg Direct IP Range toe +label.add.disk.offering=Voeg Schijf Aanbieding toe +label.add.domain=Voeg Domein toe +label.add.egress.rule=Voeg uitgaande regel toe +label.add.F5.device=Voeg F5 apparaat toe +label.add.firewall=Voeg firewall regel toe +label.add.guest.network=Gast netwerk toevoegen +label.add.host=Host toevoegen +label.adding.cluster=Bezig met toevoegen van Cluster +label.adding.failed=Toevoegen mislukt +label.adding.pod=Bezig met toevoegen van Pod +label.adding.processing=Toevoegen.... +label.add.ingress.rule=Voeg inkomende regel toe +label.adding.succeeded=Toevoegen geslaagd +label.adding=Toevoegen +label.adding.user=Bezig met toevoegen van Gebruiker +label.adding.zone=Bezig met toevoegen van Zone +label.add.ip.range=Voeg IP range toe +label.additional.networks=Additioneele Netwerken +label.add.load.balancer=Voeg Load Balancer toe +label.add.more=Voeg meer toe +label.add.netScaler.device=Voeg Netscaler apparaat toe +label.add.network.ACL=Voeg netwerk ACL toe +label.add.network.device=Voeg Netwerk Apparaat toe +label.add.network.offering=Voeg netwerk aanbieding toe +label.add.network=Voeg Netwerk toe +label.add.new.F5=Voeg nieuwe F5 toe +label.add.new.gateway=Voeg nieuwe gateway toe +label.add.new.NetScaler=Voeg nieuwe Netscaler toe +label.add.new.SRX=Voeg nieuwe SRX toe +label.add.new.tier=Voeg nieuwe Tier toe +label.add.NiciraNvp.device=Voeg NVP Controller toe +label.add.physical.network=Voeg fysiek netwerk toe +label.add.pod=Voeg Pod toe +label.add.port.forwarding.rule=Voeg port forwarding regel toe +label.add.primary.storage=Voeg Primaire Opslag toe +label.add.region=Voeg Regio toe +label.add.resources=Resources toevoegen +label.add.route=Route toevoegen +label.add.rule=Regel toevoegen +label.add.secondary.storage=Secundaire Opslag toevoegen +label.add.security.group=Security Group toevoegen +label.add.service.offering=Service Aanbieding toevoegen +label.add.SRX.device=SRX apparaat toevoegen +label.add.static.nat.rule=Statische NAT regel toevoegen +label.add.static.route=Statische route toevoegen +label.add.system.service.offering=Systeem Service Aanbieding toevoegen +label.add.template=Template toevoegen +label.add.to.group=Toevoegen aan groep +label.add.user=Gebruiker toevoegen +label.add.vlan=VLAN toevoegen +label.add.vms.to.lb=Voeg VM(s) toe aan load balancer regel +label.add.vms=VMs toevoegen +label.add.VM.to.tier=Voeg VM toe aan tier +label.add.vm=VM toevoegen +label.add=Voeg toe +label.add.volume=Volume toevoegen +label.add.vpc=VPC toevoegen +label.add.vpn.customer.gateway=VPN Customer Gateway toevoegen +label.add.VPN.gateway=VPN Gateway toevoegen +label.add.vpn.user=VPN gebruiker toevoegen +label.add.zone=Zone toevoegen +label.admin.accounts=Beheer Accounts +label.admin=Beheerder +label.advanced=Geavanceerd +label.advanced.mode=Geavanceerde Modus +label.advanced.search=Geavanceerd zoeken +label.agent.password=Agent wachtwoord +label.agent.username=Agent Gebruikersnaam +label.agree=Accepteren +label.alert=Alarm +label.algorithm=Algoritme +label.allocated=Gebruikt +label.allocation.state=Verbruik Staat +label.api.key=API Sleutel +label.apply=Uitvoeren +label.assign=Toevoegen +label.assign.to.load.balancer=Voeg instantie toe aan load balancer +label.associated.network=Bijbehorend Netwerk +label.associated.network.id=Bijbehorend Netwerk ID +label.attached.iso=Gekoppelde ISO +label.author.email=Auteur e-mail +label.author.name=Auteur naam +label.availability=Beschikbaarheid +label.availability.zone=Beschikbaarheids-zone +label.available=Beschikbaar +label.available.public.ips=Beschikbare Publieke IP adressen +label.back=Terug +label.bandwidth=Bandbreedte +label.basic=Basis +label.basic.mode=Basis Modus +label.bigswitch.controller.address=BigSwitch Vns Controller Adres +label.bootable=Bootable +label.broadcast.domain.range=Broadcast domain range +label.broadcast.domain.type=Broadcast Domain Type +label.broadcast.uri=Broadcast URI +label.by.account=Op Account +label.by.availability=Op Beschikbaarheid +label.by.domain=Op Domein +label.by.end.date=Op Eind Datum +label.by.level=Op Level +label.by.pod=Op Pod +label.by.role=Op Rol +label.by.start.date=Op Start Datum +label.by.state=Op Staat +label.bytes.received=Bytes Ontvangen +label.bytes.sent=Bytes Verzonden +label.by.traffic.type=Op Verkeerstype +label.by.type.id=Op Type ID +label.by.type=Op Type +label.by.zone=Op Zone +label.cancel=Annuleer +label.capacity=Capaciteit +label.certificate=Certificaat +label.change.service.offering=Wijzig service aanbieding +label.change.value=Wijzig waarde +label.character=Karakter +label.checksum=MD5 checksum +label.cidr.account=CIDRN of Account/Security Group +label.cidr=CIDR +label.cidr.list=Bron CIDR +label.CIDR.list=CIDR lijst +label.CIDR.of.destination.network=CIDR van bestemmingsnetwerk +label.clean.up=Opschonen +label.clear.list=Schoon lijst op +label.close=Sluiten +label.cloud.console=Cloud Beheers Console +label.cloud.managed=Cloud.com Managed +label.cluster=Cluster +label.cluster.name=Cluster Naam +label.clusters=Clusters +label.cluster.type=Cluster Type +label.clvm=CLVM +label.code=Code +label.community=Community +label.compute.and.storage=Compute en Opslag +label.compute=Compute +label.compute.offering=Compute aanbieding +label.configuration=Configuratie +label.configure=Configureer +label.configure.network.ACLs=Configureer Netwerk ACLs +label.configure.vpc=Configureer VPC +label.confirmation=Bevestiging +label.confirm.password=Bevestig wachtwoord +label.congratulations=Gefeliciteerd\! +label.conserve.mode=Conserveer modus +label.console.proxy=Console proxy +label.continue.basic.install=Ga door met basis installatie +label.continue=Ga door +label.corrections.saved=Correcties opgeslagen +label.cpu.allocated=CPU gebruik +label.cpu.allocated.for.VMs=CPU gebruikt voor VMs +label.CPU.cap=CPU Cap +label.cpu=CPU +label.cpu.limits=CPU limieten +label.cpu.mhz=CPU (in MHz) +label.cpu.utilized=CPU Verbruik +label.created=Aangemaakt +label.created.by.system=Aangemaakt door systeem +label.create.project=Nieuw project +label.create.template=Nieuwe template +label.create.VPN.connection=Nieuwe VPN connectie +label.cross.zones=Over Zones +label.custom.disk.size=Vrije schijf grootte +label.daily=Dagelijkse +label.data.disk.offering=Data Schijf Aanbieding +label.date=Datum +label.day.of.month=Dag van de Maand +label.day.of.week=Dag van de Week +label.dead.peer.detection=Dead Peer detectie +label.decline.invitation=Sla uitnodiging af +label.dedicated=Dedicated +label.default=Standaard +label.default.use=Standaard Gebruik +label.default.view=Standaard Weergave +label.delete.BigSwitchVns=Verwijder BigSwitch Vns Controller +label.delete.F5=Verwijder F5 +label.delete.gateway=Verwijder gateway +label.delete.NetScaler=Verwijder NetScaler +label.delete.NiciraNvp=Verwijder Nvp Controller +label.delete.project=Verwijder project +label.delete.SRX=Verwijder SRX +label.delete=Verwijder +label.delete.VPN.connection=Verwijder VPN connectie +label.delete.VPN.customer.gateway=Verwijder VPN Customer Gateway +label.delete.VPN.gateway=Verwijder VPN Gateway +label.delete.vpn.user=Verwijder VPN gebruiker +label.deleting.failed=Verwijderen Mislukt +label.deleting.processing=Verwijderen.... +label.description=Beschrijving +label.destination.physical.network.id=Bestemming fysiek netwerk ID +label.destination.zone=Bestemmingszone +label.destroy.router=Verwijder router +label.destroy=Verwijder +label.detaching.disk=Ontkoppelen Schijf +label.details=Details +label.device.id=Apparaat ID +label.devices=Apparaten +label.dhcp=DHCP +label.DHCP.server.type=DHCP Server Type +label.direct.ips=Shared Netwerk IPs +label.disabled=Uitgeschakeld +label.disable.provider=Provider uitschakelen +label.disable.vpn=VPN uitschakelen +label.disabling.vpn.access=Uitschakelen van VPN Toegang +label.disk.allocated=Schijfruimte gealloceerd +label.disk.offering=Schijf Aanbieding +label.disk.size.gb=Schijf Grootte (in GB) +label.disk.size=Schijf Grootte +label.disk.total=Schijf Totaal +label.disk.volume=Schijf Volume +label.display.name=Weergavenaam +label.display.text=Weergavetekst +label.dns.1=DNS 1 +label.dns.2=DNS 2 +label.dns=DNS +label.DNS.domain.for.guest.networks=DNS domein voor Gast Netwerken +label.domain.admin=Domein Beheerder +label.domain=Domein +label.domain.id=Domein ID +label.domain.name=Domeinnaam +label.domain.router=Domein router +label.domain.suffix=DNS domein achtervoegsel (v.b., xyz.com) +label.done=Klaar +label.double.quotes.are.not.allowed=Aanhalingstekens zijn hier niet toegestaan +label.download.progress=Download Voortgang +label.drag.new.position=Sleep naar nieuwe positie +label.edit.lb.rule=Wijzig LB regel +label.edit.network.details=Wijzig netwerk details +label.edit.project.details=Wijzig project details +label.edit.tags=Wijzig tags +label.edit.traffic.type=Wijzig traffic type +label.edit.vpc=Wijzig VPC +label.edit=Wijzig +label.egress.rules=Uitgaande regels +label.egress.rule=Uitgaande regel +label.elastic=Elastisch +label.elastic.IP=Elastisch IP +label.elastic.LB=Elastisch LB +label.email=Email +label.enable.provider=Provider inschakelen +label.enable.s3=S3-gebaseerde Secondary Storage inschakelen +label.enable.swift=Swift inschakelen +label.enable.vpn=VPN inschakelen +label.enabling.vpn.access=VPN toegang inschakelen +label.enabling.vpn=VPN inschakelen +label.end.IP=Eind IP +label.endpoint=Endpoint +label.endpoint.or.operation=Endpoint or Operation +label.end.port=Eind Poort +label.end.reserved.system.IP=Einde gereserveerde systeem IP +label.end.vlan=Einde Vlan +label.enter.token=Voer token in +label.error.code=Fout code +label.error=Fout +label.ESP.encryption=ESP Encryptie +label.ESP.hash=ESP Hash +label.ESP.lifetime=ESP Lifetime (secondes) +label.ESP.policy=ESP policy +label.esx.host=ESX/ESXi Host +label.example=Voorbeeld +label.external.link=Externe link +label.f5=F5 +label.failed=Mislukt +label.featured=Voorgesteld +label.fetch.latest=Haal laatste op +label.filterBy=Filter per +label.firewall=Firewall +label.first.name=Voornaam +label.format=Formaat +label.friday=Vrijdag +label.full.path=Volledig pad +label.full=Volledig +label.gateway=Gateway +label.general.alerts=Algemene Waarschuwingen +label.generating.url=Generen van URL +label.go.step.2=Ga naar Stap 2 +label.go.step.3=Ga naar Stap 3 +label.go.step.4=Ga naar Stap 4 +label.go.step.5=Ga naar Stap 5 +label.group=Groep +label.group.optional=Groep (Optioneel) +label.guest.cidr=Gast CIDR +label.guest.end.ip=Gast eind IP +label.guest=Gast +label.guest.gateway=Gast Gateway +label.guest.ip=Gast IP Adres +label.guest.ip.range=Gast IP range +label.guest.netmask=Gast Netmask +label.guest.networks=Gast netwerken +label.guest.start.ip=Gast start IP +label.guest.traffic=Gast verkeer +label.guest.type=Gast Type +label.ha.enabled=HA ingeschakeld +label.help=Help +label.hide.ingress.rule=Verberg Inkomende Regel +label.hints=Tips +label.host.alerts=Host Waarschuwingen +label.host=Host +label.host.MAC=Host MAC +label.host.name=Hostnaam +label.hosts=Hosts +label.host.tags=Host Tags +label.hourly=Uurlijks +label.hypervisor.capabilities=Hypervisor mogelijkheden +label.hypervisor=Hypervisor +label.hypervisor.type=Hypervisor Type +label.hypervisor.version=Hypervisor versie +label.id=ID +label.IKE.DH=IKE DH +label.IKE.encryption=IKE Encryptie +label.IKE.hash=IKE Hash +label.IKE.lifetime=IKE lifetime (secondes) +label.IKE.policy=IKE policy +label.info=Info +label.ingress.rule=Inkomende Regel +label.initiated.by=Ge\u00efnitieerd door +label.installWizard.addClusterIntro.subtitle=Wat is een cluster? +label.installWizard.addClusterIntro.title=Nu\: Cluster toevoegen +label.installWizard.addHostIntro.subtitle=Wat is een host? +label.installWizard.addHostIntro.title=Nu\: Host toevoegen +label.installWizard.addPodIntro.subtitle=Wat is een pod? +label.installWizard.addPodIntro.title=Nu\: Pod toevoegen +label.installWizard.addPrimaryStorageIntro.subtitle=Wat is primary storage? +label.installWizard.addPrimaryStorageIntro.title=Nu\: Primaire opslag toevoegen +label.installWizard.addSecondaryStorageIntro.subtitle=Wat is secundaire opslag? +label.installWizard.addSecondaryStorageIntro.title=Nu\: Secundaire opslag toevoegen +label.installWizard.addZoneIntro.subtitle=Wat is een zone? +label.installWizard.addZoneIntro.title=Nu\: Zone toevoegen +label.installWizard.addZone.title=Zone toevoegen +label.installWizard.click.launch=Klik op de lanceer knop. +label.installWizard.subtitle=Deze rondleiding gaat je helpen met het uitvoeren van de CloudStack&\#8482 installatie +label.installWizard.title=Hallo en welkom bij CloudStack&\#8482 +label.instance=Instantie +label.instance.limits=Instantie Limieten +label.instance.name=Instantie Naam +label.instances=Instanties +label.internal.dns.1=Interne DNS 1 +label.internal.dns.2=Interne DNS 2 +label.internal.name=Interne naam +label.interval.type=Interval Type +label.introduction.to.cloudstack=CloudStack&\#8482 Introductie +label.invalid.integer=Onjuiste Waarde +label.invalid.number=Onjuist nummer +label.invitations=Uitnodigingen +label.invited.accounts=Uitgenodigde accounts +label.invite.to=Nodig uit voor +label.invite=Uitnodigen +label.ip.address=IP Adres +label.ipaddress=IP Adres +label.ip.allocations=IP Allocaties +label.ip=IP +label.ip.limits=Publieke IP Limieten +label.ip.or.fqdn=IP of FQDN +label.ip.range=IP Range +label.ip.ranges=IP Ranges +label.IPsec.preshared.key=IPsec Preshared-Key +label.ips=IPs +label.iscsi=iSCSI +label.is.default=Is Standaard +label.iso.boot=ISO Boot +label.iso=ISO +label.isolated.networks=Geisoleerde netwerken +label.isolation.method=Isolatie methode +label.isolation.mode=Isolatie Modus +label.isolation.uri=Isolatie URI +label.is.redundant.router=Redundant +label.is.shared=Is Gedeeld +label.is.system=Is Systeem +label.item.listing=Items lijst +label.keep=Bewaar +label.keyboard.type=Toetsenbord type +label.key=Sleutel +label.kvm.traffic.label=KVM verkeer label +label.label=Label +label.lang.brportugese=Braziliaans Portgees +label.lang.chinese=Chinees (Simplified) +label.lang.english=Engels +label.lang.french=Frans +label.lang.japanese=Japans +label.lang.korean=Koreans +label.lang.russian=Russisch +label.lang.spanish=Spaans +label.last.disconnected=Laatse keer niet verbonden +label.last.name=Achternaam +label.latest.events=Laatste gebeurtenissen +label.launch=Lanceer +label.launch.vm=Lanceer VM +label.launch.zone=Lanceer zone +label.LB.isolation=LB isolatie +label.least.connections=Minste connecties +label.level=Level +label.load.balancer=Load Balancer +label.load.balancing=Load Balancing +label.load.balancing.policies=Load balancing policies +label.loading=Laden +label.local=Lokaal +label.local.storage.enabled=Lokale opslag ingeschakeld +label.local.storage=Lokale Opslag +label.login=Login +label.logout=Log uit +label.lun=LUN +label.LUN.number=LUN \# +label.make.project.owner=Maak account project eigenaar +label.manage=Beheer +label.management=Beheer +label.management.ips=Beheers IP Adressen +label.manage.resources=Beheer Resources +label.max.cpus=Max. CPU cores +label.max.guest.limit=Max. Instanties +label.maximum=Maximaal +label.max.memory=Max. geheugen (MiB) +label.max.networks=Max. netwerken +label.max.primary.storage=Max. primare opslag (GiB) +label.max.public.ips=Max. publieke IPs +label.max.secondary.storage=Max. secundaire opslag (GiB) +label.max.snapshots=Max. snapshots +label.max.templates=Max. templates +label.max.vms=Max. VMs per gebruiker +label.max.volumes=Max. volumes +label.max.vpcs=Max. VPCs +label.may.continue=U kunt nu verder gaan. +label.memory.allocated=Geheugen Gealloceerd +label.memory=Geheugen +label.memory.limits=Geheugen limieten (MiB) +label.memory.mb=Geheugen (in MB) +label.memory.total=Totaal Geheugen +label.memory.used=Geheugen gebruikt +label.menu.accounts=Accounts +label.menu.alerts=Waarschuwingen +label.menu.all.accounts=Alle Accounts +label.menu.all.instances=Alle Instanties +label.menu.community.isos=Community ISOs +label.menu.community.templates=Community Templates +label.menu.configuration=Configuratie +label.menu.dashboard=Dashboard +label.menu.destroyed.instances=Vernietigde Instanties +label.menu.disk.offerings=Schijf Aanbiedingen +label.menu.domains=Domeinen +label.menu.events=Gebeurtenissen +label.menu.featured.isos=Voorgestelde ISOs +label.menu.featured.templates=Voorgestelde Templates +label.menu.global.settings=Algemene Instellingen +label.menu.infrastructure=Infrastructuur +label.menu.instances=Instanties +label.menu.ipaddresses=IP Adressen +label.menu.isos=ISOs +label.menu.my.accounts=Mijn Accounts +label.menu.my.instances=Mijn Instanties +label.menu.my.isos=Mijn ISOs +label.menu.my.templates=Mijn Templates +label.menu.network=Netwerk +label.menu.network.offerings=Netwerk Aanbiedingen +label.menu.physical.resources=Fysieke Resources +label.menu.regions=Regio\\'s +label.menu.running.instances=Draaiende Instanties +label.menu.security.groups=Security Groups +label.menu.service.offerings=Service Aanbiedingen +label.menu.snapshots=Snapshots +label.menu.stopped.instances=Uitgeschakelde Instanties +label.menu.storage=Opslag +label.menu.system.service.offerings=Systeem Aanbiedingen +label.menu.system=Systeem +label.menu.system.vms=Systeem VMs +label.menu.templates=Templates +label.menu.virtual.appliances=Virtueele Appliances +label.menu.virtual.resources=Virtuele Resources +label.menu.volumes=Volumes +label.migrate.instance.to.host=Migreer instantie naar andere host +label.migrate.instance.to=Migreer instantie naar +label.migrate.instance.to.ps=Migreer instantie naar andere primaire opslag +label.migrate.router.to=Migreer Router naar +label.migrate.systemvm.to=Migreer Systeem VM naar +label.migrate.to.host=Migreer naar host +label.migrate.to.storage=Migreer naar opslag +label.migrate.volume=Migreer volume naar andere primaire opslag +label.minimum=Minimum +label.minute.past.hour=Minuten na het uur +label.monday=Maandag +label.monthly=Maandelijks +label.more.templates=Meer Templates +label.move.down.row=Verplaats \u00e9\u00e9n regel naar beneden +label.move.to.bottom=Verplaats naar beneden +label.move.to.top=Verplaats naar boven +label.move.up.row=Verplaats \u00e9\u00e9n regel naar boven +label.my.account=Mijn Account +label.my.network=Mijn netwerk +label.my.templates=Mijn templates +label.name=Naam +label.name.optional=Naam (Optioneel) +label.nat.port.range=NAT Poort Range +label.netmask=Netmask +label.netScaler=NetScaler +label.network.ACL=Netwerk ACL +label.network.ACLs=Netwerk ACLs +label.network.ACL.total=Netwerk ACL Totaal +label.network.desc=Netwerk Beschr. +label.network.device=Netwerk Apparaat +label.network.device.type=Netwerk Apparaat Type +label.network.domain=Netwerk Domein +label.network.domain.text=Netwerk Domein +label.network.id=Netwerk ID +label.networking.and.security=Netwerken en beveiliging +label.network.label.display.for.blank.value=Gebruik standaard gateway +label.network.name=Netwerk Naam +label.network=Netwerk +label.network.offering.display.text=Netwerk Aanbieding Weergave Tekst +label.network.offering.id=Netwerk Aanbieding ID +label.network.offering.name=Netwerk Aanbieding Naam +label.network.offering=Netwerk Aanbieding +label.network.read=Netwerk gelezen +label.network.service.providers=Netwerk Service Aanbieders +label.networks=Netwerken +label.network.type=Netwerk Type +label.network.write=Netwerk geschreven +label.new=Nieuw +label.new.password=Nieuw wachtwoord +label.new.project=Nieuw Project +label.new.vm=Nieuwe VM +label.next=Volgende +label.nexusVswitch=Nexus 1000v +label.nfs=NFS +label.nfs.server=NFS Server +label.nfs.storage=NFS Opslag +label.nic.adapter.type=NIC adapter type +label.nicira.controller.address=Controller Adres +label.nicira.l3gatewayserviceuuid=L3 Gateway Service Uuid +label.nicira.transportzoneuuid=Transport Zone Uuid +label.nics=NICs +label.no.actions=Geen Beschikbare Acties +label.no.alerts=Geen Recente Waarschuwingen +label.no.data=Geen data om weer te geven +label.no.errors=Geen Recente Fouten +label.no.isos=Geen beschikbare ISOs +label.no.items=Geen Beschikbare Items +label.no=Nee +label.none=Geen +label.no.security.groups=Geen Beschikbare Security Groups +label.not.found=Niet gevonden +label.no.thanks=Nee bedankt +label.notifications=Notificaties +label.number.of.clusters=Aantal Clusters +label.number.of.hosts=Aantal Hosts +label.number.of.pods=Aantal Pods +label.number.of.system.vms=Aantal Systeem VMs +label.number.of.virtual.routers=Aantal Virtual Routers +label.number.of.zones=Aantal Zones +label.num.cpu.cores=Aantal CPU Cores +label.numretries=Keren opnieuw geprorbeerd +label.ocfs2=OCFS2 +label.offer.ha=HA aanbieden +label.ok=OK +label.optional=Optioneel +label.order=Volgorde +label.os.preference=OS Voorkeur +label.os.type=OS Type +label.owned.public.ips=Publieke IP Adressen in beheer +label.owner.account=Account Eigenaar +label.owner.domain=Domein Eigenaar +label.parent.domain=Bovenliggend Domein +label.password.enabled=Wachtwoord Ingeschakeld +label.password=Wachtwoord +label.path=Pad +label.perfect.forward.secrecy=Perfect Forward Secrecy +label.physical.network=Fysiek Netwerk +label.physical.network.ID=Fysiek netwerk ID +label.PING.CIFS.password=PING CIFS wachtwoord +label.PING.CIFS.username=PING CIFS gebruikersnaam +label.PING.dir=PING Directory +label.PING.storage.IP=PING opslag IP +label.please.specify.netscaler.info=Geef hier informatie van de Netscaler op +label.please.wait=Een ogenblik geduld a.u.b. +label.plugin.details=Plugin details +label.plugins=Plugins +label.pod.name=Pod Naam +label.pod=Pod +label.pods=Pods +label.port.forwarding.policies=Port forwarding policies +label.port.forwarding=Port Forwarding +label.port.range=Port Range +label.PreSetup=PreSetup +label.previous=Vorige +label.prev=Terug +label.primary.allocated=Primaire Opslag Gealloceerd +label.primary.network=Primair Netwerk +label.primary.storage.count=Primaire Opslag Pools +label.primary.storage.limits=Primaire Opslag limieten (GiB) +label.primary.storage=Primaire Opslag +label.primary.used=Primaire Opslag Gebruikt +label.private.Gateway=Priv\u00e9 Gateway +label.private.interface=Priv\u00e9 Interface +label.private.ip=Priv\u00e9 IP Adres +label.private.ip.range=Priv\u00e9 IP Range +label.private.ips=Priv\u00e9 IP adressen +label.privatekey=PKCS\#8 Private Key +label.private.network=Priv\u00e9 Netwerk +label.private.port=Priv\u00e9 Port +label.private.zone=Priv\u00e9 Zone +label.project.dashboard=Project Dashboard +label.project.id=Project ID +label.project.invite=Nodig uit voor project +label.project.name=Project naam +label.project=Project +label.projects=Projecten +label.project.view=Project Weergave +label.protocol=Protocol +label.providers=Providers +label.public.interface=Publieke Interface +label.public.ip=Publiek IP Adres +label.public.ips=Publieke IP Adressen +label.public.network=Publiek netwerk +label.public.port=Publieke Poort +label.public=Publiek +label.public.traffic=Publiek verkeer +label.public.zone=Publieke Zone +label.purpose=Doel +label.Pxe.server.type=PXE Server Type +label.quickview=Sneloverzicht +label.reboot=Reboot +label.recent.errors=Recente Fouten +label.redundant.router.capability=Redundante router mogelijkheden +label.redundant.router=Redundante Router +label.redundant.state=Redundante staat +label.refresh=Ververs +label.region=Regio +label.related=Samenhangend +label.remind.later=Herinner me later +label.remove.ACL=Verwijder ACL +label.remove.egress.rule=Verwijder uitgaande regel +label.remove.from.load.balancer=Verwijder Instantie van load balancer +label.remove.ingress.rule=Verwijder inkomende regel +label.remove.ip.range=Verwijder IP range +label.remove.pf=Verwijder port forwarding regel +label.remove.project.account=Verwijder account van project +label.remove.region=Verwijder Regio +label.remove.rule=Verwijder regel +label.remove.static.nat.rule=Verwijder static NAT regel +label.remove.static.route=Verwijder statische route +label.remove.tier=Verwijder tier +label.remove.vm.from.lb=Verwijder VM van load balancer regel +label.remove.vpc=verwijder VPC +label.removing.user=Verwijderen Gebruiker +label.removing=Verwijderen +label.required=Vereist +label.reserved.system.gateway=Gereseveerde systeem gateway +label.reserved.system.ip=Gereserveerd Systeem IP +label.reserved.system.netmask=Gereserveerd systeem netmask +label.reset.VPN.connection=Reset VPN verbinding +label.resize.new.offering.id=Nieuwe Aanbieding +label.resize.new.size=Nieuwe Grootte(GB) +label.resize.shrink.ok=Verklein OK +label.resource.limits=Verbruikslimieten +label.resource.state=Verbruik staat +label.resources=Verbruiken +label.resource=Verbruik +label.restart.network=Herstart netwerk +label.restart.required=Herstart benodigd +label.restart.vpc=herstart VPC +label.restore=Herstel +label.review=Beoordeel +label.revoke.project.invite=Trek uitnodiging in +label.role=Rol +label.root.disk.controller=Root schijf controller +label.root.disk.offering=Root Schijf Aanbieding +label.round.robin=Round-robin +label.rules=Regels +label.running.vms=Draaiende VMs +label.s3.access_key=Toegangssleutel +label.s3.bucket=Bucket +label.s3.connection_timeout=Connectie Timeout +label.s3.endpoint=Endpoint +label.s3.max_error_retry=Max. opnieuw proberen na Fout +label.s3.secret_key=Geheime sleutel +label.s3.socket_timeout=Socket Timeout +label.s3.use_https=Gebruik HTTPS +label.saturday=Zaterdag +label.save.and.continue=Opslaan en verder gaan +label.save=Opslaan +label.saving.processing=Opslaan.... +label.scope=Scope +label.search=Zoeken +label.secondary.storage.count=Secundaire Opslag Pools +label.secondary.storage.limits=Secundaire Opslag limieten (GiB) +label.secondary.storage=Secundaire Opslag +label.secondary.storage.vm=Secundaire Opslag VM +label.secondary.used=Secundaire Opslag Gebruikt +label.secret.key=Geheime sleutel +label.security.group.name=Security Group Naam +label.security.group=Security Group +label.security.groups.enabled=Security Groups Ingeschakeld +label.security.groups=Security Groups +label.select.a.template=Selecteer een template +label.select.a.zone=Selecteer een zone +label.select.instance=Selecteer een instance +label.select.instance.to.attach.volume.to=Selecteer een instance om het volume aan te koppelen +label.select.iso.or.template=Selecteer een ISO of template +label.select.offering=Selecteer Aanbieding +label.select.project=Selecteer Project +label.select=Selecteer +label.select.tier=Selecteer Tier +label.select-view=Selecteer Weergave +label.select.vm.for.static.nat=Selecteer VM voor static NAT +label.sent=Verstuurd +label.server=Server +label.service.capabilities=Service Mogelijkheden +label.service.offering=Service Aanbieding +label.session.expired=Sessie Verlopen +label.setup=Instellen +label.setup.network=Stel Netwerk in +label.setup.zone=Stel Zone in +label.set.up.zone.type=Stel zone type in +label.shared=Gedeeld +label.SharedMountPoint=SharedMountPoint +label.show.ingress.rule=Toon Inkomende Regel +label.shutdown.provider=Schakel provider uit +label.site.to.site.VPN=Site-to-site VPN +label.size=Grootte +label.skip.guide=Ik heb CloudStack al eerder gebruikt, sla deze stap over +label.snapshot.limits=Snapshot Limieten +label.snapshot.name=Snapshot Naam +label.snapshot.schedule=Stel herhalende Snapshot in +label.snapshot=Snapshot +label.snapshot.s=Snapshot (s) +label.snapshots=Snapshots +label.source=Bron +label.source.nat=Source NAT +label.specify.IP.ranges=Specificeer IP ranges +label.specify.vlan=Specificeer VLAN +label.SR.name = SR Name-Label +label.srx=SRX +label.start.IP=Start IP +label.start.port=Start Poort +label.start.reserved.system.IP=Start gereseveerd systeem IP +label.start.vlan=Start VLAN +label.state=Staat +label.static.nat.enabled=Static NAT Ingeschakeld +label.static.nat=Static NAT +label.static.nat.to=Static NAT naar +label.static.nat.vm.details=Static NAT VM Details +label.statistics=Statistieken +label.status=Status +label.step.1=Stap 1 +label.step.1.title=Stap 1\: Selecteer een Template +label.step.2=Stap 2 +label.step.2.title=Stap 2\: Service Aanbieding +label.step.3=Stap 3 +label.step.3.title=Stap 4\: Selecteer een Schijf Aanbieding +label.step.4=Stap 4 +label.step.4.title=Stap 4\: Netwerk +label.step.5=Stap 5 +label.step.5.title=Stap 5\: Beoordeel +label.stickiness=Stickiness +label.sticky.cookie-name=Cookie naam +label.sticky.domain=Domein +label.sticky.expire=Verloopt +label.sticky.holdtime=Wacht tijd +label.sticky.indirect=Indirect +label.sticky.length=Lengte +label.sticky.mode=Modus +label.sticky.nocache=Geen cache +label.sticky.postonly=Alleen Post +label.sticky.prefix=Prefix +label.sticky.request-learn=Request learn +label.sticky.tablesize=Tabel grootte +label.stopped.vms=Uitgeschakelde VMs +label.stop=Stop +label.storage=Opslag +label.storage.tags=Opslag Tags +label.storage.traffic=Opslag Verkeer +label.storage.type=Opslag Type +label.subdomain.access=Subdomein Toegang +label.submitted.by=[Verstuurd door\: ] +label.submit=Verstuur +label.succeeded=Geslaagd +label.sunday=Zondag +label.super.cidr.for.guest.networks=Super CIDR voor Gast Netwerken +label.supported.services=Geondersteunde Diensten +label.supported.source.NAT.type=Ondersteunde Source NAT type +label.suspend.project=Pauzeer Project +label.system.capacity=Systeem Capaciteit +label.system.offering=Systeem Aanbieding +label.system.service.offering=Systeem Service Aanbieding +label.system.vms=Systeem VMs +label.system.vm=Systeem VM +label.system.vm.type=Systeem VM type +label.system.wide.capacity=Systeembreede capaciteit +label.tagged=Tagged +label.tags=Tags +label.target.iqn=Doel IQN +label.task.completed=Taak uitgevoerd +label.template.limits=Template Limieten +label.template=Template +label.TFTP.dir=TFTP Directory +label.theme.default=Standaard Thema +label.theme.grey=Aangepast - Grijs +label.theme.lightblue=Aangepast - Licht Blauw +label.thursday=Donderdag +label.tier.details=Tier details +label.tier=Tier +label.timeout.in.second = Timeout(seconden) +label.timeout=Timeout +label.time=Tijd +label.time.zone=Tijdzone +label.timezone=Tijdzone +label.token=Token +label.total.cpu=Totaal CPU +label.total.CPU=Totaal CPU +label.total.hosts=Totaal Hosts +label.total.memory=Totaal Geheugen +label.total.of.ip=Totaal aantal IP Adressen +label.total.of.vm=Totaal aantal VM +label.total.storage=Totaal Opslag +label.total.vms=Totaal VMs +label.traffic.label=Verkeerslabel +label.traffic.types=Verkeer Types +label.traffic.type=Verkeer Type +label.tuesday=Dinsdag +label.type.id=Type ID +label.type=Type +label.unavailable=Niet beschikbaar +label.unlimited=Ongelimiteerd +label.untagged=Untagged +label.update.project.resources=Update project verbruik +label.update.ssl.cert= SSL Certificaat +label.update.ssl= SSL Certificaat +label.updating=Bezig met updaten +label.upload=Upload +label.upload.volume=Upload Volume +label.url=URL +label.usage.interface=Verbruik Interface +label.used=Gebruikt +label.user=Gebruiker +label.username=Gebruikersnaam +label.users=Gebruikers +label.use.vm.ip=Gebruik VM IP\: +label.value=Waarde +label.vcdcname=vCenter DC naam +label.vcenter.cluster=vCenter Cluster +label.vcenter.datacenter=vCenter Datacenter +label.vcenter.datastore=VCenter Datastore +label.vcenter.host=vCenter Host +label.vcenter.password=vCenter Wachtwoord +label.vcenter.username=vCenter Gebruikersnaam +label.vcipaddress=vCenter IP Adres +label.version=Versie +label.view.all=Toon alle +label.view.console=Toon console +label.viewing=Weergeven +label.view.more=Toon meer +label.view=Toon +label.virtual.appliances=Virtueele Appliances +label.virtual.appliance=Virtuele Appliance +label.virtual.machines=Virtuele machines +label.virtual.network=Virtueel Netwerk +label.virtual.routers=Virtuele Routers +label.virtual.router=Virtuele Router +label.vm.add=Instantie Toevoegen +label.vm.destroy=Verwijder +label.vm.display.name=VM weergave naam +label.VMFS.datastore=VMFS datastore +label.vmfs=VMFS +label.vm.name=VM naam +label.vm.reboot=Reboot +label.VMs.in.tier=VMs in tier +label.vmsnapshot.current=isHuidige +label.vmsnapshot.memory=Snapshot geheugen +label.vmsnapshot.parentname=Bovenliggend +label.vmsnapshot.type=Type +label.vmsnapshot=VM Snapshots +label.vm.start=Start +label.vm.state=VM staat +label.vm.stop=Stop +label.vms=VMs +label.vmware.traffic.label=VMware verkeerslabel +label.volgroup=Volume Groep +label.volume.limits=Volume Limieten +label.volume.name=Volume Naam +label.volumes=Volumes +label.volume=Volume +label.vpc.id=VPC ID +label.VPC.router.details=VPC router details +label.vpc=VPC +label.VPN.connection=VPN Connectie +label.vpn.customer.gateway=VPN Customer Gateway +label.VPN.customer.gateway=VPN Customer Gateway +label.VPN.gateway=VPN Gateway +label.vpn=VPN +label.vsmctrlvlanid=Controle VLAN ID +label.vsmpktvlanid=Pakket VLAN ID +label.vsmstoragevlanid=Opslag VLAN ID +label.vsphere.managed=vSphere beheerd +label.waiting=Wachten +label.warn=Waarschuwing +label.wednesday=Woensdag +label.weekly=Wekelijks +label.welcome.cloud.console=Welkom op de Management Console +label.welcome=Welkom +label.what.is.cloudstack=Wat is CloudStack&\#8482? +label.xen.traffic.label=XenServer verkeerslabel +label.yes=Ja +label.zone.details=Zone details +label.zone.id=Zone ID +label.zone.name=Zone naam +label.zone.step.1.title=Stap 1\: Selecteer een Netwerk +label.zone.step.2.title=Stap 2\: Zone toevoegen +label.zone.step.3.title=Stap 3\: Pod toevoegen +label.zone.step.4.title=Step 4\: IP range toevoegen +label.zones=Zones +label.zone.type=Type Zone +label.zone.wide=Zone breed +label.zoneWizard.trafficType.guest=Gast\: Verkeer tussen virtuele machines van de eindgebruiker +label.zoneWizard.trafficType.public=Publiek\: Verkeer tussen het internet en virtueele machines in de cloud. +label.zoneWizard.trafficType.storage=Opslag\: Verkeer tussen de primaire en secundaire opslag servers zoals VM templates en snapshots +label.zone=Zone +managed.state=Beheersstaat +message.acquire.new.ip=Bevestigen dat je een nieuw IP voor dit netwerk wilt verkrijgen. +message.acquire.new.ip.vpc=Bevestig dat u een nieuw IP wilt verkrijgen voor deze VPC. +message.acquire.public.ip=Selecteer de zone waarvan u een nieuw IP wenst te verkrijgen. +message.action.cancel.maintenance=Het onderhoud voor de host is succesvol geannuleerd. Het daadwerkelijke proces kan echter enkele minuten duren. +message.action.cancel.maintenance.mode=Bevestig dat u het onderhoud wilt annuleren. +message.action.change.service.warning.for.instance=Uw instantie moet uitgeschakeld zijn voordat u de service aanbieding kunt wijzigen. +message.action.change.service.warning.for.router=Uw router moet uitgeschakeld zijn voordat u de service aanbieding kunt wijzigen. +message.action.delete.cluster=Bevestig dat u dit cluster wilt verwijderen. +message.action.delete.disk.offering=Bevestig dat u deze schijf aanbieding wilt verwijderen. +message.action.delete.domain=Bevestig dat u dit domein wilt verwijderen. +message.action.delete.external.firewall=Bevestig dat u deze externe firewall wilt verwijderen. Waarschuwing\: Als u van plan bent dezelfde firewall opnieuw toe te voegen, dient u de verbruiksstatistieken eerst te resetten. +message.action.delete.external.load.balancer=Bevestig dat u deze externe loadbalancer wilt verwijderen. Waarschuwing\: Als u van plan bent dezelfde loadbalancer opnieuw toe te voegen, dient u de verbruiksstatistieken eerst te resetten. +message.action.delete.ingress.rule=Bevestig dat u deze inkomende regel wilt verwijderen. +message.action.delete.ISO=Bevestig dat u deze ISO wilt verwijderen. +message.action.delete.ISO.for.all.zones=Deze ISO wordt gebruikt door alle zones. Bevestig dat u deze wilt verwijderen van alle zones. +message.action.delete.network=Bevestig dat u dit netwerk wilt verwijderen. +message.action.delete.nexusVswitch=Bevestig dat u deze nexus 1000v wilt verwijderen +message.action.delete.physical.network=Bevestig dat u dit fysieke netwerk wilt verwijderen. +message.action.delete.pod=Bevestig dat u deze pod wilt verwijderen. +message.action.delete.primary.storage=Bevestig dat u deze primaire opslag wilt verwijderen. +message.action.delete.secondary.storage=Bevestig dat u deze secudaire opslag wilt verwijderen. +message.action.delete.security.group=Bevestig dat u deze security group wilt verwijderen. +message.action.delete.service.offering=Bevestig dat u deze service aanbieding wilt verwijderen. +message.action.delete.snapshot=Bevestig dat u deze snapshot wilt verwijderen. +message.action.delete.system.service.offering=Bevestig dat u deze systeem service aanbieding wilt verwijderen. +message.action.delete.template=Bevestig dat u deze template wilt verwijderen +message.action.delete.template.for.all.zones=Deze template wordt gebruikt door alle zones. Bevestig dat u deze wilt verwijderen van alle zones. +message.action.delete.volume=Bevestig dat u dit volume wilt verwijderen +message.action.delete.zone=Bevestig dat u deze zone wilt verwijderen +message.action.destroy.instance=Bevestig dat u deze instantie wilt vernietigen +message.action.destroy.systemvm=Bevestig dat u deze Systeem VM wilt vernietigen +message.action.disable.cluster=Bevestig dat u dit cluster wilt uitschakelen. +message.action.disable.nexusVswitch=Bevestig dat u deze nexus 1000v wilt uitschakelen. +message.action.disable.physical.network=Bevestig dat u dit fysieke netwerk wilt uitschakelen. +message.action.disable.pod=Bevestig dat u deze pod wilt uitschakelen. +message.action.disable.static.NAT=Bevestig dat u static NAT wilt uitschakelen. +message.action.disable.zone=Bevestig dat u deze zone wilt uitschakelen. +message.action.download.iso=Bevestig dat u deze ISO wilt downloaden. +message.action.download.template=Bevestig dat u deze template wilt downloaden. +message.action.enable.cluster=Bevestig dat u dit cluster wilt inschakelen. +message.action.enable.maintenance=Uw host is succesvol voorbereid op onderhoud. Het proces kan echter een paar minuten duren afhankelijk van de hoeveelheid VMs op de host. +message.action.enable.nexusVswitch=Bevestig dat u deze nexus 1000v wilt inschakelen +message.action.enable.physical.network=Bevestig dat u dit fysieke netwerk wilt inschakelen. +message.action.enable.pod=Bevestigd dat u deze pod wilt inschakelen. +message.action.enable.zone=Bevestig dat u deze zone wilt inschakelen. +message.action.force.reconnect=De host is succesvol geforceerd om opnieuw te verbinden. Dit proces kan echter enkele minuten duren. +message.action.host.enable.maintenance.mode=Het inschakelen van de onderhoudsmodus zorgt ervoor dat alle draaiende instanties worden gemigreerd naar andere beschikbare hosts. +message.step.2.desc= +message.step.3.desc= +mode=Modus +notification.reboot.instance=Herstart instantie +state.Allocated=Gebruikt +state.Disabled=Uitgeschakeld +state.Error=Fout diff --git a/client/WEB-INF/classes/resources/messages_pl.properties b/client/WEB-INF/classes/resources/messages_pl.properties new file mode 100644 index 00000000000..9024030f51e --- /dev/null +++ b/client/WEB-INF/classes/resources/messages_pl.properties @@ -0,0 +1,469 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +error.invalid.username.password=B\u0142\u0119dna nazwa u\u017cytkownika lub has\u0142o +label.account.id=ID konta +label.account=Konto +label.account.name=Nazwa konta +label.accounts=Konta +label.action.attach.disk=Dodaj dysk +label.action.attach.disk.processing=Dodawanie dysku +label.action.attach.iso=Dodaj obraz ISO +label.action.attach.iso.processing=Dodawanie obrazu ISO +label.action.change.password=Zmie\u0144 has\u0142o +label.action.copy.ISO=Kopiuj ISO +label.action.copy.ISO.processing=Kopiuj ISO.... +label.action.copy.template=Kopij szablon +label.action.copy.template.processing=Kopije szablon.... +label.action.create.template.from.vm=Utw\u00f3rz szablon z VM +label.action.create.template.from.volume=Utw\u00f3rz Szablon z wolumenu +label.action.create.template.processing=Tworz\u0119 szablon +label.action.create.template=Utw\u00f3rz szablon +label.action.create.vm.processing=Tworz\u0119 VM.... +label.action.create.vm=Utw\u00f3rz VM +label.action.create.volume.processing=Tworz\u0119 wolumen.... +label.action.create.volume=Utw\u00f3rz wolumen +label.action.delete.account.processing=Usuwanie dost\u0119pu.... +label.action.delete.account=Usu\u0144 dost\u0119p +label.action.delete.cluster.processing=Usuwam klaster.... +label.action.delete.cluster=Usu\u0144 klaster +label.action.delete.domain.processing=Usuwam domen\u0119.... +label.action.delete.domain=Usu\u0144 domen\u0119 +label.action.delete.firewall.processing=Usuwam Firewall +label.action.delete.firewall=Usu\u0144 regu\u0142\u0119 Firewall +label.action.delete.ISO.processing=Usuwam ISO.... +label.action.delete.ISO=Usu\u0144 ISO +label.action.delete.network.processing=Usuwam sie\u0107.... +label.action.delete.network=Usu\u0144 sie\u0107 +label.action.delete.nexusVswitch=Usu\u0144 Nexus 1000v +label.action.delete.physical.network=Usu\u0144 fizyczn\u0105 sie\u0107 +label.action.delete.user.processing=Usuwam u\u017cytkownika.... +label.action.delete.user=Usu\u0144 u\u017cytkownika +label.action.delete.volume.processing=Usuwam wolumen.... +label.action.delete.volume=Usu\u0144 wolumen +label.action.delete.zone.processing=Usuwam stref\u0119.... +label.action.delete.zone=Usu\u0144 stref\u0119 +label.action.destroy.instance.processing=Usuwam instancj\u0119 +label.action.destroy.instance=Usu\u0144 instancj\u0119 +label.action.detach.disk=Od\u0142\u0105cz dysk +label.action.detach.disk.processing=Od\u0142\u0105czanie dysku.... +label.action.detach.iso=Od\u0142\u0105cz obraz ISO +label.action.detach.iso.processing=Od\u0142\u0105czanie obrazu ISO +label.action.disable.account.processing=Wy\u0142\u0105czam dost\u0119p.... +label.action.disable.account=Wy\u0142\u0105cz dost\u0119p +label.action.disable.cluster.processing=Wy\u0142\u0105czam klaster.... +label.action.disable.cluster=Wy\u0142\u0105cz klaster +label.action.disable.nexusVswitch=Wy\u0142\u0105cz Nexus 1000v +label.action.disable.physical.network=Wy\u0142\u0105cz fizyczn\u0105 sie\u0107 +label.action.disable.user.processing=Wy\u0142\u0105czam u\u017cytkownika +label.action.disable.user=Wy\u0142\u0105cz u\u017cytkownika +label.action.disable.zone.processing=Wy\u0142\u0105czam stref\u0119.... +label.action.disable.zone=Wy\u0142\u0105cz stref\u0119 +label.action.download.ISO=Pobierz ISO +label.action.download.template=Pobierz szablon +label.action.download.volume=Pobierz wolumen +label.action.download.volume.processing=Pobieram wolumen.... +label.action.edit.account=Edytuj dost\u0119p +label.action.edit.domain=Edytuj domen\u0119 +label.action.edit.global.setting=Edytuj Globalne ustawienia +label.action.edit.host=Edytuj host +label.action.edit.instance=Edytuj instancj\u0119 +label.action.edit.ISO=Edytuj ISO +label.action.edit.network=Edytuj sie\u0107 +label.action.edit.network.processing=Zmieniam sie\u0107.... +label.action.edit.template=Edytuj szablon +label.action.edit.user=Edytuj u\u017cytkownika +label.action.edit.zone=Edytuj stref\u0119 +label.action.enable.account.processing=W\u0142\u0105czam dost\u0119p.... +label.action.enable.account=W\u0142\u0105cz dost\u0119p +label.action.enable.cluster.processing=W\u0142\u0105czam klaster.... +label.action.enable.cluster=W\u0142\u0105cz klaster +label.action.enable.nexusVswitch=W\u0142\u0105cz Nexus 1000v +label.action.enable.physical.network=W\u0142\u0105cz fizyczn\u0105 sie\u0107 +label.action.enable.user.processing=W\u0142\u0105czam u\u017cytkownika.... +label.action.enable.user=W\u0142\u0105cz u\u017cytkownika +label.action.enable.zone.processing=W\u0142\u0105czam stref\u0119.... +label.action.enable.zone=W\u0142\u0105cz stref\u0119 +label.action.generate.keys=Generuj klucze +label.action.generate.keys.processing=Generuj\u0119 klucze.... +label.action.list.nexusVswitch=Kista Nexus 1000v +label.action.lock.account.processing=Blokuj\u0119 dost\u0119p.... +label.action.lock.account=Zablokuj dost\u0119p +label.action.manage.cluster.processing=Zarz\u0105dzam klastrem.... +label.action.manage.cluster=Zarz\u0105dzaj klastrem +label.action.migrate.instance=Migruj instancj\u0119 +label.action.migrate.instance.processing=Migruj\u0119 instancj\u0119.... +label.action.migrate.router=Migruj router +label.action.migrate.router.processing=Migruje router.... +label.action.migrate.systemvm=Migruj system VM +label.action.migrate.systemvm.processing=Migruj\u0119 system VM.... +label.action.reboot.instance.processing=Restartuje instancj\u0119 +label.action.reboot.instance=Restartuj instancj\u0119 +label.action.reboot.router.processing=Restartuje router..... +label.action.reboot.router=Restartuj router +label.action.reboot.systemvm.processing=Restartuje system VM.... +label.action.reboot.systemvm=Restartuj system VM +label.action.register.iso=Rejestruj ISO +label.action.register.template=Rejestruj szablon +label.action.remove.host.processing=Usuwam host.... +label.action.remove.host=Usu\u0144 host +label.action.reset.password.processing=Resetuj\u0119 has\u0142o.... +label.action.reset.password=Resetuj has\u0142o +label.action.resize.volume.processing=Zmieniam wielko\u015b\u0107 wolumenu.... +label.action.resize.volume=Zmie\u0144 wielko\u015b\u0107 wolumenu +label.action.restore.instance=Przywr\u00f3\u0107 instancj\u0119 +label.actions=Akcje +label.action.start.instance.processing=Uruchamiam instancj\u0119.... +label.action.start.instance=Uruchom instancj\u0119 +label.action.start.router.processing=Uruchamiam router.... +label.action.start.router=Uruchom router +label.action.start.systemvm.processing=Uruchamiam system VM... +label.action.start.systemvm=Uruchom system VM +label.action.stop.instance.processing=Zatrzymuj\u0119 instancj\u0119.... +label.action.stop.instance=Zatrzymaj instancj\u0119 +label.action.stop.router.processing=Zatrzymuj\u0119 router... +label.action.stop.router=Zatrzymaj router +label.action.stop.systemvm.processing=Zatrzymuj\u0119 system VM.... +label.action.stop.systemvm=Zatrzymaj system VM +label.action.take.snapshot.processing=Tworz\u0119 snapshot.... +label.action.take.snapshot=Zr\u00f3b snapshot +label.activate.project=Aktywuj projekt +label.add.account=Dodaj konto +label.add.accounts=Dodaj konta +label.add.accounts.to=Dodaj konto do +label.add.account.to.project=Dodaj konto do projektu +label.add.ACL=Dodaj ACL +label.add.by.cidr=Dodaj przez CIDR +label.add.by=Dodaj przez +label.add.by.group=Dodaj przez grup\u0119 +label.add.cluster=Dodaj klaster +label.add=Dodaj +label.add.domain=Dodaj domen\u0119 +label.add.firewall=Dodaj regu\u0142\u0119 firewall +label.add.host=Dodaj host +label.adding=Dodawanie +label.adding.failed=Dodanie nieudane +label.adding.processing=Dodawanie +label.adding.succeeded=Dodanie udane +label.add.more=Dodaj wi\u0119cej +label.add.network.device=Dodaj urz\u0105dzenie sieciowe +label.add.network=Dodaj sie\u0107 +label.add.new.F5=Dodaj nowy F5 +label.add.new.SRX=Dodaj nowy SRX +label.add.region=Dodaj region +label.add.rule=Dodaj regu\u0142\u0119 +label.add.to.group=Dodaj do grupy +label.add.user=Dodaj u\u017cytkownika +label.add.vlan=Dodaj VLAN +label.add.vm=Dodaj VM +label.add.vms=Dodaj VM-ny +label.add.volume=Dodaj wolumen +label.add.vpc=Dodaj VPC +label.add.zone=Dodaj stref\u0119 +label.admin=Admin +label.api.key=Klucz API +label.apply=Zastosuj +label.author.name=Imi\u0119 autora +label.available=Dost\u0119pne +label.available.public.ips=Dost\u0119pne publiczne adresy IP +label.back=Wstecz +label.bandwidth=Przepustowo\u015b\u0107 +label.cancel=Zako\u0144cz +label.certificate=Certyfikat +label.cidr=CIDR +label.CIDR.list=Lista CIDR +label.clean.up=Wyczy\u015b\u0107 +label.clear.list=Wyczy\u015b\u0107 list\u0119 +label.close=Zamknij +label.clvm=CLVM +label.code=Kod +label.community=Spo\u0142eczno\u015b\u0107 +label.configuration=Konfiguracja +label.configure=Konfiguruj +label.configure.vpc=Konfiguruj VPC +label.confirmation=Potwierdzenie +label.confirm.password=Potwierd\u017a has\u0142o +label.congratulations=Gratulacje\! +label.continue=Kontynuuj +label.corrections.saved=Poprawka zapisana +label.cpu=CPU +label.cpu.limits=Limit CPU +label.cpu.mhz=CPU (w MHz) +label.created.by.system=Utworzono przez system +label.created=Utworzono +label.create.project=Stw\u00f3rz projekt +label.daily=Dziennie +label.date=Data +label.day.of.month=Dzie\u0144 miesi\u0105ca +label.day.of.week=Dzie\u0144 tygodnia +label.dedicated=Dedykowany +label.default=Domy\u015blnie +label.default.view=Widok domy\u015blny +label.delete.F5=Usu\u0144 F5 +label.delete.project=Usu\u0144 projekt +label.delete.SRX=Usu\u0144 SRX +label.delete=Usu\u0144 +label.deleting.failed=Usuwanie nieudane +label.deleting.processing=Usuwanie.... +label.destroy.router=Zniszcz router +label.destroy=Zniszcz +label.detaching.disk=Od\u0142\u0105czanie dysku +label.details=Szczeg\u00f3\u0142y +label.disabled=Wy\u0142\u0105czony +label.disable.vpn=Wy\u0142\u0105cz VPN +label.disk.size.gb=Wielko\u015b\u0107 dysku (w GB) +label.disk.size=Wielko\u015b\u0107 dysku +label.display.name=Wy\u015bwietlana nazwa +label.domain.admin=Administrator domeny +label.domain=Domena +label.domain.id=ID domeny +label.domain.name=Nazwa domeny +label.done=Sko\u0144czono +label.download.progress=Post\u0119p w pobieraniu +label.drag.new.position=Przenie\u015b w nowe miejsce +label.edit=Edytuj +label.edit.network.details=Edytuj szczeg\u00f3\u0142y sieci +label.edit.project.details=Zmie\u0144 szczeg\u00f3\u0142y projektu +label.edit.vpc=Edytuj VPC +label.elastic=Elastyczny +label.elastic.IP=Zmienne IP +label.email=Poczta +label.enable.vpn=W\u0142\u0105cz VPN +label.error=B\u0142\u0105d +label.f5=F5 +label.featured=Polecane +label.filterBy=Filtrowanie wg +label.firewall=Zapora +label.first.name=Pierwsza nazwa +label.format=Format +label.friday=Pi\u0105tek +label.full.path=Pe\u0142na \u015bcie\u017cka +label.go.step.2=Id\u017a do punktu 2 +label.go.step.3=Id\u017a do punktu 3 +label.go.step.4=Id\u017a do punktu 4 +label.go.step.5=Id\u017a do punktu 5 +label.group=Grupa +label.group.optional=Grupa (opcjonalnie) +label.guest=Go\u015b\u0107 +label.guest.type=Rodzaj go\u015bci +label.help=Pomoc +label.hints=Podpowiedzi +label.id=ID +label.info=Informacje +label.instances=Instancje +label.invitations=Zaproszenia +label.invited.accounts=Zaproszone konta +label.invite.to=Zapro\u015b do +label.invite=Zapro\u015b +label.ip=IP +label.iso=ISO +label.keep=Zostaw +label.key=Klucz +label.lang.english=Angielski +label.lang.french=Francuski +label.lang.japanese=Japo\u0144ski +label.lang.korean=Korea\u0144ski +label.lang.russian=Rosyjski +label.lang.spanish=Hiszpia\u0144ski +label.last.name=Nazwisko +label.least.connections=Ostatnie po\u0142\u0105czenie +label.level=Poziom +label.loading=Wczytywanie +label.local=Lokalne +label.local.storage.enabled=Pami\u0119\u0107 lokalna w\u0142\u0105czona +label.local.storage=Pami\u0119\u0107 lokalna +label.login=Zaloguj +label.logout=Wyloguj +label.lun=LUN +label.LUN.number=LUN \# +label.max.guest.limit=Maksymalna liczba go\u015bci +label.maximum=Maksimum +label.max.public.ips=Maksymalna liczba publicznych adres\u00f3w IP +label.memory.limits=Limit pami\u0119ci (MiB) +label.memory.mb=Pami\u0119\u0107 (w MB) +label.memory=Pami\u0119\u0107 +label.menu.accounts=Konta +label.menu.alerts=Alarmy +label.menu.all.accounts=Wszystkie konta +label.menu.all.instances=Wszystkie instancje +label.menu.configuration=Konfiguracja +label.menu.domains=Domeny +label.menu.infrastructure=Infrastruktura +label.menu.instances=Instancje +label.menu.ipaddresses=Adresy IP +label.menu.isos=ISO +label.menu.my.accounts=Moje konta +label.menu.my.instances=Moje instancje +label.menu.my.isos=Moje ISO +label.menu.network=Sie\u0107 +label.menu.regions=Regiony +label.menu.system=System +label.minimum=Minimum +label.monday=Poniedzia\u0142ek +label.monthly=Miesi\u0119cznie +label.move.down.row=Jeden rz\u0105d na d\u00f3\u0142 +label.move.to.top=Przenie\u015b na sam\u0105 g\u00f3r\u0119 +label.move.up.row=Jeden rz\u0105d do g\u00f3ry +label.my.account=Moje konto +label.my.network=Moja sie\u0107 +label.name=Nazwa +label.name.optional=Nazwa (opcjonalnie) +label.network.id=ID sieci +label.network.name=Nazwa sieci +label.network=Sie\u0107 +label.networks=Sieci +label.new=Nowy +label.new.project=Nowy projekt +label.next=Nast\u0119pny +label.nfs=NFS +label.nfs.server=Serwer NFS +label.no.data=Brak danych +label.none=Brak +label.no=Nie +label.no.thanks=Nie dzi\u0119kuj\u0119 +label.notifications=Przypomnienia +label.number.of.hosts=Liczba host\u00f3w +label.ok=OK +label.order=Zadanie +label.password=Has\u0142o +label.path=\u015acie\u017cka +label.please.wait=Prosz\u0119 czeka\u0107 +label.plugin.details=Szczeg\u00f3\u0142y wtyczki +label.plugins=Wtyczki +label.previous=Wstecz +label.private.network=Sie\u0107 prywatna +label.project.id=Nazwa ID projektu +label.project.invite=Zapro\u015b do projektu +label.project.name=Nazwa projektu +label.project=Projekt +label.projects=Projekty +label.protocol=Protok\u00f3\u0142 +label.providers=Dostawcy +label.public.ip=Publiczny adres IP +label.public.ips=Publiczne adresy IP +label.public.network=Sie\u0107 publiczna +label.public=Pobliczny +label.public.port=Publiczny port +label.reboot=Uruchom ponownie +label.refresh=Od\u015bwie\u017c +label.region=Region +label.remind.later=Przypomnij p\u00f3\u017aniej +label.remove.rule=Usu\u0144 regu\u0142\u0119 +label.remove.vpc=Usu\u0144 VPC +label.removing.user=Usu\u0144 u\u017cytkownika +label.removing=Usuwanie +label.required=Wymagane +label.resource.limits=Limit zasob\u00f3w +label.resources=Zasoby +label.resource=Zas\u00f3b +label.restart.required=Wymagany restart +label.rules=Zasady +label.saturday=Sobota +label.save.and.continue=Zapisz i kontynuuj +label.save=Zapisz +label.saving.processing=Zapisywanie.... +label.search=Szukaj +label.select.instance=Wybierz instancj\u0119 +label.select.project=Wybierz projekt +label.select=Wybierz +label.sent=Wys\u0142ano +label.server=Serwer +label.size=Wielko\u015bc +label.specify.IP.ranges=Wyszczeg\u00f3lnij zasi\u0119g adres\u00f3w IP +label.srx=SRX +label.statistics=Statystyki +label.status=Status +label.step.1=Krok 1 +label.step.2=Krok 2 +label.step.3=Krok 3 +label.step.4=Krok 4 +label.step.5=Krok 5 +label.sticky.domain=Domena +label.sticky.expire=Wygasa +label.sticky.length=D\u0142ugo\u015b\u0107 +label.sticky.mode=Tryb +label.sticky.prefix=Prefiks +label.stop=Stop +label.sunday=Niedziela +label.suspend.project=Zawie\u015b projekt +label.tagged=Otagowany +label.tags=Tagi +label.task.completed=Zadania uko\u0144czone +label.time=Czas +label.time.zone=Strefa czasowa +label.timezone=Strefa czasowa +label.type.id=Wpisz ID +label.type=Wpisz +label.unavailable=Niedost\u0119pny +label.unlimited=Nieograniczony +label.untagged=Nieotagowany +label.updating=Aktualizowanie +label.url=URL +label.used=U\u017cyte +label.username=Nazwa u\u017cytkownika +label.users=U\u017cytkownicy +label.user=U\u017cytkowni +label.version=Wersja +label.view.all=Zobacz wszystko +label.view=Zobacz +label.vm.add=Dodaj instancj\u0119 +label.vm.destroy=Zniszcz +label.vmfs=VMFS +label.vm.name=Nazwa VM +label.vm.reboot=Uruchom ponownie +label.vmsnapshot.type=Wpisz +label.vm.start=Rozpocznij +label.vm.stop=Stop +label.vms=VMs +label.vpc=VPC +label.vpn=VPN +label.waiting=Czekanie +label.warn=Ostrze\u017cenie +label.wednesday=\u015aroda +label.weekly=Tygodniowo +label.welcome=Witaj +label.what.is.cloudstack=Czym jest CloudStack&\#8482? +label.yes=Tak +message.action.delete.nexusVswitch=Potwierd\u017a, \u017ce chcesz usun\u0105\u0107\: nexus 1000v +message.action.download.iso=Potwierd\u017a, \u017ce chcesz pobra\u0107 ten obraz ISO. +message.activate.project=Czy na pewno chcesz aktywowa\u0107 ten projekt? +message.confirm.delete.F5=Czy na pewno chcesz usun\u0105\u0107 F5? +message.confirm.delete.SRX=Czy na pewno chcesz usun\u0105\u0107 SRX? +message.delete.project=Czy na pewno chcesz usun\u0105\u0107 ten projekt? +message.disable.vpn=Czy na pewno chcesz wy\u0142\u0105czy\u0107 VPN? +message.no.projects=Nie posiadasz \u017cadnych projekt\u00f3w.
Utw\u00f3rz nowy projekt w zak\u0142adce projekty +message.please.proceed=Przejd\u017a do nast\u0119pnego punktu +message.step.2.desc= +message.step.3.desc= +message.suspend.project=Czy na pewno chcesz zawiesi\u0107 ten projekt +mode=Tryb +state.Accepted=Akceptowano +state.Active=Aktywny +state.Completed=Uko\u0144czono +state.Creating=Tworzenie +state.Declined=Odrzucono +state.Destroyed=Zniszczono +state.Disabled=Wy\u0142\u0105czony +state.enabled=W\u0142\u0105czone +state.Enabled=W\u0142\u0105czone +state.Error=B\u0142\u0105d +state.ready=Gotowe +state.Ready=Gotowe +state.Starting=Rozpoczynanie +state.Stopped=Zatrzymano +state.Suspended=Zawieszono +ui.listView.filters.all=Wszystko diff --git a/client/WEB-INF/classes/resources/messages_pt_BR.properties b/client/WEB-INF/classes/resources/messages_pt_BR.properties index 86bb83177a8..07fd3f42d76 100644 --- a/client/WEB-INF/classes/resources/messages_pt_BR.properties +++ b/client/WEB-INF/classes/resources/messages_pt_BR.properties @@ -373,6 +373,7 @@ label.compute.and.storage=Processamento e Armazenamento label.compute.offering=Oferta de Computa\u00e7\u00e3o label.configuration=Configura\u00e7\u00e3o label.configure=Configurar +label.configure.ldap=Configurar LDAP label.configure.network.ACLs=Configure ACLs de rede label.configure.vpc=Configurar VPC label.confirmation=Confirma\u00e7\u00e3o @@ -390,6 +391,7 @@ label.cpu.mhz=CPU (em MHz) label.cpu.utilized=CPU Utilizada label.created.by.system=Criado pelo sistema label.created=Criado +label.create.nfs.secondary.staging.store=Criar storage staging secund\u00e1rio NFS label.create.project=Criar um projeto label.create.template=Criar template label.create.VPN.connection=Criar uma conex\u00e3o VPN @@ -418,6 +420,7 @@ label.delete.VPN.gateway=deletar um gateway de VPN label.delete.vpn.user=Deletar usu\u00e1rio VPN label.deleting.failed=Falha ao remover label.deleting.processing=Removendo.... +label.deployment.planner=Deployment planejado label.description=Descri\u00e7\u00e3o label.destination.physical.network.id=ID de destino da rede f\u00edsica label.destination.zone=Zona de Destino @@ -617,6 +620,9 @@ label.launch=Executar label.launch.vm=Executar VM label.launch.zone=Executar zona. label.LB.isolation=Isolamento de LB +label.ldap.configuration=Configura\u00e7\u00e3o do LDAP +label.ldap.group.name=Grupo LDAP +label.ldap.port=Porta do LDAP label.least.connections=Least connections label.level=N\u00edvel label.load.balancer=Load Balancer @@ -784,6 +790,7 @@ label.PING.CIFS.password=PING CIFS password label.PING.CIFS.username=PING CIFS username label.PING.dir=PING Directory label.PING.storage.IP=Disparar PING para IP do Storage +label.planner.mode=Modo planejado label.please.specify.netscaler.info=Por favor especifique as informa\u00e7\u00f5es do Netscaler label.please.wait=Por Favor Aguarde label.pod.name=Nome do Pod @@ -791,6 +798,7 @@ label.pod=POD label.pods=Pods label.port.forwarding=Encaminhamento de Porta label.port.forwarding.policies=Pol\u00edticas de redirecionamento de portas +label.port=Porta label.port.range=Range de Porta label.PreSetup=PreSetup label.previous=Anterior @@ -829,6 +837,15 @@ label.public.zone=Zona P\u00fablica label.purpose=Prop\u00f3sito label.Pxe.server.type=Tipo de Servidor PXE label.quickview=Visualiza\u00e7\u00e3o r\u00e1pida +<<<<<<< HEAD +======= +label.quiesce.vm=Quiesce VM +label.rbd.id=Usu\u00e1rio Ceph +label.rbd.monitor=Monitor Ceph +label.rbd.pool=Pool Ceph +label.rbd=RDB +label.rbd.secret=Cephx secret +>>>>>>> 4e449ff... Add Dutch (Netherlands, Polish languages in Web UI Change Japanese code (ja -> ja_JP) Update transifex sync config label.reboot=Reiniciar label.recent.errors=Erros Recentes label.redundant.router.capability=Recurso de roteador redundante @@ -841,6 +858,7 @@ label.remove.egress.rule=Remover regra egress label.remove.from.load.balancer=Removendo Cloud Server do Load Balancer label.remove.ingress.rule=Remover regra ingress label.remove.ip.range=Remover range de IP +label.remove.ldap=Remover LDAP label.remove.pf=Remover regra de redirecionamento de porta label.remove.project.account=Remover conta de projeto label.remove.rule=Remover regra @@ -924,6 +942,9 @@ label.show.ingress.rule=Mostrar Regra de Entrada label.site.to.site.VPN=Site-to-site VPN label.size=Tamanho label.skip.guide=Eu utilizei o CloudStack antes, pular este guia +label.smb.domain=Dom\u00ednio SMB +label.smb.password=Senha SMB +label.smb.username=Usu\u00e1rio SMB label.snapshot.limits=Limites de Snapshot label.snapshot.name=Nome do Snapshot label.snapshot=Snapshot @@ -1080,6 +1101,12 @@ label.vm.state=Estado da VM label.vm.stop=Parar label.vms=VMs label.vmware.traffic.label=Etiqueta de tr\u00e1fego VMware +<<<<<<< HEAD +======= +label.vnet.id=VLAN ID +label.vnet=VLAN +label.volatile=Vol\u00e1til +>>>>>>> 4e449ff... Add Dutch (Netherlands, Polish languages in Web UI Change Japanese code (ja -> ja_JP) Update transifex sync config label.volgroup=Grupo de Volume label.volume=Disco label.volume.limits=Limites de Disco @@ -1230,6 +1257,7 @@ message.basic.mode.desc=Escolha este modelo de rede se voc\u00ea *n\u00e3o message.change.offering.confirm=Confirme que voc\u00ea deseja mudar o plano deste Cloud Server. message.change.password=Por favor, troque sua senha. message.configure.all.traffic.types=Voc\u00ea tem m\u00faltiplas redes f\u00edsicas; favor configurar etiquetas para cada tipo de tr\u00e1fego clicando no bot\u00e3o Edit. +message.configure.ldap=Por favor, confirme que voc\u00ea deseja configurar o LDAP. message.configuring.guest.traffic=Configurando tr\u00e1fego do guest message.configuring.physical.networks=Configurando redes f\u00edsicas message.configuring.public.traffic=Configurando tr\u00e1fego p\u00fablico @@ -1355,6 +1383,14 @@ message.please.select.a.different.public.and.management.network.before.removing= message.please.select.networks=Por favor selecione as redes para sua m\u00e1quina virtual. message.please.wait.while.zone.is.being.created=Por favor, espere enquanto sua zona est\u00e1 sendo criada; isto pode demorar um pouco... message.project.invite.sent=Convite enviado para o usu\u00e1rio; Eles ser\u00e3o adicionados ao projeto ap\u00f3s aceitarem o convite +<<<<<<< HEAD +======= +message.public.traffic.in.advanced.zone=O tr\u00e1fego p\u00fablico \u00e9 gerado quando as VMs na nuvem acessam a internet. Os IPs acess\u00edveis ao p\u00fablico devem ser alocados para essa finalidade. Os usu\u00e1rios finais podem usar a interface do usu\u00e1rio CloudStack para adquirir esses IPs afim de implementar NAT entre a sua rede de guests e sua rede p\u00fablica.

Forne\u00e7a pelo menos um intervalo de endere\u00e7os IP para o tr\u00e1fego de internet. +message.public.traffic.in.basic.zone=O tr\u00e1fego p\u00fablico \u00e9 gerado quando as VMs na nuvem acessam a Internet ou prestam servi\u00e7os aos clientes atrav\u00e9s da Internet. Os IPs acess\u00edveis ao p\u00fablico devem ser alocados para essa finalidade. Quando uma inst\u00e2ncia \u00e9 criada, um IP a partir deste conjunto de IPs p\u00fablicos ser\u00e3o destinados \u00e0 inst\u00e2ncia, al\u00e9m do endere\u00e7o IP guest. Um NAT est\u00e1tico 1-1 ser\u00e1 criada automaticamente entre o IP p\u00fablico e IP guest. Os usu\u00e1rios finais tamb\u00e9m podem usar a interface de usu\u00e1rio CloudStack para adquirir IPs adicionais afim de se implementar NAT est\u00e1tico entre suas inst\u00e2ncias e o IP p\u00fablico. +message.redirecting.region=Redirecionando para regi\u00e3o... +message.remove.ldap=Voc\u00ea tem certeza que deseja deletar a configura\u00e7\u00e3o LDAP? +message.remove.region=Voc\u00ea tem certeza que deseja remover esta regi\u00e3o deste servidor de gerenciamento? +>>>>>>> 4e449ff... Add Dutch (Netherlands, Polish languages in Web UI Change Japanese code (ja -> ja_JP) Update transifex sync config message.remove.vpc=Favor confirmar que voc\u00ea deseja remover a VPC message.remove.vpn.access=Confirme se voc\u00ea deseja remover acesso VPN do seguinte Usu\u00e1rio. message.reset.password.warning.notPasswordEnabled=O template desta inst\u00e2ncia foi criado sem senha habilitada diff --git a/client/pom.xml b/client/pom.xml index fc01113c7a0..5215e0cd90e 100644 --- a/client/pom.xml +++ b/client/pom.xml @@ -130,6 +130,11 @@ cloud-plugin-network-vxlan ${project.version}
+ + org.apache.cloudstack + cloud-plugin-network-opendaylight + ${project.version} + org.apache.cloudstack cloud-plugin-hypervisor-xen @@ -176,6 +181,11 @@ cloud-plugin-planner-user-dispersing ${project.version} + + org.apache.cloudstack + cloud-plugin-planner-skip-heurestics + ${project.version} + org.apache.cloudstack cloud-plugin-planner-user-concentrated-pod @@ -201,6 +211,11 @@ cloud-mom-rabbitmq ${project.version} + + org.apache.cloudstack + cloud-mom-inmemory + ${project.version} + mysql mysql-connector-java @@ -547,36 +562,6 @@ - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - org.apache.maven.plugins - maven-antrun-plugin - [1.7,) - - run - - - - - - - - - - - - diff --git a/client/tomcatconf/commands.properties.in b/client/tomcatconf/commands.properties.in index a05310bff77..4f38c317bdd 100644 --- a/client/tomcatconf/commands.properties.in +++ b/client/tomcatconf/commands.properties.in @@ -72,6 +72,7 @@ migrateVirtualMachine=1 migrateVirtualMachineWithVolume=1 recoverVirtualMachine=7 expungeVirtualMachine=7 +getVirtualMachineUserData=15 #### snapshot commands createSnapshot=15 @@ -266,7 +267,7 @@ deleteImageStore=1 createSecondaryStagingStore=1 listSecondaryStagingStores=1 deleteSecondaryStagingStore=1 -prepareSecondaryStorageForMigration=1 +updateCloudToUseObjectStore=1 #### host commands addHost=3 @@ -706,3 +707,8 @@ importLdapUsers=3 #### juniper-contrail commands createServiceInstance=1 + +### OpenDaylight plugin commands +addOpenDaylightController=1 +deleteOpenDaylightController=1 +listOpenDaylightControllers=1 diff --git a/core/pom.xml b/core/pom.xml index cdcfd536b93..975e9f64072 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -36,6 +36,11 @@ cloud-engine-api ${project.version} + + org.apache.cloudstack + cloud-framework-security + ${project.version} + commons-codec commons-codec diff --git a/core/resources/META-INF/cloudstack/core/spring-core-registry-core-context.xml b/core/resources/META-INF/cloudstack/core/spring-core-registry-core-context.xml index be11a1f711f..5e799c06483 100644 --- a/core/resources/META-INF/cloudstack/core/spring-core-registry-core-context.xml +++ b/core/resources/META-INF/cloudstack/core/spring-core-registry-core-context.xml @@ -77,6 +77,11 @@ + + + + diff --git a/core/resources/META-INF/cloudstack/planner/spring-core-lifecycle-planner-context-inheritable.xml b/core/resources/META-INF/cloudstack/planner/spring-core-lifecycle-planner-context-inheritable.xml index 715f86d9c28..80779e43466 100644 --- a/core/resources/META-INF/cloudstack/planner/spring-core-lifecycle-planner-context-inheritable.xml +++ b/core/resources/META-INF/cloudstack/planner/spring-core-lifecycle-planner-context-inheritable.xml @@ -38,4 +38,9 @@ value="org.apache.cloudstack.affinity.AffinityGroupProcessor" /> + + + + + diff --git a/core/src/com/cloud/agent/api/AttachVolumeCommand.java b/core/src/com/cloud/agent/api/AttachVolumeCommand.java index 911ff543bf9..a0ee4199156 100644 --- a/core/src/com/cloud/agent/api/AttachVolumeCommand.java +++ b/core/src/com/cloud/agent/api/AttachVolumeCommand.java @@ -84,7 +84,7 @@ public class AttachVolumeCommand extends Command { } public String getVolumeName() { - return volumeName; + return volumeName; } public Long getVolumeSize() { diff --git a/core/src/com/cloud/agent/api/ComputeChecksumCommand.java b/core/src/com/cloud/agent/api/ComputeChecksumCommand.java index aec244b1e4e..8c654d71ec5 100755 --- a/core/src/com/cloud/agent/api/ComputeChecksumCommand.java +++ b/core/src/com/cloud/agent/api/ComputeChecksumCommand.java @@ -16,10 +16,10 @@ // under the License. package com.cloud.agent.api; -import com.cloud.agent.api.storage.ssCommand; +import com.cloud.agent.api.storage.SsCommand; import com.cloud.agent.api.to.DataStoreTO; -public class ComputeChecksumCommand extends ssCommand { +public class ComputeChecksumCommand extends SsCommand { private DataStoreTO store; private String templatePath; diff --git a/core/src/com/cloud/agent/api/CreatePrivateTemplateFromVolumeCommand.java b/core/src/com/cloud/agent/api/CreatePrivateTemplateFromVolumeCommand.java index 84f50af4bef..7880554478d 100644 --- a/core/src/com/cloud/agent/api/CreatePrivateTemplateFromVolumeCommand.java +++ b/core/src/com/cloud/agent/api/CreatePrivateTemplateFromVolumeCommand.java @@ -79,8 +79,8 @@ public class CreatePrivateTemplateFromVolumeCommand extends SnapshotCommand { } @Override - public void setVolumePath(String _volumePath) { - this._volumePath = _volumePath; + public void setVolumePath(String volumePath) { + this._volumePath = volumePath; } @Override diff --git a/core/src/com/cloud/agent/api/GetVmConfigAnswer.java b/core/src/com/cloud/agent/api/GetVmConfigAnswer.java new file mode 100644 index 00000000000..46e003ecae3 --- /dev/null +++ b/core/src/com/cloud/agent/api/GetVmConfigAnswer.java @@ -0,0 +1,68 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.agent.api; + +import java.util.List; + +public class GetVmConfigAnswer extends Answer { + + String vmName; + List nics; + + protected GetVmConfigAnswer() { + } + + public GetVmConfigAnswer(String vmName, List nics) { + this.vmName = vmName; + this.nics = nics; + } + + public String getVmName() { + return vmName; + } + + public List getNics() { + return nics; + } + + public class NicDetails { + String macAddress; + int vlanid; + + public NicDetails() { + } + + public NicDetails(String macAddress, int vlanid) { + this.macAddress = macAddress; + this.vlanid = vlanid; + } + + public String getMacAddress() { + return macAddress; + } + + public int getVlanid() { + return vlanid; + } + + } + + @Override + public boolean executeInSequence() { + return false; + } +} \ No newline at end of file diff --git a/core/src/com/cloud/agent/api/GetVmConfigCommand.java b/core/src/com/cloud/agent/api/GetVmConfigCommand.java new file mode 100644 index 00000000000..9133bd6b2c3 --- /dev/null +++ b/core/src/com/cloud/agent/api/GetVmConfigCommand.java @@ -0,0 +1,46 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.agent.api; + + +import java.util.List; + +import com.cloud.agent.api.to.NicTO; + +public class GetVmConfigCommand extends Command { + String vmName; + List nics; + protected GetVmConfigCommand() { + } + + public GetVmConfigCommand(String vmName) { + this.vmName = vmName; + } + + public String getVmName() { + return vmName; + } + + public void setNics(List nics){ + this.nics = nics; + } + + @Override + public boolean executeInSequence() { + return false; + } +} diff --git a/core/src/com/cloud/agent/api/ManageSnapshotCommand.java b/core/src/com/cloud/agent/api/ManageSnapshotCommand.java index e3abb503294..fb2d0d52803 100644 --- a/core/src/com/cloud/agent/api/ManageSnapshotCommand.java +++ b/core/src/com/cloud/agent/api/ManageSnapshotCommand.java @@ -22,8 +22,8 @@ import com.cloud.storage.StoragePool; public class ManageSnapshotCommand extends Command { // XXX: Should be an enum // XXX: Anyway there is something called inheritance in Java - public static String CREATE_SNAPSHOT = "-c"; - public static String DESTROY_SNAPSHOT = "-d"; + public static final String CREATE_SNAPSHOT = "-c"; + public static final String DESTROY_SNAPSHOT = "-d"; private String _commandSwitch; diff --git a/core/src/com/cloud/agent/api/ModifyVmNicConfigAnswer.java b/core/src/com/cloud/agent/api/ModifyVmNicConfigAnswer.java new file mode 100644 index 00000000000..1140485c67c --- /dev/null +++ b/core/src/com/cloud/agent/api/ModifyVmNicConfigAnswer.java @@ -0,0 +1,36 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.agent.api; + +public class ModifyVmNicConfigAnswer extends Answer { + String vmName; + protected ModifyVmNicConfigAnswer() { + } + + public ModifyVmNicConfigAnswer(String vmName) { + this.vmName = vmName; + } + + public String getVmName() { + return vmName; + } + + @Override + public boolean executeInSequence() { + return false; + } +} diff --git a/core/src/com/cloud/agent/api/ModifyVmNicConfigCommand.java b/core/src/com/cloud/agent/api/ModifyVmNicConfigCommand.java new file mode 100644 index 00000000000..0230beca732 --- /dev/null +++ b/core/src/com/cloud/agent/api/ModifyVmNicConfigCommand.java @@ -0,0 +1,42 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.agent.api; + + +public class ModifyVmNicConfigCommand extends Command { + String vmName; + int vlan; + String macAddress; + protected ModifyVmNicConfigCommand() { + } + + public ModifyVmNicConfigCommand(String vmName, int vlan, String macAddress) { + this.vmName = vmName; + this.vlan = vlan; + this.macAddress = macAddress; + } + + public String getVmName() { + return vmName; + } + + + @Override + public boolean executeInSequence() { + return false; + } +} diff --git a/core/src/com/cloud/agent/api/PerformanceMonitorAnswer.java b/core/src/com/cloud/agent/api/PerformanceMonitorAnswer.java index 10f4185719d..f8ec05dfd72 100644 --- a/core/src/com/cloud/agent/api/PerformanceMonitorAnswer.java +++ b/core/src/com/cloud/agent/api/PerformanceMonitorAnswer.java @@ -17,11 +17,11 @@ package com.cloud.agent.api; public class PerformanceMonitorAnswer extends Answer { - public PerformanceMonitorAnswer() { - } + public PerformanceMonitorAnswer() { + } - public PerformanceMonitorAnswer(PerformanceMonitorCommand cmd, - boolean result, String details) { - super(cmd, result, details); - } + public PerformanceMonitorAnswer(PerformanceMonitorCommand cmd, + boolean result, String details) { + super(cmd, result, details); + } } diff --git a/core/src/com/cloud/agent/api/PerformanceMonitorCommand.java b/core/src/com/cloud/agent/api/PerformanceMonitorCommand.java index 882d7b18763..d0a6eb1f714 100644 --- a/core/src/com/cloud/agent/api/PerformanceMonitorCommand.java +++ b/core/src/com/cloud/agent/api/PerformanceMonitorCommand.java @@ -21,26 +21,26 @@ import java.util.Map; public class PerformanceMonitorCommand extends Command { - Map params = new HashMap(); + Map params = new HashMap(); - public PerformanceMonitorCommand() { - } + public PerformanceMonitorCommand() { + } - public PerformanceMonitorCommand(Map params, int wait) { - setWait(wait); - this.params = params; - } + public PerformanceMonitorCommand(Map params, int wait) { + setWait(wait); + this.params = params; + } - @Override - public boolean executeInSequence() { - return false; - } + @Override + public boolean executeInSequence() { + return false; + } - public Map getParams() { - return params; - } + public Map getParams() { + return params; + } - public void setParams(Map params) { - this.params = params; - } + public void setParams(Map params) { + this.params = params; + } } diff --git a/core/src/com/cloud/agent/api/SecStorageSetupCommand.java b/core/src/com/cloud/agent/api/SecStorageSetupCommand.java index 3c8d7300064..18710320dc8 100644 --- a/core/src/com/cloud/agent/api/SecStorageSetupCommand.java +++ b/core/src/com/cloud/agent/api/SecStorageSetupCommand.java @@ -16,50 +16,21 @@ // under the License. package com.cloud.agent.api; -import com.cloud.agent.api.LogLevel.Log4jLevel; +import org.apache.cloudstack.framework.security.keystore.KeystoreManager; + import com.cloud.agent.api.to.DataStoreTO; public class SecStorageSetupCommand extends Command { private DataStoreTO store; private String secUrl; - private Certificates certs; + private KeystoreManager.Certificates certs; - public static class Certificates { - @LogLevel(Log4jLevel.Off) - private String privKey; - @LogLevel(Log4jLevel.Off) - private String privCert; - @LogLevel(Log4jLevel.Off) - private String certChain; - - public Certificates() { - - } - - public Certificates(String prvKey, String privCert, String certChain) { - this.privKey = prvKey; - this.privCert = privCert; - this.certChain = certChain; - } - - public String getPrivKey() { - return this.privKey; - } - - public String getPrivCert() { - return this.privCert; - } - - public String getCertChain() { - return this.certChain; - } - } public SecStorageSetupCommand() { super(); } - public SecStorageSetupCommand(DataStoreTO store, String secUrl, Certificates certs) { + public SecStorageSetupCommand(DataStoreTO store, String secUrl, KeystoreManager.Certificates certs) { super(); this.secUrl = secUrl; this.certs = certs; @@ -75,8 +46,8 @@ public class SecStorageSetupCommand extends Command { return secUrl; } - public Certificates getCerts() { - return this.certs; + public KeystoreManager.Certificates getCerts() { + return certs; } public void setSecUrl(String secUrl) { diff --git a/core/src/com/cloud/agent/api/SetupCommand.java b/core/src/com/cloud/agent/api/SetupCommand.java index 65700e9453c..ee43c5933da 100644 --- a/core/src/com/cloud/agent/api/SetupCommand.java +++ b/core/src/com/cloud/agent/api/SetupCommand.java @@ -23,8 +23,6 @@ public class SetupCommand extends Command { HostEnvironment env; boolean multipath; boolean needSetup; - String secondaryStorage; - String systemVmIso; public boolean needSetup() { return needSetup; @@ -38,8 +36,6 @@ public class SetupCommand extends Command { this.env = env; this.multipath = false; this.needSetup = false; - secondaryStorage = null; - systemVmIso = null; } public HostEnvironment getEnvironment() { @@ -57,22 +53,6 @@ public class SetupCommand extends Command { return multipath; } - public void setSecondaryStorage(String secondaryStorage) { - this.secondaryStorage = secondaryStorage; - } - - public String getSecondaryStorage() { - return this.secondaryStorage; - } - - public void setSystemVmIso(String systemVmIso) { - this.systemVmIso = systemVmIso; - } - - public String getSystemVmIso() { - return this.systemVmIso; - } - @Override public boolean executeInSequence() { return true; diff --git a/core/src/com/cloud/agent/api/StartAnswer.java b/core/src/com/cloud/agent/api/StartAnswer.java index 92dce84b6df..3bd7bff65db 100644 --- a/core/src/com/cloud/agent/api/StartAnswer.java +++ b/core/src/com/cloud/agent/api/StartAnswer.java @@ -22,7 +22,7 @@ import com.cloud.agent.api.to.VirtualMachineTO; public class StartAnswer extends Answer { VirtualMachineTO vm; - String host_guid; + String hostGuid; Map _iqnToPath; protected StartAnswer() { @@ -41,13 +41,13 @@ public class StartAnswer extends Answer { public StartAnswer(StartCommand cmd) { super(cmd, true, null); this.vm = cmd.getVirtualMachine(); - this.host_guid = null; + this.hostGuid = null; } public StartAnswer(StartCommand cmd, String msg, String guid) { super(cmd, true, msg); this.vm = cmd.getVirtualMachine(); - this.host_guid = guid; + this.hostGuid = guid; } public VirtualMachineTO getVirtualMachine() { @@ -55,7 +55,7 @@ public class StartAnswer extends Answer { } public String getHost_guid() { - return host_guid; + return hostGuid; } public void setIqnToPath(Map iqnToPath) { diff --git a/core/src/com/cloud/agent/api/StartCommand.java b/core/src/com/cloud/agent/api/StartCommand.java index 308730ab5b7..88810c6ba5d 100644 --- a/core/src/com/cloud/agent/api/StartCommand.java +++ b/core/src/com/cloud/agent/api/StartCommand.java @@ -25,6 +25,7 @@ public class StartCommand extends Command { VirtualMachineTO vm; String hostIp; boolean executeInSequence = false; + String secondaryStorage; public VirtualMachineTO getVirtualMachine() { return vm; @@ -42,9 +43,18 @@ public class StartCommand extends Command { this.vm = vm; this.hostIp = host.getPrivateIpAddress(); this.executeInSequence = executeInSequence; + this.secondaryStorage = null; } public String getHostIp() { return this.hostIp; } + + public String getSecondaryStorage() { + return this.secondaryStorage; + } + + public void setSecondaryStorage(String secondary) { + this.secondaryStorage = secondary; + } } diff --git a/core/src/com/cloud/agent/api/StopAnswer.java b/core/src/com/cloud/agent/api/StopAnswer.java index b5931747175..ff2cd191899 100755 --- a/core/src/com/cloud/agent/api/StopAnswer.java +++ b/core/src/com/cloud/agent/api/StopAnswer.java @@ -24,12 +24,12 @@ public class StopAnswer extends RebootAnswer { } public StopAnswer(StopCommand cmd, String details, String platform, boolean success) { - super(cmd, details, success); + super(cmd, details, success); this.platform = platform; } public StopAnswer(StopCommand cmd, String details, boolean success) { - super(cmd, details, success); + super(cmd, details, success); this.platform = null; } diff --git a/core/src/com/cloud/agent/api/UpdateHostPasswordCommand.java b/core/src/com/cloud/agent/api/UpdateHostPasswordCommand.java index 6e448eeade4..15fb7140e9c 100644 --- a/core/src/com/cloud/agent/api/UpdateHostPasswordCommand.java +++ b/core/src/com/cloud/agent/api/UpdateHostPasswordCommand.java @@ -20,24 +20,24 @@ import com.cloud.agent.api.LogLevel.Log4jLevel; public class UpdateHostPasswordCommand extends Command { @LogLevel(Log4jLevel.Off) - protected String _username; + protected String username; @LogLevel(Log4jLevel.Off) - protected String _new_password; + protected String newPassword; protected UpdateHostPasswordCommand() { } - public UpdateHostPasswordCommand(String username, String new_password) { - this._username = username; - this._new_password = new_password; + public UpdateHostPasswordCommand(String username, String newPassword) { + this.username = username; + this.newPassword = newPassword; } public String getNewPassword() { - return _new_password; + return newPassword; } public String getUsername() { - return _username; + return username; } @Override diff --git a/core/src/com/cloud/agent/api/baremetal/prepareCreateTemplateCommand.java b/core/src/com/cloud/agent/api/baremetal/PrepareCreateTemplateCommand.java similarity index 93% rename from core/src/com/cloud/agent/api/baremetal/prepareCreateTemplateCommand.java rename to core/src/com/cloud/agent/api/baremetal/PrepareCreateTemplateCommand.java index b18742055df..f88526a8250 100644 --- a/core/src/com/cloud/agent/api/baremetal/prepareCreateTemplateCommand.java +++ b/core/src/com/cloud/agent/api/baremetal/PrepareCreateTemplateCommand.java @@ -18,7 +18,7 @@ package com.cloud.agent.api.baremetal; import com.cloud.agent.api.Command; -public class prepareCreateTemplateCommand extends Command { +public class PrepareCreateTemplateCommand extends Command { String ip; String mac; String netMask; @@ -31,7 +31,7 @@ public class prepareCreateTemplateCommand extends Command { return true; } - public prepareCreateTemplateCommand(String ip, String mac, String netMask, String gateway, String dns, String template) { + public PrepareCreateTemplateCommand(String ip, String mac, String netMask, String gateway, String dns, String template) { this.ip = ip; this.mac = mac; this.netMask = netMask; diff --git a/core/src/com/cloud/agent/api/routing/IpAliasTO.java b/core/src/com/cloud/agent/api/routing/IpAliasTO.java index fac3ed5af8f..3876e148dbe 100644 --- a/core/src/com/cloud/agent/api/routing/IpAliasTO.java +++ b/core/src/com/cloud/agent/api/routing/IpAliasTO.java @@ -19,12 +19,12 @@ package com.cloud.agent.api.routing; public class IpAliasTO { String routerip; String netmask; - String alias_count; + String aliasCount; - public IpAliasTO(String routerip, String netmask, String alias_count) { + public IpAliasTO(String routerip, String netmask, String aliasCount) { this.routerip = routerip; this.netmask = netmask; - this.alias_count = alias_count; + this.aliasCount = aliasCount; } public String getRouterip() { @@ -36,6 +36,6 @@ public class IpAliasTO { } public String getAlias_count() { - return alias_count; + return aliasCount; } } diff --git a/core/src/com/cloud/agent/api/routing/LoadBalancerConfigCommand.java b/core/src/com/cloud/agent/api/routing/LoadBalancerConfigCommand.java index 5c54375dba6..06ef62b104f 100644 --- a/core/src/com/cloud/agent/api/routing/LoadBalancerConfigCommand.java +++ b/core/src/com/cloud/agent/api/routing/LoadBalancerConfigCommand.java @@ -46,12 +46,12 @@ public class LoadBalancerConfigCommand extends NetworkElementCommand { this.vpcId = vpcId; } - public LoadBalancerConfigCommand(LoadBalancerTO[] loadBalancers, String PublicIp, String GuestIp, String PrivateIp, NicTO nic, Long vpcId, String maxconn, + public LoadBalancerConfigCommand(LoadBalancerTO[] loadBalancers, String publicIp, String guestIp, String privateIp, NicTO nic, Long vpcId, String maxconn, boolean keepAliveEnabled) { this.loadBalancers = loadBalancers; - this.lbStatsPublicIP = PublicIp; - this.lbStatsPrivateIP = PrivateIp; - this.lbStatsGuestIP = GuestIp; + this.lbStatsPublicIP = publicIp; + this.lbStatsPrivateIP = privateIp; + this.lbStatsGuestIP = guestIp; this.nic = nic; this.vpcId = vpcId; this.maxconn = maxconn; diff --git a/core/src/com/cloud/agent/api/routing/NetworkElementCommand.java b/core/src/com/cloud/agent/api/routing/NetworkElementCommand.java index 9a2bea875b4..217e962d18a 100644 --- a/core/src/com/cloud/agent/api/routing/NetworkElementCommand.java +++ b/core/src/com/cloud/agent/api/routing/NetworkElementCommand.java @@ -16,10 +16,10 @@ // under the License. package com.cloud.agent.api.routing; -import java.util.HashMap; - import com.cloud.agent.api.Command; +import java.util.HashMap; + public abstract class NetworkElementCommand extends Command { HashMap accessDetails = new HashMap(0); @@ -35,6 +35,8 @@ public abstract class NetworkElementCommand extends Command { public static final String VPC_PRIVATE_GATEWAY = "vpc.gateway.private"; public static final String FIREWALL_EGRESS_DEFAULT = "firewall.egress.default"; + private String routerAccessIp; + protected NetworkElementCommand() { super(); } @@ -52,4 +54,11 @@ public abstract class NetworkElementCommand extends Command { return false; } + public String getRouterAccessIp() { + return routerAccessIp; + } + + public void setRouterAccessIp(String routerAccessIp) { + this.routerAccessIp = routerAccessIp; + } } diff --git a/core/src/com/cloud/agent/api/storage/AbstractDownloadCommand.java b/core/src/com/cloud/agent/api/storage/AbstractDownloadCommand.java index 097717503a7..097af66ad00 100644 --- a/core/src/com/cloud/agent/api/storage/AbstractDownloadCommand.java +++ b/core/src/com/cloud/agent/api/storage/AbstractDownloadCommand.java @@ -18,7 +18,7 @@ package com.cloud.agent.api.storage; import com.cloud.storage.Storage.ImageFormat; -public abstract class AbstractDownloadCommand extends ssCommand { +public abstract class AbstractDownloadCommand extends SsCommand { private String url; private ImageFormat format; diff --git a/core/src/com/cloud/agent/api/storage/CreatePrivateTemplateAnswer.java b/core/src/com/cloud/agent/api/storage/CreatePrivateTemplateAnswer.java index 56d9c30912c..250405eedb2 100644 --- a/core/src/com/cloud/agent/api/storage/CreatePrivateTemplateAnswer.java +++ b/core/src/com/cloud/agent/api/storage/CreatePrivateTemplateAnswer.java @@ -61,8 +61,8 @@ public class CreatePrivateTemplateAnswer extends Answer { _virtualSize = virtualSize; } - public void setphysicalSize(long _physicalSize) { - this._physicalSize = _physicalSize; + public void setphysicalSize(long physicalSize) { + this._physicalSize = physicalSize; } public long getphysicalSize() { diff --git a/core/src/com/cloud/agent/api/storage/MigrateVolumeCommand.java b/core/src/com/cloud/agent/api/storage/MigrateVolumeCommand.java index b82d8481f2c..b73a48a1b37 100644 --- a/core/src/com/cloud/agent/api/storage/MigrateVolumeCommand.java +++ b/core/src/com/cloud/agent/api/storage/MigrateVolumeCommand.java @@ -25,6 +25,7 @@ public class MigrateVolumeCommand extends Command { long volumeId; String volumePath; StorageFilerTO pool; + String attachedVmName; public MigrateVolumeCommand(long volumeId, String volumePath, StoragePool pool) { this.volumeId = volumeId; @@ -32,6 +33,13 @@ public class MigrateVolumeCommand extends Command { this.pool = new StorageFilerTO(pool); } + public MigrateVolumeCommand(long volumeId, String volumePath, StoragePool pool, String attachedVmName) { + this.volumeId = volumeId; + this.volumePath = volumePath; + this.pool = new StorageFilerTO(pool); + this.attachedVmName = attachedVmName; + } + @Override public boolean executeInSequence() { return true; @@ -48,4 +56,8 @@ public class MigrateVolumeCommand extends Command { public StorageFilerTO getPool() { return pool; } + + public String getAttachedVmName() { + return attachedVmName; + } } \ No newline at end of file diff --git a/core/src/com/cloud/agent/api/storage/ssCommand.java b/core/src/com/cloud/agent/api/storage/SsCommand.java similarity index 88% rename from core/src/com/cloud/agent/api/storage/ssCommand.java rename to core/src/com/cloud/agent/api/storage/SsCommand.java index 939e394705f..d4a6e5b73cd 100644 --- a/core/src/com/cloud/agent/api/storage/ssCommand.java +++ b/core/src/com/cloud/agent/api/storage/SsCommand.java @@ -18,17 +18,17 @@ package com.cloud.agent.api.storage; import com.cloud.agent.api.Command; -public abstract class ssCommand extends Command { +public abstract class SsCommand extends Command { private String secUrl; - public ssCommand() { + public SsCommand() { } - protected ssCommand(ssCommand that) { + protected SsCommand(SsCommand that) { this.secUrl = that.secUrl; } - public ssCommand(String secUrl) { + public SsCommand(String secUrl) { this.secUrl = secUrl; } diff --git a/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRouterDeployer.java b/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRouterDeployer.java new file mode 100644 index 00000000000..243098abeab --- /dev/null +++ b/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRouterDeployer.java @@ -0,0 +1,27 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.agent.resource.virtualnetwork; + +import com.cloud.agent.api.routing.NetworkElementCommand; +import com.cloud.utils.ExecutionResult; + +public interface VirtualRouterDeployer { + ExecutionResult executeInVR(String routerIp, String script, String args); + ExecutionResult createFileInVR(String routerIp, String path, String filename, String content); + ExecutionResult prepareCommand(NetworkElementCommand cmd); + ExecutionResult cleanupCommand(NetworkElementCommand cmd); +} diff --git a/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java b/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java index 34450fe1601..1ed38644536 100755 --- a/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java +++ b/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java @@ -16,30 +16,6 @@ // under the License. package com.cloud.agent.resource.virtualnetwork; -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.net.InetSocketAddress; -import java.net.URL; -import java.net.URLConnection; -import java.nio.channels.SocketChannel; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.ejb.Local; -import javax.naming.ConfigurationException; - -import org.apache.commons.codec.binary.Base64; -import org.apache.log4j.Logger; - -import com.google.gson.Gson; - import com.cloud.agent.api.Answer; import com.cloud.agent.api.BumpUpPriorityCommand; import com.cloud.agent.api.CheckRouterAnswer; @@ -49,9 +25,8 @@ import com.cloud.agent.api.CheckS2SVpnConnectionsCommand; import com.cloud.agent.api.Command; import com.cloud.agent.api.GetDomRVersionAnswer; import com.cloud.agent.api.GetDomRVersionCmd; -import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand; -import com.cloud.agent.api.proxy.ConsoleProxyLoadAnswer; -import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand; +import com.cloud.agent.api.SetupGuestNetworkAnswer; +import com.cloud.agent.api.SetupGuestNetworkCommand; import com.cloud.agent.api.routing.CreateIpAliasCommand; import com.cloud.agent.api.routing.DeleteIpAliasCommand; import com.cloud.agent.api.routing.DhcpEntryCommand; @@ -59,15 +34,21 @@ import com.cloud.agent.api.routing.DnsMasqConfigCommand; import com.cloud.agent.api.routing.IpAliasTO; import com.cloud.agent.api.routing.IpAssocAnswer; import com.cloud.agent.api.routing.IpAssocCommand; +import com.cloud.agent.api.routing.IpAssocVpcCommand; import com.cloud.agent.api.routing.LoadBalancerConfigCommand; import com.cloud.agent.api.routing.NetworkElementCommand; import com.cloud.agent.api.routing.RemoteAccessVpnCfgCommand; import com.cloud.agent.api.routing.SavePasswordCommand; import com.cloud.agent.api.routing.SetFirewallRulesAnswer; import com.cloud.agent.api.routing.SetFirewallRulesCommand; +import com.cloud.agent.api.routing.SetMonitorServiceCommand; +import com.cloud.agent.api.routing.SetNetworkACLAnswer; +import com.cloud.agent.api.routing.SetNetworkACLCommand; import com.cloud.agent.api.routing.SetPortForwardingRulesAnswer; import com.cloud.agent.api.routing.SetPortForwardingRulesCommand; import com.cloud.agent.api.routing.SetPortForwardingRulesVpcCommand; +import com.cloud.agent.api.routing.SetSourceNatAnswer; +import com.cloud.agent.api.routing.SetSourceNatCommand; import com.cloud.agent.api.routing.SetStaticNatRulesAnswer; import com.cloud.agent.api.routing.SetStaticNatRulesCommand; import com.cloud.agent.api.routing.SetStaticRouteAnswer; @@ -78,19 +59,26 @@ import com.cloud.agent.api.routing.VpnUsersCfgCommand; import com.cloud.agent.api.to.DhcpTO; import com.cloud.agent.api.to.FirewallRuleTO; import com.cloud.agent.api.to.IpAddressTO; +import com.cloud.agent.api.to.NicTO; import com.cloud.agent.api.to.PortForwardingRuleTO; import com.cloud.agent.api.to.StaticNatRuleTO; -import com.cloud.exception.InternalErrorException; import com.cloud.network.HAProxyConfigurator; import com.cloud.network.LoadBalancerConfigurator; import com.cloud.network.rules.FirewallRule; +import com.cloud.utils.ExecutionResult; import com.cloud.utils.NumbersUtil; -import com.cloud.utils.component.ComponentLifecycle; -import com.cloud.utils.component.Manager; import com.cloud.utils.net.NetUtils; -import com.cloud.utils.script.OutputInterpreter; -import com.cloud.utils.script.Script; -import com.cloud.utils.ssh.SshHelper; +import com.google.gson.Gson; +import org.apache.commons.codec.binary.Base64; +import org.apache.log4j.Logger; + +import javax.naming.ConfigurationException; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.channels.SocketChannel; +import java.util.HashMap; +import java.util.List; +import java.util.Map; /** * VirtualNetworkResource controls and configures virtual networking @@ -100,31 +88,27 @@ import com.cloud.utils.ssh.SshHelper; * || Param Name | Description | Values | Default || * } **/ -@Local(value = {VirtualRoutingResource.class}) -public class VirtualRoutingResource implements Manager { +public class VirtualRoutingResource { private static final Logger s_logger = Logger.getLogger(VirtualRoutingResource.class); - private String _publicIpAddress; - private String _firewallPath; - private String _loadbPath; - private String _dhcpEntryPath; - private String _publicEthIf; - private String _privateEthIf; - private String _bumpUpPriorityPath; - private String _routerProxyPath; - private String _createIpAliasPath; - private String _deleteIpAliasPath; - private String _callDnsMasqPath; + private VirtualRouterDeployer _vrDeployer; - private int _timeout; - private int _startTimeout; - private String _scriptsDir; private String _name; private int _sleep; private int _retry; private int _port; + public VirtualRoutingResource(VirtualRouterDeployer deployer) { + this._vrDeployer = deployer; + } + public Answer executeRequest(final Command cmd) { try { + ExecutionResult rc = _vrDeployer.prepareCommand((NetworkElementCommand)cmd); + if (!rc.isSuccess()) { + s_logger.error("Failed to prepare VR command due to " + rc.getDetails()); + return new Answer(cmd, false, rc.getDetails()); + } + if (cmd instanceof SetPortForwardingRulesVpcCommand) { return execute((SetPortForwardingRulesVpcCommand)cmd); } else if (cmd instanceof SetPortForwardingRulesCommand) { @@ -135,12 +119,6 @@ public class VirtualRoutingResource implements Manager { return execute((SetStaticNatRulesCommand)cmd); } else if (cmd instanceof LoadBalancerConfigCommand) { return execute((LoadBalancerConfigCommand)cmd); - } else if (cmd instanceof IpAssocCommand) { - return execute((IpAssocCommand)cmd); - } else if (cmd instanceof CheckConsoleProxyLoadCommand) { - return execute((CheckConsoleProxyLoadCommand)cmd); - } else if (cmd instanceof WatchConsoleProxyLoadCommand) { - return execute((WatchConsoleProxyLoadCommand)cmd); } else if (cmd instanceof SavePasswordCommand) { return execute((SavePasswordCommand)cmd); } else if (cmd instanceof DhcpEntryCommand) { @@ -169,11 +147,28 @@ public class VirtualRoutingResource implements Manager { return execute((Site2SiteVpnCfgCommand)cmd); } else if (cmd instanceof CheckS2SVpnConnectionsCommand) { return execute((CheckS2SVpnConnectionsCommand)cmd); + } else if (cmd instanceof SetMonitorServiceCommand) { + return execute((SetMonitorServiceCommand)cmd); + } else if (cmd instanceof SetupGuestNetworkCommand) { + return execute((SetupGuestNetworkCommand)cmd); + } else if (cmd instanceof SetNetworkACLCommand) { + return execute((SetNetworkACLCommand)cmd); + } else if (cmd instanceof SetSourceNatCommand) { + return execute((SetSourceNatCommand)cmd); + } else if (cmd instanceof IpAssocVpcCommand) { + return execute((IpAssocVpcCommand)cmd); + } else if (cmd instanceof IpAssocCommand) { + return execute((IpAssocCommand)cmd); } else { return Answer.createUnsupportedCommandAnswer(cmd); } } catch (final IllegalArgumentException e) { return new Answer(cmd, false, e.getMessage()); + } finally { + ExecutionResult rc = _vrDeployer.cleanupCommand((NetworkElementCommand)cmd); + if (!rc.isSuccess()) { + s_logger.error("Failed to cleanup VR command due to " + rc.getDetails()); + } } } @@ -187,9 +182,9 @@ public class VirtualRoutingResource implements Manager { args += "-u "; args += userpwd.getUsernamePassword(); } - String result = routerProxy("vpn_l2tp.sh", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), args); - if (result != null) { - return new Answer(cmd, false, "Configure VPN user failed for user " + userpwd.getUsername()); + ExecutionResult result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "vpn_l2tp.sh", args); + if (!result.isSuccess()) { + return new Answer(cmd, false, "Configure VPN user failed for user " + userpwd.getUsername() + ":" + result.getDetails()); } } return new Answer(cmd); @@ -214,22 +209,16 @@ public class VirtualRoutingResource implements Manager { } args += " -C " + cmd.getLocalCidr(); args += " -i " + cmd.getPublicInterface(); - String result = routerProxy("vpn_l2tp.sh", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), args); - if (result != null) { - return new Answer(cmd, false, "Configure VPN failed"); - } - return new Answer(cmd); + ExecutionResult result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "vpn_l2tp.sh", args); + return new Answer(cmd, result.isSuccess(), result.getDetails()); } private Answer execute(SetFirewallRulesCommand cmd) { String[] results = new String[cmd.getRules().length]; - for (int i = 0; i < cmd.getRules().length; i++) { - results[i] = "Failed"; - } - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); + String routerAccessIp = cmd.getRouterAccessIp(); String egressDefault = cmd.getAccessDetail(NetworkElementCommand.FIREWALL_EGRESS_DEFAULT); - if (routerIp == null) { + if (routerAccessIp == null) { return new SetFirewallRulesAnswer(cmd, false, results); } @@ -237,18 +226,16 @@ public class VirtualRoutingResource implements Manager { FirewallRule.TrafficType trafficType = allrules[0].getTrafficType(); String[][] rules = cmd.generateFwRules(); - final Script command = new Script(_firewallPath, _timeout, s_logger); - command.add(routerIp); - command.add("-F"); + String args = " -F"; if (trafficType == FirewallRule.TrafficType.Egress) { - command.add("-E"); + args += " -E"; if (egressDefault.equals("true")) { - command.add("-P ", "1"); + args += " -P 1"; } else if (egressDefault.equals("System")) { - command.add("-P ", "2"); + args += " -P 2"; } else { - command.add("-P ", "0"); + args += " -P 0"; } } @@ -258,47 +245,55 @@ public class VirtualRoutingResource implements Manager { for (int i = 0; i < fwRules.length; i++) { sb.append(fwRules[i]).append(','); } - command.add("-a", sb.toString()); + args += " -a " + sb.toString(); } - String result = command.execute(); - if (result != null) { + ExecutionResult result; + + if (trafficType == FirewallRule.TrafficType.Egress) { + result = _vrDeployer.executeInVR(routerAccessIp, "firewall_egress.sh", args); + } else { + result = _vrDeployer.executeInVR(routerAccessIp, "firewall_ingress.sh", args); + } + + if (!result.isSuccess()) { + //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails + for (int i = 0; i < results.length; i++) { + results[i] = "Failed: " + result.getDetails(); + } return new SetFirewallRulesAnswer(cmd, false, results); } - return new SetFirewallRulesAnswer(cmd, true, null); + return new SetFirewallRulesAnswer(cmd, true, results); } private Answer execute(SetPortForwardingRulesCommand cmd) { - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String[] results = new String[cmd.getRules().length]; int i = 0; boolean endResult = true; for (PortForwardingRuleTO rule : cmd.getRules()) { - String result = null; - final Script command = new Script(_firewallPath, _timeout, s_logger); + StringBuilder args = new StringBuilder(); + args.append(rule.revoked() ? " -D " : " -A "); + args.append(" -P ").append(rule.getProtocol().toLowerCase()); + args.append(" -l ").append(rule.getSrcIp()); + args.append(" -p ").append(rule.getStringSrcPortRange()); + args.append(" -r ").append(rule.getDstIp()); + args.append(" -d ").append(rule.getStringDstPortRange()); - command.add(routerIp); - command.add(rule.revoked() ? "-D" : "-A"); - command.add("-P ", rule.getProtocol().toLowerCase()); - command.add("-l ", rule.getSrcIp()); - command.add("-p ", rule.getStringSrcPortRange()); - command.add("-r ", rule.getDstIp()); - command.add("-d ", rule.getStringDstPortRange()); - result = command.execute(); - if (result == null) { - results[i++] = null; - } else { + ExecutionResult result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "firewall_nat.sh", args.toString()); + + if (!result.isSuccess()) { results[i++] = "Failed"; endResult = false; + } else { + results[i++] = null; } } return new SetPortForwardingRulesAnswer(cmd, results, endResult); } - protected Answer SetVPCStaticNatRules(SetStaticNatRulesCommand cmd) { - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); + protected SetStaticNatRulesAnswer SetVPCStaticNatRules(SetStaticNatRulesCommand cmd) { String[] results = new String[cmd.getRules().length]; int i = 0; boolean endResult = true; @@ -308,9 +303,9 @@ public class VirtualRoutingResource implements Manager { args += " -l " + rule.getSrcIp(); args += " -r " + rule.getDstIp(); - String result = routerProxy("vpc_staticnat.sh", routerIp, args); + ExecutionResult result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "vpc_staticnat.sh", args); - if (result == null) { + if (!result.isSuccess()) { results[i++] = null; } else { results[i++] = "Failed"; @@ -321,44 +316,41 @@ public class VirtualRoutingResource implements Manager { } - private Answer execute(SetStaticNatRulesCommand cmd) { + private SetStaticNatRulesAnswer execute(SetStaticNatRulesCommand cmd) { if (cmd.getVpcId() != null) { return SetVPCStaticNatRules(cmd); } - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String[] results = new String[cmd.getRules().length]; int i = 0; boolean endResult = true; for (StaticNatRuleTO rule : cmd.getRules()) { - String result = null; - final Script command = new Script(_firewallPath, _timeout, s_logger); - command.add(routerIp); - command.add(rule.revoked() ? "-D" : "-A"); - //1:1 NAT needs instanceip;publicip;domrip;op - command.add(" -l ", rule.getSrcIp()); - command.add(" -r ", rule.getDstIp()); + StringBuilder args = new StringBuilder(); + args.append(rule.revoked() ? " -D " : " -A "); + args.append(" -l ").append(rule.getSrcIp()); + args.append(" -r ").append(rule.getDstIp()); if (rule.getProtocol() != null) { - command.add(" -P ", rule.getProtocol().toLowerCase()); + args.append(" -P ").append(rule.getProtocol().toLowerCase()); } - command.add(" -d ", rule.getStringSrcPortRange()); - command.add(" -G "); + args.append(" -d ").append(rule.getStringSrcPortRange()); + args.append(" -G "); - result = command.execute(); - if (result == null) { - results[i++] = null; - } else { + ExecutionResult result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "firewall_nat.sh", args.toString()); + + if (!result.isSuccess()) { results[i++] = "Failed"; endResult = false; + } else { + results[i++] = null; } } return new SetStaticNatRulesAnswer(cmd, results, endResult); } - protected Answer VPCLoadBalancerConfig(final LoadBalancerConfigCommand cmd) { + private Answer execute(LoadBalancerConfigCommand cmd) { String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); if (routerIp == null) { @@ -372,96 +364,61 @@ public class VirtualRoutingResource implements Manager { tmpCfgFileContents += config[i]; tmpCfgFileContents += "\n"; } - File permKey = new File("/root/.ssh/id_rsa.cloud"); - try { - SshHelper.scpTo(routerIp, 3922, "root", permKey, null, "/etc/haproxy/", tmpCfgFileContents.getBytes(), "haproxy.cfg.new", null); + String tmpCfgFilePath = "/etc/haproxy/"; + String tmpCfgFileName = "haproxy.cfg.new"; + ExecutionResult result = _vrDeployer.createFileInVR(cmd.getRouterAccessIp(), tmpCfgFilePath, tmpCfgFileName, tmpCfgFileContents); - String[][] rules = cfgtr.generateFwRules(cmd); - - String[] addRules = rules[LoadBalancerConfigurator.ADD]; - String[] removeRules = rules[LoadBalancerConfigurator.REMOVE]; - String[] statRules = rules[LoadBalancerConfigurator.STATS]; - - String ip = cmd.getNic().getIp(); - String args = " -i " + ip; - StringBuilder sb = new StringBuilder(); - if (addRules.length > 0) { - for (int i = 0; i < addRules.length; i++) { - sb.append(addRules[i]).append(','); - } - - args += " -a " + sb.toString(); - } - - sb = new StringBuilder(); - if (removeRules.length > 0) { - for (int i = 0; i < removeRules.length; i++) { - sb.append(removeRules[i]).append(','); - } - - args += " -d " + sb.toString(); - } - - sb = new StringBuilder(); - if (statRules.length > 0) { - for (int i = 0; i < statRules.length; i++) { - sb.append(statRules[i]).append(','); - } - - args += " -s " + sb.toString(); - } - - String result = routerProxy("vpc_loadbalancer.sh", routerIp, args); - - if (result != null) { - return new Answer(cmd, false, "LoadBalancerConfigCommand failed"); - } - return new Answer(cmd); - - } catch (Exception e) { - return new Answer(cmd, e); + if (!result.isSuccess()) { + return new Answer(cmd, false, "Fail to copy LB config file to VR"); } + + String[][] rules = cfgtr.generateFwRules(cmd); + + String[] addRules = rules[LoadBalancerConfigurator.ADD]; + String[] removeRules = rules[LoadBalancerConfigurator.REMOVE]; + String[] statRules = rules[LoadBalancerConfigurator.STATS]; + + String args = ""; + StringBuilder sb = new StringBuilder(); + if (addRules.length > 0) { + for (int i = 0; i < addRules.length; i++) { + sb.append(addRules[i]).append(','); + } + args += " -a " + sb.toString(); + } + + sb = new StringBuilder(); + if (removeRules.length > 0) { + for (int i = 0; i < removeRules.length; i++) { + sb.append(removeRules[i]).append(','); + } + + args += " -d " + sb.toString(); + } + + sb = new StringBuilder(); + if (statRules.length > 0) { + for (int i = 0; i < statRules.length; i++) { + sb.append(statRules[i]).append(','); + } + + args += " -s " + sb.toString(); + } + + if (cmd.getVpcId() == null) { + args = " -i " + routerIp + args; + result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "loadbalancer.sh", args); + } else { + args = " -i " + cmd.getNic().getIp() + args; + result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "vpc_loadbalancer.sh", args); + } + + return new Answer(cmd, result.isSuccess(), result.getDetails()); } - private Answer execute(LoadBalancerConfigCommand cmd) { - if (cmd.getVpcId() != null) { - return VPCLoadBalancerConfig(cmd); - } - - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - File tmpCfgFile = null; - try { - String cfgFilePath = ""; - LoadBalancerConfigurator cfgtr = new HAProxyConfigurator(); - String[] config = cfgtr.generateConfiguration(cmd); - String[][] rules = cfgtr.generateFwRules(cmd); - if (routerIp != null) { - tmpCfgFile = File.createTempFile(routerIp.replace('.', '_'), "cfg"); - final PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(tmpCfgFile))); - for (int i = 0; i < config.length; i++) { - out.println(config[i]); - } - out.close(); - cfgFilePath = tmpCfgFile.getAbsolutePath(); - } - - final String result = - setLoadBalancerConfig(cfgFilePath, rules[LoadBalancerConfigurator.ADD], rules[LoadBalancerConfigurator.REMOVE], rules[LoadBalancerConfigurator.STATS], - routerIp); - - return new Answer(cmd, result == null, result); - } catch (final IOException e) { - return new Answer(cmd, false, e.getMessage()); - } finally { - if (tmpCfgFile != null) { - tmpCfgFile.delete(); - } - } - } protected Answer execute(VmDataCommand cmd) { - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); Map> data = new HashMap>(); data.put(cmd.getVmIpAddress(), cmd.getVmData()); @@ -472,186 +429,88 @@ public class VirtualRoutingResource implements Manager { String args = "-d " + json; - final String result = routerProxy("vmdata.py", routerIp, args); - if (result != null) { - return new Answer(cmd, false, "VmDataCommand failed, check agent logs"); - } - return new Answer(cmd); - } - - protected Answer execute(final IpAssocCommand cmd) { - IpAddressTO[] ips = cmd.getIpAddresses(); - String[] results = new String[cmd.getIpAddresses().length]; - int i = 0; - String result = null; - String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - for (IpAddressTO ip : ips) { - result = - assignPublicIpAddress(routerName, routerIp, ip.getPublicIp(), ip.isAdd(), ip.isFirstIP(), ip.isSourceNat(), ip.getBroadcastUri(), ip.getVlanGateway(), - ip.getVlanNetmask(), ip.getVifMacAddress(), 2, false); - if (result != null) { - results[i++] = IpAssocAnswer.errorResult; - } else { - results[i++] = ip.getPublicIp() + " - success"; - ; - } - } - return new IpAssocAnswer(cmd, results); - } - - private String setLoadBalancerConfig(final String cfgFile, final String[] addRules, final String[] removeRules, final String[] statsRules, String routerIp) { - - if (routerIp == null) { - routerIp = "none"; - } - - final Script command = new Script(_loadbPath, _timeout, s_logger); - - command.add("-i", routerIp); - command.add("-f", cfgFile); - - StringBuilder sb = new StringBuilder(); - if (addRules.length > 0) { - for (int i = 0; i < addRules.length; i++) { - sb.append(addRules[i]).append(','); - } - command.add("-a", sb.toString()); - } - - sb = new StringBuilder(); - if (removeRules.length > 0) { - for (int i = 0; i < removeRules.length; i++) { - sb.append(removeRules[i]).append(','); - } - command.add("-d", sb.toString()); - } - - sb = new StringBuilder(); - if (statsRules.length > 0) { - for (int i = 0; i < statsRules.length; i++) { - sb.append(statsRules[i]).append(','); - } - command.add("-s", sb.toString()); - } - - return command.execute(); + final ExecutionResult result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "vmdata.py", args); + return new Answer(cmd, result.isSuccess(), result.getDetails()); } protected Answer execute(final SavePasswordCommand cmd) { final String password = cmd.getPassword(); final String routerPrivateIPAddress = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - final String vmName = cmd.getVmName(); final String vmIpAddress = cmd.getVmIpAddress(); - final String local = vmName; String args = "-v " + vmIpAddress; args += " -p " + password; - String result = routerProxy("savepassword.sh", routerPrivateIPAddress, args); - if (result != null) { - return new Answer(cmd, false, "Unable to save password to DomR."); - } - return new Answer(cmd); + ExecutionResult result = _vrDeployer.executeInVR(routerPrivateIPAddress, "savepassword.sh", args); + return new Answer(cmd, result.isSuccess(), result.getDetails()); } protected Answer execute(final DhcpEntryCommand cmd) { - final Script command = new Script(_dhcpEntryPath, _timeout, s_logger); - command.add("-r", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP)); + String args = " -m " + cmd.getVmMac(); if (cmd.getVmIpAddress() != null) { - command.add("-v", cmd.getVmIpAddress()); + args += " -4 " + cmd.getVmIpAddress(); } - command.add("-m", cmd.getVmMac()); - command.add("-n", cmd.getVmName()); + args += " -h " + cmd.getVmName(); if (cmd.getDefaultRouter() != null) { - command.add("-d", cmd.getDefaultRouter()); - } - if (cmd.getStaticRoutes() != null) { - command.add("-s", cmd.getStaticRoutes()); + args += " -d " + cmd.getDefaultRouter(); } if (cmd.getDefaultDns() != null) { - command.add("-N", cmd.getDefaultDns()); + args += " -n " + cmd.getDefaultDns(); + } + + if (cmd.getStaticRoutes() != null) { + args += " -s " + cmd.getStaticRoutes(); } if (cmd.getVmIp6Address() != null) { - command.add("-6", cmd.getVmIp6Address()); - command.add("-u", cmd.getDuid()); + args += " -6 " + cmd.getVmIp6Address(); + args += " -u " + cmd.getDuid(); } if (!cmd.isDefault()) { - command.add("-z"); + args += " -N"; } - final String result = command.execute(); - return new Answer(cmd, result == null, result); + final ExecutionResult result = _vrDeployer.executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "edithosts.sh", args); + return new Answer(cmd, result.isSuccess(), result.getDetails()); } protected Answer execute(final CreateIpAliasCommand cmd) { - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - final Script command = new Script(_createIpAliasPath, _timeout, s_logger); List ipAliasTOs = cmd.getIpAliasList(); String args = ""; - command.add(routerIp); for (IpAliasTO ipaliasto : ipAliasTOs) { args = args + ipaliasto.getAlias_count() + ":" + ipaliasto.getRouterip() + ":" + ipaliasto.getNetmask() + "-"; } - command.add(args); - final String result = command.execute(); - return new Answer(cmd, result == null, result); + final ExecutionResult result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "createipAlias.sh", args); + return new Answer(cmd, result.isSuccess(), result.getDetails()); } protected Answer execute(final DeleteIpAliasCommand cmd) { - final Script command = new Script(_deleteIpAliasPath, _timeout, s_logger); - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String args = ""; - command.add(routerIp); List revokedIpAliasTOs = cmd.getDeleteIpAliasTos(); for (IpAliasTO ipAliasTO : revokedIpAliasTOs) { args = args + ipAliasTO.getAlias_count() + ":" + ipAliasTO.getRouterip() + ":" + ipAliasTO.getNetmask() + "-"; } + //this is to ensure that thre is some argument passed to the deleteipAlias script when there are no revoked rules. args = args + "- "; List activeIpAliasTOs = cmd.getCreateIpAliasTos(); for (IpAliasTO ipAliasTO : activeIpAliasTOs) { args = args + ipAliasTO.getAlias_count() + ":" + ipAliasTO.getRouterip() + ":" + ipAliasTO.getNetmask() + "-"; } - command.add(args); - final String result = command.execute(); - return new Answer(cmd, result == null, result); + final ExecutionResult result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "deleteipAlias.sh", args); + return new Answer(cmd, result.isSuccess(), result.getDetails()); } protected Answer execute(final DnsMasqConfigCommand cmd) { - final Script command = new Script(_callDnsMasqPath, _timeout, s_logger); - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); List dhcpTos = cmd.getIps(); String args = ""; for (DhcpTO dhcpTo : dhcpTos) { args = args + dhcpTo.getRouterIp() + ":" + dhcpTo.getGateway() + ":" + dhcpTo.getNetmask() + ":" + dhcpTo.getStartIpOfSubnet() + "-"; } - command.add(routerIp); - command.add(args); - final String result = command.execute(); - return new Answer(cmd, result == null, result); - } - - public String getRouterStatus(String routerIP) { - return routerProxyWithParser("checkrouter.sh", routerIP, null); - } - - public String routerProxyWithParser(String script, String routerIP, String args) { - final Script command = new Script(_routerProxyPath, _timeout, s_logger); - final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser(); - command.add(script); - command.add(routerIP); - if (args != null) { - command.add(args); - } - String result = command.execute(parser); - if (result == null) { - return parser.getLine(); - } - return null; + final ExecutionResult result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "dnsmasq.sh", args); + return new Answer(cmd, result.isSuccess(), result.getDetails()); } private CheckS2SVpnConnectionsAnswer execute(CheckS2SVpnConnectionsCommand cmd) { @@ -659,78 +518,46 @@ public class VirtualRoutingResource implements Manager { String args = ""; for (String ip : cmd.getVpnIps()) { - args += " " + ip; + args += ip + " "; } - final String result = routerProxy("checkbatchs2svpn.sh", routerIP, args); - if (result != null) { - return new CheckS2SVpnConnectionsAnswer(cmd, false, "CheckS2SVpnConneciontsCommand failed"); - } - return new CheckS2SVpnConnectionsAnswer(cmd, true, result); - } - - public String routerProxy(String script, String routerIP, String args) { - final Script command = new Script(_routerProxyPath, _timeout, s_logger); - command.add(script); - command.add(routerIP); - if (args != null) { - command.add(args); - } - return command.execute(); + ExecutionResult result = _vrDeployer.executeInVR(routerIP, "checkbatchs2svpn.sh", args); + return new CheckS2SVpnConnectionsAnswer(cmd, result.isSuccess(), result.getDetails()); } protected Answer execute(CheckRouterCommand cmd) { final String routerPrivateIPAddress = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - final String result = getRouterStatus(routerPrivateIPAddress); - if (result == null || result.isEmpty()) { - return new CheckRouterAnswer(cmd, "CheckRouterCommand failed"); + final ExecutionResult result = _vrDeployer.executeInVR(routerPrivateIPAddress, "checkrouter.sh", null); + if (!result.isSuccess()) { + return new CheckRouterAnswer(cmd, result.getDetails()); } - return new CheckRouterAnswer(cmd, result, true); + return new CheckRouterAnswer(cmd, result.getDetails(), true); } protected Answer execute(BumpUpPriorityCommand cmd) { - final String routerPrivateIPAddress = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - final Script command = new Script(_bumpUpPriorityPath, _timeout, s_logger); - final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser(); - command.add(routerPrivateIPAddress); - String result = command.execute(parser); - if (result != null) { - return new Answer(cmd, false, "BumpUpPriorityCommand failed: " + result); - } - return new Answer(cmd, true, null); - } - - protected String getDomRVersion(String routerIP) { - return routerProxyWithParser("get_template_version.sh", routerIP, null); + ExecutionResult result = _vrDeployer.executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "bumpup_priority.sh", null); + return new Answer(cmd, result.isSuccess(), result.getDetails()); } protected Answer execute(GetDomRVersionCmd cmd) { final String routerPrivateIPAddress = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - final String result = getDomRVersion(routerPrivateIPAddress); - if (result == null || result.isEmpty()) { + final ExecutionResult result = _vrDeployer.executeInVR(routerPrivateIPAddress, "get_template_version.sh", null); + if (!result.isSuccess()) { return new GetDomRVersionAnswer(cmd, "GetDomRVersionCmd failed"); } - String[] lines = result.split("&"); + String[] lines = result.getDetails().split("&"); if (lines.length != 2) { - return new GetDomRVersionAnswer(cmd, result); + return new GetDomRVersionAnswer(cmd, result.getDetails()); } - return new GetDomRVersionAnswer(cmd, result, lines[0], lines[1]); - } - - protected Answer execute(final CheckConsoleProxyLoadCommand cmd) { - return executeProxyLoadScan(cmd, cmd.getProxyVmId(), cmd.getProxyVmName(), cmd.getProxyManagementIp(), cmd.getProxyCmdPort()); - } - - protected Answer execute(final WatchConsoleProxyLoadCommand cmd) { - return executeProxyLoadScan(cmd, cmd.getProxyVmId(), cmd.getProxyVmName(), cmd.getProxyManagementIp(), cmd.getProxyCmdPort()); + return new GetDomRVersionAnswer(cmd, result.getDetails(), lines[0], lines[1]); } protected Answer execute(Site2SiteVpnCfgCommand cmd) { - String args; + String args = ""; if (cmd.isCreate()) { - args = "-A"; + args += "-A"; args += " -l "; args += cmd.getLocalPublicIp(); args += " -n "; @@ -761,7 +588,7 @@ public class VirtualRoutingResource implements Manager { args += " -p "; } } else { - args = "-D"; + args += "-D"; args += " -r "; args += cmd.getPeerGatewayIp(); args += " -n "; @@ -769,59 +596,45 @@ public class VirtualRoutingResource implements Manager { args += " -N "; args += cmd.getPeerGuestCidrList(); } - String result = routerProxy("ipsectunnel.sh", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), args); - if (result != null) { - return new Answer(cmd, false, "Configure site to site VPN failed due to " + result); + ExecutionResult result = _vrDeployer.executeInVR(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), "ipsectunnel.sh", args); + if (!result.isSuccess()) { + return new Answer(cmd, false, "Configure site to site VPN failed due to " + result.getDetails()); } return new Answer(cmd); } - private Answer executeProxyLoadScan(final Command cmd, final long proxyVmId, final String proxyVmName, final String proxyManagementIp, final int cmdPort) { - String result = null; - - final StringBuffer sb = new StringBuffer(); - sb.append("http://").append(proxyManagementIp).append(":" + cmdPort).append("/cmd/getstatus"); - - boolean success = true; - try { - final URL url = new URL(sb.toString()); - final URLConnection conn = url.openConnection(); - - final InputStream is = conn.getInputStream(); - final BufferedReader reader = new BufferedReader(new InputStreamReader(is)); - final StringBuilder sb2 = new StringBuilder(); - String line = null; - try { - while ((line = reader.readLine()) != null) { - sb2.append(line + "\n"); - } - result = sb2.toString(); - } catch (final IOException e) { - success = false; - } finally { - try { - is.close(); - } catch (final IOException e) { - s_logger.warn("Exception when closing , console proxy address : " + proxyManagementIp); - success = false; - } - } - } catch (final IOException e) { - s_logger.warn("Unable to open console proxy command port url, console proxy address : " + proxyManagementIp); - success = false; - } - - return new ConsoleProxyLoadAnswer(cmd, proxyVmId, proxyVmName, success, result); - } - - public String configureMonitor(final String routerIP, final String config) { + protected Answer execute(SetMonitorServiceCommand cmd) { + String config = cmd.getConfiguration(); String args = " -c " + config; - return routerProxy("monitor_service.sh", routerIP, args); + ExecutionResult result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "monitor_service.sh", args); + + if (!result.isSuccess()) { + return new Answer(cmd, false, result.getDetails()); + } + return new Answer(cmd); } - public String assignGuestNetwork(final String dev, final String routerIP, final String routerGIP, final String gateway, final String cidr, final String netmask, - final String dns, final String domainName) { + protected SetupGuestNetworkAnswer execute(SetupGuestNetworkCommand cmd) { + NicTO nic = cmd.getNic(); + String routerIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); + String routerGIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP); + String gateway = cmd.getAccessDetail(NetworkElementCommand.GUEST_NETWORK_GATEWAY); + String cidr = Long.toString(NetUtils.getCidrSize(nic.getNetmask())); + String domainName = cmd.getNetworkDomain(); + String dns = cmd.getDefaultDns1(); + + if (dns == null || dns.isEmpty()) { + dns = cmd.getDefaultDns2(); + } else { + String dns2 = cmd.getDefaultDns2(); + if (dns2 != null && !dns2.isEmpty()) { + dns += "," + dns2; + } + } + + String dev = "eth" + nic.getDeviceId(); + String netmask = NetUtils.getSubNet(routerGIP, nic.getNetmask()); String args = " -C"; args += " -d " + dev; @@ -835,33 +648,74 @@ public class VirtualRoutingResource implements Manager { if (domainName != null && !domainName.isEmpty()) { args += " -e " + domainName; } - return routerProxy("vpc_guestnw.sh", routerIP, args); + ExecutionResult result = _vrDeployer.executeInVR(routerIP, "vpc_guestnw.sh", args); + + if (!result.isSuccess()) { + return new SetupGuestNetworkAnswer(cmd, false, "Creating guest network failed due to " + result.getDetails()); + } + return new SetupGuestNetworkAnswer(cmd, true, "success"); } - public String assignNetworkACL(final String routerIP, final String dev, final String routerGIP, final String netmask, final String rule, String privateGw) { - String args = " -d " + dev; - if (privateGw != null) { - args += " -a " + rule; - return routerProxy("vpc_privategw_acl.sh", routerIP, args); - } else { - args += " -i " + routerGIP; - args += " -m " + netmask; - args += " -a " + rule; - return routerProxy("vpc_acl.sh", routerIP, args); + private SetNetworkACLAnswer execute(SetNetworkACLCommand cmd) { + String[] results = new String[cmd.getRules().length]; + + String privateGw = cmd.getAccessDetail(NetworkElementCommand.VPC_PRIVATE_GATEWAY); + + try { + String[][] rules = cmd.generateFwRules(); + String[] aclRules = rules[0]; + NicTO nic = cmd.getNic(); + String dev = "eth" + nic.getDeviceId(); + String netmask = Long.toString(NetUtils.getCidrSize(nic.getNetmask())); + StringBuilder sb = new StringBuilder(); + + for (int i = 0; i < aclRules.length; i++) { + sb.append(aclRules[i]).append(','); + } + + String rule = sb.toString(); + ExecutionResult result; + + String args = " -d " + dev; + if (privateGw != null) { + args += " -a " + rule; + result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "vpc_privategw_acl.sh", args); + } else { + args += " -i " + nic.getIp(); + args += " -m " + netmask; + args += " -a " + rule; + result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "vpc_acl.sh", args); + } + + if (!result.isSuccess()) { + for (int i = 0; i < results.length; i++) { + results[i] = "Failed"; + } + return new SetNetworkACLAnswer(cmd, false, results); + } + + return new SetNetworkACLAnswer(cmd, true, results); + } catch (Exception e) { + String msg = "SetNetworkACL failed due to " + e.toString(); + s_logger.error(msg, e); + return new SetNetworkACLAnswer(cmd, false, results); } } - public String assignSourceNat(final String routerIP, final String pubIP, final String dev) { + protected SetSourceNatAnswer execute(SetSourceNatCommand cmd) { + String routerIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); + IpAddressTO pubIP = cmd.getIpAddress(); + String dev = "eth" + pubIP.getNicDevId(); String args = " -A "; args += " -l "; - args += pubIP; + args += pubIP.getPublicIp(); args += " -c "; args += dev; - return routerProxy("vpc_snat.sh", routerIP, args); + ExecutionResult result = _vrDeployer.executeInVR(routerIP, "vpc_snat.sh", args); + return new SetSourceNatAnswer(cmd, result.isSuccess(), result.getDetails()); } private SetPortForwardingRulesAnswer execute(SetPortForwardingRulesVpcCommand cmd) { - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String[] results = new String[cmd.getRules().length]; int i = 0; @@ -874,9 +728,9 @@ public class VirtualRoutingResource implements Manager { args += " -r " + rule.getDstIp(); args += " -d " + rule.getStringDstPortRange().replace(":", "-"); - String result = routerProxy("vpc_portforwarding.sh", routerIp, args); + ExecutionResult result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "vpc_portforwarding.sh", args); - if (result != null) { + if (!result.isSuccess()) { results[i++] = "Failed"; endResult = false; } else { @@ -886,44 +740,56 @@ public class VirtualRoutingResource implements Manager { return new SetPortForwardingRulesAnswer(cmd, results, endResult); } - public void assignVpcIpToRouter(final String routerIP, final boolean add, final String pubIP, final String nicname, final String gateway, final String netmask, - final String subnet, boolean sourceNat) throws InternalErrorException { + public IpAssocAnswer execute(IpAssocVpcCommand cmd) { + String routerIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); + String[] results = new String[cmd.getIpAddresses().length]; String args = ""; String snatArgs = ""; - - if (add) { - args += " -A "; - snatArgs += " -A "; - } else { - args += " -D "; - snatArgs += " -D "; + for (int i = 0; i < cmd.getIpAddresses().length; i ++) { + results[i] = "Failed"; } - args += " -l "; - args += pubIP; - args += " -c "; - args += nicname; - args += " -g "; - args += gateway; - args += " -m "; - args += netmask; - args += " -n "; - args += subnet; - - String result = routerProxy("vpc_ipassoc.sh", routerIP, args); - if (result != null) { - throw new InternalErrorException("KVM plugin \"vpc_ipassoc\" failed:" + result); - } - if (sourceNat) { - snatArgs += " -l " + pubIP; - snatArgs += " -c " + nicname; - - result = routerProxy("vpc_privateGateway.sh", routerIP, snatArgs); - if (result != null) { - throw new InternalErrorException("KVM plugin \"vpc_privateGateway\" failed:" + result); + int i = 0; + for (IpAddressTO ip : cmd.getIpAddresses()) { + if (ip.isAdd()) { + args += " -A "; + snatArgs += " -A "; + } else { + args += " -D "; + snatArgs += " -D "; } + args += " -l "; + args += ip.getPublicIp(); + String nicName = "eth" + ip.getNicDevId(); + args += " -c "; + args += nicName; + args += " -g "; + args += ip.getVlanGateway(); + args += " -m "; + args += Long.toString(NetUtils.getCidrSize(ip.getVlanNetmask())); + args += " -n "; + args += NetUtils.getSubNet(ip.getPublicIp(), ip.getVlanNetmask()); + + ExecutionResult result = _vrDeployer.executeInVR(routerIP, "vpc_ipassoc.sh", args); + if (!result.isSuccess()) { + results[i++] = ip.getPublicIp() + " - vpc_ipassoc failed:" + result.getDetails(); + break; + } + + if (ip.isSourceNat()) { + snatArgs += " -l " + ip.getPublicIp(); + snatArgs += " -c " + nicName; + + result = _vrDeployer.executeInVR(routerIP, "vpc_privateGateway.sh", snatArgs); + if (result != null) { + results[i++] = ip.getPublicIp() + " - vpc_privateGateway failed:" + result.getDetails(); + break; + } + } + results[i++] = ip.getPublicIp() + " - success "; } + return new IpAssocAnswer(cmd, results); } private SetStaticRouteAnswer execute(SetStaticRouteCommand cmd) { @@ -939,9 +805,9 @@ public class VirtualRoutingResource implements Manager { } String args = " -a " + sb.toString(); - String result = routerProxy("vpc_staticroute.sh", routerIP, args); + ExecutionResult result = _vrDeployer.executeInVR(routerIP, "vpc_staticroute.sh", args); - if (result != null) { + if (!result.isSuccess()) { for (int i = 0; i < results.length; i++) { results[i] = "Failed"; } @@ -956,147 +822,56 @@ public class VirtualRoutingResource implements Manager { } } - public String assignPublicIpAddress(final String vmName, final String privateIpAddress, final String publicIpAddress, final boolean add, final boolean firstIP, - final boolean sourceNat, final String broadcastUri, final String vlanGateway, final String vlanNetmask, final String vifMacAddress, int nicNum, boolean newNic) { - - String args = ""; - if (add) { - args += "-A"; - } else { - args += "-D"; - } - String cidrSize = Long.toString(NetUtils.getCidrSize(vlanNetmask)); - if (sourceNat) { - args += " -s"; - } - if (firstIP) { - args += " -f"; - } - args += " -l "; - args += publicIpAddress + "/" + cidrSize; - - String publicNic = "eth" + nicNum; - args += " -c "; - args += publicNic; - - args += " -g "; - args += vlanGateway; - - if (newNic) { - args += " -n"; + public Answer execute(IpAssocCommand cmd) { + String[] results = new String[cmd.getIpAddresses().length]; + for (int i = 0; i < results.length; i++) { + results[i] = IpAssocAnswer.errorResult; } - return routerProxy("ipassoc.sh", privateIpAddress, args); - } + int i = 0; + for (IpAddressTO ip: cmd.getIpAddresses()) { + String args = ""; + if (ip.isAdd()) { + args += "-A"; + } else { + args += "-D"; + } + String cidrSize = Long.toString(NetUtils.getCidrSize(ip.getVlanNetmask())); + if (ip.isSourceNat()) { + args += " -s"; + } + if (ip.isFirstIP()) { + args += " -f"; + } + args += " -l "; + args += ip.getPublicIp() + "/" + cidrSize; - private void deleteBridge(String brName) { - Script cmd = new Script("/bin/sh", _timeout); - cmd.add("-c"); - cmd.add("ifconfig " + brName + " down;brctl delbr " + brName); - cmd.execute(); - } + String publicNic = "eth" + ip.getNicDevId(); + args += " -c "; + args += publicNic; - private boolean isDNSmasqRunning(String dnsmasqName) { - Script cmd = new Script("/bin/sh", _timeout); - cmd.add("-c"); - cmd.add("ls -l /var/run/libvirt/network/" + dnsmasqName + ".pid"); - String result = cmd.execute(); - if (result != null) { - return false; - } else { - return true; + args += " -g "; + args += ip.getVlanGateway(); + + if (ip.isNewNic()) { + args += " -n"; + } + + ExecutionResult result = _vrDeployer.executeInVR(cmd.getRouterAccessIp(), "ipassoc.sh", args); + if (result.isSuccess()) { + results[i++] = ip.getPublicIp() + " - success"; + } else { + results[i++] = ip.getPublicIp() + " - failed:" + result.getDetails(); + break; + } } + return new IpAssocAnswer(cmd, results); } - private void stopDnsmasq(String dnsmasqName) { - Script cmd = new Script("/bin/sh", _timeout); - cmd.add("-c"); - cmd.add("kill -9 `cat /var/run/libvirt/network/" + dnsmasqName + ".pid`"); - cmd.execute(); - } - - // protected Answer execute(final SetFirewallRuleCommand cmd) { - // String args; - // if(cmd.getProtocol().toLowerCase().equals(NetUtils.NAT_PROTO)){ - // //1:1 NAT needs instanceip;publicip;domrip;op - // if(cmd.isCreate()) { - // args = "-A"; - // } else { - // args = "-D"; - // } - // - // args += " -l " + cmd.getPublicIpAddress(); - // args += " -i " + cmd.getRouterIpAddress(); - // args += " -r " + cmd.getPrivateIpAddress(); - // args += " -G " + cmd.getProtocol(); - // }else{ - // if (cmd.isEnable()) { - // args = "-A"; - // } else { - // args = "-D"; - // } - // - // args += " -P " + cmd.getProtocol().toLowerCase(); - // args += " -l " + cmd.getPublicIpAddress(); - // args += " -p " + cmd.getPublicPort(); - // args += " -n " + cmd.getRouterName(); - // args += " -i " + cmd.getRouterIpAddress(); - // args += " -r " + cmd.getPrivateIpAddress(); - // args += " -d " + cmd.getPrivatePort(); - // args += " -N " + cmd.getVlanNetmask(); - // - // String oldPrivateIP = cmd.getOldPrivateIP(); - // String oldPrivatePort = cmd.getOldPrivatePort(); - // - // if (oldPrivateIP != null) { - // args += " -w " + oldPrivateIP; - // } - // - // if (oldPrivatePort != null) { - // args += " -x " + oldPrivatePort; - // } - // } - // - // final Script command = new Script(_firewallPath, _timeout, s_logger); - // String [] argsArray = args.split(" "); - // for (String param : argsArray) { - // command.add(param); - // } - // String result = command.execute(); - // return new Answer(cmd, result == null, result); - // } - - protected String getDefaultScriptsDir() { - return "scripts/network/domr/dom0"; - } - - protected String findScript(final String script) { - return Script.findScript(_scriptsDir, script); - } - - @Override public boolean configure(final String name, final Map params) throws ConfigurationException { _name = name; - _scriptsDir = (String)params.get("domr.scripts.dir"); - if (_scriptsDir == null) { - if (s_logger.isInfoEnabled()) { - s_logger.info("VirtualRoutingResource _scriptDir can't be initialized from domr.scripts.dir param, use default"); - } - _scriptsDir = getDefaultScriptsDir(); - } - - if (s_logger.isInfoEnabled()) { - s_logger.info("VirtualRoutingResource _scriptDir to use: " + _scriptsDir); - } - - String value = (String)params.get("scripts.timeout"); - _timeout = NumbersUtil.parseInt(value, 120) * 1000; - - value = (String)params.get("start.script.timeout"); - _startTimeout = NumbersUtil.parseInt(value, 360) * 1000; - - value = (String)params.get("ssh.sleep"); + String value = (String)params.get("ssh.sleep"); _sleep = NumbersUtil.parseInt(value, 10) * 1000; value = (String)params.get("ssh.retry"); @@ -1105,60 +880,9 @@ public class VirtualRoutingResource implements Manager { value = (String)params.get("ssh.port"); _port = NumbersUtil.parseInt(value, 3922); - _publicIpAddress = (String)params.get("public.ip.address"); - if (_publicIpAddress != null) { - s_logger.warn("Incoming public ip address is overriden. Will always be using the same ip address: " + _publicIpAddress); + if (_vrDeployer == null) { + throw new ConfigurationException("Unable to find the resource for VirtualRouterDeployer!"); } - - _firewallPath = findScript("call_firewall.sh"); - if (_firewallPath == null) { - throw new ConfigurationException("Unable to find the call_firewall.sh"); - } - - _loadbPath = findScript("call_loadbalancer.sh"); - if (_loadbPath == null) { - throw new ConfigurationException("Unable to find the call_loadbalancer.sh"); - } - - _dhcpEntryPath = findScript("dhcp_entry.sh"); - if (_dhcpEntryPath == null) { - throw new ConfigurationException("Unable to find dhcp_entry.sh"); - } - - _publicEthIf = (String)params.get("public.network.device"); - if (_publicEthIf == null) { - _publicEthIf = "xenbr1"; - } - _publicEthIf = _publicEthIf.toLowerCase(); - - _privateEthIf = (String)params.get("private.network.device"); - if (_privateEthIf == null) { - _privateEthIf = "xenbr0"; - } - _privateEthIf = _privateEthIf.toLowerCase(); - - _bumpUpPriorityPath = findScript("bumpUpPriority.sh"); - if (_bumpUpPriorityPath == null) { - throw new ConfigurationException("Unable to find bumpUpPriority.sh"); - } - - _routerProxyPath = findScript("router_proxy.sh"); - if (_routerProxyPath == null) { - throw new ConfigurationException("Unable to find router_proxy.sh"); - } - _createIpAliasPath = findScript("createipAlias.sh"); - if (_createIpAliasPath == null) { - throw new ConfigurationException("unable to find createipAlias.sh"); - } - _deleteIpAliasPath = findScript("deleteipAlias.sh"); - if (_deleteIpAliasPath == null) { - throw new ConfigurationException("unable to find deleteipAlias.sh"); - } - _callDnsMasqPath = findScript("call_dnsmasq.sh"); - if (_callDnsMasqPath == null) { - throw new ConfigurationException("unable to find call_dnsmasq.sh"); - } - return true; } @@ -1237,50 +961,4 @@ public class VirtualRoutingResource implements Manager { return false; } - - @Override - public String getName() { - return _name; - } - - @Override - public void setName(String name) { - _name = name; - } - - @Override - public boolean start() { - return true; - } - - @Override - public boolean stop() { - return true; - } - - @Override - public int getRunLevel() { - return ComponentLifecycle.RUN_LEVEL_COMPONENT; - } - - public void setRunLevel() { - } - - @Override - public void setConfigParams(Map params) { - // TODO Auto-generated method stub - - } - - @Override - public Map getConfigParams() { - // TODO Auto-generated method stub - return null; - } - - @Override - public void setRunLevel(int level) { - // TODO Auto-generated method stub - - } } diff --git a/core/src/com/cloud/agent/transport/Request.java b/core/src/com/cloud/agent/transport/Request.java index f4ed5c4b6e6..b5890d90451 100755 --- a/core/src/com/cloud/agent/transport/Request.java +++ b/core/src/com/cloud/agent/transport/Request.java @@ -23,6 +23,7 @@ import java.io.StringReader; import java.lang.reflect.Type; import java.nio.ByteBuffer; import java.util.ArrayList; +import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.zip.GZIPInputStream; @@ -49,6 +50,7 @@ import com.cloud.exception.UnsupportedVersionException; import com.cloud.serializer.GsonHelper; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; +import com.cloud.utils.StringUtils; import com.cloud.utils.exception.CloudRuntimeException; /** @@ -436,11 +438,35 @@ public class Request { } buf.append(", Ver: ").append(_ver.toString()); buf.append(", Flags: ").append(Integer.toBinaryString(getFlags())).append(", "); - buf.append(content); + String cleanContent = content.toString(); + if(cleanContent.contains("password")) { + buf.append(cleanPassword(cleanContent)); + } else { + buf.append(content); + } buf.append(" }"); return buf.toString(); } + public static String cleanPassword(String logString) { + String cleanLogString = null; + if (logString != null) { + cleanLogString = logString; + String[] temp = logString.split(","); + int i = 0; + if (temp != null) { + while (i < temp.length) { + temp[i] = StringUtils.cleanString(temp[i]); + i++; + } + List stringList = new ArrayList(); + Collections.addAll(stringList, temp); + cleanLogString = StringUtils.join(stringList, ","); + } + } + return cleanLogString; + } + /** * Factory method for Request and Response. It expects the bytes to be * correctly formed so it's possible that it throws underflow exceptions diff --git a/core/src/com/cloud/host/HostInfo.java b/core/src/com/cloud/host/HostInfo.java index 89fb8061aa0..4a95aa8d862 100644 --- a/core/src/com/cloud/host/HostInfo.java +++ b/core/src/com/cloud/host/HostInfo.java @@ -21,5 +21,6 @@ public final class HostInfo { public static final String HOST_OS = "Host.OS"; //Fedora, XenServer, Ubuntu, etc public static final String HOST_OS_VERSION = "Host.OS.Version"; //12, 5.5, 9.10, etc public static final String HOST_OS_KERNEL_VERSION = "Host.OS.Kernel.Version"; //linux-2.6.31 etc - + public static final String XS620_SNAPSHOT_HOTFIX = "xs620_snapshot_hotfix"; } + diff --git a/core/src/com/cloud/info/RunningHostInfoAgregator.java b/core/src/com/cloud/info/RunningHostInfoAgregator.java index 689cdeb66e9..cec8037ccc9 100644 --- a/core/src/com/cloud/info/RunningHostInfoAgregator.java +++ b/core/src/com/cloud/info/RunningHostInfoAgregator.java @@ -24,9 +24,9 @@ import com.cloud.host.Host; public class RunningHostInfoAgregator { public static class ZoneHostInfo { - public static int ROUTING_HOST_MASK = 2; - public static int STORAGE_HOST_MASK = 4; - public static int ALL_HOST_MASK = ROUTING_HOST_MASK | STORAGE_HOST_MASK; + public static final int ROUTING_HOST_MASK = 2; + public static final int STORAGE_HOST_MASK = 4; + public static final int ALL_HOST_MASK = ROUTING_HOST_MASK | STORAGE_HOST_MASK; private long dcId; @@ -51,7 +51,7 @@ public class RunningHostInfoAgregator { } } - private Map zoneHostInfoMap = new HashMap(); + private final Map zoneHostInfoMap = new HashMap(); public RunningHostInfoAgregator() { } diff --git a/core/src/com/cloud/network/LoadBalancerValidator.java b/core/src/com/cloud/network/LoadBalancerValidator.java index 3fb8a2f89ab..f3188999f4e 100644 --- a/core/src/com/cloud/network/LoadBalancerValidator.java +++ b/core/src/com/cloud/network/LoadBalancerValidator.java @@ -16,7 +16,6 @@ // under the License. package com.cloud.network; -import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.lb.LoadBalancingRule; public interface LoadBalancerValidator { @@ -24,7 +23,6 @@ public interface LoadBalancerValidator { * Validate rules * @param rule * @return true/false. If there are no validation then true should be return. - * @throws ResourceUnavailableException */ public boolean validateLBRule(LoadBalancingRule rule); } diff --git a/core/src/com/cloud/network/resource/TrafficSentinelResource.java b/core/src/com/cloud/network/resource/TrafficSentinelResource.java index ada5f5e1d6d..67c0dd42f86 100644 --- a/core/src/com/cloud/network/resource/TrafficSentinelResource.java +++ b/core/src/com/cloud/network/resource/TrafficSentinelResource.java @@ -243,11 +243,11 @@ public class TrafficSentinelResource implements ServerResource { return answer; } - private String getScript(List Ips, Date start, Date end) { + private String getScript(List ips, Date start, Date end) { String IpAddresses = ""; - for (int i = 0; i < Ips.size(); i++) { - IpAddresses += Ips.get(i); - if (i != (Ips.size() - 1)) { + for (int i = 0; i < ips.size(); i++) { + IpAddresses += ips.get(i); + if (i != (ips.size() - 1)) { // Append comma for all Ips except the last Ip IpAddresses += ","; } diff --git a/core/src/com/cloud/storage/template/HttpTemplateDownloader.java b/core/src/com/cloud/storage/template/HttpTemplateDownloader.java index f3d34b06c96..b57f6d40c67 100644 --- a/core/src/com/cloud/storage/template/HttpTemplateDownloader.java +++ b/core/src/com/cloud/storage/template/HttpTemplateDownloader.java @@ -72,7 +72,7 @@ public class HttpTemplateDownloader extends ManagedContextRunnable implements Te boolean inited = true; private String toDir; - private long MAX_TEMPLATE_SIZE_IN_BYTES; + private long maxTemplateSizeInBytes; private ResourceType resourceType = ResourceType.TEMPLATE; private final HttpMethodRetryHandler myretryhandler; @@ -83,7 +83,7 @@ public class HttpTemplateDownloader extends ManagedContextRunnable implements Te setToDir(toDir); status = TemplateDownloader.Status.NOT_STARTED; this.resourceType = resourceType; - MAX_TEMPLATE_SIZE_IN_BYTES = maxTemplateSizeInBytes; + this.maxTemplateSizeInBytes = maxTemplateSizeInBytes; totalBytes = 0; client = new HttpClient(s_httpClientManager); @@ -217,15 +217,15 @@ public class HttpTemplateDownloader extends ManagedContextRunnable implements Te remoteSize = remoteSize2; } - if (remoteSize > MAX_TEMPLATE_SIZE_IN_BYTES) { - s_logger.info("Remote size is too large: " + remoteSize + " , max=" + MAX_TEMPLATE_SIZE_IN_BYTES); + if (remoteSize > maxTemplateSizeInBytes) { + s_logger.info("Remote size is too large: " + remoteSize + " , max=" + maxTemplateSizeInBytes); status = Status.UNRECOVERABLE_ERROR; errorString = "Download file size is too large"; return 0; } if (remoteSize == 0) { - remoteSize = MAX_TEMPLATE_SIZE_IN_BYTES; + remoteSize = maxTemplateSizeInBytes; } InputStream in = !chunked ? new BufferedInputStream(request.getResponseBodyAsStream()) : new ChunkedInputStream(request.getResponseBodyAsStream()); @@ -233,7 +233,7 @@ public class HttpTemplateDownloader extends ManagedContextRunnable implements Te RandomAccessFile out = new RandomAccessFile(file, "rwd"); out.seek(localFileSize); - s_logger.info("Starting download from " + getDownloadUrl() + " to " + toFile + " remoteSize=" + remoteSize + " , max size=" + MAX_TEMPLATE_SIZE_IN_BYTES); + s_logger.info("Starting download from " + getDownloadUrl() + " to " + toFile + " remoteSize=" + remoteSize + " , max size=" + maxTemplateSizeInBytes); byte[] block = new byte[CHUNK_SIZE]; long offset = 0; @@ -387,7 +387,7 @@ public class HttpTemplateDownloader extends ManagedContextRunnable implements Te @Override public long getMaxTemplateSizeInBytes() { - return MAX_TEMPLATE_SIZE_IN_BYTES; + return maxTemplateSizeInBytes; } public static void main(String[] args) { diff --git a/core/src/com/cloud/storage/template/OVAProcessor.java b/core/src/com/cloud/storage/template/OVAProcessor.java new file mode 100644 index 00000000000..0db3bb00e0a --- /dev/null +++ b/core/src/com/cloud/storage/template/OVAProcessor.java @@ -0,0 +1,158 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.storage.template; + +import java.io.File; +import java.util.Map; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.apache.log4j.Logger; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import com.cloud.exception.InternalErrorException; +import com.cloud.storage.Storage.ImageFormat; +import com.cloud.storage.StorageLayer; +import com.cloud.utils.component.AdapterBase; +import com.cloud.utils.script.Script; + +@Local(value = Processor.class) +public class OVAProcessor extends AdapterBase implements Processor { + private static final Logger s_logger = Logger.getLogger(OVAProcessor.class); + + StorageLayer _storage; + + @Override + public FormatInfo process(String templatePath, ImageFormat format, String templateName) throws InternalErrorException { + if (format != null) { + if (s_logger.isInfoEnabled()) { + s_logger.info("We currently don't handle conversion from " + format + " to OVA."); + } + return null; + } + + s_logger.info("Template processing. templatePath: " + templatePath + ", templateName: " + templateName); + String templateFilePath = templatePath + File.separator + templateName + "." + ImageFormat.OVA.getFileExtension(); + if (!_storage.exists(templateFilePath)) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Unable to find the vmware template file: " + templateFilePath); + } + return null; + } + + s_logger.info("Template processing - untar OVA package. templatePath: " + templatePath + ", templateName: " + templateName); + String templateFileFullPath = templatePath + File.separator + templateName + "." + ImageFormat.OVA.getFileExtension(); + File templateFile = new File(templateFileFullPath); + + Script command = new Script("tar", 0, s_logger); + command.add("--no-same-owner"); + command.add("-xf", templateFileFullPath); + command.setWorkDir(templateFile.getParent()); + String result = command.execute(); + if (result != null) { + s_logger.info("failed to untar OVA package due to " + result + ". templatePath: " + templatePath + ", templateName: " + templateName); + return null; + } + + FormatInfo info = new FormatInfo(); + info.format = ImageFormat.OVA; + info.filename = templateName + "." + ImageFormat.OVA.getFileExtension(); + info.size = _storage.getSize(templateFilePath); + info.virtualSize = getTemplateVirtualSize(templatePath, info.filename); + + // delete original OVA file + // templateFile.delete(); + return info; + } + + @Override + public Long getVirtualSize(File file) { + try { + long size = getTemplateVirtualSize(file.getParent(), file.getName()); + return size; + } catch (Exception e) { + + } + return file.length(); + } + + public long getTemplateVirtualSize(String templatePath, String templateName) throws InternalErrorException { + // get the virtual size from the OVF file meta data + long virtualSize = 0; + String templateFileFullPath = templatePath.endsWith(File.separator) ? templatePath : templatePath + File.separator; + templateFileFullPath += templateName.endsWith(ImageFormat.OVA.getFileExtension()) ? templateName : templateName + "." + ImageFormat.OVA.getFileExtension(); + String ovfFileName = getOVFFilePath(templateFileFullPath); + if (ovfFileName == null) { + String msg = "Unable to locate OVF file in template package directory: " + templatePath; + s_logger.error(msg); + throw new InternalErrorException(msg); + } + try { + Document ovfDoc = null; + ovfDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(ovfFileName)); + Element disk = (Element)ovfDoc.getElementsByTagName("Disk").item(0); + virtualSize = Long.parseLong(disk.getAttribute("ovf:capacity")); + String allocationUnits = disk.getAttribute("ovf:capacityAllocationUnits"); + if ((virtualSize != 0) && (allocationUnits != null)) { + long units = 1; + if (allocationUnits.equalsIgnoreCase("KB") || allocationUnits.equalsIgnoreCase("KiloBytes") || allocationUnits.equalsIgnoreCase("byte * 2^10")) { + units = 1024; + } else if (allocationUnits.equalsIgnoreCase("MB") || allocationUnits.equalsIgnoreCase("MegaBytes") || allocationUnits.equalsIgnoreCase("byte * 2^20")) { + units = 1024 * 1024; + } else if (allocationUnits.equalsIgnoreCase("GB") || allocationUnits.equalsIgnoreCase("GigaBytes") || allocationUnits.equalsIgnoreCase("byte * 2^30")) { + units = 1024 * 1024 * 1024; + } + virtualSize = virtualSize * units; + } else { + throw new InternalErrorException("Failed to read capacity and capacityAllocationUnits from the OVF file: " + ovfFileName); + } + return virtualSize; + } catch (Exception e) { + String msg = "Unable to parse OVF XML document to get the virtual disk size due to" + e; + s_logger.error(msg); + throw new InternalErrorException(msg); + } + } + + private String getOVFFilePath(String srcOVAFileName) { + File file = new File(srcOVAFileName); + assert (_storage != null); + String[] files = _storage.listFiles(file.getParent()); + if (files != null) { + for (String fileName : files) { + if (fileName.toLowerCase().endsWith(".ovf")) { + File ovfFile = new File(fileName); + return file.getParent() + File.separator + ovfFile.getName(); + } + } + } + return null; + } + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + _storage = (StorageLayer)params.get(StorageLayer.InstanceConfigKey); + if (_storage == null) { + throw new ConfigurationException("Unable to get storage implementation"); + } + + return true; + } +} diff --git a/core/src/com/cloud/storage/template/TemplateDownloaderBase.java b/core/src/com/cloud/storage/template/TemplateDownloaderBase.java index 7eb0b5fa669..e3fec8ee5a4 100644 --- a/core/src/com/cloud/storage/template/TemplateDownloaderBase.java +++ b/core/src/com/cloud/storage/template/TemplateDownloaderBase.java @@ -40,7 +40,7 @@ public abstract class TemplateDownloaderBase extends ManagedContextRunnable impl protected long _start; protected StorageLayer _storage; protected boolean _inited = false; - private long MAX_TEMPLATE_SIZE_IN_BYTES; + private long maxTemplateSizeInBytes; public TemplateDownloaderBase(StorageLayer storage, String downloadUrl, String toDir, long maxTemplateSizeInBytes, DownloadCompleteCallback callback) { _storage = storage; @@ -49,7 +49,7 @@ public abstract class TemplateDownloaderBase extends ManagedContextRunnable impl _callback = callback; _inited = true; - this.MAX_TEMPLATE_SIZE_IN_BYTES = maxTemplateSizeInBytes; + this.maxTemplateSizeInBytes = maxTemplateSizeInBytes; } @Override @@ -122,7 +122,7 @@ public abstract class TemplateDownloaderBase extends ManagedContextRunnable impl @Override public long getMaxTemplateSizeInBytes() { - return this.MAX_TEMPLATE_SIZE_IN_BYTES; + return this.maxTemplateSizeInBytes; } @Override diff --git a/core/src/com/cloud/storage/template/VhdProcessor.java b/core/src/com/cloud/storage/template/VhdProcessor.java index 308ea6472ef..2e4ac44dcd4 100644 --- a/core/src/com/cloud/storage/template/VhdProcessor.java +++ b/core/src/com/cloud/storage/template/VhdProcessor.java @@ -45,11 +45,11 @@ public class VhdProcessor extends AdapterBase implements Processor { private static final Logger s_logger = Logger.getLogger(VhdProcessor.class); StorageLayer _storage; - private int vhd_footer_size = 512; - private int vhd_footer_creator_app_offset = 28; - private int vhd_footer_creator_ver_offset = 32; - private int vhd_footer_current_size_offset = 48; - private byte[][] citrix_creator_app = { {0x74, 0x61, 0x70, 0x00}, {0x43, 0x54, 0x58, 0x53}}; /*"tap ", and "CTXS"*/ + private int vhdFooterSize = 512; + private int vhdFooterCreatorAppOffset = 28; + private int vhdFooterCreatorVerOffset = 32; + private int vhdFooterCurrentSizeOffset = 48; + private byte[][] citrixCreatorApp = { {0x74, 0x61, 0x70, 0x00}, {0x43, 0x54, 0x58, 0x53}}; /*"tap ", and "CTXS"*/ @Override public FormatInfo process(String templatePath, ImageFormat format, String templateName) throws InternalErrorException { @@ -77,9 +77,9 @@ public class VhdProcessor extends AdapterBase implements Processor { byte[] creatorApp = new byte[4]; try { strm = new FileInputStream(vhdFile); - strm.skip(info.size - vhd_footer_size + vhd_footer_creator_app_offset); + strm.skip(info.size - vhdFooterSize + vhdFooterCreatorAppOffset); strm.read(creatorApp); - strm.skip(vhd_footer_current_size_offset - vhd_footer_creator_ver_offset); + strm.skip(vhdFooterCurrentSizeOffset - vhdFooterCreatorVerOffset); strm.read(currentSize); } catch (Exception e) { s_logger.warn("Unable to read vhd file " + vhdPath, e); @@ -108,9 +108,9 @@ public class VhdProcessor extends AdapterBase implements Processor { byte[] creatorApp = new byte[4]; try { strm = new FileInputStream(file); - strm.skip(file.length() - vhd_footer_size + vhd_footer_creator_app_offset); + strm.skip(file.length() - vhdFooterSize + vhdFooterCreatorAppOffset); strm.read(creatorApp); - strm.skip(vhd_footer_current_size_offset - vhd_footer_creator_ver_offset); + strm.skip(vhdFooterCurrentSizeOffset - vhdFooterCreatorVerOffset); strm.read(currentSize); } catch (Exception e) { s_logger.warn("Unable to read vhd file " + file.getAbsolutePath(), e); @@ -141,8 +141,8 @@ public class VhdProcessor extends AdapterBase implements Processor { private void imageSignatureCheck(byte[] creatorApp) throws InternalErrorException { boolean findKnownCreator = false; - for (int i = 0; i < citrix_creator_app.length; i++) { - if (Arrays.equals(creatorApp, citrix_creator_app[i])) { + for (int i = 0; i < citrixCreatorApp.length; i++) { + if (Arrays.equals(creatorApp, citrixCreatorApp[i])) { findKnownCreator = true; break; } diff --git a/core/src/com/cloud/storage/template/VmdkProcessor.java b/core/src/com/cloud/storage/template/VmdkProcessor.java index be201438a1c..2c08447e9f9 100644 --- a/core/src/com/cloud/storage/template/VmdkProcessor.java +++ b/core/src/com/cloud/storage/template/VmdkProcessor.java @@ -16,22 +16,24 @@ // under the License. package com.cloud.storage.template; +import java.io.BufferedReader; import java.io.File; +import java.io.FileReader; +import java.io.FileNotFoundException; +import java.io.IOException; import java.util.Map; +import java.util.regex.Pattern; +import java.util.regex.Matcher; import javax.ejb.Local; import javax.naming.ConfigurationException; -import javax.xml.parsers.DocumentBuilderFactory; import org.apache.log4j.Logger; -import org.w3c.dom.Document; -import org.w3c.dom.Element; import com.cloud.exception.InternalErrorException; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.StorageLayer; import com.cloud.utils.component.AdapterBase; -import com.cloud.utils.script.Script; @Local(value = Processor.class) public class VmdkProcessor extends AdapterBase implements Processor { @@ -49,7 +51,7 @@ public class VmdkProcessor extends AdapterBase implements Processor { } s_logger.info("Template processing. templatePath: " + templatePath + ", templateName: " + templateName); - String templateFilePath = templatePath + File.separator + templateName + "." + ImageFormat.OVA.getFileExtension(); + String templateFilePath = templatePath + File.separator + templateName + "." + ImageFormat.VMDK.getFileExtension(); if (!_storage.exists(templateFilePath)) { if (s_logger.isInfoEnabled()) { s_logger.info("Unable to find the vmware template file: " + templateFilePath); @@ -57,28 +59,12 @@ public class VmdkProcessor extends AdapterBase implements Processor { return null; } - s_logger.info("Template processing - untar OVA package. templatePath: " + templatePath + ", templateName: " + templateName); - String templateFileFullPath = templatePath + File.separator + templateName + "." + ImageFormat.OVA.getFileExtension(); - File templateFile = new File(templateFileFullPath); - - Script command = new Script("tar", 0, s_logger); - command.add("--no-same-owner"); - command.add("-xf", templateFileFullPath); - command.setWorkDir(templateFile.getParent()); - String result = command.execute(); - if (result != null) { - s_logger.info("failed to untar OVA package due to " + result + ". templatePath: " + templatePath + ", templateName: " + templateName); - return null; - } - FormatInfo info = new FormatInfo(); - info.format = ImageFormat.OVA; - info.filename = templateName + "." + ImageFormat.OVA.getFileExtension(); + info.format = ImageFormat.VMDK; + info.filename = templateName + "." + ImageFormat.VMDK.getFileExtension(); info.size = _storage.getSize(templateFilePath); info.virtualSize = getTemplateVirtualSize(templatePath, info.filename); - // delete original OVA file - // templateFile.delete(); return info; } @@ -94,56 +80,37 @@ public class VmdkProcessor extends AdapterBase implements Processor { } public long getTemplateVirtualSize(String templatePath, String templateName) throws InternalErrorException { - // get the virtual size from the OVF file meta data long virtualSize = 0; String templateFileFullPath = templatePath.endsWith(File.separator) ? templatePath : templatePath + File.separator; - templateFileFullPath += templateName.endsWith(ImageFormat.OVA.getFileExtension()) ? templateName : templateName + "." + ImageFormat.OVA.getFileExtension(); - String ovfFileName = getOVFFilePath(templateFileFullPath); - if (ovfFileName == null) { - String msg = "Unable to locate OVF file in template package directory: " + templatePath; - s_logger.error(msg); - throw new InternalErrorException(msg); - } - try { - Document ovfDoc = null; - ovfDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(ovfFileName)); - Element disk = (Element)ovfDoc.getElementsByTagName("Disk").item(0); - virtualSize = Long.parseLong(disk.getAttribute("ovf:capacity")); - String allocationUnits = disk.getAttribute("ovf:capacityAllocationUnits"); - if ((virtualSize != 0) && (allocationUnits != null)) { - long units = 1; - if (allocationUnits.equalsIgnoreCase("KB") || allocationUnits.equalsIgnoreCase("KiloBytes") || allocationUnits.equalsIgnoreCase("byte * 2^10")) { - units = 1024; - } else if (allocationUnits.equalsIgnoreCase("MB") || allocationUnits.equalsIgnoreCase("MegaBytes") || allocationUnits.equalsIgnoreCase("byte * 2^20")) { - units = 1024 * 1024; - } else if (allocationUnits.equalsIgnoreCase("GB") || allocationUnits.equalsIgnoreCase("GigaBytes") || allocationUnits.equalsIgnoreCase("byte * 2^30")) { - units = 1024 * 1024 * 1024; - } - virtualSize = virtualSize * units; - } else { - throw new InternalErrorException("Failed to read capacity and capacityAllocationUnits from the OVF file: " + ovfFileName); - } - return virtualSize; - } catch (Exception e) { - String msg = "Unable to parse OVF XML document to get the virtual disk size due to" + e; - s_logger.error(msg); - throw new InternalErrorException(msg); - } - } + templateFileFullPath += templateName.endsWith(ImageFormat.VMDK.getFileExtension()) ? templateName : templateName + "." + ImageFormat.VMDK.getFileExtension(); + String vmdkHeader = ""; - private String getOVFFilePath(String srcOVAFileName) { - File file = new File(srcOVAFileName); - assert (_storage != null); - String[] files = _storage.listFiles(file.getParent()); - if (files != null) { - for (String fileName : files) { - if (fileName.toLowerCase().endsWith(".ovf")) { - File ovfFile = new File(fileName); - return file.getParent() + File.separator + ovfFile.getName(); + try { + FileReader fileReader = new FileReader(templateFileFullPath); + BufferedReader bufferedReader = new BufferedReader(fileReader); + Pattern regex = Pattern.compile("(RW|RDONLY|NOACCESS) (\\d+) (FLAT|SPARSE|ZERO|VMFS|VMFSSPARSE|VMFSDRM|VMFSRAW)"); + String line = null; + while((line = bufferedReader.readLine()) != null) { + Matcher m = regex.matcher(line); + if (m.find( )) { + long sectors = Long.parseLong(m.group(2)); + virtualSize = sectors * 512; + break; } } + bufferedReader.close(); + } catch(FileNotFoundException ex) { + String msg = "Unable to open file '" + templateFileFullPath + "' " + ex.toString(); + s_logger.error(msg); + throw new InternalErrorException(msg); + } catch(IOException ex) { + String msg = "Unable read open file '" + templateFileFullPath + "' " + ex.toString(); + s_logger.error(msg); + throw new InternalErrorException(msg); } - return null; + + s_logger.debug("vmdk file had size="+virtualSize); + return virtualSize; } @Override diff --git a/core/src/org/apache/cloudstack/storage/command/CopyCommand.java b/core/src/org/apache/cloudstack/storage/command/CopyCommand.java index 7fcde1e8d4f..446c61f9a7b 100644 --- a/core/src/org/apache/cloudstack/storage/command/CopyCommand.java +++ b/core/src/org/apache/cloudstack/storage/command/CopyCommand.java @@ -16,6 +16,9 @@ // under the License. package org.apache.cloudstack.storage.command; +import java.util.HashMap; +import java.util.Map; + import com.cloud.agent.api.Command; import com.cloud.agent.api.to.DataTO; @@ -24,6 +27,7 @@ public final class CopyCommand extends Command implements StorageSubSystemComman private DataTO destTO; private DataTO cacheTO; boolean executeInSequence = false; + Map options = new HashMap(); public CopyCommand(DataTO srcData, DataTO destData, int timeout, boolean executeInSequence) { super(); @@ -66,4 +70,12 @@ public final class CopyCommand extends Command implements StorageSubSystemComman return this.getWait() * 1000; } + public void setOptions(Map options) { + this.options = options; + } + + public Map getOptions() { + return options; + } + } diff --git a/core/src/org/apache/cloudstack/storage/command/DownloadCommand.java b/core/src/org/apache/cloudstack/storage/command/DownloadCommand.java index 60377fa569d..c12d4d02bff 100644 --- a/core/src/org/apache/cloudstack/storage/command/DownloadCommand.java +++ b/core/src/org/apache/cloudstack/storage/command/DownloadCommand.java @@ -158,8 +158,8 @@ public class DownloadCommand extends AbstractDownloadCommand implements Internal return _store; } - public void setDataStore(DataStoreTO _store) { - this._store = _store; + public void setDataStore(DataStoreTO store) { + this._store = store; } public String getInstallPath() { diff --git a/core/src/org/apache/cloudstack/storage/to/SnapshotObjectTO.java b/core/src/org/apache/cloudstack/storage/to/SnapshotObjectTO.java index 03b460902bf..7d1ac2d7e5e 100644 --- a/core/src/org/apache/cloudstack/storage/to/SnapshotObjectTO.java +++ b/core/src/org/apache/cloudstack/storage/to/SnapshotObjectTO.java @@ -16,8 +16,11 @@ // under the License. package org.apache.cloudstack.storage.to; +import java.util.ArrayList; + import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; +import org.apache.commons.lang.ArrayUtils; import com.cloud.agent.api.to.DataObjectType; import com.cloud.agent.api.to.DataStoreTO; @@ -34,6 +37,9 @@ public class SnapshotObjectTO implements DataTO { private HypervisorType hypervisorType; private long id; private boolean quiescevm; + private String[] parents; + private Long physicalSize = (long) 0; + public SnapshotObjectTO() { @@ -49,9 +55,17 @@ public class SnapshotObjectTO implements DataTO { } SnapshotInfo parentSnapshot = snapshot.getParent(); + ArrayList parentsArry = new ArrayList(); if (parentSnapshot != null) { this.parentSnapshotPath = parentSnapshot.getPath(); + while(parentSnapshot != null) { + parentsArry.add(parentSnapshot.getPath()); + parentSnapshot = parentSnapshot.getParent(); + } + parents = parentsArry.toArray(new String[parentsArry.size()]); + ArrayUtils.reverse(parents); } + this.dataStore = snapshot.getDataStore().getTO(); this.setName(snapshot.getName()); this.hypervisorType = snapshot.getHypervisorType(); @@ -81,6 +95,14 @@ public class SnapshotObjectTO implements DataTO { this.path = path; } + public Long getPhysicalSize() { + return this.physicalSize; + } + + public void setPhysicalSize(Long physicalSize ) { + this.physicalSize = physicalSize; + } + public VolumeObjectTO getVolume() { return volume; } @@ -139,6 +161,10 @@ public class SnapshotObjectTO implements DataTO { this.quiescevm = quiescevm; } + public String[] getParents() { + return parents; + } + @Override public String toString() { return new StringBuilder("SnapshotTO[datastore=").append(dataStore).append("|volume=").append(volume).append("|path").append(path).append("]").toString(); diff --git a/core/test/org/apache/cloudstack/api/agent/test/CheckOnHostCommandTest.java b/core/test/org/apache/cloudstack/api/agent/test/CheckOnHostCommandTest.java index d266eb3aabe..9edbf102471 100644 --- a/core/test/org/apache/cloudstack/api/agent/test/CheckOnHostCommandTest.java +++ b/core/test/org/apache/cloudstack/api/agent/test/CheckOnHostCommandTest.java @@ -81,7 +81,10 @@ public class CheckOnHostCommandTest { return "10.1.1.1"; }; - @Override + public String getStorageUrl() { + return null; + } + public String getStorageIpAddress() { return "10.1.1.2"; }; diff --git a/debian/control b/debian/control index c756dcd0d8e..ab4644badd2 100644 --- a/debian/control +++ b/debian/control @@ -2,7 +2,7 @@ Source: cloudstack Section: libs Priority: extra Maintainer: Wido den Hollander -Build-Depends: debhelper (>= 7), openjdk-6-jdk | openjdk-7-jdk, tomcat6, genisoimage, +Build-Depends: debhelper (>= 7), openjdk-7-jdk, tomcat6, genisoimage, python-mysqldb, maven3 | maven (>= 3), python (>= 2.6.6-3~) Standards-Version: 3.8.1 Homepage: http://www.cloudstack.org/ @@ -22,7 +22,7 @@ Description: CloudStack server library Package: cloudstack-agent Architecture: all -Depends: openjdk-6-jre | openjdk-7-jre, cloudstack-common (= ${source:Version}), lsb-base (>= 3.2), libcommons-daemon-java, openssh-client, libvirt0, sysvinit-utils, qemu-kvm, libvirt-bin, uuid-runtime, rsync, grep, iproute, perl-base, perl-modules, ebtables, vlan, wget, jsvc, ipset, python-libvirt, ethtool, iptables +Depends: openjdk-7-jre, cloudstack-common (= ${source:Version}), lsb-base (>= 3.2), libcommons-daemon-java, openssh-client, libvirt0, sysvinit-utils, qemu-kvm, libvirt-bin, uuid-runtime, rsync, grep, iproute, perl-base, perl-modules, ebtables, vlan, wget, jsvc, ipset, python-libvirt, ethtool, iptables Conflicts: cloud-agent, cloud-agent-libs, cloud-agent-deps, cloud-agent-scripts Description: CloudStack agent The CloudStack agent is in charge of managing shared computing resources in @@ -31,7 +31,7 @@ Description: CloudStack agent Package: cloudstack-usage Architecture: all -Depends: openjdk-6-jre | openjdk-7-jre, cloudstack-common (= ${source:Version}), jsvc +Depends: openjdk-7-jre, cloudstack-common (= ${source:Version}), jsvc Description: CloudStack usage monitor The CloudStack usage monitor provides usage accounting across the entire cloud for cloud operators to charge based on usage parameters. diff --git a/deps/XenServerJava/pom.xml b/deps/XenServerJava/pom.xml index a621ab3d72c..84d9a975c98 100644 --- a/deps/XenServerJava/pom.xml +++ b/deps/XenServerJava/pom.xml @@ -36,7 +36,25 @@ - src - install + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + cloudstack-checkstyle + none + + + + + org.apache.cloudstack + checkstyle + + ${project.parent.version} + + + + diff --git a/deps/XenServerJava/src/com/xensource/xenapi/APIVersion.java b/deps/XenServerJava/src/com/xensource/xenapi/APIVersion.java index 174cf5ad581..8d7247d4fc3 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/APIVersion.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/APIVersion.java @@ -91,28 +91,28 @@ public enum APIVersion { switch (this) { - case API_1_1: - return "1.1"; - case API_1_2: - return "1.2"; - case API_1_3: - return "1.3"; - case API_1_4: - return "1.4"; - case API_1_5: - return "1.5"; - case API_1_6: - return "1.6"; - case API_1_7: - return "1.7"; - case API_1_8: - return "1.8"; - case API_1_9: - return "1.9"; - case API_1_10: - return "1.10"; - default: - return "Unknown"; + case API_1_1: + return "1.1"; + case API_1_2: + return "1.2"; + case API_1_3: + return "1.3"; + case API_1_4: + return "1.4"; + case API_1_5: + return "1.5"; + case API_1_6: + return "1.6"; + case API_1_7: + return "1.7"; + case API_1_8: + return "1.8"; + case API_1_9: + return "1.9"; + case API_1_10: + return "1.10"; + default: + return "Unknown"; } } } diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Auth.java b/deps/XenServerJava/src/com/xensource/xenapi/Auth.java index fd84390d2a5..cffaaaca965 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Auth.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Auth.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -52,7 +51,6 @@ import org.apache.xmlrpc.XmlRpcException; */ public class Auth extends XenAPIObject { - public String toWireString() { return null; } @@ -64,15 +62,15 @@ public class Auth extends XenAPIObject { * @return the subject_identifier obtained from the external directory service */ public static String getSubjectIdentifier(Connection c, String subjectName) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "auth.get_subject_identifier"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(subjectName)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -82,15 +80,15 @@ public class Auth extends XenAPIObject { * @return key-value pairs containing at least a key called subject_name */ public static Map getSubjectInformationFromIdentifier(Connection c, String subjectIdentifier) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "auth.get_subject_information_from_identifier"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(subjectIdentifier)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -100,15 +98,15 @@ public class Auth extends XenAPIObject { * @return set of subject_identifiers that provides the group membership of subject_identifier passed as argument, it contains, recursively, all groups a subject_identifier is member of. */ public static Set getGroupMembership(Connection c, String subjectIdentifier) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "auth.get_group_membership"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(subjectIdentifier)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Blob.java b/deps/XenServerJava/src/com/xensource/xenapi/Blob.java index eeff12e709b..494b9286407 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Blob.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Blob.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class Blob extends XenAPIObject { * For internal use only. */ Blob(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class Blob extends XenAPIObject { { if (obj != null && obj instanceof Blob) { - Blob other = (Blob) obj; + Blob other = (Blob)obj; return other.ref.equals(this.ref); } else { @@ -113,8 +112,8 @@ public class Blob extends XenAPIObject { /** * Convert a blob.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("name_label", this.nameLabel == null ? "" : this.nameLabel); map.put("name_description", this.nameDescription == null ? "" : this.nameDescription); @@ -161,15 +160,15 @@ public class Blob extends XenAPIObject { * @return all fields from the object */ public Blob.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "blob.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBlobRecord(result); + return Types.toBlobRecord(result); } /** @@ -179,15 +178,15 @@ public class Blob extends XenAPIObject { * @return reference to the object */ public static Blob getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "blob.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBlob(result); + return Types.toBlob(result); } /** @@ -197,15 +196,15 @@ public class Blob extends XenAPIObject { * @return references to objects with matching names */ public static Set getByNameLabel(Connection c, String label) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "blob.get_by_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(label)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfBlob(result); + return Types.toSetOfBlob(result); } /** @@ -214,15 +213,15 @@ public class Blob extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "blob.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -231,15 +230,15 @@ public class Blob extends XenAPIObject { * @return value of the field */ public String getNameLabel(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "blob.get_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -248,15 +247,15 @@ public class Blob extends XenAPIObject { * @return value of the field */ public String getNameDescription(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "blob.get_name_description"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -265,15 +264,15 @@ public class Blob extends XenAPIObject { * @return value of the field */ public Long getSize(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "blob.get_size"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -282,15 +281,15 @@ public class Blob extends XenAPIObject { * @return value of the field */ public Boolean getPublic(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "blob.get_public"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -299,15 +298,15 @@ public class Blob extends XenAPIObject { * @return value of the field */ public Date getLastUpdated(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "blob.get_last_updated"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDate(result); + return Types.toDate(result); } /** @@ -316,15 +315,15 @@ public class Blob extends XenAPIObject { * @return value of the field */ public String getMimeType(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "blob.get_mime_type"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -333,9 +332,9 @@ public class Blob extends XenAPIObject { * @param label New value to set */ public void setNameLabel(Connection c, String label) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "blob.set_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(label)}; @@ -349,9 +348,9 @@ public class Blob extends XenAPIObject { * @param description New value to set */ public void setNameDescription(Connection c, String description) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "blob.set_name_description"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(description)}; @@ -365,9 +364,9 @@ public class Blob extends XenAPIObject { * @param _public New value to set */ public void setPublic(Connection c, Boolean _public) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "blob.set_public"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(_public)}; @@ -383,15 +382,15 @@ public class Blob extends XenAPIObject { * @return The reference to the created blob */ public static Blob create(Connection c, String mimeType, Boolean _public) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "blob.create"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(mimeType), Marshalling.toXMLRPC(_public)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBlob(result); + return Types.toBlob(result); } /** @@ -399,9 +398,9 @@ public class Blob extends XenAPIObject { * */ public void destroy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "blob.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -415,15 +414,15 @@ public class Blob extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "blob.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfBlob(result); + return Types.toSetOfBlob(result); } /** @@ -432,15 +431,15 @@ public class Blob extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "blob.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfBlobBlobRecord(result); + return Types.toMapOfBlobBlobRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Bond.java b/deps/XenServerJava/src/com/xensource/xenapi/Bond.java index d9d30459e6e..935fd9847e5 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Bond.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Bond.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class Bond extends XenAPIObject { * For internal use only. */ Bond(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class Bond extends XenAPIObject { { if (obj != null && obj instanceof Bond) { - Bond other = (Bond) obj; + Bond other = (Bond)obj; return other.ref.equals(this.ref); } else { @@ -114,8 +113,8 @@ public class Bond extends XenAPIObject { /** * Convert a Bond.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("master", this.master == null ? new PIF("OpaqueRef:NULL") : this.master); map.put("slaves", this.slaves == null ? new LinkedHashSet() : this.slaves); @@ -167,15 +166,15 @@ public class Bond extends XenAPIObject { * @return all fields from the object */ public Bond.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Bond.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBondRecord(result); + return Types.toBondRecord(result); } /** @@ -185,15 +184,15 @@ public class Bond extends XenAPIObject { * @return reference to the object */ public static Bond getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Bond.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBond(result); + return Types.toBond(result); } /** @@ -202,15 +201,15 @@ public class Bond extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Bond.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -219,15 +218,15 @@ public class Bond extends XenAPIObject { * @return value of the field */ public PIF getMaster(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Bond.get_master"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toPIF(result); + return Types.toPIF(result); } /** @@ -236,15 +235,15 @@ public class Bond extends XenAPIObject { * @return value of the field */ public Set getSlaves(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Bond.get_slaves"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfPIF(result); + return Types.toSetOfPIF(result); } /** @@ -253,15 +252,15 @@ public class Bond extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Bond.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -270,15 +269,15 @@ public class Bond extends XenAPIObject { * @return value of the field */ public PIF getPrimarySlave(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Bond.get_primary_slave"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toPIF(result); + return Types.toPIF(result); } /** @@ -287,15 +286,15 @@ public class Bond extends XenAPIObject { * @return value of the field */ public Types.BondMode getMode(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Bond.get_mode"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBondMode(result); + return Types.toBondMode(result); } /** @@ -304,15 +303,15 @@ public class Bond extends XenAPIObject { * @return value of the field */ public Map getProperties(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Bond.get_properties"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -321,15 +320,15 @@ public class Bond extends XenAPIObject { * @return value of the field */ public Long getLinksUp(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Bond.get_links_up"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -338,9 +337,9 @@ public class Bond extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Bond.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -355,9 +354,9 @@ public class Bond extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Bond.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -371,9 +370,9 @@ public class Bond extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Bond.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -392,12 +391,13 @@ public class Bond extends XenAPIObject { * @return Task */ public static Task createAsync(Connection c, Network network, Set members, String MAC, Types.BondMode mode, Map properties) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.Bond.create"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(network), Marshalling.toXMLRPC(members), Marshalling.toXMLRPC(MAC), Marshalling.toXMLRPC(mode), Marshalling.toXMLRPC(properties)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(network), Marshalling.toXMLRPC(members), Marshalling.toXMLRPC(MAC), + Marshalling.toXMLRPC(mode), Marshalling.toXMLRPC(properties)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -414,15 +414,16 @@ public class Bond extends XenAPIObject { * @return The reference of the created Bond object */ public static Bond create(Connection c, Network network, Set members, String MAC, Types.BondMode mode, Map properties) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Bond.create"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(network), Marshalling.toXMLRPC(members), Marshalling.toXMLRPC(MAC), Marshalling.toXMLRPC(mode), Marshalling.toXMLRPC(properties)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(network), Marshalling.toXMLRPC(members), Marshalling.toXMLRPC(MAC), + Marshalling.toXMLRPC(mode), Marshalling.toXMLRPC(properties)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBond(result); + return Types.toBond(result); } /** @@ -431,9 +432,9 @@ public class Bond extends XenAPIObject { * @return Task */ public Task destroyAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.Bond.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -447,9 +448,9 @@ public class Bond extends XenAPIObject { * */ public void destroy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Bond.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -464,9 +465,9 @@ public class Bond extends XenAPIObject { * @return Task */ public Task setModeAsync(Connection c, Types.BondMode value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.Bond.set_mode"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -481,9 +482,9 @@ public class Bond extends XenAPIObject { * @param value The new bond mode */ public void setMode(Connection c, Types.BondMode value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Bond.set_mode"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -499,9 +500,9 @@ public class Bond extends XenAPIObject { * @return Task */ public Task setPropertyAsync(Connection c, String name, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.Bond.set_property"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(value)}; @@ -517,9 +518,9 @@ public class Bond extends XenAPIObject { * @param value The property value */ public void setProperty(Connection c, String name, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Bond.set_property"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(value)}; @@ -533,15 +534,15 @@ public class Bond extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Bond.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfBond(result); + return Types.toSetOfBond(result); } /** @@ -550,15 +551,15 @@ public class Bond extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Bond.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfBondBondRecord(result); + return Types.toMapOfBondBondRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Connection.java b/deps/XenServerJava/src/com/xensource/xenapi/Connection.java index 20ed00118b1..a6524503609 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Connection.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Connection.java @@ -101,7 +101,7 @@ public class Connection */ @Deprecated public Connection(String client, String username, String password) throws java.net.MalformedURLException, - XmlRpcException, BadServerResponse, SessionAuthenticationFailed, XenAPIException + XmlRpcException, BadServerResponse, SessionAuthenticationFailed, XenAPIException { deprecatedConstructorUsed = true; @@ -121,9 +121,9 @@ public class Connection //was the problem that the host was running rio? If so it will have complained that it got three parameters //instead of two. Let us carefully verify the details of this complaint if (0 == errDesc[0].compareTo("MESSAGE_PARAMETER_COUNT_MISMATCH") - && 0 == errDesc[1].compareTo("session.login_with_password") - && 0 == errDesc[2].compareTo("2") - && 0 == errDesc[3].compareTo("3")) + && 0 == errDesc[1].compareTo("session.login_with_password") + && 0 == errDesc[2].compareTo("2") + && 0 == errDesc[3].compareTo("3")) { //and if so, we can have another go, using the older login method, and see how that goes. this.sessionReference = loginWithPassword(this.client, username, password); @@ -139,13 +139,11 @@ public class Connection try { setAPIVersion(new Session(sessionReference)); - } - catch (XenAPIException exn) + } catch (XenAPIException exn) { dispose(); throw exn; - } - catch (XmlRpcException exn) + } catch (XmlRpcException exn) { dispose(); throw exn; @@ -208,12 +206,11 @@ public class Connection if (sessionReference != null) { String method_call = "session.logout"; - Object[] method_params = { Marshalling.toXMLRPC(this.sessionReference) }; + Object[] method_params = {Marshalling.toXMLRPC(this.sessionReference)}; client.execute(method_call, method_params); sessionReference = null; } - } - catch (XmlRpcException exn) + } catch (XmlRpcException exn) { } } @@ -223,17 +220,17 @@ public class Connection */ @Deprecated private static String loginWithPassword(XmlRpcClient client, String username, String password) - throws BadServerResponse, XmlRpcException, SessionAuthenticationFailed + throws BadServerResponse, XmlRpcException, SessionAuthenticationFailed { String method_call = "session.login_with_password"; - Object[] method_params = { Marshalling.toXMLRPC(username), Marshalling.toXMLRPC(password) }; - Map response = (Map) client.execute(method_call, method_params); + Object[] method_params = {Marshalling.toXMLRPC(username), Marshalling.toXMLRPC(password)}; + Map response = (Map)client.execute(method_call, method_params); if (response.get("Status").equals("Success")) { - return (String) response.get("Value"); + return (String)response.get("Value"); } else if (response.get("Status").equals("Failure")) { - Object[] error = (Object[]) response.get("ErrorDescription"); + Object[] error = (Object[])response.get("ErrorDescription"); if (error[0].equals("SESSION_AUTHENTICATION_FAILED")) { throw new SessionAuthenticationFailed(); @@ -247,18 +244,18 @@ public class Connection */ @Deprecated private static String loginWithPassword(XmlRpcClient client, String username, String password, String ApiVersion) - throws BadServerResponse, XmlRpcException, SessionAuthenticationFailed + throws BadServerResponse, XmlRpcException, SessionAuthenticationFailed { String method_call = "session.login_with_password"; - Object[] method_params = { Marshalling.toXMLRPC(username), Marshalling.toXMLRPC(password), - Marshalling.toXMLRPC(ApiVersion) }; - Map response = (Map) client.execute(method_call, method_params); + Object[] method_params = {Marshalling.toXMLRPC(username), Marshalling.toXMLRPC(password), + Marshalling.toXMLRPC(ApiVersion)}; + Map response = (Map)client.execute(method_call, method_params); if (response.get("Status").equals("Success")) { - return (String) response.get("Value"); + return (String)response.get("Value"); } else if (response.get("Status").equals("Failure")) { - Object[] error = (Object[]) response.get("ErrorDescription"); + Object[] error = (Object[])response.get("ErrorDescription"); if (error[0].equals("SESSION_AUTHENTICATION_FAILED")) { throw new SessionAuthenticationFailed(); @@ -271,8 +268,9 @@ public class Connection public XmlRpcClientConfigImpl getConfig() { - return config; + return config; } + private XmlRpcClient getClientFromURL(URL url) { config.setTimeZone(TimeZone.getTimeZone("UTC")); @@ -300,7 +298,7 @@ public class Connection */ protected Map dispatch(String method_call, Object[] method_params) throws XmlRpcException, XenAPIException { - Map response = (Map) client.execute(method_call, method_params); + Map response = (Map)client.execute(method_call, method_params); if (!deprecatedConstructorUsed) { @@ -316,7 +314,7 @@ public class Connection setAPIVersion(session); } else if (method_call.equals("session.slave_local_login_with_password") && - response.get("Status").equals("Success")) + response.get("Status").equals("Success")) { // Store the Session reference and assume the latest API version. sessionReference = Types.toSession(response.get("Value")).ref; @@ -331,7 +329,7 @@ public class Connection // this session from the master instead. if (response.get("Status").equals("Failure")) { - Object[] error = (Object[]) response.get("ErrorDescription"); + Object[] error = (Object[])response.get("ErrorDescription"); if (error.length == 2 && error[0].equals("HOST_IS_SLAVE")) { try @@ -340,20 +338,18 @@ public class Connection ((XmlRpcHttpClientConfig)client.getClientConfig()).getServerURL(); Connection tmp_conn = new Connection(new URL(client_url.getProtocol(), - (String)error[1], - client_url.getPort(), - client_url.getFile()), _wait); + (String)error[1], + client_url.getPort(), + client_url.getFile()), _wait); tmp_conn.sessionReference = sessionReference; try { Session.logout(tmp_conn); - } - finally + } finally { tmp_conn.dispose(); } - } - catch (Exception exn2) + } catch (Exception exn2) { // Ignore -- we're going to throw HostIsSlave anyway. } @@ -368,7 +364,6 @@ public class Connection return Types.checkResponse(response); } - private void setAPIVersion(Session session) throws XenAPIException, XmlRpcException { try @@ -376,8 +371,7 @@ public class Connection long major = session.getThisHost(this).getAPIVersionMajor(this); long minor = session.getThisHost(this).getAPIVersionMinor(this); apiVersion = APIVersion.fromMajorMinor(major, minor); - } - catch (BadServerResponse exn) + } catch (BadServerResponse exn) { apiVersion = APIVersion.API_1_1; } diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Console.java b/deps/XenServerJava/src/com/xensource/xenapi/Console.java index c734a839629..ac2c9a7ce8a 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Console.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Console.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class Console extends XenAPIObject { * For internal use only. */ Console(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class Console extends XenAPIObject { { if (obj != null && obj instanceof Console) { - Console other = (Console) obj; + Console other = (Console)obj; return other.ref.equals(this.ref); } else { @@ -111,8 +110,8 @@ public class Console extends XenAPIObject { /** * Convert a console.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("protocol", this.protocol == null ? Types.ConsoleProtocol.UNRECOGNIZED : this.protocol); map.put("location", this.location == null ? "" : this.location); @@ -149,15 +148,15 @@ public class Console extends XenAPIObject { * @return all fields from the object */ public Console.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "console.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toConsoleRecord(result); + return Types.toConsoleRecord(result); } /** @@ -167,15 +166,15 @@ public class Console extends XenAPIObject { * @return reference to the object */ public static Console getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "console.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toConsole(result); + return Types.toConsole(result); } /** @@ -185,9 +184,9 @@ public class Console extends XenAPIObject { * @return Task */ public static Task createAsync(Connection c, Console.Record record) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.console.create"; String session = c.getSessionReference(); Map record_map = record.toMap(); @@ -204,16 +203,16 @@ public class Console extends XenAPIObject { * @return reference to the newly created object */ public static Console create(Connection c, Console.Record record) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "console.create"; String session = c.getSessionReference(); Map record_map = record.toMap(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(record_map)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toConsole(result); + return Types.toConsole(result); } /** @@ -222,9 +221,9 @@ public class Console extends XenAPIObject { * @return Task */ public Task destroyAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.console.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -238,9 +237,9 @@ public class Console extends XenAPIObject { * */ public void destroy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "console.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -254,15 +253,15 @@ public class Console extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "console.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -271,15 +270,15 @@ public class Console extends XenAPIObject { * @return value of the field */ public Types.ConsoleProtocol getProtocol(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "console.get_protocol"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toConsoleProtocol(result); + return Types.toConsoleProtocol(result); } /** @@ -288,15 +287,15 @@ public class Console extends XenAPIObject { * @return value of the field */ public String getLocation(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "console.get_location"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -305,15 +304,15 @@ public class Console extends XenAPIObject { * @return value of the field */ public VM getVM(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "console.get_VM"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVM(result); + return Types.toVM(result); } /** @@ -322,15 +321,15 @@ public class Console extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "console.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -339,9 +338,9 @@ public class Console extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "console.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -356,9 +355,9 @@ public class Console extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "console.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -372,9 +371,9 @@ public class Console extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "console.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -388,15 +387,15 @@ public class Console extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "console.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfConsole(result); + return Types.toSetOfConsole(result); } /** @@ -405,15 +404,15 @@ public class Console extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "console.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfConsoleConsoleRecord(result); + return Types.toMapOfConsoleConsoleRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Crashdump.java b/deps/XenServerJava/src/com/xensource/xenapi/Crashdump.java index d1187bb4a7a..be11588cc25 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Crashdump.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Crashdump.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class Crashdump extends XenAPIObject { * For internal use only. */ Crashdump(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class Crashdump extends XenAPIObject { { if (obj != null && obj instanceof Crashdump) { - Crashdump other = (Crashdump) obj; + Crashdump other = (Crashdump)obj; return other.ref.equals(this.ref); } else { @@ -110,8 +109,8 @@ public class Crashdump extends XenAPIObject { /** * Convert a crashdump.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("VM", this.VM == null ? new VM("OpaqueRef:NULL") : this.VM); map.put("VDI", this.VDI == null ? new VDI("OpaqueRef:NULL") : this.VDI); @@ -143,15 +142,15 @@ public class Crashdump extends XenAPIObject { * @return all fields from the object */ public Crashdump.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "crashdump.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toCrashdumpRecord(result); + return Types.toCrashdumpRecord(result); } /** @@ -161,15 +160,15 @@ public class Crashdump extends XenAPIObject { * @return reference to the object */ public static Crashdump getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "crashdump.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toCrashdump(result); + return Types.toCrashdump(result); } /** @@ -178,15 +177,15 @@ public class Crashdump extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "crashdump.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -195,15 +194,15 @@ public class Crashdump extends XenAPIObject { * @return value of the field */ public VM getVM(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "crashdump.get_VM"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVM(result); + return Types.toVM(result); } /** @@ -212,15 +211,15 @@ public class Crashdump extends XenAPIObject { * @return value of the field */ public VDI getVDI(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "crashdump.get_VDI"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVDI(result); + return Types.toVDI(result); } /** @@ -229,15 +228,15 @@ public class Crashdump extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "crashdump.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -246,9 +245,9 @@ public class Crashdump extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "crashdump.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -263,9 +262,9 @@ public class Crashdump extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "crashdump.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -279,9 +278,9 @@ public class Crashdump extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "crashdump.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -295,9 +294,9 @@ public class Crashdump extends XenAPIObject { * @return Task */ public Task destroyAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.crashdump.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -311,9 +310,9 @@ public class Crashdump extends XenAPIObject { * */ public void destroy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "crashdump.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -327,15 +326,15 @@ public class Crashdump extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "crashdump.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfCrashdump(result); + return Types.toSetOfCrashdump(result); } /** @@ -344,15 +343,15 @@ public class Crashdump extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "crashdump.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfCrashdumpCrashdumpRecord(result); + return Types.toMapOfCrashdumpCrashdumpRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/DRTask.java b/deps/XenServerJava/src/com/xensource/xenapi/DRTask.java index 9694faa3c3c..14a5e4064a7 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/DRTask.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/DRTask.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class DRTask extends XenAPIObject { * For internal use only. */ DRTask(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class DRTask extends XenAPIObject { { if (obj != null && obj instanceof DRTask) { - DRTask other = (DRTask) obj; + DRTask other = (DRTask)obj; return other.ref.equals(this.ref); } else { @@ -108,8 +107,8 @@ public class DRTask extends XenAPIObject { /** * Convert a DR_task.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("introduced_SRs", this.introducedSRs == null ? new LinkedHashSet() : this.introducedSRs); return map; @@ -131,15 +130,15 @@ public class DRTask extends XenAPIObject { * @return all fields from the object */ public DRTask.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "DR_task.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDRTaskRecord(result); + return Types.toDRTaskRecord(result); } /** @@ -149,15 +148,15 @@ public class DRTask extends XenAPIObject { * @return reference to the object */ public static DRTask getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "DR_task.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDRTask(result); + return Types.toDRTask(result); } /** @@ -166,15 +165,15 @@ public class DRTask extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "DR_task.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -183,15 +182,15 @@ public class DRTask extends XenAPIObject { * @return value of the field */ public Set getIntroducedSRs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "DR_task.get_introduced_SRs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfSR(result); + return Types.toSetOfSR(result); } /** @@ -203,9 +202,9 @@ public class DRTask extends XenAPIObject { * @return Task */ public static Task createAsync(Connection c, String type, Map deviceConfig, Set whitelist) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.DR_task.create"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(whitelist)}; @@ -223,15 +222,15 @@ public class DRTask extends XenAPIObject { * @return The reference to the created task */ public static DRTask create(Connection c, String type, Map deviceConfig, Set whitelist) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "DR_task.create"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(whitelist)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDRTask(result); + return Types.toDRTask(result); } /** @@ -240,9 +239,9 @@ public class DRTask extends XenAPIObject { * @return Task */ public Task destroyAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.DR_task.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -256,9 +255,9 @@ public class DRTask extends XenAPIObject { * */ public void destroy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "DR_task.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -272,15 +271,15 @@ public class DRTask extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "DR_task.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfDRTask(result); + return Types.toSetOfDRTask(result); } /** @@ -289,15 +288,15 @@ public class DRTask extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "DR_task.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfDRTaskDRTaskRecord(result); + return Types.toMapOfDRTaskDRTaskRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/DataSource.java b/deps/XenServerJava/src/com/xensource/xenapi/DataSource.java index a0f46fb4fe8..5f777a32197 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/DataSource.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/DataSource.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class DataSource extends XenAPIObject { * For internal use only. */ DataSource(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class DataSource extends XenAPIObject { { if (obj != null && obj instanceof DataSource) { - DataSource other = (DataSource) obj; + DataSource other = (DataSource)obj; return other.ref.equals(this.ref); } else { @@ -114,8 +113,8 @@ public class DataSource extends XenAPIObject { /** * Convert a data_source.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("name_label", this.nameLabel == null ? "" : this.nameLabel); map.put("name_description", this.nameDescription == null ? "" : this.nameDescription); map.put("enabled", this.enabled == null ? false : this.enabled); diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Event.java b/deps/XenServerJava/src/com/xensource/xenapi/Event.java index 3574cd19b0f..ec438140fe2 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Event.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Event.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class Event extends XenAPIObject { * For internal use only. */ Event(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class Event extends XenAPIObject { { if (obj != null && obj instanceof Event) { - Event other = (Event) obj; + Event other = (Event)obj; return other.ref.equals(this.ref); } else { @@ -113,8 +112,8 @@ public class Event extends XenAPIObject { /** * Convert a event.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("id", this.id == null ? 0 : this.id); map.put("timestamp", this.timestamp == null ? new Date(0) : this.timestamp); map.put("class", this.clazz == null ? "" : this.clazz); @@ -163,9 +162,9 @@ public class Event extends XenAPIObject { * @return Task */ public static Task registerAsync(Connection c, Set classes) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.event.register"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(classes)}; @@ -180,9 +179,9 @@ public class Event extends XenAPIObject { * @param classes register for events for the indicated classes */ public static void register(Connection c, Set classes) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "event.register"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(classes)}; @@ -197,9 +196,9 @@ public class Event extends XenAPIObject { * @return Task */ public static Task unregisterAsync(Connection c, Set classes) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.event.unregister"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(classes)}; @@ -214,9 +213,9 @@ public class Event extends XenAPIObject { * @param classes remove this session's registration for the indicated classes */ public static void unregister(Connection c, Set classes) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "event.unregister"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(classes)}; @@ -230,17 +229,17 @@ public class Event extends XenAPIObject { * @return the batch of events */ public static Set next(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.SessionNotRegistered, - Types.EventsLost { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.SessionNotRegistered, + Types.EventsLost { String method_call = "event.next"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfEventRecord(result); + return Types.toSetOfEventRecord(result); } /** @@ -252,17 +251,17 @@ public class Event extends XenAPIObject { * @return the batch of events */ public static Set from(Connection c, Set classes, String token, Double timeout) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.SessionNotRegistered, - Types.EventsLost { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.SessionNotRegistered, + Types.EventsLost { String method_call = "event.from"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(classes), Marshalling.toXMLRPC(token), Marshalling.toXMLRPC(timeout)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfEventRecord(result); + return Types.toSetOfEventRecord(result); } /** @@ -271,15 +270,15 @@ public class Event extends XenAPIObject { * @return the event ID */ public static Long getCurrentId(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "event.get_current_id"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -290,15 +289,30 @@ public class Event extends XenAPIObject { * @return the event ID */ public static String inject(Connection c, String clazz, String ref) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "event.inject"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(clazz), Marshalling.toXMLRPC(ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); + } + + public static Map properFrom(Connection c, Set classes, String token, Double timeout) throws BadServerResponse, XenAPIException, XmlRpcException, + Types.SessionNotRegistered, + Types.EventsLost { + String method_call = "event.from"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(classes), Marshalling.toXMLRPC(token), Marshalling.toXMLRPC(timeout)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + Map value = (Map)result; + Map from = new HashMap(); + from.put("token", value.get("token")); + from.put("events", Types.toSetOfEventRecord(value.get("events"))); + return from; } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/GPUGroup.java b/deps/XenServerJava/src/com/xensource/xenapi/GPUGroup.java index fbd7d7d59dd..90704462703 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/GPUGroup.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/GPUGroup.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class GPUGroup extends XenAPIObject { * For internal use only. */ GPUGroup(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class GPUGroup extends XenAPIObject { { if (obj != null && obj instanceof GPUGroup) { - GPUGroup other = (GPUGroup) obj; + GPUGroup other = (GPUGroup)obj; return other.ref.equals(this.ref); } else { @@ -113,8 +112,8 @@ public class GPUGroup extends XenAPIObject { /** * Convert a GPU_group.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("name_label", this.nameLabel == null ? "" : this.nameLabel); map.put("name_description", this.nameDescription == null ? "" : this.nameDescription); @@ -161,15 +160,15 @@ public class GPUGroup extends XenAPIObject { * @return all fields from the object */ public GPUGroup.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "GPU_group.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toGPUGroupRecord(result); + return Types.toGPUGroupRecord(result); } /** @@ -179,15 +178,15 @@ public class GPUGroup extends XenAPIObject { * @return reference to the object */ public static GPUGroup getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "GPU_group.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toGPUGroup(result); + return Types.toGPUGroup(result); } /** @@ -197,15 +196,15 @@ public class GPUGroup extends XenAPIObject { * @return references to objects with matching names */ public static Set getByNameLabel(Connection c, String label) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "GPU_group.get_by_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(label)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfGPUGroup(result); + return Types.toSetOfGPUGroup(result); } /** @@ -214,15 +213,15 @@ public class GPUGroup extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "GPU_group.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -231,15 +230,15 @@ public class GPUGroup extends XenAPIObject { * @return value of the field */ public String getNameLabel(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "GPU_group.get_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -248,15 +247,15 @@ public class GPUGroup extends XenAPIObject { * @return value of the field */ public String getNameDescription(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "GPU_group.get_name_description"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -265,15 +264,15 @@ public class GPUGroup extends XenAPIObject { * @return value of the field */ public Set getPGPUs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "GPU_group.get_PGPUs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfPGPU(result); + return Types.toSetOfPGPU(result); } /** @@ -282,15 +281,15 @@ public class GPUGroup extends XenAPIObject { * @return value of the field */ public Set getVGPUs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "GPU_group.get_VGPUs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVGPU(result); + return Types.toSetOfVGPU(result); } /** @@ -299,15 +298,15 @@ public class GPUGroup extends XenAPIObject { * @return value of the field */ public Set getGPUTypes(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "GPU_group.get_GPU_types"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -316,15 +315,15 @@ public class GPUGroup extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "GPU_group.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -333,9 +332,9 @@ public class GPUGroup extends XenAPIObject { * @param label New value to set */ public void setNameLabel(Connection c, String label) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "GPU_group.set_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(label)}; @@ -349,9 +348,9 @@ public class GPUGroup extends XenAPIObject { * @param description New value to set */ public void setNameDescription(Connection c, String description) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "GPU_group.set_name_description"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(description)}; @@ -365,9 +364,9 @@ public class GPUGroup extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "GPU_group.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -382,9 +381,9 @@ public class GPUGroup extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "GPU_group.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -398,9 +397,9 @@ public class GPUGroup extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "GPU_group.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -414,15 +413,15 @@ public class GPUGroup extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "GPU_group.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfGPUGroup(result); + return Types.toSetOfGPUGroup(result); } /** @@ -431,15 +430,15 @@ public class GPUGroup extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "GPU_group.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfGPUGroupGPUGroupRecord(result); + return Types.toMapOfGPUGroupGPUGroupRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Host.java b/deps/XenServerJava/src/com/xensource/xenapi/Host.java index 2368930b55b..21950482123 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Host.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Host.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class Host extends XenAPIObject { * For internal use only. */ Host(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class Host extends XenAPIObject { { if (obj != null && obj instanceof Host) { - Host other = (Host) obj; + Host other = (Host)obj; return other.ref.equals(this.ref); } else { @@ -153,8 +152,8 @@ public class Host extends XenAPIObject { /** * Convert a host.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("name_label", this.nameLabel == null ? "" : this.nameLabel); map.put("name_description", this.nameDescription == null ? "" : this.nameDescription); @@ -164,7 +163,8 @@ public class Host extends XenAPIObject { map.put("API_version_major", this.APIVersionMajor == null ? 0 : this.APIVersionMajor); map.put("API_version_minor", this.APIVersionMinor == null ? 0 : this.APIVersionMinor); map.put("API_version_vendor", this.APIVersionVendor == null ? "" : this.APIVersionVendor); - map.put("API_version_vendor_implementation", this.APIVersionVendorImplementation == null ? new HashMap() : this.APIVersionVendorImplementation); + map.put("API_version_vendor_implementation", this.APIVersionVendorImplementation == null ? new HashMap() + : this.APIVersionVendorImplementation); map.put("enabled", this.enabled == null ? false : this.enabled); map.put("software_version", this.softwareVersion == null ? new HashMap() : this.softwareVersion); map.put("other_config", this.otherConfig == null ? new HashMap() : this.otherConfig); @@ -401,15 +401,15 @@ public class Host extends XenAPIObject { * @return all fields from the object */ public Host.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toHostRecord(result); + return Types.toHostRecord(result); } /** @@ -419,15 +419,15 @@ public class Host extends XenAPIObject { * @return reference to the object */ public static Host getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toHost(result); + return Types.toHost(result); } /** @@ -437,15 +437,15 @@ public class Host extends XenAPIObject { * @return references to objects with matching names */ public static Set getByNameLabel(Connection c, String label) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_by_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(label)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfHost(result); + return Types.toSetOfHost(result); } /** @@ -454,15 +454,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -471,15 +471,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public String getNameLabel(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -488,15 +488,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public String getNameDescription(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_name_description"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -505,15 +505,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Long getMemoryOverhead(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_memory_overhead"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -522,15 +522,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Set getAllowedOperations(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_allowed_operations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfHostAllowedOperations(result); + return Types.toSetOfHostAllowedOperations(result); } /** @@ -539,15 +539,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Map getCurrentOperations(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_current_operations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringHostAllowedOperations(result); + return Types.toMapOfStringHostAllowedOperations(result); } /** @@ -556,15 +556,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Long getAPIVersionMajor(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_API_version_major"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -573,15 +573,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Long getAPIVersionMinor(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_API_version_minor"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -590,15 +590,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public String getAPIVersionVendor(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_API_version_vendor"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -607,15 +607,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Map getAPIVersionVendorImplementation(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_API_version_vendor_implementation"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -624,15 +624,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Boolean getEnabled(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_enabled"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -641,15 +641,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Map getSoftwareVersion(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_software_version"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -658,15 +658,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -675,15 +675,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Set getCapabilities(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_capabilities"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -692,15 +692,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Map getCpuConfiguration(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_cpu_configuration"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -709,15 +709,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public String getSchedPolicy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_sched_policy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -726,15 +726,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Set getSupportedBootloaders(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_supported_bootloaders"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -743,15 +743,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Set getResidentVMs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_resident_VMs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVM(result); + return Types.toSetOfVM(result); } /** @@ -760,15 +760,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Map getLogging(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_logging"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -777,15 +777,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Set getPIFs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_PIFs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfPIF(result); + return Types.toSetOfPIF(result); } /** @@ -794,15 +794,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public SR getSuspendImageSr(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_suspend_image_sr"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSR(result); + return Types.toSR(result); } /** @@ -811,15 +811,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public SR getCrashDumpSr(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_crash_dump_sr"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSR(result); + return Types.toSR(result); } /** @@ -828,15 +828,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Set getCrashdumps(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_crashdumps"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfHostCrashdump(result); + return Types.toSetOfHostCrashdump(result); } /** @@ -845,15 +845,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Set getPatches(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_patches"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfHostPatch(result); + return Types.toSetOfHostPatch(result); } /** @@ -862,15 +862,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Set getPBDs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_PBDs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfPBD(result); + return Types.toSetOfPBD(result); } /** @@ -879,15 +879,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Set getHostCPUs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_host_CPUs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfHostCpu(result); + return Types.toSetOfHostCpu(result); } /** @@ -896,15 +896,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Map getCpuInfo(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_cpu_info"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -913,15 +913,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public String getHostname(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_hostname"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -930,15 +930,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public String getAddress(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_address"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -947,15 +947,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public HostMetrics getMetrics(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_metrics"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toHostMetrics(result); + return Types.toHostMetrics(result); } /** @@ -964,15 +964,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Map getLicenseParams(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_license_params"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -981,15 +981,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Set getHaStatefiles(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_ha_statefiles"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -998,15 +998,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Set getHaNetworkPeers(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_ha_network_peers"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -1015,15 +1015,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Map getBlobs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_blobs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringBlob(result); + return Types.toMapOfStringBlob(result); } /** @@ -1032,15 +1032,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Set getTags(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_tags"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -1049,15 +1049,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public String getExternalAuthType(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_external_auth_type"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -1066,15 +1066,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public String getExternalAuthServiceName(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_external_auth_service_name"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -1083,15 +1083,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Map getExternalAuthConfiguration(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_external_auth_configuration"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -1100,15 +1100,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public String getEdition(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_edition"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -1117,15 +1117,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Map getLicenseServer(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_license_server"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -1134,15 +1134,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Map getBiosStrings(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_bios_strings"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -1151,15 +1151,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public String getPowerOnMode(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_power_on_mode"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -1168,15 +1168,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Map getPowerOnConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_power_on_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -1185,15 +1185,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public SR getLocalCacheSr(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_local_cache_sr"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSR(result); + return Types.toSR(result); } /** @@ -1202,15 +1202,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Map getChipsetInfo(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_chipset_info"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -1219,15 +1219,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Set getPCIs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_PCIs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfPCI(result); + return Types.toSetOfPCI(result); } /** @@ -1236,15 +1236,15 @@ public class Host extends XenAPIObject { * @return value of the field */ public Set getPGPUs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_PGPUs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfPGPU(result); + return Types.toSetOfPGPU(result); } /** @@ -1253,9 +1253,9 @@ public class Host extends XenAPIObject { * @param label New value to set */ public void setNameLabel(Connection c, String label) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.set_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(label)}; @@ -1269,9 +1269,9 @@ public class Host extends XenAPIObject { * @param description New value to set */ public void setNameDescription(Connection c, String description) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.set_name_description"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(description)}; @@ -1285,9 +1285,9 @@ public class Host extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -1302,9 +1302,9 @@ public class Host extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -1318,9 +1318,9 @@ public class Host extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -1334,9 +1334,9 @@ public class Host extends XenAPIObject { * @param logging New value to set */ public void setLogging(Connection c, Map logging) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.set_logging"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(logging)}; @@ -1351,9 +1351,9 @@ public class Host extends XenAPIObject { * @param value Value to add */ public void addToLogging(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.add_to_logging"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -1367,9 +1367,9 @@ public class Host extends XenAPIObject { * @param key Key to remove */ public void removeFromLogging(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.remove_from_logging"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -1383,9 +1383,9 @@ public class Host extends XenAPIObject { * @param suspendImageSr New value to set */ public void setSuspendImageSr(Connection c, SR suspendImageSr) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.set_suspend_image_sr"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(suspendImageSr)}; @@ -1399,9 +1399,9 @@ public class Host extends XenAPIObject { * @param crashDumpSr New value to set */ public void setCrashDumpSr(Connection c, SR crashDumpSr) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.set_crash_dump_sr"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(crashDumpSr)}; @@ -1415,9 +1415,9 @@ public class Host extends XenAPIObject { * @param hostname New value to set */ public void setHostname(Connection c, String hostname) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.set_hostname"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(hostname)}; @@ -1431,9 +1431,9 @@ public class Host extends XenAPIObject { * @param address New value to set */ public void setAddress(Connection c, String address) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.set_address"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(address)}; @@ -1447,9 +1447,9 @@ public class Host extends XenAPIObject { * @param tags New value to set */ public void setTags(Connection c, Set tags) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.set_tags"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(tags)}; @@ -1463,9 +1463,9 @@ public class Host extends XenAPIObject { * @param value New value to add */ public void addTags(Connection c, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.add_tags"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1479,9 +1479,9 @@ public class Host extends XenAPIObject { * @param value Value to remove */ public void removeTags(Connection c, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.remove_tags"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1495,9 +1495,9 @@ public class Host extends XenAPIObject { * @param licenseServer New value to set */ public void setLicenseServer(Connection c, Map licenseServer) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.set_license_server"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(licenseServer)}; @@ -1512,9 +1512,9 @@ public class Host extends XenAPIObject { * @param value Value to add */ public void addToLicenseServer(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.add_to_license_server"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -1528,9 +1528,9 @@ public class Host extends XenAPIObject { * @param key Key to remove */ public void removeFromLicenseServer(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.remove_from_license_server"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -1544,9 +1544,9 @@ public class Host extends XenAPIObject { * @return Task */ public Task disableAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host.disable"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1560,9 +1560,9 @@ public class Host extends XenAPIObject { * */ public void disable(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.disable"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1576,9 +1576,9 @@ public class Host extends XenAPIObject { * @return Task */ public Task enableAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host.enable"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1592,9 +1592,9 @@ public class Host extends XenAPIObject { * */ public void enable(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.enable"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1608,9 +1608,9 @@ public class Host extends XenAPIObject { * @return Task */ public Task shutdownAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host.shutdown"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1624,9 +1624,9 @@ public class Host extends XenAPIObject { * */ public void shutdown(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.shutdown"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1640,9 +1640,9 @@ public class Host extends XenAPIObject { * @return Task */ public Task rebootAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host.reboot"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1656,9 +1656,9 @@ public class Host extends XenAPIObject { * */ public void reboot(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.reboot"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1672,9 +1672,9 @@ public class Host extends XenAPIObject { * @return Task */ public Task dmesgAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host.dmesg"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1689,15 +1689,15 @@ public class Host extends XenAPIObject { * @return dmesg string */ public String dmesg(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.dmesg"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -1706,9 +1706,9 @@ public class Host extends XenAPIObject { * @return Task */ public Task dmesgClearAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host.dmesg_clear"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1723,15 +1723,15 @@ public class Host extends XenAPIObject { * @return dmesg string */ public String dmesgClear(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.dmesg_clear"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -1740,9 +1740,9 @@ public class Host extends XenAPIObject { * @return Task */ public Task getLogAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host.get_log"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1757,15 +1757,15 @@ public class Host extends XenAPIObject { * @return The contents of the host's primary log file */ public String getLog(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_log"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -1775,9 +1775,9 @@ public class Host extends XenAPIObject { * @return Task */ public Task sendDebugKeysAsync(Connection c, String keys) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host.send_debug_keys"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(keys)}; @@ -1792,9 +1792,9 @@ public class Host extends XenAPIObject { * @param keys The keys to send */ public void sendDebugKeys(Connection c, String keys) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.send_debug_keys"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(keys)}; @@ -1810,9 +1810,9 @@ public class Host extends XenAPIObject { * @return Task */ public Task bugreportUploadAsync(Connection c, String url, Map options) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host.bugreport_upload"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(url), Marshalling.toXMLRPC(options)}; @@ -1828,9 +1828,9 @@ public class Host extends XenAPIObject { * @param options Extra configuration operations */ public void bugreportUpload(Connection c, String url, Map options) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.bugreport_upload"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(url), Marshalling.toXMLRPC(options)}; @@ -1844,15 +1844,15 @@ public class Host extends XenAPIObject { * @return The name of every supported method. */ public static Set listMethods(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.list_methods"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -1862,10 +1862,10 @@ public class Host extends XenAPIObject { * @return Task */ public Task licenseApplyAsync(Connection c, String contents) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.LicenseProcessingError { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.LicenseProcessingError { String method_call = "Async.host.license_apply"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(contents)}; @@ -1880,10 +1880,10 @@ public class Host extends XenAPIObject { * @param contents The contents of the license file, base64 encoded */ public void licenseApply(Connection c, String contents) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.LicenseProcessingError { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.LicenseProcessingError { String method_call = "host.license_apply"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(contents)}; @@ -1897,9 +1897,9 @@ public class Host extends XenAPIObject { * @return Task */ public Task destroyAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1913,9 +1913,9 @@ public class Host extends XenAPIObject { * */ public void destroy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1929,9 +1929,9 @@ public class Host extends XenAPIObject { * @return Task */ public Task powerOnAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host.power_on"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1945,9 +1945,9 @@ public class Host extends XenAPIObject { * */ public void powerOn(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.power_on"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1960,9 +1960,9 @@ public class Host extends XenAPIObject { * */ public static void emergencyHaDisable(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.emergency_ha_disable"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; @@ -1976,15 +1976,15 @@ public class Host extends XenAPIObject { * @return A set of data sources */ public Set getDataSources(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_data_sources"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfDataSourceRecord(result); + return Types.toSetOfDataSourceRecord(result); } /** @@ -1993,9 +1993,9 @@ public class Host extends XenAPIObject { * @param dataSource The data source to record */ public void recordDataSource(Connection c, String dataSource) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.record_data_source"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(dataSource)}; @@ -2010,15 +2010,15 @@ public class Host extends XenAPIObject { * @return The latest value, averaged over the last 5 seconds */ public Double queryDataSource(Connection c, String dataSource) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.query_data_source"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(dataSource)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDouble(result); + return Types.toDouble(result); } /** @@ -2027,9 +2027,9 @@ public class Host extends XenAPIObject { * @param dataSource The data source whose archives are to be forgotten */ public void forgetDataSourceArchives(Connection c, String dataSource) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.forget_data_source_archives"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(dataSource)}; @@ -2043,9 +2043,9 @@ public class Host extends XenAPIObject { * @return Task */ public Task assertCanEvacuateAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host.assert_can_evacuate"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -2059,9 +2059,9 @@ public class Host extends XenAPIObject { * */ public void assertCanEvacuate(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.assert_can_evacuate"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -2075,9 +2075,9 @@ public class Host extends XenAPIObject { * @return Task */ public Task getVmsWhichPreventEvacuationAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host.get_vms_which_prevent_evacuation"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -2092,15 +2092,15 @@ public class Host extends XenAPIObject { * @return VMs which block evacuation together with reasons */ public Map> getVmsWhichPreventEvacuation(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_vms_which_prevent_evacuation"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfVMSetOfString(result); + return Types.toMapOfVMSetOfString(result); } /** @@ -2109,10 +2109,11 @@ public class Host extends XenAPIObject { * * @return Task */ - @Deprecated public Task getUncooperativeResidentVMsAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + @Deprecated + public Task getUncooperativeResidentVMsAsync(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host.get_uncooperative_resident_VMs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -2127,16 +2128,17 @@ public class Host extends XenAPIObject { * * @return VMs which are not co-operating */ - @Deprecated public Set getUncooperativeResidentVMs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + @Deprecated + public Set getUncooperativeResidentVMs(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_uncooperative_resident_VMs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVM(result); + return Types.toSetOfVM(result); } /** @@ -2145,9 +2147,9 @@ public class Host extends XenAPIObject { * @return Task */ public Task evacuateAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host.evacuate"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -2161,9 +2163,9 @@ public class Host extends XenAPIObject { * */ public void evacuate(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.evacuate"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -2177,9 +2179,9 @@ public class Host extends XenAPIObject { * @return Task */ public Task syslogReconfigureAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host.syslog_reconfigure"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -2193,9 +2195,9 @@ public class Host extends XenAPIObject { * */ public void syslogReconfigure(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.syslog_reconfigure"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -2210,9 +2212,9 @@ public class Host extends XenAPIObject { * @return Task */ public static Task managementReconfigureAsync(Connection c, PIF pif) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host.management_reconfigure"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(pif)}; @@ -2227,9 +2229,9 @@ public class Host extends XenAPIObject { * @param pif reference to a PIF object corresponding to the management interface */ public static void managementReconfigure(Connection c, PIF pif) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.management_reconfigure"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(pif)}; @@ -2243,9 +2245,9 @@ public class Host extends XenAPIObject { * @param iface name of the interface to use as a management interface */ public static void localManagementReconfigure(Connection c, String iface) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.local_management_reconfigure"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(iface)}; @@ -2258,9 +2260,9 @@ public class Host extends XenAPIObject { * */ public static void managementDisable(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.management_disable"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; @@ -2274,9 +2276,9 @@ public class Host extends XenAPIObject { * @return Task */ public Task getManagementIfaceAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host.get_management_interface"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -2291,15 +2293,15 @@ public class Host extends XenAPIObject { * @return The managment interface for the host */ public PIF getManagementIface(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_management_interface"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toPIF(result); + return Types.toPIF(result); } /** @@ -2308,15 +2310,15 @@ public class Host extends XenAPIObject { * @return An XML fragment containing the system status capabilities. */ public String getSystemStatusCapabilities(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_system_status_capabilities"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -2325,9 +2327,9 @@ public class Host extends XenAPIObject { * @return Task */ public Task restartAgentAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host.restart_agent"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -2341,9 +2343,9 @@ public class Host extends XenAPIObject { * */ public void restartAgent(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.restart_agent"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -2356,9 +2358,9 @@ public class Host extends XenAPIObject { * */ public static void shutdownAgent(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.shutdown_agent"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; @@ -2372,10 +2374,10 @@ public class Host extends XenAPIObject { * @param hostname The new host name */ public void setHostnameLive(Connection c, String hostname) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.HostNameInvalid { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.HostNameInvalid { String method_call = "host.set_hostname_live"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(hostname)}; @@ -2389,9 +2391,9 @@ public class Host extends XenAPIObject { * @return Task */ public Task computeFreeMemoryAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host.compute_free_memory"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -2406,15 +2408,15 @@ public class Host extends XenAPIObject { * @return the amount of free memory on the host. */ public Long computeFreeMemory(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.compute_free_memory"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -2423,9 +2425,9 @@ public class Host extends XenAPIObject { * @return Task */ public Task computeMemoryOverheadAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host.compute_memory_overhead"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -2440,15 +2442,15 @@ public class Host extends XenAPIObject { * @return the virtualization memory overhead of the host. */ public Long computeMemoryOverhead(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.compute_memory_overhead"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -2456,9 +2458,9 @@ public class Host extends XenAPIObject { * */ public void syncData(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.sync_data"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -2472,9 +2474,9 @@ public class Host extends XenAPIObject { * @param delay Delay in seconds from when the call is received to perform the backup */ public void backupRrds(Connection c, Double delay) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.backup_rrds"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(delay)}; @@ -2491,12 +2493,13 @@ public class Host extends XenAPIObject { * @return Task */ public Task createNewBlobAsync(Connection c, String name, String mimeType, Boolean _public) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host.create_new_blob"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType), Marshalling.toXMLRPC(_public)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType), + Marshalling.toXMLRPC(_public)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -2511,15 +2514,16 @@ public class Host extends XenAPIObject { * @return The reference of the blob, needed for populating its data */ public Blob createNewBlob(Connection c, String name, String mimeType, Boolean _public) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.create_new_blob"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType), Marshalling.toXMLRPC(_public)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType), + Marshalling.toXMLRPC(_public)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBlob(result); + return Types.toBlob(result); } /** @@ -2531,12 +2535,13 @@ public class Host extends XenAPIObject { * @return Task */ public Task callPluginAsync(Connection c, String plugin, String fn, Map args) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host.call_plugin"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(plugin), Marshalling.toXMLRPC(fn), Marshalling.toXMLRPC(args)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(plugin), Marshalling.toXMLRPC(fn), + Marshalling.toXMLRPC(args)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -2551,15 +2556,16 @@ public class Host extends XenAPIObject { * @return Result from the plugin */ public String callPlugin(Connection c, String plugin, String fn, Map args) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.call_plugin"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(plugin), Marshalling.toXMLRPC(fn), Marshalling.toXMLRPC(args)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(plugin), Marshalling.toXMLRPC(fn), + Marshalling.toXMLRPC(args)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -2568,15 +2574,15 @@ public class Host extends XenAPIObject { * @return The current time */ public Date getServertime(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_servertime"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDate(result); + return Types.toDate(result); } /** @@ -2585,15 +2591,15 @@ public class Host extends XenAPIObject { * @return The current local time */ public Date getServerLocaltime(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_server_localtime"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDate(result); + return Types.toDate(result); } /** @@ -2604,12 +2610,13 @@ public class Host extends XenAPIObject { * @param authType The type of authentication (e.g. AD for Active Directory) */ public void enableExternalAuth(Connection c, Map config, String serviceName, String authType) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.enable_external_auth"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(config), Marshalling.toXMLRPC(serviceName), Marshalling.toXMLRPC(authType)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(config), Marshalling.toXMLRPC(serviceName), + Marshalling.toXMLRPC(authType)}; Map response = c.dispatch(method_call, method_params); return; } @@ -2620,9 +2627,9 @@ public class Host extends XenAPIObject { * @param config Optional parameters as a list of key-values containing the configuration data */ public void disableExternalAuth(Connection c, Map config) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.disable_external_auth"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(config)}; @@ -2636,9 +2643,9 @@ public class Host extends XenAPIObject { * @return Task */ public Task retrieveWlbEvacuateRecommendationsAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host.retrieve_wlb_evacuate_recommendations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -2653,15 +2660,15 @@ public class Host extends XenAPIObject { * @return VMs and the reasons why they would block evacuation, or their target host recommended by the wlb server */ public Map> retrieveWlbEvacuateRecommendations(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.retrieve_wlb_evacuate_recommendations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfVMSetOfString(result); + return Types.toMapOfVMSetOfString(result); } /** @@ -2670,9 +2677,9 @@ public class Host extends XenAPIObject { * @return Task */ public Task getServerCertificateAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host.get_server_certificate"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -2687,15 +2694,15 @@ public class Host extends XenAPIObject { * @return The installed server SSL certificate, in PEM form. */ public String getServerCertificate(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_server_certificate"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -2704,9 +2711,9 @@ public class Host extends XenAPIObject { * @param edition The requested edition */ public void applyEdition(Connection c, String edition) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.apply_edition"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(edition)}; @@ -2720,9 +2727,9 @@ public class Host extends XenAPIObject { * @return Task */ public Task refreshPackInfoAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host.refresh_pack_info"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -2736,9 +2743,9 @@ public class Host extends XenAPIObject { * */ public void refreshPackInfo(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.refresh_pack_info"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -2754,9 +2761,9 @@ public class Host extends XenAPIObject { * @return Task */ public Task setPowerOnModeAsync(Connection c, String powerOnMode, Map powerOnConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host.set_power_on_mode"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(powerOnMode), Marshalling.toXMLRPC(powerOnConfig)}; @@ -2772,9 +2779,9 @@ public class Host extends XenAPIObject { * @param powerOnConfig Power on config */ public void setPowerOnMode(Connection c, String powerOnMode, Map powerOnConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.set_power_on_mode"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(powerOnMode), Marshalling.toXMLRPC(powerOnConfig)}; @@ -2788,9 +2795,9 @@ public class Host extends XenAPIObject { * @param features The features string (32 hexadecimal digits) */ public void setCpuFeatures(Connection c, String features) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.set_cpu_features"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(features)}; @@ -2803,9 +2810,9 @@ public class Host extends XenAPIObject { * */ public void resetCpuFeatures(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.reset_cpu_features"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -2819,9 +2826,9 @@ public class Host extends XenAPIObject { * @param sr The SR to use as a local cache */ public void enableLocalStorageCaching(Connection c, SR sr) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.enable_local_storage_caching"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(sr)}; @@ -2834,9 +2841,9 @@ public class Host extends XenAPIObject { * */ public void disableLocalStorageCaching(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.disable_local_storage_caching"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -2852,9 +2859,9 @@ public class Host extends XenAPIObject { * @return Task */ public Task migrateReceiveAsync(Connection c, Network network, Map options) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host.migrate_receive"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(network), Marshalling.toXMLRPC(options)}; @@ -2871,15 +2878,15 @@ public class Host extends XenAPIObject { * @return A value which should be passed to VM.migrate */ public Map migrateReceive(Connection c, Network network, Map options) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.migrate_receive"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(network), Marshalling.toXMLRPC(options)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -2888,15 +2895,15 @@ public class Host extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfHost(result); + return Types.toSetOfHost(result); } /** @@ -2905,15 +2912,15 @@ public class Host extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfHostHostRecord(result); + return Types.toMapOfHostHostRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/HostCpu.java b/deps/XenServerJava/src/com/xensource/xenapi/HostCpu.java index 4f4cdbc7296..15fcfa7113f 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/HostCpu.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/HostCpu.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class HostCpu extends XenAPIObject { * For internal use only. */ HostCpu(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class HostCpu extends XenAPIObject { { if (obj != null && obj instanceof HostCpu) { - HostCpu other = (HostCpu) obj; + HostCpu other = (HostCpu)obj; return other.ref.equals(this.ref); } else { @@ -119,8 +118,8 @@ public class HostCpu extends XenAPIObject { /** * Convert a host_cpu.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("host", this.host == null ? new Host("OpaqueRef:NULL") : this.host); map.put("number", this.number == null ? 0 : this.number); @@ -197,16 +196,17 @@ public class HostCpu extends XenAPIObject { * * @return all fields from the object */ - @Deprecated public HostCpu.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + @Deprecated + public HostCpu.Record getRecord(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_cpu.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toHostCpuRecord(result); + return Types.toHostCpuRecord(result); } /** @@ -216,16 +216,17 @@ public class HostCpu extends XenAPIObject { * @param uuid UUID of object to return * @return reference to the object */ - @Deprecated public static HostCpu getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + @Deprecated + public static HostCpu getByUuid(Connection c, String uuid) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_cpu.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toHostCpu(result); + return Types.toHostCpu(result); } /** @@ -234,15 +235,15 @@ public class HostCpu extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_cpu.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -251,15 +252,15 @@ public class HostCpu extends XenAPIObject { * @return value of the field */ public Host getHost(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_cpu.get_host"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toHost(result); + return Types.toHost(result); } /** @@ -268,15 +269,15 @@ public class HostCpu extends XenAPIObject { * @return value of the field */ public Long getNumber(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_cpu.get_number"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -285,15 +286,15 @@ public class HostCpu extends XenAPIObject { * @return value of the field */ public String getVendor(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_cpu.get_vendor"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -302,15 +303,15 @@ public class HostCpu extends XenAPIObject { * @return value of the field */ public Long getSpeed(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_cpu.get_speed"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -319,15 +320,15 @@ public class HostCpu extends XenAPIObject { * @return value of the field */ public String getModelname(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_cpu.get_modelname"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -336,15 +337,15 @@ public class HostCpu extends XenAPIObject { * @return value of the field */ public Long getFamily(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_cpu.get_family"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -353,15 +354,15 @@ public class HostCpu extends XenAPIObject { * @return value of the field */ public Long getModel(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_cpu.get_model"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -370,15 +371,15 @@ public class HostCpu extends XenAPIObject { * @return value of the field */ public String getStepping(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_cpu.get_stepping"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -387,15 +388,15 @@ public class HostCpu extends XenAPIObject { * @return value of the field */ public String getFlags(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_cpu.get_flags"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -404,15 +405,15 @@ public class HostCpu extends XenAPIObject { * @return value of the field */ public String getFeatures(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_cpu.get_features"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -421,15 +422,15 @@ public class HostCpu extends XenAPIObject { * @return value of the field */ public Double getUtilisation(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_cpu.get_utilisation"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDouble(result); + return Types.toDouble(result); } /** @@ -438,15 +439,15 @@ public class HostCpu extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_cpu.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -455,9 +456,9 @@ public class HostCpu extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_cpu.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -472,9 +473,9 @@ public class HostCpu extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_cpu.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -488,9 +489,9 @@ public class HostCpu extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_cpu.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -504,16 +505,17 @@ public class HostCpu extends XenAPIObject { * * @return references to all objects */ - @Deprecated public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + @Deprecated + public static Set getAll(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_cpu.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfHostCpu(result); + return Types.toSetOfHostCpu(result); } /** @@ -522,15 +524,15 @@ public class HostCpu extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_cpu.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfHostCpuHostCpuRecord(result); + return Types.toMapOfHostCpuHostCpuRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/HostCrashdump.java b/deps/XenServerJava/src/com/xensource/xenapi/HostCrashdump.java index f63479054a3..02c3bd943f6 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/HostCrashdump.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/HostCrashdump.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class HostCrashdump extends XenAPIObject { * For internal use only. */ HostCrashdump(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class HostCrashdump extends XenAPIObject { { if (obj != null && obj instanceof HostCrashdump) { - HostCrashdump other = (HostCrashdump) obj; + HostCrashdump other = (HostCrashdump)obj; return other.ref.equals(this.ref); } else { @@ -111,8 +110,8 @@ public class HostCrashdump extends XenAPIObject { /** * Convert a host_crashdump.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("host", this.host == null ? new Host("OpaqueRef:NULL") : this.host); map.put("timestamp", this.timestamp == null ? new Date(0) : this.timestamp); @@ -149,15 +148,15 @@ public class HostCrashdump extends XenAPIObject { * @return all fields from the object */ public HostCrashdump.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_crashdump.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toHostCrashdumpRecord(result); + return Types.toHostCrashdumpRecord(result); } /** @@ -167,15 +166,15 @@ public class HostCrashdump extends XenAPIObject { * @return reference to the object */ public static HostCrashdump getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_crashdump.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toHostCrashdump(result); + return Types.toHostCrashdump(result); } /** @@ -184,15 +183,15 @@ public class HostCrashdump extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_crashdump.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -201,15 +200,15 @@ public class HostCrashdump extends XenAPIObject { * @return value of the field */ public Host getHost(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_crashdump.get_host"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toHost(result); + return Types.toHost(result); } /** @@ -218,15 +217,15 @@ public class HostCrashdump extends XenAPIObject { * @return value of the field */ public Date getTimestamp(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_crashdump.get_timestamp"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDate(result); + return Types.toDate(result); } /** @@ -235,15 +234,15 @@ public class HostCrashdump extends XenAPIObject { * @return value of the field */ public Long getSize(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_crashdump.get_size"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -252,15 +251,15 @@ public class HostCrashdump extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_crashdump.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -269,9 +268,9 @@ public class HostCrashdump extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_crashdump.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -286,9 +285,9 @@ public class HostCrashdump extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_crashdump.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -302,9 +301,9 @@ public class HostCrashdump extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_crashdump.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -318,9 +317,9 @@ public class HostCrashdump extends XenAPIObject { * @return Task */ public Task destroyAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host_crashdump.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -334,9 +333,9 @@ public class HostCrashdump extends XenAPIObject { * */ public void destroy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_crashdump.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -352,9 +351,9 @@ public class HostCrashdump extends XenAPIObject { * @return Task */ public Task uploadAsync(Connection c, String url, Map options) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host_crashdump.upload"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(url), Marshalling.toXMLRPC(options)}; @@ -370,9 +369,9 @@ public class HostCrashdump extends XenAPIObject { * @param options Extra configuration operations */ public void upload(Connection c, String url, Map options) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_crashdump.upload"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(url), Marshalling.toXMLRPC(options)}; @@ -386,15 +385,15 @@ public class HostCrashdump extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_crashdump.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfHostCrashdump(result); + return Types.toSetOfHostCrashdump(result); } /** @@ -403,15 +402,15 @@ public class HostCrashdump extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_crashdump.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfHostCrashdumpHostCrashdumpRecord(result); + return Types.toMapOfHostCrashdumpHostCrashdumpRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/HostMetrics.java b/deps/XenServerJava/src/com/xensource/xenapi/HostMetrics.java index 5c7c7805902..b41277aeb05 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/HostMetrics.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/HostMetrics.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class HostMetrics extends XenAPIObject { * For internal use only. */ HostMetrics(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class HostMetrics extends XenAPIObject { { if (obj != null && obj instanceof HostMetrics) { - HostMetrics other = (HostMetrics) obj; + HostMetrics other = (HostMetrics)obj; return other.ref.equals(this.ref); } else { @@ -112,8 +111,8 @@ public class HostMetrics extends XenAPIObject { /** * Convert a host_metrics.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("memory_total", this.memoryTotal == null ? 0 : this.memoryTotal); map.put("memory_free", this.memoryFree == null ? 0 : this.memoryFree); @@ -155,15 +154,15 @@ public class HostMetrics extends XenAPIObject { * @return all fields from the object */ public HostMetrics.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_metrics.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toHostMetricsRecord(result); + return Types.toHostMetricsRecord(result); } /** @@ -173,15 +172,15 @@ public class HostMetrics extends XenAPIObject { * @return reference to the object */ public static HostMetrics getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_metrics.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toHostMetrics(result); + return Types.toHostMetrics(result); } /** @@ -190,15 +189,15 @@ public class HostMetrics extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_metrics.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -207,15 +206,15 @@ public class HostMetrics extends XenAPIObject { * @return value of the field */ public Long getMemoryTotal(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_metrics.get_memory_total"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -224,16 +223,17 @@ public class HostMetrics extends XenAPIObject { * * @return value of the field */ - @Deprecated public Long getMemoryFree(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + @Deprecated + public Long getMemoryFree(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_metrics.get_memory_free"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -242,15 +242,15 @@ public class HostMetrics extends XenAPIObject { * @return value of the field */ public Boolean getLive(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_metrics.get_live"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -259,15 +259,15 @@ public class HostMetrics extends XenAPIObject { * @return value of the field */ public Date getLastUpdated(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_metrics.get_last_updated"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDate(result); + return Types.toDate(result); } /** @@ -276,15 +276,15 @@ public class HostMetrics extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_metrics.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -293,9 +293,9 @@ public class HostMetrics extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_metrics.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -310,9 +310,9 @@ public class HostMetrics extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_metrics.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -326,9 +326,9 @@ public class HostMetrics extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_metrics.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -342,15 +342,15 @@ public class HostMetrics extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_metrics.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfHostMetrics(result); + return Types.toSetOfHostMetrics(result); } /** @@ -359,15 +359,15 @@ public class HostMetrics extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_metrics.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfHostMetricsHostMetricsRecord(result); + return Types.toMapOfHostMetricsHostMetricsRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/HostPatch.java b/deps/XenServerJava/src/com/xensource/xenapi/HostPatch.java index fafe4377f42..fa77588232a 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/HostPatch.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/HostPatch.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class HostPatch extends XenAPIObject { * For internal use only. */ HostPatch(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class HostPatch extends XenAPIObject { { if (obj != null && obj instanceof HostPatch) { - HostPatch other = (HostPatch) obj; + HostPatch other = (HostPatch)obj; return other.ref.equals(this.ref); } else { @@ -116,8 +115,8 @@ public class HostPatch extends XenAPIObject { /** * Convert a host_patch.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("name_label", this.nameLabel == null ? "" : this.nameLabel); map.put("name_description", this.nameDescription == null ? "" : this.nameDescription); @@ -179,15 +178,15 @@ public class HostPatch extends XenAPIObject { * @return all fields from the object */ public HostPatch.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_patch.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toHostPatchRecord(result); + return Types.toHostPatchRecord(result); } /** @@ -197,15 +196,15 @@ public class HostPatch extends XenAPIObject { * @return reference to the object */ public static HostPatch getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_patch.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toHostPatch(result); + return Types.toHostPatch(result); } /** @@ -215,15 +214,15 @@ public class HostPatch extends XenAPIObject { * @return references to objects with matching names */ public static Set getByNameLabel(Connection c, String label) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_patch.get_by_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(label)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfHostPatch(result); + return Types.toSetOfHostPatch(result); } /** @@ -232,15 +231,15 @@ public class HostPatch extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_patch.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -249,15 +248,15 @@ public class HostPatch extends XenAPIObject { * @return value of the field */ public String getNameLabel(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_patch.get_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -266,15 +265,15 @@ public class HostPatch extends XenAPIObject { * @return value of the field */ public String getNameDescription(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_patch.get_name_description"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -283,15 +282,15 @@ public class HostPatch extends XenAPIObject { * @return value of the field */ public String getVersion(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_patch.get_version"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -300,15 +299,15 @@ public class HostPatch extends XenAPIObject { * @return value of the field */ public Host getHost(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_patch.get_host"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toHost(result); + return Types.toHost(result); } /** @@ -317,15 +316,15 @@ public class HostPatch extends XenAPIObject { * @return value of the field */ public Boolean getApplied(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_patch.get_applied"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -334,15 +333,15 @@ public class HostPatch extends XenAPIObject { * @return value of the field */ public Date getTimestampApplied(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_patch.get_timestamp_applied"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDate(result); + return Types.toDate(result); } /** @@ -351,15 +350,15 @@ public class HostPatch extends XenAPIObject { * @return value of the field */ public Long getSize(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_patch.get_size"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -368,15 +367,15 @@ public class HostPatch extends XenAPIObject { * @return value of the field */ public PoolPatch getPoolPatch(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_patch.get_pool_patch"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toPoolPatch(result); + return Types.toPoolPatch(result); } /** @@ -385,15 +384,15 @@ public class HostPatch extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_patch.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -402,9 +401,9 @@ public class HostPatch extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_patch.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -419,9 +418,9 @@ public class HostPatch extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_patch.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -435,9 +434,9 @@ public class HostPatch extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_patch.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -451,10 +450,11 @@ public class HostPatch extends XenAPIObject { * * @return Task */ - @Deprecated public Task destroyAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + @Deprecated + public Task destroyAsync(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host_patch.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -468,10 +468,11 @@ public class HostPatch extends XenAPIObject { * @deprecated * */ - @Deprecated public void destroy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + @Deprecated + public void destroy(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_patch.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -485,10 +486,11 @@ public class HostPatch extends XenAPIObject { * * @return Task */ - @Deprecated public Task applyAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + @Deprecated + public Task applyAsync(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.host_patch.apply"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -503,16 +505,17 @@ public class HostPatch extends XenAPIObject { * * @return the output of the patch application process */ - @Deprecated public String apply(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + @Deprecated + public String apply(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_patch.apply"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -521,15 +524,15 @@ public class HostPatch extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_patch.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfHostPatch(result); + return Types.toSetOfHostPatch(result); } /** @@ -538,15 +541,15 @@ public class HostPatch extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "host_patch.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfHostPatchHostPatchRecord(result); + return Types.toMapOfHostPatchHostPatchRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Marshalling.java b/deps/XenServerJava/src/com/xensource/xenapi/Marshalling.java index 6a2565d66ed..865bc16af11 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Marshalling.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Marshalling.java @@ -29,8 +29,8 @@ public final class Marshalling { o instanceof Double || o instanceof Date) { return o; - } else if (o instanceof Long) { - return o.toString(); + } else if (o instanceof Long) { + return o.toString(); } else if (o instanceof Map) { Map result = new HashMap(); Map m = (Map)o; @@ -46,14 +46,14 @@ public final class Marshalling { result.add(toXMLRPC(e)); } return result; - } else if (o instanceof XenAPIObject) { - return ((XenAPIObject) o).toWireString(); - } else if (o instanceof Enum) { - return o.toString(); - }else if (o == null){ - return ""; + } else if (o instanceof XenAPIObject) { + return ((XenAPIObject)o).toWireString(); + } else if (o instanceof Enum) { + return o.toString(); + } else if (o == null) { + return ""; } else { - throw new RuntimeException ("=============don't know how to marshall:({[" + o + "]})"); + throw new RuntimeException("=============don't know how to marshall:({[" + o + "]})"); } } } diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Message.java b/deps/XenServerJava/src/com/xensource/xenapi/Message.java index 95bcc8fa107..a3658e38344 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Message.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Message.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class Message extends XenAPIObject { * For internal use only. */ Message(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class Message extends XenAPIObject { { if (obj != null && obj instanceof Message) { - Message other = (Message) obj; + Message other = (Message)obj; return other.ref.equals(this.ref); } else { @@ -113,8 +112,8 @@ public class Message extends XenAPIObject { /** * Convert a message.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("name", this.name == null ? "" : this.name); map.put("priority", this.priority == null ? 0 : this.priority); @@ -166,15 +165,16 @@ public class Message extends XenAPIObject { * @return The reference of the created message */ public static Message create(Connection c, String name, Long priority, Types.Cls cls, String objUuid, String body) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "message.create"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(priority), Marshalling.toXMLRPC(cls), Marshalling.toXMLRPC(objUuid), Marshalling.toXMLRPC(body)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(priority), Marshalling.toXMLRPC(cls), + Marshalling.toXMLRPC(objUuid), Marshalling.toXMLRPC(body)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMessage(result); + return Types.toMessage(result); } /** @@ -182,9 +182,9 @@ public class Message extends XenAPIObject { * */ public void destroy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "message.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -201,15 +201,15 @@ public class Message extends XenAPIObject { * @return The relevant messages */ public static Map get(Connection c, Types.Cls cls, String objUuid, Date since) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "message.get"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(cls), Marshalling.toXMLRPC(objUuid), Marshalling.toXMLRPC(since)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfMessageMessageRecord(result); + return Types.toMapOfMessageMessageRecord(result); } /** @@ -218,15 +218,15 @@ public class Message extends XenAPIObject { * @return The references to the messages */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "message.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfMessage(result); + return Types.toSetOfMessage(result); } /** @@ -236,15 +236,15 @@ public class Message extends XenAPIObject { * @return The relevant messages */ public static Map getSince(Connection c, Date since) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "message.get_since"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(since)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfMessageMessageRecord(result); + return Types.toMapOfMessageMessageRecord(result); } /** @@ -253,15 +253,15 @@ public class Message extends XenAPIObject { * @return The message record */ public Message.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "message.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMessageRecord(result); + return Types.toMessageRecord(result); } /** @@ -271,15 +271,15 @@ public class Message extends XenAPIObject { * @return The message reference */ public static Message getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "message.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMessage(result); + return Types.toMessage(result); } /** @@ -288,15 +288,15 @@ public class Message extends XenAPIObject { * @return The messages */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "message.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfMessageMessageRecord(result); + return Types.toMapOfMessageMessageRecord(result); } /** @@ -306,15 +306,15 @@ public class Message extends XenAPIObject { * @return The messages */ public static Map getAllRecordsWhere(Connection c, String expr) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "message.get_all_records_where"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(expr)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfMessageMessageRecord(result); + return Types.toMapOfMessageMessageRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Network.java b/deps/XenServerJava/src/com/xensource/xenapi/Network.java index 1b23afeee4d..e9194ef7103 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Network.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Network.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class Network extends XenAPIObject { * For internal use only. */ Network(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class Network extends XenAPIObject { { if (obj != null && obj instanceof Network) { - Network other = (Network) obj; + Network other = (Network)obj; return other.ref.equals(this.ref); } else { @@ -119,8 +118,8 @@ public class Network extends XenAPIObject { /** * Convert a network.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("name_label", this.nameLabel == null ? "" : this.nameLabel); map.put("name_description", this.nameDescription == null ? "" : this.nameDescription); @@ -197,15 +196,15 @@ public class Network extends XenAPIObject { * @return all fields from the object */ public Network.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toNetworkRecord(result); + return Types.toNetworkRecord(result); } /** @@ -215,15 +214,15 @@ public class Network extends XenAPIObject { * @return reference to the object */ public static Network getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toNetwork(result); + return Types.toNetwork(result); } /** @@ -233,9 +232,9 @@ public class Network extends XenAPIObject { * @return Task */ public static Task createAsync(Connection c, Network.Record record) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.network.create"; String session = c.getSessionReference(); Map record_map = record.toMap(); @@ -252,16 +251,16 @@ public class Network extends XenAPIObject { * @return reference to the newly created object */ public static Network create(Connection c, Network.Record record) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.create"; String session = c.getSessionReference(); Map record_map = record.toMap(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(record_map)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toNetwork(result); + return Types.toNetwork(result); } /** @@ -270,9 +269,9 @@ public class Network extends XenAPIObject { * @return Task */ public Task destroyAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.network.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -286,9 +285,9 @@ public class Network extends XenAPIObject { * */ public void destroy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -303,15 +302,15 @@ public class Network extends XenAPIObject { * @return references to objects with matching names */ public static Set getByNameLabel(Connection c, String label) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.get_by_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(label)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfNetwork(result); + return Types.toSetOfNetwork(result); } /** @@ -320,15 +319,15 @@ public class Network extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -337,15 +336,15 @@ public class Network extends XenAPIObject { * @return value of the field */ public String getNameLabel(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.get_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -354,15 +353,15 @@ public class Network extends XenAPIObject { * @return value of the field */ public String getNameDescription(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.get_name_description"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -371,15 +370,15 @@ public class Network extends XenAPIObject { * @return value of the field */ public Set getAllowedOperations(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.get_allowed_operations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfNetworkOperations(result); + return Types.toSetOfNetworkOperations(result); } /** @@ -388,15 +387,15 @@ public class Network extends XenAPIObject { * @return value of the field */ public Map getCurrentOperations(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.get_current_operations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringNetworkOperations(result); + return Types.toMapOfStringNetworkOperations(result); } /** @@ -405,15 +404,15 @@ public class Network extends XenAPIObject { * @return value of the field */ public Set getVIFs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.get_VIFs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVIF(result); + return Types.toSetOfVIF(result); } /** @@ -422,15 +421,15 @@ public class Network extends XenAPIObject { * @return value of the field */ public Set getPIFs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.get_PIFs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfPIF(result); + return Types.toSetOfPIF(result); } /** @@ -439,15 +438,15 @@ public class Network extends XenAPIObject { * @return value of the field */ public Long getMTU(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.get_MTU"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -456,15 +455,15 @@ public class Network extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -473,15 +472,15 @@ public class Network extends XenAPIObject { * @return value of the field */ public String getBridge(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.get_bridge"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -490,15 +489,15 @@ public class Network extends XenAPIObject { * @return value of the field */ public Map getBlobs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.get_blobs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringBlob(result); + return Types.toMapOfStringBlob(result); } /** @@ -507,15 +506,15 @@ public class Network extends XenAPIObject { * @return value of the field */ public Set getTags(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.get_tags"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -524,15 +523,15 @@ public class Network extends XenAPIObject { * @return value of the field */ public Types.NetworkDefaultLockingMode getDefaultLockingMode(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.get_default_locking_mode"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toNetworkDefaultLockingMode(result); + return Types.toNetworkDefaultLockingMode(result); } /** @@ -541,9 +540,9 @@ public class Network extends XenAPIObject { * @param label New value to set */ public void setNameLabel(Connection c, String label) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.set_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(label)}; @@ -557,9 +556,9 @@ public class Network extends XenAPIObject { * @param description New value to set */ public void setNameDescription(Connection c, String description) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.set_name_description"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(description)}; @@ -573,9 +572,9 @@ public class Network extends XenAPIObject { * @param MTU New value to set */ public void setMTU(Connection c, Long MTU) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.set_MTU"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(MTU)}; @@ -589,9 +588,9 @@ public class Network extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -606,9 +605,9 @@ public class Network extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -622,9 +621,9 @@ public class Network extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -638,9 +637,9 @@ public class Network extends XenAPIObject { * @param tags New value to set */ public void setTags(Connection c, Set tags) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.set_tags"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(tags)}; @@ -654,9 +653,9 @@ public class Network extends XenAPIObject { * @param value New value to add */ public void addTags(Connection c, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.add_tags"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -670,9 +669,9 @@ public class Network extends XenAPIObject { * @param value Value to remove */ public void removeTags(Connection c, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.remove_tags"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -689,12 +688,13 @@ public class Network extends XenAPIObject { * @return Task */ public Task createNewBlobAsync(Connection c, String name, String mimeType, Boolean _public) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.network.create_new_blob"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType), Marshalling.toXMLRPC(_public)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType), + Marshalling.toXMLRPC(_public)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -709,15 +709,16 @@ public class Network extends XenAPIObject { * @return The reference of the blob, needed for populating its data */ public Blob createNewBlob(Connection c, String name, String mimeType, Boolean _public) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.create_new_blob"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType), Marshalling.toXMLRPC(_public)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType), + Marshalling.toXMLRPC(_public)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBlob(result); + return Types.toBlob(result); } /** @@ -727,9 +728,9 @@ public class Network extends XenAPIObject { * @return Task */ public Task setDefaultLockingModeAsync(Connection c, Types.NetworkDefaultLockingMode value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.network.set_default_locking_mode"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -744,9 +745,9 @@ public class Network extends XenAPIObject { * @param value The default locking mode for VIFs attached to this network. */ public void setDefaultLockingMode(Connection c, Types.NetworkDefaultLockingMode value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.set_default_locking_mode"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -760,15 +761,15 @@ public class Network extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfNetwork(result); + return Types.toSetOfNetwork(result); } /** @@ -777,15 +778,15 @@ public class Network extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "network.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfNetworkNetworkRecord(result); + return Types.toMapOfNetworkNetworkRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/PBD.java b/deps/XenServerJava/src/com/xensource/xenapi/PBD.java index 6fddfa68542..d2898247572 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/PBD.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/PBD.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class PBD extends XenAPIObject { * For internal use only. */ PBD(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class PBD extends XenAPIObject { { if (obj != null && obj instanceof PBD) { - PBD other = (PBD) obj; + PBD other = (PBD)obj; return other.ref.equals(this.ref); } else { @@ -112,8 +111,8 @@ public class PBD extends XenAPIObject { /** * Convert a PBD.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("host", this.host == null ? new Host("OpaqueRef:NULL") : this.host); map.put("SR", this.SR == null ? new SR("OpaqueRef:NULL") : this.SR); @@ -155,15 +154,15 @@ public class PBD extends XenAPIObject { * @return all fields from the object */ public PBD.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PBD.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toPBDRecord(result); + return Types.toPBDRecord(result); } /** @@ -173,15 +172,15 @@ public class PBD extends XenAPIObject { * @return reference to the object */ public static PBD getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PBD.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toPBD(result); + return Types.toPBD(result); } /** @@ -191,9 +190,9 @@ public class PBD extends XenAPIObject { * @return Task */ public static Task createAsync(Connection c, PBD.Record record) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.PBD.create"; String session = c.getSessionReference(); Map record_map = record.toMap(); @@ -210,16 +209,16 @@ public class PBD extends XenAPIObject { * @return reference to the newly created object */ public static PBD create(Connection c, PBD.Record record) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PBD.create"; String session = c.getSessionReference(); Map record_map = record.toMap(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(record_map)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toPBD(result); + return Types.toPBD(result); } /** @@ -228,9 +227,9 @@ public class PBD extends XenAPIObject { * @return Task */ public Task destroyAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.PBD.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -244,9 +243,9 @@ public class PBD extends XenAPIObject { * */ public void destroy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PBD.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -260,15 +259,15 @@ public class PBD extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PBD.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -277,15 +276,15 @@ public class PBD extends XenAPIObject { * @return value of the field */ public Host getHost(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PBD.get_host"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toHost(result); + return Types.toHost(result); } /** @@ -294,15 +293,15 @@ public class PBD extends XenAPIObject { * @return value of the field */ public SR getSR(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PBD.get_SR"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSR(result); + return Types.toSR(result); } /** @@ -311,15 +310,15 @@ public class PBD extends XenAPIObject { * @return value of the field */ public Map getDeviceConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PBD.get_device_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -328,15 +327,15 @@ public class PBD extends XenAPIObject { * @return value of the field */ public Boolean getCurrentlyAttached(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PBD.get_currently_attached"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -345,15 +344,15 @@ public class PBD extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PBD.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -362,9 +361,9 @@ public class PBD extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PBD.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -379,9 +378,9 @@ public class PBD extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PBD.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -395,9 +394,9 @@ public class PBD extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PBD.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -411,10 +410,10 @@ public class PBD extends XenAPIObject { * @return Task */ public Task plugAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.SrUnknownDriver { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.SrUnknownDriver { String method_call = "Async.PBD.plug"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -428,10 +427,10 @@ public class PBD extends XenAPIObject { * */ public void plug(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.SrUnknownDriver { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.SrUnknownDriver { String method_call = "PBD.plug"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -445,9 +444,9 @@ public class PBD extends XenAPIObject { * @return Task */ public Task unplugAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.PBD.unplug"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -461,9 +460,9 @@ public class PBD extends XenAPIObject { * */ public void unplug(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PBD.unplug"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -478,9 +477,9 @@ public class PBD extends XenAPIObject { * @return Task */ public Task setDeviceConfigAsync(Connection c, Map value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.PBD.set_device_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -495,9 +494,9 @@ public class PBD extends XenAPIObject { * @param value The new value of the PBD's device_config */ public void setDeviceConfig(Connection c, Map value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PBD.set_device_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -511,15 +510,15 @@ public class PBD extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PBD.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfPBD(result); + return Types.toSetOfPBD(result); } /** @@ -528,15 +527,15 @@ public class PBD extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PBD.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfPBDPBDRecord(result); + return Types.toMapOfPBDPBDRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/PCI.java b/deps/XenServerJava/src/com/xensource/xenapi/PCI.java index 9e2ec77d0be..e11230a6289 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/PCI.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/PCI.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class PCI extends XenAPIObject { * For internal use only. */ PCI(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class PCI extends XenAPIObject { { if (obj != null && obj instanceof PCI) { - PCI other = (PCI) obj; + PCI other = (PCI)obj; return other.ref.equals(this.ref); } else { @@ -114,8 +113,8 @@ public class PCI extends XenAPIObject { /** * Convert a PCI.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("class_name", this.clazzName == null ? "" : this.clazzName); map.put("vendor_name", this.vendorName == null ? "" : this.vendorName); @@ -167,15 +166,15 @@ public class PCI extends XenAPIObject { * @return all fields from the object */ public PCI.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PCI.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toPCIRecord(result); + return Types.toPCIRecord(result); } /** @@ -185,15 +184,15 @@ public class PCI extends XenAPIObject { * @return reference to the object */ public static PCI getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PCI.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toPCI(result); + return Types.toPCI(result); } /** @@ -202,15 +201,15 @@ public class PCI extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PCI.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -219,15 +218,15 @@ public class PCI extends XenAPIObject { * @return value of the field */ public String getClazzName(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PCI.get_class_name"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -236,15 +235,15 @@ public class PCI extends XenAPIObject { * @return value of the field */ public String getVendorName(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PCI.get_vendor_name"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -253,15 +252,15 @@ public class PCI extends XenAPIObject { * @return value of the field */ public String getDeviceName(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PCI.get_device_name"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -270,15 +269,15 @@ public class PCI extends XenAPIObject { * @return value of the field */ public Host getHost(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PCI.get_host"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toHost(result); + return Types.toHost(result); } /** @@ -287,15 +286,15 @@ public class PCI extends XenAPIObject { * @return value of the field */ public String getPciId(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PCI.get_pci_id"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -304,15 +303,15 @@ public class PCI extends XenAPIObject { * @return value of the field */ public Set getDependencies(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PCI.get_dependencies"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfPCI(result); + return Types.toSetOfPCI(result); } /** @@ -321,15 +320,15 @@ public class PCI extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PCI.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -338,9 +337,9 @@ public class PCI extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PCI.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -355,9 +354,9 @@ public class PCI extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PCI.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -371,9 +370,9 @@ public class PCI extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PCI.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -387,15 +386,15 @@ public class PCI extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PCI.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfPCI(result); + return Types.toSetOfPCI(result); } /** @@ -404,15 +403,15 @@ public class PCI extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PCI.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfPCIPCIRecord(result); + return Types.toMapOfPCIPCIRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/PGPU.java b/deps/XenServerJava/src/com/xensource/xenapi/PGPU.java index a9e1c432dad..0f5ddb4bdf9 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/PGPU.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/PGPU.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class PGPU extends XenAPIObject { * For internal use only. */ PGPU(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class PGPU extends XenAPIObject { { if (obj != null && obj instanceof PGPU) { - PGPU other = (PGPU) obj; + PGPU other = (PGPU)obj; return other.ref.equals(this.ref); } else { @@ -111,8 +110,8 @@ public class PGPU extends XenAPIObject { /** * Convert a PGPU.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("PCI", this.PCI == null ? new PCI("OpaqueRef:NULL") : this.PCI); map.put("GPU_group", this.GPUGroup == null ? new GPUGroup("OpaqueRef:NULL") : this.GPUGroup); @@ -149,15 +148,15 @@ public class PGPU extends XenAPIObject { * @return all fields from the object */ public PGPU.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PGPU.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toPGPURecord(result); + return Types.toPGPURecord(result); } /** @@ -167,15 +166,15 @@ public class PGPU extends XenAPIObject { * @return reference to the object */ public static PGPU getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PGPU.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toPGPU(result); + return Types.toPGPU(result); } /** @@ -184,15 +183,15 @@ public class PGPU extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PGPU.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -201,15 +200,15 @@ public class PGPU extends XenAPIObject { * @return value of the field */ public PCI getPCI(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PGPU.get_PCI"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toPCI(result); + return Types.toPCI(result); } /** @@ -218,15 +217,15 @@ public class PGPU extends XenAPIObject { * @return value of the field */ public GPUGroup getGPUGroup(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PGPU.get_GPU_group"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toGPUGroup(result); + return Types.toGPUGroup(result); } /** @@ -235,15 +234,15 @@ public class PGPU extends XenAPIObject { * @return value of the field */ public Host getHost(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PGPU.get_host"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toHost(result); + return Types.toHost(result); } /** @@ -252,15 +251,15 @@ public class PGPU extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PGPU.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -269,9 +268,9 @@ public class PGPU extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PGPU.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -286,9 +285,9 @@ public class PGPU extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PGPU.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -302,9 +301,9 @@ public class PGPU extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PGPU.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -318,15 +317,15 @@ public class PGPU extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PGPU.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfPGPU(result); + return Types.toSetOfPGPU(result); } /** @@ -335,15 +334,15 @@ public class PGPU extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PGPU.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfPGPUPGPURecord(result); + return Types.toMapOfPGPUPGPURecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/PIF.java b/deps/XenServerJava/src/com/xensource/xenapi/PIF.java index 950afebce14..27618b4105b 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/PIF.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/PIF.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class PIF extends XenAPIObject { * For internal use only. */ PIF(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class PIF extends XenAPIObject { { if (obj != null && obj instanceof PIF) { - PIF other = (PIF) obj; + PIF other = (PIF)obj; return other.ref.equals(this.ref); } else { @@ -134,8 +133,8 @@ public class PIF extends XenAPIObject { /** * Convert a PIF.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("device", this.device == null ? "" : this.device); map.put("network", this.network == null ? new Network("OpaqueRef:NULL") : this.network); @@ -287,15 +286,15 @@ public class PIF extends XenAPIObject { * @return all fields from the object */ public PIF.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toPIFRecord(result); + return Types.toPIFRecord(result); } /** @@ -305,15 +304,15 @@ public class PIF extends XenAPIObject { * @return reference to the object */ public static PIF getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toPIF(result); + return Types.toPIF(result); } /** @@ -322,15 +321,15 @@ public class PIF extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -339,15 +338,15 @@ public class PIF extends XenAPIObject { * @return value of the field */ public String getDevice(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_device"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -356,15 +355,15 @@ public class PIF extends XenAPIObject { * @return value of the field */ public Network getNetwork(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_network"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toNetwork(result); + return Types.toNetwork(result); } /** @@ -373,15 +372,15 @@ public class PIF extends XenAPIObject { * @return value of the field */ public Host getHost(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_host"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toHost(result); + return Types.toHost(result); } /** @@ -390,15 +389,15 @@ public class PIF extends XenAPIObject { * @return value of the field */ public String getMAC(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_MAC"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -407,15 +406,15 @@ public class PIF extends XenAPIObject { * @return value of the field */ public Long getMTU(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_MTU"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -424,15 +423,15 @@ public class PIF extends XenAPIObject { * @return value of the field */ public Long getVLAN(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_VLAN"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -441,15 +440,15 @@ public class PIF extends XenAPIObject { * @return value of the field */ public PIFMetrics getMetrics(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_metrics"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toPIFMetrics(result); + return Types.toPIFMetrics(result); } /** @@ -458,15 +457,15 @@ public class PIF extends XenAPIObject { * @return value of the field */ public Boolean getPhysical(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_physical"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -475,15 +474,15 @@ public class PIF extends XenAPIObject { * @return value of the field */ public Boolean getCurrentlyAttached(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_currently_attached"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -492,15 +491,15 @@ public class PIF extends XenAPIObject { * @return value of the field */ public Types.IpConfigurationMode getIpConfigurationMode(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_ip_configuration_mode"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toIpConfigurationMode(result); + return Types.toIpConfigurationMode(result); } /** @@ -509,15 +508,15 @@ public class PIF extends XenAPIObject { * @return value of the field */ public String getIP(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_IP"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -526,15 +525,15 @@ public class PIF extends XenAPIObject { * @return value of the field */ public String getNetmask(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_netmask"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -543,15 +542,15 @@ public class PIF extends XenAPIObject { * @return value of the field */ public String getGateway(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_gateway"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -560,15 +559,15 @@ public class PIF extends XenAPIObject { * @return value of the field */ public String getDNS(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_DNS"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -577,15 +576,15 @@ public class PIF extends XenAPIObject { * @return value of the field */ public Bond getBondSlaveOf(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_bond_slave_of"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBond(result); + return Types.toBond(result); } /** @@ -594,15 +593,15 @@ public class PIF extends XenAPIObject { * @return value of the field */ public Set getBondMasterOf(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_bond_master_of"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfBond(result); + return Types.toSetOfBond(result); } /** @@ -611,15 +610,15 @@ public class PIF extends XenAPIObject { * @return value of the field */ public VLAN getVLANMasterOf(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_VLAN_master_of"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVLAN(result); + return Types.toVLAN(result); } /** @@ -628,15 +627,15 @@ public class PIF extends XenAPIObject { * @return value of the field */ public Set getVLANSlaveOf(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_VLAN_slave_of"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVLAN(result); + return Types.toSetOfVLAN(result); } /** @@ -645,15 +644,15 @@ public class PIF extends XenAPIObject { * @return value of the field */ public Boolean getManagement(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_management"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -662,15 +661,15 @@ public class PIF extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -679,15 +678,15 @@ public class PIF extends XenAPIObject { * @return value of the field */ public Boolean getDisallowUnplug(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_disallow_unplug"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -696,15 +695,15 @@ public class PIF extends XenAPIObject { * @return value of the field */ public Set getTunnelAccessPIFOf(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_tunnel_access_PIF_of"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfTunnel(result); + return Types.toSetOfTunnel(result); } /** @@ -713,15 +712,15 @@ public class PIF extends XenAPIObject { * @return value of the field */ public Set getTunnelTransportPIFOf(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_tunnel_transport_PIF_of"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfTunnel(result); + return Types.toSetOfTunnel(result); } /** @@ -730,15 +729,15 @@ public class PIF extends XenAPIObject { * @return value of the field */ public Types.Ipv6ConfigurationMode getIpv6ConfigurationMode(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_ipv6_configuration_mode"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toIpv6ConfigurationMode(result); + return Types.toIpv6ConfigurationMode(result); } /** @@ -747,15 +746,15 @@ public class PIF extends XenAPIObject { * @return value of the field */ public Set getIPv6(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_IPv6"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -764,15 +763,15 @@ public class PIF extends XenAPIObject { * @return value of the field */ public String getIpv6Gateway(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_ipv6_gateway"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -781,15 +780,15 @@ public class PIF extends XenAPIObject { * @return value of the field */ public Types.PrimaryAddressType getPrimaryAddressType(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_primary_address_type"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toPrimaryAddressType(result); + return Types.toPrimaryAddressType(result); } /** @@ -798,9 +797,9 @@ public class PIF extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -815,9 +814,9 @@ public class PIF extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -831,9 +830,9 @@ public class PIF extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -847,9 +846,9 @@ public class PIF extends XenAPIObject { * @param disallowUnplug New value to set */ public void setDisallowUnplug(Connection c, Boolean disallowUnplug) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.set_disallow_unplug"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(disallowUnplug)}; @@ -867,14 +866,16 @@ public class PIF extends XenAPIObject { * @param VLAN VLAN tag for the new interface * @return Task */ - @Deprecated public static Task createVLANAsync(Connection c, String device, Network network, Host host, Long VLAN) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VlanTagInvalid { + @Deprecated + public static Task createVLANAsync(Connection c, String device, Network network, Host host, Long VLAN) throws + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VlanTagInvalid { String method_call = "Async.PIF.create_VLAN"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(device), Marshalling.toXMLRPC(network), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(VLAN)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(device), Marshalling.toXMLRPC(network), Marshalling.toXMLRPC(host), + Marshalling.toXMLRPC(VLAN)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -890,17 +891,19 @@ public class PIF extends XenAPIObject { * @param VLAN VLAN tag for the new interface * @return The reference of the created PIF object */ - @Deprecated public static PIF createVLAN(Connection c, String device, Network network, Host host, Long VLAN) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VlanTagInvalid { + @Deprecated + public static PIF createVLAN(Connection c, String device, Network network, Host host, Long VLAN) throws + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VlanTagInvalid { String method_call = "PIF.create_VLAN"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(device), Marshalling.toXMLRPC(network), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(VLAN)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(device), Marshalling.toXMLRPC(network), Marshalling.toXMLRPC(host), + Marshalling.toXMLRPC(VLAN)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toPIF(result); + return Types.toPIF(result); } /** @@ -909,11 +912,12 @@ public class PIF extends XenAPIObject { * * @return Task */ - @Deprecated public Task destroyAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.PifIsPhysical { + @Deprecated + public Task destroyAsync(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.PifIsPhysical { String method_call = "Async.PIF.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -927,11 +931,12 @@ public class PIF extends XenAPIObject { * @deprecated * */ - @Deprecated public void destroy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.PifIsPhysical { + @Deprecated + public void destroy(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.PifIsPhysical { String method_call = "PIF.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -950,12 +955,13 @@ public class PIF extends XenAPIObject { * @return Task */ public Task reconfigureIpAsync(Connection c, Types.IpConfigurationMode mode, String IP, String netmask, String gateway, String DNS) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.PIF.reconfigure_ip"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(mode), Marshalling.toXMLRPC(IP), Marshalling.toXMLRPC(netmask), Marshalling.toXMLRPC(gateway), Marshalling.toXMLRPC(DNS)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(mode), Marshalling.toXMLRPC(IP), + Marshalling.toXMLRPC(netmask), Marshalling.toXMLRPC(gateway), Marshalling.toXMLRPC(DNS)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -971,12 +977,13 @@ public class PIF extends XenAPIObject { * @param DNS the new DNS settings */ public void reconfigureIp(Connection c, Types.IpConfigurationMode mode, String IP, String netmask, String gateway, String DNS) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.reconfigure_ip"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(mode), Marshalling.toXMLRPC(IP), Marshalling.toXMLRPC(netmask), Marshalling.toXMLRPC(gateway), Marshalling.toXMLRPC(DNS)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(mode), Marshalling.toXMLRPC(IP), + Marshalling.toXMLRPC(netmask), Marshalling.toXMLRPC(gateway), Marshalling.toXMLRPC(DNS)}; Map response = c.dispatch(method_call, method_params); return; } @@ -991,12 +998,13 @@ public class PIF extends XenAPIObject { * @return Task */ public Task reconfigureIpv6Async(Connection c, Types.Ipv6ConfigurationMode mode, String IPv6, String gateway, String DNS) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.PIF.reconfigure_ipv6"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(mode), Marshalling.toXMLRPC(IPv6), Marshalling.toXMLRPC(gateway), Marshalling.toXMLRPC(DNS)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(mode), Marshalling.toXMLRPC(IPv6), + Marshalling.toXMLRPC(gateway), Marshalling.toXMLRPC(DNS)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -1011,12 +1019,13 @@ public class PIF extends XenAPIObject { * @param DNS the new DNS settings */ public void reconfigureIpv6(Connection c, Types.Ipv6ConfigurationMode mode, String IPv6, String gateway, String DNS) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.reconfigure_ipv6"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(mode), Marshalling.toXMLRPC(IPv6), Marshalling.toXMLRPC(gateway), Marshalling.toXMLRPC(DNS)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(mode), Marshalling.toXMLRPC(IPv6), + Marshalling.toXMLRPC(gateway), Marshalling.toXMLRPC(DNS)}; Map response = c.dispatch(method_call, method_params); return; } @@ -1028,9 +1037,9 @@ public class PIF extends XenAPIObject { * @return Task */ public Task setPrimaryAddressTypeAsync(Connection c, Types.PrimaryAddressType primaryAddressType) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.PIF.set_primary_address_type"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(primaryAddressType)}; @@ -1045,9 +1054,9 @@ public class PIF extends XenAPIObject { * @param primaryAddressType Whether to prefer IPv4 or IPv6 connections */ public void setPrimaryAddressType(Connection c, Types.PrimaryAddressType primaryAddressType) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.set_primary_address_type"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(primaryAddressType)}; @@ -1062,9 +1071,9 @@ public class PIF extends XenAPIObject { * @return Task */ public static Task scanAsync(Connection c, Host host) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.PIF.scan"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host)}; @@ -1079,9 +1088,9 @@ public class PIF extends XenAPIObject { * @param host The host on which to scan */ public static void scan(Connection c, Host host) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.scan"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host)}; @@ -1098,9 +1107,9 @@ public class PIF extends XenAPIObject { * @return Task */ public static Task introduceAsync(Connection c, Host host, String MAC, String device) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.PIF.introduce"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(MAC), Marshalling.toXMLRPC(device)}; @@ -1118,15 +1127,15 @@ public class PIF extends XenAPIObject { * @return The reference of the created PIF object */ public static PIF introduce(Connection c, Host host, String MAC, String device) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.introduce"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(MAC), Marshalling.toXMLRPC(device)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toPIF(result); + return Types.toPIF(result); } /** @@ -1135,10 +1144,10 @@ public class PIF extends XenAPIObject { * @return Task */ public Task forgetAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.PifTunnelStillExists { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.PifTunnelStillExists { String method_call = "Async.PIF.forget"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1152,10 +1161,10 @@ public class PIF extends XenAPIObject { * */ public void forget(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.PifTunnelStillExists { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.PifTunnelStillExists { String method_call = "PIF.forget"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1169,9 +1178,9 @@ public class PIF extends XenAPIObject { * @return Task */ public Task unplugAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.PIF.unplug"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1185,9 +1194,9 @@ public class PIF extends XenAPIObject { * */ public void unplug(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.unplug"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1201,10 +1210,10 @@ public class PIF extends XenAPIObject { * @return Task */ public Task plugAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.TransportPifNotConfigured { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.TransportPifNotConfigured { String method_call = "Async.PIF.plug"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1218,10 +1227,10 @@ public class PIF extends XenAPIObject { * */ public void plug(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.TransportPifNotConfigured { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.TransportPifNotConfigured { String method_call = "PIF.plug"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1255,13 +1264,20 @@ public class PIF extends XenAPIObject { * @param primaryAddressType * @return Task */ - public static Task dbIntroduceAsync(Connection c, String device, Network network, Host host, String MAC, Long MTU, Long VLAN, Boolean physical, Types.IpConfigurationMode ipConfigurationMode, String IP, String netmask, String gateway, String DNS, Bond bondSlaveOf, VLAN VLANMasterOf, Boolean management, Map otherConfig, Boolean disallowUnplug, Types.Ipv6ConfigurationMode ipv6ConfigurationMode, Set IPv6, String ipv6Gateway, Types.PrimaryAddressType primaryAddressType) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + public static Task dbIntroduceAsync(Connection c, String device, Network network, Host host, String MAC, Long MTU, Long VLAN, Boolean physical, + Types.IpConfigurationMode ipConfigurationMode, String IP, String netmask, String gateway, String DNS, Bond bondSlaveOf, VLAN VLANMasterOf, Boolean management, + Map otherConfig, Boolean disallowUnplug, Types.Ipv6ConfigurationMode ipv6ConfigurationMode, Set IPv6, String ipv6Gateway, + Types.PrimaryAddressType primaryAddressType) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.PIF.db_introduce"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(device), Marshalling.toXMLRPC(network), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(MAC), Marshalling.toXMLRPC(MTU), Marshalling.toXMLRPC(VLAN), Marshalling.toXMLRPC(physical), Marshalling.toXMLRPC(ipConfigurationMode), Marshalling.toXMLRPC(IP), Marshalling.toXMLRPC(netmask), Marshalling.toXMLRPC(gateway), Marshalling.toXMLRPC(DNS), Marshalling.toXMLRPC(bondSlaveOf), Marshalling.toXMLRPC(VLANMasterOf), Marshalling.toXMLRPC(management), Marshalling.toXMLRPC(otherConfig), Marshalling.toXMLRPC(disallowUnplug), Marshalling.toXMLRPC(ipv6ConfigurationMode), Marshalling.toXMLRPC(IPv6), Marshalling.toXMLRPC(ipv6Gateway), Marshalling.toXMLRPC(primaryAddressType)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(device), Marshalling.toXMLRPC(network), Marshalling.toXMLRPC(host), + Marshalling.toXMLRPC(MAC), Marshalling.toXMLRPC(MTU), Marshalling.toXMLRPC(VLAN), Marshalling.toXMLRPC(physical), Marshalling.toXMLRPC(ipConfigurationMode), + Marshalling.toXMLRPC(IP), Marshalling.toXMLRPC(netmask), Marshalling.toXMLRPC(gateway), Marshalling.toXMLRPC(DNS), Marshalling.toXMLRPC(bondSlaveOf), + Marshalling.toXMLRPC(VLANMasterOf), Marshalling.toXMLRPC(management), Marshalling.toXMLRPC(otherConfig), Marshalling.toXMLRPC(disallowUnplug), + Marshalling.toXMLRPC(ipv6ConfigurationMode), Marshalling.toXMLRPC(IPv6), Marshalling.toXMLRPC(ipv6Gateway), Marshalling.toXMLRPC(primaryAddressType)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -1293,16 +1309,23 @@ public class PIF extends XenAPIObject { * @param primaryAddressType * @return The ref of the newly created PIF record. */ - public static PIF dbIntroduce(Connection c, String device, Network network, Host host, String MAC, Long MTU, Long VLAN, Boolean physical, Types.IpConfigurationMode ipConfigurationMode, String IP, String netmask, String gateway, String DNS, Bond bondSlaveOf, VLAN VLANMasterOf, Boolean management, Map otherConfig, Boolean disallowUnplug, Types.Ipv6ConfigurationMode ipv6ConfigurationMode, Set IPv6, String ipv6Gateway, Types.PrimaryAddressType primaryAddressType) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + public static PIF dbIntroduce(Connection c, String device, Network network, Host host, String MAC, Long MTU, Long VLAN, Boolean physical, + Types.IpConfigurationMode ipConfigurationMode, String IP, String netmask, String gateway, String DNS, Bond bondSlaveOf, VLAN VLANMasterOf, Boolean management, + Map otherConfig, Boolean disallowUnplug, Types.Ipv6ConfigurationMode ipv6ConfigurationMode, Set IPv6, String ipv6Gateway, + Types.PrimaryAddressType primaryAddressType) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.db_introduce"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(device), Marshalling.toXMLRPC(network), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(MAC), Marshalling.toXMLRPC(MTU), Marshalling.toXMLRPC(VLAN), Marshalling.toXMLRPC(physical), Marshalling.toXMLRPC(ipConfigurationMode), Marshalling.toXMLRPC(IP), Marshalling.toXMLRPC(netmask), Marshalling.toXMLRPC(gateway), Marshalling.toXMLRPC(DNS), Marshalling.toXMLRPC(bondSlaveOf), Marshalling.toXMLRPC(VLANMasterOf), Marshalling.toXMLRPC(management), Marshalling.toXMLRPC(otherConfig), Marshalling.toXMLRPC(disallowUnplug), Marshalling.toXMLRPC(ipv6ConfigurationMode), Marshalling.toXMLRPC(IPv6), Marshalling.toXMLRPC(ipv6Gateway), Marshalling.toXMLRPC(primaryAddressType)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(device), Marshalling.toXMLRPC(network), Marshalling.toXMLRPC(host), + Marshalling.toXMLRPC(MAC), Marshalling.toXMLRPC(MTU), Marshalling.toXMLRPC(VLAN), Marshalling.toXMLRPC(physical), Marshalling.toXMLRPC(ipConfigurationMode), + Marshalling.toXMLRPC(IP), Marshalling.toXMLRPC(netmask), Marshalling.toXMLRPC(gateway), Marshalling.toXMLRPC(DNS), Marshalling.toXMLRPC(bondSlaveOf), + Marshalling.toXMLRPC(VLANMasterOf), Marshalling.toXMLRPC(management), Marshalling.toXMLRPC(otherConfig), Marshalling.toXMLRPC(disallowUnplug), + Marshalling.toXMLRPC(ipv6ConfigurationMode), Marshalling.toXMLRPC(IPv6), Marshalling.toXMLRPC(ipv6Gateway), Marshalling.toXMLRPC(primaryAddressType)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toPIF(result); + return Types.toPIF(result); } /** @@ -1311,9 +1334,9 @@ public class PIF extends XenAPIObject { * @return Task */ public Task dbForgetAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.PIF.db_forget"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1327,9 +1350,9 @@ public class PIF extends XenAPIObject { * */ public void dbForget(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.db_forget"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1343,15 +1366,15 @@ public class PIF extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfPIF(result); + return Types.toSetOfPIF(result); } /** @@ -1360,15 +1383,15 @@ public class PIF extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfPIFPIFRecord(result); + return Types.toMapOfPIFPIFRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/PIFMetrics.java b/deps/XenServerJava/src/com/xensource/xenapi/PIFMetrics.java index d0a3911d327..ab6268ee8f7 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/PIFMetrics.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/PIFMetrics.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class PIFMetrics extends XenAPIObject { * For internal use only. */ PIFMetrics(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class PIFMetrics extends XenAPIObject { { if (obj != null && obj instanceof PIFMetrics) { - PIFMetrics other = (PIFMetrics) obj; + PIFMetrics other = (PIFMetrics)obj; return other.ref.equals(this.ref); } else { @@ -119,8 +118,8 @@ public class PIFMetrics extends XenAPIObject { /** * Convert a PIF_metrics.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("io_read_kbs", this.ioReadKbs == null ? 0.0 : this.ioReadKbs); map.put("io_write_kbs", this.ioWriteKbs == null ? 0.0 : this.ioWriteKbs); @@ -197,15 +196,15 @@ public class PIFMetrics extends XenAPIObject { * @return all fields from the object */ public PIFMetrics.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF_metrics.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toPIFMetricsRecord(result); + return Types.toPIFMetricsRecord(result); } /** @@ -215,15 +214,15 @@ public class PIFMetrics extends XenAPIObject { * @return reference to the object */ public static PIFMetrics getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF_metrics.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toPIFMetrics(result); + return Types.toPIFMetrics(result); } /** @@ -232,15 +231,15 @@ public class PIFMetrics extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF_metrics.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -249,15 +248,15 @@ public class PIFMetrics extends XenAPIObject { * @return value of the field */ public Double getIoReadKbs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF_metrics.get_io_read_kbs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDouble(result); + return Types.toDouble(result); } /** @@ -266,15 +265,15 @@ public class PIFMetrics extends XenAPIObject { * @return value of the field */ public Double getIoWriteKbs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF_metrics.get_io_write_kbs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDouble(result); + return Types.toDouble(result); } /** @@ -283,15 +282,15 @@ public class PIFMetrics extends XenAPIObject { * @return value of the field */ public Boolean getCarrier(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF_metrics.get_carrier"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -300,15 +299,15 @@ public class PIFMetrics extends XenAPIObject { * @return value of the field */ public String getVendorId(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF_metrics.get_vendor_id"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -317,15 +316,15 @@ public class PIFMetrics extends XenAPIObject { * @return value of the field */ public String getVendorName(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF_metrics.get_vendor_name"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -334,15 +333,15 @@ public class PIFMetrics extends XenAPIObject { * @return value of the field */ public String getDeviceId(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF_metrics.get_device_id"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -351,15 +350,15 @@ public class PIFMetrics extends XenAPIObject { * @return value of the field */ public String getDeviceName(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF_metrics.get_device_name"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -368,15 +367,15 @@ public class PIFMetrics extends XenAPIObject { * @return value of the field */ public Long getSpeed(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF_metrics.get_speed"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -385,15 +384,15 @@ public class PIFMetrics extends XenAPIObject { * @return value of the field */ public Boolean getDuplex(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF_metrics.get_duplex"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -402,15 +401,15 @@ public class PIFMetrics extends XenAPIObject { * @return value of the field */ public String getPciBusPath(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF_metrics.get_pci_bus_path"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -419,15 +418,15 @@ public class PIFMetrics extends XenAPIObject { * @return value of the field */ public Date getLastUpdated(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF_metrics.get_last_updated"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDate(result); + return Types.toDate(result); } /** @@ -436,15 +435,15 @@ public class PIFMetrics extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF_metrics.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -453,9 +452,9 @@ public class PIFMetrics extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF_metrics.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -470,9 +469,9 @@ public class PIFMetrics extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF_metrics.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -486,9 +485,9 @@ public class PIFMetrics extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF_metrics.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -502,15 +501,15 @@ public class PIFMetrics extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF_metrics.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfPIFMetrics(result); + return Types.toSetOfPIFMetrics(result); } /** @@ -519,15 +518,15 @@ public class PIFMetrics extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "PIF_metrics.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfPIFMetricsPIFMetricsRecord(result); + return Types.toMapOfPIFMetricsPIFMetricsRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Pool.java b/deps/XenServerJava/src/com/xensource/xenapi/Pool.java index 2dc0fac9c78..7ceebb02d56 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Pool.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Pool.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class Pool extends XenAPIObject { * For internal use only. */ Pool(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class Pool extends XenAPIObject { { if (obj != null && obj instanceof Pool) { - Pool other = (Pool) obj; + Pool other = (Pool)obj; return other.ref.equals(this.ref); } else { @@ -133,8 +132,8 @@ public class Pool extends XenAPIObject { /** * Convert a pool.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("name_label", this.nameLabel == null ? "" : this.nameLabel); map.put("name_description", this.nameDescription == null ? "" : this.nameDescription); @@ -281,15 +280,15 @@ public class Pool extends XenAPIObject { * @return all fields from the object */ public Pool.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toPoolRecord(result); + return Types.toPoolRecord(result); } /** @@ -299,15 +298,15 @@ public class Pool extends XenAPIObject { * @return reference to the object */ public static Pool getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toPool(result); + return Types.toPool(result); } /** @@ -316,15 +315,15 @@ public class Pool extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -333,15 +332,15 @@ public class Pool extends XenAPIObject { * @return value of the field */ public String getNameLabel(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -350,15 +349,15 @@ public class Pool extends XenAPIObject { * @return value of the field */ public String getNameDescription(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_name_description"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -367,15 +366,15 @@ public class Pool extends XenAPIObject { * @return value of the field */ public Host getMaster(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_master"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toHost(result); + return Types.toHost(result); } /** @@ -384,15 +383,15 @@ public class Pool extends XenAPIObject { * @return value of the field */ public SR getDefaultSR(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_default_SR"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSR(result); + return Types.toSR(result); } /** @@ -401,15 +400,15 @@ public class Pool extends XenAPIObject { * @return value of the field */ public SR getSuspendImageSR(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_suspend_image_SR"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSR(result); + return Types.toSR(result); } /** @@ -418,15 +417,15 @@ public class Pool extends XenAPIObject { * @return value of the field */ public SR getCrashDumpSR(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_crash_dump_SR"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSR(result); + return Types.toSR(result); } /** @@ -435,15 +434,15 @@ public class Pool extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -452,15 +451,15 @@ public class Pool extends XenAPIObject { * @return value of the field */ public Boolean getHaEnabled(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_ha_enabled"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -469,15 +468,15 @@ public class Pool extends XenAPIObject { * @return value of the field */ public Map getHaConfiguration(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_ha_configuration"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -486,15 +485,15 @@ public class Pool extends XenAPIObject { * @return value of the field */ public Set getHaStatefiles(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_ha_statefiles"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -503,15 +502,15 @@ public class Pool extends XenAPIObject { * @return value of the field */ public Long getHaHostFailuresToTolerate(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_ha_host_failures_to_tolerate"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -520,15 +519,15 @@ public class Pool extends XenAPIObject { * @return value of the field */ public Long getHaPlanExistsFor(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_ha_plan_exists_for"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -537,15 +536,15 @@ public class Pool extends XenAPIObject { * @return value of the field */ public Boolean getHaAllowOvercommit(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_ha_allow_overcommit"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -554,15 +553,15 @@ public class Pool extends XenAPIObject { * @return value of the field */ public Boolean getHaOvercommitted(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_ha_overcommitted"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -571,15 +570,15 @@ public class Pool extends XenAPIObject { * @return value of the field */ public Map getBlobs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_blobs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringBlob(result); + return Types.toMapOfStringBlob(result); } /** @@ -588,15 +587,15 @@ public class Pool extends XenAPIObject { * @return value of the field */ public Set getTags(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_tags"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -605,15 +604,15 @@ public class Pool extends XenAPIObject { * @return value of the field */ public Map getGuiConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_gui_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -622,15 +621,15 @@ public class Pool extends XenAPIObject { * @return value of the field */ public String getWlbUrl(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_wlb_url"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -639,15 +638,15 @@ public class Pool extends XenAPIObject { * @return value of the field */ public String getWlbUsername(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_wlb_username"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -656,15 +655,15 @@ public class Pool extends XenAPIObject { * @return value of the field */ public Boolean getWlbEnabled(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_wlb_enabled"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -673,15 +672,15 @@ public class Pool extends XenAPIObject { * @return value of the field */ public Boolean getWlbVerifyCert(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_wlb_verify_cert"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -690,15 +689,15 @@ public class Pool extends XenAPIObject { * @return value of the field */ public Boolean getRedoLogEnabled(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_redo_log_enabled"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -707,15 +706,15 @@ public class Pool extends XenAPIObject { * @return value of the field */ public VDI getRedoLogVdi(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_redo_log_vdi"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVDI(result); + return Types.toVDI(result); } /** @@ -724,15 +723,15 @@ public class Pool extends XenAPIObject { * @return value of the field */ public String getVswitchController(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_vswitch_controller"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -741,15 +740,15 @@ public class Pool extends XenAPIObject { * @return value of the field */ public Map getRestrictions(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_restrictions"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -758,15 +757,15 @@ public class Pool extends XenAPIObject { * @return value of the field */ public Set getMetadataVDIs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_metadata_VDIs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVDI(result); + return Types.toSetOfVDI(result); } /** @@ -775,9 +774,9 @@ public class Pool extends XenAPIObject { * @param nameLabel New value to set */ public void setNameLabel(Connection c, String nameLabel) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.set_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(nameLabel)}; @@ -791,9 +790,9 @@ public class Pool extends XenAPIObject { * @param nameDescription New value to set */ public void setNameDescription(Connection c, String nameDescription) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.set_name_description"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(nameDescription)}; @@ -807,9 +806,9 @@ public class Pool extends XenAPIObject { * @param defaultSR New value to set */ public void setDefaultSR(Connection c, SR defaultSR) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.set_default_SR"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(defaultSR)}; @@ -823,9 +822,9 @@ public class Pool extends XenAPIObject { * @param suspendImageSR New value to set */ public void setSuspendImageSR(Connection c, SR suspendImageSR) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.set_suspend_image_SR"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(suspendImageSR)}; @@ -839,9 +838,9 @@ public class Pool extends XenAPIObject { * @param crashDumpSR New value to set */ public void setCrashDumpSR(Connection c, SR crashDumpSR) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.set_crash_dump_SR"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(crashDumpSR)}; @@ -855,9 +854,9 @@ public class Pool extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -872,9 +871,9 @@ public class Pool extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -888,9 +887,9 @@ public class Pool extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -904,9 +903,9 @@ public class Pool extends XenAPIObject { * @param haAllowOvercommit New value to set */ public void setHaAllowOvercommit(Connection c, Boolean haAllowOvercommit) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.set_ha_allow_overcommit"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(haAllowOvercommit)}; @@ -920,9 +919,9 @@ public class Pool extends XenAPIObject { * @param tags New value to set */ public void setTags(Connection c, Set tags) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.set_tags"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(tags)}; @@ -936,9 +935,9 @@ public class Pool extends XenAPIObject { * @param value New value to add */ public void addTags(Connection c, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.add_tags"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -952,9 +951,9 @@ public class Pool extends XenAPIObject { * @param value Value to remove */ public void removeTags(Connection c, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.remove_tags"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -968,9 +967,9 @@ public class Pool extends XenAPIObject { * @param guiConfig New value to set */ public void setGuiConfig(Connection c, Map guiConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.set_gui_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(guiConfig)}; @@ -985,9 +984,9 @@ public class Pool extends XenAPIObject { * @param value Value to add */ public void addToGuiConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.add_to_gui_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -1001,9 +1000,9 @@ public class Pool extends XenAPIObject { * @param key Key to remove */ public void removeFromGuiConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.remove_from_gui_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -1017,9 +1016,9 @@ public class Pool extends XenAPIObject { * @param wlbEnabled New value to set */ public void setWlbEnabled(Connection c, Boolean wlbEnabled) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.set_wlb_enabled"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(wlbEnabled)}; @@ -1033,9 +1032,9 @@ public class Pool extends XenAPIObject { * @param wlbVerifyCert New value to set */ public void setWlbVerifyCert(Connection c, Boolean wlbVerifyCert) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.set_wlb_verify_cert"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(wlbVerifyCert)}; @@ -1052,13 +1051,14 @@ public class Pool extends XenAPIObject { * @return Task */ public static Task joinAsync(Connection c, String masterAddress, String masterUsername, String masterPassword) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.JoiningHostCannotContainSharedSrs { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.JoiningHostCannotContainSharedSrs { String method_call = "Async.pool.join"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(masterAddress), Marshalling.toXMLRPC(masterUsername), Marshalling.toXMLRPC(masterPassword)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(masterAddress), Marshalling.toXMLRPC(masterUsername), + Marshalling.toXMLRPC(masterPassword)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -1072,13 +1072,14 @@ public class Pool extends XenAPIObject { * @param masterPassword The password for the master (for initial authentication) */ public static void join(Connection c, String masterAddress, String masterUsername, String masterPassword) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.JoiningHostCannotContainSharedSrs { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.JoiningHostCannotContainSharedSrs { String method_call = "pool.join"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(masterAddress), Marshalling.toXMLRPC(masterUsername), Marshalling.toXMLRPC(masterPassword)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(masterAddress), Marshalling.toXMLRPC(masterUsername), + Marshalling.toXMLRPC(masterPassword)}; Map response = c.dispatch(method_call, method_params); return; } @@ -1092,12 +1093,13 @@ public class Pool extends XenAPIObject { * @return Task */ public static Task joinForceAsync(Connection c, String masterAddress, String masterUsername, String masterPassword) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool.join_force"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(masterAddress), Marshalling.toXMLRPC(masterUsername), Marshalling.toXMLRPC(masterPassword)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(masterAddress), Marshalling.toXMLRPC(masterUsername), + Marshalling.toXMLRPC(masterPassword)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -1111,12 +1113,13 @@ public class Pool extends XenAPIObject { * @param masterPassword The password for the master (for initial authentication) */ public static void joinForce(Connection c, String masterAddress, String masterUsername, String masterPassword) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.join_force"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(masterAddress), Marshalling.toXMLRPC(masterUsername), Marshalling.toXMLRPC(masterPassword)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(masterAddress), Marshalling.toXMLRPC(masterUsername), + Marshalling.toXMLRPC(masterPassword)}; Map response = c.dispatch(method_call, method_params); return; } @@ -1128,9 +1131,9 @@ public class Pool extends XenAPIObject { * @return Task */ public static Task ejectAsync(Connection c, Host host) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool.eject"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host)}; @@ -1145,9 +1148,9 @@ public class Pool extends XenAPIObject { * @param host The host to eject */ public static void eject(Connection c, Host host) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.eject"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host)}; @@ -1160,9 +1163,9 @@ public class Pool extends XenAPIObject { * */ public static void emergencyTransitionToMaster(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.emergency_transition_to_master"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; @@ -1176,9 +1179,9 @@ public class Pool extends XenAPIObject { * @param masterAddress The hostname of the master */ public static void emergencyResetMaster(Connection c, String masterAddress) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.emergency_reset_master"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(masterAddress)}; @@ -1192,9 +1195,9 @@ public class Pool extends XenAPIObject { * @return Task */ public static Task recoverSlavesAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool.recover_slaves"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; @@ -1209,15 +1212,15 @@ public class Pool extends XenAPIObject { * @return list of hosts whose master address were succesfully reset */ public static Set recoverSlaves(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.recover_slaves"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfHost(result); + return Types.toSetOfHost(result); } /** @@ -1229,10 +1232,10 @@ public class Pool extends XenAPIObject { * @return Task */ public static Task createVLANAsync(Connection c, String device, Network network, Long VLAN) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VlanTagInvalid { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VlanTagInvalid { String method_call = "Async.pool.create_VLAN"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(device), Marshalling.toXMLRPC(network), Marshalling.toXMLRPC(VLAN)}; @@ -1250,16 +1253,16 @@ public class Pool extends XenAPIObject { * @return The references of the created PIF objects */ public static Set createVLAN(Connection c, String device, Network network, Long VLAN) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VlanTagInvalid { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VlanTagInvalid { String method_call = "pool.create_VLAN"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(device), Marshalling.toXMLRPC(network), Marshalling.toXMLRPC(VLAN)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfPIF(result); + return Types.toSetOfPIF(result); } /** @@ -1271,10 +1274,10 @@ public class Pool extends XenAPIObject { * @return Task */ public static Task createVLANFromPIFAsync(Connection c, PIF pif, Network network, Long VLAN) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VlanTagInvalid { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VlanTagInvalid { String method_call = "Async.pool.create_VLAN_from_PIF"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(pif), Marshalling.toXMLRPC(network), Marshalling.toXMLRPC(VLAN)}; @@ -1292,16 +1295,16 @@ public class Pool extends XenAPIObject { * @return The references of the created PIF objects */ public static Set createVLANFromPIF(Connection c, PIF pif, Network network, Long VLAN) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VlanTagInvalid { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VlanTagInvalid { String method_call = "pool.create_VLAN_from_PIF"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(pif), Marshalling.toXMLRPC(network), Marshalling.toXMLRPC(VLAN)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfPIF(result); + return Types.toSetOfPIF(result); } /** @@ -1312,9 +1315,9 @@ public class Pool extends XenAPIObject { * @return Task */ public static Task enableHaAsync(Connection c, Set heartbeatSrs, Map configuration) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool.enable_ha"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(heartbeatSrs), Marshalling.toXMLRPC(configuration)}; @@ -1330,9 +1333,9 @@ public class Pool extends XenAPIObject { * @param configuration Detailed HA configuration to apply */ public static void enableHa(Connection c, Set heartbeatSrs, Map configuration) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.enable_ha"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(heartbeatSrs), Marshalling.toXMLRPC(configuration)}; @@ -1346,9 +1349,9 @@ public class Pool extends XenAPIObject { * @return Task */ public static Task disableHaAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool.disable_ha"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; @@ -1362,9 +1365,9 @@ public class Pool extends XenAPIObject { * */ public static void disableHa(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.disable_ha"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; @@ -1378,9 +1381,9 @@ public class Pool extends XenAPIObject { * @return Task */ public static Task syncDatabaseAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool.sync_database"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; @@ -1394,9 +1397,9 @@ public class Pool extends XenAPIObject { * */ public static void syncDatabase(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.sync_database"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; @@ -1411,9 +1414,9 @@ public class Pool extends XenAPIObject { * @return Task */ public static Task designateNewMasterAsync(Connection c, Host host) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool.designate_new_master"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host)}; @@ -1428,9 +1431,9 @@ public class Pool extends XenAPIObject { * @param host The host who should become the new master */ public static void designateNewMaster(Connection c, Host host) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.designate_new_master"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host)}; @@ -1444,9 +1447,9 @@ public class Pool extends XenAPIObject { * @param seconds The number of seconds to block the restart thread for */ public static void haPreventRestartsFor(Connection c, Long seconds) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.ha_prevent_restarts_for"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(seconds)}; @@ -1461,15 +1464,15 @@ public class Pool extends XenAPIObject { * @return true if a failover plan exists for the supplied number of host failures */ public static Boolean haFailoverPlanExists(Connection c, Long n) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.ha_failover_plan_exists"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(n)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -1478,15 +1481,15 @@ public class Pool extends XenAPIObject { * @return maximum value for ha_host_failures_to_tolerate given current configuration */ public static Long haComputeMaxHostFailuresToTolerate(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.ha_compute_max_host_failures_to_tolerate"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -1496,15 +1499,15 @@ public class Pool extends XenAPIObject { * @return maximum value for ha_host_failures_to_tolerate given provided configuration */ public static Long haComputeHypotheticalMaxHostFailuresToTolerate(Connection c, Map configuration) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.ha_compute_hypothetical_max_host_failures_to_tolerate"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(configuration)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -1515,15 +1518,15 @@ public class Pool extends XenAPIObject { * @return VM failover plan: a map of VM to host to restart the host on */ public static Map> haComputeVmFailoverPlan(Connection c, Set failedHosts, Set failedVms) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.ha_compute_vm_failover_plan"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(failedHosts), Marshalling.toXMLRPC(failedVms)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfVMMapOfStringString(result); + return Types.toMapOfVMMapOfStringString(result); } /** @@ -1533,9 +1536,9 @@ public class Pool extends XenAPIObject { * @return Task */ public Task setHaHostFailuresToTolerateAsync(Connection c, Long value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool.set_ha_host_failures_to_tolerate"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1550,9 +1553,9 @@ public class Pool extends XenAPIObject { * @param value New number of host failures to consider */ public void setHaHostFailuresToTolerate(Connection c, Long value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.set_ha_host_failures_to_tolerate"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1569,12 +1572,13 @@ public class Pool extends XenAPIObject { * @return Task */ public Task createNewBlobAsync(Connection c, String name, String mimeType, Boolean _public) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool.create_new_blob"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType), Marshalling.toXMLRPC(_public)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType), + Marshalling.toXMLRPC(_public)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -1589,15 +1593,16 @@ public class Pool extends XenAPIObject { * @return The reference of the blob, needed for populating its data */ public Blob createNewBlob(Connection c, String name, String mimeType, Boolean _public) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.create_new_blob"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType), Marshalling.toXMLRPC(_public)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType), + Marshalling.toXMLRPC(_public)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBlob(result); + return Types.toBlob(result); } /** @@ -1608,12 +1613,13 @@ public class Pool extends XenAPIObject { * @param authType The type of authentication (e.g. AD for Active Directory) */ public void enableExternalAuth(Connection c, Map config, String serviceName, String authType) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.enable_external_auth"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(config), Marshalling.toXMLRPC(serviceName), Marshalling.toXMLRPC(authType)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(config), Marshalling.toXMLRPC(serviceName), + Marshalling.toXMLRPC(authType)}; Map response = c.dispatch(method_call, method_params); return; } @@ -1624,9 +1630,9 @@ public class Pool extends XenAPIObject { * @param config Optional parameters as a list of key-values containing the configuration data */ public void disableExternalAuth(Connection c, Map config) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.disable_external_auth"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(config)}; @@ -1639,9 +1645,9 @@ public class Pool extends XenAPIObject { * */ public void detectNonhomogeneousExternalAuth(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.detect_nonhomogeneous_external_auth"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1660,12 +1666,13 @@ public class Pool extends XenAPIObject { * @return Task */ public static Task initializeWlbAsync(Connection c, String wlbUrl, String wlbUsername, String wlbPassword, String xenserverUsername, String xenserverPassword) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool.initialize_wlb"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(wlbUrl), Marshalling.toXMLRPC(wlbUsername), Marshalling.toXMLRPC(wlbPassword), Marshalling.toXMLRPC(xenserverUsername), Marshalling.toXMLRPC(xenserverPassword)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(wlbUrl), Marshalling.toXMLRPC(wlbUsername), Marshalling.toXMLRPC(wlbPassword), + Marshalling.toXMLRPC(xenserverUsername), Marshalling.toXMLRPC(xenserverPassword)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -1681,12 +1688,13 @@ public class Pool extends XenAPIObject { * @param xenserverPassword The password used by the wlb server to authenticate with the xenserver */ public static void initializeWlb(Connection c, String wlbUrl, String wlbUsername, String wlbPassword, String xenserverUsername, String xenserverPassword) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.initialize_wlb"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(wlbUrl), Marshalling.toXMLRPC(wlbUsername), Marshalling.toXMLRPC(wlbPassword), Marshalling.toXMLRPC(xenserverUsername), Marshalling.toXMLRPC(xenserverPassword)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(wlbUrl), Marshalling.toXMLRPC(wlbUsername), Marshalling.toXMLRPC(wlbPassword), + Marshalling.toXMLRPC(xenserverUsername), Marshalling.toXMLRPC(xenserverPassword)}; Map response = c.dispatch(method_call, method_params); return; } @@ -1697,9 +1705,9 @@ public class Pool extends XenAPIObject { * @return Task */ public static Task deconfigureWlbAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool.deconfigure_wlb"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; @@ -1713,9 +1721,9 @@ public class Pool extends XenAPIObject { * */ public static void deconfigureWlb(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.deconfigure_wlb"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; @@ -1730,9 +1738,9 @@ public class Pool extends XenAPIObject { * @return Task */ public static Task sendWlbConfigurationAsync(Connection c, Map config) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool.send_wlb_configuration"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(config)}; @@ -1747,9 +1755,9 @@ public class Pool extends XenAPIObject { * @param config The configuration to use in optimizing this pool */ public static void sendWlbConfiguration(Connection c, Map config) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.send_wlb_configuration"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(config)}; @@ -1763,9 +1771,9 @@ public class Pool extends XenAPIObject { * @return Task */ public static Task retrieveWlbConfigurationAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool.retrieve_wlb_configuration"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; @@ -1780,15 +1788,15 @@ public class Pool extends XenAPIObject { * @return The configuration used in optimizing this pool */ public static Map retrieveWlbConfiguration(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.retrieve_wlb_configuration"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -1797,9 +1805,9 @@ public class Pool extends XenAPIObject { * @return Task */ public static Task retrieveWlbRecommendationsAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool.retrieve_wlb_recommendations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; @@ -1814,15 +1822,15 @@ public class Pool extends XenAPIObject { * @return The list of vm migration recommendations */ public static Map> retrieveWlbRecommendations(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.retrieve_wlb_recommendations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfVMSetOfString(result); + return Types.toMapOfVMSetOfString(result); } /** @@ -1834,9 +1842,9 @@ public class Pool extends XenAPIObject { * @return Task */ public static Task sendTestPostAsync(Connection c, String host, Long port, String body) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool.send_test_post"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(port), Marshalling.toXMLRPC(body)}; @@ -1854,15 +1862,15 @@ public class Pool extends XenAPIObject { * @return The response */ public static String sendTestPost(Connection c, String host, Long port, String body) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.send_test_post"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(port), Marshalling.toXMLRPC(body)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -1873,9 +1881,9 @@ public class Pool extends XenAPIObject { * @return Task */ public static Task certificateInstallAsync(Connection c, String name, String cert) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool.certificate_install"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(cert)}; @@ -1891,9 +1899,9 @@ public class Pool extends XenAPIObject { * @param cert The certificate */ public static void certificateInstall(Connection c, String name, String cert) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.certificate_install"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(cert)}; @@ -1908,9 +1916,9 @@ public class Pool extends XenAPIObject { * @return Task */ public static Task certificateUninstallAsync(Connection c, String name) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool.certificate_uninstall"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(name)}; @@ -1925,9 +1933,9 @@ public class Pool extends XenAPIObject { * @param name The certificate name */ public static void certificateUninstall(Connection c, String name) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.certificate_uninstall"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(name)}; @@ -1941,9 +1949,9 @@ public class Pool extends XenAPIObject { * @return Task */ public static Task certificateListAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool.certificate_list"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; @@ -1958,15 +1966,15 @@ public class Pool extends XenAPIObject { * @return All installed certificates */ public static Set certificateList(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.certificate_list"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -1977,9 +1985,9 @@ public class Pool extends XenAPIObject { * @return Task */ public static Task crlInstallAsync(Connection c, String name, String cert) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool.crl_install"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(cert)}; @@ -1995,9 +2003,9 @@ public class Pool extends XenAPIObject { * @param cert The CRL */ public static void crlInstall(Connection c, String name, String cert) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.crl_install"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(cert)}; @@ -2012,9 +2020,9 @@ public class Pool extends XenAPIObject { * @return Task */ public static Task crlUninstallAsync(Connection c, String name) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool.crl_uninstall"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(name)}; @@ -2029,9 +2037,9 @@ public class Pool extends XenAPIObject { * @param name The CRL name */ public static void crlUninstall(Connection c, String name) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.crl_uninstall"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(name)}; @@ -2045,9 +2053,9 @@ public class Pool extends XenAPIObject { * @return Task */ public static Task crlListAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool.crl_list"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; @@ -2062,15 +2070,15 @@ public class Pool extends XenAPIObject { * @return All installed CRLs */ public static Set crlList(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.crl_list"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -2079,9 +2087,9 @@ public class Pool extends XenAPIObject { * @return Task */ public static Task certificateSyncAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool.certificate_sync"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; @@ -2095,9 +2103,9 @@ public class Pool extends XenAPIObject { * */ public static void certificateSync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.certificate_sync"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; @@ -2112,9 +2120,9 @@ public class Pool extends XenAPIObject { * @return Task */ public static Task enableRedoLogAsync(Connection c, SR sr) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool.enable_redo_log"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(sr)}; @@ -2129,9 +2137,9 @@ public class Pool extends XenAPIObject { * @param sr SR to hold the redo log. */ public static void enableRedoLog(Connection c, SR sr) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.enable_redo_log"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(sr)}; @@ -2145,9 +2153,9 @@ public class Pool extends XenAPIObject { * @return Task */ public static Task disableRedoLogAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool.disable_redo_log"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; @@ -2161,9 +2169,9 @@ public class Pool extends XenAPIObject { * */ public static void disableRedoLog(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.disable_redo_log"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; @@ -2178,9 +2186,9 @@ public class Pool extends XenAPIObject { * @return Task */ public static Task setVswitchControllerAsync(Connection c, String address) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool.set_vswitch_controller"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(address)}; @@ -2195,9 +2203,9 @@ public class Pool extends XenAPIObject { * @param address IP address of the vswitch controller. */ public static void setVswitchController(Connection c, String address) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.set_vswitch_controller"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(address)}; @@ -2212,15 +2220,15 @@ public class Pool extends XenAPIObject { * @return An XMLRPC result */ public String testArchiveTarget(Connection c, Map config) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.test_archive_target"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(config)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -2229,9 +2237,9 @@ public class Pool extends XenAPIObject { * @return Task */ public Task enableLocalStorageCachingAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool.enable_local_storage_caching"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -2245,9 +2253,9 @@ public class Pool extends XenAPIObject { * */ public void enableLocalStorageCaching(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.enable_local_storage_caching"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -2261,9 +2269,9 @@ public class Pool extends XenAPIObject { * @return Task */ public Task disableLocalStorageCachingAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool.disable_local_storage_caching"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -2277,9 +2285,9 @@ public class Pool extends XenAPIObject { * */ public void disableLocalStorageCaching(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.disable_local_storage_caching"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -2293,15 +2301,15 @@ public class Pool extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfPool(result); + return Types.toSetOfPool(result); } /** @@ -2310,15 +2318,15 @@ public class Pool extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfPoolPoolRecord(result); + return Types.toMapOfPoolPoolRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/PoolPatch.java b/deps/XenServerJava/src/com/xensource/xenapi/PoolPatch.java index 750a9f3225c..7361bc7da0e 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/PoolPatch.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/PoolPatch.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class PoolPatch extends XenAPIObject { * For internal use only. */ PoolPatch(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class PoolPatch extends XenAPIObject { { if (obj != null && obj instanceof PoolPatch) { - PoolPatch other = (PoolPatch) obj; + PoolPatch other = (PoolPatch)obj; return other.ref.equals(this.ref); } else { @@ -115,8 +114,8 @@ public class PoolPatch extends XenAPIObject { /** * Convert a pool_patch.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("name_label", this.nameLabel == null ? "" : this.nameLabel); map.put("name_description", this.nameDescription == null ? "" : this.nameDescription); @@ -173,15 +172,15 @@ public class PoolPatch extends XenAPIObject { * @return all fields from the object */ public PoolPatch.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool_patch.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toPoolPatchRecord(result); + return Types.toPoolPatchRecord(result); } /** @@ -191,15 +190,15 @@ public class PoolPatch extends XenAPIObject { * @return reference to the object */ public static PoolPatch getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool_patch.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toPoolPatch(result); + return Types.toPoolPatch(result); } /** @@ -209,15 +208,15 @@ public class PoolPatch extends XenAPIObject { * @return references to objects with matching names */ public static Set getByNameLabel(Connection c, String label) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool_patch.get_by_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(label)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfPoolPatch(result); + return Types.toSetOfPoolPatch(result); } /** @@ -226,15 +225,15 @@ public class PoolPatch extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool_patch.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -243,15 +242,15 @@ public class PoolPatch extends XenAPIObject { * @return value of the field */ public String getNameLabel(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool_patch.get_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -260,15 +259,15 @@ public class PoolPatch extends XenAPIObject { * @return value of the field */ public String getNameDescription(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool_patch.get_name_description"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -277,15 +276,15 @@ public class PoolPatch extends XenAPIObject { * @return value of the field */ public String getVersion(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool_patch.get_version"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -294,15 +293,15 @@ public class PoolPatch extends XenAPIObject { * @return value of the field */ public Long getSize(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool_patch.get_size"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -311,15 +310,15 @@ public class PoolPatch extends XenAPIObject { * @return value of the field */ public Boolean getPoolApplied(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool_patch.get_pool_applied"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -328,15 +327,15 @@ public class PoolPatch extends XenAPIObject { * @return value of the field */ public Set getHostPatches(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool_patch.get_host_patches"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfHostPatch(result); + return Types.toSetOfHostPatch(result); } /** @@ -345,15 +344,15 @@ public class PoolPatch extends XenAPIObject { * @return value of the field */ public Set getAfterApplyGuidance(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool_patch.get_after_apply_guidance"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfAfterApplyGuidance(result); + return Types.toSetOfAfterApplyGuidance(result); } /** @@ -362,15 +361,15 @@ public class PoolPatch extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool_patch.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -379,9 +378,9 @@ public class PoolPatch extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool_patch.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -396,9 +395,9 @@ public class PoolPatch extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool_patch.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -412,9 +411,9 @@ public class PoolPatch extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool_patch.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -429,9 +428,9 @@ public class PoolPatch extends XenAPIObject { * @return Task */ public Task applyAsync(Connection c, Host host) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool_patch.apply"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(host)}; @@ -447,15 +446,15 @@ public class PoolPatch extends XenAPIObject { * @return the output of the patch application process */ public String apply(Connection c, Host host) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool_patch.apply"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(host)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -464,9 +463,9 @@ public class PoolPatch extends XenAPIObject { * @return Task */ public Task poolApplyAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool_patch.pool_apply"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -480,9 +479,9 @@ public class PoolPatch extends XenAPIObject { * */ public void poolApply(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool_patch.pool_apply"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -497,9 +496,9 @@ public class PoolPatch extends XenAPIObject { * @return Task */ public Task precheckAsync(Connection c, Host host) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool_patch.precheck"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(host)}; @@ -515,15 +514,15 @@ public class PoolPatch extends XenAPIObject { * @return the output of the patch prechecks */ public String precheck(Connection c, Host host) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool_patch.precheck"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(host)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -532,9 +531,9 @@ public class PoolPatch extends XenAPIObject { * @return Task */ public Task cleanAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool_patch.clean"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -548,9 +547,9 @@ public class PoolPatch extends XenAPIObject { * */ public void clean(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool_patch.clean"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -564,9 +563,9 @@ public class PoolPatch extends XenAPIObject { * @return Task */ public Task poolCleanAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool_patch.pool_clean"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -580,9 +579,9 @@ public class PoolPatch extends XenAPIObject { * */ public void poolClean(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool_patch.pool_clean"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -596,9 +595,9 @@ public class PoolPatch extends XenAPIObject { * @return Task */ public Task destroyAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool_patch.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -612,9 +611,9 @@ public class PoolPatch extends XenAPIObject { * */ public void destroy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool_patch.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -629,9 +628,9 @@ public class PoolPatch extends XenAPIObject { * @return Task */ public Task cleanOnHostAsync(Connection c, Host host) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.pool_patch.clean_on_host"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(host)}; @@ -646,9 +645,9 @@ public class PoolPatch extends XenAPIObject { * @param host The host on which to clean the patch */ public void cleanOnHost(Connection c, Host host) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool_patch.clean_on_host"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(host)}; @@ -662,15 +661,15 @@ public class PoolPatch extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool_patch.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfPoolPatch(result); + return Types.toSetOfPoolPatch(result); } /** @@ -679,15 +678,15 @@ public class PoolPatch extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "pool_patch.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfPoolPatchPoolPatchRecord(result); + return Types.toMapOfPoolPatchPoolPatchRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Role.java b/deps/XenServerJava/src/com/xensource/xenapi/Role.java index f8dea77010b..5808b13cdb2 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Role.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Role.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class Role extends XenAPIObject { * For internal use only. */ Role(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class Role extends XenAPIObject { { if (obj != null && obj instanceof Role) { - Role other = (Role) obj; + Role other = (Role)obj; return other.ref.equals(this.ref); } else { @@ -110,8 +109,8 @@ public class Role extends XenAPIObject { /** * Convert a role.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("name_label", this.nameLabel == null ? "" : this.nameLabel); map.put("name_description", this.nameDescription == null ? "" : this.nameDescription); @@ -143,15 +142,15 @@ public class Role extends XenAPIObject { * @return all fields from the object */ public Role.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "role.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toRoleRecord(result); + return Types.toRoleRecord(result); } /** @@ -161,15 +160,15 @@ public class Role extends XenAPIObject { * @return reference to the object */ public static Role getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "role.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toRole(result); + return Types.toRole(result); } /** @@ -179,15 +178,15 @@ public class Role extends XenAPIObject { * @return references to objects with matching names */ public static Set getByNameLabel(Connection c, String label) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "role.get_by_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(label)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfRole(result); + return Types.toSetOfRole(result); } /** @@ -196,15 +195,15 @@ public class Role extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "role.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -213,15 +212,15 @@ public class Role extends XenAPIObject { * @return value of the field */ public String getNameLabel(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "role.get_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -230,15 +229,15 @@ public class Role extends XenAPIObject { * @return value of the field */ public String getNameDescription(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "role.get_name_description"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -247,15 +246,15 @@ public class Role extends XenAPIObject { * @return value of the field */ public Set getSubroles(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "role.get_subroles"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfRole(result); + return Types.toSetOfRole(result); } /** @@ -264,15 +263,15 @@ public class Role extends XenAPIObject { * @return a list of permissions */ public Set getPermissions(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "role.get_permissions"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfRole(result); + return Types.toSetOfRole(result); } /** @@ -281,15 +280,15 @@ public class Role extends XenAPIObject { * @return a list of permission names */ public Set getPermissionsNameLabel(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "role.get_permissions_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -298,15 +297,15 @@ public class Role extends XenAPIObject { * @return a list of references to roles */ public Set getByPermission(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "role.get_by_permission"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfRole(result); + return Types.toSetOfRole(result); } /** @@ -316,15 +315,15 @@ public class Role extends XenAPIObject { * @return a list of references to roles */ public static Set getByPermissionNameLabel(Connection c, String label) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "role.get_by_permission_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(label)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfRole(result); + return Types.toSetOfRole(result); } /** @@ -333,15 +332,15 @@ public class Role extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "role.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfRole(result); + return Types.toSetOfRole(result); } /** @@ -350,15 +349,15 @@ public class Role extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "role.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfRoleRoleRecord(result); + return Types.toMapOfRoleRoleRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/SM.java b/deps/XenServerJava/src/com/xensource/xenapi/SM.java index 9c7341ceb10..0ec362694b6 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/SM.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/SM.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class SM extends XenAPIObject { * For internal use only. */ SM(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class SM extends XenAPIObject { { if (obj != null && obj instanceof SM) { - SM other = (SM) obj; + SM other = (SM)obj; return other.ref.equals(this.ref); } else { @@ -118,8 +117,8 @@ public class SM extends XenAPIObject { /** * Convert a SM.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("name_label", this.nameLabel == null ? "" : this.nameLabel); map.put("name_description", this.nameDescription == null ? "" : this.nameDescription); @@ -191,15 +190,15 @@ public class SM extends XenAPIObject { * @return all fields from the object */ public SM.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SM.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSMRecord(result); + return Types.toSMRecord(result); } /** @@ -209,15 +208,15 @@ public class SM extends XenAPIObject { * @return reference to the object */ public static SM getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SM.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSM(result); + return Types.toSM(result); } /** @@ -227,15 +226,15 @@ public class SM extends XenAPIObject { * @return references to objects with matching names */ public static Set getByNameLabel(Connection c, String label) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SM.get_by_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(label)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfSM(result); + return Types.toSetOfSM(result); } /** @@ -244,15 +243,15 @@ public class SM extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SM.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -261,15 +260,15 @@ public class SM extends XenAPIObject { * @return value of the field */ public String getNameLabel(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SM.get_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -278,15 +277,15 @@ public class SM extends XenAPIObject { * @return value of the field */ public String getNameDescription(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SM.get_name_description"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -295,15 +294,15 @@ public class SM extends XenAPIObject { * @return value of the field */ public String getType(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SM.get_type"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -312,15 +311,15 @@ public class SM extends XenAPIObject { * @return value of the field */ public String getVendor(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SM.get_vendor"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -329,15 +328,15 @@ public class SM extends XenAPIObject { * @return value of the field */ public String getCopyright(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SM.get_copyright"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -346,15 +345,15 @@ public class SM extends XenAPIObject { * @return value of the field */ public String getVersion(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SM.get_version"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -363,15 +362,15 @@ public class SM extends XenAPIObject { * @return value of the field */ public String getRequiredApiVersion(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SM.get_required_api_version"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -380,15 +379,15 @@ public class SM extends XenAPIObject { * @return value of the field */ public Map getConfiguration(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SM.get_configuration"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -397,15 +396,15 @@ public class SM extends XenAPIObject { * @return value of the field */ public Set getCapabilities(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SM.get_capabilities"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -414,15 +413,15 @@ public class SM extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SM.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -431,15 +430,15 @@ public class SM extends XenAPIObject { * @return value of the field */ public String getDriverFilename(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SM.get_driver_filename"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -448,9 +447,9 @@ public class SM extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SM.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -465,9 +464,9 @@ public class SM extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SM.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -481,9 +480,9 @@ public class SM extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SM.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -497,15 +496,15 @@ public class SM extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SM.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfSM(result); + return Types.toSetOfSM(result); } /** @@ -514,15 +513,15 @@ public class SM extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SM.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfSMSMRecord(result); + return Types.toMapOfSMSMRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/SR.java b/deps/XenServerJava/src/com/xensource/xenapi/SR.java index 72314032506..db6770fbe8f 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/SR.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/SR.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class SR extends XenAPIObject { * For internal use only. */ SR(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class SR extends XenAPIObject { { if (obj != null && obj instanceof SR) { - SR other = (SR) obj; + SR other = (SR)obj; return other.ref.equals(this.ref); } else { @@ -125,8 +124,8 @@ public class SR extends XenAPIObject { /** * Convert a SR.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("name_label", this.nameLabel == null ? "" : this.nameLabel); map.put("name_description", this.nameDescription == null ? "" : this.nameDescription); @@ -233,15 +232,15 @@ public class SR extends XenAPIObject { * @return all fields from the object */ public SR.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSRRecord(result); + return Types.toSRRecord(result); } /** @@ -251,15 +250,15 @@ public class SR extends XenAPIObject { * @return reference to the object */ public static SR getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSR(result); + return Types.toSR(result); } /** @@ -269,15 +268,15 @@ public class SR extends XenAPIObject { * @return references to objects with matching names */ public static Set getByNameLabel(Connection c, String label) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.get_by_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(label)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfSR(result); + return Types.toSetOfSR(result); } /** @@ -286,15 +285,15 @@ public class SR extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -303,15 +302,15 @@ public class SR extends XenAPIObject { * @return value of the field */ public String getNameLabel(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.get_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -320,15 +319,15 @@ public class SR extends XenAPIObject { * @return value of the field */ public String getNameDescription(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.get_name_description"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -337,15 +336,15 @@ public class SR extends XenAPIObject { * @return value of the field */ public Set getAllowedOperations(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.get_allowed_operations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfStorageOperations(result); + return Types.toSetOfStorageOperations(result); } /** @@ -354,15 +353,15 @@ public class SR extends XenAPIObject { * @return value of the field */ public Map getCurrentOperations(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.get_current_operations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringStorageOperations(result); + return Types.toMapOfStringStorageOperations(result); } /** @@ -371,15 +370,15 @@ public class SR extends XenAPIObject { * @return value of the field */ public Set getVDIs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.get_VDIs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVDI(result); + return Types.toSetOfVDI(result); } /** @@ -388,15 +387,15 @@ public class SR extends XenAPIObject { * @return value of the field */ public Set getPBDs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.get_PBDs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfPBD(result); + return Types.toSetOfPBD(result); } /** @@ -405,15 +404,15 @@ public class SR extends XenAPIObject { * @return value of the field */ public Long getVirtualAllocation(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.get_virtual_allocation"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -422,15 +421,15 @@ public class SR extends XenAPIObject { * @return value of the field */ public Long getPhysicalUtilisation(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.get_physical_utilisation"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -439,15 +438,15 @@ public class SR extends XenAPIObject { * @return value of the field */ public Long getPhysicalSize(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.get_physical_size"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -456,15 +455,15 @@ public class SR extends XenAPIObject { * @return value of the field */ public String getType(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.get_type"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -473,15 +472,15 @@ public class SR extends XenAPIObject { * @return value of the field */ public String getContentType(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.get_content_type"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -490,15 +489,15 @@ public class SR extends XenAPIObject { * @return value of the field */ public Boolean getShared(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.get_shared"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -507,15 +506,15 @@ public class SR extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -524,15 +523,15 @@ public class SR extends XenAPIObject { * @return value of the field */ public Set getTags(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.get_tags"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -541,15 +540,15 @@ public class SR extends XenAPIObject { * @return value of the field */ public Map getSmConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.get_sm_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -558,15 +557,15 @@ public class SR extends XenAPIObject { * @return value of the field */ public Map getBlobs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.get_blobs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringBlob(result); + return Types.toMapOfStringBlob(result); } /** @@ -575,15 +574,15 @@ public class SR extends XenAPIObject { * @return value of the field */ public Boolean getLocalCacheEnabled(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.get_local_cache_enabled"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -592,15 +591,15 @@ public class SR extends XenAPIObject { * @return value of the field */ public DRTask getIntroducedBy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.get_introduced_by"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDRTask(result); + return Types.toDRTask(result); } /** @@ -609,9 +608,9 @@ public class SR extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -626,9 +625,9 @@ public class SR extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -642,9 +641,9 @@ public class SR extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -658,9 +657,9 @@ public class SR extends XenAPIObject { * @param tags New value to set */ public void setTags(Connection c, Set tags) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.set_tags"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(tags)}; @@ -674,9 +673,9 @@ public class SR extends XenAPIObject { * @param value New value to add */ public void addTags(Connection c, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.add_tags"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -690,9 +689,9 @@ public class SR extends XenAPIObject { * @param value Value to remove */ public void removeTags(Connection c, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.remove_tags"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -706,9 +705,9 @@ public class SR extends XenAPIObject { * @param smConfig New value to set */ public void setSmConfig(Connection c, Map smConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.set_sm_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(smConfig)}; @@ -723,9 +722,9 @@ public class SR extends XenAPIObject { * @param value Value to add */ public void addToSmConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.add_to_sm_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -739,9 +738,9 @@ public class SR extends XenAPIObject { * @param key Key to remove */ public void removeFromSmConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.remove_from_sm_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -763,15 +762,16 @@ public class SR extends XenAPIObject { * @param smConfig Storage backend specific configuration options * @return Task */ - public static Task createAsync(Connection c, Host host, Map deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, String contentType, Boolean shared, Map smConfig) throws - BadServerResponse, - VersionException, - XenAPIException, - XmlRpcException, - Types.SrUnknownDriver { + public static Task createAsync(Connection c, Host host, Map deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, + String contentType, Boolean shared, Map smConfig) throws + BadServerResponse, + VersionException, + XenAPIException, + XmlRpcException, + Types.SrUnknownDriver { - if(c.rioConnection){ - if (smConfig.isEmpty()){ + if (c.rioConnection) { + if (smConfig.isEmpty()) { return rioCreateAsync(c, host, deviceConfig, physicalSize, nameLabel, nameDescription, type, contentType, shared); } else { throw new Types.VersionException("smConfig parameter must be empty map for Rio (legacy XenServer) host"); @@ -781,29 +781,33 @@ public class SR extends XenAPIObject { } } - - - private static Task rioCreateAsync(Connection c, Host host, Map deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, String contentType, Boolean shared) throws - BadServerResponse, - XmlRpcException, - XenAPIException, - Types.SrUnknownDriver { + private static Task rioCreateAsync(Connection c, Host host, Map deviceConfig, Long physicalSize, String nameLabel, String nameDescription, + String type, String contentType, Boolean shared) throws + BadServerResponse, + XmlRpcException, + XenAPIException, + Types.SrUnknownDriver { String method_call = "Async.SR.create"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(physicalSize), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType), Marshalling.toXMLRPC(shared)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(physicalSize), + Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType), + Marshalling.toXMLRPC(shared)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); } - private static Task miamiCreateAsync(Connection c, Host host, Map deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, String contentType, Boolean shared, Map smConfig) throws - BadServerResponse, - XmlRpcException, - XenAPIException, - Types.SrUnknownDriver { + private static Task miamiCreateAsync(Connection c, Host host, Map deviceConfig, Long physicalSize, String nameLabel, String nameDescription, + String type, String contentType, Boolean shared, Map smConfig) throws + BadServerResponse, + XmlRpcException, + XenAPIException, + Types.SrUnknownDriver { String method_call = "Async.SR.create"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(physicalSize), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType), Marshalling.toXMLRPC(shared), Marshalling.toXMLRPC(smConfig)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(physicalSize), + Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType), + Marshalling.toXMLRPC(shared), Marshalling.toXMLRPC(smConfig)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -823,15 +827,16 @@ public class SR extends XenAPIObject { * @param smConfig Storage backend specific configuration options * @return The reference of the newly created Storage Repository. */ - public static SR create(Connection c, Host host, Map deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, String contentType, Boolean shared, Map smConfig) throws - BadServerResponse, - VersionException, - XenAPIException, - XmlRpcException, - Types.SrUnknownDriver { + public static SR create(Connection c, Host host, Map deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, + String contentType, Boolean shared, Map smConfig) throws + BadServerResponse, + VersionException, + XenAPIException, + XmlRpcException, + Types.SrUnknownDriver { - if(c.rioConnection){ - if (smConfig.isEmpty()){ + if (c.rioConnection) { + if (smConfig.isEmpty()) { return rioCreate(c, host, deviceConfig, physicalSize, nameLabel, nameDescription, type, contentType, shared); } else { throw new Types.VersionException("smConfig parameter must be empty map for Rio (legacy XenServer) host"); @@ -841,32 +846,36 @@ public class SR extends XenAPIObject { } } - - - private static SR rioCreate(Connection c, Host host, Map deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, String contentType, Boolean shared) throws - BadServerResponse, - XmlRpcException, - XenAPIException, - Types.SrUnknownDriver { + private static SR rioCreate(Connection c, Host host, Map deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, + String contentType, Boolean shared) throws + BadServerResponse, + XmlRpcException, + XenAPIException, + Types.SrUnknownDriver { String method_call = "SR.create"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(physicalSize), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType), Marshalling.toXMLRPC(shared)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(physicalSize), + Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType), + Marshalling.toXMLRPC(shared)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSR(result); + return Types.toSR(result); } - private static SR miamiCreate(Connection c, Host host, Map deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, String contentType, Boolean shared, Map smConfig) throws - BadServerResponse, - XmlRpcException, - XenAPIException, - Types.SrUnknownDriver { + private static SR miamiCreate(Connection c, Host host, Map deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, + String contentType, Boolean shared, Map smConfig) throws + BadServerResponse, + XmlRpcException, + XenAPIException, + Types.SrUnknownDriver { String method_call = "SR.create"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(physicalSize), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType), Marshalling.toXMLRPC(shared), Marshalling.toXMLRPC(smConfig)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(physicalSize), + Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType), + Marshalling.toXMLRPC(shared), Marshalling.toXMLRPC(smConfig)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSR(result); + return Types.toSR(result); } /** @@ -881,14 +890,15 @@ public class SR extends XenAPIObject { * @param smConfig Storage backend specific configuration options * @return Task */ - public static Task introduceAsync(Connection c, String uuid, String nameLabel, String nameDescription, String type, String contentType, Boolean shared, Map smConfig) throws - BadServerResponse, - VersionException, - XenAPIException, - XmlRpcException { + public static Task introduceAsync(Connection c, String uuid, String nameLabel, String nameDescription, String type, String contentType, Boolean shared, + Map smConfig) throws + BadServerResponse, + VersionException, + XenAPIException, + XmlRpcException { - if(c.rioConnection){ - if (smConfig.isEmpty()){ + if (c.rioConnection) { + if (smConfig.isEmpty()) { return rioIntroduceAsync(c, uuid, nameLabel, nameDescription, type, contentType, shared); } else { throw new Types.VersionException("smConfig parameter must be empty map for Rio (legacy XenServer) host"); @@ -898,27 +908,28 @@ public class SR extends XenAPIObject { } } - - private static Task rioIntroduceAsync(Connection c, String uuid, String nameLabel, String nameDescription, String type, String contentType, Boolean shared) throws - BadServerResponse, - XmlRpcException, - XenAPIException { + BadServerResponse, + XmlRpcException, + XenAPIException { String method_call = "Async.SR.introduce"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType), Marshalling.toXMLRPC(shared)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), + Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType), Marshalling.toXMLRPC(shared)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); } - private static Task miamiIntroduceAsync(Connection c, String uuid, String nameLabel, String nameDescription, String type, String contentType, Boolean shared, Map smConfig) throws - BadServerResponse, - XmlRpcException, - XenAPIException { + private static Task miamiIntroduceAsync(Connection c, String uuid, String nameLabel, String nameDescription, String type, String contentType, Boolean shared, + Map smConfig) throws + BadServerResponse, + XmlRpcException, + XenAPIException { String method_call = "Async.SR.introduce"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType), Marshalling.toXMLRPC(shared), Marshalling.toXMLRPC(smConfig)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), + Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType), Marshalling.toXMLRPC(shared), Marshalling.toXMLRPC(smConfig)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -936,14 +947,15 @@ public class SR extends XenAPIObject { * @param smConfig Storage backend specific configuration options * @return The reference of the newly introduced Storage Repository. */ - public static SR introduce(Connection c, String uuid, String nameLabel, String nameDescription, String type, String contentType, Boolean shared, Map smConfig) throws - BadServerResponse, - VersionException, - XenAPIException, - XmlRpcException { + public static SR introduce(Connection c, String uuid, String nameLabel, String nameDescription, String type, String contentType, Boolean shared, + Map smConfig) throws + BadServerResponse, + VersionException, + XenAPIException, + XmlRpcException { - if(c.rioConnection){ - if (smConfig.isEmpty()){ + if (c.rioConnection) { + if (smConfig.isEmpty()) { return rioIntroduce(c, uuid, nameLabel, nameDescription, type, contentType, shared); } else { throw new Types.VersionException("smConfig parameter must be empty map for Rio (legacy XenServer) host"); @@ -953,30 +965,31 @@ public class SR extends XenAPIObject { } } - - private static SR rioIntroduce(Connection c, String uuid, String nameLabel, String nameDescription, String type, String contentType, Boolean shared) throws - BadServerResponse, - XmlRpcException, - XenAPIException { + BadServerResponse, + XmlRpcException, + XenAPIException { String method_call = "SR.introduce"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType), Marshalling.toXMLRPC(shared)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), + Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType), Marshalling.toXMLRPC(shared)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSR(result); + return Types.toSR(result); } - private static SR miamiIntroduce(Connection c, String uuid, String nameLabel, String nameDescription, String type, String contentType, Boolean shared, Map smConfig) throws - BadServerResponse, - XmlRpcException, - XenAPIException { + private static SR miamiIntroduce(Connection c, String uuid, String nameLabel, String nameDescription, String type, String contentType, Boolean shared, + Map smConfig) throws + BadServerResponse, + XmlRpcException, + XenAPIException { String method_call = "SR.introduce"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType), Marshalling.toXMLRPC(shared), Marshalling.toXMLRPC(smConfig)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), + Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType), Marshalling.toXMLRPC(shared), Marshalling.toXMLRPC(smConfig)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSR(result); + return Types.toSR(result); } /** @@ -993,14 +1006,16 @@ public class SR extends XenAPIObject { * @param smConfig Storage backend specific configuration options * @return Task */ - @Deprecated public static Task makeAsync(Connection c, Host host, Map deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, String contentType, Map smConfig) throws - BadServerResponse, - VersionException, - XenAPIException, - XmlRpcException { + @Deprecated + public static Task makeAsync(Connection c, Host host, Map deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, + String contentType, Map smConfig) throws + BadServerResponse, + VersionException, + XenAPIException, + XmlRpcException { - if(c.rioConnection){ - if (smConfig.isEmpty()){ + if (c.rioConnection) { + if (smConfig.isEmpty()) { return rioMakeAsync(c, host, deviceConfig, physicalSize, nameLabel, nameDescription, type, contentType); } else { throw new Types.VersionException("smConfig parameter must be empty map for Rio (legacy XenServer) host"); @@ -1010,27 +1025,32 @@ public class SR extends XenAPIObject { } } - - - @Deprecated private static Task rioMakeAsync(Connection c, Host host, Map deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, String contentType) throws - BadServerResponse, - XmlRpcException, - XenAPIException { + @Deprecated + private static Task rioMakeAsync(Connection c, Host host, Map deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, + String contentType) throws + BadServerResponse, + XmlRpcException, + XenAPIException { String method_call = "Async.SR.make"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(physicalSize), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(physicalSize), + Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); } - @Deprecated private static Task miamiMakeAsync(Connection c, Host host, Map deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, String contentType, Map smConfig) throws - BadServerResponse, - XmlRpcException, - XenAPIException { + @Deprecated + private static Task miamiMakeAsync(Connection c, Host host, Map deviceConfig, Long physicalSize, String nameLabel, String nameDescription, + String type, String contentType, Map smConfig) throws + BadServerResponse, + XmlRpcException, + XenAPIException { String method_call = "Async.SR.make"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(physicalSize), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType), Marshalling.toXMLRPC(smConfig)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(physicalSize), + Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType), + Marshalling.toXMLRPC(smConfig)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -1050,14 +1070,16 @@ public class SR extends XenAPIObject { * @param smConfig Storage backend specific configuration options * @return The uuid of the newly created Storage Repository. */ - @Deprecated public static String make(Connection c, Host host, Map deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, String contentType, Map smConfig) throws - BadServerResponse, - VersionException, - XenAPIException, - XmlRpcException { + @Deprecated + public static String make(Connection c, Host host, Map deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, + String contentType, Map smConfig) throws + BadServerResponse, + VersionException, + XenAPIException, + XmlRpcException { - if(c.rioConnection){ - if (smConfig.isEmpty()){ + if (c.rioConnection) { + if (smConfig.isEmpty()) { return rioMake(c, host, deviceConfig, physicalSize, nameLabel, nameDescription, type, contentType); } else { throw new Types.VersionException("smConfig parameter must be empty map for Rio (legacy XenServer) host"); @@ -1067,30 +1089,35 @@ public class SR extends XenAPIObject { } } - - - @Deprecated private static String rioMake(Connection c, Host host, Map deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, String contentType) throws - BadServerResponse, - XmlRpcException, - XenAPIException { + @Deprecated + private static String rioMake(Connection c, Host host, Map deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, + String contentType) throws + BadServerResponse, + XmlRpcException, + XenAPIException { String method_call = "SR.make"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(physicalSize), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(physicalSize), + Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } - @Deprecated private static String miamiMake(Connection c, Host host, Map deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, String contentType, Map smConfig) throws - BadServerResponse, - XmlRpcException, - XenAPIException { + @Deprecated + private static String miamiMake(Connection c, Host host, Map deviceConfig, Long physicalSize, String nameLabel, String nameDescription, String type, + String contentType, Map smConfig) throws + BadServerResponse, + XmlRpcException, + XenAPIException { String method_call = "SR.make"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(physicalSize), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType), Marshalling.toXMLRPC(smConfig)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(physicalSize), + Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(contentType), + Marshalling.toXMLRPC(smConfig)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -1099,10 +1126,10 @@ public class SR extends XenAPIObject { * @return Task */ public Task destroyAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.SrHasPbd { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.SrHasPbd { String method_call = "Async.SR.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1116,10 +1143,10 @@ public class SR extends XenAPIObject { * */ public void destroy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.SrHasPbd { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.SrHasPbd { String method_call = "SR.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1133,10 +1160,10 @@ public class SR extends XenAPIObject { * @return Task */ public Task forgetAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.SrHasPbd { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.SrHasPbd { String method_call = "Async.SR.forget"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1150,10 +1177,10 @@ public class SR extends XenAPIObject { * */ public void forget(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.SrHasPbd { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.SrHasPbd { String method_call = "SR.forget"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1167,9 +1194,9 @@ public class SR extends XenAPIObject { * @return Task */ public Task updateAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.SR.update"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1183,9 +1210,9 @@ public class SR extends XenAPIObject { * */ public void update(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.update"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1199,15 +1226,15 @@ public class SR extends XenAPIObject { * @return the supported SR types */ public static Set getSupportedTypes(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.get_supported_types"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -1216,9 +1243,9 @@ public class SR extends XenAPIObject { * @return Task */ public Task scanAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.SR.scan"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1232,9 +1259,9 @@ public class SR extends XenAPIObject { * */ public void scan(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.scan"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1252,12 +1279,13 @@ public class SR extends XenAPIObject { * @return Task */ public static Task probeAsync(Connection c, Host host, Map deviceConfig, String type, Map smConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.SR.probe"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(smConfig)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(type), + Marshalling.toXMLRPC(smConfig)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -1273,15 +1301,16 @@ public class SR extends XenAPIObject { * @return An XML fragment containing the scan results. These are specific to the scan being performed, and the backend. */ public static String probe(Connection c, Host host, Map deviceConfig, String type, Map smConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.probe"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(smConfig)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(type), + Marshalling.toXMLRPC(smConfig)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -1291,9 +1320,9 @@ public class SR extends XenAPIObject { * @return Task */ public Task setSharedAsync(Connection c, Boolean value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.SR.set_shared"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1308,9 +1337,9 @@ public class SR extends XenAPIObject { * @param value True if the SR is shared */ public void setShared(Connection c, Boolean value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.set_shared"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1325,9 +1354,9 @@ public class SR extends XenAPIObject { * @return Task */ public Task setNameLabelAsync(Connection c, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.SR.set_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1342,9 +1371,9 @@ public class SR extends XenAPIObject { * @param value The name label for the SR */ public void setNameLabel(Connection c, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.set_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1359,9 +1388,9 @@ public class SR extends XenAPIObject { * @return Task */ public Task setNameDescriptionAsync(Connection c, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.SR.set_name_description"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1376,9 +1405,9 @@ public class SR extends XenAPIObject { * @param value The name description for the SR */ public void setNameDescription(Connection c, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.set_name_description"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1395,12 +1424,13 @@ public class SR extends XenAPIObject { * @return Task */ public Task createNewBlobAsync(Connection c, String name, String mimeType, Boolean _public) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.SR.create_new_blob"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType), Marshalling.toXMLRPC(_public)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType), + Marshalling.toXMLRPC(_public)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -1415,15 +1445,16 @@ public class SR extends XenAPIObject { * @return The reference of the blob, needed for populating its data */ public Blob createNewBlob(Connection c, String name, String mimeType, Boolean _public) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.create_new_blob"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType), Marshalling.toXMLRPC(_public)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType), + Marshalling.toXMLRPC(_public)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBlob(result); + return Types.toBlob(result); } /** @@ -1432,9 +1463,9 @@ public class SR extends XenAPIObject { * @param value The new value of the SR's physical_size */ public void setPhysicalSize(Connection c, Long value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.set_physical_size"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1448,9 +1479,9 @@ public class SR extends XenAPIObject { * @param value The new value of the SR's virtual_allocation */ public void setVirtualAllocation(Connection c, Long value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.set_virtual_allocation"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1464,9 +1495,9 @@ public class SR extends XenAPIObject { * @param value The new value of the SR's physical utilisation */ public void setPhysicalUtilisation(Connection c, Long value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.set_physical_utilisation"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1480,9 +1511,9 @@ public class SR extends XenAPIObject { * @return Task */ public Task assertCanHostHaStatefileAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.SR.assert_can_host_ha_statefile"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1496,9 +1527,9 @@ public class SR extends XenAPIObject { * */ public void assertCanHostHaStatefile(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.assert_can_host_ha_statefile"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1512,9 +1543,9 @@ public class SR extends XenAPIObject { * @return Task */ public Task assertSupportsDatabaseReplicationAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.SR.assert_supports_database_replication"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1528,9 +1559,9 @@ public class SR extends XenAPIObject { * */ public void assertSupportsDatabaseReplication(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.assert_supports_database_replication"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1544,9 +1575,9 @@ public class SR extends XenAPIObject { * @return Task */ public Task enableDatabaseReplicationAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.SR.enable_database_replication"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1560,9 +1591,9 @@ public class SR extends XenAPIObject { * */ public void enableDatabaseReplication(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.enable_database_replication"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1576,9 +1607,9 @@ public class SR extends XenAPIObject { * @return Task */ public Task disableDatabaseReplicationAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.SR.disable_database_replication"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1592,9 +1623,9 @@ public class SR extends XenAPIObject { * */ public void disableDatabaseReplication(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.disable_database_replication"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1608,15 +1639,15 @@ public class SR extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfSR(result); + return Types.toSetOfSR(result); } /** @@ -1625,15 +1656,15 @@ public class SR extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "SR.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfSRSRRecord(result); + return Types.toMapOfSRSRRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Secret.java b/deps/XenServerJava/src/com/xensource/xenapi/Secret.java index a9f8eddc847..870725fda50 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Secret.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Secret.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class Secret extends XenAPIObject { * For internal use only. */ Secret(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class Secret extends XenAPIObject { { if (obj != null && obj instanceof Secret) { - Secret other = (Secret) obj; + Secret other = (Secret)obj; return other.ref.equals(this.ref); } else { @@ -109,8 +108,8 @@ public class Secret extends XenAPIObject { /** * Convert a secret.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("value", this.value == null ? "" : this.value); map.put("other_config", this.otherConfig == null ? new HashMap() : this.otherConfig); @@ -137,15 +136,15 @@ public class Secret extends XenAPIObject { * @return all fields from the object */ public Secret.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "secret.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSecretRecord(result); + return Types.toSecretRecord(result); } /** @@ -155,15 +154,15 @@ public class Secret extends XenAPIObject { * @return reference to the object */ public static Secret getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "secret.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSecret(result); + return Types.toSecret(result); } /** @@ -173,9 +172,9 @@ public class Secret extends XenAPIObject { * @return Task */ public static Task createAsync(Connection c, Secret.Record record) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.secret.create"; String session = c.getSessionReference(); Map record_map = record.toMap(); @@ -192,16 +191,16 @@ public class Secret extends XenAPIObject { * @return reference to the newly created object */ public static Secret create(Connection c, Secret.Record record) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "secret.create"; String session = c.getSessionReference(); Map record_map = record.toMap(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(record_map)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSecret(result); + return Types.toSecret(result); } /** @@ -210,9 +209,9 @@ public class Secret extends XenAPIObject { * @return Task */ public Task destroyAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.secret.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -226,9 +225,9 @@ public class Secret extends XenAPIObject { * */ public void destroy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "secret.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -242,15 +241,15 @@ public class Secret extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "secret.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -259,15 +258,15 @@ public class Secret extends XenAPIObject { * @return value of the field */ public String getValue(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "secret.get_value"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -276,15 +275,15 @@ public class Secret extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "secret.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -293,9 +292,9 @@ public class Secret extends XenAPIObject { * @param value New value to set */ public void setValue(Connection c, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "secret.set_value"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -309,9 +308,9 @@ public class Secret extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "secret.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -326,9 +325,9 @@ public class Secret extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "secret.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -342,9 +341,9 @@ public class Secret extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "secret.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -358,15 +357,15 @@ public class Secret extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "secret.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfSecret(result); + return Types.toSetOfSecret(result); } /** @@ -375,15 +374,15 @@ public class Secret extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "secret.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfSecretSecretRecord(result); + return Types.toMapOfSecretSecretRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Session.java b/deps/XenServerJava/src/com/xensource/xenapi/Session.java index f34476b162a..bdf3b4cf80b 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Session.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Session.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class Session extends XenAPIObject { * For internal use only. */ Session(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class Session extends XenAPIObject { { if (obj != null && obj instanceof Session) { - Session other = (Session) obj; + Session other = (Session)obj; return other.ref.equals(this.ref); } else { @@ -120,8 +119,8 @@ public class Session extends XenAPIObject { /** * Convert a session.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("this_host", this.thisHost == null ? new Host("OpaqueRef:NULL") : this.thisHost); map.put("this_user", this.thisUser == null ? new User("OpaqueRef:NULL") : this.thisUser); @@ -203,15 +202,15 @@ public class Session extends XenAPIObject { * @return all fields from the object */ public Session.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "session.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSessionRecord(result); + return Types.toSessionRecord(result); } /** @@ -221,15 +220,15 @@ public class Session extends XenAPIObject { * @return reference to the object */ public static Session getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "session.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSession(result); + return Types.toSession(result); } /** @@ -238,15 +237,15 @@ public class Session extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "session.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -255,15 +254,15 @@ public class Session extends XenAPIObject { * @return value of the field */ public Host getThisHost(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "session.get_this_host"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toHost(result); + return Types.toHost(result); } /** @@ -272,15 +271,15 @@ public class Session extends XenAPIObject { * @return value of the field */ public User getThisUser(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "session.get_this_user"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toUser(result); + return Types.toUser(result); } /** @@ -289,15 +288,15 @@ public class Session extends XenAPIObject { * @return value of the field */ public Date getLastActive(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "session.get_last_active"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDate(result); + return Types.toDate(result); } /** @@ -306,15 +305,15 @@ public class Session extends XenAPIObject { * @return value of the field */ public Boolean getPool(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "session.get_pool"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -323,15 +322,15 @@ public class Session extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "session.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -340,15 +339,15 @@ public class Session extends XenAPIObject { * @return value of the field */ public Boolean getIsLocalSuperuser(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "session.get_is_local_superuser"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -357,15 +356,15 @@ public class Session extends XenAPIObject { * @return value of the field */ public Subject getSubject(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "session.get_subject"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSubject(result); + return Types.toSubject(result); } /** @@ -374,15 +373,15 @@ public class Session extends XenAPIObject { * @return value of the field */ public Date getValidationTime(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "session.get_validation_time"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDate(result); + return Types.toDate(result); } /** @@ -391,15 +390,15 @@ public class Session extends XenAPIObject { * @return value of the field */ public String getAuthUserSid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "session.get_auth_user_sid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -408,15 +407,15 @@ public class Session extends XenAPIObject { * @return value of the field */ public String getAuthUserName(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "session.get_auth_user_name"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -425,15 +424,15 @@ public class Session extends XenAPIObject { * @return value of the field */ public Set getRbacPermissions(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "session.get_rbac_permissions"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -442,15 +441,15 @@ public class Session extends XenAPIObject { * @return value of the field */ public Set getTasks(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "session.get_tasks"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfTask(result); + return Types.toSetOfTask(result); } /** @@ -459,15 +458,15 @@ public class Session extends XenAPIObject { * @return value of the field */ public Session getParent(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "session.get_parent"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSession(result); + return Types.toSession(result); } /** @@ -476,9 +475,9 @@ public class Session extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "session.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -493,9 +492,9 @@ public class Session extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "session.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -509,9 +508,9 @@ public class Session extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "session.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -528,15 +527,15 @@ public class Session extends XenAPIObject { * @return reference of newly created session */ public static Session loginWithPassword(Connection c, String uname, String pwd, String version) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.SessionAuthenticationFailed { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.SessionAuthenticationFailed { String method_call = "session.login_with_password"; Object[] method_params = {Marshalling.toXMLRPC(uname), Marshalling.toXMLRPC(pwd), Marshalling.toXMLRPC(version)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSession(result); + return Types.toSession(result); } /** @@ -544,9 +543,9 @@ public class Session extends XenAPIObject { * */ public static void logout(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "session.logout"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; @@ -561,9 +560,9 @@ public class Session extends XenAPIObject { * @param newPwd New password for account */ public static void changePassword(Connection c, String oldPwd, String newPwd) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "session.change_password"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(oldPwd), Marshalling.toXMLRPC(newPwd)}; @@ -579,14 +578,14 @@ public class Session extends XenAPIObject { * @return ID of newly created session */ public static Session slaveLocalLoginWithPassword(Connection c, String uname, String pwd) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "session.slave_local_login_with_password"; Object[] method_params = {Marshalling.toXMLRPC(uname), Marshalling.toXMLRPC(pwd)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSession(result); + return Types.toSession(result); } /** @@ -594,9 +593,9 @@ public class Session extends XenAPIObject { * */ public static void localLogout(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "session.local_logout"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; @@ -610,9 +609,9 @@ public class Session extends XenAPIObject { * @return Task */ public static Task getAllSubjectIdentifiersAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.session.get_all_subject_identifiers"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; @@ -627,15 +626,15 @@ public class Session extends XenAPIObject { * @return The list of user subject-identifiers of all existing sessions */ public static Set getAllSubjectIdentifiers(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "session.get_all_subject_identifiers"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -645,9 +644,9 @@ public class Session extends XenAPIObject { * @return Task */ public static Task logoutSubjectIdentifierAsync(Connection c, String subjectIdentifier) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.session.logout_subject_identifier"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(subjectIdentifier)}; @@ -662,9 +661,9 @@ public class Session extends XenAPIObject { * @param subjectIdentifier User subject-identifier of the sessions to be destroyed */ public static void logoutSubjectIdentifier(Connection c, String subjectIdentifier) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "session.logout_subject_identifier"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(subjectIdentifier)}; diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Subject.java b/deps/XenServerJava/src/com/xensource/xenapi/Subject.java index a181b58fda5..a599f237be9 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Subject.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Subject.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class Subject extends XenAPIObject { * For internal use only. */ Subject(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class Subject extends XenAPIObject { { if (obj != null && obj instanceof Subject) { - Subject other = (Subject) obj; + Subject other = (Subject)obj; return other.ref.equals(this.ref); } else { @@ -110,8 +109,8 @@ public class Subject extends XenAPIObject { /** * Convert a subject.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("subject_identifier", this.subjectIdentifier == null ? "" : this.subjectIdentifier); map.put("other_config", this.otherConfig == null ? new HashMap() : this.otherConfig); @@ -143,15 +142,15 @@ public class Subject extends XenAPIObject { * @return all fields from the object */ public Subject.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "subject.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSubjectRecord(result); + return Types.toSubjectRecord(result); } /** @@ -161,15 +160,15 @@ public class Subject extends XenAPIObject { * @return reference to the object */ public static Subject getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "subject.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSubject(result); + return Types.toSubject(result); } /** @@ -179,9 +178,9 @@ public class Subject extends XenAPIObject { * @return Task */ public static Task createAsync(Connection c, Subject.Record record) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.subject.create"; String session = c.getSessionReference(); Map record_map = record.toMap(); @@ -198,16 +197,16 @@ public class Subject extends XenAPIObject { * @return reference to the newly created object */ public static Subject create(Connection c, Subject.Record record) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "subject.create"; String session = c.getSessionReference(); Map record_map = record.toMap(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(record_map)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSubject(result); + return Types.toSubject(result); } /** @@ -216,9 +215,9 @@ public class Subject extends XenAPIObject { * @return Task */ public Task destroyAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.subject.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -232,9 +231,9 @@ public class Subject extends XenAPIObject { * */ public void destroy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "subject.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -248,15 +247,15 @@ public class Subject extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "subject.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -265,15 +264,15 @@ public class Subject extends XenAPIObject { * @return value of the field */ public String getSubjectIdentifier(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "subject.get_subject_identifier"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -282,15 +281,15 @@ public class Subject extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "subject.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -299,15 +298,15 @@ public class Subject extends XenAPIObject { * @return value of the field */ public Set getRoles(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "subject.get_roles"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfRole(result); + return Types.toSetOfRole(result); } /** @@ -316,9 +315,9 @@ public class Subject extends XenAPIObject { * @param role The unique role reference */ public void addToRoles(Connection c, Role role) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "subject.add_to_roles"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(role)}; @@ -332,9 +331,9 @@ public class Subject extends XenAPIObject { * @param role The unique role reference in the subject's roles field */ public void removeFromRoles(Connection c, Role role) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "subject.remove_from_roles"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(role)}; @@ -348,15 +347,15 @@ public class Subject extends XenAPIObject { * @return a list of permission names */ public Set getPermissionsNameLabel(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "subject.get_permissions_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -365,15 +364,15 @@ public class Subject extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "subject.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfSubject(result); + return Types.toSetOfSubject(result); } /** @@ -382,15 +381,15 @@ public class Subject extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "subject.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfSubjectSubjectRecord(result); + return Types.toMapOfSubjectSubjectRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Task.java b/deps/XenServerJava/src/com/xensource/xenapi/Task.java index beb9686332e..59d59f6131b 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Task.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Task.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class Task extends XenAPIObject { * For internal use only. */ Task(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class Task extends XenAPIObject { { if (obj != null && obj instanceof Task) { - Task other = (Task) obj; + Task other = (Task)obj; return other.ref.equals(this.ref); } else { @@ -122,8 +121,8 @@ public class Task extends XenAPIObject { /** * Convert a task.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("name_label", this.nameLabel == null ? "" : this.nameLabel); map.put("name_description", this.nameDescription == null ? "" : this.nameDescription); @@ -215,15 +214,15 @@ public class Task extends XenAPIObject { * @return all fields from the object */ public Task.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "task.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toTaskRecord(result); + return Types.toTaskRecord(result); } /** @@ -233,15 +232,15 @@ public class Task extends XenAPIObject { * @return reference to the object */ public static Task getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "task.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toTask(result); + return Types.toTask(result); } /** @@ -251,15 +250,15 @@ public class Task extends XenAPIObject { * @return references to objects with matching names */ public static Set getByNameLabel(Connection c, String label) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "task.get_by_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(label)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfTask(result); + return Types.toSetOfTask(result); } /** @@ -268,15 +267,15 @@ public class Task extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "task.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -285,15 +284,15 @@ public class Task extends XenAPIObject { * @return value of the field */ public String getNameLabel(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "task.get_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -302,15 +301,15 @@ public class Task extends XenAPIObject { * @return value of the field */ public String getNameDescription(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "task.get_name_description"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -319,15 +318,15 @@ public class Task extends XenAPIObject { * @return value of the field */ public Set getAllowedOperations(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "task.get_allowed_operations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfTaskAllowedOperations(result); + return Types.toSetOfTaskAllowedOperations(result); } /** @@ -336,15 +335,15 @@ public class Task extends XenAPIObject { * @return value of the field */ public Map getCurrentOperations(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "task.get_current_operations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringTaskAllowedOperations(result); + return Types.toMapOfStringTaskAllowedOperations(result); } /** @@ -353,15 +352,15 @@ public class Task extends XenAPIObject { * @return value of the field */ public Date getCreated(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "task.get_created"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDate(result); + return Types.toDate(result); } /** @@ -370,15 +369,15 @@ public class Task extends XenAPIObject { * @return value of the field */ public Date getFinished(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "task.get_finished"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDate(result); + return Types.toDate(result); } /** @@ -387,15 +386,15 @@ public class Task extends XenAPIObject { * @return value of the field */ public Types.TaskStatusType getStatus(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "task.get_status"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toTaskStatusType(result); + return Types.toTaskStatusType(result); } /** @@ -404,15 +403,15 @@ public class Task extends XenAPIObject { * @return value of the field */ public Host getResidentOn(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "task.get_resident_on"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toHost(result); + return Types.toHost(result); } /** @@ -421,15 +420,15 @@ public class Task extends XenAPIObject { * @return value of the field */ public Double getProgress(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "task.get_progress"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDouble(result); + return Types.toDouble(result); } /** @@ -438,15 +437,15 @@ public class Task extends XenAPIObject { * @return value of the field */ public String getType(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "task.get_type"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -455,15 +454,15 @@ public class Task extends XenAPIObject { * @return value of the field */ public String getResult(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "task.get_result"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -472,15 +471,15 @@ public class Task extends XenAPIObject { * @return value of the field */ public Set getErrorInfo(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "task.get_error_info"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -489,15 +488,15 @@ public class Task extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "task.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -506,15 +505,15 @@ public class Task extends XenAPIObject { * @return value of the field */ public Task getSubtaskOf(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "task.get_subtask_of"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toTask(result); + return Types.toTask(result); } /** @@ -523,15 +522,15 @@ public class Task extends XenAPIObject { * @return value of the field */ public Set getSubtasks(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "task.get_subtasks"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfTask(result); + return Types.toSetOfTask(result); } /** @@ -540,9 +539,9 @@ public class Task extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "task.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -557,9 +556,9 @@ public class Task extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "task.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -573,9 +572,9 @@ public class Task extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "task.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -591,15 +590,15 @@ public class Task extends XenAPIObject { * @return The reference of the created task object */ public static Task create(Connection c, String label, String description) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "task.create"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(label), Marshalling.toXMLRPC(description)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toTask(result); + return Types.toTask(result); } /** @@ -607,9 +606,9 @@ public class Task extends XenAPIObject { * */ public void destroy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "task.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -623,10 +622,10 @@ public class Task extends XenAPIObject { * @return Task */ public Task cancelAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.OperationNotAllowed { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.OperationNotAllowed { String method_call = "Async.task.cancel"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -640,10 +639,10 @@ public class Task extends XenAPIObject { * */ public void cancel(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.OperationNotAllowed { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.OperationNotAllowed { String method_call = "task.cancel"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -657,15 +656,15 @@ public class Task extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "task.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfTask(result); + return Types.toSetOfTask(result); } /** @@ -674,15 +673,15 @@ public class Task extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "task.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfTaskTaskRecord(result); + return Types.toMapOfTaskTaskRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Tunnel.java b/deps/XenServerJava/src/com/xensource/xenapi/Tunnel.java index 8289e8f35d2..44b236df1b7 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Tunnel.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Tunnel.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class Tunnel extends XenAPIObject { * For internal use only. */ Tunnel(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class Tunnel extends XenAPIObject { { if (obj != null && obj instanceof Tunnel) { - Tunnel other = (Tunnel) obj; + Tunnel other = (Tunnel)obj; return other.ref.equals(this.ref); } else { @@ -111,8 +110,8 @@ public class Tunnel extends XenAPIObject { /** * Convert a tunnel.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("access_PIF", this.accessPIF == null ? new PIF("OpaqueRef:NULL") : this.accessPIF); map.put("transport_PIF", this.transportPIF == null ? new PIF("OpaqueRef:NULL") : this.transportPIF); @@ -149,15 +148,15 @@ public class Tunnel extends XenAPIObject { * @return all fields from the object */ public Tunnel.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "tunnel.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toTunnelRecord(result); + return Types.toTunnelRecord(result); } /** @@ -167,15 +166,15 @@ public class Tunnel extends XenAPIObject { * @return reference to the object */ public static Tunnel getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "tunnel.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toTunnel(result); + return Types.toTunnel(result); } /** @@ -184,15 +183,15 @@ public class Tunnel extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "tunnel.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -201,15 +200,15 @@ public class Tunnel extends XenAPIObject { * @return value of the field */ public PIF getAccessPIF(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "tunnel.get_access_PIF"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toPIF(result); + return Types.toPIF(result); } /** @@ -218,15 +217,15 @@ public class Tunnel extends XenAPIObject { * @return value of the field */ public PIF getTransportPIF(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "tunnel.get_transport_PIF"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toPIF(result); + return Types.toPIF(result); } /** @@ -235,15 +234,15 @@ public class Tunnel extends XenAPIObject { * @return value of the field */ public Map getStatus(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "tunnel.get_status"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -252,15 +251,15 @@ public class Tunnel extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "tunnel.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -269,9 +268,9 @@ public class Tunnel extends XenAPIObject { * @param status New value to set */ public void setStatus(Connection c, Map status) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "tunnel.set_status"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(status)}; @@ -286,9 +285,9 @@ public class Tunnel extends XenAPIObject { * @param value Value to add */ public void addToStatus(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "tunnel.add_to_status"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -302,9 +301,9 @@ public class Tunnel extends XenAPIObject { * @param key Key to remove */ public void removeFromStatus(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "tunnel.remove_from_status"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -318,9 +317,9 @@ public class Tunnel extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "tunnel.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -335,9 +334,9 @@ public class Tunnel extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "tunnel.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -351,9 +350,9 @@ public class Tunnel extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "tunnel.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -369,12 +368,12 @@ public class Tunnel extends XenAPIObject { * @return Task */ public static Task createAsync(Connection c, PIF transportPIF, Network network) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.OpenvswitchNotActive, - Types.TransportPifNotConfigured, - Types.IsTunnelAccessPif { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.OpenvswitchNotActive, + Types.TransportPifNotConfigured, + Types.IsTunnelAccessPif { String method_call = "Async.tunnel.create"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(transportPIF), Marshalling.toXMLRPC(network)}; @@ -391,18 +390,18 @@ public class Tunnel extends XenAPIObject { * @return The reference of the created tunnel object */ public static Tunnel create(Connection c, PIF transportPIF, Network network) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.OpenvswitchNotActive, - Types.TransportPifNotConfigured, - Types.IsTunnelAccessPif { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.OpenvswitchNotActive, + Types.TransportPifNotConfigured, + Types.IsTunnelAccessPif { String method_call = "tunnel.create"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(transportPIF), Marshalling.toXMLRPC(network)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toTunnel(result); + return Types.toTunnel(result); } /** @@ -411,9 +410,9 @@ public class Tunnel extends XenAPIObject { * @return Task */ public Task destroyAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.tunnel.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -427,9 +426,9 @@ public class Tunnel extends XenAPIObject { * */ public void destroy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "tunnel.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -443,15 +442,15 @@ public class Tunnel extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "tunnel.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfTunnel(result); + return Types.toSetOfTunnel(result); } /** @@ -460,15 +459,15 @@ public class Tunnel extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "tunnel.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfTunnelTunnelRecord(result); + return Types.toMapOfTunnelTunnelRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Types.java b/deps/XenServerJava/src/com/xensource/xenapi/Types.java index bde887a4ec3..777d580e0b1 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Types.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Types.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import java.util.Date; @@ -69,7 +68,7 @@ public class Types String[] result = new String[objArray.length]; for (int i = 0; i < objArray.length; i++) { - result[i] = (String) objArray[i]; + result[i] = (String)objArray[i]; } return result; } @@ -119,6 +118,7 @@ public class Types return sb.toString(); } } + /** * Thrown if the response from the server contains an invalid status. */ @@ -126,7 +126,7 @@ public class Types { public BadServerResponse(Map response) { - super(ObjectArrayToStringArray((Object[]) response.get("ErrorDescription"))); + super(ObjectArrayToStringArray((Object[])response.get("ErrorDescription"))); } } @@ -172,10 +172,11 @@ public class Types return matcher.group(1); } - /** - * Checks the provided server response was successful. If the call failed, throws a XenAPIException. If the server - * returned an invalid response, throws a BadServerResponse. Otherwise, returns the server response as passed in. - */ + + /** + * Checks the provided server response was successful. If the call failed, throws a XenAPIException. If the server + * returned an invalid response, throws a BadServerResponse. Otherwise, returns the server response as passed in. + */ static Map checkResponse(Map response) throws XenAPIException, BadServerResponse { if (response.get("Status").equals("Success")) @@ -185,7 +186,7 @@ public class Types if (response.get("Status").equals("Failure")) { - String[] ErrorDescription = ObjectArrayToStringArray((Object[]) response.get("ErrorDescription")); + String[] ErrorDescription = ObjectArrayToStringArray((Object[])response.get("ErrorDescription")); if (ErrorDescription[0].equals("RESTORE_TARGET_MISSING_DEVICE")) { @@ -1278,6 +1279,17 @@ public class Types String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; throw new Types.CrlNameInvalid(p1); } + if (ErrorDescription[0].equals("VDI_NOT_SPARSE")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + throw new Types.VdiNotSparse(p1); + } + if (ErrorDescription[0].equals("VDI_TOO_SMALL")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + String p2 = ErrorDescription.length > 2 ? ErrorDescription[2] : ""; + throw new Types.VdiTooSmall(p1, p2); + } if (ErrorDescription[0].equals("HOST_POWER_ON_MODE_DISABLED")) { throw new Types.HostPowerOnModeDisabled(); @@ -1993,21 +2005,34 @@ public class Types */ BLOCKED; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == SCAN) return "scan"; - if (this == CLONE) return "clone"; - if (this == COPY) return "copy"; - if (this == RESIZE) return "resize"; - if (this == RESIZE_ONLINE) return "resize_online"; - if (this == SNAPSHOT) return "snapshot"; - if (this == DESTROY) return "destroy"; - if (this == FORGET) return "forget"; - if (this == UPDATE) return "update"; - if (this == FORCE_UNLOCK) return "force_unlock"; - if (this == GENERATE_CONFIG) return "generate_config"; - if (this == BLOCKED) return "blocked"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == SCAN) + return "scan"; + if (this == CLONE) + return "clone"; + if (this == COPY) + return "copy"; + if (this == RESIZE) + return "resize"; + if (this == RESIZE_ONLINE) + return "resize_online"; + if (this == SNAPSHOT) + return "snapshot"; + if (this == DESTROY) + return "destroy"; + if (this == FORGET) + return "forget"; + if (this == UPDATE) + return "update"; + if (this == FORCE_UNLOCK) + return "force_unlock"; + if (this == GENERATE_CONFIG) + return "generate_config"; + if (this == BLOCKED) + return "blocked"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -2038,14 +2063,20 @@ public class Types */ VMPP; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == VM) return "VM"; - if (this == HOST) return "Host"; - if (this == SR) return "SR"; - if (this == POOL) return "Pool"; - if (this == VMPP) return "VMPP"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == VM) + return "VM"; + if (this == HOST) + return "Host"; + if (this == SR) + return "SR"; + if (this == POOL) + return "Pool"; + if (this == VMPP) + return "VMPP"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -2088,17 +2119,26 @@ public class Types */ REDO_LOG; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == SYSTEM) return "system"; - if (this == USER) return "user"; - if (this == EPHEMERAL) return "ephemeral"; - if (this == SUSPEND) return "suspend"; - if (this == CRASHDUMP) return "crashdump"; - if (this == HA_STATEFILE) return "ha_statefile"; - if (this == METADATA) return "metadata"; - if (this == REDO_LOG) return "redo_log"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == SYSTEM) + return "system"; + if (this == USER) + return "user"; + if (this == EPHEMERAL) + return "ephemeral"; + if (this == SUSPEND) + return "suspend"; + if (this == CRASHDUMP) + return "crashdump"; + if (this == HA_STATEFILE) + return "ha_statefile"; + if (this == METADATA) + return "metadata"; + if (this == REDO_LOG) + return "redo_log"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -2125,13 +2165,18 @@ public class Types */ RESTARTXAPI; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == RESTARTHVM) return "restartHVM"; - if (this == RESTARTPV) return "restartPV"; - if (this == RESTARTHOST) return "restartHost"; - if (this == RESTARTXAPI) return "restartXAPI"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == RESTARTHVM) + return "restartHVM"; + if (this == RESTARTPV) + return "restartPV"; + if (this == RESTARTHOST) + return "restartHost"; + if (this == RESTARTXAPI) + return "restartXAPI"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -2154,12 +2199,16 @@ public class Types */ MOD; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == ADD) return "add"; - if (this == DEL) return "del"; - if (this == MOD) return "mod"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == ADD) + return "add"; + if (this == DEL) + return "del"; + if (this == MOD) + return "mod"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -2178,11 +2227,14 @@ public class Types */ IPV6; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == IPV4) return "IPv4"; - if (this == IPV6) return "IPv6"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == IPV4) + return "IPv4"; + if (this == IPV6) + return "IPv6"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -2197,10 +2249,12 @@ public class Types */ CANCEL; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == CANCEL) return "cancel"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == CANCEL) + return "cancel"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -2231,14 +2285,20 @@ public class Types */ CANCELLED; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == PENDING) return "pending"; - if (this == SUCCESS) return "success"; - if (this == FAILURE) return "failure"; - if (this == CANCELLING) return "cancelling"; - if (this == CANCELLED) return "cancelled"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == PENDING) + return "pending"; + if (this == SUCCESS) + return "success"; + if (this == FAILURE) + return "failure"; + if (this == CANCELLING) + return "cancelling"; + if (this == CANCELLED) + return "cancelled"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -2253,10 +2313,12 @@ public class Types */ ATTACHING; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == ATTACHING) return "attaching"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == ATTACHING) + return "attaching"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -2279,12 +2341,16 @@ public class Types */ RDP; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == VT100) return "vt100"; - if (this == RFB) return "rfb"; - if (this == RDP) return "rdp"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == VT100) + return "vt100"; + if (this == RFB) + return "rfb"; + if (this == RDP) + return "rdp"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -2319,15 +2385,22 @@ public class Types */ RENAME_RESTART; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == DESTROY) return "destroy"; - if (this == COREDUMP_AND_DESTROY) return "coredump_and_destroy"; - if (this == RESTART) return "restart"; - if (this == COREDUMP_AND_RESTART) return "coredump_and_restart"; - if (this == PRESERVE) return "preserve"; - if (this == RENAME_RESTART) return "rename_restart"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == DESTROY) + return "destroy"; + if (this == COREDUMP_AND_DESTROY) + return "coredump_and_destroy"; + if (this == RESTART) + return "restart"; + if (this == COREDUMP_AND_RESTART) + return "coredump_and_restart"; + if (this == PRESERVE) + return "preserve"; + if (this == RENAME_RESTART) + return "rename_restart"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -2346,11 +2419,14 @@ public class Types */ CHECKPOINT; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == SNAPSHOT) return "snapshot"; - if (this == CHECKPOINT) return "checkpoint"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == SNAPSHOT) + return "snapshot"; + if (this == CHECKPOINT) + return "checkpoint"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -2369,11 +2445,14 @@ public class Types */ RESTART; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == DESTROY) return "destroy"; - if (this == RESTART) return "restart"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == DESTROY) + return "destroy"; + if (this == RESTART) + return "restart"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -2396,12 +2475,16 @@ public class Types */ UNPLUG; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == ATTACH) return "attach"; - if (this == PLUG) return "plug"; - if (this == UNPLUG) return "unplug"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == ATTACH) + return "attach"; + if (this == PLUG) + return "plug"; + if (this == UNPLUG) + return "unplug"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -2592,54 +2675,100 @@ public class Types */ VGPU; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == SESSION) return "session"; - if (this == AUTH) return "auth"; - if (this == SUBJECT) return "subject"; - if (this == ROLE) return "role"; - if (this == TASK) return "task"; - if (this == EVENT) return "event"; - if (this == POOL) return "pool"; - if (this == POOL_PATCH) return "pool_patch"; - if (this == VM) return "VM"; - if (this == VM_METRICS) return "VM_metrics"; - if (this == VM_GUEST_METRICS) return "VM_guest_metrics"; - if (this == VMPP) return "VMPP"; - if (this == VM_APPLIANCE) return "VM_appliance"; - if (this == DR_TASK) return "DR_task"; - if (this == HOST) return "host"; - if (this == HOST_CRASHDUMP) return "host_crashdump"; - if (this == HOST_PATCH) return "host_patch"; - if (this == HOST_METRICS) return "host_metrics"; - if (this == HOST_CPU) return "host_cpu"; - if (this == NETWORK) return "network"; - if (this == VIF) return "VIF"; - if (this == VIF_METRICS) return "VIF_metrics"; - if (this == PIF) return "PIF"; - if (this == PIF_METRICS) return "PIF_metrics"; - if (this == BOND) return "Bond"; - if (this == VLAN) return "VLAN"; - if (this == SM) return "SM"; - if (this == SR) return "SR"; - if (this == VDI) return "VDI"; - if (this == VBD) return "VBD"; - if (this == VBD_METRICS) return "VBD_metrics"; - if (this == PBD) return "PBD"; - if (this == CRASHDUMP) return "crashdump"; - if (this == VTPM) return "VTPM"; - if (this == CONSOLE) return "console"; - if (this == USER) return "user"; - if (this == DATA_SOURCE) return "data_source"; - if (this == BLOB) return "blob"; - if (this == MESSAGE) return "message"; - if (this == SECRET) return "secret"; - if (this == TUNNEL) return "tunnel"; - if (this == PCI) return "PCI"; - if (this == PGPU) return "PGPU"; - if (this == GPU_GROUP) return "GPU_group"; - if (this == VGPU) return "VGPU"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == SESSION) + return "session"; + if (this == AUTH) + return "auth"; + if (this == SUBJECT) + return "subject"; + if (this == ROLE) + return "role"; + if (this == TASK) + return "task"; + if (this == EVENT) + return "event"; + if (this == POOL) + return "pool"; + if (this == POOL_PATCH) + return "pool_patch"; + if (this == VM) + return "VM"; + if (this == VM_METRICS) + return "VM_metrics"; + if (this == VM_GUEST_METRICS) + return "VM_guest_metrics"; + if (this == VMPP) + return "VMPP"; + if (this == VM_APPLIANCE) + return "VM_appliance"; + if (this == DR_TASK) + return "DR_task"; + if (this == HOST) + return "host"; + if (this == HOST_CRASHDUMP) + return "host_crashdump"; + if (this == HOST_PATCH) + return "host_patch"; + if (this == HOST_METRICS) + return "host_metrics"; + if (this == HOST_CPU) + return "host_cpu"; + if (this == NETWORK) + return "network"; + if (this == VIF) + return "VIF"; + if (this == VIF_METRICS) + return "VIF_metrics"; + if (this == PIF) + return "PIF"; + if (this == PIF_METRICS) + return "PIF_metrics"; + if (this == BOND) + return "Bond"; + if (this == VLAN) + return "VLAN"; + if (this == SM) + return "SM"; + if (this == SR) + return "SR"; + if (this == VDI) + return "VDI"; + if (this == VBD) + return "VBD"; + if (this == VBD_METRICS) + return "VBD_metrics"; + if (this == PBD) + return "PBD"; + if (this == CRASHDUMP) + return "crashdump"; + if (this == VTPM) + return "VTPM"; + if (this == CONSOLE) + return "console"; + if (this == USER) + return "user"; + if (this == DATA_SOURCE) + return "data_source"; + if (this == BLOB) + return "blob"; + if (this == MESSAGE) + return "message"; + if (this == SECRET) + return "secret"; + if (this == TUNNEL) + return "tunnel"; + if (this == PCI) + return "PCI"; + if (this == PGPU) + return "PGPU"; + if (this == GPU_GROUP) + return "GPU_group"; + if (this == VGPU) + return "VGPU"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -2682,17 +2811,26 @@ public class Types */ VM_MIGRATE; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == PROVISION) return "provision"; - if (this == EVACUATE) return "evacuate"; - if (this == SHUTDOWN) return "shutdown"; - if (this == REBOOT) return "reboot"; - if (this == POWER_ON) return "power_on"; - if (this == VM_START) return "vm_start"; - if (this == VM_RESUME) return "vm_resume"; - if (this == VM_MIGRATE) return "vm_migrate"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == PROVISION) + return "provision"; + if (this == EVACUATE) + return "evacuate"; + if (this == SHUTDOWN) + return "shutdown"; + if (this == REBOOT) + return "reboot"; + if (this == POWER_ON) + return "power_on"; + if (this == VM_START) + return "vm_start"; + if (this == VM_RESUME) + return "vm_resume"; + if (this == VM_MIGRATE) + return "vm_migrate"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -2719,13 +2857,18 @@ public class Types */ WEEKLY; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == NEVER) return "never"; - if (this == ALWAYS_AFTER_BACKUP) return "always_after_backup"; - if (this == DAILY) return "daily"; - if (this == WEEKLY) return "weekly"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == NEVER) + return "never"; + if (this == ALWAYS_AFTER_BACKUP) + return "always_after_backup"; + if (this == DAILY) + return "daily"; + if (this == WEEKLY) + return "weekly"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -2748,12 +2891,16 @@ public class Types */ NFS; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == NONE) return "none"; - if (this == CIFS) return "cifs"; - if (this == NFS) return "nfs"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == NONE) + return "none"; + if (this == CIFS) + return "cifs"; + if (this == NFS) + return "nfs"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -2772,11 +2919,14 @@ public class Types */ RW; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == RO) return "RO"; - if (this == RW) return "RW"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == RO) + return "RO"; + if (this == RW) + return "RW"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -2803,13 +2953,18 @@ public class Types */ AUTOCONF; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == NONE) return "None"; - if (this == DHCP) return "DHCP"; - if (this == STATIC) return "Static"; - if (this == AUTOCONF) return "Autoconf"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == NONE) + return "None"; + if (this == DHCP) + return "DHCP"; + if (this == STATIC) + return "Static"; + if (this == AUTOCONF) + return "Autoconf"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -2828,11 +2983,14 @@ public class Types */ DISK; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == CD) return "CD"; - if (this == DISK) return "Disk"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == CD) + return "CD"; + if (this == DISK) + return "Disk"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -2851,11 +3009,14 @@ public class Types */ PERSIST; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == RESET) return "reset"; - if (this == PERSIST) return "persist"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == RESET) + return "reset"; + if (this == PERSIST) + return "persist"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -2882,13 +3043,18 @@ public class Types */ SHUTDOWN; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == START) return "start"; - if (this == CLEAN_SHUTDOWN) return "clean_shutdown"; - if (this == HARD_SHUTDOWN) return "hard_shutdown"; - if (this == SHUTDOWN) return "shutdown"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == START) + return "start"; + if (this == CLEAN_SHUTDOWN) + return "clean_shutdown"; + if (this == HARD_SHUTDOWN) + return "hard_shutdown"; + if (this == SHUTDOWN) + return "shutdown"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -2931,17 +3097,26 @@ public class Types */ UNPAUSE; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == ATTACH) return "attach"; - if (this == EJECT) return "eject"; - if (this == INSERT) return "insert"; - if (this == PLUG) return "plug"; - if (this == UNPLUG) return "unplug"; - if (this == UNPLUG_FORCE) return "unplug_force"; - if (this == PAUSE) return "pause"; - if (this == UNPAUSE) return "unpause"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == ATTACH) + return "attach"; + if (this == EJECT) + return "eject"; + if (this == INSERT) + return "insert"; + if (this == PLUG) + return "plug"; + if (this == UNPLUG) + return "unplug"; + if (this == UNPLUG_FORCE) + return "unplug_force"; + if (this == PAUSE) + return "pause"; + if (this == UNPAUSE) + return "unpause"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -2964,12 +3139,16 @@ public class Types */ WEEKLY; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == HOURLY) return "hourly"; - if (this == DAILY) return "daily"; - if (this == WEEKLY) return "weekly"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == HOURLY) + return "hourly"; + if (this == DAILY) + return "daily"; + if (this == WEEKLY) + return "weekly"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -2988,11 +3167,14 @@ public class Types */ DISABLED; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == UNLOCKED) return "unlocked"; - if (this == DISABLED) return "disabled"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == UNLOCKED) + return "unlocked"; + if (this == DISABLED) + return "disabled"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -3019,13 +3201,18 @@ public class Types */ SUSPENDED; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == HALTED) return "Halted"; - if (this == PAUSED) return "Paused"; - if (this == RUNNING) return "Running"; - if (this == SUSPENDED) return "Suspended"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == HALTED) + return "Halted"; + if (this == PAUSED) + return "Paused"; + if (this == RUNNING) + return "Running"; + if (this == SUSPENDED) + return "Suspended"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -3216,54 +3403,100 @@ public class Types */ DESTROY; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == SNAPSHOT) return "snapshot"; - if (this == CLONE) return "clone"; - if (this == COPY) return "copy"; - if (this == CREATE_TEMPLATE) return "create_template"; - if (this == REVERT) return "revert"; - if (this == CHECKPOINT) return "checkpoint"; - if (this == SNAPSHOT_WITH_QUIESCE) return "snapshot_with_quiesce"; - if (this == PROVISION) return "provision"; - if (this == START) return "start"; - if (this == START_ON) return "start_on"; - if (this == PAUSE) return "pause"; - if (this == UNPAUSE) return "unpause"; - if (this == CLEAN_SHUTDOWN) return "clean_shutdown"; - if (this == CLEAN_REBOOT) return "clean_reboot"; - if (this == HARD_SHUTDOWN) return "hard_shutdown"; - if (this == POWER_STATE_RESET) return "power_state_reset"; - if (this == HARD_REBOOT) return "hard_reboot"; - if (this == SUSPEND) return "suspend"; - if (this == CSVM) return "csvm"; - if (this == RESUME) return "resume"; - if (this == RESUME_ON) return "resume_on"; - if (this == POOL_MIGRATE) return "pool_migrate"; - if (this == MIGRATE_SEND) return "migrate_send"; - if (this == GET_BOOT_RECORD) return "get_boot_record"; - if (this == SEND_SYSRQ) return "send_sysrq"; - if (this == SEND_TRIGGER) return "send_trigger"; - if (this == QUERY_SERVICES) return "query_services"; - if (this == CHANGING_MEMORY_LIVE) return "changing_memory_live"; - if (this == AWAITING_MEMORY_LIVE) return "awaiting_memory_live"; - if (this == CHANGING_DYNAMIC_RANGE) return "changing_dynamic_range"; - if (this == CHANGING_STATIC_RANGE) return "changing_static_range"; - if (this == CHANGING_MEMORY_LIMITS) return "changing_memory_limits"; - if (this == CHANGING_SHADOW_MEMORY) return "changing_shadow_memory"; - if (this == CHANGING_SHADOW_MEMORY_LIVE) return "changing_shadow_memory_live"; - if (this == CHANGING_VCPUS) return "changing_VCPUs"; - if (this == CHANGING_VCPUS_LIVE) return "changing_VCPUs_live"; - if (this == ASSERT_OPERATION_VALID) return "assert_operation_valid"; - if (this == DATA_SOURCE_OP) return "data_source_op"; - if (this == UPDATE_ALLOWED_OPERATIONS) return "update_allowed_operations"; - if (this == MAKE_INTO_TEMPLATE) return "make_into_template"; - if (this == IMPORT) return "import"; - if (this == EXPORT) return "export"; - if (this == METADATA_EXPORT) return "metadata_export"; - if (this == REVERTING) return "reverting"; - if (this == DESTROY) return "destroy"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == SNAPSHOT) + return "snapshot"; + if (this == CLONE) + return "clone"; + if (this == COPY) + return "copy"; + if (this == CREATE_TEMPLATE) + return "create_template"; + if (this == REVERT) + return "revert"; + if (this == CHECKPOINT) + return "checkpoint"; + if (this == SNAPSHOT_WITH_QUIESCE) + return "snapshot_with_quiesce"; + if (this == PROVISION) + return "provision"; + if (this == START) + return "start"; + if (this == START_ON) + return "start_on"; + if (this == PAUSE) + return "pause"; + if (this == UNPAUSE) + return "unpause"; + if (this == CLEAN_SHUTDOWN) + return "clean_shutdown"; + if (this == CLEAN_REBOOT) + return "clean_reboot"; + if (this == HARD_SHUTDOWN) + return "hard_shutdown"; + if (this == POWER_STATE_RESET) + return "power_state_reset"; + if (this == HARD_REBOOT) + return "hard_reboot"; + if (this == SUSPEND) + return "suspend"; + if (this == CSVM) + return "csvm"; + if (this == RESUME) + return "resume"; + if (this == RESUME_ON) + return "resume_on"; + if (this == POOL_MIGRATE) + return "pool_migrate"; + if (this == MIGRATE_SEND) + return "migrate_send"; + if (this == GET_BOOT_RECORD) + return "get_boot_record"; + if (this == SEND_SYSRQ) + return "send_sysrq"; + if (this == SEND_TRIGGER) + return "send_trigger"; + if (this == QUERY_SERVICES) + return "query_services"; + if (this == CHANGING_MEMORY_LIVE) + return "changing_memory_live"; + if (this == AWAITING_MEMORY_LIVE) + return "awaiting_memory_live"; + if (this == CHANGING_DYNAMIC_RANGE) + return "changing_dynamic_range"; + if (this == CHANGING_STATIC_RANGE) + return "changing_static_range"; + if (this == CHANGING_MEMORY_LIMITS) + return "changing_memory_limits"; + if (this == CHANGING_SHADOW_MEMORY) + return "changing_shadow_memory"; + if (this == CHANGING_SHADOW_MEMORY_LIVE) + return "changing_shadow_memory_live"; + if (this == CHANGING_VCPUS) + return "changing_VCPUs"; + if (this == CHANGING_VCPUS_LIVE) + return "changing_VCPUs_live"; + if (this == ASSERT_OPERATION_VALID) + return "assert_operation_valid"; + if (this == DATA_SOURCE_OP) + return "data_source_op"; + if (this == UPDATE_ALLOWED_OPERATIONS) + return "update_allowed_operations"; + if (this == MAKE_INTO_TEMPLATE) + return "make_into_template"; + if (this == IMPORT) + return "import"; + if (this == EXPORT) + return "export"; + if (this == METADATA_EXPORT) + return "metadata_export"; + if (this == REVERTING) + return "reverting"; + if (this == DESTROY) + return "destroy"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -3286,12 +3519,16 @@ public class Types */ LACP; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == BALANCE_SLB) return "balance-slb"; - if (this == ACTIVE_BACKUP) return "active-backup"; - if (this == LACP) return "lacp"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == BALANCE_SLB) + return "balance-slb"; + if (this == ACTIVE_BACKUP) + return "active-backup"; + if (this == LACP) + return "lacp"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -3314,12 +3551,16 @@ public class Types */ STATIC; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == NONE) return "None"; - if (this == DHCP) return "DHCP"; - if (this == STATIC) return "Static"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == NONE) + return "None"; + if (this == DHCP) + return "DHCP"; + if (this == STATIC) + return "Static"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -3386,23 +3627,38 @@ public class Types */ PBD_DESTROY; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == SCAN) return "scan"; - if (this == DESTROY) return "destroy"; - if (this == FORGET) return "forget"; - if (this == PLUG) return "plug"; - if (this == UNPLUG) return "unplug"; - if (this == UPDATE) return "update"; - if (this == VDI_CREATE) return "vdi_create"; - if (this == VDI_INTRODUCE) return "vdi_introduce"; - if (this == VDI_DESTROY) return "vdi_destroy"; - if (this == VDI_RESIZE) return "vdi_resize"; - if (this == VDI_CLONE) return "vdi_clone"; - if (this == VDI_SNAPSHOT) return "vdi_snapshot"; - if (this == PBD_CREATE) return "pbd_create"; - if (this == PBD_DESTROY) return "pbd_destroy"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == SCAN) + return "scan"; + if (this == DESTROY) + return "destroy"; + if (this == FORGET) + return "forget"; + if (this == PLUG) + return "plug"; + if (this == UNPLUG) + return "unplug"; + if (this == UPDATE) + return "update"; + if (this == VDI_CREATE) + return "vdi_create"; + if (this == VDI_INTRODUCE) + return "vdi_introduce"; + if (this == VDI_DESTROY) + return "vdi_destroy"; + if (this == VDI_RESIZE) + return "vdi_resize"; + if (this == VDI_CLONE) + return "vdi_clone"; + if (this == VDI_SNAPSHOT) + return "vdi_snapshot"; + if (this == PBD_CREATE) + return "pbd_create"; + if (this == PBD_DESTROY) + return "pbd_destroy"; + /* This can never be reached */ + return "illegal enum"; } }; @@ -3429,18 +3685,22 @@ public class Types */ DISABLED; public String toString() { - if (this == UNRECOGNIZED) return "UNRECOGNIZED"; - if (this == NETWORK_DEFAULT) return "network_default"; - if (this == LOCKED) return "locked"; - if (this == UNLOCKED) return "unlocked"; - if (this == DISABLED) return "disabled"; - /* This can never be reached */ - return "illegal enum"; + if (this == UNRECOGNIZED) + return "UNRECOGNIZED"; + if (this == NETWORK_DEFAULT) + return "network_default"; + if (this == LOCKED) + return "locked"; + if (this == UNLOCKED) + return "unlocked"; + if (this == DISABLED) + return "disabled"; + /* This can never be reached */ + return "illegal enum"; } }; - /** * The restore could not be performed because a network interface is missing */ @@ -7573,6 +7833,45 @@ public class Types } + /** + * The VDI is too small. Please resize it to at least the minimum size. + */ + public static class VdiTooSmall extends XenAPIException { + public final String vdi; + public final String minimumSize; + + /** + * Create a new VdiTooSmall + * + * @param vdi + * @param minimumSize + */ + public VdiTooSmall(String vdi, String minimumSize) { + super("The VDI is too small. Please resize it to at least the minimum size."); + this.vdi = vdi; + this.minimumSize = minimumSize; + } + + } + + /** + * The VDI is not stored using a sparse format. It is not possible to query and manipulate only the changed blocks (or 'block differences' or 'disk deltas') between two VDIs. Please select a VDI which uses a sparse-aware technology such as VHD. + */ + public static class VdiNotSparse extends XenAPIException { + public final String vdi; + + /** + * Create a new VdiNotSparse + * + * @param vdi + */ + public VdiNotSparse(String vdi) { + super("The VDI is not stored using a sparse format. It is not possible to query and manipulate only the changed blocks (or 'block differences' or 'disk deltas') between two VDIs. Please select a VDI which uses a sparse-aware technology such as VHD."); + this.vdi = vdi; + } + + } + /** * The hosts in this pool are not homogeneous. */ @@ -9614,33 +9913,32 @@ public class Types } - public static String toString(Object object) { if (object == null) { return null; } - return (String) object; + return (String)object; } public static Long toLong(Object object) { if (object == null) { return null; } - return Long.valueOf((String) object); + return Long.valueOf((String)object); } public static Double toDouble(Object object) { if (object == null) { return null; } - return (Double) object; + return (Double)object; } public static Boolean toBoolean(Object object) { if (object == null) { return null; } - return (Boolean) object; + return (Boolean)object; } public static Date toDate(Object object) { @@ -9648,11 +9946,11 @@ public class Types return null; } try { - return (Date) object; - } catch (ClassCastException e){ + return (Date)object; + } catch (ClassCastException e) { //Occasionally the date comes back as an ocaml float rather than //in the xmlrpc format! Catch this and convert. - return (new Date((long) (1000*Double.parseDouble((String) object)))); + return (new Date((long)(1000 * Double.parseDouble((String)object)))); } } @@ -9661,7 +9959,7 @@ public class Types return null; } try { - return XenAPIObjects.valueOf(((String) object).toUpperCase().replace('-','_')); + return XenAPIObjects.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return XenAPIObjects.UNRECOGNIZED; } @@ -9672,7 +9970,7 @@ public class Types return null; } try { - return AfterApplyGuidance.valueOf(((String) object).toUpperCase().replace('-','_')); + return AfterApplyGuidance.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return AfterApplyGuidance.UNRECOGNIZED; } @@ -9683,7 +9981,7 @@ public class Types return null; } try { - return BondMode.valueOf(((String) object).toUpperCase().replace('-','_')); + return BondMode.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return BondMode.UNRECOGNIZED; } @@ -9694,7 +9992,7 @@ public class Types return null; } try { - return Cls.valueOf(((String) object).toUpperCase().replace('-','_')); + return Cls.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return Cls.UNRECOGNIZED; } @@ -9705,7 +10003,7 @@ public class Types return null; } try { - return ConsoleProtocol.valueOf(((String) object).toUpperCase().replace('-','_')); + return ConsoleProtocol.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return ConsoleProtocol.UNRECOGNIZED; } @@ -9716,7 +10014,7 @@ public class Types return null; } try { - return EventOperation.valueOf(((String) object).toUpperCase().replace('-','_')); + return EventOperation.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return EventOperation.UNRECOGNIZED; } @@ -9727,7 +10025,7 @@ public class Types return null; } try { - return HostAllowedOperations.valueOf(((String) object).toUpperCase().replace('-','_')); + return HostAllowedOperations.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return HostAllowedOperations.UNRECOGNIZED; } @@ -9738,7 +10036,7 @@ public class Types return null; } try { - return IpConfigurationMode.valueOf(((String) object).toUpperCase().replace('-','_')); + return IpConfigurationMode.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return IpConfigurationMode.UNRECOGNIZED; } @@ -9749,7 +10047,7 @@ public class Types return null; } try { - return Ipv6ConfigurationMode.valueOf(((String) object).toUpperCase().replace('-','_')); + return Ipv6ConfigurationMode.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return Ipv6ConfigurationMode.UNRECOGNIZED; } @@ -9760,7 +10058,7 @@ public class Types return null; } try { - return NetworkDefaultLockingMode.valueOf(((String) object).toUpperCase().replace('-','_')); + return NetworkDefaultLockingMode.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return NetworkDefaultLockingMode.UNRECOGNIZED; } @@ -9771,7 +10069,7 @@ public class Types return null; } try { - return NetworkOperations.valueOf(((String) object).toUpperCase().replace('-','_')); + return NetworkOperations.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return NetworkOperations.UNRECOGNIZED; } @@ -9782,7 +10080,7 @@ public class Types return null; } try { - return OnBoot.valueOf(((String) object).toUpperCase().replace('-','_')); + return OnBoot.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return OnBoot.UNRECOGNIZED; } @@ -9793,7 +10091,7 @@ public class Types return null; } try { - return OnCrashBehaviour.valueOf(((String) object).toUpperCase().replace('-','_')); + return OnCrashBehaviour.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return OnCrashBehaviour.UNRECOGNIZED; } @@ -9804,7 +10102,7 @@ public class Types return null; } try { - return OnNormalExit.valueOf(((String) object).toUpperCase().replace('-','_')); + return OnNormalExit.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return OnNormalExit.UNRECOGNIZED; } @@ -9815,7 +10113,7 @@ public class Types return null; } try { - return PrimaryAddressType.valueOf(((String) object).toUpperCase().replace('-','_')); + return PrimaryAddressType.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return PrimaryAddressType.UNRECOGNIZED; } @@ -9826,7 +10124,7 @@ public class Types return null; } try { - return StorageOperations.valueOf(((String) object).toUpperCase().replace('-','_')); + return StorageOperations.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return StorageOperations.UNRECOGNIZED; } @@ -9837,7 +10135,7 @@ public class Types return null; } try { - return TaskAllowedOperations.valueOf(((String) object).toUpperCase().replace('-','_')); + return TaskAllowedOperations.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return TaskAllowedOperations.UNRECOGNIZED; } @@ -9848,7 +10146,7 @@ public class Types return null; } try { - return TaskStatusType.valueOf(((String) object).toUpperCase().replace('-','_')); + return TaskStatusType.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return TaskStatusType.UNRECOGNIZED; } @@ -9859,7 +10157,7 @@ public class Types return null; } try { - return VbdMode.valueOf(((String) object).toUpperCase().replace('-','_')); + return VbdMode.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return VbdMode.UNRECOGNIZED; } @@ -9870,7 +10168,7 @@ public class Types return null; } try { - return VbdOperations.valueOf(((String) object).toUpperCase().replace('-','_')); + return VbdOperations.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return VbdOperations.UNRECOGNIZED; } @@ -9881,7 +10179,7 @@ public class Types return null; } try { - return VbdType.valueOf(((String) object).toUpperCase().replace('-','_')); + return VbdType.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return VbdType.UNRECOGNIZED; } @@ -9892,7 +10190,7 @@ public class Types return null; } try { - return VdiOperations.valueOf(((String) object).toUpperCase().replace('-','_')); + return VdiOperations.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return VdiOperations.UNRECOGNIZED; } @@ -9903,7 +10201,7 @@ public class Types return null; } try { - return VdiType.valueOf(((String) object).toUpperCase().replace('-','_')); + return VdiType.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return VdiType.UNRECOGNIZED; } @@ -9914,7 +10212,7 @@ public class Types return null; } try { - return VifLockingMode.valueOf(((String) object).toUpperCase().replace('-','_')); + return VifLockingMode.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return VifLockingMode.UNRECOGNIZED; } @@ -9925,7 +10223,7 @@ public class Types return null; } try { - return VifOperations.valueOf(((String) object).toUpperCase().replace('-','_')); + return VifOperations.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return VifOperations.UNRECOGNIZED; } @@ -9936,7 +10234,7 @@ public class Types return null; } try { - return VmApplianceOperation.valueOf(((String) object).toUpperCase().replace('-','_')); + return VmApplianceOperation.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return VmApplianceOperation.UNRECOGNIZED; } @@ -9947,7 +10245,7 @@ public class Types return null; } try { - return VmOperations.valueOf(((String) object).toUpperCase().replace('-','_')); + return VmOperations.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return VmOperations.UNRECOGNIZED; } @@ -9958,7 +10256,7 @@ public class Types return null; } try { - return VmPowerState.valueOf(((String) object).toUpperCase().replace('-','_')); + return VmPowerState.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return VmPowerState.UNRECOGNIZED; } @@ -9969,7 +10267,7 @@ public class Types return null; } try { - return VmppArchiveFrequency.valueOf(((String) object).toUpperCase().replace('-','_')); + return VmppArchiveFrequency.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return VmppArchiveFrequency.UNRECOGNIZED; } @@ -9980,7 +10278,7 @@ public class Types return null; } try { - return VmppArchiveTargetType.valueOf(((String) object).toUpperCase().replace('-','_')); + return VmppArchiveTargetType.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return VmppArchiveTargetType.UNRECOGNIZED; } @@ -9991,7 +10289,7 @@ public class Types return null; } try { - return VmppBackupFrequency.valueOf(((String) object).toUpperCase().replace('-','_')); + return VmppBackupFrequency.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return VmppBackupFrequency.UNRECOGNIZED; } @@ -10002,7 +10300,7 @@ public class Types return null; } try { - return VmppBackupType.valueOf(((String) object).toUpperCase().replace('-','_')); + return VmppBackupType.valueOf(((String)object).toUpperCase().replace('-', '_')); } catch (IllegalArgumentException ex) { return VmppBackupType.UNRECOGNIZED; } @@ -10012,9 +10310,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { String typed = toString(item); result.add(typed); } @@ -10025,9 +10323,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { Types.AfterApplyGuidance typed = toAfterApplyGuidance(item); result.add(typed); } @@ -10038,9 +10336,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { Types.HostAllowedOperations typed = toHostAllowedOperations(item); result.add(typed); } @@ -10051,9 +10349,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { Types.NetworkOperations typed = toNetworkOperations(item); result.add(typed); } @@ -10064,9 +10362,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { Types.StorageOperations typed = toStorageOperations(item); result.add(typed); } @@ -10077,9 +10375,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { Types.TaskAllowedOperations typed = toTaskAllowedOperations(item); result.add(typed); } @@ -10090,9 +10388,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { Types.VbdOperations typed = toVbdOperations(item); result.add(typed); } @@ -10103,9 +10401,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { Types.VdiOperations typed = toVdiOperations(item); result.add(typed); } @@ -10116,9 +10414,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { Types.VifOperations typed = toVifOperations(item); result.add(typed); } @@ -10129,9 +10427,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { Types.VmApplianceOperation typed = toVmApplianceOperation(item); result.add(typed); } @@ -10142,9 +10440,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { Types.VmOperations typed = toVmOperations(item); result.add(typed); } @@ -10155,9 +10453,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { Bond typed = toBond(item); result.add(typed); } @@ -10168,9 +10466,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { DRTask typed = toDRTask(item); result.add(typed); } @@ -10181,9 +10479,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { GPUGroup typed = toGPUGroup(item); result.add(typed); } @@ -10194,9 +10492,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { PBD typed = toPBD(item); result.add(typed); } @@ -10207,9 +10505,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { PCI typed = toPCI(item); result.add(typed); } @@ -10220,9 +10518,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { PGPU typed = toPGPU(item); result.add(typed); } @@ -10233,9 +10531,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { PIF typed = toPIF(item); result.add(typed); } @@ -10246,9 +10544,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { PIFMetrics typed = toPIFMetrics(item); result.add(typed); } @@ -10259,9 +10557,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { SM typed = toSM(item); result.add(typed); } @@ -10272,9 +10570,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { SR typed = toSR(item); result.add(typed); } @@ -10285,9 +10583,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { VBD typed = toVBD(item); result.add(typed); } @@ -10298,9 +10596,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { VBDMetrics typed = toVBDMetrics(item); result.add(typed); } @@ -10311,9 +10609,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { VDI typed = toVDI(item); result.add(typed); } @@ -10324,9 +10622,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { VGPU typed = toVGPU(item); result.add(typed); } @@ -10337,9 +10635,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { VIF typed = toVIF(item); result.add(typed); } @@ -10350,9 +10648,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { VIFMetrics typed = toVIFMetrics(item); result.add(typed); } @@ -10363,9 +10661,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { VLAN typed = toVLAN(item); result.add(typed); } @@ -10376,9 +10674,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { VM typed = toVM(item); result.add(typed); } @@ -10389,9 +10687,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { VMPP typed = toVMPP(item); result.add(typed); } @@ -10402,9 +10700,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { VMAppliance typed = toVMAppliance(item); result.add(typed); } @@ -10415,9 +10713,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { VMGuestMetrics typed = toVMGuestMetrics(item); result.add(typed); } @@ -10428,9 +10726,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { VMMetrics typed = toVMMetrics(item); result.add(typed); } @@ -10441,9 +10739,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { VTPM typed = toVTPM(item); result.add(typed); } @@ -10454,9 +10752,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { Blob typed = toBlob(item); result.add(typed); } @@ -10467,9 +10765,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { Console typed = toConsole(item); result.add(typed); } @@ -10480,9 +10778,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { Crashdump typed = toCrashdump(item); result.add(typed); } @@ -10493,9 +10791,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { Host typed = toHost(item); result.add(typed); } @@ -10506,9 +10804,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { HostCpu typed = toHostCpu(item); result.add(typed); } @@ -10519,9 +10817,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { HostCrashdump typed = toHostCrashdump(item); result.add(typed); } @@ -10532,9 +10830,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { HostMetrics typed = toHostMetrics(item); result.add(typed); } @@ -10545,9 +10843,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { HostPatch typed = toHostPatch(item); result.add(typed); } @@ -10558,9 +10856,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { Message typed = toMessage(item); result.add(typed); } @@ -10571,9 +10869,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { Network typed = toNetwork(item); result.add(typed); } @@ -10584,9 +10882,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { Pool typed = toPool(item); result.add(typed); } @@ -10597,9 +10895,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { PoolPatch typed = toPoolPatch(item); result.add(typed); } @@ -10610,9 +10908,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { Role typed = toRole(item); result.add(typed); } @@ -10623,9 +10921,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { Secret typed = toSecret(item); result.add(typed); } @@ -10636,9 +10934,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { Subject typed = toSubject(item); result.add(typed); } @@ -10649,9 +10947,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { Task typed = toTask(item); result.add(typed); } @@ -10662,9 +10960,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { Tunnel typed = toTunnel(item); result.add(typed); } @@ -10675,9 +10973,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { DataSource.Record typed = toDataSourceRecord(item); result.add(typed); } @@ -10688,9 +10986,9 @@ public class Types if (object == null) { return null; } - Object[] items = (Object[]) object; + Object[] items = (Object[])object; Set result = new LinkedHashSet(); - for(Object item: items) { + for (Object item : items) { Event.Record typed = toEventRecord(item); result.add(typed); } @@ -10701,10 +10999,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { String key = toString(entry.getKey()); String value = toString(entry.getValue()); result.put(key, value); @@ -10716,10 +11014,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { String key = toString(entry.getKey()); Types.HostAllowedOperations value = toHostAllowedOperations(entry.getValue()); result.put(key, value); @@ -10731,10 +11029,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { String key = toString(entry.getKey()); Types.NetworkOperations value = toNetworkOperations(entry.getValue()); result.put(key, value); @@ -10746,10 +11044,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { String key = toString(entry.getKey()); Types.StorageOperations value = toStorageOperations(entry.getValue()); result.put(key, value); @@ -10761,10 +11059,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { String key = toString(entry.getKey()); Types.TaskAllowedOperations value = toTaskAllowedOperations(entry.getValue()); result.put(key, value); @@ -10776,10 +11074,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { String key = toString(entry.getKey()); Types.VbdOperations value = toVbdOperations(entry.getValue()); result.put(key, value); @@ -10791,10 +11089,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { String key = toString(entry.getKey()); Types.VdiOperations value = toVdiOperations(entry.getValue()); result.put(key, value); @@ -10806,10 +11104,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { String key = toString(entry.getKey()); Types.VifOperations value = toVifOperations(entry.getValue()); result.put(key, value); @@ -10821,10 +11119,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { String key = toString(entry.getKey()); Types.VmApplianceOperation value = toVmApplianceOperation(entry.getValue()); result.put(key, value); @@ -10836,10 +11134,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { String key = toString(entry.getKey()); Types.VmOperations value = toVmOperations(entry.getValue()); result.put(key, value); @@ -10851,10 +11149,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { String key = toString(entry.getKey()); Blob value = toBlob(entry.getValue()); result.put(key, value); @@ -10866,10 +11164,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { Long key = toLong(entry.getKey()); Long value = toLong(entry.getValue()); result.put(key, value); @@ -10881,10 +11179,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { Long key = toLong(entry.getKey()); Double value = toDouble(entry.getValue()); result.put(key, value); @@ -10896,10 +11194,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map> result = new HashMap>(); + Map map = (Map)object; + Map> result = new HashMap>(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { Long key = toLong(entry.getKey()); Set value = toSetOfString(entry.getValue()); result.put(key, value); @@ -10911,10 +11209,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { Types.VmOperations key = toVmOperations(entry.getKey()); String value = toString(entry.getValue()); result.put(key, value); @@ -10926,10 +11224,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { Bond key = toBond(entry.getKey()); Bond.Record value = toBondRecord(entry.getValue()); result.put(key, value); @@ -10941,10 +11239,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { DRTask key = toDRTask(entry.getKey()); DRTask.Record value = toDRTaskRecord(entry.getValue()); result.put(key, value); @@ -10956,10 +11254,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { GPUGroup key = toGPUGroup(entry.getKey()); GPUGroup.Record value = toGPUGroupRecord(entry.getValue()); result.put(key, value); @@ -10971,10 +11269,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { PBD key = toPBD(entry.getKey()); PBD.Record value = toPBDRecord(entry.getValue()); result.put(key, value); @@ -10986,10 +11284,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { PCI key = toPCI(entry.getKey()); PCI.Record value = toPCIRecord(entry.getValue()); result.put(key, value); @@ -11001,10 +11299,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { PGPU key = toPGPU(entry.getKey()); PGPU.Record value = toPGPURecord(entry.getValue()); result.put(key, value); @@ -11016,10 +11314,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { PIF key = toPIF(entry.getKey()); PIF.Record value = toPIFRecord(entry.getValue()); result.put(key, value); @@ -11031,10 +11329,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { PIFMetrics key = toPIFMetrics(entry.getKey()); PIFMetrics.Record value = toPIFMetricsRecord(entry.getValue()); result.put(key, value); @@ -11046,10 +11344,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { SM key = toSM(entry.getKey()); SM.Record value = toSMRecord(entry.getValue()); result.put(key, value); @@ -11061,10 +11359,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { SR key = toSR(entry.getKey()); SR.Record value = toSRRecord(entry.getValue()); result.put(key, value); @@ -11076,10 +11374,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { VBD key = toVBD(entry.getKey()); VBD.Record value = toVBDRecord(entry.getValue()); result.put(key, value); @@ -11091,10 +11389,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { VBDMetrics key = toVBDMetrics(entry.getKey()); VBDMetrics.Record value = toVBDMetricsRecord(entry.getValue()); result.put(key, value); @@ -11106,10 +11404,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { VDI key = toVDI(entry.getKey()); SR value = toSR(entry.getValue()); result.put(key, value); @@ -11121,10 +11419,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { VDI key = toVDI(entry.getKey()); VDI.Record value = toVDIRecord(entry.getValue()); result.put(key, value); @@ -11136,10 +11434,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { VGPU key = toVGPU(entry.getKey()); VGPU.Record value = toVGPURecord(entry.getValue()); result.put(key, value); @@ -11151,10 +11449,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { VIF key = toVIF(entry.getKey()); Network value = toNetwork(entry.getValue()); result.put(key, value); @@ -11166,10 +11464,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { VIF key = toVIF(entry.getKey()); VIF.Record value = toVIFRecord(entry.getValue()); result.put(key, value); @@ -11181,10 +11479,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { VIFMetrics key = toVIFMetrics(entry.getKey()); VIFMetrics.Record value = toVIFMetricsRecord(entry.getValue()); result.put(key, value); @@ -11196,10 +11494,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { VLAN key = toVLAN(entry.getKey()); VLAN.Record value = toVLANRecord(entry.getValue()); result.put(key, value); @@ -11211,10 +11509,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { VM key = toVM(entry.getKey()); String value = toString(entry.getValue()); result.put(key, value); @@ -11226,10 +11524,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map> result = new HashMap>(); + Map map = (Map)object; + Map> result = new HashMap>(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { VM key = toVM(entry.getKey()); Set value = toSetOfString(entry.getValue()); result.put(key, value); @@ -11241,10 +11539,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map> result = new HashMap>(); + Map map = (Map)object; + Map> result = new HashMap>(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { VM key = toVM(entry.getKey()); Map value = toMapOfStringString(entry.getValue()); result.put(key, value); @@ -11256,10 +11554,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { VM key = toVM(entry.getKey()); VM.Record value = toVMRecord(entry.getValue()); result.put(key, value); @@ -11271,10 +11569,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { VMPP key = toVMPP(entry.getKey()); VMPP.Record value = toVMPPRecord(entry.getValue()); result.put(key, value); @@ -11286,10 +11584,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { VMAppliance key = toVMAppliance(entry.getKey()); VMAppliance.Record value = toVMApplianceRecord(entry.getValue()); result.put(key, value); @@ -11301,10 +11599,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { VMGuestMetrics key = toVMGuestMetrics(entry.getKey()); VMGuestMetrics.Record value = toVMGuestMetricsRecord(entry.getValue()); result.put(key, value); @@ -11316,10 +11614,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { VMMetrics key = toVMMetrics(entry.getKey()); VMMetrics.Record value = toVMMetricsRecord(entry.getValue()); result.put(key, value); @@ -11331,10 +11629,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { Blob key = toBlob(entry.getKey()); Blob.Record value = toBlobRecord(entry.getValue()); result.put(key, value); @@ -11346,10 +11644,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { Console key = toConsole(entry.getKey()); Console.Record value = toConsoleRecord(entry.getValue()); result.put(key, value); @@ -11361,10 +11659,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { Crashdump key = toCrashdump(entry.getKey()); Crashdump.Record value = toCrashdumpRecord(entry.getValue()); result.put(key, value); @@ -11376,10 +11674,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map> result = new HashMap>(); + Map map = (Map)object; + Map> result = new HashMap>(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { Host key = toHost(entry.getKey()); Set value = toSetOfString(entry.getValue()); result.put(key, value); @@ -11391,10 +11689,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { Host key = toHost(entry.getKey()); Host.Record value = toHostRecord(entry.getValue()); result.put(key, value); @@ -11406,10 +11704,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { HostCpu key = toHostCpu(entry.getKey()); HostCpu.Record value = toHostCpuRecord(entry.getValue()); result.put(key, value); @@ -11421,10 +11719,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { HostCrashdump key = toHostCrashdump(entry.getKey()); HostCrashdump.Record value = toHostCrashdumpRecord(entry.getValue()); result.put(key, value); @@ -11436,10 +11734,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { HostMetrics key = toHostMetrics(entry.getKey()); HostMetrics.Record value = toHostMetricsRecord(entry.getValue()); result.put(key, value); @@ -11451,10 +11749,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { HostPatch key = toHostPatch(entry.getKey()); HostPatch.Record value = toHostPatchRecord(entry.getValue()); result.put(key, value); @@ -11466,10 +11764,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { Message key = toMessage(entry.getKey()); Message.Record value = toMessageRecord(entry.getValue()); result.put(key, value); @@ -11481,10 +11779,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { Network key = toNetwork(entry.getKey()); Network.Record value = toNetworkRecord(entry.getValue()); result.put(key, value); @@ -11496,10 +11794,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { Pool key = toPool(entry.getKey()); Pool.Record value = toPoolRecord(entry.getValue()); result.put(key, value); @@ -11511,10 +11809,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { PoolPatch key = toPoolPatch(entry.getKey()); PoolPatch.Record value = toPoolPatchRecord(entry.getValue()); result.put(key, value); @@ -11526,10 +11824,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { Role key = toRole(entry.getKey()); Role.Record value = toRoleRecord(entry.getValue()); result.put(key, value); @@ -11541,10 +11839,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { Secret key = toSecret(entry.getKey()); Secret.Record value = toSecretRecord(entry.getValue()); result.put(key, value); @@ -11556,10 +11854,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { Subject key = toSubject(entry.getKey()); Subject.Record value = toSubjectRecord(entry.getValue()); result.put(key, value); @@ -11571,10 +11869,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { Task key = toTask(entry.getKey()); Task.Record value = toTaskRecord(entry.getValue()); result.put(key, value); @@ -11586,10 +11884,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; - Map result = new HashMap(); + Map map = (Map)object; + Map result = new HashMap(); Set entries = map.entrySet(); - for(Map.Entry entry: entries) { + for (Map.Entry entry : entries) { Tunnel key = toTunnel(entry.getKey()); Tunnel.Record value = toTunnelRecord(entry.getValue()); result.put(key, value); @@ -11601,310 +11899,310 @@ public class Types if (object == null) { return null; } - return new Bond((String) object); + return new Bond((String)object); } public static DRTask toDRTask(Object object) { if (object == null) { return null; } - return new DRTask((String) object); + return new DRTask((String)object); } public static GPUGroup toGPUGroup(Object object) { if (object == null) { return null; } - return new GPUGroup((String) object); + return new GPUGroup((String)object); } public static PBD toPBD(Object object) { if (object == null) { return null; } - return new PBD((String) object); + return new PBD((String)object); } public static PCI toPCI(Object object) { if (object == null) { return null; } - return new PCI((String) object); + return new PCI((String)object); } public static PGPU toPGPU(Object object) { if (object == null) { return null; } - return new PGPU((String) object); + return new PGPU((String)object); } public static PIF toPIF(Object object) { if (object == null) { return null; } - return new PIF((String) object); + return new PIF((String)object); } public static PIFMetrics toPIFMetrics(Object object) { if (object == null) { return null; } - return new PIFMetrics((String) object); + return new PIFMetrics((String)object); } public static SM toSM(Object object) { if (object == null) { return null; } - return new SM((String) object); + return new SM((String)object); } public static SR toSR(Object object) { if (object == null) { return null; } - return new SR((String) object); + return new SR((String)object); } public static VBD toVBD(Object object) { if (object == null) { return null; } - return new VBD((String) object); + return new VBD((String)object); } public static VBDMetrics toVBDMetrics(Object object) { if (object == null) { return null; } - return new VBDMetrics((String) object); + return new VBDMetrics((String)object); } public static VDI toVDI(Object object) { if (object == null) { return null; } - return new VDI((String) object); + return new VDI((String)object); } public static VGPU toVGPU(Object object) { if (object == null) { return null; } - return new VGPU((String) object); + return new VGPU((String)object); } public static VIF toVIF(Object object) { if (object == null) { return null; } - return new VIF((String) object); + return new VIF((String)object); } public static VIFMetrics toVIFMetrics(Object object) { if (object == null) { return null; } - return new VIFMetrics((String) object); + return new VIFMetrics((String)object); } public static VLAN toVLAN(Object object) { if (object == null) { return null; } - return new VLAN((String) object); + return new VLAN((String)object); } public static VM toVM(Object object) { if (object == null) { return null; } - return new VM((String) object); + return new VM((String)object); } public static VMPP toVMPP(Object object) { if (object == null) { return null; } - return new VMPP((String) object); + return new VMPP((String)object); } public static VMAppliance toVMAppliance(Object object) { if (object == null) { return null; } - return new VMAppliance((String) object); + return new VMAppliance((String)object); } public static VMGuestMetrics toVMGuestMetrics(Object object) { if (object == null) { return null; } - return new VMGuestMetrics((String) object); + return new VMGuestMetrics((String)object); } public static VMMetrics toVMMetrics(Object object) { if (object == null) { return null; } - return new VMMetrics((String) object); + return new VMMetrics((String)object); } public static VTPM toVTPM(Object object) { if (object == null) { return null; } - return new VTPM((String) object); + return new VTPM((String)object); } public static Blob toBlob(Object object) { if (object == null) { return null; } - return new Blob((String) object); + return new Blob((String)object); } public static Console toConsole(Object object) { if (object == null) { return null; } - return new Console((String) object); + return new Console((String)object); } public static Crashdump toCrashdump(Object object) { if (object == null) { return null; } - return new Crashdump((String) object); + return new Crashdump((String)object); } public static Host toHost(Object object) { if (object == null) { return null; } - return new Host((String) object); + return new Host((String)object); } public static HostCpu toHostCpu(Object object) { if (object == null) { return null; } - return new HostCpu((String) object); + return new HostCpu((String)object); } public static HostCrashdump toHostCrashdump(Object object) { if (object == null) { return null; } - return new HostCrashdump((String) object); + return new HostCrashdump((String)object); } public static HostMetrics toHostMetrics(Object object) { if (object == null) { return null; } - return new HostMetrics((String) object); + return new HostMetrics((String)object); } public static HostPatch toHostPatch(Object object) { if (object == null) { return null; } - return new HostPatch((String) object); + return new HostPatch((String)object); } public static Message toMessage(Object object) { if (object == null) { return null; } - return new Message((String) object); + return new Message((String)object); } public static Network toNetwork(Object object) { if (object == null) { return null; } - return new Network((String) object); + return new Network((String)object); } public static Pool toPool(Object object) { if (object == null) { return null; } - return new Pool((String) object); + return new Pool((String)object); } public static PoolPatch toPoolPatch(Object object) { if (object == null) { return null; } - return new PoolPatch((String) object); + return new PoolPatch((String)object); } public static Role toRole(Object object) { if (object == null) { return null; } - return new Role((String) object); + return new Role((String)object); } public static Secret toSecret(Object object) { if (object == null) { return null; } - return new Secret((String) object); + return new Secret((String)object); } public static Session toSession(Object object) { if (object == null) { return null; } - return new Session((String) object); + return new Session((String)object); } public static Subject toSubject(Object object) { if (object == null) { return null; } - return new Subject((String) object); + return new Subject((String)object); } public static Task toTask(Object object) { if (object == null) { return null; } - return new Task((String) object); + return new Task((String)object); } public static Tunnel toTunnel(Object object) { if (object == null) { return null; } - return new Tunnel((String) object); + return new Tunnel((String)object); } public static User toUser(Object object) { if (object == null) { return null; } - return new User((String) object); + return new User((String)object); } public static Bond.Record toBondRecord(Object object) { if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; Bond.Record record = new Bond.Record(); - record.uuid = toString(map.get("uuid")); - record.master = toPIF(map.get("master")); - record.slaves = toSetOfPIF(map.get("slaves")); - record.otherConfig = toMapOfStringString(map.get("other_config")); - record.primarySlave = toPIF(map.get("primary_slave")); - record.mode = toBondMode(map.get("mode")); - record.properties = toMapOfStringString(map.get("properties")); - record.linksUp = toLong(map.get("links_up")); + record.uuid = toString(map.get("uuid")); + record.master = toPIF(map.get("master")); + record.slaves = toSetOfPIF(map.get("slaves")); + record.otherConfig = toMapOfStringString(map.get("other_config")); + record.primarySlave = toPIF(map.get("primary_slave")); + record.mode = toBondMode(map.get("mode")); + record.properties = toMapOfStringString(map.get("properties")); + record.linksUp = toLong(map.get("links_up")); return record; } @@ -11912,10 +12210,10 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; DRTask.Record record = new DRTask.Record(); - record.uuid = toString(map.get("uuid")); - record.introducedSRs = toSetOfSR(map.get("introduced_SRs")); + record.uuid = toString(map.get("uuid")); + record.introducedSRs = toSetOfSR(map.get("introduced_SRs")); return record; } @@ -11923,15 +12221,15 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; GPUGroup.Record record = new GPUGroup.Record(); - record.uuid = toString(map.get("uuid")); - record.nameLabel = toString(map.get("name_label")); - record.nameDescription = toString(map.get("name_description")); - record.PGPUs = toSetOfPGPU(map.get("PGPUs")); - record.VGPUs = toSetOfVGPU(map.get("VGPUs")); - record.GPUTypes = toSetOfString(map.get("GPU_types")); - record.otherConfig = toMapOfStringString(map.get("other_config")); + record.uuid = toString(map.get("uuid")); + record.nameLabel = toString(map.get("name_label")); + record.nameDescription = toString(map.get("name_description")); + record.PGPUs = toSetOfPGPU(map.get("PGPUs")); + record.VGPUs = toSetOfVGPU(map.get("VGPUs")); + record.GPUTypes = toSetOfString(map.get("GPU_types")); + record.otherConfig = toMapOfStringString(map.get("other_config")); return record; } @@ -11939,14 +12237,14 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; PBD.Record record = new PBD.Record(); - record.uuid = toString(map.get("uuid")); - record.host = toHost(map.get("host")); - record.SR = toSR(map.get("SR")); - record.deviceConfig = toMapOfStringString(map.get("device_config")); - record.currentlyAttached = toBoolean(map.get("currently_attached")); - record.otherConfig = toMapOfStringString(map.get("other_config")); + record.uuid = toString(map.get("uuid")); + record.host = toHost(map.get("host")); + record.SR = toSR(map.get("SR")); + record.deviceConfig = toMapOfStringString(map.get("device_config")); + record.currentlyAttached = toBoolean(map.get("currently_attached")); + record.otherConfig = toMapOfStringString(map.get("other_config")); return record; } @@ -11954,16 +12252,16 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; PCI.Record record = new PCI.Record(); - record.uuid = toString(map.get("uuid")); - record.clazzName = toString(map.get("class_name")); - record.vendorName = toString(map.get("vendor_name")); - record.deviceName = toString(map.get("device_name")); - record.host = toHost(map.get("host")); - record.pciId = toString(map.get("pci_id")); - record.dependencies = toSetOfPCI(map.get("dependencies")); - record.otherConfig = toMapOfStringString(map.get("other_config")); + record.uuid = toString(map.get("uuid")); + record.clazzName = toString(map.get("class_name")); + record.vendorName = toString(map.get("vendor_name")); + record.deviceName = toString(map.get("device_name")); + record.host = toHost(map.get("host")); + record.pciId = toString(map.get("pci_id")); + record.dependencies = toSetOfPCI(map.get("dependencies")); + record.otherConfig = toMapOfStringString(map.get("other_config")); return record; } @@ -11971,13 +12269,13 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; PGPU.Record record = new PGPU.Record(); - record.uuid = toString(map.get("uuid")); - record.PCI = toPCI(map.get("PCI")); - record.GPUGroup = toGPUGroup(map.get("GPU_group")); - record.host = toHost(map.get("host")); - record.otherConfig = toMapOfStringString(map.get("other_config")); + record.uuid = toString(map.get("uuid")); + record.PCI = toPCI(map.get("PCI")); + record.GPUGroup = toGPUGroup(map.get("GPU_group")); + record.host = toHost(map.get("host")); + record.otherConfig = toMapOfStringString(map.get("other_config")); return record; } @@ -11985,36 +12283,36 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; PIF.Record record = new PIF.Record(); - record.uuid = toString(map.get("uuid")); - record.device = toString(map.get("device")); - record.network = toNetwork(map.get("network")); - record.host = toHost(map.get("host")); - record.MAC = toString(map.get("MAC")); - record.MTU = toLong(map.get("MTU")); - record.VLAN = toLong(map.get("VLAN")); - record.metrics = toPIFMetrics(map.get("metrics")); - record.physical = toBoolean(map.get("physical")); - record.currentlyAttached = toBoolean(map.get("currently_attached")); - record.ipConfigurationMode = toIpConfigurationMode(map.get("ip_configuration_mode")); - record.IP = toString(map.get("IP")); - record.netmask = toString(map.get("netmask")); - record.gateway = toString(map.get("gateway")); - record.DNS = toString(map.get("DNS")); - record.bondSlaveOf = toBond(map.get("bond_slave_of")); - record.bondMasterOf = toSetOfBond(map.get("bond_master_of")); - record.VLANMasterOf = toVLAN(map.get("VLAN_master_of")); - record.VLANSlaveOf = toSetOfVLAN(map.get("VLAN_slave_of")); - record.management = toBoolean(map.get("management")); - record.otherConfig = toMapOfStringString(map.get("other_config")); - record.disallowUnplug = toBoolean(map.get("disallow_unplug")); - record.tunnelAccessPIFOf = toSetOfTunnel(map.get("tunnel_access_PIF_of")); - record.tunnelTransportPIFOf = toSetOfTunnel(map.get("tunnel_transport_PIF_of")); - record.ipv6ConfigurationMode = toIpv6ConfigurationMode(map.get("ipv6_configuration_mode")); - record.IPv6 = toSetOfString(map.get("IPv6")); - record.ipv6Gateway = toString(map.get("ipv6_gateway")); - record.primaryAddressType = toPrimaryAddressType(map.get("primary_address_type")); + record.uuid = toString(map.get("uuid")); + record.device = toString(map.get("device")); + record.network = toNetwork(map.get("network")); + record.host = toHost(map.get("host")); + record.MAC = toString(map.get("MAC")); + record.MTU = toLong(map.get("MTU")); + record.VLAN = toLong(map.get("VLAN")); + record.metrics = toPIFMetrics(map.get("metrics")); + record.physical = toBoolean(map.get("physical")); + record.currentlyAttached = toBoolean(map.get("currently_attached")); + record.ipConfigurationMode = toIpConfigurationMode(map.get("ip_configuration_mode")); + record.IP = toString(map.get("IP")); + record.netmask = toString(map.get("netmask")); + record.gateway = toString(map.get("gateway")); + record.DNS = toString(map.get("DNS")); + record.bondSlaveOf = toBond(map.get("bond_slave_of")); + record.bondMasterOf = toSetOfBond(map.get("bond_master_of")); + record.VLANMasterOf = toVLAN(map.get("VLAN_master_of")); + record.VLANSlaveOf = toSetOfVLAN(map.get("VLAN_slave_of")); + record.management = toBoolean(map.get("management")); + record.otherConfig = toMapOfStringString(map.get("other_config")); + record.disallowUnplug = toBoolean(map.get("disallow_unplug")); + record.tunnelAccessPIFOf = toSetOfTunnel(map.get("tunnel_access_PIF_of")); + record.tunnelTransportPIFOf = toSetOfTunnel(map.get("tunnel_transport_PIF_of")); + record.ipv6ConfigurationMode = toIpv6ConfigurationMode(map.get("ipv6_configuration_mode")); + record.IPv6 = toSetOfString(map.get("IPv6")); + record.ipv6Gateway = toString(map.get("ipv6_gateway")); + record.primaryAddressType = toPrimaryAddressType(map.get("primary_address_type")); return record; } @@ -12022,21 +12320,21 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; PIFMetrics.Record record = new PIFMetrics.Record(); - record.uuid = toString(map.get("uuid")); - record.ioReadKbs = toDouble(map.get("io_read_kbs")); - record.ioWriteKbs = toDouble(map.get("io_write_kbs")); - record.carrier = toBoolean(map.get("carrier")); - record.vendorId = toString(map.get("vendor_id")); - record.vendorName = toString(map.get("vendor_name")); - record.deviceId = toString(map.get("device_id")); - record.deviceName = toString(map.get("device_name")); - record.speed = toLong(map.get("speed")); - record.duplex = toBoolean(map.get("duplex")); - record.pciBusPath = toString(map.get("pci_bus_path")); - record.lastUpdated = toDate(map.get("last_updated")); - record.otherConfig = toMapOfStringString(map.get("other_config")); + record.uuid = toString(map.get("uuid")); + record.ioReadKbs = toDouble(map.get("io_read_kbs")); + record.ioWriteKbs = toDouble(map.get("io_write_kbs")); + record.carrier = toBoolean(map.get("carrier")); + record.vendorId = toString(map.get("vendor_id")); + record.vendorName = toString(map.get("vendor_name")); + record.deviceId = toString(map.get("device_id")); + record.deviceName = toString(map.get("device_name")); + record.speed = toLong(map.get("speed")); + record.duplex = toBoolean(map.get("duplex")); + record.pciBusPath = toString(map.get("pci_bus_path")); + record.lastUpdated = toDate(map.get("last_updated")); + record.otherConfig = toMapOfStringString(map.get("other_config")); return record; } @@ -12044,20 +12342,20 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; SM.Record record = new SM.Record(); - record.uuid = toString(map.get("uuid")); - record.nameLabel = toString(map.get("name_label")); - record.nameDescription = toString(map.get("name_description")); - record.type = toString(map.get("type")); - record.vendor = toString(map.get("vendor")); - record.copyright = toString(map.get("copyright")); - record.version = toString(map.get("version")); - record.requiredApiVersion = toString(map.get("required_api_version")); - record.configuration = toMapOfStringString(map.get("configuration")); - record.capabilities = toSetOfString(map.get("capabilities")); - record.otherConfig = toMapOfStringString(map.get("other_config")); - record.driverFilename = toString(map.get("driver_filename")); + record.uuid = toString(map.get("uuid")); + record.nameLabel = toString(map.get("name_label")); + record.nameDescription = toString(map.get("name_description")); + record.type = toString(map.get("type")); + record.vendor = toString(map.get("vendor")); + record.copyright = toString(map.get("copyright")); + record.version = toString(map.get("version")); + record.requiredApiVersion = toString(map.get("required_api_version")); + record.configuration = toMapOfStringString(map.get("configuration")); + record.capabilities = toSetOfString(map.get("capabilities")); + record.otherConfig = toMapOfStringString(map.get("other_config")); + record.driverFilename = toString(map.get("driver_filename")); return record; } @@ -12065,27 +12363,27 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; SR.Record record = new SR.Record(); - record.uuid = toString(map.get("uuid")); - record.nameLabel = toString(map.get("name_label")); - record.nameDescription = toString(map.get("name_description")); - record.allowedOperations = toSetOfStorageOperations(map.get("allowed_operations")); - record.currentOperations = toMapOfStringStorageOperations(map.get("current_operations")); - record.VDIs = toSetOfVDI(map.get("VDIs")); - record.PBDs = toSetOfPBD(map.get("PBDs")); - record.virtualAllocation = toLong(map.get("virtual_allocation")); - record.physicalUtilisation = toLong(map.get("physical_utilisation")); - record.physicalSize = toLong(map.get("physical_size")); - record.type = toString(map.get("type")); - record.contentType = toString(map.get("content_type")); - record.shared = toBoolean(map.get("shared")); - record.otherConfig = toMapOfStringString(map.get("other_config")); - record.tags = toSetOfString(map.get("tags")); - record.smConfig = toMapOfStringString(map.get("sm_config")); - record.blobs = toMapOfStringBlob(map.get("blobs")); - record.localCacheEnabled = toBoolean(map.get("local_cache_enabled")); - record.introducedBy = toDRTask(map.get("introduced_by")); + record.uuid = toString(map.get("uuid")); + record.nameLabel = toString(map.get("name_label")); + record.nameDescription = toString(map.get("name_description")); + record.allowedOperations = toSetOfStorageOperations(map.get("allowed_operations")); + record.currentOperations = toMapOfStringStorageOperations(map.get("current_operations")); + record.VDIs = toSetOfVDI(map.get("VDIs")); + record.PBDs = toSetOfPBD(map.get("PBDs")); + record.virtualAllocation = toLong(map.get("virtual_allocation")); + record.physicalUtilisation = toLong(map.get("physical_utilisation")); + record.physicalSize = toLong(map.get("physical_size")); + record.type = toString(map.get("type")); + record.contentType = toString(map.get("content_type")); + record.shared = toBoolean(map.get("shared")); + record.otherConfig = toMapOfStringString(map.get("other_config")); + record.tags = toSetOfString(map.get("tags")); + record.smConfig = toMapOfStringString(map.get("sm_config")); + record.blobs = toMapOfStringBlob(map.get("blobs")); + record.localCacheEnabled = toBoolean(map.get("local_cache_enabled")); + record.introducedBy = toDRTask(map.get("introduced_by")); return record; } @@ -12093,30 +12391,30 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; VBD.Record record = new VBD.Record(); - record.uuid = toString(map.get("uuid")); - record.allowedOperations = toSetOfVbdOperations(map.get("allowed_operations")); - record.currentOperations = toMapOfStringVbdOperations(map.get("current_operations")); - record.VM = toVM(map.get("VM")); - record.VDI = toVDI(map.get("VDI")); - record.device = toString(map.get("device")); - record.userdevice = toString(map.get("userdevice")); - record.bootable = toBoolean(map.get("bootable")); - record.mode = toVbdMode(map.get("mode")); - record.type = toVbdType(map.get("type")); - record.unpluggable = toBoolean(map.get("unpluggable")); - record.storageLock = toBoolean(map.get("storage_lock")); - record.empty = toBoolean(map.get("empty")); - record.otherConfig = toMapOfStringString(map.get("other_config")); - record.currentlyAttached = toBoolean(map.get("currently_attached")); - record.statusCode = toLong(map.get("status_code")); - record.statusDetail = toString(map.get("status_detail")); - record.runtimeProperties = toMapOfStringString(map.get("runtime_properties")); - record.qosAlgorithmType = toString(map.get("qos_algorithm_type")); - record.qosAlgorithmParams = toMapOfStringString(map.get("qos_algorithm_params")); - record.qosSupportedAlgorithms = toSetOfString(map.get("qos_supported_algorithms")); - record.metrics = toVBDMetrics(map.get("metrics")); + record.uuid = toString(map.get("uuid")); + record.allowedOperations = toSetOfVbdOperations(map.get("allowed_operations")); + record.currentOperations = toMapOfStringVbdOperations(map.get("current_operations")); + record.VM = toVM(map.get("VM")); + record.VDI = toVDI(map.get("VDI")); + record.device = toString(map.get("device")); + record.userdevice = toString(map.get("userdevice")); + record.bootable = toBoolean(map.get("bootable")); + record.mode = toVbdMode(map.get("mode")); + record.type = toVbdType(map.get("type")); + record.unpluggable = toBoolean(map.get("unpluggable")); + record.storageLock = toBoolean(map.get("storage_lock")); + record.empty = toBoolean(map.get("empty")); + record.otherConfig = toMapOfStringString(map.get("other_config")); + record.currentlyAttached = toBoolean(map.get("currently_attached")); + record.statusCode = toLong(map.get("status_code")); + record.statusDetail = toString(map.get("status_detail")); + record.runtimeProperties = toMapOfStringString(map.get("runtime_properties")); + record.qosAlgorithmType = toString(map.get("qos_algorithm_type")); + record.qosAlgorithmParams = toMapOfStringString(map.get("qos_algorithm_params")); + record.qosSupportedAlgorithms = toSetOfString(map.get("qos_supported_algorithms")); + record.metrics = toVBDMetrics(map.get("metrics")); return record; } @@ -12124,13 +12422,13 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; VBDMetrics.Record record = new VBDMetrics.Record(); - record.uuid = toString(map.get("uuid")); - record.ioReadKbs = toDouble(map.get("io_read_kbs")); - record.ioWriteKbs = toDouble(map.get("io_write_kbs")); - record.lastUpdated = toDate(map.get("last_updated")); - record.otherConfig = toMapOfStringString(map.get("other_config")); + record.uuid = toString(map.get("uuid")); + record.ioReadKbs = toDouble(map.get("io_read_kbs")); + record.ioWriteKbs = toDouble(map.get("io_write_kbs")); + record.lastUpdated = toDate(map.get("last_updated")); + record.otherConfig = toMapOfStringString(map.get("other_config")); return record; } @@ -12138,38 +12436,38 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; VDI.Record record = new VDI.Record(); - record.uuid = toString(map.get("uuid")); - record.nameLabel = toString(map.get("name_label")); - record.nameDescription = toString(map.get("name_description")); - record.allowedOperations = toSetOfVdiOperations(map.get("allowed_operations")); - record.currentOperations = toMapOfStringVdiOperations(map.get("current_operations")); - record.SR = toSR(map.get("SR")); - record.VBDs = toSetOfVBD(map.get("VBDs")); - record.crashDumps = toSetOfCrashdump(map.get("crash_dumps")); - record.virtualSize = toLong(map.get("virtual_size")); - record.physicalUtilisation = toLong(map.get("physical_utilisation")); - record.type = toVdiType(map.get("type")); - record.sharable = toBoolean(map.get("sharable")); - record.readOnly = toBoolean(map.get("read_only")); - record.otherConfig = toMapOfStringString(map.get("other_config")); - record.storageLock = toBoolean(map.get("storage_lock")); - record.location = toString(map.get("location")); - record.managed = toBoolean(map.get("managed")); - record.missing = toBoolean(map.get("missing")); - record.parent = toVDI(map.get("parent")); - record.xenstoreData = toMapOfStringString(map.get("xenstore_data")); - record.smConfig = toMapOfStringString(map.get("sm_config")); - record.isASnapshot = toBoolean(map.get("is_a_snapshot")); - record.snapshotOf = toVDI(map.get("snapshot_of")); - record.snapshots = toSetOfVDI(map.get("snapshots")); - record.snapshotTime = toDate(map.get("snapshot_time")); - record.tags = toSetOfString(map.get("tags")); - record.allowCaching = toBoolean(map.get("allow_caching")); - record.onBoot = toOnBoot(map.get("on_boot")); - record.metadataOfPool = toPool(map.get("metadata_of_pool")); - record.metadataLatest = toBoolean(map.get("metadata_latest")); + record.uuid = toString(map.get("uuid")); + record.nameLabel = toString(map.get("name_label")); + record.nameDescription = toString(map.get("name_description")); + record.allowedOperations = toSetOfVdiOperations(map.get("allowed_operations")); + record.currentOperations = toMapOfStringVdiOperations(map.get("current_operations")); + record.SR = toSR(map.get("SR")); + record.VBDs = toSetOfVBD(map.get("VBDs")); + record.crashDumps = toSetOfCrashdump(map.get("crash_dumps")); + record.virtualSize = toLong(map.get("virtual_size")); + record.physicalUtilisation = toLong(map.get("physical_utilisation")); + record.type = toVdiType(map.get("type")); + record.sharable = toBoolean(map.get("sharable")); + record.readOnly = toBoolean(map.get("read_only")); + record.otherConfig = toMapOfStringString(map.get("other_config")); + record.storageLock = toBoolean(map.get("storage_lock")); + record.location = toString(map.get("location")); + record.managed = toBoolean(map.get("managed")); + record.missing = toBoolean(map.get("missing")); + record.parent = toVDI(map.get("parent")); + record.xenstoreData = toMapOfStringString(map.get("xenstore_data")); + record.smConfig = toMapOfStringString(map.get("sm_config")); + record.isASnapshot = toBoolean(map.get("is_a_snapshot")); + record.snapshotOf = toVDI(map.get("snapshot_of")); + record.snapshots = toSetOfVDI(map.get("snapshots")); + record.snapshotTime = toDate(map.get("snapshot_time")); + record.tags = toSetOfString(map.get("tags")); + record.allowCaching = toBoolean(map.get("allow_caching")); + record.onBoot = toOnBoot(map.get("on_boot")); + record.metadataOfPool = toPool(map.get("metadata_of_pool")); + record.metadataLatest = toBoolean(map.get("metadata_latest")); return record; } @@ -12177,14 +12475,14 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; VGPU.Record record = new VGPU.Record(); - record.uuid = toString(map.get("uuid")); - record.VM = toVM(map.get("VM")); - record.GPUGroup = toGPUGroup(map.get("GPU_group")); - record.device = toString(map.get("device")); - record.currentlyAttached = toBoolean(map.get("currently_attached")); - record.otherConfig = toMapOfStringString(map.get("other_config")); + record.uuid = toString(map.get("uuid")); + record.VM = toVM(map.get("VM")); + record.GPUGroup = toGPUGroup(map.get("GPU_group")); + record.device = toString(map.get("device")); + record.currentlyAttached = toBoolean(map.get("currently_attached")); + record.otherConfig = toMapOfStringString(map.get("other_config")); return record; } @@ -12192,29 +12490,29 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; VIF.Record record = new VIF.Record(); - record.uuid = toString(map.get("uuid")); - record.allowedOperations = toSetOfVifOperations(map.get("allowed_operations")); - record.currentOperations = toMapOfStringVifOperations(map.get("current_operations")); - record.device = toString(map.get("device")); - record.network = toNetwork(map.get("network")); - record.VM = toVM(map.get("VM")); - record.MAC = toString(map.get("MAC")); - record.MTU = toLong(map.get("MTU")); - record.otherConfig = toMapOfStringString(map.get("other_config")); - record.currentlyAttached = toBoolean(map.get("currently_attached")); - record.statusCode = toLong(map.get("status_code")); - record.statusDetail = toString(map.get("status_detail")); - record.runtimeProperties = toMapOfStringString(map.get("runtime_properties")); - record.qosAlgorithmType = toString(map.get("qos_algorithm_type")); - record.qosAlgorithmParams = toMapOfStringString(map.get("qos_algorithm_params")); - record.qosSupportedAlgorithms = toSetOfString(map.get("qos_supported_algorithms")); - record.metrics = toVIFMetrics(map.get("metrics")); - record.MACAutogenerated = toBoolean(map.get("MAC_autogenerated")); - record.lockingMode = toVifLockingMode(map.get("locking_mode")); - record.ipv4Allowed = toSetOfString(map.get("ipv4_allowed")); - record.ipv6Allowed = toSetOfString(map.get("ipv6_allowed")); + record.uuid = toString(map.get("uuid")); + record.allowedOperations = toSetOfVifOperations(map.get("allowed_operations")); + record.currentOperations = toMapOfStringVifOperations(map.get("current_operations")); + record.device = toString(map.get("device")); + record.network = toNetwork(map.get("network")); + record.VM = toVM(map.get("VM")); + record.MAC = toString(map.get("MAC")); + record.MTU = toLong(map.get("MTU")); + record.otherConfig = toMapOfStringString(map.get("other_config")); + record.currentlyAttached = toBoolean(map.get("currently_attached")); + record.statusCode = toLong(map.get("status_code")); + record.statusDetail = toString(map.get("status_detail")); + record.runtimeProperties = toMapOfStringString(map.get("runtime_properties")); + record.qosAlgorithmType = toString(map.get("qos_algorithm_type")); + record.qosAlgorithmParams = toMapOfStringString(map.get("qos_algorithm_params")); + record.qosSupportedAlgorithms = toSetOfString(map.get("qos_supported_algorithms")); + record.metrics = toVIFMetrics(map.get("metrics")); + record.MACAutogenerated = toBoolean(map.get("MAC_autogenerated")); + record.lockingMode = toVifLockingMode(map.get("locking_mode")); + record.ipv4Allowed = toSetOfString(map.get("ipv4_allowed")); + record.ipv6Allowed = toSetOfString(map.get("ipv6_allowed")); return record; } @@ -12222,13 +12520,13 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; VIFMetrics.Record record = new VIFMetrics.Record(); - record.uuid = toString(map.get("uuid")); - record.ioReadKbs = toDouble(map.get("io_read_kbs")); - record.ioWriteKbs = toDouble(map.get("io_write_kbs")); - record.lastUpdated = toDate(map.get("last_updated")); - record.otherConfig = toMapOfStringString(map.get("other_config")); + record.uuid = toString(map.get("uuid")); + record.ioReadKbs = toDouble(map.get("io_read_kbs")); + record.ioWriteKbs = toDouble(map.get("io_write_kbs")); + record.lastUpdated = toDate(map.get("last_updated")); + record.otherConfig = toMapOfStringString(map.get("other_config")); return record; } @@ -12236,13 +12534,13 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; VLAN.Record record = new VLAN.Record(); - record.uuid = toString(map.get("uuid")); - record.taggedPIF = toPIF(map.get("tagged_PIF")); - record.untaggedPIF = toPIF(map.get("untagged_PIF")); - record.tag = toLong(map.get("tag")); - record.otherConfig = toMapOfStringString(map.get("other_config")); + record.uuid = toString(map.get("uuid")); + record.taggedPIF = toPIF(map.get("tagged_PIF")); + record.untaggedPIF = toPIF(map.get("untagged_PIF")); + record.tag = toLong(map.get("tag")); + record.otherConfig = toMapOfStringString(map.get("other_config")); return record; } @@ -12250,82 +12548,82 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; VM.Record record = new VM.Record(); - record.uuid = toString(map.get("uuid")); - record.allowedOperations = toSetOfVmOperations(map.get("allowed_operations")); - record.currentOperations = toMapOfStringVmOperations(map.get("current_operations")); - record.powerState = toVmPowerState(map.get("power_state")); - record.nameLabel = toString(map.get("name_label")); - record.nameDescription = toString(map.get("name_description")); - record.userVersion = toLong(map.get("user_version")); - record.isATemplate = toBoolean(map.get("is_a_template")); - record.suspendVDI = toVDI(map.get("suspend_VDI")); - record.residentOn = toHost(map.get("resident_on")); - record.affinity = toHost(map.get("affinity")); - record.memoryOverhead = toLong(map.get("memory_overhead")); - record.memoryTarget = toLong(map.get("memory_target")); - record.memoryStaticMax = toLong(map.get("memory_static_max")); - record.memoryDynamicMax = toLong(map.get("memory_dynamic_max")); - record.memoryDynamicMin = toLong(map.get("memory_dynamic_min")); - record.memoryStaticMin = toLong(map.get("memory_static_min")); - record.VCPUsParams = toMapOfStringString(map.get("VCPUs_params")); - record.VCPUsMax = toLong(map.get("VCPUs_max")); - record.VCPUsAtStartup = toLong(map.get("VCPUs_at_startup")); - record.actionsAfterShutdown = toOnNormalExit(map.get("actions_after_shutdown")); - record.actionsAfterReboot = toOnNormalExit(map.get("actions_after_reboot")); - record.actionsAfterCrash = toOnCrashBehaviour(map.get("actions_after_crash")); - record.consoles = toSetOfConsole(map.get("consoles")); - record.VIFs = toSetOfVIF(map.get("VIFs")); - record.VBDs = toSetOfVBD(map.get("VBDs")); - record.crashDumps = toSetOfCrashdump(map.get("crash_dumps")); - record.VTPMs = toSetOfVTPM(map.get("VTPMs")); - record.PVBootloader = toString(map.get("PV_bootloader")); - record.PVKernel = toString(map.get("PV_kernel")); - record.PVRamdisk = toString(map.get("PV_ramdisk")); - record.PVArgs = toString(map.get("PV_args")); - record.PVBootloaderArgs = toString(map.get("PV_bootloader_args")); - record.PVLegacyArgs = toString(map.get("PV_legacy_args")); - record.HVMBootPolicy = toString(map.get("HVM_boot_policy")); - record.HVMBootParams = toMapOfStringString(map.get("HVM_boot_params")); - record.HVMShadowMultiplier = toDouble(map.get("HVM_shadow_multiplier")); - record.platform = toMapOfStringString(map.get("platform")); - record.PCIBus = toString(map.get("PCI_bus")); - record.otherConfig = toMapOfStringString(map.get("other_config")); - record.domid = toLong(map.get("domid")); - record.domarch = toString(map.get("domarch")); - record.lastBootCPUFlags = toMapOfStringString(map.get("last_boot_CPU_flags")); - record.isControlDomain = toBoolean(map.get("is_control_domain")); - record.metrics = toVMMetrics(map.get("metrics")); - record.guestMetrics = toVMGuestMetrics(map.get("guest_metrics")); - record.lastBootedRecord = toString(map.get("last_booted_record")); - record.recommendations = toString(map.get("recommendations")); - record.xenstoreData = toMapOfStringString(map.get("xenstore_data")); - record.haAlwaysRun = toBoolean(map.get("ha_always_run")); - record.haRestartPriority = toString(map.get("ha_restart_priority")); - record.isASnapshot = toBoolean(map.get("is_a_snapshot")); - record.snapshotOf = toVM(map.get("snapshot_of")); - record.snapshots = toSetOfVM(map.get("snapshots")); - record.snapshotTime = toDate(map.get("snapshot_time")); - record.transportableSnapshotId = toString(map.get("transportable_snapshot_id")); - record.blobs = toMapOfStringBlob(map.get("blobs")); - record.tags = toSetOfString(map.get("tags")); - record.blockedOperations = toMapOfVmOperationsString(map.get("blocked_operations")); - record.snapshotInfo = toMapOfStringString(map.get("snapshot_info")); - record.snapshotMetadata = toString(map.get("snapshot_metadata")); - record.parent = toVM(map.get("parent")); - record.children = toSetOfVM(map.get("children")); - record.biosStrings = toMapOfStringString(map.get("bios_strings")); - record.protectionPolicy = toVMPP(map.get("protection_policy")); - record.isSnapshotFromVmpp = toBoolean(map.get("is_snapshot_from_vmpp")); - record.appliance = toVMAppliance(map.get("appliance")); - record.startDelay = toLong(map.get("start_delay")); - record.shutdownDelay = toLong(map.get("shutdown_delay")); - record.order = toLong(map.get("order")); - record.VGPUs = toSetOfVGPU(map.get("VGPUs")); - record.attachedPCIs = toSetOfPCI(map.get("attached_PCIs")); - record.suspendSR = toSR(map.get("suspend_SR")); - record.version = toLong(map.get("version")); + record.uuid = toString(map.get("uuid")); + record.allowedOperations = toSetOfVmOperations(map.get("allowed_operations")); + record.currentOperations = toMapOfStringVmOperations(map.get("current_operations")); + record.powerState = toVmPowerState(map.get("power_state")); + record.nameLabel = toString(map.get("name_label")); + record.nameDescription = toString(map.get("name_description")); + record.userVersion = toLong(map.get("user_version")); + record.isATemplate = toBoolean(map.get("is_a_template")); + record.suspendVDI = toVDI(map.get("suspend_VDI")); + record.residentOn = toHost(map.get("resident_on")); + record.affinity = toHost(map.get("affinity")); + record.memoryOverhead = toLong(map.get("memory_overhead")); + record.memoryTarget = toLong(map.get("memory_target")); + record.memoryStaticMax = toLong(map.get("memory_static_max")); + record.memoryDynamicMax = toLong(map.get("memory_dynamic_max")); + record.memoryDynamicMin = toLong(map.get("memory_dynamic_min")); + record.memoryStaticMin = toLong(map.get("memory_static_min")); + record.VCPUsParams = toMapOfStringString(map.get("VCPUs_params")); + record.VCPUsMax = toLong(map.get("VCPUs_max")); + record.VCPUsAtStartup = toLong(map.get("VCPUs_at_startup")); + record.actionsAfterShutdown = toOnNormalExit(map.get("actions_after_shutdown")); + record.actionsAfterReboot = toOnNormalExit(map.get("actions_after_reboot")); + record.actionsAfterCrash = toOnCrashBehaviour(map.get("actions_after_crash")); + record.consoles = toSetOfConsole(map.get("consoles")); + record.VIFs = toSetOfVIF(map.get("VIFs")); + record.VBDs = toSetOfVBD(map.get("VBDs")); + record.crashDumps = toSetOfCrashdump(map.get("crash_dumps")); + record.VTPMs = toSetOfVTPM(map.get("VTPMs")); + record.PVBootloader = toString(map.get("PV_bootloader")); + record.PVKernel = toString(map.get("PV_kernel")); + record.PVRamdisk = toString(map.get("PV_ramdisk")); + record.PVArgs = toString(map.get("PV_args")); + record.PVBootloaderArgs = toString(map.get("PV_bootloader_args")); + record.PVLegacyArgs = toString(map.get("PV_legacy_args")); + record.HVMBootPolicy = toString(map.get("HVM_boot_policy")); + record.HVMBootParams = toMapOfStringString(map.get("HVM_boot_params")); + record.HVMShadowMultiplier = toDouble(map.get("HVM_shadow_multiplier")); + record.platform = toMapOfStringString(map.get("platform")); + record.PCIBus = toString(map.get("PCI_bus")); + record.otherConfig = toMapOfStringString(map.get("other_config")); + record.domid = toLong(map.get("domid")); + record.domarch = toString(map.get("domarch")); + record.lastBootCPUFlags = toMapOfStringString(map.get("last_boot_CPU_flags")); + record.isControlDomain = toBoolean(map.get("is_control_domain")); + record.metrics = toVMMetrics(map.get("metrics")); + record.guestMetrics = toVMGuestMetrics(map.get("guest_metrics")); + record.lastBootedRecord = toString(map.get("last_booted_record")); + record.recommendations = toString(map.get("recommendations")); + record.xenstoreData = toMapOfStringString(map.get("xenstore_data")); + record.haAlwaysRun = toBoolean(map.get("ha_always_run")); + record.haRestartPriority = toString(map.get("ha_restart_priority")); + record.isASnapshot = toBoolean(map.get("is_a_snapshot")); + record.snapshotOf = toVM(map.get("snapshot_of")); + record.snapshots = toSetOfVM(map.get("snapshots")); + record.snapshotTime = toDate(map.get("snapshot_time")); + record.transportableSnapshotId = toString(map.get("transportable_snapshot_id")); + record.blobs = toMapOfStringBlob(map.get("blobs")); + record.tags = toSetOfString(map.get("tags")); + record.blockedOperations = toMapOfVmOperationsString(map.get("blocked_operations")); + record.snapshotInfo = toMapOfStringString(map.get("snapshot_info")); + record.snapshotMetadata = toString(map.get("snapshot_metadata")); + record.parent = toVM(map.get("parent")); + record.children = toSetOfVM(map.get("children")); + record.biosStrings = toMapOfStringString(map.get("bios_strings")); + record.protectionPolicy = toVMPP(map.get("protection_policy")); + record.isSnapshotFromVmpp = toBoolean(map.get("is_snapshot_from_vmpp")); + record.appliance = toVMAppliance(map.get("appliance")); + record.startDelay = toLong(map.get("start_delay")); + record.shutdownDelay = toLong(map.get("shutdown_delay")); + record.order = toLong(map.get("order")); + record.VGPUs = toSetOfVGPU(map.get("VGPUs")); + record.attachedPCIs = toSetOfPCI(map.get("attached_PCIs")); + record.suspendSR = toSR(map.get("suspend_SR")); + record.version = toLong(map.get("version")); return record; } @@ -12333,28 +12631,28 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; VMPP.Record record = new VMPP.Record(); - record.uuid = toString(map.get("uuid")); - record.nameLabel = toString(map.get("name_label")); - record.nameDescription = toString(map.get("name_description")); - record.isPolicyEnabled = toBoolean(map.get("is_policy_enabled")); - record.backupType = toVmppBackupType(map.get("backup_type")); - record.backupRetentionValue = toLong(map.get("backup_retention_value")); - record.backupFrequency = toVmppBackupFrequency(map.get("backup_frequency")); - record.backupSchedule = toMapOfStringString(map.get("backup_schedule")); - record.isBackupRunning = toBoolean(map.get("is_backup_running")); - record.backupLastRunTime = toDate(map.get("backup_last_run_time")); - record.archiveTargetType = toVmppArchiveTargetType(map.get("archive_target_type")); - record.archiveTargetConfig = toMapOfStringString(map.get("archive_target_config")); - record.archiveFrequency = toVmppArchiveFrequency(map.get("archive_frequency")); - record.archiveSchedule = toMapOfStringString(map.get("archive_schedule")); - record.isArchiveRunning = toBoolean(map.get("is_archive_running")); - record.archiveLastRunTime = toDate(map.get("archive_last_run_time")); - record.VMs = toSetOfVM(map.get("VMs")); - record.isAlarmEnabled = toBoolean(map.get("is_alarm_enabled")); - record.alarmConfig = toMapOfStringString(map.get("alarm_config")); - record.recentAlerts = toSetOfString(map.get("recent_alerts")); + record.uuid = toString(map.get("uuid")); + record.nameLabel = toString(map.get("name_label")); + record.nameDescription = toString(map.get("name_description")); + record.isPolicyEnabled = toBoolean(map.get("is_policy_enabled")); + record.backupType = toVmppBackupType(map.get("backup_type")); + record.backupRetentionValue = toLong(map.get("backup_retention_value")); + record.backupFrequency = toVmppBackupFrequency(map.get("backup_frequency")); + record.backupSchedule = toMapOfStringString(map.get("backup_schedule")); + record.isBackupRunning = toBoolean(map.get("is_backup_running")); + record.backupLastRunTime = toDate(map.get("backup_last_run_time")); + record.archiveTargetType = toVmppArchiveTargetType(map.get("archive_target_type")); + record.archiveTargetConfig = toMapOfStringString(map.get("archive_target_config")); + record.archiveFrequency = toVmppArchiveFrequency(map.get("archive_frequency")); + record.archiveSchedule = toMapOfStringString(map.get("archive_schedule")); + record.isArchiveRunning = toBoolean(map.get("is_archive_running")); + record.archiveLastRunTime = toDate(map.get("archive_last_run_time")); + record.VMs = toSetOfVM(map.get("VMs")); + record.isAlarmEnabled = toBoolean(map.get("is_alarm_enabled")); + record.alarmConfig = toMapOfStringString(map.get("alarm_config")); + record.recentAlerts = toSetOfString(map.get("recent_alerts")); return record; } @@ -12362,14 +12660,14 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; VMAppliance.Record record = new VMAppliance.Record(); - record.uuid = toString(map.get("uuid")); - record.nameLabel = toString(map.get("name_label")); - record.nameDescription = toString(map.get("name_description")); - record.allowedOperations = toSetOfVmApplianceOperation(map.get("allowed_operations")); - record.currentOperations = toMapOfStringVmApplianceOperation(map.get("current_operations")); - record.VMs = toSetOfVM(map.get("VMs")); + record.uuid = toString(map.get("uuid")); + record.nameLabel = toString(map.get("name_label")); + record.nameDescription = toString(map.get("name_description")); + record.allowedOperations = toSetOfVmApplianceOperation(map.get("allowed_operations")); + record.currentOperations = toMapOfStringVmApplianceOperation(map.get("current_operations")); + record.VMs = toSetOfVM(map.get("VMs")); return record; } @@ -12377,19 +12675,19 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; VMGuestMetrics.Record record = new VMGuestMetrics.Record(); - record.uuid = toString(map.get("uuid")); - record.osVersion = toMapOfStringString(map.get("os_version")); - record.PVDriversVersion = toMapOfStringString(map.get("PV_drivers_version")); - record.PVDriversUpToDate = toBoolean(map.get("PV_drivers_up_to_date")); - record.memory = toMapOfStringString(map.get("memory")); - record.disks = toMapOfStringString(map.get("disks")); - record.networks = toMapOfStringString(map.get("networks")); - record.other = toMapOfStringString(map.get("other")); - record.lastUpdated = toDate(map.get("last_updated")); - record.otherConfig = toMapOfStringString(map.get("other_config")); - record.live = toBoolean(map.get("live")); + record.uuid = toString(map.get("uuid")); + record.osVersion = toMapOfStringString(map.get("os_version")); + record.PVDriversVersion = toMapOfStringString(map.get("PV_drivers_version")); + record.PVDriversUpToDate = toBoolean(map.get("PV_drivers_up_to_date")); + record.memory = toMapOfStringString(map.get("memory")); + record.disks = toMapOfStringString(map.get("disks")); + record.networks = toMapOfStringString(map.get("networks")); + record.other = toMapOfStringString(map.get("other")); + record.lastUpdated = toDate(map.get("last_updated")); + record.otherConfig = toMapOfStringString(map.get("other_config")); + record.live = toBoolean(map.get("live")); return record; } @@ -12397,20 +12695,20 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; VMMetrics.Record record = new VMMetrics.Record(); - record.uuid = toString(map.get("uuid")); - record.memoryActual = toLong(map.get("memory_actual")); - record.VCPUsNumber = toLong(map.get("VCPUs_number")); - record.VCPUsUtilisation = toMapOfLongDouble(map.get("VCPUs_utilisation")); - record.VCPUsCPU = toMapOfLongLong(map.get("VCPUs_CPU")); - record.VCPUsParams = toMapOfStringString(map.get("VCPUs_params")); - record.VCPUsFlags = toMapOfLongSetOfString(map.get("VCPUs_flags")); - record.state = toSetOfString(map.get("state")); - record.startTime = toDate(map.get("start_time")); - record.installTime = toDate(map.get("install_time")); - record.lastUpdated = toDate(map.get("last_updated")); - record.otherConfig = toMapOfStringString(map.get("other_config")); + record.uuid = toString(map.get("uuid")); + record.memoryActual = toLong(map.get("memory_actual")); + record.VCPUsNumber = toLong(map.get("VCPUs_number")); + record.VCPUsUtilisation = toMapOfLongDouble(map.get("VCPUs_utilisation")); + record.VCPUsCPU = toMapOfLongLong(map.get("VCPUs_CPU")); + record.VCPUsParams = toMapOfStringString(map.get("VCPUs_params")); + record.VCPUsFlags = toMapOfLongSetOfString(map.get("VCPUs_flags")); + record.state = toSetOfString(map.get("state")); + record.startTime = toDate(map.get("start_time")); + record.installTime = toDate(map.get("install_time")); + record.lastUpdated = toDate(map.get("last_updated")); + record.otherConfig = toMapOfStringString(map.get("other_config")); return record; } @@ -12418,11 +12716,11 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; VTPM.Record record = new VTPM.Record(); - record.uuid = toString(map.get("uuid")); - record.VM = toVM(map.get("VM")); - record.backend = toVM(map.get("backend")); + record.uuid = toString(map.get("uuid")); + record.VM = toVM(map.get("VM")); + record.backend = toVM(map.get("backend")); return record; } @@ -12430,15 +12728,15 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; Blob.Record record = new Blob.Record(); - record.uuid = toString(map.get("uuid")); - record.nameLabel = toString(map.get("name_label")); - record.nameDescription = toString(map.get("name_description")); - record.size = toLong(map.get("size")); - record._public = toBoolean(map.get("public")); - record.lastUpdated = toDate(map.get("last_updated")); - record.mimeType = toString(map.get("mime_type")); + record.uuid = toString(map.get("uuid")); + record.nameLabel = toString(map.get("name_label")); + record.nameDescription = toString(map.get("name_description")); + record.size = toLong(map.get("size")); + record._public = toBoolean(map.get("public")); + record.lastUpdated = toDate(map.get("last_updated")); + record.mimeType = toString(map.get("mime_type")); return record; } @@ -12446,13 +12744,13 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; Console.Record record = new Console.Record(); - record.uuid = toString(map.get("uuid")); - record.protocol = toConsoleProtocol(map.get("protocol")); - record.location = toString(map.get("location")); - record.VM = toVM(map.get("VM")); - record.otherConfig = toMapOfStringString(map.get("other_config")); + record.uuid = toString(map.get("uuid")); + record.protocol = toConsoleProtocol(map.get("protocol")); + record.location = toString(map.get("location")); + record.VM = toVM(map.get("VM")); + record.otherConfig = toMapOfStringString(map.get("other_config")); return record; } @@ -12460,12 +12758,12 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; Crashdump.Record record = new Crashdump.Record(); - record.uuid = toString(map.get("uuid")); - record.VM = toVM(map.get("VM")); - record.VDI = toVDI(map.get("VDI")); - record.otherConfig = toMapOfStringString(map.get("other_config")); + record.uuid = toString(map.get("uuid")); + record.VM = toVM(map.get("VM")); + record.VDI = toVDI(map.get("VDI")); + record.otherConfig = toMapOfStringString(map.get("other_config")); return record; } @@ -12473,16 +12771,16 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; DataSource.Record record = new DataSource.Record(); - record.nameLabel = toString(map.get("name_label")); - record.nameDescription = toString(map.get("name_description")); - record.enabled = toBoolean(map.get("enabled")); - record.standard = toBoolean(map.get("standard")); - record.units = toString(map.get("units")); - record.min = toDouble(map.get("min")); - record.max = toDouble(map.get("max")); - record.value = toDouble(map.get("value")); + record.nameLabel = toString(map.get("name_label")); + record.nameDescription = toString(map.get("name_description")); + record.enabled = toBoolean(map.get("enabled")); + record.standard = toBoolean(map.get("standard")); + record.units = toString(map.get("units")); + record.min = toDouble(map.get("min")); + record.max = toDouble(map.get("max")); + record.value = toDouble(map.get("value")); return record; } @@ -12490,65 +12788,153 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; Event.Record record = new Event.Record(); - record.id = toLong(map.get("id")); - record.timestamp = toDate(map.get("timestamp")); - record.clazz = toString(map.get("class")); - record.operation = toEventOperation(map.get("operation")); - record.ref = toString(map.get("ref")); - record.objUuid = toString(map.get("obj_uuid")); + record.id = toLong(map.get("id")); + record.timestamp = toDate(map.get("timestamp")); + record.clazz = toString(map.get("class")); + record.operation = toEventOperation(map.get("operation")); + record.ref = toString(map.get("ref")); + record.objUuid = toString(map.get("obj_uuid")); - - Object a,b; - a=map.get("snapshot"); - switch(toXenAPIObjects(record.clazz)) + Object a, b; + a = map.get("snapshot"); + switch (toXenAPIObjects(record.clazz)) { - case SESSION: b = toSessionRecord(a); break; - case SUBJECT: b = toSubjectRecord(a); break; - case ROLE: b = toRoleRecord(a); break; - case TASK: b = toTaskRecord(a); break; - case EVENT: b = toEventRecord(a); break; - case POOL: b = toPoolRecord(a); break; - case POOL_PATCH: b = toPoolPatchRecord(a); break; - case VM: b = toVMRecord(a); break; - case VM_METRICS: b = toVMMetricsRecord(a); break; - case VM_GUEST_METRICS: b = toVMGuestMetricsRecord(a); break; - case VMPP: b = toVMPPRecord(a); break; - case VM_APPLIANCE: b = toVMApplianceRecord(a); break; - case DR_TASK: b = toDRTaskRecord(a); break; - case HOST: b = toHostRecord(a); break; - case HOST_CRASHDUMP: b = toHostCrashdumpRecord(a); break; - case HOST_PATCH: b = toHostPatchRecord(a); break; - case HOST_METRICS: b = toHostMetricsRecord(a); break; - case HOST_CPU: b = toHostCpuRecord(a); break; - case NETWORK: b = toNetworkRecord(a); break; - case VIF: b = toVIFRecord(a); break; - case VIF_METRICS: b = toVIFMetricsRecord(a); break; - case PIF: b = toPIFRecord(a); break; - case PIF_METRICS: b = toPIFMetricsRecord(a); break; - case BOND: b = toBondRecord(a); break; - case VLAN: b = toVLANRecord(a); break; - case SM: b = toSMRecord(a); break; - case SR: b = toSRRecord(a); break; - case VDI: b = toVDIRecord(a); break; - case VBD: b = toVBDRecord(a); break; - case VBD_METRICS: b = toVBDMetricsRecord(a); break; - case PBD: b = toPBDRecord(a); break; - case CRASHDUMP: b = toCrashdumpRecord(a); break; - case VTPM: b = toVTPMRecord(a); break; - case CONSOLE: b = toConsoleRecord(a); break; - case USER: b = toUserRecord(a); break; - case DATA_SOURCE: b = toDataSourceRecord(a); break; - case BLOB: b = toBlobRecord(a); break; - case MESSAGE: b = toMessageRecord(a); break; - case SECRET: b = toSecretRecord(a); break; - case TUNNEL: b = toTunnelRecord(a); break; - case PCI: b = toPCIRecord(a); break; - case PGPU: b = toPGPURecord(a); break; - case GPU_GROUP: b = toGPUGroupRecord(a); break; - case VGPU: b = toVGPURecord(a); break; - default: throw new RuntimeException("Internal error in auto-generated code whilst unmarshalling event snapshot"); + case SESSION: + b = toSessionRecord(a); + break; + case SUBJECT: + b = toSubjectRecord(a); + break; + case ROLE: + b = toRoleRecord(a); + break; + case TASK: + b = toTaskRecord(a); + break; + case EVENT: + b = toEventRecord(a); + break; + case POOL: + b = toPoolRecord(a); + break; + case POOL_PATCH: + b = toPoolPatchRecord(a); + break; + case VM: + b = toVMRecord(a); + break; + case VM_METRICS: + b = toVMMetricsRecord(a); + break; + case VM_GUEST_METRICS: + b = toVMGuestMetricsRecord(a); + break; + case VMPP: + b = toVMPPRecord(a); + break; + case VM_APPLIANCE: + b = toVMApplianceRecord(a); + break; + case DR_TASK: + b = toDRTaskRecord(a); + break; + case HOST: + b = toHostRecord(a); + break; + case HOST_CRASHDUMP: + b = toHostCrashdumpRecord(a); + break; + case HOST_PATCH: + b = toHostPatchRecord(a); + break; + case HOST_METRICS: + b = toHostMetricsRecord(a); + break; + case HOST_CPU: + b = toHostCpuRecord(a); + break; + case NETWORK: + b = toNetworkRecord(a); + break; + case VIF: + b = toVIFRecord(a); + break; + case VIF_METRICS: + b = toVIFMetricsRecord(a); + break; + case PIF: + b = toPIFRecord(a); + break; + case PIF_METRICS: + b = toPIFMetricsRecord(a); + break; + case BOND: + b = toBondRecord(a); + break; + case VLAN: + b = toVLANRecord(a); + break; + case SM: + b = toSMRecord(a); + break; + case SR: + b = toSRRecord(a); + break; + case VDI: + b = toVDIRecord(a); + break; + case VBD: + b = toVBDRecord(a); + break; + case VBD_METRICS: + b = toVBDMetricsRecord(a); + break; + case PBD: + b = toPBDRecord(a); + break; + case CRASHDUMP: + b = toCrashdumpRecord(a); + break; + case VTPM: + b = toVTPMRecord(a); + break; + case CONSOLE: + b = toConsoleRecord(a); + break; + case USER: + b = toUserRecord(a); + break; + case DATA_SOURCE: + b = toDataSourceRecord(a); + break; + case BLOB: + b = toBlobRecord(a); + break; + case MESSAGE: + b = toMessageRecord(a); + break; + case SECRET: + b = toSecretRecord(a); + break; + case TUNNEL: + b = toTunnelRecord(a); + break; + case PCI: + b = toPCIRecord(a); + break; + case PGPU: + b = toPGPURecord(a); + break; + case GPU_GROUP: + b = toGPUGroupRecord(a); + break; + case VGPU: + b = toVGPURecord(a); + break; + default: + throw new RuntimeException("Internal error in auto-generated code whilst unmarshalling event snapshot"); } record.snapshot = b; return record; @@ -12558,55 +12944,55 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; Host.Record record = new Host.Record(); - record.uuid = toString(map.get("uuid")); - record.nameLabel = toString(map.get("name_label")); - record.nameDescription = toString(map.get("name_description")); - record.memoryOverhead = toLong(map.get("memory_overhead")); - record.allowedOperations = toSetOfHostAllowedOperations(map.get("allowed_operations")); - record.currentOperations = toMapOfStringHostAllowedOperations(map.get("current_operations")); - record.APIVersionMajor = toLong(map.get("API_version_major")); - record.APIVersionMinor = toLong(map.get("API_version_minor")); - record.APIVersionVendor = toString(map.get("API_version_vendor")); - record.APIVersionVendorImplementation = toMapOfStringString(map.get("API_version_vendor_implementation")); - record.enabled = toBoolean(map.get("enabled")); - record.softwareVersion = toMapOfStringString(map.get("software_version")); - record.otherConfig = toMapOfStringString(map.get("other_config")); - record.capabilities = toSetOfString(map.get("capabilities")); - record.cpuConfiguration = toMapOfStringString(map.get("cpu_configuration")); - record.schedPolicy = toString(map.get("sched_policy")); - record.supportedBootloaders = toSetOfString(map.get("supported_bootloaders")); - record.residentVMs = toSetOfVM(map.get("resident_VMs")); - record.logging = toMapOfStringString(map.get("logging")); - record.PIFs = toSetOfPIF(map.get("PIFs")); - record.suspendImageSr = toSR(map.get("suspend_image_sr")); - record.crashDumpSr = toSR(map.get("crash_dump_sr")); - record.crashdumps = toSetOfHostCrashdump(map.get("crashdumps")); - record.patches = toSetOfHostPatch(map.get("patches")); - record.PBDs = toSetOfPBD(map.get("PBDs")); - record.hostCPUs = toSetOfHostCpu(map.get("host_CPUs")); - record.cpuInfo = toMapOfStringString(map.get("cpu_info")); - record.hostname = toString(map.get("hostname")); - record.address = toString(map.get("address")); - record.metrics = toHostMetrics(map.get("metrics")); - record.licenseParams = toMapOfStringString(map.get("license_params")); - record.haStatefiles = toSetOfString(map.get("ha_statefiles")); - record.haNetworkPeers = toSetOfString(map.get("ha_network_peers")); - record.blobs = toMapOfStringBlob(map.get("blobs")); - record.tags = toSetOfString(map.get("tags")); - record.externalAuthType = toString(map.get("external_auth_type")); - record.externalAuthServiceName = toString(map.get("external_auth_service_name")); - record.externalAuthConfiguration = toMapOfStringString(map.get("external_auth_configuration")); - record.edition = toString(map.get("edition")); - record.licenseServer = toMapOfStringString(map.get("license_server")); - record.biosStrings = toMapOfStringString(map.get("bios_strings")); - record.powerOnMode = toString(map.get("power_on_mode")); - record.powerOnConfig = toMapOfStringString(map.get("power_on_config")); - record.localCacheSr = toSR(map.get("local_cache_sr")); - record.chipsetInfo = toMapOfStringString(map.get("chipset_info")); - record.PCIs = toSetOfPCI(map.get("PCIs")); - record.PGPUs = toSetOfPGPU(map.get("PGPUs")); + record.uuid = toString(map.get("uuid")); + record.nameLabel = toString(map.get("name_label")); + record.nameDescription = toString(map.get("name_description")); + record.memoryOverhead = toLong(map.get("memory_overhead")); + record.allowedOperations = toSetOfHostAllowedOperations(map.get("allowed_operations")); + record.currentOperations = toMapOfStringHostAllowedOperations(map.get("current_operations")); + record.APIVersionMajor = toLong(map.get("API_version_major")); + record.APIVersionMinor = toLong(map.get("API_version_minor")); + record.APIVersionVendor = toString(map.get("API_version_vendor")); + record.APIVersionVendorImplementation = toMapOfStringString(map.get("API_version_vendor_implementation")); + record.enabled = toBoolean(map.get("enabled")); + record.softwareVersion = toMapOfStringString(map.get("software_version")); + record.otherConfig = toMapOfStringString(map.get("other_config")); + record.capabilities = toSetOfString(map.get("capabilities")); + record.cpuConfiguration = toMapOfStringString(map.get("cpu_configuration")); + record.schedPolicy = toString(map.get("sched_policy")); + record.supportedBootloaders = toSetOfString(map.get("supported_bootloaders")); + record.residentVMs = toSetOfVM(map.get("resident_VMs")); + record.logging = toMapOfStringString(map.get("logging")); + record.PIFs = toSetOfPIF(map.get("PIFs")); + record.suspendImageSr = toSR(map.get("suspend_image_sr")); + record.crashDumpSr = toSR(map.get("crash_dump_sr")); + record.crashdumps = toSetOfHostCrashdump(map.get("crashdumps")); + record.patches = toSetOfHostPatch(map.get("patches")); + record.PBDs = toSetOfPBD(map.get("PBDs")); + record.hostCPUs = toSetOfHostCpu(map.get("host_CPUs")); + record.cpuInfo = toMapOfStringString(map.get("cpu_info")); + record.hostname = toString(map.get("hostname")); + record.address = toString(map.get("address")); + record.metrics = toHostMetrics(map.get("metrics")); + record.licenseParams = toMapOfStringString(map.get("license_params")); + record.haStatefiles = toSetOfString(map.get("ha_statefiles")); + record.haNetworkPeers = toSetOfString(map.get("ha_network_peers")); + record.blobs = toMapOfStringBlob(map.get("blobs")); + record.tags = toSetOfString(map.get("tags")); + record.externalAuthType = toString(map.get("external_auth_type")); + record.externalAuthServiceName = toString(map.get("external_auth_service_name")); + record.externalAuthConfiguration = toMapOfStringString(map.get("external_auth_configuration")); + record.edition = toString(map.get("edition")); + record.licenseServer = toMapOfStringString(map.get("license_server")); + record.biosStrings = toMapOfStringString(map.get("bios_strings")); + record.powerOnMode = toString(map.get("power_on_mode")); + record.powerOnConfig = toMapOfStringString(map.get("power_on_config")); + record.localCacheSr = toSR(map.get("local_cache_sr")); + record.chipsetInfo = toMapOfStringString(map.get("chipset_info")); + record.PCIs = toSetOfPCI(map.get("PCIs")); + record.PGPUs = toSetOfPGPU(map.get("PGPUs")); return record; } @@ -12614,21 +13000,21 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; HostCpu.Record record = new HostCpu.Record(); - record.uuid = toString(map.get("uuid")); - record.host = toHost(map.get("host")); - record.number = toLong(map.get("number")); - record.vendor = toString(map.get("vendor")); - record.speed = toLong(map.get("speed")); - record.modelname = toString(map.get("modelname")); - record.family = toLong(map.get("family")); - record.model = toLong(map.get("model")); - record.stepping = toString(map.get("stepping")); - record.flags = toString(map.get("flags")); - record.features = toString(map.get("features")); - record.utilisation = toDouble(map.get("utilisation")); - record.otherConfig = toMapOfStringString(map.get("other_config")); + record.uuid = toString(map.get("uuid")); + record.host = toHost(map.get("host")); + record.number = toLong(map.get("number")); + record.vendor = toString(map.get("vendor")); + record.speed = toLong(map.get("speed")); + record.modelname = toString(map.get("modelname")); + record.family = toLong(map.get("family")); + record.model = toLong(map.get("model")); + record.stepping = toString(map.get("stepping")); + record.flags = toString(map.get("flags")); + record.features = toString(map.get("features")); + record.utilisation = toDouble(map.get("utilisation")); + record.otherConfig = toMapOfStringString(map.get("other_config")); return record; } @@ -12636,13 +13022,13 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; HostCrashdump.Record record = new HostCrashdump.Record(); - record.uuid = toString(map.get("uuid")); - record.host = toHost(map.get("host")); - record.timestamp = toDate(map.get("timestamp")); - record.size = toLong(map.get("size")); - record.otherConfig = toMapOfStringString(map.get("other_config")); + record.uuid = toString(map.get("uuid")); + record.host = toHost(map.get("host")); + record.timestamp = toDate(map.get("timestamp")); + record.size = toLong(map.get("size")); + record.otherConfig = toMapOfStringString(map.get("other_config")); return record; } @@ -12650,14 +13036,14 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; HostMetrics.Record record = new HostMetrics.Record(); - record.uuid = toString(map.get("uuid")); - record.memoryTotal = toLong(map.get("memory_total")); - record.memoryFree = toLong(map.get("memory_free")); - record.live = toBoolean(map.get("live")); - record.lastUpdated = toDate(map.get("last_updated")); - record.otherConfig = toMapOfStringString(map.get("other_config")); + record.uuid = toString(map.get("uuid")); + record.memoryTotal = toLong(map.get("memory_total")); + record.memoryFree = toLong(map.get("memory_free")); + record.live = toBoolean(map.get("live")); + record.lastUpdated = toDate(map.get("last_updated")); + record.otherConfig = toMapOfStringString(map.get("other_config")); return record; } @@ -12665,18 +13051,18 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; HostPatch.Record record = new HostPatch.Record(); - record.uuid = toString(map.get("uuid")); - record.nameLabel = toString(map.get("name_label")); - record.nameDescription = toString(map.get("name_description")); - record.version = toString(map.get("version")); - record.host = toHost(map.get("host")); - record.applied = toBoolean(map.get("applied")); - record.timestampApplied = toDate(map.get("timestamp_applied")); - record.size = toLong(map.get("size")); - record.poolPatch = toPoolPatch(map.get("pool_patch")); - record.otherConfig = toMapOfStringString(map.get("other_config")); + record.uuid = toString(map.get("uuid")); + record.nameLabel = toString(map.get("name_label")); + record.nameDescription = toString(map.get("name_description")); + record.version = toString(map.get("version")); + record.host = toHost(map.get("host")); + record.applied = toBoolean(map.get("applied")); + record.timestampApplied = toDate(map.get("timestamp_applied")); + record.size = toLong(map.get("size")); + record.poolPatch = toPoolPatch(map.get("pool_patch")); + record.otherConfig = toMapOfStringString(map.get("other_config")); return record; } @@ -12684,15 +13070,15 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; Message.Record record = new Message.Record(); - record.uuid = toString(map.get("uuid")); - record.name = toString(map.get("name")); - record.priority = toLong(map.get("priority")); - record.cls = toCls(map.get("cls")); - record.objUuid = toString(map.get("obj_uuid")); - record.timestamp = toDate(map.get("timestamp")); - record.body = toString(map.get("body")); + record.uuid = toString(map.get("uuid")); + record.name = toString(map.get("name")); + record.priority = toLong(map.get("priority")); + record.cls = toCls(map.get("cls")); + record.objUuid = toString(map.get("obj_uuid")); + record.timestamp = toDate(map.get("timestamp")); + record.body = toString(map.get("body")); return record; } @@ -12700,21 +13086,21 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; Network.Record record = new Network.Record(); - record.uuid = toString(map.get("uuid")); - record.nameLabel = toString(map.get("name_label")); - record.nameDescription = toString(map.get("name_description")); - record.allowedOperations = toSetOfNetworkOperations(map.get("allowed_operations")); - record.currentOperations = toMapOfStringNetworkOperations(map.get("current_operations")); - record.VIFs = toSetOfVIF(map.get("VIFs")); - record.PIFs = toSetOfPIF(map.get("PIFs")); - record.MTU = toLong(map.get("MTU")); - record.otherConfig = toMapOfStringString(map.get("other_config")); - record.bridge = toString(map.get("bridge")); - record.blobs = toMapOfStringBlob(map.get("blobs")); - record.tags = toSetOfString(map.get("tags")); - record.defaultLockingMode = toNetworkDefaultLockingMode(map.get("default_locking_mode")); + record.uuid = toString(map.get("uuid")); + record.nameLabel = toString(map.get("name_label")); + record.nameDescription = toString(map.get("name_description")); + record.allowedOperations = toSetOfNetworkOperations(map.get("allowed_operations")); + record.currentOperations = toMapOfStringNetworkOperations(map.get("current_operations")); + record.VIFs = toSetOfVIF(map.get("VIFs")); + record.PIFs = toSetOfPIF(map.get("PIFs")); + record.MTU = toLong(map.get("MTU")); + record.otherConfig = toMapOfStringString(map.get("other_config")); + record.bridge = toString(map.get("bridge")); + record.blobs = toMapOfStringBlob(map.get("blobs")); + record.tags = toSetOfString(map.get("tags")); + record.defaultLockingMode = toNetworkDefaultLockingMode(map.get("default_locking_mode")); return record; } @@ -12722,35 +13108,35 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; Pool.Record record = new Pool.Record(); - record.uuid = toString(map.get("uuid")); - record.nameLabel = toString(map.get("name_label")); - record.nameDescription = toString(map.get("name_description")); - record.master = toHost(map.get("master")); - record.defaultSR = toSR(map.get("default_SR")); - record.suspendImageSR = toSR(map.get("suspend_image_SR")); - record.crashDumpSR = toSR(map.get("crash_dump_SR")); - record.otherConfig = toMapOfStringString(map.get("other_config")); - record.haEnabled = toBoolean(map.get("ha_enabled")); - record.haConfiguration = toMapOfStringString(map.get("ha_configuration")); - record.haStatefiles = toSetOfString(map.get("ha_statefiles")); - record.haHostFailuresToTolerate = toLong(map.get("ha_host_failures_to_tolerate")); - record.haPlanExistsFor = toLong(map.get("ha_plan_exists_for")); - record.haAllowOvercommit = toBoolean(map.get("ha_allow_overcommit")); - record.haOvercommitted = toBoolean(map.get("ha_overcommitted")); - record.blobs = toMapOfStringBlob(map.get("blobs")); - record.tags = toSetOfString(map.get("tags")); - record.guiConfig = toMapOfStringString(map.get("gui_config")); - record.wlbUrl = toString(map.get("wlb_url")); - record.wlbUsername = toString(map.get("wlb_username")); - record.wlbEnabled = toBoolean(map.get("wlb_enabled")); - record.wlbVerifyCert = toBoolean(map.get("wlb_verify_cert")); - record.redoLogEnabled = toBoolean(map.get("redo_log_enabled")); - record.redoLogVdi = toVDI(map.get("redo_log_vdi")); - record.vswitchController = toString(map.get("vswitch_controller")); - record.restrictions = toMapOfStringString(map.get("restrictions")); - record.metadataVDIs = toSetOfVDI(map.get("metadata_VDIs")); + record.uuid = toString(map.get("uuid")); + record.nameLabel = toString(map.get("name_label")); + record.nameDescription = toString(map.get("name_description")); + record.master = toHost(map.get("master")); + record.defaultSR = toSR(map.get("default_SR")); + record.suspendImageSR = toSR(map.get("suspend_image_SR")); + record.crashDumpSR = toSR(map.get("crash_dump_SR")); + record.otherConfig = toMapOfStringString(map.get("other_config")); + record.haEnabled = toBoolean(map.get("ha_enabled")); + record.haConfiguration = toMapOfStringString(map.get("ha_configuration")); + record.haStatefiles = toSetOfString(map.get("ha_statefiles")); + record.haHostFailuresToTolerate = toLong(map.get("ha_host_failures_to_tolerate")); + record.haPlanExistsFor = toLong(map.get("ha_plan_exists_for")); + record.haAllowOvercommit = toBoolean(map.get("ha_allow_overcommit")); + record.haOvercommitted = toBoolean(map.get("ha_overcommitted")); + record.blobs = toMapOfStringBlob(map.get("blobs")); + record.tags = toSetOfString(map.get("tags")); + record.guiConfig = toMapOfStringString(map.get("gui_config")); + record.wlbUrl = toString(map.get("wlb_url")); + record.wlbUsername = toString(map.get("wlb_username")); + record.wlbEnabled = toBoolean(map.get("wlb_enabled")); + record.wlbVerifyCert = toBoolean(map.get("wlb_verify_cert")); + record.redoLogEnabled = toBoolean(map.get("redo_log_enabled")); + record.redoLogVdi = toVDI(map.get("redo_log_vdi")); + record.vswitchController = toString(map.get("vswitch_controller")); + record.restrictions = toMapOfStringString(map.get("restrictions")); + record.metadataVDIs = toSetOfVDI(map.get("metadata_VDIs")); return record; } @@ -12758,17 +13144,17 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; PoolPatch.Record record = new PoolPatch.Record(); - record.uuid = toString(map.get("uuid")); - record.nameLabel = toString(map.get("name_label")); - record.nameDescription = toString(map.get("name_description")); - record.version = toString(map.get("version")); - record.size = toLong(map.get("size")); - record.poolApplied = toBoolean(map.get("pool_applied")); - record.hostPatches = toSetOfHostPatch(map.get("host_patches")); - record.afterApplyGuidance = toSetOfAfterApplyGuidance(map.get("after_apply_guidance")); - record.otherConfig = toMapOfStringString(map.get("other_config")); + record.uuid = toString(map.get("uuid")); + record.nameLabel = toString(map.get("name_label")); + record.nameDescription = toString(map.get("name_description")); + record.version = toString(map.get("version")); + record.size = toLong(map.get("size")); + record.poolApplied = toBoolean(map.get("pool_applied")); + record.hostPatches = toSetOfHostPatch(map.get("host_patches")); + record.afterApplyGuidance = toSetOfAfterApplyGuidance(map.get("after_apply_guidance")); + record.otherConfig = toMapOfStringString(map.get("other_config")); return record; } @@ -12776,12 +13162,12 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; Role.Record record = new Role.Record(); - record.uuid = toString(map.get("uuid")); - record.nameLabel = toString(map.get("name_label")); - record.nameDescription = toString(map.get("name_description")); - record.subroles = toSetOfRole(map.get("subroles")); + record.uuid = toString(map.get("uuid")); + record.nameLabel = toString(map.get("name_label")); + record.nameDescription = toString(map.get("name_description")); + record.subroles = toSetOfRole(map.get("subroles")); return record; } @@ -12789,11 +13175,11 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; Secret.Record record = new Secret.Record(); - record.uuid = toString(map.get("uuid")); - record.value = toString(map.get("value")); - record.otherConfig = toMapOfStringString(map.get("other_config")); + record.uuid = toString(map.get("uuid")); + record.value = toString(map.get("value")); + record.otherConfig = toMapOfStringString(map.get("other_config")); return record; } @@ -12801,22 +13187,22 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; Session.Record record = new Session.Record(); - record.uuid = toString(map.get("uuid")); - record.thisHost = toHost(map.get("this_host")); - record.thisUser = toUser(map.get("this_user")); - record.lastActive = toDate(map.get("last_active")); - record.pool = toBoolean(map.get("pool")); - record.otherConfig = toMapOfStringString(map.get("other_config")); - record.isLocalSuperuser = toBoolean(map.get("is_local_superuser")); - record.subject = toSubject(map.get("subject")); - record.validationTime = toDate(map.get("validation_time")); - record.authUserSid = toString(map.get("auth_user_sid")); - record.authUserName = toString(map.get("auth_user_name")); - record.rbacPermissions = toSetOfString(map.get("rbac_permissions")); - record.tasks = toSetOfTask(map.get("tasks")); - record.parent = toSession(map.get("parent")); + record.uuid = toString(map.get("uuid")); + record.thisHost = toHost(map.get("this_host")); + record.thisUser = toUser(map.get("this_user")); + record.lastActive = toDate(map.get("last_active")); + record.pool = toBoolean(map.get("pool")); + record.otherConfig = toMapOfStringString(map.get("other_config")); + record.isLocalSuperuser = toBoolean(map.get("is_local_superuser")); + record.subject = toSubject(map.get("subject")); + record.validationTime = toDate(map.get("validation_time")); + record.authUserSid = toString(map.get("auth_user_sid")); + record.authUserName = toString(map.get("auth_user_name")); + record.rbacPermissions = toSetOfString(map.get("rbac_permissions")); + record.tasks = toSetOfTask(map.get("tasks")); + record.parent = toSession(map.get("parent")); return record; } @@ -12824,12 +13210,12 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; Subject.Record record = new Subject.Record(); - record.uuid = toString(map.get("uuid")); - record.subjectIdentifier = toString(map.get("subject_identifier")); - record.otherConfig = toMapOfStringString(map.get("other_config")); - record.roles = toSetOfRole(map.get("roles")); + record.uuid = toString(map.get("uuid")); + record.subjectIdentifier = toString(map.get("subject_identifier")); + record.otherConfig = toMapOfStringString(map.get("other_config")); + record.roles = toSetOfRole(map.get("roles")); return record; } @@ -12837,24 +13223,24 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; Task.Record record = new Task.Record(); - record.uuid = toString(map.get("uuid")); - record.nameLabel = toString(map.get("name_label")); - record.nameDescription = toString(map.get("name_description")); - record.allowedOperations = toSetOfTaskAllowedOperations(map.get("allowed_operations")); - record.currentOperations = toMapOfStringTaskAllowedOperations(map.get("current_operations")); - record.created = toDate(map.get("created")); - record.finished = toDate(map.get("finished")); - record.status = toTaskStatusType(map.get("status")); - record.residentOn = toHost(map.get("resident_on")); - record.progress = toDouble(map.get("progress")); - record.type = toString(map.get("type")); - record.result = toString(map.get("result")); - record.errorInfo = toSetOfString(map.get("error_info")); - record.otherConfig = toMapOfStringString(map.get("other_config")); - record.subtaskOf = toTask(map.get("subtask_of")); - record.subtasks = toSetOfTask(map.get("subtasks")); + record.uuid = toString(map.get("uuid")); + record.nameLabel = toString(map.get("name_label")); + record.nameDescription = toString(map.get("name_description")); + record.allowedOperations = toSetOfTaskAllowedOperations(map.get("allowed_operations")); + record.currentOperations = toMapOfStringTaskAllowedOperations(map.get("current_operations")); + record.created = toDate(map.get("created")); + record.finished = toDate(map.get("finished")); + record.status = toTaskStatusType(map.get("status")); + record.residentOn = toHost(map.get("resident_on")); + record.progress = toDouble(map.get("progress")); + record.type = toString(map.get("type")); + record.result = toString(map.get("result")); + record.errorInfo = toSetOfString(map.get("error_info")); + record.otherConfig = toMapOfStringString(map.get("other_config")); + record.subtaskOf = toTask(map.get("subtask_of")); + record.subtasks = toSetOfTask(map.get("subtasks")); return record; } @@ -12862,13 +13248,13 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; Tunnel.Record record = new Tunnel.Record(); - record.uuid = toString(map.get("uuid")); - record.accessPIF = toPIF(map.get("access_PIF")); - record.transportPIF = toPIF(map.get("transport_PIF")); - record.status = toMapOfStringString(map.get("status")); - record.otherConfig = toMapOfStringString(map.get("other_config")); + record.uuid = toString(map.get("uuid")); + record.accessPIF = toPIF(map.get("access_PIF")); + record.transportPIF = toPIF(map.get("transport_PIF")); + record.status = toMapOfStringString(map.get("status")); + record.otherConfig = toMapOfStringString(map.get("other_config")); return record; } @@ -12876,182 +13262,181 @@ public class Types if (object == null) { return null; } - Map map = (Map) object; + Map map = (Map)object; User.Record record = new User.Record(); - record.uuid = toString(map.get("uuid")); - record.shortName = toString(map.get("short_name")); - record.fullname = toString(map.get("fullname")); - record.otherConfig = toMapOfStringString(map.get("other_config")); + record.uuid = toString(map.get("uuid")); + record.shortName = toString(map.get("short_name")); + record.fullname = toString(map.get("fullname")); + record.otherConfig = toMapOfStringString(map.get("other_config")); return record; } - - public static Bond toBond(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toBond(parseResult(task.getResult(connection))); + public static Bond toBond(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toBond(parseResult(task.getResult(connection))); } - public static DRTask toDRTask(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toDRTask(parseResult(task.getResult(connection))); + public static DRTask toDRTask(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toDRTask(parseResult(task.getResult(connection))); } - public static GPUGroup toGPUGroup(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toGPUGroup(parseResult(task.getResult(connection))); + public static GPUGroup toGPUGroup(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toGPUGroup(parseResult(task.getResult(connection))); } - public static PBD toPBD(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toPBD(parseResult(task.getResult(connection))); + public static PBD toPBD(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toPBD(parseResult(task.getResult(connection))); } - public static PCI toPCI(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toPCI(parseResult(task.getResult(connection))); + public static PCI toPCI(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toPCI(parseResult(task.getResult(connection))); } - public static PGPU toPGPU(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toPGPU(parseResult(task.getResult(connection))); + public static PGPU toPGPU(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toPGPU(parseResult(task.getResult(connection))); } - public static PIF toPIF(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toPIF(parseResult(task.getResult(connection))); + public static PIF toPIF(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toPIF(parseResult(task.getResult(connection))); } - public static PIFMetrics toPIFMetrics(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toPIFMetrics(parseResult(task.getResult(connection))); + public static PIFMetrics toPIFMetrics(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toPIFMetrics(parseResult(task.getResult(connection))); } - public static SM toSM(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toSM(parseResult(task.getResult(connection))); + public static SM toSM(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toSM(parseResult(task.getResult(connection))); } - public static SR toSR(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toSR(parseResult(task.getResult(connection))); + public static SR toSR(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toSR(parseResult(task.getResult(connection))); } - public static VBD toVBD(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toVBD(parseResult(task.getResult(connection))); + public static VBD toVBD(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toVBD(parseResult(task.getResult(connection))); } - public static VBDMetrics toVBDMetrics(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toVBDMetrics(parseResult(task.getResult(connection))); + public static VBDMetrics toVBDMetrics(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toVBDMetrics(parseResult(task.getResult(connection))); } - public static VDI toVDI(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toVDI(parseResult(task.getResult(connection))); + public static VDI toVDI(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toVDI(parseResult(task.getResult(connection))); } - public static VGPU toVGPU(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toVGPU(parseResult(task.getResult(connection))); + public static VGPU toVGPU(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toVGPU(parseResult(task.getResult(connection))); } - public static VIF toVIF(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toVIF(parseResult(task.getResult(connection))); + public static VIF toVIF(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toVIF(parseResult(task.getResult(connection))); } - public static VIFMetrics toVIFMetrics(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toVIFMetrics(parseResult(task.getResult(connection))); + public static VIFMetrics toVIFMetrics(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toVIFMetrics(parseResult(task.getResult(connection))); } - public static VLAN toVLAN(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toVLAN(parseResult(task.getResult(connection))); + public static VLAN toVLAN(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toVLAN(parseResult(task.getResult(connection))); } - public static VM toVM(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toVM(parseResult(task.getResult(connection))); + public static VM toVM(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toVM(parseResult(task.getResult(connection))); } - public static VMPP toVMPP(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toVMPP(parseResult(task.getResult(connection))); + public static VMPP toVMPP(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toVMPP(parseResult(task.getResult(connection))); } - public static VMAppliance toVMAppliance(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toVMAppliance(parseResult(task.getResult(connection))); + public static VMAppliance toVMAppliance(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toVMAppliance(parseResult(task.getResult(connection))); } - public static VMGuestMetrics toVMGuestMetrics(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toVMGuestMetrics(parseResult(task.getResult(connection))); + public static VMGuestMetrics toVMGuestMetrics(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toVMGuestMetrics(parseResult(task.getResult(connection))); } - public static VMMetrics toVMMetrics(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toVMMetrics(parseResult(task.getResult(connection))); + public static VMMetrics toVMMetrics(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toVMMetrics(parseResult(task.getResult(connection))); } - public static VTPM toVTPM(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toVTPM(parseResult(task.getResult(connection))); + public static VTPM toVTPM(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toVTPM(parseResult(task.getResult(connection))); } - public static Blob toBlob(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toBlob(parseResult(task.getResult(connection))); + public static Blob toBlob(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toBlob(parseResult(task.getResult(connection))); } - public static Console toConsole(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toConsole(parseResult(task.getResult(connection))); + public static Console toConsole(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toConsole(parseResult(task.getResult(connection))); } - public static Crashdump toCrashdump(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toCrashdump(parseResult(task.getResult(connection))); + public static Crashdump toCrashdump(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toCrashdump(parseResult(task.getResult(connection))); } - public static Host toHost(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toHost(parseResult(task.getResult(connection))); + public static Host toHost(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toHost(parseResult(task.getResult(connection))); } - public static HostCpu toHostCpu(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toHostCpu(parseResult(task.getResult(connection))); + public static HostCpu toHostCpu(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toHostCpu(parseResult(task.getResult(connection))); } - public static HostCrashdump toHostCrashdump(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toHostCrashdump(parseResult(task.getResult(connection))); + public static HostCrashdump toHostCrashdump(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toHostCrashdump(parseResult(task.getResult(connection))); } - public static HostMetrics toHostMetrics(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toHostMetrics(parseResult(task.getResult(connection))); + public static HostMetrics toHostMetrics(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toHostMetrics(parseResult(task.getResult(connection))); } - public static HostPatch toHostPatch(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toHostPatch(parseResult(task.getResult(connection))); + public static HostPatch toHostPatch(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toHostPatch(parseResult(task.getResult(connection))); } - public static Message toMessage(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toMessage(parseResult(task.getResult(connection))); + public static Message toMessage(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toMessage(parseResult(task.getResult(connection))); } - public static Network toNetwork(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toNetwork(parseResult(task.getResult(connection))); + public static Network toNetwork(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toNetwork(parseResult(task.getResult(connection))); } - public static Pool toPool(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toPool(parseResult(task.getResult(connection))); + public static Pool toPool(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toPool(parseResult(task.getResult(connection))); } - public static PoolPatch toPoolPatch(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toPoolPatch(parseResult(task.getResult(connection))); + public static PoolPatch toPoolPatch(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toPoolPatch(parseResult(task.getResult(connection))); } - public static Role toRole(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toRole(parseResult(task.getResult(connection))); + public static Role toRole(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toRole(parseResult(task.getResult(connection))); } - public static Secret toSecret(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toSecret(parseResult(task.getResult(connection))); + public static Secret toSecret(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toSecret(parseResult(task.getResult(connection))); } - public static Session toSession(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toSession(parseResult(task.getResult(connection))); + public static Session toSession(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toSession(parseResult(task.getResult(connection))); } - public static Subject toSubject(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toSubject(parseResult(task.getResult(connection))); + public static Subject toSubject(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toSubject(parseResult(task.getResult(connection))); } - public static Task toTask(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toTask(parseResult(task.getResult(connection))); + public static Task toTask(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toTask(parseResult(task.getResult(connection))); } - public static Tunnel toTunnel(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toTunnel(parseResult(task.getResult(connection))); + public static Tunnel toTunnel(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toTunnel(parseResult(task.getResult(connection))); } - public static User toUser(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ - return Types.toUser(parseResult(task.getResult(connection))); + public static User toUser(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult { + return Types.toUser(parseResult(task.getResult(connection))); } } diff --git a/deps/XenServerJava/src/com/xensource/xenapi/User.java b/deps/XenServerJava/src/com/xensource/xenapi/User.java index 0d2e4fd81d8..dff27f5b367 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/User.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/User.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class User extends XenAPIObject { * For internal use only. */ User(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class User extends XenAPIObject { { if (obj != null && obj instanceof User) { - User other = (User) obj; + User other = (User)obj; return other.ref.equals(this.ref); } else { @@ -110,8 +109,8 @@ public class User extends XenAPIObject { /** * Convert a user.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("short_name", this.shortName == null ? "" : this.shortName); map.put("fullname", this.fullname == null ? "" : this.fullname); @@ -143,16 +142,17 @@ public class User extends XenAPIObject { * * @return all fields from the object */ - @Deprecated public User.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + @Deprecated + public User.Record getRecord(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "user.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toUserRecord(result); + return Types.toUserRecord(result); } /** @@ -162,16 +162,17 @@ public class User extends XenAPIObject { * @param uuid UUID of object to return * @return reference to the object */ - @Deprecated public static User getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + @Deprecated + public static User getByUuid(Connection c, String uuid) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "user.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toUser(result); + return Types.toUser(result); } /** @@ -181,10 +182,11 @@ public class User extends XenAPIObject { * @param record All constructor arguments * @return Task */ - @Deprecated public static Task createAsync(Connection c, User.Record record) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + @Deprecated + public static Task createAsync(Connection c, User.Record record) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.user.create"; String session = c.getSessionReference(); Map record_map = record.toMap(); @@ -201,17 +203,18 @@ public class User extends XenAPIObject { * @param record All constructor arguments * @return reference to the newly created object */ - @Deprecated public static User create(Connection c, User.Record record) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + @Deprecated + public static User create(Connection c, User.Record record) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "user.create"; String session = c.getSessionReference(); Map record_map = record.toMap(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(record_map)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toUser(result); + return Types.toUser(result); } /** @@ -220,10 +223,11 @@ public class User extends XenAPIObject { * * @return Task */ - @Deprecated public Task destroyAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + @Deprecated + public Task destroyAsync(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.user.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -237,10 +241,11 @@ public class User extends XenAPIObject { * @deprecated * */ - @Deprecated public void destroy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + @Deprecated + public void destroy(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "user.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -254,15 +259,15 @@ public class User extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "user.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -271,15 +276,15 @@ public class User extends XenAPIObject { * @return value of the field */ public String getShortName(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "user.get_short_name"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -288,15 +293,15 @@ public class User extends XenAPIObject { * @return value of the field */ public String getFullname(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "user.get_fullname"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -305,15 +310,15 @@ public class User extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "user.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -322,9 +327,9 @@ public class User extends XenAPIObject { * @param fullname New value to set */ public void setFullname(Connection c, String fullname) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "user.set_fullname"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(fullname)}; @@ -338,9 +343,9 @@ public class User extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "user.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -355,9 +360,9 @@ public class User extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "user.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -371,9 +376,9 @@ public class User extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "user.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; diff --git a/deps/XenServerJava/src/com/xensource/xenapi/VBD.java b/deps/XenServerJava/src/com/xensource/xenapi/VBD.java index 18cbb7b488d..56e6f4b3d0e 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/VBD.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/VBD.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class VBD extends XenAPIObject { * For internal use only. */ VBD(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class VBD extends XenAPIObject { { if (obj != null && obj instanceof VBD) { - VBD other = (VBD) obj; + VBD other = (VBD)obj; return other.ref.equals(this.ref); } else { @@ -128,8 +127,8 @@ public class VBD extends XenAPIObject { /** * Convert a VBD.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("allowed_operations", this.allowedOperations == null ? new LinkedHashSet() : this.allowedOperations); map.put("current_operations", this.currentOperations == null ? new HashMap() : this.currentOperations); @@ -251,15 +250,15 @@ public class VBD extends XenAPIObject { * @return all fields from the object */ public VBD.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVBDRecord(result); + return Types.toVBDRecord(result); } /** @@ -269,15 +268,15 @@ public class VBD extends XenAPIObject { * @return reference to the object */ public static VBD getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVBD(result); + return Types.toVBD(result); } /** @@ -287,9 +286,9 @@ public class VBD extends XenAPIObject { * @return Task */ public static Task createAsync(Connection c, VBD.Record record) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VBD.create"; String session = c.getSessionReference(); Map record_map = record.toMap(); @@ -306,16 +305,16 @@ public class VBD extends XenAPIObject { * @return reference to the newly created object */ public static VBD create(Connection c, VBD.Record record) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.create"; String session = c.getSessionReference(); Map record_map = record.toMap(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(record_map)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVBD(result); + return Types.toVBD(result); } /** @@ -324,9 +323,9 @@ public class VBD extends XenAPIObject { * @return Task */ public Task destroyAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VBD.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -340,9 +339,9 @@ public class VBD extends XenAPIObject { * */ public void destroy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -356,15 +355,15 @@ public class VBD extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -373,15 +372,15 @@ public class VBD extends XenAPIObject { * @return value of the field */ public Set getAllowedOperations(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.get_allowed_operations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVbdOperations(result); + return Types.toSetOfVbdOperations(result); } /** @@ -390,15 +389,15 @@ public class VBD extends XenAPIObject { * @return value of the field */ public Map getCurrentOperations(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.get_current_operations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringVbdOperations(result); + return Types.toMapOfStringVbdOperations(result); } /** @@ -407,15 +406,15 @@ public class VBD extends XenAPIObject { * @return value of the field */ public VM getVM(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.get_VM"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVM(result); + return Types.toVM(result); } /** @@ -424,15 +423,15 @@ public class VBD extends XenAPIObject { * @return value of the field */ public VDI getVDI(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.get_VDI"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVDI(result); + return Types.toVDI(result); } /** @@ -441,15 +440,15 @@ public class VBD extends XenAPIObject { * @return value of the field */ public String getDevice(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.get_device"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -458,15 +457,15 @@ public class VBD extends XenAPIObject { * @return value of the field */ public String getUserdevice(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.get_userdevice"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -475,15 +474,15 @@ public class VBD extends XenAPIObject { * @return value of the field */ public Boolean getBootable(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.get_bootable"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -492,15 +491,15 @@ public class VBD extends XenAPIObject { * @return value of the field */ public Types.VbdMode getMode(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.get_mode"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVbdMode(result); + return Types.toVbdMode(result); } /** @@ -509,15 +508,15 @@ public class VBD extends XenAPIObject { * @return value of the field */ public Types.VbdType getType(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.get_type"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVbdType(result); + return Types.toVbdType(result); } /** @@ -526,15 +525,15 @@ public class VBD extends XenAPIObject { * @return value of the field */ public Boolean getUnpluggable(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.get_unpluggable"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -543,15 +542,15 @@ public class VBD extends XenAPIObject { * @return value of the field */ public Boolean getStorageLock(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.get_storage_lock"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -560,15 +559,15 @@ public class VBD extends XenAPIObject { * @return value of the field */ public Boolean getEmpty(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.get_empty"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -577,15 +576,15 @@ public class VBD extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -594,15 +593,15 @@ public class VBD extends XenAPIObject { * @return value of the field */ public Boolean getCurrentlyAttached(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.get_currently_attached"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -611,15 +610,15 @@ public class VBD extends XenAPIObject { * @return value of the field */ public Long getStatusCode(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.get_status_code"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -628,15 +627,15 @@ public class VBD extends XenAPIObject { * @return value of the field */ public String getStatusDetail(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.get_status_detail"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -645,15 +644,15 @@ public class VBD extends XenAPIObject { * @return value of the field */ public Map getRuntimeProperties(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.get_runtime_properties"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -662,15 +661,15 @@ public class VBD extends XenAPIObject { * @return value of the field */ public String getQosAlgorithmType(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.get_qos_algorithm_type"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -679,15 +678,15 @@ public class VBD extends XenAPIObject { * @return value of the field */ public Map getQosAlgorithmParams(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.get_qos_algorithm_params"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -696,15 +695,15 @@ public class VBD extends XenAPIObject { * @return value of the field */ public Set getQosSupportedAlgorithms(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.get_qos_supported_algorithms"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -713,15 +712,15 @@ public class VBD extends XenAPIObject { * @return value of the field */ public VBDMetrics getMetrics(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.get_metrics"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVBDMetrics(result); + return Types.toVBDMetrics(result); } /** @@ -730,9 +729,9 @@ public class VBD extends XenAPIObject { * @param userdevice New value to set */ public void setUserdevice(Connection c, String userdevice) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.set_userdevice"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(userdevice)}; @@ -746,9 +745,9 @@ public class VBD extends XenAPIObject { * @param bootable New value to set */ public void setBootable(Connection c, Boolean bootable) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.set_bootable"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(bootable)}; @@ -762,9 +761,9 @@ public class VBD extends XenAPIObject { * @param mode New value to set */ public void setMode(Connection c, Types.VbdMode mode) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.set_mode"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(mode)}; @@ -778,9 +777,9 @@ public class VBD extends XenAPIObject { * @param type New value to set */ public void setType(Connection c, Types.VbdType type) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.set_type"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(type)}; @@ -794,9 +793,9 @@ public class VBD extends XenAPIObject { * @param unpluggable New value to set */ public void setUnpluggable(Connection c, Boolean unpluggable) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.set_unpluggable"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(unpluggable)}; @@ -810,9 +809,9 @@ public class VBD extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -827,9 +826,9 @@ public class VBD extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -843,9 +842,9 @@ public class VBD extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -859,9 +858,9 @@ public class VBD extends XenAPIObject { * @param algorithmType New value to set */ public void setQosAlgorithmType(Connection c, String algorithmType) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.set_qos_algorithm_type"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(algorithmType)}; @@ -875,9 +874,9 @@ public class VBD extends XenAPIObject { * @param algorithmParams New value to set */ public void setQosAlgorithmParams(Connection c, Map algorithmParams) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.set_qos_algorithm_params"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(algorithmParams)}; @@ -892,9 +891,9 @@ public class VBD extends XenAPIObject { * @param value Value to add */ public void addToQosAlgorithmParams(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.add_to_qos_algorithm_params"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -908,9 +907,9 @@ public class VBD extends XenAPIObject { * @param key Key to remove */ public void removeFromQosAlgorithmParams(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.remove_from_qos_algorithm_params"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -924,11 +923,11 @@ public class VBD extends XenAPIObject { * @return Task */ public Task ejectAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VbdNotRemovableMedia, - Types.VbdIsEmpty { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VbdNotRemovableMedia, + Types.VbdIsEmpty { String method_call = "Async.VBD.eject"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -942,11 +941,11 @@ public class VBD extends XenAPIObject { * */ public void eject(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VbdNotRemovableMedia, - Types.VbdIsEmpty { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VbdNotRemovableMedia, + Types.VbdIsEmpty { String method_call = "VBD.eject"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -961,11 +960,11 @@ public class VBD extends XenAPIObject { * @return Task */ public Task insertAsync(Connection c, VDI vdi) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VbdNotRemovableMedia, - Types.VbdNotEmpty { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VbdNotRemovableMedia, + Types.VbdNotEmpty { String method_call = "Async.VBD.insert"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(vdi)}; @@ -980,11 +979,11 @@ public class VBD extends XenAPIObject { * @param vdi The new VDI to 'insert' */ public void insert(Connection c, VDI vdi) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VbdNotRemovableMedia, - Types.VbdNotEmpty { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VbdNotRemovableMedia, + Types.VbdNotEmpty { String method_call = "VBD.insert"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(vdi)}; @@ -998,9 +997,9 @@ public class VBD extends XenAPIObject { * @return Task */ public Task plugAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VBD.plug"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1014,9 +1013,9 @@ public class VBD extends XenAPIObject { * */ public void plug(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.plug"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1030,11 +1029,11 @@ public class VBD extends XenAPIObject { * @return Task */ public Task unplugAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.DeviceDetachRejected, - Types.DeviceAlreadyDetached { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.DeviceDetachRejected, + Types.DeviceAlreadyDetached { String method_call = "Async.VBD.unplug"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1048,11 +1047,11 @@ public class VBD extends XenAPIObject { * */ public void unplug(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.DeviceDetachRejected, - Types.DeviceAlreadyDetached { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.DeviceDetachRejected, + Types.DeviceAlreadyDetached { String method_call = "VBD.unplug"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1066,9 +1065,9 @@ public class VBD extends XenAPIObject { * @return Task */ public Task unplugForceAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VBD.unplug_force"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1082,9 +1081,9 @@ public class VBD extends XenAPIObject { * */ public void unplugForce(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.unplug_force"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1098,9 +1097,9 @@ public class VBD extends XenAPIObject { * @return Task */ public Task assertAttachableAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VBD.assert_attachable"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1114,9 +1113,9 @@ public class VBD extends XenAPIObject { * */ public void assertAttachable(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.assert_attachable"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1130,15 +1129,15 @@ public class VBD extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVBD(result); + return Types.toSetOfVBD(result); } /** @@ -1147,15 +1146,15 @@ public class VBD extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfVBDVBDRecord(result); + return Types.toMapOfVBDVBDRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/VBDMetrics.java b/deps/XenServerJava/src/com/xensource/xenapi/VBDMetrics.java index adb6bb513de..1f678faecdb 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/VBDMetrics.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/VBDMetrics.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class VBDMetrics extends XenAPIObject { * For internal use only. */ VBDMetrics(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class VBDMetrics extends XenAPIObject { { if (obj != null && obj instanceof VBDMetrics) { - VBDMetrics other = (VBDMetrics) obj; + VBDMetrics other = (VBDMetrics)obj; return other.ref.equals(this.ref); } else { @@ -111,8 +110,8 @@ public class VBDMetrics extends XenAPIObject { /** * Convert a VBD_metrics.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("io_read_kbs", this.ioReadKbs == null ? 0.0 : this.ioReadKbs); map.put("io_write_kbs", this.ioWriteKbs == null ? 0.0 : this.ioWriteKbs); @@ -149,15 +148,15 @@ public class VBDMetrics extends XenAPIObject { * @return all fields from the object */ public VBDMetrics.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD_metrics.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVBDMetricsRecord(result); + return Types.toVBDMetricsRecord(result); } /** @@ -167,15 +166,15 @@ public class VBDMetrics extends XenAPIObject { * @return reference to the object */ public static VBDMetrics getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD_metrics.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVBDMetrics(result); + return Types.toVBDMetrics(result); } /** @@ -184,15 +183,15 @@ public class VBDMetrics extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD_metrics.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -201,15 +200,15 @@ public class VBDMetrics extends XenAPIObject { * @return value of the field */ public Double getIoReadKbs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD_metrics.get_io_read_kbs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDouble(result); + return Types.toDouble(result); } /** @@ -218,15 +217,15 @@ public class VBDMetrics extends XenAPIObject { * @return value of the field */ public Double getIoWriteKbs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD_metrics.get_io_write_kbs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDouble(result); + return Types.toDouble(result); } /** @@ -235,15 +234,15 @@ public class VBDMetrics extends XenAPIObject { * @return value of the field */ public Date getLastUpdated(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD_metrics.get_last_updated"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDate(result); + return Types.toDate(result); } /** @@ -252,15 +251,15 @@ public class VBDMetrics extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD_metrics.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -269,9 +268,9 @@ public class VBDMetrics extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD_metrics.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -286,9 +285,9 @@ public class VBDMetrics extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD_metrics.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -302,9 +301,9 @@ public class VBDMetrics extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD_metrics.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -318,15 +317,15 @@ public class VBDMetrics extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD_metrics.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVBDMetrics(result); + return Types.toSetOfVBDMetrics(result); } /** @@ -335,15 +334,15 @@ public class VBDMetrics extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VBD_metrics.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfVBDMetricsVBDMetricsRecord(result); + return Types.toMapOfVBDMetricsVBDMetricsRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/VDI.java b/deps/XenServerJava/src/com/xensource/xenapi/VDI.java index 4ea9daff1fa..992a6a6d898 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/VDI.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/VDI.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class VDI extends XenAPIObject { * For internal use only. */ VDI(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class VDI extends XenAPIObject { { if (obj != null && obj instanceof VDI) { - VDI other = (VDI) obj; + VDI other = (VDI)obj; return other.ref.equals(this.ref); } else { @@ -136,8 +135,8 @@ public class VDI extends XenAPIObject { /** * Convert a VDI.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("name_label", this.nameLabel == null ? "" : this.nameLabel); map.put("name_description", this.nameDescription == null ? "" : this.nameDescription); @@ -299,15 +298,15 @@ public class VDI extends XenAPIObject { * @return all fields from the object */ public VDI.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVDIRecord(result); + return Types.toVDIRecord(result); } /** @@ -317,15 +316,15 @@ public class VDI extends XenAPIObject { * @return reference to the object */ public static VDI getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVDI(result); + return Types.toVDI(result); } /** @@ -335,9 +334,9 @@ public class VDI extends XenAPIObject { * @return Task */ public static Task createAsync(Connection c, VDI.Record record) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VDI.create"; String session = c.getSessionReference(); Map record_map = record.toMap(); @@ -354,16 +353,16 @@ public class VDI extends XenAPIObject { * @return reference to the newly created object */ public static VDI create(Connection c, VDI.Record record) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.create"; String session = c.getSessionReference(); Map record_map = record.toMap(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(record_map)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVDI(result); + return Types.toVDI(result); } /** @@ -372,9 +371,9 @@ public class VDI extends XenAPIObject { * @return Task */ public Task destroyAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VDI.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -388,9 +387,9 @@ public class VDI extends XenAPIObject { * */ public void destroy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -405,15 +404,15 @@ public class VDI extends XenAPIObject { * @return references to objects with matching names */ public static Set getByNameLabel(Connection c, String label) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_by_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(label)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVDI(result); + return Types.toSetOfVDI(result); } /** @@ -422,15 +421,15 @@ public class VDI extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -439,15 +438,15 @@ public class VDI extends XenAPIObject { * @return value of the field */ public String getNameLabel(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -456,15 +455,15 @@ public class VDI extends XenAPIObject { * @return value of the field */ public String getNameDescription(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_name_description"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -473,15 +472,15 @@ public class VDI extends XenAPIObject { * @return value of the field */ public Set getAllowedOperations(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_allowed_operations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVdiOperations(result); + return Types.toSetOfVdiOperations(result); } /** @@ -490,15 +489,15 @@ public class VDI extends XenAPIObject { * @return value of the field */ public Map getCurrentOperations(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_current_operations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringVdiOperations(result); + return Types.toMapOfStringVdiOperations(result); } /** @@ -507,15 +506,15 @@ public class VDI extends XenAPIObject { * @return value of the field */ public SR getSR(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_SR"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSR(result); + return Types.toSR(result); } /** @@ -524,15 +523,15 @@ public class VDI extends XenAPIObject { * @return value of the field */ public Set getVBDs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_VBDs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVBD(result); + return Types.toSetOfVBD(result); } /** @@ -541,15 +540,15 @@ public class VDI extends XenAPIObject { * @return value of the field */ public Set getCrashDumps(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_crash_dumps"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfCrashdump(result); + return Types.toSetOfCrashdump(result); } /** @@ -558,15 +557,15 @@ public class VDI extends XenAPIObject { * @return value of the field */ public Long getVirtualSize(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_virtual_size"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -575,15 +574,15 @@ public class VDI extends XenAPIObject { * @return value of the field */ public Long getPhysicalUtilisation(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_physical_utilisation"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -592,15 +591,15 @@ public class VDI extends XenAPIObject { * @return value of the field */ public Types.VdiType getType(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_type"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVdiType(result); + return Types.toVdiType(result); } /** @@ -609,15 +608,15 @@ public class VDI extends XenAPIObject { * @return value of the field */ public Boolean getSharable(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_sharable"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -626,15 +625,15 @@ public class VDI extends XenAPIObject { * @return value of the field */ public Boolean getReadOnly(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_read_only"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -643,15 +642,15 @@ public class VDI extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -660,15 +659,15 @@ public class VDI extends XenAPIObject { * @return value of the field */ public Boolean getStorageLock(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_storage_lock"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -677,15 +676,15 @@ public class VDI extends XenAPIObject { * @return value of the field */ public String getLocation(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_location"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -694,15 +693,15 @@ public class VDI extends XenAPIObject { * @return value of the field */ public Boolean getManaged(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_managed"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -711,15 +710,15 @@ public class VDI extends XenAPIObject { * @return value of the field */ public Boolean getMissing(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_missing"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -728,15 +727,15 @@ public class VDI extends XenAPIObject { * @return value of the field */ public VDI getParent(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_parent"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVDI(result); + return Types.toVDI(result); } /** @@ -745,15 +744,15 @@ public class VDI extends XenAPIObject { * @return value of the field */ public Map getXenstoreData(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_xenstore_data"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -762,15 +761,15 @@ public class VDI extends XenAPIObject { * @return value of the field */ public Map getSmConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_sm_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -779,15 +778,15 @@ public class VDI extends XenAPIObject { * @return value of the field */ public Boolean getIsASnapshot(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_is_a_snapshot"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -796,15 +795,15 @@ public class VDI extends XenAPIObject { * @return value of the field */ public VDI getSnapshotOf(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_snapshot_of"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVDI(result); + return Types.toVDI(result); } /** @@ -813,15 +812,15 @@ public class VDI extends XenAPIObject { * @return value of the field */ public Set getSnapshots(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_snapshots"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVDI(result); + return Types.toSetOfVDI(result); } /** @@ -830,15 +829,15 @@ public class VDI extends XenAPIObject { * @return value of the field */ public Date getSnapshotTime(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_snapshot_time"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDate(result); + return Types.toDate(result); } /** @@ -847,15 +846,15 @@ public class VDI extends XenAPIObject { * @return value of the field */ public Set getTags(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_tags"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -864,15 +863,15 @@ public class VDI extends XenAPIObject { * @return value of the field */ public Boolean getAllowCaching(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_allow_caching"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -881,15 +880,15 @@ public class VDI extends XenAPIObject { * @return value of the field */ public Types.OnBoot getOnBoot(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_on_boot"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toOnBoot(result); + return Types.toOnBoot(result); } /** @@ -898,15 +897,15 @@ public class VDI extends XenAPIObject { * @return value of the field */ public Pool getMetadataOfPool(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_metadata_of_pool"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toPool(result); + return Types.toPool(result); } /** @@ -915,15 +914,15 @@ public class VDI extends XenAPIObject { * @return value of the field */ public Boolean getMetadataLatest(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_metadata_latest"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -932,9 +931,9 @@ public class VDI extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -949,9 +948,9 @@ public class VDI extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -965,9 +964,9 @@ public class VDI extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -981,9 +980,9 @@ public class VDI extends XenAPIObject { * @param xenstoreData New value to set */ public void setXenstoreData(Connection c, Map xenstoreData) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.set_xenstore_data"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(xenstoreData)}; @@ -998,9 +997,9 @@ public class VDI extends XenAPIObject { * @param value Value to add */ public void addToXenstoreData(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.add_to_xenstore_data"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -1014,9 +1013,9 @@ public class VDI extends XenAPIObject { * @param key Key to remove */ public void removeFromXenstoreData(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.remove_from_xenstore_data"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -1030,9 +1029,9 @@ public class VDI extends XenAPIObject { * @param smConfig New value to set */ public void setSmConfig(Connection c, Map smConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.set_sm_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(smConfig)}; @@ -1047,9 +1046,9 @@ public class VDI extends XenAPIObject { * @param value Value to add */ public void addToSmConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.add_to_sm_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -1063,9 +1062,9 @@ public class VDI extends XenAPIObject { * @param key Key to remove */ public void removeFromSmConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.remove_from_sm_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -1079,9 +1078,9 @@ public class VDI extends XenAPIObject { * @param tags New value to set */ public void setTags(Connection c, Set tags) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.set_tags"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(tags)}; @@ -1095,9 +1094,9 @@ public class VDI extends XenAPIObject { * @param value New value to add */ public void addTags(Connection c, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.add_tags"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1111,9 +1110,9 @@ public class VDI extends XenAPIObject { * @param value Value to remove */ public void removeTags(Connection c, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.remove_tags"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1128,13 +1127,13 @@ public class VDI extends XenAPIObject { * @return Task */ public Task snapshotAsync(Connection c, Map driverParams) throws - BadServerResponse, - VersionException, - XenAPIException, - XmlRpcException { + BadServerResponse, + VersionException, + XenAPIException, + XmlRpcException { - if(c.rioConnection){ - if (driverParams.isEmpty()){ + if (c.rioConnection) { + if (driverParams.isEmpty()) { return rioSnapshotAsync(c); } else { throw new Types.VersionException("driverParams parameter must be empty map for Rio (legacy XenServer) host"); @@ -1144,12 +1143,10 @@ public class VDI extends XenAPIObject { } } - - private Task rioSnapshotAsync(Connection c) throws - BadServerResponse, - XmlRpcException, - XenAPIException { + BadServerResponse, + XmlRpcException, + XenAPIException { String method_call = "Async.VDI.snapshot"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1159,9 +1156,9 @@ public class VDI extends XenAPIObject { } private Task miamiSnapshotAsync(Connection c, Map driverParams) throws - BadServerResponse, - XmlRpcException, - XenAPIException { + BadServerResponse, + XmlRpcException, + XenAPIException { String method_call = "Async.VDI.snapshot"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(driverParams)}; @@ -1177,13 +1174,13 @@ public class VDI extends XenAPIObject { * @return The ID of the newly created VDI. */ public VDI snapshot(Connection c, Map driverParams) throws - BadServerResponse, - VersionException, - XenAPIException, - XmlRpcException { + BadServerResponse, + VersionException, + XenAPIException, + XmlRpcException { - if(c.rioConnection){ - if (driverParams.isEmpty()){ + if (c.rioConnection) { + if (driverParams.isEmpty()) { return rioSnapshot(c); } else { throw new Types.VersionException("driverParams parameter must be empty map for Rio (legacy XenServer) host"); @@ -1193,30 +1190,28 @@ public class VDI extends XenAPIObject { } } - - private VDI rioSnapshot(Connection c) throws - BadServerResponse, - XmlRpcException, - XenAPIException { + BadServerResponse, + XmlRpcException, + XenAPIException { String method_call = "VDI.snapshot"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVDI(result); + return Types.toVDI(result); } private VDI miamiSnapshot(Connection c, Map driverParams) throws - BadServerResponse, - XmlRpcException, - XenAPIException { + BadServerResponse, + XmlRpcException, + XenAPIException { String method_call = "VDI.snapshot"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(driverParams)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVDI(result); + return Types.toVDI(result); } /** @@ -1226,13 +1221,13 @@ public class VDI extends XenAPIObject { * @return Task */ public Task createCloneAsync(Connection c, Map driverParams) throws - BadServerResponse, - VersionException, - XenAPIException, - XmlRpcException { + BadServerResponse, + VersionException, + XenAPIException, + XmlRpcException { - if(c.rioConnection){ - if (driverParams.isEmpty()){ + if (c.rioConnection) { + if (driverParams.isEmpty()) { return rioCreateCloneAsync(c); } else { throw new Types.VersionException("driverParams parameter must be empty map for Rio (legacy XenServer) host"); @@ -1242,12 +1237,10 @@ public class VDI extends XenAPIObject { } } - - private Task rioCreateCloneAsync(Connection c) throws - BadServerResponse, - XmlRpcException, - XenAPIException { + BadServerResponse, + XmlRpcException, + XenAPIException { String method_call = "Async.VDI.clone"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1257,9 +1250,9 @@ public class VDI extends XenAPIObject { } private Task miamiCreateCloneAsync(Connection c, Map driverParams) throws - BadServerResponse, - XmlRpcException, - XenAPIException { + BadServerResponse, + XmlRpcException, + XenAPIException { String method_call = "Async.VDI.clone"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(driverParams)}; @@ -1275,13 +1268,13 @@ public class VDI extends XenAPIObject { * @return The ID of the newly created VDI. */ public VDI createClone(Connection c, Map driverParams) throws - BadServerResponse, - VersionException, - XenAPIException, - XmlRpcException { + BadServerResponse, + VersionException, + XenAPIException, + XmlRpcException { - if(c.rioConnection){ - if (driverParams.isEmpty()){ + if (c.rioConnection) { + if (driverParams.isEmpty()) { return rioCreateClone(c); } else { throw new Types.VersionException("driverParams parameter must be empty map for Rio (legacy XenServer) host"); @@ -1291,30 +1284,28 @@ public class VDI extends XenAPIObject { } } - - private VDI rioCreateClone(Connection c) throws - BadServerResponse, - XmlRpcException, - XenAPIException { + BadServerResponse, + XmlRpcException, + XenAPIException { String method_call = "VDI.clone"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVDI(result); + return Types.toVDI(result); } private VDI miamiCreateClone(Connection c, Map driverParams) throws - BadServerResponse, - XmlRpcException, - XenAPIException { + BadServerResponse, + XmlRpcException, + XenAPIException { String method_call = "VDI.clone"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(driverParams)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVDI(result); + return Types.toVDI(result); } /** @@ -1324,9 +1315,9 @@ public class VDI extends XenAPIObject { * @return Task */ public Task resizeAsync(Connection c, Long size) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VDI.resize"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(size)}; @@ -1341,9 +1332,9 @@ public class VDI extends XenAPIObject { * @param size The new size of the VDI */ public void resize(Connection c, Long size) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.resize"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(size)}; @@ -1358,9 +1349,9 @@ public class VDI extends XenAPIObject { * @return Task */ public Task resizeOnlineAsync(Connection c, Long size) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VDI.resize_online"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(size)}; @@ -1375,9 +1366,9 @@ public class VDI extends XenAPIObject { * @param size The new size of the VDI */ public void resizeOnline(Connection c, Long size) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.resize_online"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(size)}; @@ -1408,14 +1399,20 @@ public class VDI extends XenAPIObject { * @param snapshotOf Storage-specific config * @return Task */ - public static Task introduceAsync(Connection c, String uuid, String nameLabel, String nameDescription, SR SR, Types.VdiType type, Boolean sharable, Boolean readOnly, Map otherConfig, String location, Map xenstoreData, Map smConfig, Boolean managed, Long virtualSize, Long physicalUtilisation, Pool metadataOfPool, Boolean isASnapshot, Date snapshotTime, VDI snapshotOf) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.SrOperationNotSupported { + public static Task introduceAsync(Connection c, String uuid, String nameLabel, String nameDescription, SR SR, Types.VdiType type, Boolean sharable, Boolean readOnly, + Map otherConfig, String location, Map xenstoreData, Map smConfig, Boolean managed, Long virtualSize, + Long physicalUtilisation, Pool metadataOfPool, Boolean isASnapshot, Date snapshotTime, VDI snapshotOf) throws + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.SrOperationNotSupported { String method_call = "Async.VDI.introduce"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(SR), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(sharable), Marshalling.toXMLRPC(readOnly), Marshalling.toXMLRPC(otherConfig), Marshalling.toXMLRPC(location), Marshalling.toXMLRPC(xenstoreData), Marshalling.toXMLRPC(smConfig), Marshalling.toXMLRPC(managed), Marshalling.toXMLRPC(virtualSize), Marshalling.toXMLRPC(physicalUtilisation), Marshalling.toXMLRPC(metadataOfPool), Marshalling.toXMLRPC(isASnapshot), Marshalling.toXMLRPC(snapshotTime), Marshalling.toXMLRPC(snapshotOf)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), + Marshalling.toXMLRPC(SR), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(sharable), Marshalling.toXMLRPC(readOnly), Marshalling.toXMLRPC(otherConfig), + Marshalling.toXMLRPC(location), Marshalling.toXMLRPC(xenstoreData), Marshalling.toXMLRPC(smConfig), Marshalling.toXMLRPC(managed), + Marshalling.toXMLRPC(virtualSize), Marshalling.toXMLRPC(physicalUtilisation), Marshalling.toXMLRPC(metadataOfPool), Marshalling.toXMLRPC(isASnapshot), + Marshalling.toXMLRPC(snapshotTime), Marshalling.toXMLRPC(snapshotOf)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -1444,17 +1441,23 @@ public class VDI extends XenAPIObject { * @param snapshotOf Storage-specific config * @return The ref of the newly created VDI record. */ - public static VDI introduce(Connection c, String uuid, String nameLabel, String nameDescription, SR SR, Types.VdiType type, Boolean sharable, Boolean readOnly, Map otherConfig, String location, Map xenstoreData, Map smConfig, Boolean managed, Long virtualSize, Long physicalUtilisation, Pool metadataOfPool, Boolean isASnapshot, Date snapshotTime, VDI snapshotOf) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.SrOperationNotSupported { + public static VDI introduce(Connection c, String uuid, String nameLabel, String nameDescription, SR SR, Types.VdiType type, Boolean sharable, Boolean readOnly, + Map otherConfig, String location, Map xenstoreData, Map smConfig, Boolean managed, Long virtualSize, + Long physicalUtilisation, Pool metadataOfPool, Boolean isASnapshot, Date snapshotTime, VDI snapshotOf) throws + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.SrOperationNotSupported { String method_call = "VDI.introduce"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(SR), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(sharable), Marshalling.toXMLRPC(readOnly), Marshalling.toXMLRPC(otherConfig), Marshalling.toXMLRPC(location), Marshalling.toXMLRPC(xenstoreData), Marshalling.toXMLRPC(smConfig), Marshalling.toXMLRPC(managed), Marshalling.toXMLRPC(virtualSize), Marshalling.toXMLRPC(physicalUtilisation), Marshalling.toXMLRPC(metadataOfPool), Marshalling.toXMLRPC(isASnapshot), Marshalling.toXMLRPC(snapshotTime), Marshalling.toXMLRPC(snapshotOf)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), + Marshalling.toXMLRPC(SR), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(sharable), Marshalling.toXMLRPC(readOnly), Marshalling.toXMLRPC(otherConfig), + Marshalling.toXMLRPC(location), Marshalling.toXMLRPC(xenstoreData), Marshalling.toXMLRPC(smConfig), Marshalling.toXMLRPC(managed), + Marshalling.toXMLRPC(virtualSize), Marshalling.toXMLRPC(physicalUtilisation), Marshalling.toXMLRPC(metadataOfPool), Marshalling.toXMLRPC(isASnapshot), + Marshalling.toXMLRPC(snapshotTime), Marshalling.toXMLRPC(snapshotOf)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVDI(result); + return Types.toVDI(result); } /** @@ -1480,13 +1483,19 @@ public class VDI extends XenAPIObject { * @param snapshotOf Storage-specific config * @return Task */ - public static Task dbIntroduceAsync(Connection c, String uuid, String nameLabel, String nameDescription, SR SR, Types.VdiType type, Boolean sharable, Boolean readOnly, Map otherConfig, String location, Map xenstoreData, Map smConfig, Boolean managed, Long virtualSize, Long physicalUtilisation, Pool metadataOfPool, Boolean isASnapshot, Date snapshotTime, VDI snapshotOf) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + public static Task dbIntroduceAsync(Connection c, String uuid, String nameLabel, String nameDescription, SR SR, Types.VdiType type, Boolean sharable, + Boolean readOnly, Map otherConfig, String location, Map xenstoreData, Map smConfig, Boolean managed, + Long virtualSize, Long physicalUtilisation, Pool metadataOfPool, Boolean isASnapshot, Date snapshotTime, VDI snapshotOf) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VDI.db_introduce"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(SR), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(sharable), Marshalling.toXMLRPC(readOnly), Marshalling.toXMLRPC(otherConfig), Marshalling.toXMLRPC(location), Marshalling.toXMLRPC(xenstoreData), Marshalling.toXMLRPC(smConfig), Marshalling.toXMLRPC(managed), Marshalling.toXMLRPC(virtualSize), Marshalling.toXMLRPC(physicalUtilisation), Marshalling.toXMLRPC(metadataOfPool), Marshalling.toXMLRPC(isASnapshot), Marshalling.toXMLRPC(snapshotTime), Marshalling.toXMLRPC(snapshotOf)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), + Marshalling.toXMLRPC(SR), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(sharable), Marshalling.toXMLRPC(readOnly), Marshalling.toXMLRPC(otherConfig), + Marshalling.toXMLRPC(location), Marshalling.toXMLRPC(xenstoreData), Marshalling.toXMLRPC(smConfig), Marshalling.toXMLRPC(managed), + Marshalling.toXMLRPC(virtualSize), Marshalling.toXMLRPC(physicalUtilisation), Marshalling.toXMLRPC(metadataOfPool), Marshalling.toXMLRPC(isASnapshot), + Marshalling.toXMLRPC(snapshotTime), Marshalling.toXMLRPC(snapshotOf)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -1515,16 +1524,22 @@ public class VDI extends XenAPIObject { * @param snapshotOf Storage-specific config * @return The ref of the newly created VDI record. */ - public static VDI dbIntroduce(Connection c, String uuid, String nameLabel, String nameDescription, SR SR, Types.VdiType type, Boolean sharable, Boolean readOnly, Map otherConfig, String location, Map xenstoreData, Map smConfig, Boolean managed, Long virtualSize, Long physicalUtilisation, Pool metadataOfPool, Boolean isASnapshot, Date snapshotTime, VDI snapshotOf) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + public static VDI dbIntroduce(Connection c, String uuid, String nameLabel, String nameDescription, SR SR, Types.VdiType type, Boolean sharable, Boolean readOnly, + Map otherConfig, String location, Map xenstoreData, Map smConfig, Boolean managed, Long virtualSize, + Long physicalUtilisation, Pool metadataOfPool, Boolean isASnapshot, Date snapshotTime, VDI snapshotOf) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.db_introduce"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(SR), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(sharable), Marshalling.toXMLRPC(readOnly), Marshalling.toXMLRPC(otherConfig), Marshalling.toXMLRPC(location), Marshalling.toXMLRPC(xenstoreData), Marshalling.toXMLRPC(smConfig), Marshalling.toXMLRPC(managed), Marshalling.toXMLRPC(virtualSize), Marshalling.toXMLRPC(physicalUtilisation), Marshalling.toXMLRPC(metadataOfPool), Marshalling.toXMLRPC(isASnapshot), Marshalling.toXMLRPC(snapshotTime), Marshalling.toXMLRPC(snapshotOf)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), + Marshalling.toXMLRPC(SR), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(sharable), Marshalling.toXMLRPC(readOnly), Marshalling.toXMLRPC(otherConfig), + Marshalling.toXMLRPC(location), Marshalling.toXMLRPC(xenstoreData), Marshalling.toXMLRPC(smConfig), Marshalling.toXMLRPC(managed), + Marshalling.toXMLRPC(virtualSize), Marshalling.toXMLRPC(physicalUtilisation), Marshalling.toXMLRPC(metadataOfPool), Marshalling.toXMLRPC(isASnapshot), + Marshalling.toXMLRPC(snapshotTime), Marshalling.toXMLRPC(snapshotOf)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVDI(result); + return Types.toVDI(result); } /** @@ -1533,9 +1548,9 @@ public class VDI extends XenAPIObject { * @return Task */ public Task dbForgetAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VDI.db_forget"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1549,9 +1564,9 @@ public class VDI extends XenAPIObject { * */ public void dbForget(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.db_forget"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1565,10 +1580,10 @@ public class VDI extends XenAPIObject { * @return Task */ public Task updateAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.SrOperationNotSupported { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.SrOperationNotSupported { String method_call = "Async.VDI.update"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1582,10 +1597,10 @@ public class VDI extends XenAPIObject { * */ public void update(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.SrOperationNotSupported { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.SrOperationNotSupported { String method_call = "VDI.update"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1593,6 +1608,29 @@ public class VDI extends XenAPIObject { return; } + /** + * Copy either a full VDI or the block differences between two VDIs into either a fresh VDI or an existing VDI. + * + * @param sr The destination SR (only required if the destination VDI is not specified + * @param baseVdi The base VDI (only required if copying only changed blocks, by default all blocks will be copied) + * @param intoVdi The destination VDI to copy blocks into (if omitted then a destination SR must be provided and a fresh VDI will be created) + * @return Task + */ + public Task copyAsync2(Connection c, SR sr, VDI baseVdi, VDI intoVdi) throws + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VdiReadonly, + Types.VdiTooSmall, + Types.VdiNotSparse { + String method_call = "Async.VDI.copy"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(sr), Marshalling.toXMLRPC(baseVdi), Marshalling.toXMLRPC(intoVdi)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + /** * Make a fresh VDI in the specified SR and copy the supplied VDI's data to the new disk * @@ -1600,9 +1638,9 @@ public class VDI extends XenAPIObject { * @return Task */ public Task copyAsync(Connection c, SR sr) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VDI.copy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(sr)}; @@ -1618,15 +1656,15 @@ public class VDI extends XenAPIObject { * @return The reference of the newly created VDI. */ public VDI copy(Connection c, SR sr) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.copy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(sr)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVDI(result); + return Types.toVDI(result); } /** @@ -1635,9 +1673,9 @@ public class VDI extends XenAPIObject { * @param value The new value of the VDI's managed field */ public void setManaged(Connection c, Boolean value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.set_managed"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1651,9 +1689,9 @@ public class VDI extends XenAPIObject { * @return Task */ public Task forgetAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VDI.forget"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1667,9 +1705,9 @@ public class VDI extends XenAPIObject { * */ public void forget(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.forget"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1683,9 +1721,9 @@ public class VDI extends XenAPIObject { * @param value The new value of the VDI's sharable field */ public void setSharable(Connection c, Boolean value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.set_sharable"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1699,9 +1737,9 @@ public class VDI extends XenAPIObject { * @param value The new value of the VDI's read_only field */ public void setReadOnly(Connection c, Boolean value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.set_read_only"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1715,9 +1753,9 @@ public class VDI extends XenAPIObject { * @param value The new value of the VDI's missing field */ public void setMissing(Connection c, Boolean value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.set_missing"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1731,9 +1769,9 @@ public class VDI extends XenAPIObject { * @param value The new value of the VDI's virtual size */ public void setVirtualSize(Connection c, Long value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.set_virtual_size"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1747,9 +1785,9 @@ public class VDI extends XenAPIObject { * @param value The new value of the VDI's physical utilisation */ public void setPhysicalUtilisation(Connection c, Long value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.set_physical_utilisation"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1763,9 +1801,9 @@ public class VDI extends XenAPIObject { * @param value The new value indicating whether this VDI is a snapshot */ public void setIsASnapshot(Connection c, Boolean value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.set_is_a_snapshot"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1779,9 +1817,9 @@ public class VDI extends XenAPIObject { * @param value The VDI of which this VDI is a snapshot */ public void setSnapshotOf(Connection c, VDI value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.set_snapshot_of"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1795,9 +1833,9 @@ public class VDI extends XenAPIObject { * @param value The snapshot time of this VDI. */ public void setSnapshotTime(Connection c, Date value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.set_snapshot_time"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1811,9 +1849,9 @@ public class VDI extends XenAPIObject { * @param value The pool whose metadata is contained by this VDI */ public void setMetadataOfPool(Connection c, Pool value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.set_metadata_of_pool"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1828,9 +1866,9 @@ public class VDI extends XenAPIObject { * @return Task */ public Task setNameLabelAsync(Connection c, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VDI.set_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1845,9 +1883,9 @@ public class VDI extends XenAPIObject { * @param value The name lable for the VDI */ public void setNameLabel(Connection c, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.set_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1862,9 +1900,9 @@ public class VDI extends XenAPIObject { * @return Task */ public Task setNameDescriptionAsync(Connection c, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VDI.set_name_description"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1879,9 +1917,9 @@ public class VDI extends XenAPIObject { * @param value The name description for the VDI */ public void setNameDescription(Connection c, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.set_name_description"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1896,9 +1934,9 @@ public class VDI extends XenAPIObject { * @return Task */ public Task setOnBootAsync(Connection c, Types.OnBoot value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VDI.set_on_boot"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1913,9 +1951,9 @@ public class VDI extends XenAPIObject { * @param value The value to set */ public void setOnBoot(Connection c, Types.OnBoot value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.set_on_boot"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1930,9 +1968,9 @@ public class VDI extends XenAPIObject { * @return Task */ public Task setAllowCachingAsync(Connection c, Boolean value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VDI.set_allow_caching"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1947,9 +1985,9 @@ public class VDI extends XenAPIObject { * @param value The value to set */ public void setAllowCaching(Connection c, Boolean value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.set_allow_caching"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1963,9 +2001,9 @@ public class VDI extends XenAPIObject { * @return Task */ public Task openDatabaseAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VDI.open_database"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -1980,15 +2018,15 @@ public class VDI extends XenAPIObject { * @return A session which can be used to query the database */ public Session openDatabase(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.open_database"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSession(result); + return Types.toSession(result); } /** @@ -1997,9 +2035,9 @@ public class VDI extends XenAPIObject { * @return Task */ public Task readDatabasePoolUuidAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VDI.read_database_pool_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -2014,15 +2052,15 @@ public class VDI extends XenAPIObject { * @return The cached pool UUID of the database on the VDI. */ public String readDatabasePoolUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.read_database_pool_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -2033,9 +2071,9 @@ public class VDI extends XenAPIObject { * @return Task */ public Task poolMigrateAsync(Connection c, SR sr, Map options) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VDI.pool_migrate"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(sr), Marshalling.toXMLRPC(options)}; @@ -2052,15 +2090,15 @@ public class VDI extends XenAPIObject { * @return The new reference of the migrated VDI. */ public VDI poolMigrate(Connection c, SR sr, Map options) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.pool_migrate"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(sr), Marshalling.toXMLRPC(options)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVDI(result); + return Types.toVDI(result); } /** @@ -2069,15 +2107,15 @@ public class VDI extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVDI(result); + return Types.toSetOfVDI(result); } /** @@ -2086,15 +2124,15 @@ public class VDI extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VDI.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfVDIVDIRecord(result); + return Types.toMapOfVDIVDIRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/VGPU.java b/deps/XenServerJava/src/com/xensource/xenapi/VGPU.java index 075ab54757c..19c88fd4561 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/VGPU.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/VGPU.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class VGPU extends XenAPIObject { * For internal use only. */ VGPU(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class VGPU extends XenAPIObject { { if (obj != null && obj instanceof VGPU) { - VGPU other = (VGPU) obj; + VGPU other = (VGPU)obj; return other.ref.equals(this.ref); } else { @@ -112,8 +111,8 @@ public class VGPU extends XenAPIObject { /** * Convert a VGPU.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("VM", this.VM == null ? new VM("OpaqueRef:NULL") : this.VM); map.put("GPU_group", this.GPUGroup == null ? new GPUGroup("OpaqueRef:NULL") : this.GPUGroup); @@ -155,15 +154,15 @@ public class VGPU extends XenAPIObject { * @return all fields from the object */ public VGPU.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VGPU.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVGPURecord(result); + return Types.toVGPURecord(result); } /** @@ -173,15 +172,15 @@ public class VGPU extends XenAPIObject { * @return reference to the object */ public static VGPU getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VGPU.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVGPU(result); + return Types.toVGPU(result); } /** @@ -190,15 +189,15 @@ public class VGPU extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VGPU.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -207,15 +206,15 @@ public class VGPU extends XenAPIObject { * @return value of the field */ public VM getVM(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VGPU.get_VM"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVM(result); + return Types.toVM(result); } /** @@ -224,15 +223,15 @@ public class VGPU extends XenAPIObject { * @return value of the field */ public GPUGroup getGPUGroup(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VGPU.get_GPU_group"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toGPUGroup(result); + return Types.toGPUGroup(result); } /** @@ -241,15 +240,15 @@ public class VGPU extends XenAPIObject { * @return value of the field */ public String getDevice(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VGPU.get_device"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -258,15 +257,15 @@ public class VGPU extends XenAPIObject { * @return value of the field */ public Boolean getCurrentlyAttached(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VGPU.get_currently_attached"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -275,15 +274,15 @@ public class VGPU extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VGPU.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -292,9 +291,9 @@ public class VGPU extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VGPU.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -309,9 +308,9 @@ public class VGPU extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VGPU.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -325,9 +324,9 @@ public class VGPU extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VGPU.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -345,12 +344,13 @@ public class VGPU extends XenAPIObject { * @return Task */ public static Task createAsync(Connection c, VM VM, GPUGroup GPUGroup, String device, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VGPU.create"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(VM), Marshalling.toXMLRPC(GPUGroup), Marshalling.toXMLRPC(device), Marshalling.toXMLRPC(otherConfig)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(VM), Marshalling.toXMLRPC(GPUGroup), Marshalling.toXMLRPC(device), + Marshalling.toXMLRPC(otherConfig)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -366,15 +366,16 @@ public class VGPU extends XenAPIObject { * @return reference to the newly created object */ public static VGPU create(Connection c, VM VM, GPUGroup GPUGroup, String device, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VGPU.create"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(VM), Marshalling.toXMLRPC(GPUGroup), Marshalling.toXMLRPC(device), Marshalling.toXMLRPC(otherConfig)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(VM), Marshalling.toXMLRPC(GPUGroup), Marshalling.toXMLRPC(device), + Marshalling.toXMLRPC(otherConfig)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVGPU(result); + return Types.toVGPU(result); } /** @@ -383,9 +384,9 @@ public class VGPU extends XenAPIObject { * @return Task */ public Task destroyAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VGPU.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -399,9 +400,9 @@ public class VGPU extends XenAPIObject { * */ public void destroy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VGPU.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -415,15 +416,15 @@ public class VGPU extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VGPU.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVGPU(result); + return Types.toSetOfVGPU(result); } /** @@ -432,15 +433,15 @@ public class VGPU extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VGPU.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfVGPUVGPURecord(result); + return Types.toMapOfVGPUVGPURecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/VIF.java b/deps/XenServerJava/src/com/xensource/xenapi/VIF.java index c1d25b445ac..8302800686d 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/VIF.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/VIF.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class VIF extends XenAPIObject { * For internal use only. */ VIF(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class VIF extends XenAPIObject { { if (obj != null && obj instanceof VIF) { - VIF other = (VIF) obj; + VIF other = (VIF)obj; return other.ref.equals(this.ref); } else { @@ -127,8 +126,8 @@ public class VIF extends XenAPIObject { /** * Convert a VIF.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("allowed_operations", this.allowedOperations == null ? new LinkedHashSet() : this.allowedOperations); map.put("current_operations", this.currentOperations == null ? new HashMap() : this.currentOperations); @@ -245,15 +244,15 @@ public class VIF extends XenAPIObject { * @return all fields from the object */ public VIF.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVIFRecord(result); + return Types.toVIFRecord(result); } /** @@ -263,15 +262,15 @@ public class VIF extends XenAPIObject { * @return reference to the object */ public static VIF getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVIF(result); + return Types.toVIF(result); } /** @@ -281,9 +280,9 @@ public class VIF extends XenAPIObject { * @return Task */ public static Task createAsync(Connection c, VIF.Record record) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VIF.create"; String session = c.getSessionReference(); Map record_map = record.toMap(); @@ -300,16 +299,16 @@ public class VIF extends XenAPIObject { * @return reference to the newly created object */ public static VIF create(Connection c, VIF.Record record) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.create"; String session = c.getSessionReference(); Map record_map = record.toMap(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(record_map)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVIF(result); + return Types.toVIF(result); } /** @@ -318,9 +317,9 @@ public class VIF extends XenAPIObject { * @return Task */ public Task destroyAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VIF.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -334,9 +333,9 @@ public class VIF extends XenAPIObject { * */ public void destroy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -350,15 +349,15 @@ public class VIF extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -367,15 +366,15 @@ public class VIF extends XenAPIObject { * @return value of the field */ public Set getAllowedOperations(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.get_allowed_operations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVifOperations(result); + return Types.toSetOfVifOperations(result); } /** @@ -384,15 +383,15 @@ public class VIF extends XenAPIObject { * @return value of the field */ public Map getCurrentOperations(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.get_current_operations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringVifOperations(result); + return Types.toMapOfStringVifOperations(result); } /** @@ -401,15 +400,15 @@ public class VIF extends XenAPIObject { * @return value of the field */ public String getDevice(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.get_device"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -418,15 +417,15 @@ public class VIF extends XenAPIObject { * @return value of the field */ public Network getNetwork(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.get_network"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toNetwork(result); + return Types.toNetwork(result); } /** @@ -435,15 +434,15 @@ public class VIF extends XenAPIObject { * @return value of the field */ public VM getVM(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.get_VM"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVM(result); + return Types.toVM(result); } /** @@ -452,15 +451,15 @@ public class VIF extends XenAPIObject { * @return value of the field */ public String getMAC(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.get_MAC"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -469,15 +468,15 @@ public class VIF extends XenAPIObject { * @return value of the field */ public Long getMTU(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.get_MTU"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -486,15 +485,15 @@ public class VIF extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -503,15 +502,15 @@ public class VIF extends XenAPIObject { * @return value of the field */ public Boolean getCurrentlyAttached(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.get_currently_attached"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -520,15 +519,15 @@ public class VIF extends XenAPIObject { * @return value of the field */ public Long getStatusCode(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.get_status_code"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -537,15 +536,15 @@ public class VIF extends XenAPIObject { * @return value of the field */ public String getStatusDetail(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.get_status_detail"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -554,15 +553,15 @@ public class VIF extends XenAPIObject { * @return value of the field */ public Map getRuntimeProperties(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.get_runtime_properties"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -571,15 +570,15 @@ public class VIF extends XenAPIObject { * @return value of the field */ public String getQosAlgorithmType(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.get_qos_algorithm_type"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -588,15 +587,15 @@ public class VIF extends XenAPIObject { * @return value of the field */ public Map getQosAlgorithmParams(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.get_qos_algorithm_params"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -605,15 +604,15 @@ public class VIF extends XenAPIObject { * @return value of the field */ public Set getQosSupportedAlgorithms(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.get_qos_supported_algorithms"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -622,15 +621,15 @@ public class VIF extends XenAPIObject { * @return value of the field */ public VIFMetrics getMetrics(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.get_metrics"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVIFMetrics(result); + return Types.toVIFMetrics(result); } /** @@ -639,15 +638,15 @@ public class VIF extends XenAPIObject { * @return value of the field */ public Boolean getMACAutogenerated(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.get_MAC_autogenerated"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -656,15 +655,15 @@ public class VIF extends XenAPIObject { * @return value of the field */ public Types.VifLockingMode getLockingMode(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.get_locking_mode"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVifLockingMode(result); + return Types.toVifLockingMode(result); } /** @@ -673,15 +672,15 @@ public class VIF extends XenAPIObject { * @return value of the field */ public Set getIpv4Allowed(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.get_ipv4_allowed"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -690,15 +689,15 @@ public class VIF extends XenAPIObject { * @return value of the field */ public Set getIpv6Allowed(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.get_ipv6_allowed"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -707,9 +706,9 @@ public class VIF extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -724,9 +723,9 @@ public class VIF extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -740,9 +739,9 @@ public class VIF extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -756,9 +755,9 @@ public class VIF extends XenAPIObject { * @param algorithmType New value to set */ public void setQosAlgorithmType(Connection c, String algorithmType) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.set_qos_algorithm_type"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(algorithmType)}; @@ -772,9 +771,9 @@ public class VIF extends XenAPIObject { * @param algorithmParams New value to set */ public void setQosAlgorithmParams(Connection c, Map algorithmParams) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.set_qos_algorithm_params"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(algorithmParams)}; @@ -789,9 +788,9 @@ public class VIF extends XenAPIObject { * @param value Value to add */ public void addToQosAlgorithmParams(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.add_to_qos_algorithm_params"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -805,9 +804,9 @@ public class VIF extends XenAPIObject { * @param key Key to remove */ public void removeFromQosAlgorithmParams(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.remove_from_qos_algorithm_params"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -821,9 +820,9 @@ public class VIF extends XenAPIObject { * @return Task */ public Task plugAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VIF.plug"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -837,9 +836,9 @@ public class VIF extends XenAPIObject { * */ public void plug(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.plug"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -853,9 +852,9 @@ public class VIF extends XenAPIObject { * @return Task */ public Task unplugAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VIF.unplug"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -869,9 +868,9 @@ public class VIF extends XenAPIObject { * */ public void unplug(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.unplug"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -885,9 +884,9 @@ public class VIF extends XenAPIObject { * @return Task */ public Task unplugForceAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VIF.unplug_force"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -901,9 +900,9 @@ public class VIF extends XenAPIObject { * */ public void unplugForce(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.unplug_force"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -918,9 +917,9 @@ public class VIF extends XenAPIObject { * @return Task */ public Task setLockingModeAsync(Connection c, Types.VifLockingMode value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VIF.set_locking_mode"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -935,9 +934,9 @@ public class VIF extends XenAPIObject { * @param value The new locking mode for the VIF */ public void setLockingMode(Connection c, Types.VifLockingMode value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.set_locking_mode"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -952,9 +951,9 @@ public class VIF extends XenAPIObject { * @return Task */ public Task setIpv4AllowedAsync(Connection c, Set value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VIF.set_ipv4_allowed"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -969,9 +968,9 @@ public class VIF extends XenAPIObject { * @param value The IP addresses which will be associated with the VIF */ public void setIpv4Allowed(Connection c, Set value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.set_ipv4_allowed"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -986,9 +985,9 @@ public class VIF extends XenAPIObject { * @return Task */ public Task addIpv4AllowedAsync(Connection c, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VIF.add_ipv4_allowed"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1003,9 +1002,9 @@ public class VIF extends XenAPIObject { * @param value The IP address which will be associated with the VIF */ public void addIpv4Allowed(Connection c, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.add_ipv4_allowed"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1020,9 +1019,9 @@ public class VIF extends XenAPIObject { * @return Task */ public Task removeIpv4AllowedAsync(Connection c, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VIF.remove_ipv4_allowed"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1037,9 +1036,9 @@ public class VIF extends XenAPIObject { * @param value The IP address which will be removed from the VIF */ public void removeIpv4Allowed(Connection c, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.remove_ipv4_allowed"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1054,9 +1053,9 @@ public class VIF extends XenAPIObject { * @return Task */ public Task setIpv6AllowedAsync(Connection c, Set value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VIF.set_ipv6_allowed"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1071,9 +1070,9 @@ public class VIF extends XenAPIObject { * @param value The IP addresses which will be associated with the VIF */ public void setIpv6Allowed(Connection c, Set value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.set_ipv6_allowed"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1088,9 +1087,9 @@ public class VIF extends XenAPIObject { * @return Task */ public Task addIpv6AllowedAsync(Connection c, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VIF.add_ipv6_allowed"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1105,9 +1104,9 @@ public class VIF extends XenAPIObject { * @param value The IP address which will be associated with the VIF */ public void addIpv6Allowed(Connection c, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.add_ipv6_allowed"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1122,9 +1121,9 @@ public class VIF extends XenAPIObject { * @return Task */ public Task removeIpv6AllowedAsync(Connection c, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VIF.remove_ipv6_allowed"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1139,9 +1138,9 @@ public class VIF extends XenAPIObject { * @param value The IP address which will be removed from the VIF */ public void removeIpv6Allowed(Connection c, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.remove_ipv6_allowed"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1155,15 +1154,15 @@ public class VIF extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVIF(result); + return Types.toSetOfVIF(result); } /** @@ -1172,15 +1171,15 @@ public class VIF extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfVIFVIFRecord(result); + return Types.toMapOfVIFVIFRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/VIFMetrics.java b/deps/XenServerJava/src/com/xensource/xenapi/VIFMetrics.java index ed7504c17b1..0c17217956d 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/VIFMetrics.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/VIFMetrics.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class VIFMetrics extends XenAPIObject { * For internal use only. */ VIFMetrics(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class VIFMetrics extends XenAPIObject { { if (obj != null && obj instanceof VIFMetrics) { - VIFMetrics other = (VIFMetrics) obj; + VIFMetrics other = (VIFMetrics)obj; return other.ref.equals(this.ref); } else { @@ -111,8 +110,8 @@ public class VIFMetrics extends XenAPIObject { /** * Convert a VIF_metrics.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("io_read_kbs", this.ioReadKbs == null ? 0.0 : this.ioReadKbs); map.put("io_write_kbs", this.ioWriteKbs == null ? 0.0 : this.ioWriteKbs); @@ -149,15 +148,15 @@ public class VIFMetrics extends XenAPIObject { * @return all fields from the object */ public VIFMetrics.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF_metrics.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVIFMetricsRecord(result); + return Types.toVIFMetricsRecord(result); } /** @@ -167,15 +166,15 @@ public class VIFMetrics extends XenAPIObject { * @return reference to the object */ public static VIFMetrics getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF_metrics.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVIFMetrics(result); + return Types.toVIFMetrics(result); } /** @@ -184,15 +183,15 @@ public class VIFMetrics extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF_metrics.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -201,15 +200,15 @@ public class VIFMetrics extends XenAPIObject { * @return value of the field */ public Double getIoReadKbs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF_metrics.get_io_read_kbs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDouble(result); + return Types.toDouble(result); } /** @@ -218,15 +217,15 @@ public class VIFMetrics extends XenAPIObject { * @return value of the field */ public Double getIoWriteKbs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF_metrics.get_io_write_kbs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDouble(result); + return Types.toDouble(result); } /** @@ -235,15 +234,15 @@ public class VIFMetrics extends XenAPIObject { * @return value of the field */ public Date getLastUpdated(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF_metrics.get_last_updated"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDate(result); + return Types.toDate(result); } /** @@ -252,15 +251,15 @@ public class VIFMetrics extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF_metrics.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -269,9 +268,9 @@ public class VIFMetrics extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF_metrics.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -286,9 +285,9 @@ public class VIFMetrics extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF_metrics.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -302,9 +301,9 @@ public class VIFMetrics extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF_metrics.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -318,15 +317,15 @@ public class VIFMetrics extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF_metrics.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVIFMetrics(result); + return Types.toSetOfVIFMetrics(result); } /** @@ -335,15 +334,15 @@ public class VIFMetrics extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VIF_metrics.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfVIFMetricsVIFMetricsRecord(result); + return Types.toMapOfVIFMetricsVIFMetricsRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/VLAN.java b/deps/XenServerJava/src/com/xensource/xenapi/VLAN.java index 232640527ac..9bea0399a45 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/VLAN.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/VLAN.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class VLAN extends XenAPIObject { * For internal use only. */ VLAN(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class VLAN extends XenAPIObject { { if (obj != null && obj instanceof VLAN) { - VLAN other = (VLAN) obj; + VLAN other = (VLAN)obj; return other.ref.equals(this.ref); } else { @@ -111,8 +110,8 @@ public class VLAN extends XenAPIObject { /** * Convert a VLAN.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("tagged_PIF", this.taggedPIF == null ? new PIF("OpaqueRef:NULL") : this.taggedPIF); map.put("untagged_PIF", this.untaggedPIF == null ? new PIF("OpaqueRef:NULL") : this.untaggedPIF); @@ -149,15 +148,15 @@ public class VLAN extends XenAPIObject { * @return all fields from the object */ public VLAN.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VLAN.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVLANRecord(result); + return Types.toVLANRecord(result); } /** @@ -167,15 +166,15 @@ public class VLAN extends XenAPIObject { * @return reference to the object */ public static VLAN getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VLAN.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVLAN(result); + return Types.toVLAN(result); } /** @@ -184,15 +183,15 @@ public class VLAN extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VLAN.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -201,15 +200,15 @@ public class VLAN extends XenAPIObject { * @return value of the field */ public PIF getTaggedPIF(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VLAN.get_tagged_PIF"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toPIF(result); + return Types.toPIF(result); } /** @@ -218,15 +217,15 @@ public class VLAN extends XenAPIObject { * @return value of the field */ public PIF getUntaggedPIF(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VLAN.get_untagged_PIF"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toPIF(result); + return Types.toPIF(result); } /** @@ -235,15 +234,15 @@ public class VLAN extends XenAPIObject { * @return value of the field */ public Long getTag(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VLAN.get_tag"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -252,15 +251,15 @@ public class VLAN extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VLAN.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -269,9 +268,9 @@ public class VLAN extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VLAN.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -286,9 +285,9 @@ public class VLAN extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VLAN.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -302,9 +301,9 @@ public class VLAN extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VLAN.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -321,9 +320,9 @@ public class VLAN extends XenAPIObject { * @return Task */ public static Task createAsync(Connection c, PIF taggedPIF, Long tag, Network network) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VLAN.create"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(taggedPIF), Marshalling.toXMLRPC(tag), Marshalling.toXMLRPC(network)}; @@ -341,15 +340,15 @@ public class VLAN extends XenAPIObject { * @return The reference of the created VLAN object */ public static VLAN create(Connection c, PIF taggedPIF, Long tag, Network network) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VLAN.create"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(taggedPIF), Marshalling.toXMLRPC(tag), Marshalling.toXMLRPC(network)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVLAN(result); + return Types.toVLAN(result); } /** @@ -358,9 +357,9 @@ public class VLAN extends XenAPIObject { * @return Task */ public Task destroyAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VLAN.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -374,9 +373,9 @@ public class VLAN extends XenAPIObject { * */ public void destroy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VLAN.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -390,15 +389,15 @@ public class VLAN extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VLAN.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVLAN(result); + return Types.toSetOfVLAN(result); } /** @@ -407,15 +406,15 @@ public class VLAN extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VLAN.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfVLANVLANRecord(result); + return Types.toMapOfVLANVLANRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/VM.java b/deps/XenServerJava/src/com/xensource/xenapi/VM.java index 736026654d7..cfa5e6c97c7 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/VM.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/VM.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class VM extends XenAPIObject { * For internal use only. */ VM(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class VM extends XenAPIObject { { if (obj != null && obj instanceof VM) { - VM other = (VM) obj; + VM other = (VM)obj; return other.ref.equals(this.ref); } else { @@ -180,8 +179,8 @@ public class VM extends XenAPIObject { /** * Convert a VM.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("allowed_operations", this.allowedOperations == null ? new LinkedHashSet() : this.allowedOperations); map.put("current_operations", this.currentOperations == null ? new HashMap() : this.currentOperations); @@ -563,15 +562,15 @@ public class VM extends XenAPIObject { * @return all fields from the object */ public VM.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVMRecord(result); + return Types.toVMRecord(result); } /** @@ -581,15 +580,15 @@ public class VM extends XenAPIObject { * @return reference to the object */ public static VM getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVM(result); + return Types.toVM(result); } /** @@ -599,9 +598,9 @@ public class VM extends XenAPIObject { * @return Task */ public static Task createAsync(Connection c, VM.Record record) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM.create"; String session = c.getSessionReference(); Map record_map = record.toMap(); @@ -618,16 +617,16 @@ public class VM extends XenAPIObject { * @return reference to the newly created object */ public static VM create(Connection c, VM.Record record) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.create"; String session = c.getSessionReference(); Map record_map = record.toMap(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(record_map)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVM(result); + return Types.toVM(result); } /** @@ -636,9 +635,9 @@ public class VM extends XenAPIObject { * @return Task */ public Task destroyAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -652,9 +651,9 @@ public class VM extends XenAPIObject { * */ public void destroy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -669,15 +668,15 @@ public class VM extends XenAPIObject { * @return references to objects with matching names */ public static Set getByNameLabel(Connection c, String label) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_by_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(label)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVM(result); + return Types.toSetOfVM(result); } /** @@ -686,15 +685,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -703,15 +702,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Set getAllowedOperations(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_allowed_operations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVmOperations(result); + return Types.toSetOfVmOperations(result); } /** @@ -720,15 +719,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Map getCurrentOperations(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_current_operations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringVmOperations(result); + return Types.toMapOfStringVmOperations(result); } /** @@ -737,15 +736,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Types.VmPowerState getPowerState(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_power_state"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVmPowerState(result); + return Types.toVmPowerState(result); } /** @@ -754,15 +753,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public String getNameLabel(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -771,15 +770,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public String getNameDescription(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_name_description"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -788,15 +787,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Long getUserVersion(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_user_version"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -805,15 +804,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Boolean getIsATemplate(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_is_a_template"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -822,15 +821,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public VDI getSuspendVDI(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_suspend_VDI"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVDI(result); + return Types.toVDI(result); } /** @@ -839,15 +838,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Host getResidentOn(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_resident_on"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toHost(result); + return Types.toHost(result); } /** @@ -856,15 +855,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Host getAffinity(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_affinity"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toHost(result); + return Types.toHost(result); } /** @@ -873,15 +872,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Long getMemoryOverhead(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_memory_overhead"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -890,16 +889,17 @@ public class VM extends XenAPIObject { * * @return value of the field */ - @Deprecated public Long getMemoryTarget(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + @Deprecated + public Long getMemoryTarget(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_memory_target"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -908,15 +908,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Long getMemoryStaticMax(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_memory_static_max"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -925,15 +925,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Long getMemoryDynamicMax(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_memory_dynamic_max"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -942,15 +942,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Long getMemoryDynamicMin(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_memory_dynamic_min"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -959,15 +959,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Long getMemoryStaticMin(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_memory_static_min"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -976,15 +976,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Map getVCPUsParams(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_VCPUs_params"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -993,15 +993,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Long getVCPUsMax(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_VCPUs_max"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -1010,15 +1010,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Long getVCPUsAtStartup(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_VCPUs_at_startup"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -1027,15 +1027,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Types.OnNormalExit getActionsAfterShutdown(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_actions_after_shutdown"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toOnNormalExit(result); + return Types.toOnNormalExit(result); } /** @@ -1044,15 +1044,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Types.OnNormalExit getActionsAfterReboot(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_actions_after_reboot"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toOnNormalExit(result); + return Types.toOnNormalExit(result); } /** @@ -1061,15 +1061,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Types.OnCrashBehaviour getActionsAfterCrash(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_actions_after_crash"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toOnCrashBehaviour(result); + return Types.toOnCrashBehaviour(result); } /** @@ -1078,15 +1078,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Set getConsoles(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_consoles"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfConsole(result); + return Types.toSetOfConsole(result); } /** @@ -1095,15 +1095,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Set getVIFs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_VIFs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVIF(result); + return Types.toSetOfVIF(result); } /** @@ -1112,15 +1112,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Set getVBDs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_VBDs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVBD(result); + return Types.toSetOfVBD(result); } /** @@ -1129,15 +1129,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Set getCrashDumps(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_crash_dumps"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfCrashdump(result); + return Types.toSetOfCrashdump(result); } /** @@ -1146,15 +1146,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Set getVTPMs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_VTPMs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVTPM(result); + return Types.toSetOfVTPM(result); } /** @@ -1163,15 +1163,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public String getPVBootloader(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_PV_bootloader"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -1180,15 +1180,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public String getPVKernel(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_PV_kernel"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -1197,15 +1197,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public String getPVRamdisk(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_PV_ramdisk"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -1214,15 +1214,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public String getPVArgs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_PV_args"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -1231,15 +1231,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public String getPVBootloaderArgs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_PV_bootloader_args"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -1248,15 +1248,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public String getPVLegacyArgs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_PV_legacy_args"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -1265,15 +1265,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public String getHVMBootPolicy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_HVM_boot_policy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -1282,15 +1282,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Map getHVMBootParams(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_HVM_boot_params"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -1299,15 +1299,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Double getHVMShadowMultiplier(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_HVM_shadow_multiplier"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDouble(result); + return Types.toDouble(result); } /** @@ -1316,15 +1316,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Map getPlatform(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_platform"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -1333,16 +1333,17 @@ public class VM extends XenAPIObject { * * @return value of the field */ - @Deprecated public String getPCIBus(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + @Deprecated + public String getPCIBus(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_PCI_bus"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -1351,15 +1352,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -1368,15 +1369,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Long getDomid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_domid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -1385,15 +1386,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public String getDomarch(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_domarch"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -1402,15 +1403,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Map getLastBootCPUFlags(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_last_boot_CPU_flags"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -1419,15 +1420,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Boolean getIsControlDomain(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_is_control_domain"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -1436,15 +1437,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public VMMetrics getMetrics(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_metrics"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVMMetrics(result); + return Types.toVMMetrics(result); } /** @@ -1453,15 +1454,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public VMGuestMetrics getGuestMetrics(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_guest_metrics"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVMGuestMetrics(result); + return Types.toVMGuestMetrics(result); } /** @@ -1470,15 +1471,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public String getLastBootedRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_last_booted_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -1487,15 +1488,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public String getRecommendations(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_recommendations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -1504,15 +1505,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Map getXenstoreData(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_xenstore_data"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -1521,16 +1522,17 @@ public class VM extends XenAPIObject { * * @return value of the field */ - @Deprecated public Boolean getHaAlwaysRun(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + @Deprecated + public Boolean getHaAlwaysRun(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_ha_always_run"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -1539,15 +1541,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public String getHaRestartPriority(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_ha_restart_priority"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -1556,15 +1558,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Boolean getIsASnapshot(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_is_a_snapshot"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -1573,15 +1575,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public VM getSnapshotOf(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_snapshot_of"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVM(result); + return Types.toVM(result); } /** @@ -1590,15 +1592,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Set getSnapshots(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_snapshots"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVM(result); + return Types.toSetOfVM(result); } /** @@ -1607,15 +1609,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Date getSnapshotTime(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_snapshot_time"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDate(result); + return Types.toDate(result); } /** @@ -1624,15 +1626,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public String getTransportableSnapshotId(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_transportable_snapshot_id"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -1641,15 +1643,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Map getBlobs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_blobs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringBlob(result); + return Types.toMapOfStringBlob(result); } /** @@ -1658,15 +1660,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Set getTags(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_tags"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -1675,15 +1677,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Map getBlockedOperations(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_blocked_operations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfVmOperationsString(result); + return Types.toMapOfVmOperationsString(result); } /** @@ -1692,15 +1694,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Map getSnapshotInfo(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_snapshot_info"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -1709,15 +1711,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public String getSnapshotMetadata(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_snapshot_metadata"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -1726,15 +1728,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public VM getParent(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_parent"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVM(result); + return Types.toVM(result); } /** @@ -1743,15 +1745,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Set getChildren(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_children"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVM(result); + return Types.toSetOfVM(result); } /** @@ -1760,15 +1762,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Map getBiosStrings(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_bios_strings"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -1777,15 +1779,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public VMPP getProtectionPolicy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_protection_policy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVMPP(result); + return Types.toVMPP(result); } /** @@ -1794,15 +1796,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Boolean getIsSnapshotFromVmpp(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_is_snapshot_from_vmpp"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -1811,15 +1813,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public VMAppliance getAppliance(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_appliance"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVMAppliance(result); + return Types.toVMAppliance(result); } /** @@ -1828,15 +1830,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Long getStartDelay(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_start_delay"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -1845,15 +1847,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Long getShutdownDelay(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_shutdown_delay"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -1862,15 +1864,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Long getOrder(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_order"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -1879,15 +1881,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Set getVGPUs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_VGPUs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVGPU(result); + return Types.toSetOfVGPU(result); } /** @@ -1896,15 +1898,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Set getAttachedPCIs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_attached_PCIs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfPCI(result); + return Types.toSetOfPCI(result); } /** @@ -1913,15 +1915,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public SR getSuspendSR(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_suspend_SR"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSR(result); + return Types.toSR(result); } /** @@ -1930,15 +1932,15 @@ public class VM extends XenAPIObject { * @return value of the field */ public Long getVersion(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_version"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -1947,9 +1949,9 @@ public class VM extends XenAPIObject { * @param label New value to set */ public void setNameLabel(Connection c, String label) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(label)}; @@ -1963,9 +1965,9 @@ public class VM extends XenAPIObject { * @param description New value to set */ public void setNameDescription(Connection c, String description) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_name_description"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(description)}; @@ -1979,9 +1981,9 @@ public class VM extends XenAPIObject { * @param userVersion New value to set */ public void setUserVersion(Connection c, Long userVersion) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_user_version"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(userVersion)}; @@ -1995,9 +1997,9 @@ public class VM extends XenAPIObject { * @param isATemplate New value to set */ public void setIsATemplate(Connection c, Boolean isATemplate) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_is_a_template"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(isATemplate)}; @@ -2011,9 +2013,9 @@ public class VM extends XenAPIObject { * @param affinity New value to set */ public void setAffinity(Connection c, Host affinity) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_affinity"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(affinity)}; @@ -2027,9 +2029,9 @@ public class VM extends XenAPIObject { * @param params New value to set */ public void setVCPUsParams(Connection c, Map params) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_VCPUs_params"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(params)}; @@ -2044,9 +2046,9 @@ public class VM extends XenAPIObject { * @param value Value to add */ public void addToVCPUsParams(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.add_to_VCPUs_params"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -2060,9 +2062,9 @@ public class VM extends XenAPIObject { * @param key Key to remove */ public void removeFromVCPUsParams(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.remove_from_VCPUs_params"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -2076,9 +2078,9 @@ public class VM extends XenAPIObject { * @param afterShutdown New value to set */ public void setActionsAfterShutdown(Connection c, Types.OnNormalExit afterShutdown) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_actions_after_shutdown"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(afterShutdown)}; @@ -2092,9 +2094,9 @@ public class VM extends XenAPIObject { * @param afterReboot New value to set */ public void setActionsAfterReboot(Connection c, Types.OnNormalExit afterReboot) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_actions_after_reboot"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(afterReboot)}; @@ -2108,9 +2110,9 @@ public class VM extends XenAPIObject { * @param afterCrash New value to set */ public void setActionsAfterCrash(Connection c, Types.OnCrashBehaviour afterCrash) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_actions_after_crash"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(afterCrash)}; @@ -2124,9 +2126,9 @@ public class VM extends XenAPIObject { * @param bootloader New value to set */ public void setPVBootloader(Connection c, String bootloader) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_PV_bootloader"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(bootloader)}; @@ -2140,9 +2142,9 @@ public class VM extends XenAPIObject { * @param kernel New value to set */ public void setPVKernel(Connection c, String kernel) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_PV_kernel"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(kernel)}; @@ -2156,9 +2158,9 @@ public class VM extends XenAPIObject { * @param ramdisk New value to set */ public void setPVRamdisk(Connection c, String ramdisk) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_PV_ramdisk"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(ramdisk)}; @@ -2172,9 +2174,9 @@ public class VM extends XenAPIObject { * @param args New value to set */ public void setPVArgs(Connection c, String args) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_PV_args"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(args)}; @@ -2188,9 +2190,9 @@ public class VM extends XenAPIObject { * @param bootloaderArgs New value to set */ public void setPVBootloaderArgs(Connection c, String bootloaderArgs) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_PV_bootloader_args"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(bootloaderArgs)}; @@ -2204,9 +2206,9 @@ public class VM extends XenAPIObject { * @param legacyArgs New value to set */ public void setPVLegacyArgs(Connection c, String legacyArgs) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_PV_legacy_args"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(legacyArgs)}; @@ -2220,9 +2222,9 @@ public class VM extends XenAPIObject { * @param bootPolicy New value to set */ public void setHVMBootPolicy(Connection c, String bootPolicy) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_HVM_boot_policy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(bootPolicy)}; @@ -2236,9 +2238,9 @@ public class VM extends XenAPIObject { * @param bootParams New value to set */ public void setHVMBootParams(Connection c, Map bootParams) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_HVM_boot_params"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(bootParams)}; @@ -2253,9 +2255,9 @@ public class VM extends XenAPIObject { * @param value Value to add */ public void addToHVMBootParams(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.add_to_HVM_boot_params"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -2269,9 +2271,9 @@ public class VM extends XenAPIObject { * @param key Key to remove */ public void removeFromHVMBootParams(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.remove_from_HVM_boot_params"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -2285,9 +2287,9 @@ public class VM extends XenAPIObject { * @param platform New value to set */ public void setPlatform(Connection c, Map platform) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_platform"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(platform)}; @@ -2302,9 +2304,9 @@ public class VM extends XenAPIObject { * @param value Value to add */ public void addToPlatform(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.add_to_platform"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -2318,9 +2320,9 @@ public class VM extends XenAPIObject { * @param key Key to remove */ public void removeFromPlatform(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.remove_from_platform"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -2334,10 +2336,11 @@ public class VM extends XenAPIObject { * * @param PCIBus New value to set */ - @Deprecated public void setPCIBus(Connection c, String PCIBus) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + @Deprecated + public void setPCIBus(Connection c, String PCIBus) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_PCI_bus"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(PCIBus)}; @@ -2351,9 +2354,9 @@ public class VM extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -2368,9 +2371,9 @@ public class VM extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -2384,9 +2387,9 @@ public class VM extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -2400,9 +2403,9 @@ public class VM extends XenAPIObject { * @param recommendations New value to set */ public void setRecommendations(Connection c, String recommendations) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_recommendations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(recommendations)}; @@ -2416,9 +2419,9 @@ public class VM extends XenAPIObject { * @param xenstoreData New value to set */ public void setXenstoreData(Connection c, Map xenstoreData) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_xenstore_data"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(xenstoreData)}; @@ -2433,9 +2436,9 @@ public class VM extends XenAPIObject { * @param value Value to add */ public void addToXenstoreData(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.add_to_xenstore_data"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -2449,9 +2452,9 @@ public class VM extends XenAPIObject { * @param key Key to remove */ public void removeFromXenstoreData(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.remove_from_xenstore_data"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -2465,9 +2468,9 @@ public class VM extends XenAPIObject { * @param tags New value to set */ public void setTags(Connection c, Set tags) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_tags"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(tags)}; @@ -2481,9 +2484,9 @@ public class VM extends XenAPIObject { * @param value New value to add */ public void addTags(Connection c, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.add_tags"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -2497,9 +2500,9 @@ public class VM extends XenAPIObject { * @param value Value to remove */ public void removeTags(Connection c, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.remove_tags"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -2513,9 +2516,9 @@ public class VM extends XenAPIObject { * @param blockedOperations New value to set */ public void setBlockedOperations(Connection c, Map blockedOperations) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_blocked_operations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(blockedOperations)}; @@ -2530,9 +2533,9 @@ public class VM extends XenAPIObject { * @param value Value to add */ public void addToBlockedOperations(Connection c, Types.VmOperations key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.add_to_blocked_operations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -2546,9 +2549,9 @@ public class VM extends XenAPIObject { * @param key Key to remove */ public void removeFromBlockedOperations(Connection c, Types.VmOperations key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.remove_from_blocked_operations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -2562,9 +2565,9 @@ public class VM extends XenAPIObject { * @param suspendSR New value to set */ public void setSuspendSR(Connection c, SR suspendSR) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_suspend_SR"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(suspendSR)}; @@ -2579,12 +2582,12 @@ public class VM extends XenAPIObject { * @return Task */ public Task snapshotAsync(Connection c, String newName) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.SrFull, - Types.OperationNotAllowed { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.SrFull, + Types.OperationNotAllowed { String method_call = "Async.VM.snapshot"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(newName)}; @@ -2600,18 +2603,18 @@ public class VM extends XenAPIObject { * @return The reference of the newly created VM. */ public VM snapshot(Connection c, String newName) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.SrFull, - Types.OperationNotAllowed { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.SrFull, + Types.OperationNotAllowed { String method_call = "VM.snapshot"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(newName)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVM(result); + return Types.toVM(result); } /** @@ -2621,16 +2624,16 @@ public class VM extends XenAPIObject { * @return Task */ public Task snapshotWithQuiesceAsync(Connection c, String newName) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.SrFull, - Types.OperationNotAllowed, - Types.VmSnapshotWithQuiesceFailed, - Types.VmSnapshotWithQuiesceTimeout, - Types.VmSnapshotWithQuiescePluginDeosNotRespond, - Types.VmSnapshotWithQuiesceNotSupported { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.SrFull, + Types.OperationNotAllowed, + Types.VmSnapshotWithQuiesceFailed, + Types.VmSnapshotWithQuiesceTimeout, + Types.VmSnapshotWithQuiescePluginDeosNotRespond, + Types.VmSnapshotWithQuiesceNotSupported { String method_call = "Async.VM.snapshot_with_quiesce"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(newName)}; @@ -2646,22 +2649,22 @@ public class VM extends XenAPIObject { * @return The reference of the newly created VM. */ public VM snapshotWithQuiesce(Connection c, String newName) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.SrFull, - Types.OperationNotAllowed, - Types.VmSnapshotWithQuiesceFailed, - Types.VmSnapshotWithQuiesceTimeout, - Types.VmSnapshotWithQuiescePluginDeosNotRespond, - Types.VmSnapshotWithQuiesceNotSupported { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.SrFull, + Types.OperationNotAllowed, + Types.VmSnapshotWithQuiesceFailed, + Types.VmSnapshotWithQuiesceTimeout, + Types.VmSnapshotWithQuiescePluginDeosNotRespond, + Types.VmSnapshotWithQuiesceNotSupported { String method_call = "VM.snapshot_with_quiesce"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(newName)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVM(result); + return Types.toVM(result); } /** @@ -2671,12 +2674,12 @@ public class VM extends XenAPIObject { * @return Task */ public Task createCloneAsync(Connection c, String newName) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.SrFull, - Types.OperationNotAllowed { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.SrFull, + Types.OperationNotAllowed { String method_call = "Async.VM.clone"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(newName)}; @@ -2692,18 +2695,18 @@ public class VM extends XenAPIObject { * @return The reference of the newly created VM. */ public VM createClone(Connection c, String newName) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.SrFull, - Types.OperationNotAllowed { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.SrFull, + Types.OperationNotAllowed { String method_call = "VM.clone"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(newName)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVM(result); + return Types.toVM(result); } /** @@ -2714,12 +2717,12 @@ public class VM extends XenAPIObject { * @return Task */ public Task copyAsync(Connection c, String newName, SR sr) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.SrFull, - Types.OperationNotAllowed { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.SrFull, + Types.OperationNotAllowed { String method_call = "Async.VM.copy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(newName), Marshalling.toXMLRPC(sr)}; @@ -2736,18 +2739,18 @@ public class VM extends XenAPIObject { * @return The reference of the newly created VM. */ public VM copy(Connection c, String newName, SR sr) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.SrFull, - Types.OperationNotAllowed { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.SrFull, + Types.OperationNotAllowed { String method_call = "VM.copy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(newName), Marshalling.toXMLRPC(sr)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVM(result); + return Types.toVM(result); } /** @@ -2756,13 +2759,13 @@ public class VM extends XenAPIObject { * @return Task */ public Task revertAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.OperationNotAllowed, - Types.SrFull, - Types.VmRevertFailed { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.OperationNotAllowed, + Types.SrFull, + Types.VmRevertFailed { String method_call = "Async.VM.revert"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -2776,13 +2779,13 @@ public class VM extends XenAPIObject { * */ public void revert(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.OperationNotAllowed, - Types.SrFull, - Types.VmRevertFailed { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.OperationNotAllowed, + Types.SrFull, + Types.VmRevertFailed { String method_call = "VM.revert"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -2797,14 +2800,14 @@ public class VM extends XenAPIObject { * @return Task */ public Task checkpointAsync(Connection c, String newName) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.SrFull, - Types.OperationNotAllowed, - Types.VmCheckpointSuspendFailed, - Types.VmCheckpointResumeFailed { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.SrFull, + Types.OperationNotAllowed, + Types.VmCheckpointSuspendFailed, + Types.VmCheckpointResumeFailed { String method_call = "Async.VM.checkpoint"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(newName)}; @@ -2820,20 +2823,20 @@ public class VM extends XenAPIObject { * @return The reference of the newly created VM. */ public VM checkpoint(Connection c, String newName) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.SrFull, - Types.OperationNotAllowed, - Types.VmCheckpointSuspendFailed, - Types.VmCheckpointResumeFailed { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.SrFull, + Types.OperationNotAllowed, + Types.VmCheckpointSuspendFailed, + Types.VmCheckpointResumeFailed { String method_call = "VM.checkpoint"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(newName)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVM(result); + return Types.toVM(result); } /** @@ -2842,12 +2845,12 @@ public class VM extends XenAPIObject { * @return Task */ public Task provisionAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.SrFull, - Types.OperationNotAllowed { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.SrFull, + Types.OperationNotAllowed { String method_call = "Async.VM.provision"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -2861,12 +2864,12 @@ public class VM extends XenAPIObject { * */ public void provision(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.SrFull, - Types.OperationNotAllowed { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.SrFull, + Types.OperationNotAllowed { String method_call = "VM.provision"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -2882,18 +2885,18 @@ public class VM extends XenAPIObject { * @return Task */ public Task startAsync(Connection c, Boolean startPaused, Boolean force) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.VmHvmRequired, - Types.VmIsTemplate, - Types.OtherOperationInProgress, - Types.OperationNotAllowed, - Types.BootloaderFailed, - Types.UnknownBootloader, - Types.NoHostsAvailable, - Types.LicenceRestriction { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.VmHvmRequired, + Types.VmIsTemplate, + Types.OtherOperationInProgress, + Types.OperationNotAllowed, + Types.BootloaderFailed, + Types.UnknownBootloader, + Types.NoHostsAvailable, + Types.LicenceRestriction { String method_call = "Async.VM.start"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(startPaused), Marshalling.toXMLRPC(force)}; @@ -2909,18 +2912,18 @@ public class VM extends XenAPIObject { * @param force Attempt to force the VM to start. If this flag is false then the VM may fail pre-boot safety checks (e.g. if the CPU the VM last booted on looks substantially different to the current one) */ public void start(Connection c, Boolean startPaused, Boolean force) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.VmHvmRequired, - Types.VmIsTemplate, - Types.OtherOperationInProgress, - Types.OperationNotAllowed, - Types.BootloaderFailed, - Types.UnknownBootloader, - Types.NoHostsAvailable, - Types.LicenceRestriction { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.VmHvmRequired, + Types.VmIsTemplate, + Types.OtherOperationInProgress, + Types.OperationNotAllowed, + Types.BootloaderFailed, + Types.UnknownBootloader, + Types.NoHostsAvailable, + Types.LicenceRestriction { String method_call = "VM.start"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(startPaused), Marshalling.toXMLRPC(force)}; @@ -2937,18 +2940,19 @@ public class VM extends XenAPIObject { * @return Task */ public Task startOnAsync(Connection c, Host host, Boolean startPaused, Boolean force) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.VmIsTemplate, - Types.OtherOperationInProgress, - Types.OperationNotAllowed, - Types.BootloaderFailed, - Types.UnknownBootloader { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.VmIsTemplate, + Types.OtherOperationInProgress, + Types.OperationNotAllowed, + Types.BootloaderFailed, + Types.UnknownBootloader { String method_call = "Async.VM.start_on"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(startPaused), Marshalling.toXMLRPC(force)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(startPaused), + Marshalling.toXMLRPC(force)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -2962,18 +2966,19 @@ public class VM extends XenAPIObject { * @param force Attempt to force the VM to start. If this flag is false then the VM may fail pre-boot safety checks (e.g. if the CPU the VM last booted on looks substantially different to the current one) */ public void startOn(Connection c, Host host, Boolean startPaused, Boolean force) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.VmIsTemplate, - Types.OtherOperationInProgress, - Types.OperationNotAllowed, - Types.BootloaderFailed, - Types.UnknownBootloader { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.VmIsTemplate, + Types.OtherOperationInProgress, + Types.OperationNotAllowed, + Types.BootloaderFailed, + Types.UnknownBootloader { String method_call = "VM.start_on"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(startPaused), Marshalling.toXMLRPC(force)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(startPaused), + Marshalling.toXMLRPC(force)}; Map response = c.dispatch(method_call, method_params); return; } @@ -2984,13 +2989,13 @@ public class VM extends XenAPIObject { * @return Task */ public Task pauseAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.OtherOperationInProgress, - Types.OperationNotAllowed, - Types.VmIsTemplate { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.OtherOperationInProgress, + Types.OperationNotAllowed, + Types.VmIsTemplate { String method_call = "Async.VM.pause"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -3004,13 +3009,13 @@ public class VM extends XenAPIObject { * */ public void pause(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.OtherOperationInProgress, - Types.OperationNotAllowed, - Types.VmIsTemplate { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.OtherOperationInProgress, + Types.OperationNotAllowed, + Types.VmIsTemplate { String method_call = "VM.pause"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -3024,12 +3029,12 @@ public class VM extends XenAPIObject { * @return Task */ public Task unpauseAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.OperationNotAllowed, - Types.VmIsTemplate { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.OperationNotAllowed, + Types.VmIsTemplate { String method_call = "Async.VM.unpause"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -3043,12 +3048,12 @@ public class VM extends XenAPIObject { * */ public void unpause(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.OperationNotAllowed, - Types.VmIsTemplate { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.OperationNotAllowed, + Types.VmIsTemplate { String method_call = "VM.unpause"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -3062,13 +3067,13 @@ public class VM extends XenAPIObject { * @return Task */ public Task cleanShutdownAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.OtherOperationInProgress, - Types.OperationNotAllowed, - Types.VmIsTemplate { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.OtherOperationInProgress, + Types.OperationNotAllowed, + Types.VmIsTemplate { String method_call = "Async.VM.clean_shutdown"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -3082,13 +3087,13 @@ public class VM extends XenAPIObject { * */ public void cleanShutdown(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.OtherOperationInProgress, - Types.OperationNotAllowed, - Types.VmIsTemplate { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.OtherOperationInProgress, + Types.OperationNotAllowed, + Types.VmIsTemplate { String method_call = "VM.clean_shutdown"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -3102,13 +3107,13 @@ public class VM extends XenAPIObject { * @return Task */ public Task cleanRebootAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.OtherOperationInProgress, - Types.OperationNotAllowed, - Types.VmIsTemplate { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.OtherOperationInProgress, + Types.OperationNotAllowed, + Types.VmIsTemplate { String method_call = "Async.VM.clean_reboot"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -3122,13 +3127,13 @@ public class VM extends XenAPIObject { * */ public void cleanReboot(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.OtherOperationInProgress, - Types.OperationNotAllowed, - Types.VmIsTemplate { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.OtherOperationInProgress, + Types.OperationNotAllowed, + Types.VmIsTemplate { String method_call = "VM.clean_reboot"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -3142,13 +3147,13 @@ public class VM extends XenAPIObject { * @return Task */ public Task hardShutdownAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.OtherOperationInProgress, - Types.OperationNotAllowed, - Types.VmIsTemplate { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.OtherOperationInProgress, + Types.OperationNotAllowed, + Types.VmIsTemplate { String method_call = "Async.VM.hard_shutdown"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -3162,13 +3167,13 @@ public class VM extends XenAPIObject { * */ public void hardShutdown(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.OtherOperationInProgress, - Types.OperationNotAllowed, - Types.VmIsTemplate { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.OtherOperationInProgress, + Types.OperationNotAllowed, + Types.VmIsTemplate { String method_call = "VM.hard_shutdown"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -3182,9 +3187,9 @@ public class VM extends XenAPIObject { * @return Task */ public Task powerStateResetAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM.power_state_reset"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -3198,9 +3203,9 @@ public class VM extends XenAPIObject { * */ public void powerStateReset(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.power_state_reset"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -3214,13 +3219,13 @@ public class VM extends XenAPIObject { * @return Task */ public Task hardRebootAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.OtherOperationInProgress, - Types.OperationNotAllowed, - Types.VmIsTemplate { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.OtherOperationInProgress, + Types.OperationNotAllowed, + Types.VmIsTemplate { String method_call = "Async.VM.hard_reboot"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -3234,13 +3239,13 @@ public class VM extends XenAPIObject { * */ public void hardReboot(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.OtherOperationInProgress, - Types.OperationNotAllowed, - Types.VmIsTemplate { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.OtherOperationInProgress, + Types.OperationNotAllowed, + Types.VmIsTemplate { String method_call = "VM.hard_reboot"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -3254,13 +3259,13 @@ public class VM extends XenAPIObject { * @return Task */ public Task suspendAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.OtherOperationInProgress, - Types.OperationNotAllowed, - Types.VmIsTemplate { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.OtherOperationInProgress, + Types.OperationNotAllowed, + Types.VmIsTemplate { String method_call = "Async.VM.suspend"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -3274,13 +3279,13 @@ public class VM extends XenAPIObject { * */ public void suspend(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.OtherOperationInProgress, - Types.OperationNotAllowed, - Types.VmIsTemplate { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.OtherOperationInProgress, + Types.OperationNotAllowed, + Types.VmIsTemplate { String method_call = "VM.suspend"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -3296,12 +3301,12 @@ public class VM extends XenAPIObject { * @return Task */ public Task resumeAsync(Connection c, Boolean startPaused, Boolean force) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.OperationNotAllowed, - Types.VmIsTemplate { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.OperationNotAllowed, + Types.VmIsTemplate { String method_call = "Async.VM.resume"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(startPaused), Marshalling.toXMLRPC(force)}; @@ -3317,12 +3322,12 @@ public class VM extends XenAPIObject { * @param force Attempt to force the VM to resume. If this flag is false then the VM may fail pre-resume safety checks (e.g. if the CPU the VM was running on looks substantially different to the current one) */ public void resume(Connection c, Boolean startPaused, Boolean force) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.OperationNotAllowed, - Types.VmIsTemplate { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.OperationNotAllowed, + Types.VmIsTemplate { String method_call = "VM.resume"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(startPaused), Marshalling.toXMLRPC(force)}; @@ -3339,15 +3344,16 @@ public class VM extends XenAPIObject { * @return Task */ public Task resumeOnAsync(Connection c, Host host, Boolean startPaused, Boolean force) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.OperationNotAllowed, - Types.VmIsTemplate { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.OperationNotAllowed, + Types.VmIsTemplate { String method_call = "Async.VM.resume_on"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(startPaused), Marshalling.toXMLRPC(force)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(startPaused), + Marshalling.toXMLRPC(force)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -3361,15 +3367,16 @@ public class VM extends XenAPIObject { * @param force Attempt to force the VM to resume. If this flag is false then the VM may fail pre-resume safety checks (e.g. if the CPU the VM was running on looks substantially different to the current one) */ public void resumeOn(Connection c, Host host, Boolean startPaused, Boolean force) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.OperationNotAllowed, - Types.VmIsTemplate { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.OperationNotAllowed, + Types.VmIsTemplate { String method_call = "VM.resume_on"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(startPaused), Marshalling.toXMLRPC(force)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(startPaused), + Marshalling.toXMLRPC(force)}; Map response = c.dispatch(method_call, method_params); return; } @@ -3382,15 +3389,15 @@ public class VM extends XenAPIObject { * @return Task */ public Task poolMigrateAsync(Connection c, Host host, Map options) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.OtherOperationInProgress, - Types.VmIsTemplate, - Types.OperationNotAllowed, - Types.VmMigrateFailed, - Types.VmMissingPvDrivers { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.OtherOperationInProgress, + Types.VmIsTemplate, + Types.OperationNotAllowed, + Types.VmMigrateFailed, + Types.VmMissingPvDrivers { String method_call = "Async.VM.pool_migrate"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(options)}; @@ -3406,15 +3413,15 @@ public class VM extends XenAPIObject { * @param options Extra configuration operations */ public void poolMigrate(Connection c, Host host, Map options) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState, - Types.OtherOperationInProgress, - Types.VmIsTemplate, - Types.OperationNotAllowed, - Types.VmMigrateFailed, - Types.VmMissingPvDrivers { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState, + Types.OtherOperationInProgress, + Types.VmIsTemplate, + Types.OperationNotAllowed, + Types.VmMigrateFailed, + Types.VmMissingPvDrivers { String method_call = "VM.pool_migrate"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(options)}; @@ -3429,9 +3436,9 @@ public class VM extends XenAPIObject { * @return Task */ public Task setVCPUsNumberLiveAsync(Connection c, Long nvcpu) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM.set_VCPUs_number_live"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(nvcpu)}; @@ -3446,9 +3453,9 @@ public class VM extends XenAPIObject { * @param nvcpu The number of VCPUs */ public void setVCPUsNumberLive(Connection c, Long nvcpu) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_VCPUs_number_live"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(nvcpu)}; @@ -3464,9 +3471,9 @@ public class VM extends XenAPIObject { * @return Task */ public Task addToVCPUsParamsLiveAsync(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM.add_to_VCPUs_params_live"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -3482,9 +3489,9 @@ public class VM extends XenAPIObject { * @param value The value */ public void addToVCPUsParamsLive(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.add_to_VCPUs_params_live"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -3498,9 +3505,9 @@ public class VM extends XenAPIObject { * @param value The value */ public void setHaRestartPriority(Connection c, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_ha_restart_priority"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -3514,10 +3521,11 @@ public class VM extends XenAPIObject { * * @param value The value */ - @Deprecated public void setHaAlwaysRun(Connection c, Boolean value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + @Deprecated + public void setHaAlwaysRun(Connection c, Boolean value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_ha_always_run"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -3531,9 +3539,9 @@ public class VM extends XenAPIObject { * @return Task */ public Task computeMemoryOverheadAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM.compute_memory_overhead"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -3548,15 +3556,15 @@ public class VM extends XenAPIObject { * @return the virtualization memory overhead of the VM. */ public Long computeMemoryOverhead(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.compute_memory_overhead"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -3565,9 +3573,9 @@ public class VM extends XenAPIObject { * @param value The new value of memory_dynamic_max */ public void setMemoryDynamicMax(Connection c, Long value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_memory_dynamic_max"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -3581,9 +3589,9 @@ public class VM extends XenAPIObject { * @param value The new value of memory_dynamic_min */ public void setMemoryDynamicMin(Connection c, Long value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_memory_dynamic_min"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -3599,9 +3607,9 @@ public class VM extends XenAPIObject { * @return Task */ public Task setMemoryDynamicRangeAsync(Connection c, Long min, Long max) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM.set_memory_dynamic_range"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(min), Marshalling.toXMLRPC(max)}; @@ -3617,9 +3625,9 @@ public class VM extends XenAPIObject { * @param max The new maximum value */ public void setMemoryDynamicRange(Connection c, Long min, Long max) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_memory_dynamic_range"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(min), Marshalling.toXMLRPC(max)}; @@ -3633,10 +3641,10 @@ public class VM extends XenAPIObject { * @param value The new value of memory_static_max */ public void setMemoryStaticMax(Connection c, Long value) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.HaOperationWouldBreakFailoverPlan { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.HaOperationWouldBreakFailoverPlan { String method_call = "VM.set_memory_static_max"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -3650,9 +3658,9 @@ public class VM extends XenAPIObject { * @param value The new value of memory_static_min */ public void setMemoryStaticMin(Connection c, Long value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_memory_static_min"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -3668,9 +3676,9 @@ public class VM extends XenAPIObject { * @return Task */ public Task setMemoryStaticRangeAsync(Connection c, Long min, Long max) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM.set_memory_static_range"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(min), Marshalling.toXMLRPC(max)}; @@ -3686,9 +3694,9 @@ public class VM extends XenAPIObject { * @param max The new maximum value */ public void setMemoryStaticRange(Connection c, Long min, Long max) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_memory_static_range"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(min), Marshalling.toXMLRPC(max)}; @@ -3706,12 +3714,13 @@ public class VM extends XenAPIObject { * @return Task */ public Task setMemoryLimitsAsync(Connection c, Long staticMin, Long staticMax, Long dynamicMin, Long dynamicMax) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM.set_memory_limits"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(staticMin), Marshalling.toXMLRPC(staticMax), Marshalling.toXMLRPC(dynamicMin), Marshalling.toXMLRPC(dynamicMax)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(staticMin), Marshalling.toXMLRPC(staticMax), + Marshalling.toXMLRPC(dynamicMin), Marshalling.toXMLRPC(dynamicMax)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -3726,12 +3735,13 @@ public class VM extends XenAPIObject { * @param dynamicMax The new value of memory_dynamic_max. */ public void setMemoryLimits(Connection c, Long staticMin, Long staticMax, Long dynamicMin, Long dynamicMax) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_memory_limits"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(staticMin), Marshalling.toXMLRPC(staticMax), Marshalling.toXMLRPC(dynamicMin), Marshalling.toXMLRPC(dynamicMax)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(staticMin), Marshalling.toXMLRPC(staticMax), + Marshalling.toXMLRPC(dynamicMin), Marshalling.toXMLRPC(dynamicMax)}; Map response = c.dispatch(method_call, method_params); return; } @@ -3743,10 +3753,11 @@ public class VM extends XenAPIObject { * @param target The target in bytes * @return Task */ - @Deprecated public Task setMemoryTargetLiveAsync(Connection c, Long target) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + @Deprecated + public Task setMemoryTargetLiveAsync(Connection c, Long target) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM.set_memory_target_live"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(target)}; @@ -3761,10 +3772,11 @@ public class VM extends XenAPIObject { * * @param target The target in bytes */ - @Deprecated public void setMemoryTargetLive(Connection c, Long target) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + @Deprecated + public void setMemoryTargetLive(Connection c, Long target) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_memory_target_live"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(target)}; @@ -3778,10 +3790,11 @@ public class VM extends XenAPIObject { * * @return Task */ - @Deprecated public Task waitMemoryTargetLiveAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + @Deprecated + public Task waitMemoryTargetLiveAsync(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM.wait_memory_target_live"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -3795,10 +3808,11 @@ public class VM extends XenAPIObject { * @deprecated * */ - @Deprecated public void waitMemoryTargetLive(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + @Deprecated + public void waitMemoryTargetLive(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.wait_memory_target_live"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -3812,10 +3826,11 @@ public class VM extends XenAPIObject { * * @return Task */ - @Deprecated public Task getCooperativeAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + @Deprecated + public Task getCooperativeAsync(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM.get_cooperative"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -3830,16 +3845,17 @@ public class VM extends XenAPIObject { * * @return true if the VM is currently 'co-operative'; false otherwise */ - @Deprecated public Boolean getCooperative(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + @Deprecated + public Boolean getCooperative(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_cooperative"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -3848,9 +3864,9 @@ public class VM extends XenAPIObject { * @param value The new shadow memory multiplier to set */ public void setHVMShadowMultiplier(Connection c, Double value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_HVM_shadow_multiplier"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -3865,9 +3881,9 @@ public class VM extends XenAPIObject { * @return Task */ public Task setShadowMultiplierLiveAsync(Connection c, Double multiplier) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM.set_shadow_multiplier_live"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(multiplier)}; @@ -3882,9 +3898,9 @@ public class VM extends XenAPIObject { * @param multiplier The new shadow memory multiplier to set */ public void setShadowMultiplierLive(Connection c, Double multiplier) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_shadow_multiplier_live"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(multiplier)}; @@ -3898,9 +3914,9 @@ public class VM extends XenAPIObject { * @param value The new maximum number of VCPUs */ public void setVCPUsMax(Connection c, Long value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_VCPUs_max"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -3914,9 +3930,9 @@ public class VM extends XenAPIObject { * @param value The new maximum number of VCPUs */ public void setVCPUsAtStartup(Connection c, Long value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_VCPUs_at_startup"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -3931,10 +3947,10 @@ public class VM extends XenAPIObject { * @return Task */ public Task sendSysrqAsync(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState { String method_call = "Async.VM.send_sysrq"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -3949,10 +3965,10 @@ public class VM extends XenAPIObject { * @param key The key to send */ public void sendSysrq(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState { String method_call = "VM.send_sysrq"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -3967,10 +3983,10 @@ public class VM extends XenAPIObject { * @return Task */ public Task sendTriggerAsync(Connection c, String trigger) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState { String method_call = "Async.VM.send_trigger"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(trigger)}; @@ -3985,10 +4001,10 @@ public class VM extends XenAPIObject { * @param trigger The trigger to send */ public void sendTrigger(Connection c, String trigger) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState { String method_call = "VM.send_trigger"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(trigger)}; @@ -4004,9 +4020,9 @@ public class VM extends XenAPIObject { * @return Task */ public Task maximiseMemoryAsync(Connection c, Long total, Boolean approximate) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM.maximise_memory"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(total), Marshalling.toXMLRPC(approximate)}; @@ -4023,15 +4039,15 @@ public class VM extends XenAPIObject { * @return The maximum possible static-max */ public Long maximiseMemory(Connection c, Long total, Boolean approximate) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.maximise_memory"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(total), Marshalling.toXMLRPC(approximate)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -4045,13 +4061,14 @@ public class VM extends XenAPIObject { * @return Task */ public Task migrateSendAsync(Connection c, Map dest, Boolean live, Map vdiMap, Map vifMap, Map options) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState { String method_call = "Async.VM.migrate_send"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(dest), Marshalling.toXMLRPC(live), Marshalling.toXMLRPC(vdiMap), Marshalling.toXMLRPC(vifMap), Marshalling.toXMLRPC(options)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(dest), Marshalling.toXMLRPC(live), + Marshalling.toXMLRPC(vdiMap), Marshalling.toXMLRPC(vifMap), Marshalling.toXMLRPC(options)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -4067,13 +4084,14 @@ public class VM extends XenAPIObject { * @param options Other parameters */ public void migrateSend(Connection c, Map dest, Boolean live, Map vdiMap, Map vifMap, Map options) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmBadPowerState { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState { String method_call = "VM.migrate_send"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(dest), Marshalling.toXMLRPC(live), Marshalling.toXMLRPC(vdiMap), Marshalling.toXMLRPC(vifMap), Marshalling.toXMLRPC(options)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(dest), Marshalling.toXMLRPC(live), + Marshalling.toXMLRPC(vdiMap), Marshalling.toXMLRPC(vifMap), Marshalling.toXMLRPC(options)}; Map response = c.dispatch(method_call, method_params); return; } @@ -4088,13 +4106,15 @@ public class VM extends XenAPIObject { * @param options Other parameters * @return Task */ - public Task assertCanMigrateAsync(Connection c, Map dest, Boolean live, Map vdiMap, Map vifMap, Map options) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + public Task assertCanMigrateAsync(Connection c, Map dest, Boolean live, Map vdiMap, Map vifMap, Map options) + throws + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM.assert_can_migrate"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(dest), Marshalling.toXMLRPC(live), Marshalling.toXMLRPC(vdiMap), Marshalling.toXMLRPC(vifMap), Marshalling.toXMLRPC(options)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(dest), Marshalling.toXMLRPC(live), + Marshalling.toXMLRPC(vdiMap), Marshalling.toXMLRPC(vifMap), Marshalling.toXMLRPC(options)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -4110,12 +4130,13 @@ public class VM extends XenAPIObject { * @param options Other parameters */ public void assertCanMigrate(Connection c, Map dest, Boolean live, Map vdiMap, Map vifMap, Map options) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.assert_can_migrate"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(dest), Marshalling.toXMLRPC(live), Marshalling.toXMLRPC(vdiMap), Marshalling.toXMLRPC(vifMap), Marshalling.toXMLRPC(options)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(dest), Marshalling.toXMLRPC(live), + Marshalling.toXMLRPC(vdiMap), Marshalling.toXMLRPC(vifMap), Marshalling.toXMLRPC(options)}; Map response = c.dispatch(method_call, method_params); return; } @@ -4126,15 +4147,15 @@ public class VM extends XenAPIObject { * @return A record describing the VM */ public VM.Record getBootRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_boot_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVMRecord(result); + return Types.toVMRecord(result); } /** @@ -4143,15 +4164,15 @@ public class VM extends XenAPIObject { * @return A set of data sources */ public Set getDataSources(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_data_sources"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfDataSourceRecord(result); + return Types.toSetOfDataSourceRecord(result); } /** @@ -4160,9 +4181,9 @@ public class VM extends XenAPIObject { * @param dataSource The data source to record */ public void recordDataSource(Connection c, String dataSource) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.record_data_source"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(dataSource)}; @@ -4177,15 +4198,15 @@ public class VM extends XenAPIObject { * @return The latest value, averaged over the last 5 seconds */ public Double queryDataSource(Connection c, String dataSource) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.query_data_source"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(dataSource)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDouble(result); + return Types.toDouble(result); } /** @@ -4194,9 +4215,9 @@ public class VM extends XenAPIObject { * @param dataSource The data source whose archives are to be forgotten */ public void forgetDataSourceArchives(Connection c, String dataSource) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.forget_data_source_archives"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(dataSource)}; @@ -4211,9 +4232,9 @@ public class VM extends XenAPIObject { * @return Task */ public Task assertOperationValidAsync(Connection c, Types.VmOperations op) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM.assert_operation_valid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(op)}; @@ -4228,9 +4249,9 @@ public class VM extends XenAPIObject { * @param op proposed operation */ public void assertOperationValid(Connection c, Types.VmOperations op) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.assert_operation_valid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(op)}; @@ -4244,9 +4265,9 @@ public class VM extends XenAPIObject { * @return Task */ public Task updateAllowedOperationsAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM.update_allowed_operations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -4260,9 +4281,9 @@ public class VM extends XenAPIObject { * */ public void updateAllowedOperations(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.update_allowed_operations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -4276,15 +4297,15 @@ public class VM extends XenAPIObject { * @return The allowed values */ public Set getAllowedVBDDevices(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_allowed_VBD_devices"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -4293,15 +4314,15 @@ public class VM extends XenAPIObject { * @return The allowed values */ public Set getAllowedVIFDevices(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_allowed_VIF_devices"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -4310,9 +4331,9 @@ public class VM extends XenAPIObject { * @return Task */ public Task getPossibleHostsAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM.get_possible_hosts"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -4327,15 +4348,15 @@ public class VM extends XenAPIObject { * @return The possible hosts */ public Set getPossibleHosts(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_possible_hosts"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfHost(result); + return Types.toSetOfHost(result); } /** @@ -4345,12 +4366,12 @@ public class VM extends XenAPIObject { * @return Task */ public Task assertCanBootHereAsync(Connection c, Host host) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.HostNotEnoughFreeMemory, - Types.VmRequiresSr, - Types.VmHostIncompatibleVersion { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.HostNotEnoughFreeMemory, + Types.VmRequiresSr, + Types.VmHostIncompatibleVersion { String method_call = "Async.VM.assert_can_boot_here"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(host)}; @@ -4365,12 +4386,12 @@ public class VM extends XenAPIObject { * @param host The host */ public void assertCanBootHere(Connection c, Host host) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.HostNotEnoughFreeMemory, - Types.VmRequiresSr, - Types.VmHostIncompatibleVersion { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.HostNotEnoughFreeMemory, + Types.VmRequiresSr, + Types.VmHostIncompatibleVersion { String method_call = "VM.assert_can_boot_here"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(host)}; @@ -4387,12 +4408,13 @@ public class VM extends XenAPIObject { * @return Task */ public Task createNewBlobAsync(Connection c, String name, String mimeType, Boolean _public) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM.create_new_blob"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType), Marshalling.toXMLRPC(_public)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType), + Marshalling.toXMLRPC(_public)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -4407,15 +4429,16 @@ public class VM extends XenAPIObject { * @return The reference of the blob, needed for populating its data */ public Blob createNewBlob(Connection c, String name, String mimeType, Boolean _public) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.create_new_blob"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType), Marshalling.toXMLRPC(_public)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType), + Marshalling.toXMLRPC(_public)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBlob(result); + return Types.toBlob(result); } /** @@ -4424,9 +4447,9 @@ public class VM extends XenAPIObject { * @return Task */ public Task assertAgileAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM.assert_agile"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -4440,9 +4463,9 @@ public class VM extends XenAPIObject { * */ public void assertAgile(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.assert_agile"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -4456,9 +4479,9 @@ public class VM extends XenAPIObject { * @return Task */ public Task retrieveWlbRecommendationsAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM.retrieve_wlb_recommendations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -4473,15 +4496,15 @@ public class VM extends XenAPIObject { * @return The potential hosts and their corresponding recommendations or errors */ public Map> retrieveWlbRecommendations(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.retrieve_wlb_recommendations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfHostSetOfString(result); + return Types.toMapOfHostSetOfString(result); } /** @@ -4491,9 +4514,9 @@ public class VM extends XenAPIObject { * @return Task */ public Task copyBiosStringsAsync(Connection c, Host host) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM.copy_bios_strings"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(host)}; @@ -4508,9 +4531,9 @@ public class VM extends XenAPIObject { * @param host The host to copy the BIOS strings from */ public void copyBiosStrings(Connection c, Host host) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.copy_bios_strings"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(host)}; @@ -4524,9 +4547,9 @@ public class VM extends XenAPIObject { * @param value The value */ public void setProtectionPolicy(Connection c, VMPP value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_protection_policy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -4541,9 +4564,9 @@ public class VM extends XenAPIObject { * @return Task */ public Task setStartDelayAsync(Connection c, Long value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM.set_start_delay"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -4558,9 +4581,9 @@ public class VM extends XenAPIObject { * @param value This VM's start delay in seconds */ public void setStartDelay(Connection c, Long value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_start_delay"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -4575,9 +4598,9 @@ public class VM extends XenAPIObject { * @return Task */ public Task setShutdownDelayAsync(Connection c, Long value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM.set_shutdown_delay"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -4592,9 +4615,9 @@ public class VM extends XenAPIObject { * @param value This VM's shutdown delay in seconds */ public void setShutdownDelay(Connection c, Long value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_shutdown_delay"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -4609,9 +4632,9 @@ public class VM extends XenAPIObject { * @return Task */ public Task setOrderAsync(Connection c, Long value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM.set_order"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -4626,9 +4649,9 @@ public class VM extends XenAPIObject { * @param value This VM's boot order */ public void setOrder(Connection c, Long value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_order"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -4643,9 +4666,9 @@ public class VM extends XenAPIObject { * @return Task */ public Task setSuspendVDIAsync(Connection c, VDI value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM.set_suspend_VDI"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -4660,9 +4683,9 @@ public class VM extends XenAPIObject { * @param value The suspend VDI uuid */ public void setSuspendVDI(Connection c, VDI value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_suspend_VDI"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -4677,11 +4700,11 @@ public class VM extends XenAPIObject { * @return Task */ public Task assertCanBeRecoveredAsync(Connection c, Session sessionTo) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmIsPartOfAnAppliance, - Types.VmRequiresSr { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmIsPartOfAnAppliance, + Types.VmRequiresSr { String method_call = "Async.VM.assert_can_be_recovered"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(sessionTo)}; @@ -4696,11 +4719,11 @@ public class VM extends XenAPIObject { * @param sessionTo The session to which the VM is to be recovered. */ public void assertCanBeRecovered(Connection c, Session sessionTo) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmIsPartOfAnAppliance, - Types.VmRequiresSr { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmIsPartOfAnAppliance, + Types.VmRequiresSr { String method_call = "VM.assert_can_be_recovered"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(sessionTo)}; @@ -4716,9 +4739,9 @@ public class VM extends XenAPIObject { * @return Task */ public Task recoverAsync(Connection c, Session sessionTo, Boolean force) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM.recover"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(sessionTo), Marshalling.toXMLRPC(force)}; @@ -4734,9 +4757,9 @@ public class VM extends XenAPIObject { * @param force Whether the VM should replace newer versions of itself. */ public void recover(Connection c, Session sessionTo, Boolean force) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.recover"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(sessionTo), Marshalling.toXMLRPC(force)}; @@ -4755,12 +4778,13 @@ public class VM extends XenAPIObject { * @return Task */ public static Task importConvertAsync(Connection c, String type, String username, String password, SR sr, Map remoteConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM.import_convert"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(username), Marshalling.toXMLRPC(password), Marshalling.toXMLRPC(sr), Marshalling.toXMLRPC(remoteConfig)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(username), Marshalling.toXMLRPC(password), + Marshalling.toXMLRPC(sr), Marshalling.toXMLRPC(remoteConfig)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -4776,12 +4800,13 @@ public class VM extends XenAPIObject { * @param remoteConfig Remote configuration options */ public static void importConvert(Connection c, String type, String username, String password, SR sr, Map remoteConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.import_convert"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(username), Marshalling.toXMLRPC(password), Marshalling.toXMLRPC(sr), Marshalling.toXMLRPC(remoteConfig)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(username), Marshalling.toXMLRPC(password), + Marshalling.toXMLRPC(sr), Marshalling.toXMLRPC(remoteConfig)}; Map response = c.dispatch(method_call, method_params); return; } @@ -4793,9 +4818,9 @@ public class VM extends XenAPIObject { * @return Task */ public Task setApplianceAsync(Connection c, VMAppliance value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM.set_appliance"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -4810,9 +4835,9 @@ public class VM extends XenAPIObject { * @param value The appliance to which this VM should be assigned. */ public void setAppliance(Connection c, VMAppliance value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.set_appliance"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -4826,9 +4851,9 @@ public class VM extends XenAPIObject { * @return Task */ public Task queryServicesAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM.query_services"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -4843,15 +4868,15 @@ public class VM extends XenAPIObject { * @return map of service type to name */ public Map queryServices(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.query_services"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -4860,15 +4885,15 @@ public class VM extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVM(result); + return Types.toSetOfVM(result); } /** @@ -4877,15 +4902,15 @@ public class VM extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfVMVMRecord(result); + return Types.toMapOfVMVMRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/VMAppliance.java b/deps/XenServerJava/src/com/xensource/xenapi/VMAppliance.java index a04026314b9..b7e7e36684e 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/VMAppliance.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/VMAppliance.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class VMAppliance extends XenAPIObject { * For internal use only. */ VMAppliance(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class VMAppliance extends XenAPIObject { { if (obj != null && obj instanceof VMAppliance) { - VMAppliance other = (VMAppliance) obj; + VMAppliance other = (VMAppliance)obj; return other.ref.equals(this.ref); } else { @@ -112,8 +111,8 @@ public class VMAppliance extends XenAPIObject { /** * Convert a VM_appliance.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("name_label", this.nameLabel == null ? "" : this.nameLabel); map.put("name_description", this.nameDescription == null ? "" : this.nameDescription); @@ -155,15 +154,15 @@ public class VMAppliance extends XenAPIObject { * @return all fields from the object */ public VMAppliance.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_appliance.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVMApplianceRecord(result); + return Types.toVMApplianceRecord(result); } /** @@ -173,15 +172,15 @@ public class VMAppliance extends XenAPIObject { * @return reference to the object */ public static VMAppliance getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_appliance.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVMAppliance(result); + return Types.toVMAppliance(result); } /** @@ -191,9 +190,9 @@ public class VMAppliance extends XenAPIObject { * @return Task */ public static Task createAsync(Connection c, VMAppliance.Record record) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM_appliance.create"; String session = c.getSessionReference(); Map record_map = record.toMap(); @@ -210,16 +209,16 @@ public class VMAppliance extends XenAPIObject { * @return reference to the newly created object */ public static VMAppliance create(Connection c, VMAppliance.Record record) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_appliance.create"; String session = c.getSessionReference(); Map record_map = record.toMap(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(record_map)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVMAppliance(result); + return Types.toVMAppliance(result); } /** @@ -228,9 +227,9 @@ public class VMAppliance extends XenAPIObject { * @return Task */ public Task destroyAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VM_appliance.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -244,9 +243,9 @@ public class VMAppliance extends XenAPIObject { * */ public void destroy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_appliance.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -261,15 +260,15 @@ public class VMAppliance extends XenAPIObject { * @return references to objects with matching names */ public static Set getByNameLabel(Connection c, String label) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_appliance.get_by_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(label)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVMAppliance(result); + return Types.toSetOfVMAppliance(result); } /** @@ -278,15 +277,15 @@ public class VMAppliance extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_appliance.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -295,15 +294,15 @@ public class VMAppliance extends XenAPIObject { * @return value of the field */ public String getNameLabel(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_appliance.get_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -312,15 +311,15 @@ public class VMAppliance extends XenAPIObject { * @return value of the field */ public String getNameDescription(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_appliance.get_name_description"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -329,15 +328,15 @@ public class VMAppliance extends XenAPIObject { * @return value of the field */ public Set getAllowedOperations(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_appliance.get_allowed_operations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVmApplianceOperation(result); + return Types.toSetOfVmApplianceOperation(result); } /** @@ -346,15 +345,15 @@ public class VMAppliance extends XenAPIObject { * @return value of the field */ public Map getCurrentOperations(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_appliance.get_current_operations"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringVmApplianceOperation(result); + return Types.toMapOfStringVmApplianceOperation(result); } /** @@ -363,15 +362,15 @@ public class VMAppliance extends XenAPIObject { * @return value of the field */ public Set getVMs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_appliance.get_VMs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVM(result); + return Types.toSetOfVM(result); } /** @@ -380,9 +379,9 @@ public class VMAppliance extends XenAPIObject { * @param label New value to set */ public void setNameLabel(Connection c, String label) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_appliance.set_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(label)}; @@ -396,9 +395,9 @@ public class VMAppliance extends XenAPIObject { * @param description New value to set */ public void setNameDescription(Connection c, String description) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_appliance.set_name_description"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(description)}; @@ -413,10 +412,10 @@ public class VMAppliance extends XenAPIObject { * @return Task */ public Task startAsync(Connection c, Boolean paused) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.OperationPartiallyFailed { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.OperationPartiallyFailed { String method_call = "Async.VM_appliance.start"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(paused)}; @@ -431,10 +430,10 @@ public class VMAppliance extends XenAPIObject { * @param paused Instantiate all VMs belonging to this appliance in paused state if set to true. */ public void start(Connection c, Boolean paused) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.OperationPartiallyFailed { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.OperationPartiallyFailed { String method_call = "VM_appliance.start"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(paused)}; @@ -448,10 +447,10 @@ public class VMAppliance extends XenAPIObject { * @return Task */ public Task cleanShutdownAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.OperationPartiallyFailed { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.OperationPartiallyFailed { String method_call = "Async.VM_appliance.clean_shutdown"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -465,10 +464,10 @@ public class VMAppliance extends XenAPIObject { * */ public void cleanShutdown(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.OperationPartiallyFailed { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.OperationPartiallyFailed { String method_call = "VM_appliance.clean_shutdown"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -482,10 +481,10 @@ public class VMAppliance extends XenAPIObject { * @return Task */ public Task hardShutdownAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.OperationPartiallyFailed { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.OperationPartiallyFailed { String method_call = "Async.VM_appliance.hard_shutdown"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -499,10 +498,10 @@ public class VMAppliance extends XenAPIObject { * */ public void hardShutdown(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.OperationPartiallyFailed { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.OperationPartiallyFailed { String method_call = "VM_appliance.hard_shutdown"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -516,10 +515,10 @@ public class VMAppliance extends XenAPIObject { * @return Task */ public Task shutdownAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.OperationPartiallyFailed { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.OperationPartiallyFailed { String method_call = "Async.VM_appliance.shutdown"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -533,10 +532,10 @@ public class VMAppliance extends XenAPIObject { * */ public void shutdown(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.OperationPartiallyFailed { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.OperationPartiallyFailed { String method_call = "VM_appliance.shutdown"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -551,10 +550,10 @@ public class VMAppliance extends XenAPIObject { * @return Task */ public Task assertCanBeRecoveredAsync(Connection c, Session sessionTo) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmRequiresSr { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmRequiresSr { String method_call = "Async.VM_appliance.assert_can_be_recovered"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(sessionTo)}; @@ -569,10 +568,10 @@ public class VMAppliance extends XenAPIObject { * @param sessionTo The session to which the VM appliance is to be recovered. */ public void assertCanBeRecovered(Connection c, Session sessionTo) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmRequiresSr { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmRequiresSr { String method_call = "VM_appliance.assert_can_be_recovered"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(sessionTo)}; @@ -588,10 +587,10 @@ public class VMAppliance extends XenAPIObject { * @return Task */ public Task recoverAsync(Connection c, Session sessionTo, Boolean force) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmRequiresSr { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmRequiresSr { String method_call = "Async.VM_appliance.recover"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(sessionTo), Marshalling.toXMLRPC(force)}; @@ -607,10 +606,10 @@ public class VMAppliance extends XenAPIObject { * @param force Whether the VMs should replace newer versions of themselves. */ public void recover(Connection c, Session sessionTo, Boolean force) throws - BadServerResponse, - XenAPIException, - XmlRpcException, - Types.VmRequiresSr { + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmRequiresSr { String method_call = "VM_appliance.recover"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(sessionTo), Marshalling.toXMLRPC(force)}; @@ -624,15 +623,15 @@ public class VMAppliance extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_appliance.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVMAppliance(result); + return Types.toSetOfVMAppliance(result); } /** @@ -641,15 +640,15 @@ public class VMAppliance extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_appliance.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfVMApplianceVMApplianceRecord(result); + return Types.toMapOfVMApplianceVMApplianceRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/VMGuestMetrics.java b/deps/XenServerJava/src/com/xensource/xenapi/VMGuestMetrics.java index 9a6caf052bd..08d88e3641c 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/VMGuestMetrics.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/VMGuestMetrics.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class VMGuestMetrics extends XenAPIObject { * For internal use only. */ VMGuestMetrics(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class VMGuestMetrics extends XenAPIObject { { if (obj != null && obj instanceof VMGuestMetrics) { - VMGuestMetrics other = (VMGuestMetrics) obj; + VMGuestMetrics other = (VMGuestMetrics)obj; return other.ref.equals(this.ref); } else { @@ -117,8 +116,8 @@ public class VMGuestMetrics extends XenAPIObject { /** * Convert a VM_guest_metrics.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("os_version", this.osVersion == null ? new HashMap() : this.osVersion); map.put("PV_drivers_version", this.PVDriversVersion == null ? new HashMap() : this.PVDriversVersion); @@ -185,15 +184,15 @@ public class VMGuestMetrics extends XenAPIObject { * @return all fields from the object */ public VMGuestMetrics.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_guest_metrics.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVMGuestMetricsRecord(result); + return Types.toVMGuestMetricsRecord(result); } /** @@ -203,15 +202,15 @@ public class VMGuestMetrics extends XenAPIObject { * @return reference to the object */ public static VMGuestMetrics getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_guest_metrics.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVMGuestMetrics(result); + return Types.toVMGuestMetrics(result); } /** @@ -220,15 +219,15 @@ public class VMGuestMetrics extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_guest_metrics.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -237,15 +236,15 @@ public class VMGuestMetrics extends XenAPIObject { * @return value of the field */ public Map getOsVersion(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_guest_metrics.get_os_version"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -254,15 +253,15 @@ public class VMGuestMetrics extends XenAPIObject { * @return value of the field */ public Map getPVDriversVersion(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_guest_metrics.get_PV_drivers_version"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -271,15 +270,15 @@ public class VMGuestMetrics extends XenAPIObject { * @return value of the field */ public Boolean getPVDriversUpToDate(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_guest_metrics.get_PV_drivers_up_to_date"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -288,15 +287,15 @@ public class VMGuestMetrics extends XenAPIObject { * @return value of the field */ public Map getMemory(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_guest_metrics.get_memory"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -305,15 +304,15 @@ public class VMGuestMetrics extends XenAPIObject { * @return value of the field */ public Map getDisks(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_guest_metrics.get_disks"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -322,15 +321,15 @@ public class VMGuestMetrics extends XenAPIObject { * @return value of the field */ public Map getNetworks(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_guest_metrics.get_networks"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -339,15 +338,15 @@ public class VMGuestMetrics extends XenAPIObject { * @return value of the field */ public Map getOther(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_guest_metrics.get_other"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -356,15 +355,15 @@ public class VMGuestMetrics extends XenAPIObject { * @return value of the field */ public Date getLastUpdated(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_guest_metrics.get_last_updated"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDate(result); + return Types.toDate(result); } /** @@ -373,15 +372,15 @@ public class VMGuestMetrics extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_guest_metrics.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -390,15 +389,15 @@ public class VMGuestMetrics extends XenAPIObject { * @return value of the field */ public Boolean getLive(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_guest_metrics.get_live"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -407,9 +406,9 @@ public class VMGuestMetrics extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_guest_metrics.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -424,9 +423,9 @@ public class VMGuestMetrics extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_guest_metrics.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -440,9 +439,9 @@ public class VMGuestMetrics extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_guest_metrics.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -456,15 +455,15 @@ public class VMGuestMetrics extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_guest_metrics.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVMGuestMetrics(result); + return Types.toSetOfVMGuestMetrics(result); } /** @@ -473,15 +472,15 @@ public class VMGuestMetrics extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_guest_metrics.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfVMGuestMetricsVMGuestMetricsRecord(result); + return Types.toMapOfVMGuestMetricsVMGuestMetricsRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/VMMetrics.java b/deps/XenServerJava/src/com/xensource/xenapi/VMMetrics.java index 8544e42e143..5f9a7a42c7c 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/VMMetrics.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/VMMetrics.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class VMMetrics extends XenAPIObject { * For internal use only. */ VMMetrics(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class VMMetrics extends XenAPIObject { { if (obj != null && obj instanceof VMMetrics) { - VMMetrics other = (VMMetrics) obj; + VMMetrics other = (VMMetrics)obj; return other.ref.equals(this.ref); } else { @@ -118,8 +117,8 @@ public class VMMetrics extends XenAPIObject { /** * Convert a VM_metrics.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("memory_actual", this.memoryActual == null ? 0 : this.memoryActual); map.put("VCPUs_number", this.VCPUsNumber == null ? 0 : this.VCPUsNumber); @@ -191,15 +190,15 @@ public class VMMetrics extends XenAPIObject { * @return all fields from the object */ public VMMetrics.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_metrics.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVMMetricsRecord(result); + return Types.toVMMetricsRecord(result); } /** @@ -209,15 +208,15 @@ public class VMMetrics extends XenAPIObject { * @return reference to the object */ public static VMMetrics getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_metrics.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVMMetrics(result); + return Types.toVMMetrics(result); } /** @@ -226,15 +225,15 @@ public class VMMetrics extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_metrics.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -243,15 +242,15 @@ public class VMMetrics extends XenAPIObject { * @return value of the field */ public Long getMemoryActual(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_metrics.get_memory_actual"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -260,15 +259,15 @@ public class VMMetrics extends XenAPIObject { * @return value of the field */ public Long getVCPUsNumber(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_metrics.get_VCPUs_number"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -277,15 +276,15 @@ public class VMMetrics extends XenAPIObject { * @return value of the field */ public Map getVCPUsUtilisation(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_metrics.get_VCPUs_utilisation"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfLongDouble(result); + return Types.toMapOfLongDouble(result); } /** @@ -294,15 +293,15 @@ public class VMMetrics extends XenAPIObject { * @return value of the field */ public Map getVCPUsCPU(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_metrics.get_VCPUs_CPU"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfLongLong(result); + return Types.toMapOfLongLong(result); } /** @@ -311,15 +310,15 @@ public class VMMetrics extends XenAPIObject { * @return value of the field */ public Map getVCPUsParams(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_metrics.get_VCPUs_params"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -328,15 +327,15 @@ public class VMMetrics extends XenAPIObject { * @return value of the field */ public Map> getVCPUsFlags(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_metrics.get_VCPUs_flags"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfLongSetOfString(result); + return Types.toMapOfLongSetOfString(result); } /** @@ -345,15 +344,15 @@ public class VMMetrics extends XenAPIObject { * @return value of the field */ public Set getState(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_metrics.get_state"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -362,15 +361,15 @@ public class VMMetrics extends XenAPIObject { * @return value of the field */ public Date getStartTime(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_metrics.get_start_time"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDate(result); + return Types.toDate(result); } /** @@ -379,15 +378,15 @@ public class VMMetrics extends XenAPIObject { * @return value of the field */ public Date getInstallTime(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_metrics.get_install_time"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDate(result); + return Types.toDate(result); } /** @@ -396,15 +395,15 @@ public class VMMetrics extends XenAPIObject { * @return value of the field */ public Date getLastUpdated(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_metrics.get_last_updated"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDate(result); + return Types.toDate(result); } /** @@ -413,15 +412,15 @@ public class VMMetrics extends XenAPIObject { * @return value of the field */ public Map getOtherConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_metrics.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -430,9 +429,9 @@ public class VMMetrics extends XenAPIObject { * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map otherConfig) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_metrics.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; @@ -447,9 +446,9 @@ public class VMMetrics extends XenAPIObject { * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_metrics.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -463,9 +462,9 @@ public class VMMetrics extends XenAPIObject { * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_metrics.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -479,15 +478,15 @@ public class VMMetrics extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_metrics.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVMMetrics(result); + return Types.toSetOfVMMetrics(result); } /** @@ -496,15 +495,15 @@ public class VMMetrics extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VM_metrics.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfVMMetricsVMMetricsRecord(result); + return Types.toMapOfVMMetricsVMMetricsRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/VMPP.java b/deps/XenServerJava/src/com/xensource/xenapi/VMPP.java index 3e8d2fbdd42..0ee0b3e7439 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/VMPP.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/VMPP.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class VMPP extends XenAPIObject { * For internal use only. */ VMPP(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class VMPP extends XenAPIObject { { if (obj != null && obj instanceof VMPP) { - VMPP other = (VMPP) obj; + VMPP other = (VMPP)obj; return other.ref.equals(this.ref); } else { @@ -126,8 +125,8 @@ public class VMPP extends XenAPIObject { /** * Convert a VMPP.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("name_label", this.nameLabel == null ? "" : this.nameLabel); map.put("name_description", this.nameDescription == null ? "" : this.nameDescription); @@ -239,15 +238,15 @@ public class VMPP extends XenAPIObject { * @return all fields from the object */ public VMPP.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVMPPRecord(result); + return Types.toVMPPRecord(result); } /** @@ -257,15 +256,15 @@ public class VMPP extends XenAPIObject { * @return reference to the object */ public static VMPP getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVMPP(result); + return Types.toVMPP(result); } /** @@ -275,9 +274,9 @@ public class VMPP extends XenAPIObject { * @return Task */ public static Task createAsync(Connection c, VMPP.Record record) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VMPP.create"; String session = c.getSessionReference(); Map record_map = record.toMap(); @@ -294,16 +293,16 @@ public class VMPP extends XenAPIObject { * @return reference to the newly created object */ public static VMPP create(Connection c, VMPP.Record record) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.create"; String session = c.getSessionReference(); Map record_map = record.toMap(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(record_map)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVMPP(result); + return Types.toVMPP(result); } /** @@ -312,9 +311,9 @@ public class VMPP extends XenAPIObject { * @return Task */ public Task destroyAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VMPP.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -328,9 +327,9 @@ public class VMPP extends XenAPIObject { * */ public void destroy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -345,15 +344,15 @@ public class VMPP extends XenAPIObject { * @return references to objects with matching names */ public static Set getByNameLabel(Connection c, String label) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.get_by_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(label)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVMPP(result); + return Types.toSetOfVMPP(result); } /** @@ -362,15 +361,15 @@ public class VMPP extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -379,15 +378,15 @@ public class VMPP extends XenAPIObject { * @return value of the field */ public String getNameLabel(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.get_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -396,15 +395,15 @@ public class VMPP extends XenAPIObject { * @return value of the field */ public String getNameDescription(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.get_name_description"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -413,15 +412,15 @@ public class VMPP extends XenAPIObject { * @return value of the field */ public Boolean getIsPolicyEnabled(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.get_is_policy_enabled"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -430,15 +429,15 @@ public class VMPP extends XenAPIObject { * @return value of the field */ public Types.VmppBackupType getBackupType(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.get_backup_type"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVmppBackupType(result); + return Types.toVmppBackupType(result); } /** @@ -447,15 +446,15 @@ public class VMPP extends XenAPIObject { * @return value of the field */ public Long getBackupRetentionValue(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.get_backup_retention_value"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toLong(result); + return Types.toLong(result); } /** @@ -464,15 +463,15 @@ public class VMPP extends XenAPIObject { * @return value of the field */ public Types.VmppBackupFrequency getBackupFrequency(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.get_backup_frequency"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVmppBackupFrequency(result); + return Types.toVmppBackupFrequency(result); } /** @@ -481,15 +480,15 @@ public class VMPP extends XenAPIObject { * @return value of the field */ public Map getBackupSchedule(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.get_backup_schedule"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -498,15 +497,15 @@ public class VMPP extends XenAPIObject { * @return value of the field */ public Boolean getIsBackupRunning(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.get_is_backup_running"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -515,15 +514,15 @@ public class VMPP extends XenAPIObject { * @return value of the field */ public Date getBackupLastRunTime(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.get_backup_last_run_time"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDate(result); + return Types.toDate(result); } /** @@ -532,15 +531,15 @@ public class VMPP extends XenAPIObject { * @return value of the field */ public Types.VmppArchiveTargetType getArchiveTargetType(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.get_archive_target_type"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVmppArchiveTargetType(result); + return Types.toVmppArchiveTargetType(result); } /** @@ -549,15 +548,15 @@ public class VMPP extends XenAPIObject { * @return value of the field */ public Map getArchiveTargetConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.get_archive_target_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -566,15 +565,15 @@ public class VMPP extends XenAPIObject { * @return value of the field */ public Types.VmppArchiveFrequency getArchiveFrequency(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.get_archive_frequency"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVmppArchiveFrequency(result); + return Types.toVmppArchiveFrequency(result); } /** @@ -583,15 +582,15 @@ public class VMPP extends XenAPIObject { * @return value of the field */ public Map getArchiveSchedule(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.get_archive_schedule"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -600,15 +599,15 @@ public class VMPP extends XenAPIObject { * @return value of the field */ public Boolean getIsArchiveRunning(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.get_is_archive_running"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -617,15 +616,15 @@ public class VMPP extends XenAPIObject { * @return value of the field */ public Date getArchiveLastRunTime(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.get_archive_last_run_time"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toDate(result); + return Types.toDate(result); } /** @@ -634,15 +633,15 @@ public class VMPP extends XenAPIObject { * @return value of the field */ public Set getVMs(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.get_VMs"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVM(result); + return Types.toSetOfVM(result); } /** @@ -651,15 +650,15 @@ public class VMPP extends XenAPIObject { * @return value of the field */ public Boolean getIsAlarmEnabled(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.get_is_alarm_enabled"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toBoolean(result); + return Types.toBoolean(result); } /** @@ -668,15 +667,15 @@ public class VMPP extends XenAPIObject { * @return value of the field */ public Map getAlarmConfig(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.get_alarm_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfStringString(result); + return Types.toMapOfStringString(result); } /** @@ -685,15 +684,15 @@ public class VMPP extends XenAPIObject { * @return value of the field */ public Set getRecentAlerts(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.get_recent_alerts"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -702,9 +701,9 @@ public class VMPP extends XenAPIObject { * @param label New value to set */ public void setNameLabel(Connection c, String label) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.set_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(label)}; @@ -718,9 +717,9 @@ public class VMPP extends XenAPIObject { * @param description New value to set */ public void setNameDescription(Connection c, String description) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.set_name_description"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(description)}; @@ -734,9 +733,9 @@ public class VMPP extends XenAPIObject { * @param isPolicyEnabled New value to set */ public void setIsPolicyEnabled(Connection c, Boolean isPolicyEnabled) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.set_is_policy_enabled"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(isPolicyEnabled)}; @@ -750,9 +749,9 @@ public class VMPP extends XenAPIObject { * @param backupType New value to set */ public void setBackupType(Connection c, Types.VmppBackupType backupType) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.set_backup_type"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(backupType)}; @@ -766,15 +765,15 @@ public class VMPP extends XenAPIObject { * @return An XMLRPC result */ public String protectNow(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.protect_now"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -784,15 +783,15 @@ public class VMPP extends XenAPIObject { * @return An XMLRPC result */ public static String archiveNow(Connection c, VM snapshot) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.archive_now"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(snapshot)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -802,15 +801,15 @@ public class VMPP extends XenAPIObject { * @return A list of alerts encoded in xml */ public Set getAlerts(Connection c, Long hoursFromNow) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.get_alerts"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(hoursFromNow)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfString(result); + return Types.toSetOfString(result); } /** @@ -819,9 +818,9 @@ public class VMPP extends XenAPIObject { * @param value the value to set */ public void setBackupRetentionValue(Connection c, Long value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.set_backup_retention_value"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -835,9 +834,9 @@ public class VMPP extends XenAPIObject { * @param value the backup frequency */ public void setBackupFrequency(Connection c, Types.VmppBackupFrequency value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.set_backup_frequency"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -851,9 +850,9 @@ public class VMPP extends XenAPIObject { * @param value the value to set */ public void setBackupSchedule(Connection c, Map value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.set_backup_schedule"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -867,9 +866,9 @@ public class VMPP extends XenAPIObject { * @param value the archive frequency */ public void setArchiveFrequency(Connection c, Types.VmppArchiveFrequency value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.set_archive_frequency"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -883,9 +882,9 @@ public class VMPP extends XenAPIObject { * @param value the value to set */ public void setArchiveSchedule(Connection c, Map value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.set_archive_schedule"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -899,9 +898,9 @@ public class VMPP extends XenAPIObject { * @param value the archive target config type */ public void setArchiveTargetType(Connection c, Types.VmppArchiveTargetType value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.set_archive_target_type"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -915,9 +914,9 @@ public class VMPP extends XenAPIObject { * @param value the value to set */ public void setArchiveTargetConfig(Connection c, Map value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.set_archive_target_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -931,9 +930,9 @@ public class VMPP extends XenAPIObject { * @param value true if alarm is enabled for this policy */ public void setIsAlarmEnabled(Connection c, Boolean value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.set_is_alarm_enabled"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -947,9 +946,9 @@ public class VMPP extends XenAPIObject { * @param value the value to set */ public void setAlarmConfig(Connection c, Map value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.set_alarm_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -964,9 +963,9 @@ public class VMPP extends XenAPIObject { * @param value the value to add */ public void addToBackupSchedule(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.add_to_backup_schedule"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -981,9 +980,9 @@ public class VMPP extends XenAPIObject { * @param value the value to add */ public void addToArchiveTargetConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.add_to_archive_target_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -998,9 +997,9 @@ public class VMPP extends XenAPIObject { * @param value the value to add */ public void addToArchiveSchedule(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.add_to_archive_schedule"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -1015,9 +1014,9 @@ public class VMPP extends XenAPIObject { * @param value the value to add */ public void addToAlarmConfig(Connection c, String key, String value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.add_to_alarm_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; @@ -1031,9 +1030,9 @@ public class VMPP extends XenAPIObject { * @param key the key to remove */ public void removeFromBackupSchedule(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.remove_from_backup_schedule"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -1047,9 +1046,9 @@ public class VMPP extends XenAPIObject { * @param key the key to remove */ public void removeFromArchiveTargetConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.remove_from_archive_target_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -1063,9 +1062,9 @@ public class VMPP extends XenAPIObject { * @param key the key to remove */ public void removeFromArchiveSchedule(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.remove_from_archive_schedule"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -1079,9 +1078,9 @@ public class VMPP extends XenAPIObject { * @param key the key to remove */ public void removeFromAlarmConfig(Connection c, String key) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.remove_from_alarm_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; @@ -1095,9 +1094,9 @@ public class VMPP extends XenAPIObject { * @param value the value to set */ public void setBackupLastRunTime(Connection c, Date value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.set_backup_last_run_time"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1111,9 +1110,9 @@ public class VMPP extends XenAPIObject { * @param value the value to set */ public void setArchiveLastRunTime(Connection c, Date value) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.set_archive_last_run_time"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; @@ -1127,15 +1126,15 @@ public class VMPP extends XenAPIObject { * @return references to all objects */ public static Set getAll(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toSetOfVMPP(result); + return Types.toSetOfVMPP(result); } /** @@ -1144,15 +1143,15 @@ public class VMPP extends XenAPIObject { * @return records of all objects */ public static Map getAllRecords(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VMPP.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toMapOfVMPPVMPPRecord(result); + return Types.toMapOfVMPPVMPPRecord(result); } } \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/VTPM.java b/deps/XenServerJava/src/com/xensource/xenapi/VTPM.java index 71736a01664..25c332081ef 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/VTPM.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/VTPM.java @@ -28,7 +28,6 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -61,14 +60,14 @@ public class VTPM extends XenAPIObject { * For internal use only. */ VTPM(String ref) { - this.ref = ref; + this.ref = ref; } /** * @return The XenAPI reference (OpaqueRef) to this object. */ public String toWireString() { - return this.ref; + return this.ref; } /** @@ -79,7 +78,7 @@ public class VTPM extends XenAPIObject { { if (obj != null && obj instanceof VTPM) { - VTPM other = (VTPM) obj; + VTPM other = (VTPM)obj; return other.ref.equals(this.ref); } else { @@ -109,8 +108,8 @@ public class VTPM extends XenAPIObject { /** * Convert a VTPM.Record to a Map */ - public Map toMap() { - Map map = new HashMap(); + public Map toMap() { + Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("VM", this.VM == null ? new VM("OpaqueRef:NULL") : this.VM); map.put("backend", this.backend == null ? new VM("OpaqueRef:NULL") : this.backend); @@ -137,15 +136,15 @@ public class VTPM extends XenAPIObject { * @return all fields from the object */ public VTPM.Record getRecord(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VTPM.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVTPMRecord(result); + return Types.toVTPMRecord(result); } /** @@ -155,15 +154,15 @@ public class VTPM extends XenAPIObject { * @return reference to the object */ public static VTPM getByUuid(Connection c, String uuid) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VTPM.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVTPM(result); + return Types.toVTPM(result); } /** @@ -173,9 +172,9 @@ public class VTPM extends XenAPIObject { * @return Task */ public static Task createAsync(Connection c, VTPM.Record record) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VTPM.create"; String session = c.getSessionReference(); Map record_map = record.toMap(); @@ -192,16 +191,16 @@ public class VTPM extends XenAPIObject { * @return reference to the newly created object */ public static VTPM create(Connection c, VTPM.Record record) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VTPM.create"; String session = c.getSessionReference(); Map record_map = record.toMap(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(record_map)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVTPM(result); + return Types.toVTPM(result); } /** @@ -210,9 +209,9 @@ public class VTPM extends XenAPIObject { * @return Task */ public Task destroyAsync(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "Async.VTPM.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -226,9 +225,9 @@ public class VTPM extends XenAPIObject { * */ public void destroy(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VTPM.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; @@ -242,15 +241,15 @@ public class VTPM extends XenAPIObject { * @return value of the field */ public String getUuid(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VTPM.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toString(result); + return Types.toString(result); } /** @@ -259,15 +258,15 @@ public class VTPM extends XenAPIObject { * @return value of the field */ public VM getVM(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VTPM.get_VM"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVM(result); + return Types.toVM(result); } /** @@ -276,15 +275,15 @@ public class VTPM extends XenAPIObject { * @return value of the field */ public VM getBackend(Connection c) throws - BadServerResponse, - XenAPIException, - XmlRpcException { + BadServerResponse, + XenAPIException, + XmlRpcException { String method_call = "VTPM.get_backend"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); - return Types.toVM(result); + return Types.toVM(result); } } \ No newline at end of file diff --git a/engine/api/src/com/cloud/vm/VirtualMachineManager.java b/engine/api/src/com/cloud/vm/VirtualMachineManager.java index 7292d659f7e..ac79860df31 100644 --- a/engine/api/src/com/cloud/vm/VirtualMachineManager.java +++ b/engine/api/src/com/cloud/vm/VirtualMachineManager.java @@ -48,9 +48,10 @@ import com.cloud.utils.fsm.NoTransitionException; * Manages allocating resources to vms. */ public interface VirtualMachineManager extends Manager { + static final ConfigKey ExecuteInSequence = new ConfigKey("Advanced", Boolean.class, "execute.in.sequence.hypervisor.commands", "false", - "If set to true, StartCommand, StopCommand, CopyCommand, MigrateCommand will be synchronized on the agent side." - + " If set to false, these commands become asynchronous. Default value is false.", true); + "If set to true, StartCommand, StopCommand, CopyCommand, MigrateCommand will be synchronized on the agent side." + + " If set to false, these commands become asynchronous. Default value is false.", false); public interface Topics { public static final String VM_POWER_STATE = "vm.powerstate"; @@ -60,7 +61,7 @@ public interface VirtualMachineManager extends Manager { * Allocates a new virtual machine instance in the CloudStack DB. This * orchestrates the creation of all virtual resources needed in CloudStack * DB to bring up a VM. - * + * * @param vmInstanceName Instance name of the VM. This name uniquely * a VM in CloudStack's deploy environment. The caller gets to * define this VM but it must be unqiue for all of CloudStack. @@ -93,55 +94,44 @@ public interface VirtualMachineManager extends Manager { boolean stateTransitTo(VirtualMachine vm, VirtualMachine.Event e, Long hostId) throws NoTransitionException; - void advanceStart(String vmUuid, Map params) throws InsufficientCapacityException, ResourceUnavailableException, + void advanceStart(String vmUuid, Map params, DeploymentPlanner planner) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException, OperationTimedoutException; - void advanceStart(String vmUuid, Map params, DeploymentPlan planToDeploy) throws InsufficientCapacityException, + void advanceStart(String vmUuid, Map params, DeploymentPlan planToDeploy, DeploymentPlanner planner) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException, OperationTimedoutException; - void orchestrateStart(String vmUuid, Map params, DeploymentPlan planToDeploy) throws InsufficientCapacityException, - ResourceUnavailableException, ConcurrentOperationException, OperationTimedoutException; - - void advanceStop(String vmUuid, boolean cleanupEvenIfUnableToStop) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException; + void orchestrateStart(String vmUuid, Map params, DeploymentPlan planToDeploy, DeploymentPlanner planner) throws InsufficientCapacityException, + ResourceUnavailableException, ConcurrentOperationException, OperationTimedoutException; - void orchestrateStop(String vmUuid, boolean cleanupEvenIfUnableToStop) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException; + void advanceStop(String vmUuid, boolean cleanupEvenIfUnableToStop) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException; void advanceExpunge(String vmUuid) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException; void destroy(String vmUuid) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException; - void migrateAway(String vmUuid, long hostId) throws InsufficientServerCapacityException; + void migrateAway(String vmUuid, long hostId, DeploymentPlanner planner) throws InsufficientServerCapacityException; void migrate(String vmUuid, long srcHostId, DeployDestination dest) throws ResourceUnavailableException, ConcurrentOperationException; - - void orchestrateMigrate(String vmUuid, long srcHostId, DeployDestination dest) throws ResourceUnavailableException, ConcurrentOperationException; - void migrateWithStorage(String vmUuid, long srcId, long destId, Map volumeToPool) throws ResourceUnavailableException, - ConcurrentOperationException; - - void orchestrateMigrateWithStorage(String vmUuid, long srcId, long destId, Map volumeToPool) throws ResourceUnavailableException, ConcurrentOperationException; - + void migrateWithStorage(String vmUuid, long srcId, long destId, Map volumeToPool) throws ResourceUnavailableException, ConcurrentOperationException; + void reboot(String vmUuid, Map params) throws InsufficientCapacityException, ResourceUnavailableException; - void orchestrateReboot(String vmUuid, Map params) throws InsufficientCapacityException, ResourceUnavailableException; - void advanceReboot(String vmUuid, Map params) throws InsufficientCapacityException, ResourceUnavailableException, - ConcurrentOperationException, OperationTimedoutException; + ConcurrentOperationException, OperationTimedoutException; /** * Check to see if a virtual machine can be upgraded to the given service offering - * + * * @param vm * @param offering * @return true if the host can handle the upgrade, false otherwise */ boolean isVirtualMachineUpgradable(final VirtualMachine vm, final ServiceOffering offering); - + VirtualMachine findById(long vmId); void storageMigration(String vmUuid, StoragePool storagePoolId); - - void orchestrateStorageMigration(String vmUuid, StoragePool storagePoolId); /** * @param vmInstance @@ -165,12 +155,8 @@ public interface VirtualMachineManager extends Manager { * @throws ResourceUnavailableException * @throws InsufficientCapacityException */ - NicProfile addVmToNetwork(VirtualMachine vm, Network network, NicProfile requested) throws ConcurrentOperationException, ResourceUnavailableException, - InsufficientCapacityException; - - NicProfile orchestrateAddVmToNetwork(VirtualMachine vm, Network network, NicProfile requested) throws ConcurrentOperationException, - ResourceUnavailableException, InsufficientCapacityException; - + NicProfile addVmToNetwork(VirtualMachine vm, Network network, NicProfile requested) throws ConcurrentOperationException, + ResourceUnavailableException, InsufficientCapacityException; /** * @param vm @@ -181,8 +167,6 @@ public interface VirtualMachineManager extends Manager { */ boolean removeNicFromVm(VirtualMachine vm, Nic nic) throws ConcurrentOperationException, ResourceUnavailableException; - boolean orchestrateRemoveNicFromVm(VirtualMachine vm, Nic nic) throws ConcurrentOperationException, ResourceUnavailableException; - /** * @param vm * @param network @@ -192,9 +176,6 @@ public interface VirtualMachineManager extends Manager { * @throws ConcurrentOperationException */ boolean removeVmFromNetwork(VirtualMachine vm, Network network, URI broadcastUri) throws ConcurrentOperationException, ResourceUnavailableException; - - boolean orchestrateRemoveVmFromNetwork(VirtualMachine vm, Network network, URI broadcastUri) throws ConcurrentOperationException, ResourceUnavailableException; - /** * @param nic * @param hypervisorType @@ -209,15 +190,11 @@ public interface VirtualMachineManager extends Manager { */ VirtualMachineTO toVmTO(VirtualMachineProfile profile); - VirtualMachine reConfigureVm(String vmUuid, ServiceOffering newServiceOffering, boolean sameHost) throws ResourceUnavailableException, ConcurrentOperationException; - - VirtualMachine orchestrateReConfigureVm(String vmUuid, ServiceOffering newServiceOffering, boolean sameHost) throws ResourceUnavailableException, ConcurrentOperationException; + VirtualMachine reConfigureVm(String vmUuid, ServiceOffering newServiceOffering, boolean sameHost) throws ResourceUnavailableException, ConcurrentOperationException, + InsufficientServerCapacityException; void findHostAndMigrate(String vmUuid, Long newSvcOfferingId, DeploymentPlanner.ExcludeList excludeHostList) throws InsufficientCapacityException, - ConcurrentOperationException, ResourceUnavailableException; + ConcurrentOperationException, ResourceUnavailableException; void migrateForScale(String vmUuid, long srcHostId, DeployDestination dest, Long newSvcOfferingId) throws ResourceUnavailableException, ConcurrentOperationException; - - void orchestrateMigrateForScale(String vmUuid, long srcHostId, DeployDestination dest, Long newSvcOfferingId) throws ResourceUnavailableException, ConcurrentOperationException; - } diff --git a/engine/api/src/org/apache/cloudstack/engine/orchestration/service/NetworkOrchestrationService.java b/engine/api/src/org/apache/cloudstack/engine/orchestration/service/NetworkOrchestrationService.java index fc196e24568..a50c184a5e0 100755 --- a/engine/api/src/org/apache/cloudstack/engine/orchestration/service/NetworkOrchestrationService.java +++ b/engine/api/src/org/apache/cloudstack/engine/orchestration/service/NetworkOrchestrationService.java @@ -125,7 +125,7 @@ public interface NetworkOrchestrationService { boolean shutdownNetwork(long networkId, ReservationContext context, boolean cleanupElements); - boolean destroyNetwork(long networkId, ReservationContext context); + boolean destroyNetwork(long networkId, ReservationContext context, boolean forced); Network createGuestNetwork(long networkOfferingId, String name, String displayText, String gateway, String cidr, String vlanId, String networkDomain, Account owner, Long domainId, PhysicalNetwork physicalNetwork, long zoneId, ACLType aclType, Boolean subdomainAccess, Long vpcId, String ip6Gateway, String ip6Cidr, @@ -208,11 +208,13 @@ public interface NetworkOrchestrationService { boolean isSecondaryIpSetForNic(long nicId); - List listVmNics(Long vmId, Long nicId); + List listVmNics(long vmId, Long nicId, Long networkId); Nic savePlaceholderNic(Network network, String ip4Address, String ip6Address, Type vmType); DhcpServiceProvider getDhcpServiceProvider(Network network); void removeDhcpServiceInSubnet(Nic nic); + + boolean resourceCountNeedsUpdate(NetworkOffering ntwkOff, ACLType aclType); } diff --git a/engine/api/src/org/apache/cloudstack/engine/orchestration/service/VolumeOrchestrationService.java b/engine/api/src/org/apache/cloudstack/engine/orchestration/service/VolumeOrchestrationService.java index a9ccc06617a..f79d3361b97 100644 --- a/engine/api/src/org/apache/cloudstack/engine/orchestration/service/VolumeOrchestrationService.java +++ b/engine/api/src/org/apache/cloudstack/engine/orchestration/service/VolumeOrchestrationService.java @@ -44,6 +44,7 @@ import com.cloud.utils.fsm.NoTransitionException; import com.cloud.vm.DiskProfile; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; +import org.apache.cloudstack.framework.config.ConfigKey; /** * VolumeOrchestrationService is a PURE orchestration service on CloudStack @@ -53,6 +54,21 @@ import com.cloud.vm.VirtualMachineProfile; * to provision volumes. */ public interface VolumeOrchestrationService { + + static final ConfigKey CustomDiskOfferingMinSize = new ConfigKey("Advanced", + Long.class, + "custom.diskoffering.size.min", + "1", + "Minimum size in GB for custom disk offering.", + true + ); + static final ConfigKey CustomDiskOfferingMaxSize = new ConfigKey("Advanced", + Long.class, + "custom.diskoffering.size.max", + "1024", + "Maximum size in GB for custom disk offering.", + true + ); VolumeInfo moveVolume(VolumeInfo volume, long destPoolDcId, Long destPoolPodId, Long destPoolClusterId, HypervisorType dataDiskHyperType) throws ConcurrentOperationException, StorageUnavailableException; @@ -78,6 +94,8 @@ public interface VolumeOrchestrationService { void cleanupVolumes(long vmId) throws ConcurrentOperationException; + void disconnectVolumesFromHost(long vmId, long hostId); + void migrateVolumes(VirtualMachine vm, VirtualMachineTO vmTo, Host srcHost, Host destHost, Map volumeToPool); boolean storageMigration(VirtualMachineProfile vm, StoragePool destPool) throws StorageUnavailableException; diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStoreManager.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStoreManager.java index 210d4ae2fbe..5ebef031c5c 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStoreManager.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/DataStoreManager.java @@ -42,4 +42,6 @@ public interface DataStoreManager { List listImageStores(); List listImageCacheStores(); + + boolean isRegionStore(DataStore store); } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/EndPointSelector.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/EndPointSelector.java index b812f6efd99..4657316dd8a 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/EndPointSelector.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/EndPointSelector.java @@ -23,11 +23,17 @@ import java.util.List; public interface EndPointSelector { EndPoint select(DataObject srcData, DataObject destData); + EndPoint select(DataObject srcData, DataObject destData, StorageAction action); + EndPoint select(DataObject object); EndPoint select(DataStore store); + EndPoint select(DataObject object, StorageAction action); + List selectAll(DataStore store); EndPoint select(Scope scope, Long storeId); + + EndPoint selectHypervisorHost(Scope scope); } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStoreDriver.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStoreDriver.java index f3399cd733e..c4dfc5ceb7e 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStoreDriver.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStoreDriver.java @@ -21,9 +21,19 @@ package org.apache.cloudstack.engine.subsystem.api.storage; import org.apache.cloudstack.framework.async.AsyncCompletionCallback; import org.apache.cloudstack.storage.command.CommandResult; +import com.cloud.host.Host; +import com.cloud.storage.StoragePool; +import com.cloud.storage.Volume; + public interface PrimaryDataStoreDriver extends DataStoreDriver { public ChapInfo getChapInfo(VolumeInfo volumeInfo); + public boolean connectVolumeToHost(VolumeInfo volumeInfo, Host host, DataStore dataStore); + + public void disconnectVolumeFromHost(VolumeInfo volumeInfo, Host host, DataStore dataStore); + + public long getVolumeSizeIncludingHypervisorSnapshotReserve(Volume volume, StoragePool pool); + public void takeSnapshot(SnapshotInfo snapshot, AsyncCompletionCallback callback); public void revertSnapshot(SnapshotInfo snapshot, AsyncCompletionCallback callback); diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotDataFactory.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotDataFactory.java index d5255f40407..59e59a60662 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotDataFactory.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotDataFactory.java @@ -30,4 +30,6 @@ public interface SnapshotDataFactory { SnapshotInfo getSnapshot(long snapshotId, DataStoreRole role); List listSnapshotOnCache(long snapshotId); + + SnapshotInfo getReadySnapshotOnCache(long snapshotId); } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotService.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotService.java index e953eb6e21b..000b9ec4e60 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotService.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotService.java @@ -25,4 +25,6 @@ public interface SnapshotService { boolean deleteSnapshot(SnapshotInfo snapshot); boolean revertSnapshot(Long snapshotId); + + void syncVolumeSnapshotsToRegionStore(long volumeId, DataStore store); } diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/StorageAction.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/StorageAction.java new file mode 100644 index 00000000000..4fbb20ed29e --- /dev/null +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/StorageAction.java @@ -0,0 +1,25 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.cloudstack.engine.subsystem.api.storage; + +public enum StorageAction { + TAKESNAPSHOT, + BACKUPSNAPSHOT, + DELETESNAPSHOT +} diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeInfo.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeInfo.java index 5cba79ad2b4..f93f4efac83 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeInfo.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeInfo.java @@ -22,6 +22,7 @@ import com.cloud.agent.api.Answer; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.offering.DiskOffering.DiskCacheMode; import com.cloud.storage.Volume; +import com.cloud.vm.VirtualMachine; public interface VolumeInfo extends DataObject, Volume { boolean isAttachedVM(); @@ -35,6 +36,7 @@ public interface VolumeInfo extends DataObject, Volume { Long getLastPoolId(); String getAttachedVmName(); + VirtualMachine getAttachedVM(); void processEventOnly(ObjectInDataStoreStateMachine.Event event); diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeService.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeService.java index bcc4e7f9c54..3f676ae73dc 100644 --- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeService.java +++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeService.java @@ -44,6 +44,10 @@ public interface VolumeService { ChapInfo getChapInfo(VolumeInfo volumeInfo, DataStore dataStore); + boolean connectVolumeToHost(VolumeInfo volumeInfo, Host host, DataStore dataStore); + + void disconnectVolumeFromHost(VolumeInfo volumeInfo, Host host, DataStore dataStore); + /** * Creates the volume based on the given criteria * diff --git a/engine/components-api/src/com/cloud/alert/AlertManager.java b/engine/components-api/src/com/cloud/alert/AlertManager.java index 56a27df1b42..be29a5dc57b 100755 --- a/engine/components-api/src/com/cloud/alert/AlertManager.java +++ b/engine/components-api/src/com/cloud/alert/AlertManager.java @@ -21,8 +21,8 @@ import org.apache.cloudstack.framework.config.ConfigKey; import com.cloud.utils.component.Manager; -public interface AlertManager extends Manager, AlertService{ - +public interface AlertManager extends Manager, AlertService { + static final ConfigKey StorageCapacityThreshold = new ConfigKey(Double.class, "cluster.storage.capacity.notificationthreshold", "Alert", "0.75", "Percentage (as a value between 0 and 1) of storage utilization above which alerts will be sent about low storage available.", true, ConfigKey.Scope.Cluster, null); @@ -34,11 +34,11 @@ public interface AlertManager extends Manager, AlertService{ static final ConfigKey StorageAllocatedCapacityThreshold = new ConfigKey(Double.class, "cluster.storage.allocated.capacity.notificationthreshold", "Alert", "0.75", "Percentage (as a value between 0 and 1) of allocated storage utilization above which alerts will be sent about low storage available.", true, ConfigKey.Scope.Cluster, null); - + void clearAlert(AlertType alertType, long dataCenterId, long podId); void recalculateCapacity(); - + void sendAlert(AlertType alertType, long dataCenterId, Long podId, String subject, String body); } diff --git a/engine/components-api/src/com/cloud/deploy/DeploymentPlanningManager.java b/engine/components-api/src/com/cloud/deploy/DeploymentPlanningManager.java index b61e89ddcea..de2fc0eaf5a 100644 --- a/engine/components-api/src/com/cloud/deploy/DeploymentPlanningManager.java +++ b/engine/components-api/src/com/cloud/deploy/DeploymentPlanningManager.java @@ -39,11 +39,12 @@ public interface DeploymentPlanningManager extends Manager { * * */ - DeployDestination planDeployment(VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoids) throws InsufficientServerCapacityException, - AffinityConflictException; + DeployDestination planDeployment(VirtualMachineProfile vmProfile, DeploymentPlan plan, + ExcludeList avoids, DeploymentPlanner planner) throws InsufficientServerCapacityException, AffinityConflictException; - String finalizeReservation(DeployDestination plannedDestination, VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoids) - throws InsufficientServerCapacityException, AffinityConflictException; + String finalizeReservation(DeployDestination plannedDestination, + VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoids) + throws InsufficientServerCapacityException, AffinityConflictException; void cleanupVMReservations(); } diff --git a/engine/components-api/src/com/cloud/event/UsageEventUtils.java b/engine/components-api/src/com/cloud/event/UsageEventUtils.java index 90a2f17f1b8..4f32cb32636 100644 --- a/engine/components-api/src/com/cloud/event/UsageEventUtils.java +++ b/engine/components-api/src/com/cloud/event/UsageEventUtils.java @@ -41,11 +41,11 @@ import com.cloud.utils.component.ComponentContext; public class UsageEventUtils { - private static UsageEventDao _usageEventDao; - private static AccountDao _accountDao; - private static DataCenterDao _dcDao; + private static UsageEventDao s_usageEventDao; + private static AccountDao s_accountDao; + private static DataCenterDao s_dcDao; private static final Logger s_logger = Logger.getLogger(UsageEventUtils.class); - protected static EventBus _eventBus = null; + protected static EventBus s_eventBus = null; @Inject UsageEventDao usageEventDao; @@ -59,9 +59,9 @@ public class UsageEventUtils { @PostConstruct void init() { - _usageEventDao = usageEventDao; - _accountDao = accountDao; - _dcDao = dcDao; + s_usageEventDao = usageEventDao; + s_accountDao = accountDao; + s_dcDao = dcDao; } public static void publishUsageEvent(String usageType, long accountId, long zoneId, long resourceId, String resourceName, Long offeringId, Long templateId, @@ -107,47 +107,47 @@ public class UsageEventUtils { private static void saveUsageEvent(String usageType, long accountId, long zoneId, long resourceId, String resourceName, Long offeringId, Long templateId, String resourceType, Map details) { UsageEventVO usageEvent = new UsageEventVO(usageType, accountId, zoneId, resourceId, resourceName, offeringId, templateId, resourceType); - _usageEventDao.persist(usageEvent); - _usageEventDao.saveDetails(usageEvent.getId(), details); + s_usageEventDao.persist(usageEvent); + s_usageEventDao.saveDetails(usageEvent.getId(), details); } public static void saveUsageEvent(String usageType, long accountId, long zoneId, long resourceId, String resourceName, Long offeringId, Long templateId, Long size) { - _usageEventDao.persist(new UsageEventVO(usageType, accountId, zoneId, resourceId, resourceName, offeringId, templateId, size)); + s_usageEventDao.persist(new UsageEventVO(usageType, accountId, zoneId, resourceId, resourceName, offeringId, templateId, size)); } public static void saveUsageEvent(String usageType, long accountId, long zoneId, long resourceId, String resourceName, Long offeringId, Long templateId, Long size, Long virtualSize) { - _usageEventDao.persist(new UsageEventVO(usageType, accountId, zoneId, resourceId, resourceName, offeringId, templateId, size, virtualSize)); + s_usageEventDao.persist(new UsageEventVO(usageType, accountId, zoneId, resourceId, resourceName, offeringId, templateId, size, virtualSize)); } public static void saveUsageEvent(String usageType, long accountId, long zoneId, long resourceId, String resourceName) { - _usageEventDao.persist(new UsageEventVO(usageType, accountId, zoneId, resourceId, resourceName)); + s_usageEventDao.persist(new UsageEventVO(usageType, accountId, zoneId, resourceId, resourceName)); } public static void saveUsageEvent(String usageType, long accountId, long zoneId, long ipAddressId, String ipAddress, boolean isSourceNat, String guestType, boolean isSystem) { - _usageEventDao.persist(new UsageEventVO(usageType, accountId, zoneId, ipAddressId, ipAddress, isSourceNat, guestType, isSystem)); + s_usageEventDao.persist(new UsageEventVO(usageType, accountId, zoneId, ipAddressId, ipAddress, isSourceNat, guestType, isSystem)); } public static void saveUsageEvent(String usageType, long accountId, long zoneId, long resourceId, String resourceName, Long offeringId, Long templateId, String resourceType) { - _usageEventDao.persist(new UsageEventVO(usageType, accountId, zoneId, resourceId, resourceName, offeringId, templateId, resourceType)); + s_usageEventDao.persist(new UsageEventVO(usageType, accountId, zoneId, resourceId, resourceName, offeringId, templateId, resourceType)); } public static void saveUsageEvent(String usageType, long accountId, long zoneId, long vmId, long securityGroupId) { - _usageEventDao.persist(new UsageEventVO(usageType, accountId, zoneId, vmId, securityGroupId)); + s_usageEventDao.persist(new UsageEventVO(usageType, accountId, zoneId, vmId, securityGroupId)); } private static void publishUsageEvent(String usageEventType, Long accountId, Long zoneId, String resourceType, String resourceUUID) { try { - _eventBus = ComponentContext.getComponent(EventBus.class); + s_eventBus = ComponentContext.getComponent(EventBus.class); } catch (NoSuchBeanDefinitionException nbe) { return; // no provider is configured to provide events bus, so just return } - Account account = _accountDao.findById(accountId); - DataCenterVO dc = _dcDao.findById(zoneId); + Account account = s_accountDao.findById(accountId); + DataCenterVO dc = s_dcDao.findById(zoneId); // if account has been deleted, this might be called during cleanup of resources and results in null pointer if (account == null) @@ -156,7 +156,7 @@ public class UsageEventUtils { // if an invalid zone is passed in, create event without zone UUID String zoneUuid = null; if (dc != null) - zoneUuid = dc.getUuid(); + zoneUuid = dc.getUuid(); Event event = new Event(Name, EventCategory.USAGE_EVENT.getName(), usageEventType, resourceType, resourceUUID); @@ -173,7 +173,7 @@ public class UsageEventUtils { event.setDescription(eventDescription); try { - _eventBus.publish(event); + s_eventBus.publish(event); } catch (EventBusException e) { s_logger.warn("Failed to publish usage event on the the event bus."); } diff --git a/engine/components-api/src/com/cloud/network/IpAddressManager.java b/engine/components-api/src/com/cloud/network/IpAddressManager.java index e7061f9ecd9..9ccc9466f70 100644 --- a/engine/components-api/src/com/cloud/network/IpAddressManager.java +++ b/engine/components-api/src/com/cloud/network/IpAddressManager.java @@ -21,7 +21,6 @@ import java.util.List; import org.apache.cloudstack.framework.config.ConfigKey; import com.cloud.dc.DataCenter; -import com.cloud.dc.Pod; import com.cloud.dc.Vlan.VlanType; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientAddressCapacityException; @@ -169,8 +168,8 @@ public interface IpAddressManager { int getRuleCountForIp(Long addressId, FirewallRule.Purpose purpose, FirewallRule.State state); - public String allocateGuestIP(Account ipOwner, boolean isSystem, long zoneId, Long networkId, String requestedIp) throws InsufficientAddressCapacityException; + public String allocateGuestIP(Network network, String requestedIp) throws InsufficientAddressCapacityException; - String allocatePublicIpForGuestNic(Long networkId, DataCenter dc, Pod pod, Account caller, String requestedIp) throws InsufficientAddressCapacityException; + String allocatePublicIpForGuestNic(Network network, Long podId, Account ipOwner, String requestedIp) throws InsufficientAddressCapacityException; } diff --git a/engine/components-api/src/com/cloud/network/NetworkStateListener.java b/engine/components-api/src/com/cloud/network/NetworkStateListener.java index 12190613ce8..0a5e0332a9b 100644 --- a/engine/components-api/src/com/cloud/network/NetworkStateListener.java +++ b/engine/components-api/src/com/cloud/network/NetworkStateListener.java @@ -45,7 +45,7 @@ public class NetworkStateListener implements StateListener handleVmWorkJob(VmWork work) throws Exception; +} diff --git a/engine/components-api/src/com/cloud/vm/VmWorkJobHandlerProxy.java b/engine/components-api/src/com/cloud/vm/VmWorkJobHandlerProxy.java new file mode 100644 index 00000000000..ce10a83c7cd --- /dev/null +++ b/engine/components-api/src/com/cloud/vm/VmWorkJobHandlerProxy.java @@ -0,0 +1,133 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.vm; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + +import org.apache.log4j.Logger; + +import com.google.gson.Gson; + +import org.apache.cloudstack.framework.jobs.impl.JobSerializerHelper; +import org.apache.cloudstack.jobs.JobInfo; + +import com.cloud.serializer.GsonHelper; +import com.cloud.utils.Pair; + +/** + * VmWorkJobHandlerProxy can not be used as standalone due to run-time + * reflection usage in its implementation, run-time reflection conflicts with Spring proxy mode. + * It means that we can not instantiate VmWorkJobHandlerProxy beans directly in Spring and expect + * it can handle VmWork directly from there. + * + */ +public class VmWorkJobHandlerProxy implements VmWorkJobHandler { + + private static final Logger s_logger = Logger.getLogger(VmWorkJobHandlerProxy.class); + + private Object _target; + private Map, Method> _handlerMethodMap = new HashMap, Method>(); + + private Gson _gsonLogger; + + public VmWorkJobHandlerProxy(Object target) { + _gsonLogger = GsonHelper.getGsonLogger(); + + buildLookupMap(target.getClass()); + _target = target; + } + + private void buildLookupMap(Class hostClass) { + Class clz = hostClass; + while (clz != null && clz != Object.class) { + Method[] hostHandlerMethods = clz.getDeclaredMethods(); + + for (Method method : hostHandlerMethods) { + if (isVmWorkJobHandlerMethod(method)) { + Class paramType = method.getParameterTypes()[0]; + assert (_handlerMethodMap.get(paramType) == null); + + method.setAccessible(true); + _handlerMethodMap.put(paramType, method); + } + } + + clz = clz.getSuperclass(); + } + } + + @SuppressWarnings("deprecation") + private boolean isVmWorkJobHandlerMethod(Method method) { + if (method.getParameterTypes().length != 1) + return false; + + Class returnType = method.getReturnType(); + if (!Pair.class.isAssignableFrom(returnType)) + return false; + + Class paramType = method.getParameterTypes()[0]; + if (!VmWork.class.isAssignableFrom(paramType)) + return false; + + return true; + } + + private Method getHandlerMethod(Class paramType) { + return _handlerMethodMap.get(paramType); + } + + @SuppressWarnings("unchecked") + @Override + public Pair handleVmWorkJob(VmWork work) throws Exception { + + Method method = getHandlerMethod(work.getClass()); + if (method != null) { + + try { + if (s_logger.isDebugEnabled()) + s_logger.debug("Execute VM work job: " + work.getClass().getName() + _gsonLogger.toJson(work)); + + Object obj = method.invoke(_target, work); + + if (s_logger.isDebugEnabled()) + s_logger.debug("Done executing VM work job: " + work.getClass().getName() + _gsonLogger.toJson(work)); + + assert (obj instanceof Pair); + return (Pair)obj; + } catch (InvocationTargetException e) { + s_logger.error("Invocation exception, caused by: " + e.getCause()); + + // legacy CloudStack code relies on checked exception for error handling + // we need to re-throw the real exception here + if (e.getCause() != null && e.getCause() instanceof Exception) { + s_logger.info("Rethrow exception " + e.getCause()); + throw (Exception)e.getCause(); + } + + throw e; + } + } else { + s_logger.error("Unable to find handler for VM work job: " + work.getClass().getName() + _gsonLogger.toJson(work)); + + RuntimeException ex = new RuntimeException("Unable to find handler for VM work job: " + work.getClass().getName()); + return new Pair(JobInfo.Status.FAILED, JobSerializerHelper.toObjectSerializedString(ex)); + } + } +} diff --git a/engine/orchestration/src/com/cloud/vm/VmWorkSerializer.java b/engine/components-api/src/com/cloud/vm/VmWorkSerializer.java similarity index 84% rename from engine/orchestration/src/com/cloud/vm/VmWorkSerializer.java rename to engine/components-api/src/com/cloud/vm/VmWorkSerializer.java index 9a1aaaced67..bd6b52d261f 100644 --- a/engine/orchestration/src/com/cloud/vm/VmWorkSerializer.java +++ b/engine/components-api/src/com/cloud/vm/VmWorkSerializer.java @@ -21,8 +21,6 @@ import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; -import org.apache.cloudstack.framework.jobs.impl.JobSerializerHelper; - import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; @@ -31,9 +29,11 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; +import org.apache.cloudstack.framework.jobs.impl.JobSerializerHelper; + public class VmWorkSerializer { static class StringMapTypeAdapter implements JsonDeserializer { - + @Override public Map deserialize(JsonElement src, Type srcType, JsonDeserializationContext context) throws JsonParseException { @@ -47,7 +47,7 @@ public class VmWorkSerializer { return obj; } } - + protected static Gson s_gson; static { GsonBuilder gBuilder = new GsonBuilder(); @@ -55,21 +55,20 @@ public class VmWorkSerializer { gBuilder.registerTypeAdapter(Map.class, new StringMapTypeAdapter()); s_gson = gBuilder.create(); } - + public static String serialize(VmWork work) { - // TODO: there are way many generics, too tedious to get serialization work under GSON - // use java binary serialization instead - // - return JobSerializerHelper.toObjectSerializedString(work); + // TODO: there are way many generics, too tedious to get serialization work under GSON + // use java binary serialization instead + // + return JobSerializerHelper.toObjectSerializedString(work); // return s_gson.toJson(work); } public static T deserialize(Class clazz, String workInJsonText) { - // TODO: there are way many generics, too tedious to get serialization work under GSON - // use java binary serialization instead - // + // TODO: there are way many generics, too tedious to get serialization work under GSON + // use java binary serialization instead + // return (T)JobSerializerHelper.fromObjectSerializedString(workInJsonText); - // return (T)s_gson.fromJson(workInJsonText, clazz); + // return (T)s_gson.fromJson(workInJsonText, clazz); } } - diff --git a/engine/components-api/src/com/cloud/vm/snapshot/VMSnapshotManager.java b/engine/components-api/src/com/cloud/vm/snapshot/VMSnapshotManager.java index 7d233ca7d30..e7e3372b0db 100644 --- a/engine/components-api/src/com/cloud/vm/snapshot/VMSnapshotManager.java +++ b/engine/components-api/src/com/cloud/vm/snapshot/VMSnapshotManager.java @@ -42,5 +42,4 @@ public interface VMSnapshotManager extends VMSnapshotService, Manager { boolean syncVMSnapshot(VMInstanceVO vm, Long hostId); boolean hasActiveVMSnapshotTasks(Long vmId); - } diff --git a/engine/orchestration/resources/META-INF/cloudstack/core/spring-engine-orchestration-core-context.xml b/engine/orchestration/resources/META-INF/cloudstack/core/spring-engine-orchestration-core-context.xml index 0c76f008c32..fd5299c8f70 100644 --- a/engine/orchestration/resources/META-INF/cloudstack/core/spring-engine-orchestration-core-context.xml +++ b/engine/orchestration/resources/META-INF/cloudstack/core/spring-engine-orchestration-core-context.xml @@ -60,7 +60,6 @@ - + - + + + + + + + + + + + + + diff --git a/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java b/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java index 42648df9a89..d51df220195 100755 --- a/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java +++ b/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java @@ -828,7 +828,8 @@ public class AgentManagerImpl extends ManagerBase implements AgentManager, Handl DataCenterVO dcVO = _dcDao.findById(host.getDataCenterId()); HostPodVO podVO = _podDao.findById(host.getPodId()); String hostDesc = "name: " + host.getName() + " (id:" + host.getId() + "), availability zone: " + dcVO.getName() + ", pod: " + podVO.getName(); - _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, host.getDataCenterId(), host.getPodId(), "Host in ALERT state, " + hostDesc, "In availability zone " + host.getDataCenterId() + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, host.getDataCenterId(), host.getPodId(), "Host in ALERT state, " + hostDesc, + "In availability zone " + host.getDataCenterId() + ", host is in alert state: " + host.getId() + "-" + host.getName()); } } else { @@ -1474,20 +1475,12 @@ public class AgentManagerImpl extends ManagerBase implements AgentManager, Handl List hosts = sc.list(); for (HostVO host : hosts) { - long hostId = host.getId(); - DataCenterVO dcVO = _dcDao.findById(host.getDataCenterId()); - HostPodVO podVO = _podDao.findById(host.getPodId()); - String hostDesc = "name: " + host.getName() + " (id:" + hostId + "), availability zone: " + dcVO.getName() + ", pod: " + podVO.getName(); - - if (host.getType() != Host.Type.Storage) { -// List vos = _vmDao.listByHostId(hostId); -// List vosMigrating = _vmDao.listVmsMigratingFromHost(hostId); -// if (vos.isEmpty() && vosMigrating.isEmpty()) { -// _alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, host.getDataCenterId(), host.getPodId(), "Migration Complete for host " + hostDesc, "Host [" -// + hostDesc -// + "] is ready for maintenance"); -// _resourceMgr.resourceStateTransitTo(host, ResourceState.Event.InternalEnterMaintenance, _msId); -// } + if (_resourceMgr.checkAndMaintain(host.getId())) { + DataCenterVO dcVO = _dcDao.findById(host.getDataCenterId()); + HostPodVO podVO = _podDao.findById(host.getPodId()); + String hostDesc = "name: " + host.getName() + " (id:" + host.getId() + "), availability zone: " + dcVO.getName() + ", pod: " + podVO.getName(); + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, host.getDataCenterId(), host.getPodId(), "Migration Complete for host " + hostDesc, "Host [" + + hostDesc + "] is ready for maintenance"); } } } catch (Throwable th) { diff --git a/engine/orchestration/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java b/engine/orchestration/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java index d1fd2a7c899..01508a423a1 100755 --- a/engine/orchestration/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java +++ b/engine/orchestration/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java @@ -94,7 +94,7 @@ import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.nio.Link; import com.cloud.utils.nio.Task; -@Local(value = { AgentManager.class, ClusteredAgentRebalanceService.class }) +@Local(value = {AgentManager.class, ClusteredAgentRebalanceService.class}) public class ClusteredAgentManagerImpl extends AgentManagerImpl implements ClusterManagerListener, ClusteredAgentRebalanceService { final static Logger s_logger = Logger.getLogger(ClusteredAgentManagerImpl.class); private static final ScheduledExecutorService s_transferExecutor = Executors.newScheduledThreadPool(2, new NamedThreadFactory("Cluster-AgentRebalancingExecutor")); @@ -128,13 +128,13 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust } protected final ConfigKey EnableLB = new ConfigKey(Boolean.class, "agent.lb.enabled", "Advanced", "false", - "Enable agent load balancing between management server nodes", true); + "Enable agent load balancing between management server nodes", true); protected final ConfigKey ConnectedAgentThreshold = new ConfigKey(Double.class, "agent.load.threshold", "Advanced", "0.7", - "What percentage of the agents can be held by one management server before load balancing happens", true); + "What percentage of the agents can be held by one management server before load balancing happens", true); protected final ConfigKey LoadSize = new ConfigKey(Integer.class, "direct.agent.load.size", "Advanced", "16", - "How many agents to connect to in each round", true); + "How many agents to connect to in each round", true); protected final ConfigKey ScanInterval = new ConfigKey(Integer.class, "direct.agent.scan.interval", "Advanced", "90", - "Interval between scans to load agents", false, ConfigKey.Scope.Global, 1000); + "Interval between scans to load agents", false, ConfigKey.Scope.Global, 1000); @Override public boolean configure(String name, Map xmlParams) throws ConfigurationException { @@ -334,7 +334,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust if (transferVO != null) { if (transferVO.getFutureOwner() == _nodeId && transferVO.getState() == HostTransferState.TransferStarted) { s_logger.debug("Not processing " + Event.AgentDisconnected + " event for the host id=" + hostId + " as the host is being connected to " + - _nodeId); + _nodeId); return true; } } @@ -344,7 +344,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust // but the host has already reconnected to the current management server if (!attache.forForward()) { s_logger.debug("Not processing " + Event.AgentDisconnected + " event for the host id=" + hostId + - " as the host is directly connected to the current management server " + _nodeId); + " as the host is directly connected to the current management server " + _nodeId); return true; } @@ -375,7 +375,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust public void notifyNodesInCluster(AgentAttache attache) { s_logger.debug("Notifying other nodes of to disconnect"); - Command[] cmds = new Command[] { new ChangeAgentCommand(attache.getId(), Event.AgentDisconnected) }; + Command[] cmds = new Command[] {new ChangeAgentCommand(attache.getId(), Event.AgentDisconnected)}; _clusterMgr.broadcast(attache.getId(), _gson.toJson(cmds)); } @@ -384,23 +384,23 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust if (s_logger.isDebugEnabled()) { s_logger.debug("Notifying other MS nodes to run host scan task"); } - Command[] cmds = new Command[] { new ScheduleHostScanTaskCommand() }; + Command[] cmds = new Command[] {new ScheduleHostScanTaskCommand()}; _clusterMgr.broadcast(0, _gson.toJson(cmds)); } protected static void logT(byte[] bytes, final String msg) { s_logger.trace("Seq " + Request.getAgentId(bytes) + "-" + Request.getSequence(bytes) + ": MgmtId " + Request.getManagementServerId(bytes) + ": " + - (Request.isRequest(bytes) ? "Req: " : "Resp: ") + msg); + (Request.isRequest(bytes) ? "Req: " : "Resp: ") + msg); } protected static void logD(byte[] bytes, final String msg) { s_logger.debug("Seq " + Request.getAgentId(bytes) + "-" + Request.getSequence(bytes) + ": MgmtId " + Request.getManagementServerId(bytes) + ": " + - (Request.isRequest(bytes) ? "Req: " : "Resp: ") + msg); + (Request.isRequest(bytes) ? "Req: " : "Resp: ") + msg); } protected static void logI(byte[] bytes, final String msg) { s_logger.info("Seq " + Request.getAgentId(bytes) + "-" + Request.getSequence(bytes) + ": MgmtId " + Request.getManagementServerId(bytes) + ": " + - (Request.isRequest(bytes) ? "Req: " : "Resp: ") + msg); + (Request.isRequest(bytes) ? "Req: " : "Resp: ") + msg); } public boolean routeToPeer(String peer, byte[] bytes) { @@ -425,7 +425,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust if (s_logger.isDebugEnabled()) { logD(bytes, "Routing to peer"); } - Link.write(ch, new ByteBuffer[] { ByteBuffer.wrap(bytes) }, sslEngine); + Link.write(ch, new ByteBuffer[] {ByteBuffer.wrap(bytes)}, sslEngine); return true; } catch (IOException e) { try { @@ -618,7 +618,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust } Request req = Request.parse(data); Command[] cmds = req.getCommands(); - CancelCommand cancel = (CancelCommand) cmds[0]; + CancelCommand cancel = (CancelCommand)cmds[0]; if (s_logger.isDebugEnabled()) { logD(data, "Cancel request received"); } @@ -647,7 +647,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust return; } else { if (agent instanceof Routable) { - Routable cluster = (Routable) agent; + Routable cluster = (Routable)agent; cluster.routeToAgent(data); } else { agent.send(Request.parse(data)); @@ -664,7 +664,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust if (mgmtId != -1 && mgmtId != _nodeId) { routeToPeer(Long.toString(mgmtId), data); if (Request.requiresSequentialExecution(data)) { - AgentAttache attache = (AgentAttache) link.attachment(); + AgentAttache attache = (AgentAttache)link.attachment(); if (attache != null) { attache.sendNext(Request.getSequence(data)); } else if (s_logger.isDebugEnabled()) { @@ -726,7 +726,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust @Override public boolean executeRebalanceRequest(long agentId, long currentOwnerId, long futureOwnerId, Event event) throws AgentUnavailableException, - OperationTimedoutException { + OperationTimedoutException { boolean result = false; if (event == Event.RequestAgentRebalance) { return setToWaitForRebalance(agentId, currentOwnerId, futureOwnerId); @@ -793,7 +793,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust } else { if (s_logger.isDebugEnabled()) { s_logger.debug("There are no hosts to rebalance in the system. Current number of active management server nodes in the system is " + allMS.size() + - "; number of managed agents is " + allManagedAgents.size()); + "; number of managed agents is " + allManagedAgents.size()); } return; } @@ -947,7 +947,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust // no need to do anything with the real attache as we haven't modified it yet Date cutTime = DateUtil.currentGMTTime(); HostTransferMapVO transferMap = - _hostTransferDao.findActiveHostTransferMapByHostId(hostId, new Date(cutTime.getTime() - rebalanceTimeOut)); + _hostTransferDao.findActiveHostTransferMapByHostId(hostId, new Date(cutTime.getTime() - rebalanceTimeOut)); if (transferMap == null) { s_logger.debug("Timed out waiting for the host id=" + hostId + " to be ready to transfer, skipping rebalance for the host"); @@ -966,7 +966,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust ManagementServerHostVO ms = _mshostDao.findByMsid(transferMap.getFutureOwner()); if (ms != null && ms.getState() != ManagementServerHost.State.Up) { s_logger.debug("Can't transfer host " + hostId + " as it's future owner is not in UP state: " + ms + - ", skipping rebalance for the host"); + ", skipping rebalance for the host"); iterator.remove(); _hostTransferDao.completeAgentTransfer(hostId); continue; @@ -983,7 +983,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust } else { s_logger.debug("Agent " + hostId + " can't be transfered yet as its request queue size is " + attache.getQueueSize() + - " and listener queue size is " + attache.getNonRecurringListenersSize()); + " and listener queue size is " + attache.getNonRecurringListenersSize()); } } } else { @@ -1050,7 +1050,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust if (result) { if (s_logger.isDebugEnabled()) { s_logger.debug("Loading directly connected host " + host.getId() + "(" + host.getName() + ") to the management server " + _nodeId + - " as a part of rebalance process"); + " as a part of rebalance process"); } result = loadDirectlyConnectedHost(host, true); } else { @@ -1059,16 +1059,16 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust } catch (Exception ex) { s_logger.warn("Failed to load directly connected host " + host.getId() + "(" + host.getName() + ") to the management server " + _nodeId + - " as a part of rebalance process due to:", ex); + " as a part of rebalance process due to:", ex); result = false; } if (result) { s_logger.debug("Successfully loaded directly connected host " + host.getId() + "(" + host.getName() + ") to the management server " + _nodeId + - " as a part of rebalance process"); + " as a part of rebalance process"); } else { s_logger.warn("Failed to load directly connected host " + host.getId() + "(" + host.getName() + ") to the management server " + _nodeId + - " as a part of rebalance process"); + " as a part of rebalance process"); } } @@ -1089,7 +1089,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust return; } - ClusteredAgentAttache forwardAttache = (ClusteredAgentAttache) attache; + ClusteredAgentAttache forwardAttache = (ClusteredAgentAttache)attache; if (success) { @@ -1100,7 +1100,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust Request requestToTransfer = forwardAttache.getRequestToTransfer(); while (requestToTransfer != null) { s_logger.debug("Forwarding request " + requestToTransfer.getSequence() + " held in transfer attache " + hostId + " from the management server " + - _nodeId + " to " + futureOwnerId); + _nodeId + " to " + futureOwnerId); boolean routeResult = routeToPeer(Long.toString(futureOwnerId), requestToTransfer.getBytes()); if (!routeResult) { logD(requestToTransfer.getBytes(), "Failed to route request to peer"); @@ -1138,10 +1138,10 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust } synchronized (_agents) { - ClusteredDirectAgentAttache attache = (ClusteredDirectAgentAttache) _agents.get(hostId); + ClusteredDirectAgentAttache attache = (ClusteredDirectAgentAttache)_agents.get(hostId); if (attache != null && attache.getQueueSize() == 0 && attache.getNonRecurringListenersSize() == 0) { handleDisconnectWithoutInvestigation(attache, Event.StartAgentRebalance, true, true); - ClusteredAgentAttache forwardAttache = (ClusteredAgentAttache) createAttache(hostId); + ClusteredAgentAttache forwardAttache = (ClusteredAgentAttache)createAttache(hostId); if (forwardAttache == null) { s_logger.warn("Unable to create a forward attache for the host " + hostId + " as a part of rebalance process"); return false; @@ -1154,7 +1154,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust s_logger.warn("Attache for the agent " + hostId + " no longer exists on management server " + _nodeId + ", can't start host rebalancing"); } else { s_logger.warn("Attache for the agent " + hostId + " has request queue size= " + attache.getQueueSize() + " and listener queue size " + - attache.getNonRecurringListenersSize() + ", can't start host rebalancing"); + attache.getNonRecurringListenersSize() + ", can't start host rebalancing"); } return false; } @@ -1211,7 +1211,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust // Scheduling host scan task in peer MS is a best effort operation during host add, regular host scan // happens at fixed intervals anyways. So handling any exceptions that may be thrown s_logger.warn("Exception happened while trying to schedule host scan task on mgmt server " + _clusterMgr.getSelfPeerName() + - ", ignoring as regular host scan happens at fixed interval anyways", e); + ", ignoring as regular host scan happens at fixed interval anyways", e); return null; } @@ -1250,7 +1250,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust } if (cmds.length == 1 && cmds[0] instanceof ChangeAgentCommand) { // intercepted - ChangeAgentCommand cmd = (ChangeAgentCommand) cmds[0]; + ChangeAgentCommand cmd = (ChangeAgentCommand)cmds[0]; if (s_logger.isDebugEnabled()) { s_logger.debug("Intercepting command for agent change: agent " + cmd.getAgentId() + " event: " + cmd.getEvent()); @@ -1271,7 +1271,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust answers[0] = new ChangeAgentAnswer(cmd, result); return _gson.toJson(answers); } else if (cmds.length == 1 && cmds[0] instanceof TransferAgentCommand) { - TransferAgentCommand cmd = (TransferAgentCommand) cmds[0]; + TransferAgentCommand cmd = (TransferAgentCommand)cmds[0]; if (s_logger.isDebugEnabled()) { s_logger.debug("Intercepting command for agent rebalancing: agent " + cmd.getAgentId() + " event: " + cmd.getEvent()); @@ -1294,7 +1294,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust answers[0] = new Answer(cmd, result, null); return _gson.toJson(answers); } else if (cmds.length == 1 && cmds[0] instanceof PropagateResourceEventCommand) { - PropagateResourceEventCommand cmd = (PropagateResourceEventCommand) cmds[0]; + PropagateResourceEventCommand cmd = (PropagateResourceEventCommand)cmds[0]; s_logger.debug("Intercepting command to propagate event " + cmd.getEvent().name() + " for host " + cmd.getHostId()); @@ -1311,7 +1311,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust answers[0] = new Answer(cmd, result, null); return _gson.toJson(answers); } else if (cmds.length == 1 && cmds[0] instanceof ScheduleHostScanTaskCommand) { - ScheduleHostScanTaskCommand cmd = (ScheduleHostScanTaskCommand) cmds[0]; + ScheduleHostScanTaskCommand cmd = (ScheduleHostScanTaskCommand)cmds[0]; String response = handleScheduleHostScanTaskCommand(cmd); return response; } @@ -1328,14 +1328,14 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust if (s_logger.isDebugEnabled()) { s_logger.debug("Completed dispatching -> " + pdu.getAgentId() + ", json: " + pdu.getJsonPackage() + " in " + - (System.currentTimeMillis() - startTick) + " ms, return result: " + jsonReturn); + (System.currentTimeMillis() - startTick) + " ms, return result: " + jsonReturn); } return jsonReturn; } else { if (s_logger.isDebugEnabled()) { s_logger.debug("Completed dispatching -> " + pdu.getAgentId() + ", json: " + pdu.getJsonPackage() + " in " + - (System.currentTimeMillis() - startTick) + " ms, return null result"); + (System.currentTimeMillis() - startTick) + " ms, return null result"); } } } catch (AgentUnavailableException e) { @@ -1386,12 +1386,12 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust double load = managedHostsCount / allHostsCount; if (load >= ConnectedAgentThreshold.value()) { s_logger.debug("Scheduling agent rebalancing task as the average agent load " + load + " is more than the threshold " + - ConnectedAgentThreshold.value()); + ConnectedAgentThreshold.value()); scheduleRebalanceAgents(); _agentLbHappened = true; } else { s_logger.debug("Not scheduling agent rebalancing task as the averages load " + load + " is less than the threshold " + - ConnectedAgentThreshold.value()); + ConnectedAgentThreshold.value()); } } } diff --git a/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java b/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java index 1cac898f927..b71252879fc 100755 --- a/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java +++ b/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java @@ -40,6 +40,8 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.log4j.Logger; + import org.apache.cloudstack.affinity.dao.AffinityGroupVMMapDao; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; @@ -56,10 +58,10 @@ import org.apache.cloudstack.framework.jobs.AsyncJobManager; import org.apache.cloudstack.framework.jobs.Outcome; import org.apache.cloudstack.framework.jobs.dao.VmWorkJobDao; import org.apache.cloudstack.framework.jobs.impl.AsyncJobVO; -import org.apache.cloudstack.framework.jobs.impl.JobSerializerHelper; import org.apache.cloudstack.framework.jobs.impl.OutcomeImpl; import org.apache.cloudstack.framework.jobs.impl.VmWorkJobVO; import org.apache.cloudstack.framework.messagebus.MessageBus; +import org.apache.cloudstack.framework.messagebus.MessageDispatcher; import org.apache.cloudstack.framework.messagebus.MessageHandler; import org.apache.cloudstack.jobs.JobInfo; import org.apache.cloudstack.managed.context.ManagedContextRunnable; @@ -67,7 +69,6 @@ import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; import org.apache.cloudstack.storage.to.VolumeObjectTO; import org.apache.cloudstack.utils.identity.ManagementServerNode; -import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.Listener; @@ -117,6 +118,7 @@ import com.cloud.dc.dao.HostPodDao; import com.cloud.deploy.DataCenterDeployment; import com.cloud.deploy.DeployDestination; import com.cloud.deploy.DeploymentPlan; +import com.cloud.deploy.DeploymentPlanner; import com.cloud.deploy.DeploymentPlanner.ExcludeList; import com.cloud.deploy.DeploymentPlanningManager; import com.cloud.domain.dao.DomainDao; @@ -181,7 +183,7 @@ import com.cloud.utils.db.DB; import com.cloud.utils.db.EntityManager; import com.cloud.utils.db.GlobalLock; import com.cloud.utils.db.Transaction; -import com.cloud.utils.db.TransactionCallbackNoReturn; +import com.cloud.utils.db.TransactionCallback; import com.cloud.utils.db.TransactionCallbackWithException; import com.cloud.utils.db.TransactionCallbackWithExceptionNoReturn; import com.cloud.utils.db.TransactionLegacy; @@ -204,9 +206,11 @@ import com.cloud.vm.snapshot.VMSnapshotVO; import com.cloud.vm.snapshot.dao.VMSnapshotDao; @Local(value = VirtualMachineManager.class) -public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMachineManager, Listener, Configurable { +public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMachineManager, VmWorkJobHandler, Listener, Configurable { private static final Logger s_logger = Logger.getLogger(VirtualMachineManagerImpl.class); + public static final String VM_WORK_JOB_HANDLER = VirtualMachineManagerImpl.class.getSimpleName(); + private static final String VM_SYNC_ALERT_SUBJECT = "VM state sync alert"; @Inject @@ -269,17 +273,18 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac protected AffinityGroupVMMapDao _affinityGroupVMMapDao; @Inject protected EntityManager _entityMgr; + @Inject ConfigDepot _configDepot; - protected List _hostAllocators; + protected List hostAllocators; public List getHostAllocators() { - return _hostAllocators; + return hostAllocators; } - public void setHostAllocators(List _hostAllocators) { - this._hostAllocators = _hostAllocators; + public void setHostAllocators(List hostAllocators) { + this.hostAllocators = hostAllocators; } protected List _storagePoolAllocators; @@ -311,6 +316,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac @Inject protected AsyncJobManager _jobMgr; + VmWorkJobHandlerProxy _jobHandlerProxy = new VmWorkJobHandlerProxy(this); + Map _vmGurus = new HashMap(); protected StateMachine2 _stateMachine; @@ -453,7 +460,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac return; } - advanceStop(vm, false); + advanceStop(vm.getUuid(), false); + vm = _vmDao.findByUuid(vm.getUuid()); try { if (!stateTransitTo(vm, VirtualMachine.Event.ExpungeOperation, vm.getHostId())) { @@ -478,6 +486,36 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac List nicExpungeCommands = hvGuru.finalizeExpungeNics(vm, profile.getNics()); _networkMgr.cleanupNics(profile); + s_logger.debug("Cleaning up hypervisor data structures (ex. SRs in XenServer) for managed storage"); + + List volumeExpungeCommands = hvGuru.finalizeExpungeVolumes(vm); + + Long hostId = vm.getHostId() != null ? vm.getHostId() : vm.getLastHostId(); + + if (volumeExpungeCommands != null && volumeExpungeCommands.size() > 0 && hostId != null) { + Commands cmds = new Commands(Command.OnError.Stop); + + for (Command volumeExpungeCommand : volumeExpungeCommands) { + cmds.addCommand(volumeExpungeCommand); + } + + _agentMgr.send(hostId, cmds); + + if (!cmds.isSuccessful()) { + for (Answer answer : cmds.getAnswers()) { + if (!answer.getResult()) { + s_logger.warn("Failed to expunge vm due to: " + answer.getDetails()); + + throw new CloudRuntimeException("Unable to expunge " + vm + " due to " + answer.getDetails()); + } + } + } + } + + if (hostId != null) { + volumeMgr.disconnectVolumesFromHost(vm.getId(), hostId); + } + // Clean up volumes based on the vm's instance id volumeMgr.cleanupVolumes(vm.getId()); @@ -489,7 +527,6 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac // send hypervisor-dependent commands before removing List finalizeExpungeCommands = hvGuru.finalizeExpunge(vm); if (finalizeExpungeCommands != null && finalizeExpungeCommands.size() > 0) { - Long hostId = vm.getHostId() != null ? vm.getHostId() : vm.getLastHostId(); if (hostId != null) { Commands cmds = new Commands(Command.OnError.Stop); for (Command command : finalizeExpungeCommands) { @@ -520,8 +557,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac @Override public boolean start() { + // TODO, initial delay is hardcoded + _executor.scheduleAtFixedRate(new TransitionTask(), 5000, VmJobStateReportInterval.value(), TimeUnit.SECONDS); _executor.scheduleAtFixedRate(new CleanupTask(), VmOpCleanupInterval.value(), VmOpCleanupInterval.value(), TimeUnit.SECONDS); cancelWorkItems(_nodeId); + + // cleanup left over place holder works + _workJobDao.expungeLeftoverWorkJobs(ManagementServerNode.getManagementServerId()); return true; } @@ -540,6 +582,10 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac _agentMgr.registerForHostEvents(this, true, true, true); + if (VmJobEnabled.value()) { + _messageBus.subscribe(VirtualMachineManager.Topics.VM_POWER_STATE, MessageDispatcher.getDispatcher(this)); + } + return true; } @@ -555,7 +601,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac @Override public void start(String vmUuid, Map params, DeploymentPlan planToDeploy) { try { - advanceStart(vmUuid, params, planToDeploy); + advanceStart(vmUuid, params, planToDeploy, null); } catch (ConcurrentOperationException e) { throw new CloudRuntimeException("Unable to start a VM due to concurrent operation", e).add(VirtualMachine.class, vmUuid); } catch (InsufficientCapacityException e) { @@ -696,20 +742,29 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @Override - public void advanceStart(String vmUuid, Map params) + public void advanceStart(String vmUuid, Map params, DeploymentPlanner planner) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException { - - advanceStart(vmUuid, params, null); + advanceStart(vmUuid, params, null, planner); } @Override - public void advanceStart(String vmUuid, Map params, DeploymentPlan planToDeploy) throws InsufficientCapacityException, + public void advanceStart(String vmUuid, Map params, DeploymentPlan planToDeploy, DeploymentPlanner planner) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException { AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); - if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER)) { + if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) { // avoid re-entrance - orchestrateStart(vmUuid, params, planToDeploy); + VmWorkJobVO placeHolder = null; + if (VmJobEnabled.value()) { + VirtualMachine vm = _vmDao.findByUuid(vmUuid); + placeHolder = createPlaceHolderWork(vm.getId()); + } + try { + orchestrateStart(vmUuid, params, planToDeploy, planner); + } finally { + if (VmJobEnabled.value()) + _workJobDao.expunge(placeHolder.getId()); + } } else { Outcome outcome = startVmThroughJobQueue(vmUuid, params, planToDeploy); @@ -721,19 +776,20 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac throw new RuntimeException("Execution excetion", e); } - Throwable jobException = retriveExecutionException(outcome.getJob()); - if (jobException != null) { - if (jobException instanceof ConcurrentOperationException) - throw (ConcurrentOperationException)jobException; - else if (jobException instanceof ResourceUnavailableException) - throw (ResourceUnavailableException)jobException; + Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); + if (jobResult != null) { + if (jobResult instanceof ConcurrentOperationException) + throw (ConcurrentOperationException)jobResult; + else if (jobResult instanceof ResourceUnavailableException) + throw (ResourceUnavailableException)jobResult; } } } + @Override - public void orchestrateStart(String vmUuid, Map params, DeploymentPlan planToDeploy) throws InsufficientCapacityException, - ConcurrentOperationException, ResourceUnavailableException { + public void orchestrateStart(String vmUuid, Map params, DeploymentPlan planToDeploy, DeploymentPlanner planner) + throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException { CallContext cctxt = CallContext.current(); Account account = cctxt.getCallingAccount(); @@ -847,10 +903,11 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } } - VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vm, template, offering, account, params); + Account owner = _entityMgr.findById(Account.class, vm.getAccountId()); + VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vm, template, offering, owner, params); DeployDestination dest = null; try { - dest = _dpMgr.planDeployment(vmProfile, plan, avoids); + dest = _dpMgr.planDeployment(vmProfile, plan, avoids, planner); } catch (AffinityConflictException e2) { s_logger.warn("Unable to create deployment, affinity rules associted to the VM conflict", e2); throw new CloudRuntimeException("Unable to create deployment, affinity rules associted to the VM conflict"); @@ -964,15 +1021,15 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac s_logger.info("The guru did not like the answers so stopping " + vm); } - StopCommand cmd = new StopCommand(vm, ExecuteInSequence.value()); - StopAnswer answer = (StopAnswer) _agentMgr.easySend(destHostId, cmd); - if ( answer != null ) { + StopCommand cmd = new StopCommand(vm, ExecuteInSequence.value()); + StopAnswer answer = (StopAnswer)_agentMgr.easySend(destHostId, cmd); + if (answer != null) { if (vm.getType() == VirtualMachine.Type.User) { String platform = answer.getPlatform(); if (platform != null) { UserVmVO userVm = _userVmDao.findById(vm.getId()); _userVmDao.loadDetails(userVm); - userVm.setDetail("platform", platform); + userVm.setDetail("platform", platform); _userVmDao.saveDetails(userVm); } } @@ -1068,6 +1125,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac VolumeVO volume = _volsDao.findById(volumeId); disk.setPath(volume.get_iScsiName()); + + if (disk.getData() instanceof VolumeObjectTO) { + VolumeObjectTO volTo = (VolumeObjectTO)disk.getData(); + + volTo.setPath(volume.get_iScsiName()); + } + volume.setPath(volume.get_iScsiName()); _volsDao.update(volumeId, volume); @@ -1078,20 +1142,22 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac // for managed storage on XenServer and VMware, need to update the DB with a path if the VDI/VMDK file was newly created private void handlePath(DiskTO[] disks, Map iqnToPath) { - if (disks != null) { + if (disks != null && iqnToPath != null) { for (DiskTO disk : disks) { Map details = disk.getDetails(); boolean isManaged = details != null && Boolean.parseBoolean(details.get(DiskTO.MANAGED)); - if (isManaged && disk.getPath() == null) { + if (isManaged) { Long volumeId = disk.getData().getId(); VolumeVO volume = _volsDao.findById(volumeId); String iScsiName = volume.get_iScsiName(); String path = iqnToPath.get(iScsiName); - volume.setPath(path); + if (path != null) { + volume.setPath(path); - _volsDao.update(volumeId, volume); + _volsDao.update(volumeId, volume); + } } } } @@ -1128,14 +1194,14 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac VirtualMachine vm = profile.getVirtualMachine(); StopCommand stop = new StopCommand(vm, ExecuteInSequence.value()); try { - StopAnswer answer = (StopAnswer) _agentMgr.send(vm.getHostId(), stop); - if ( answer != null ) { + StopAnswer answer = (StopAnswer)_agentMgr.send(vm.getHostId(), stop); + if (answer != null) { if (vm.getType() == VirtualMachine.Type.User) { String platform = answer.getPlatform(); if (platform != null) { UserVmVO userVm = _userVmDao.findById(vm.getId()); _userVmDao.loadDetails(userVm); - userVm.setDetail("platform", platform); + userVm.setDetail("platform", platform); _userVmDao.saveDetails(userVm); } } @@ -1224,12 +1290,24 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac @Override public void advanceStop(String vmUuid, boolean cleanUpEvenIfUnableToStop) - throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException { + throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException { AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); - if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER)) { + if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) { // avoid re-entrance - orchestrateStop(vmUuid, cleanUpEvenIfUnableToStop); + + VmWorkJobVO placeHolder = null; + if (VmJobEnabled.value()) { + VirtualMachine vm = _vmDao.findByUuid(vmUuid); + placeHolder = createPlaceHolderWork(vm.getId()); + } + try { + orchestrateStop(vmUuid, cleanUpEvenIfUnableToStop); + } finally { + if (VmJobEnabled.value()) + _workJobDao.expunge(placeHolder.getId()); + } + } else { Outcome outcome = stopVmThroughJobQueue(vmUuid, cleanUpEvenIfUnableToStop); @@ -1241,21 +1319,19 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac throw new RuntimeException("Execution excetion", e); } - Throwable jobException = retriveExecutionException(outcome.getJob()); - if (jobException != null) { - if (jobException instanceof AgentUnavailableException) - throw (AgentUnavailableException)jobException; - else if (jobException instanceof ConcurrentOperationException) - throw (ConcurrentOperationException)jobException; - else if (jobException instanceof OperationTimedoutException) - throw (OperationTimedoutException)jobException; + Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); + if (jobResult != null) { + if (jobResult instanceof AgentUnavailableException) + throw (AgentUnavailableException)jobResult; + else if (jobResult instanceof ConcurrentOperationException) + throw (ConcurrentOperationException)jobResult; + else if (jobResult instanceof OperationTimedoutException) + throw (OperationTimedoutException)jobResult; } } } - @Override - public void orchestrateStop(String vmUuid, boolean cleanUpEvenIfUnableToStop) throws AgentUnavailableException, OperationTimedoutException, - ConcurrentOperationException { + private void orchestrateStop(String vmUuid, boolean cleanUpEvenIfUnableToStop) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException { VMInstanceVO vm = _vmDao.findByUuid(vmUuid); advanceStop(vm, cleanUpEvenIfUnableToStop); @@ -1368,13 +1444,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac StopAnswer answer = null; try { answer = (StopAnswer)_agentMgr.send(vm.getHostId(), stop); - if ( answer != null ) { + if (answer != null) { if (vm.getType() == VirtualMachine.Type.User) { String platform = answer.getPlatform(); - if ( platform != null) { + if (platform != null) { UserVmVO userVm = _userVmDao.findById(vm.getId()); _userVmDao.loadDetails(userVm); - userVm.setDetail("platform", platform); + userVm.setDetail("platform", platform); _userVmDao.saveDetails(userVm); } } @@ -1489,13 +1565,15 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac s_logger.debug("Destroying vm " + vm); } - advanceStop(vm, VmDestroyForcestop.value()); + advanceStop(vmUuid, VmDestroyForcestop.value()); if (!_vmSnapshotMgr.deleteAllVMSnapshots(vm.getId(), null)) { s_logger.debug("Unable to delete all snapshots for " + vm); throw new CloudRuntimeException("Unable to delete vm snapshots for " + vm); } + // reload the vm object from db + vm = _vmDao.findByUuid(vmUuid); try { if (!stateTransitTo(vm, VirtualMachine.Event.DestroyRequested, vm.getHostId())) { s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm); @@ -1519,9 +1597,19 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac @Override public void storageMigration(String vmUuid, StoragePool destPool) { AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); - if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER)) { + if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) { // avoid re-entrance - orchestrateStorageMigration(vmUuid, destPool); + VmWorkJobVO placeHolder = null; + if (VmJobEnabled.value()) { + VirtualMachine vm = _vmDao.findByUuid(vmUuid); + placeHolder = createPlaceHolderWork(vm.getId()); + } + try { + orchestrateStorageMigration(vmUuid, destPool); + } finally { + if (VmJobEnabled.value()) + _workJobDao.expunge(placeHolder.getId()); + } } else { Outcome outcome = migrateVmStorageThroughJobQueue(vmUuid, destPool); @@ -1533,16 +1621,15 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac throw new RuntimeException("Execution excetion", e); } - Throwable jobException = retriveExecutionException(outcome.getJob()); - if (jobException != null) { - if (jobException instanceof RuntimeException) - throw (RuntimeException)jobException; + Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); + if (jobResult != null) { + if (jobResult instanceof RuntimeException) + throw (RuntimeException)jobResult; } } } - @Override - public void orchestrateStorageMigration(String vmUuid, StoragePool destPool) { + private void orchestrateStorageMigration(String vmUuid, StoragePool destPool) { VMInstanceVO vm = _vmDao.findByUuid(vmUuid); try { @@ -1599,12 +1686,22 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac @Override public void migrate(String vmUuid, long srcHostId, DeployDestination dest) - throws ResourceUnavailableException, ConcurrentOperationException { + throws ResourceUnavailableException, ConcurrentOperationException { AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); - if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER)) { + if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) { // avoid re-entrance - orchestrateMigrate(vmUuid, srcHostId, dest); + VmWorkJobVO placeHolder = null; + if (VmJobEnabled.value()) { + VirtualMachine vm = _vmDao.findByUuid(vmUuid); + placeHolder = createPlaceHolderWork(vm.getId()); + } + try { + orchestrateMigrate(vmUuid, srcHostId, dest); + } finally { + if (VmJobEnabled.value()) + _workJobDao.expunge(placeHolder.getId()); + } } else { Outcome outcome = migrateVmThroughJobQueue(vmUuid, srcHostId, dest); @@ -1616,20 +1713,19 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac throw new RuntimeException("Execution excetion", e); } - Throwable jobException = retriveExecutionException(outcome.getJob()); - if (jobException != null) { - if (jobException instanceof ResourceUnavailableException) - throw (ResourceUnavailableException)jobException; - else if (jobException instanceof ConcurrentOperationException) - throw (ConcurrentOperationException)jobException; - else if (jobException instanceof RuntimeException) - throw (RuntimeException)jobException; + Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); + if (jobResult != null) { + if (jobResult instanceof ResourceUnavailableException) + throw (ResourceUnavailableException)jobResult; + else if (jobResult instanceof ConcurrentOperationException) + throw (ConcurrentOperationException)jobResult; + else if (jobResult instanceof RuntimeException) + throw (RuntimeException)jobResult; } } } - @Override - public void orchestrateMigrate(String vmUuid, long srcHostId, DeployDestination dest) throws ResourceUnavailableException, ConcurrentOperationException { + private void orchestrateMigrate(String vmUuid, long srcHostId, DeployDestination dest) throws ResourceUnavailableException, ConcurrentOperationException { VMInstanceVO vm = _vmDao.findByUuid(vmUuid); if (vm == null) { if (s_logger.isDebugEnabled()) { @@ -1871,12 +1967,24 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac @Override public void migrateWithStorage(String vmUuid, long srcHostId, long destHostId, Map volumeToPool) - throws ResourceUnavailableException, ConcurrentOperationException { + throws ResourceUnavailableException, ConcurrentOperationException { AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); - if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER)) { + if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) { // avoid re-entrance - orchestrateMigrateWithStorage(vmUuid, srcHostId, destHostId, volumeToPool); + + VmWorkJobVO placeHolder = null; + if (VmJobEnabled.value()) { + VirtualMachine vm = _vmDao.findByUuid(vmUuid); + placeHolder = createPlaceHolderWork(vm.getId()); + } + try { + orchestrateMigrateWithStorage(vmUuid, srcHostId, destHostId, volumeToPool); + } finally { + if (VmJobEnabled.value()) + _workJobDao.expunge(placeHolder.getId()); + } + } else { Outcome outcome = migrateVmWithStorageThroughJobQueue(vmUuid, srcHostId, destHostId, volumeToPool); @@ -1888,7 +1996,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac throw new RuntimeException("Execution excetion", e); } - Throwable jobException = retriveExecutionException(outcome.getJob()); + Object jobException = _jobMgr.unmarshallResultObject(outcome.getJob()); if (jobException != null) { if (jobException instanceof ResourceUnavailableException) throw (ResourceUnavailableException)jobException; @@ -1898,9 +2006,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } } - @Override - public void orchestrateMigrateWithStorage(String vmUuid, long srcHostId, long destHostId, Map volumeToPool) throws ResourceUnavailableException, - ConcurrentOperationException { + private void orchestrateMigrateWithStorage(String vmUuid, long srcHostId, long destHostId, Map volumeToPool) throws ResourceUnavailableException, + ConcurrentOperationException { VMInstanceVO vm = _vmDao.findByUuid(vmUuid); @@ -2038,7 +2145,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @Override - public void migrateAway(String vmUuid, long srcHostId) throws InsufficientServerCapacityException { + public void migrateAway(String vmUuid, long srcHostId, DeploymentPlanner planner) throws InsufficientServerCapacityException { VMInstanceVO vm = _vmDao.findByUuid(vmUuid); if (vm == null) { s_logger.debug("Unable to find a VM for " + vmUuid); @@ -2071,7 +2178,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac while (true) { try { - dest = _dpMgr.planDeployment(profile, plan, excludes); + dest = _dpMgr.planDeployment(profile, plan, excludes, planner); } catch (AffinityConflictException e2) { s_logger.warn("Unable to create deployment, affinity rules associted to the VM conflict", e2); throw new CloudRuntimeException("Unable to create deployment, affinity rules associted to the VM conflict"); @@ -2099,7 +2206,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } try { - advanceStop(vm, true); + advanceStop(vmUuid, true); throw new CloudRuntimeException("Unable to migrate " + vm); } catch (ResourceUnavailableException e) { s_logger.debug("Unable to stop VM due to " + e.getMessage()); @@ -2120,6 +2227,10 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac s_logger.trace("VM Operation Thread Running"); try { _workDao.cleanup(VmOpCleanupWait.value()); + + // TODO. hard-coded to one hour after job has been completed + Date cutDate = new Date(new Date().getTime() - 3600000); + _workJobDao.expungeCompletedWorkJobs(cutDate); } catch (Exception e) { s_logger.error("VM Operations failed due to ", e); } @@ -2129,7 +2240,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac @Override public boolean isVirtualMachineUpgradable(VirtualMachine vm, ServiceOffering offering) { boolean isMachineUpgradable = true; - for (HostAllocator allocator : _hostAllocators) { + for (HostAllocator allocator : hostAllocators) { isMachineUpgradable = allocator.isVirtualMachineUpgradable(vm, offering); if (isMachineUpgradable) continue; @@ -2151,12 +2262,22 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac @Override public void advanceReboot(String vmUuid, Map params) - throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException { + throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException { AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); - if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER)) { + if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) { // avoid re-entrance - orchestrateReboot(vmUuid, params); + VmWorkJobVO placeHolder = null; + if (VmJobEnabled.value()) { + VirtualMachine vm = _vmDao.findByUuid(vmUuid); + placeHolder = createPlaceHolderWork(vm.getId()); + } + try { + orchestrateReboot(vmUuid, params); + } finally { + if (VmJobEnabled.value()) + _workJobDao.expunge(placeHolder.getId()); + } } else { Outcome outcome = rebootVmThroughJobQueue(vmUuid, params); @@ -2168,21 +2289,20 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac throw new RuntimeException("Execution excetion", e); } - Throwable jobException = retriveExecutionException(outcome.getJob()); - if (jobException != null) { - if (jobException instanceof ResourceUnavailableException) - throw (ResourceUnavailableException)jobException; - else if (jobException instanceof ConcurrentOperationException) - throw (ConcurrentOperationException)jobException; - else if (jobException instanceof InsufficientCapacityException) - throw (InsufficientCapacityException)jobException; + Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); + if (jobResult != null) { + if (jobResult instanceof ResourceUnavailableException) + throw (ResourceUnavailableException)jobResult; + else if (jobResult instanceof ConcurrentOperationException) + throw (ConcurrentOperationException)jobResult; + else if (jobResult instanceof InsufficientCapacityException) + throw (InsufficientCapacityException)jobResult; } } } - @Override - public void orchestrateReboot(String vmUuid, Map params) throws InsufficientCapacityException, ConcurrentOperationException, - ResourceUnavailableException { + private void orchestrateReboot(String vmUuid, Map params) throws InsufficientCapacityException, ConcurrentOperationException, + ResourceUnavailableException { VMInstanceVO vm = _vmDao.findByUuid(vmUuid); DataCenter dc = _entityMgr.findById(DataCenter.class, vm.getDataCenterId()); @@ -2570,11 +2690,11 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac vm.getHostId() + "] stopped due to storage failure."); } // track platform info - if( info.platform != null && !info.platform.isEmpty() ) { + if (info.platform != null && !info.platform.isEmpty()) { if (vm.getType() == VirtualMachine.Type.User) { UserVmVO userVm = _userVmDao.findById(vm.getId()); _userVmDao.loadDetails(userVm); - userVm.setDetail("platform", info.platform); + userVm.setDetail("platform", info.platform); _userVmDao.saveDetails(userVm); } } @@ -2658,7 +2778,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac if (agentState == State.Shutdowned) { if (serverState == State.Running || serverState == State.Starting || serverState == State.Stopping) { try { - advanceStop(vm, true); + advanceStop(vm.getUuid(), true); } catch (AgentUnavailableException e) { assert (false) : "How do we hit this with forced on?"; return null; @@ -2708,7 +2828,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac s_logger.warn(e.getMessage()); } } - } else if (serverState == State.Stopping) { + } else if (serverState == State.Stopped) { s_logger.debug("Scheduling a stop command for " + vm); _haMgr.scheduleStop(vm, hostId, WorkType.Stop); } else { @@ -2828,7 +2948,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } } - if (VmJobEnabled.value()) { + if(VmJobEnabled.value()) { if (ping.getHostVmStateReport() != null && ping.getHostVmStateReport().size() > 0) { _syncMgr.processHostVmStatePingReport(agentId, ping.getHostVmStateReport()); } @@ -2939,9 +3059,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac return; } try { - lock.addRef(); - List instances = - _vmDao.findVMInTransition(new Date(new Date().getTime() - (AgentManager.Wait.value() * 1000)), State.Starting, State.Stopping); + scanStalledVMInTransitionStateOnDisconnectedHosts(); + + List instances = _vmDao.findVMInTransition(new Date(new Date().getTime() - (AgentManager.Wait.value() * 1000)), State.Starting, State.Stopping); for (VMInstanceVO instance : instances) { State state = instance.getState(); if (state == State.Stopping) { @@ -2970,9 +3090,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac this.name = name; this.state = state; this.vm = vm; - this.hostUuid = host; + hostUuid = host; this.platform = platform; - + } public AgentVmInfo(String name, VMInstanceVO vm, State state, String host) { @@ -2986,7 +3106,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac public String getHostUuid() { return hostUuid; } - + public String getPlatform() { return platform; } @@ -3073,12 +3193,21 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac @Override public NicProfile addVmToNetwork(VirtualMachine vm, Network network, NicProfile requested) - throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { + throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); - if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER)) { + if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) { // avoid re-entrance - return orchestrateAddVmToNetwork(vm, network, requested); + VmWorkJobVO placeHolder = null; + if (VmJobEnabled.value()) { + placeHolder = createPlaceHolderWork(vm.getId()); + } + try { + return orchestrateAddVmToNetwork(vm, network, requested); + } finally { + if (VmJobEnabled.value()) + _workJobDao.expunge(placeHolder.getId()); + } } else { Outcome outcome = addVmToNetworkThroughJobQueue(vm, network, requested); @@ -3090,32 +3219,26 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac throw new RuntimeException("Execution excetion", e); } - AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, outcome.getJob().getId()); - if (jobVo.getResultCode() == JobInfo.Status.SUCCEEDED.ordinal()) { - - NicProfile nic = (NicProfile)JobSerializerHelper.fromObjectSerializedString(jobVo.getResult()); - return nic; - } else { - Throwable jobException = retriveExecutionException(outcome.getJob()); - if (jobException != null) { - if (jobException instanceof ResourceUnavailableException) - throw (ResourceUnavailableException)jobException; - else if (jobException instanceof ConcurrentOperationException) - throw (ConcurrentOperationException)jobException; - else if (jobException instanceof InsufficientCapacityException) - throw (InsufficientCapacityException)jobException; - else if (jobException instanceof RuntimeException) - throw (RuntimeException)jobException; - } - throw new RuntimeException("Job failed with unhandled exception"); + Object jobException = _jobMgr.unmarshallResultObject(outcome.getJob()); + if (jobException != null) { + if (jobException instanceof ResourceUnavailableException) + throw (ResourceUnavailableException)jobException; + else if (jobException instanceof ConcurrentOperationException) + throw (ConcurrentOperationException)jobException; + else if (jobException instanceof InsufficientCapacityException) + throw (InsufficientCapacityException)jobException; + else if (jobException instanceof RuntimeException) + throw (RuntimeException)jobException; + else if (jobException instanceof Long) + return requested; } + + throw new RuntimeException("Unexpected job execution result"); } } - @Override - public NicProfile orchestrateAddVmToNetwork(VirtualMachine vm, Network network, NicProfile requested) throws ConcurrentOperationException, - ResourceUnavailableException, - InsufficientCapacityException { + private NicProfile orchestrateAddVmToNetwork(VirtualMachine vm, Network network, NicProfile requested) throws ConcurrentOperationException, ResourceUnavailableException, + InsufficientCapacityException { CallContext cctx = CallContext.current(); s_logger.debug("Adding vm " + vm + " to network " + network + "; requested nic profile " + requested); @@ -3182,12 +3305,22 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac @Override public boolean removeNicFromVm(VirtualMachine vm, Nic nic) - throws ConcurrentOperationException, ResourceUnavailableException { + throws ConcurrentOperationException, ResourceUnavailableException { AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); - if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER)) { + if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) { // avoid re-entrance - return orchestrateRemoveNicFromVm(vm, nic); + VmWorkJobVO placeHolder = null; + if (VmJobEnabled.value()) { + placeHolder = createPlaceHolderWork(vm.getId()); + } + try { + return orchestrateRemoveNicFromVm(vm, nic); + } finally { + if (VmJobEnabled.value()) + _workJobDao.expunge(placeHolder.getId()); + } + } else { Outcome outcome = removeNicFromVmThroughJobQueue(vm, nic); @@ -3199,29 +3332,23 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac throw new RuntimeException("Execution excetion", e); } - AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, outcome.getJob().getId()); - - if (jobVo.getResultCode() == JobInfo.Status.SUCCEEDED.ordinal()) { - Boolean result = (Boolean)JobSerializerHelper.fromObjectSerializedString(jobVo.getResult()); - return result; - } else { - Throwable jobException = retriveExecutionException(outcome.getJob()); - if (jobException != null) { - if (jobException instanceof ResourceUnavailableException) - throw (ResourceUnavailableException)jobException; - else if (jobException instanceof ConcurrentOperationException) - throw (ConcurrentOperationException)jobException; - else if (jobException instanceof RuntimeException) - throw (RuntimeException)jobException; - } - - throw new RuntimeException("Job failed with un-handled exception"); + Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); + if (jobResult != null) { + if (jobResult instanceof ResourceUnavailableException) + throw (ResourceUnavailableException)jobResult; + else if (jobResult instanceof ConcurrentOperationException) + throw (ConcurrentOperationException)jobResult; + else if (jobResult instanceof RuntimeException) + throw (RuntimeException)jobResult; + else if (jobResult instanceof Boolean) + return (Boolean)jobResult; } + + throw new RuntimeException("Job failed with un-handled exception"); } } - @Override - public boolean orchestrateRemoveNicFromVm(VirtualMachine vm, Nic nic) throws ConcurrentOperationException, ResourceUnavailableException { + private boolean orchestrateRemoveNicFromVm(VirtualMachine vm, Nic nic) throws ConcurrentOperationException, ResourceUnavailableException { CallContext cctx = CallContext.current(); VMInstanceVO vmVO = _vmDao.findById(vm.getId()); NetworkVO network = _networkDao.findById(nic.getNetworkId()); @@ -3287,9 +3414,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac return orchestrateRemoveVmFromNetwork(vm, network, broadcastUri); } - @Override @DB - public boolean orchestrateRemoveVmFromNetwork(VirtualMachine vm, Network network, URI broadcastUri) throws ConcurrentOperationException, ResourceUnavailableException { + private boolean orchestrateRemoveVmFromNetwork(VirtualMachine vm, Network network, URI broadcastUri) throws ConcurrentOperationException, ResourceUnavailableException { CallContext cctx = CallContext.current(); VMInstanceVO vmVO = _vmDao.findById(vm.getId()); ReservationContext context = new ReservationContextImpl(null, null, cctx.getCallingUser(), cctx.getCallingAccount()); @@ -3399,7 +3525,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac DeployDestination dest = null; try { - dest = _dpMgr.planDeployment(profile, plan, excludes); + dest = _dpMgr.planDeployment(profile, plan, excludes, null); } catch (AffinityConflictException e2) { s_logger.warn("Unable to create deployment, affinity rules associted to the VM conflict", e2); throw new CloudRuntimeException("Unable to create deployment, affinity rules associted to the VM conflict"); @@ -3429,11 +3555,21 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac @Override public void migrateForScale(String vmUuid, long srcHostId, DeployDestination dest, Long oldSvcOfferingId) - throws ResourceUnavailableException, ConcurrentOperationException { + throws ResourceUnavailableException, ConcurrentOperationException { AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); - if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER)) { + if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) { // avoid re-entrance - orchestrateMigrateForScale(vmUuid, srcHostId, dest, oldSvcOfferingId); + VmWorkJobVO placeHolder = null; + if (VmJobEnabled.value()) { + VirtualMachine vm = _vmDao.findByUuid(vmUuid); + placeHolder = createPlaceHolderWork(vm.getId()); + } + try { + orchestrateMigrateForScale(vmUuid, srcHostId, dest, oldSvcOfferingId); + } finally { + if (VmJobEnabled.value()) + _workJobDao.expunge(placeHolder.getId()); + } } else { Outcome outcome = migrateVmForScaleThroughJobQueue(vmUuid, srcHostId, dest, oldSvcOfferingId); @@ -3445,19 +3581,18 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac throw new RuntimeException("Execution excetion", e); } - Throwable jobException = retriveExecutionException(outcome.getJob()); - if (jobException != null) { - if (jobException instanceof ResourceUnavailableException) - throw (ResourceUnavailableException)jobException; - else if (jobException instanceof ConcurrentOperationException) - throw (ConcurrentOperationException)jobException; + Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); + if (jobResult != null) { + if (jobResult instanceof ResourceUnavailableException) + throw (ResourceUnavailableException)jobResult; + else if (jobResult instanceof ConcurrentOperationException) + throw (ConcurrentOperationException)jobResult; } } } - @Override - public void orchestrateMigrateForScale(String vmUuid, long srcHostId, DeployDestination dest, Long oldSvcOfferingId) - throws ResourceUnavailableException, ConcurrentOperationException { + private void orchestrateMigrateForScale(String vmUuid, long srcHostId, DeployDestination dest, Long oldSvcOfferingId) + throws ResourceUnavailableException, ConcurrentOperationException { VMInstanceVO vm = _vmDao.findByUuid(vmUuid); s_logger.info("Migrating " + vm + " to " + dest); @@ -3677,13 +3812,23 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac @Override public VMInstanceVO reConfigureVm(String vmUuid, ServiceOffering oldServiceOffering, - boolean reconfiguringOnExistingHost) - throws ResourceUnavailableException, ConcurrentOperationException { + boolean reconfiguringOnExistingHost) + throws ResourceUnavailableException, InsufficientServerCapacityException, ConcurrentOperationException { AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); - if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER)) { + if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) { // avoid re-entrance - return orchestrateReConfigureVm(vmUuid, oldServiceOffering, reconfiguringOnExistingHost); + VmWorkJobVO placeHolder = null; + if (VmJobEnabled.value()) { + VirtualMachine vm = _vmDao.findByUuid(vmUuid); + placeHolder = createPlaceHolderWork(vm.getId()); + } + try { + return orchestrateReConfigureVm(vmUuid, oldServiceOffering, reconfiguringOnExistingHost); + } finally { + if (VmJobEnabled.value()) + _workJobDao.expunge(placeHolder.getId()); + } } else { Outcome outcome = reconfigureVmThroughJobQueue(vmUuid, oldServiceOffering, reconfiguringOnExistingHost); @@ -3696,27 +3841,26 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac throw new RuntimeException("Execution excetion", e); } - AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, outcome.getJob().getId()); - if (jobVo.getResultCode() == JobInfo.Status.SUCCEEDED.ordinal()) { - return _entityMgr.findById(VMInstanceVO.class, vm.getId()); - } else { - Throwable jobException = retriveExecutionException(outcome.getJob()); - if (jobException != null) { - if (jobException instanceof ResourceUnavailableException) - throw (ResourceUnavailableException)jobException; - else if (jobException instanceof ConcurrentOperationException) - throw (ConcurrentOperationException)jobException; + Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); + if (jobResult != null) { + if (jobResult instanceof ResourceUnavailableException) + throw (ResourceUnavailableException)jobResult; + else if (jobResult instanceof ConcurrentOperationException) + throw (ConcurrentOperationException)jobResult; + else if (jobResult instanceof InsufficientServerCapacityException) + throw (InsufficientServerCapacityException)jobResult; + else if (jobResult instanceof Throwable) { + s_logger.error("Unhandled exception", (Throwable)jobResult); + throw new RuntimeException("Unhandled exception", (Throwable)jobResult); } - - throw new RuntimeException("Failed with un-handled exception"); } + + return (VMInstanceVO)vm; } } - @Override - public VMInstanceVO orchestrateReConfigureVm(String vmUuid, ServiceOffering oldServiceOffering, boolean reconfiguringOnExistingHost) - throws ResourceUnavailableException, - ConcurrentOperationException { + private VMInstanceVO orchestrateReConfigureVm(String vmUuid, ServiceOffering oldServiceOffering, boolean reconfiguringOnExistingHost) throws ResourceUnavailableException, + ConcurrentOperationException { VMInstanceVO vm = _vmDao.findByUuid(vmUuid); long newServiceofferingId = vm.getServiceOfferingId(); @@ -3777,8 +3921,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac @Override public ConfigKey[] getConfigKeys() { - return new ConfigKey[] {ClusterDeltaSyncInterval, StartRetry, VmDestroyForcestop, VmOpCancelInterval, VmOpCleanupInterval, VmOpCleanupWait, VmOpLockStateRetry, - VmOpWaitInterval, ExecuteInSequence, VmJobCheckInterval, VmJobTimeout, VmJobStateReportInterval}; + return new ConfigKey[] {ClusterDeltaSyncInterval, StartRetry, VmDestroyForcestop, VmOpCancelInterval, VmOpCleanupInterval, VmOpCleanupWait, + VmOpLockStateRetry, + VmOpWaitInterval, ExecuteInSequence, VmJobCheckInterval, VmJobTimeout, VmJobStateReportInterval}; } public List getStoragePoolAllocators() { @@ -3795,135 +3940,136 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac // @MessageHandler(topic = Topics.VM_POWER_STATE) - private void HandlePownerStateReport(Object target, String subject, String senderAddress, Object args) { + private void HandlePowerStateReport(String subject, String senderAddress, Object args) { assert (args != null); Long vmId = (Long)args; List pendingWorkJobs = _workJobDao.listPendingWorkJobs( - VirtualMachine.Type.Instance, vmId); + VirtualMachine.Type.Instance, vmId); if (pendingWorkJobs.size() == 0) { // there is no pending operation job VMInstanceVO vm = _vmDao.findById(vmId); if (vm != null) { switch (vm.getPowerState()) { - case PowerOn: - handlePowerOnReportWithNoPendingJobsOnVM(vm); - break; + case PowerOn: + handlePowerOnReportWithNoPendingJobsOnVM(vm); + break; - case PowerOff: - handlePowerOffReportWithNoPendingJobsOnVM(vm); - break; + case PowerOff: + handlePowerOffReportWithNoPendingJobsOnVM(vm); + break; - // PowerUnknown shouldn't be reported, it is a derived - // VM power state from host state (host un-reachable - case PowerUnknown: - default: - assert (false); - break; + // PowerUnknown shouldn't be reported, it is a derived + // VM power state from host state (host un-reachable) + case PowerUnknown: + default: + assert (false); + break; } } else { s_logger.warn("VM " + vmId + " no longer exists when processing VM state report"); } } else { - // TODO, do job wake-up signalling, since currently async job wake-up is not in use - // we will skip it for nows + // reset VM power state tracking so that we won't lost signal when VM has + // been translated to + _vmDao.resetVmPowerStateTracking(vmId); } } private void handlePowerOnReportWithNoPendingJobsOnVM(VMInstanceVO vm) { // - // 1) handle left-over transitional VM states - // 2) handle out of band VM live migration - // 3) handle out of sync stationary states, marking VM from Stopped to Running with - // alert messages + // 1) handle left-over transitional VM states + // 2) handle out of band VM live migration + // 3) handle out of sync stationary states, marking VM from Stopped to Running with + // alert messages // switch (vm.getState()) { - case Starting: - try { - stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOnReport, vm.getPowerHostId()); - } catch (NoTransitionException e) { - s_logger.warn("Unexpected VM state transition exception, race-condition?", e); - } + case Starting: + try { + stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOnReport, vm.getPowerHostId()); + } catch (NoTransitionException e) { + s_logger.warn("Unexpected VM state transition exception, race-condition?", e); + } - // we need to alert admin or user about this risky state transition - _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(), - VM_SYNC_ALERT_SUBJECT, "VM " + vm.getHostName() + "(" + vm.getInstanceName() + - ") state is sync-ed (Starting -> Running) from out-of-context transition. VM network environment may need to be reset"); - break; + // we need to alert admin or user about this risky state transition + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(), + VM_SYNC_ALERT_SUBJECT, "VM " + vm.getHostName() + "(" + vm.getInstanceName() + + ") state is sync-ed (Starting -> Running) from out-of-context transition. VM network environment may need to be reset"); + break; - case Running: - try { - if (vm.getHostId() != null && vm.getHostId().longValue() != vm.getPowerHostId().longValue()) - s_logger.info("Detected out of band VM migration from host " + vm.getHostId() + " to host " + vm.getPowerHostId()); - stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOnReport, vm.getPowerHostId()); - } catch (NoTransitionException e) { - s_logger.warn("Unexpected VM state transition exception, race-condition?", e); - } - break; + case Running: + try { + if (vm.getHostId() != null && vm.getHostId().longValue() != vm.getPowerHostId().longValue()) + s_logger.info("Detected out of band VM migration from host " + vm.getHostId() + " to host " + vm.getPowerHostId()); + stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOnReport, vm.getPowerHostId()); + } catch (NoTransitionException e) { + s_logger.warn("Unexpected VM state transition exception, race-condition?", e); + } + break; - case Stopping: - case Stopped: - try { - stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOnReport, vm.getPowerHostId()); - } catch (NoTransitionException e) { - s_logger.warn("Unexpected VM state transition exception, race-condition?", e); - } - _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(), - VM_SYNC_ALERT_SUBJECT, "VM " + vm.getHostName() + "(" + vm.getInstanceName() + ") state is sync-ed (" + vm.getState() + - " -> Running) from out-of-context transition. VM network environment may need to be reset"); - break; + case Stopping: + case Stopped: + try { + stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOnReport, vm.getPowerHostId()); + } catch (NoTransitionException e) { + s_logger.warn("Unexpected VM state transition exception, race-condition?", e); + } + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(), + VM_SYNC_ALERT_SUBJECT, "VM " + vm.getHostName() + "(" + vm.getInstanceName() + ") state is sync-ed (" + vm.getState() + + " -> Running) from out-of-context transition. VM network environment may need to be reset"); + break; - case Destroyed: - case Expunging: - s_logger.info("Receive power on report when VM is in destroyed or expunging state. vm: " + case Destroyed: + case Expunging: + s_logger.info("Receive power on report when VM is in destroyed or expunging state. vm: " + vm.getId() + ", state: " + vm.getState()); - break; + break; - case Migrating: - try { - stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOnReport, vm.getPowerHostId()); - } catch (NoTransitionException e) { - s_logger.warn("Unexpected VM state transition exception, race-condition?", e); - } - break; + case Migrating: + try { + stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOnReport, vm.getPowerHostId()); + } catch (NoTransitionException e) { + s_logger.warn("Unexpected VM state transition exception, race-condition?", e); + } + break; - case Error: - default: - s_logger.info("Receive power on report when VM is in error or unexpected state. vm: " + case Error: + default: + s_logger.info("Receive power on report when VM is in error or unexpected state. vm: " + vm.getId() + ", state: " + vm.getState()); - break; + break; } } private void handlePowerOffReportWithNoPendingJobsOnVM(VMInstanceVO vm) { - // 1) handle left-over transitional VM states - // 2) handle out of sync stationary states, schedule force-stop to release resources + // 1) handle left-over transitional VM states + // 2) handle out of sync stationary states, schedule force-stop to release resources // switch (vm.getState()) { - case Starting: - case Stopping: - case Stopped: - case Migrating: - try { - stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOffReport, vm.getPowerHostId()); - } catch (NoTransitionException e) { - s_logger.warn("Unexpected VM state transition exception, race-condition?", e); - } - _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(), - VM_SYNC_ALERT_SUBJECT, "VM " + vm.getHostName() + "(" + vm.getInstanceName() + ") state is sync-ed (" + vm.getState() + - " -> Stopped) from out-of-context transition."); - // TODO: we need to forcely release all resource allocation - break; + case Starting: + case Stopping: + case Running: + case Stopped: + case Migrating: + try { + stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOffReport, vm.getPowerHostId()); + } catch (NoTransitionException e) { + s_logger.warn("Unexpected VM state transition exception, race-condition?", e); + } + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(), + VM_SYNC_ALERT_SUBJECT, "VM " + vm.getHostName() + "(" + vm.getInstanceName() + ") state is sync-ed (" + vm.getState() + + " -> Stopped) from out-of-context transition."); + // TODO: we need to forcely release all resource allocation + break; - case Running: - case Destroyed: - case Expunging: - break; + case Destroyed: + case Expunging: + break; - case Error: - default: - break; + case Error: + default: + break; } } @@ -3933,8 +4079,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac // VMs in expunging state (this need to be handled specially) // // checking condition - // 1) no pending VmWork job - // 2) on hostId host and host is UP + // 1) no pending VmWork job + // 2) on hostId host and host is UP // // When host is UP, soon or later we will get a report from the host about the VM, // however, if VM is missing from the host report (it may happen in out of band changes @@ -3972,17 +4118,17 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac // We now only alert administrator about this situation _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(), - VM_SYNC_ALERT_SUBJECT, "VM " + vm.getHostName() + "(" + vm.getInstanceName() + ") is stuck in " + vm.getState() + - " state and its host is unreachable for too long"); + VM_SYNC_ALERT_SUBJECT, "VM " + vm.getHostName() + "(" + vm.getInstanceName() + ") is stuck in " + vm.getState() + + " state and its host is unreachable for too long"); } } // VMs that in transitional state without recent power state report private List listStalledVMInTransitionStateOnUpHost(long hostId, Date cutTime) { String sql = "SELECT i.* FROM vm_instance as i, host as h WHERE h.status = 'UP' " + - "AND h.id = ? AND i.power_state_update_time < ? AND i.host_id = h.id " + - "AND (i.state ='Starting' OR i.state='Stopping' OR i.state='Migrating') " + - "AND i.id NOT IN (SELECT w.vm_instance_id FROM vm_work_job AS w JOIN async_job AS j ON w.id = j.id WHERE j.job_status = ?)"; + "AND h.id = ? AND i.power_state_update_time < ? AND i.host_id = h.id " + + "AND (i.state ='Starting' OR i.state='Stopping' OR i.state='Migrating') " + + "AND i.id NOT IN (SELECT w.vm_instance_id FROM vm_work_job AS w JOIN async_job AS j ON w.id = j.id WHERE j.job_status = ?)"; List l = new ArrayList(); TransactionLegacy txn = null; @@ -4014,9 +4160,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac // VMs that in transitional state and recently have power state update private List listVMInTransitionStateWithRecentReportOnUpHost(long hostId, Date cutTime) { String sql = "SELECT i.* FROM vm_instance as i, host as h WHERE h.status = 'UP' " + - "AND h.id = ? AND i.power_state_update_time > ? AND i.host_id = h.id " + - "AND (i.state ='Starting' OR i.state='Stopping' OR i.state='Migrating') " + - "AND i.id NOT IN (SELECT w.vm_instance_id FROM vm_work_job AS w JOIN async_job AS j ON w.id = j.id WHERE j.job_status = ?)"; + "AND h.id = ? AND i.power_state_update_time > ? AND i.host_id = h.id " + + "AND (i.state ='Starting' OR i.state='Stopping' OR i.state='Migrating') " + + "AND i.id NOT IN (SELECT w.vm_instance_id FROM vm_work_job AS w JOIN async_job AS j ON w.id = j.id WHERE j.job_status = ?)"; List l = new ArrayList(); TransactionLegacy txn = null; @@ -4045,9 +4191,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac private List listStalledVMInTransitionStateOnDisconnectedHosts(Date cutTime) { String sql = "SELECT i.* FROM vm_instance as i, host as h WHERE h.status != 'UP' " + - "AND i.power_state_update_time < ? AND i.host_id = h.id " + - "AND (i.state ='Starting' OR i.state='Stopping' OR i.state='Migrating') " + - "AND i.id NOT IN (SELECT w.vm_instance_id FROM vm_work_job AS w JOIN async_job AS j ON w.id = j.id WHERE j.job_status = ?)"; + "AND i.power_state_update_time < ? AND i.host_id = h.id " + + "AND (i.state ='Starting' OR i.state='Stopping' OR i.state='Migrating') " + + "AND i.id NOT IN (SELECT w.vm_instance_id FROM vm_work_job AS w JOIN async_job AS j ON w.id = j.id WHERE j.job_status = ?)"; List l = new ArrayList(); TransactionLegacy txn = null; @@ -4099,10 +4245,10 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } } - public class VmJobSyncOutcome extends OutcomeImpl { + public class VmJobVirtualMachineOutcome extends OutcomeImpl { private long _vmId; - public VmJobSyncOutcome(final AsyncJob job, final long vmId) { + public VmJobVirtualMachineOutcome(final AsyncJob job, final long vmId) { super(VirtualMachine.class, job, VmJobCheckInterval.value(), new Predicate() { @Override public boolean checkCondition() { @@ -4123,77 +4269,63 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } } - public Throwable retriveExecutionException(AsyncJob job) { - assert (job != null); - assert (job.getDispatcher().equals(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER)); - - AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, job.getId()); - if (jobVo != null && jobVo.getResult() != null) { - Object obj = JobSerializerHelper.fromSerializedString(job.getResult()); - - if (obj != null && obj instanceof Throwable) - return (Throwable)obj; - } - return null; - } - // // TODO build a common pattern to reduce code duplication in following methods // no time for this at current iteration // - public Outcome startVmThroughJobQueue(final String vmUuid, - final Map params, - final DeploymentPlan planToDeploy) { - - final CallContext context = CallContext.current(); + public Outcome startVmThroughJobQueue(final String vmUuid, + final Map params, + final DeploymentPlan planToDeploy) { + + final CallContext context = CallContext.current(); final User callingUser = context.getCallingUser(); final Account callingAccount = context.getCallingAccount(); final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); - Transaction.execute(new TransactionCallbackNoReturn () { - public void doInTransactionWithoutResult(TransactionStatus status) { - VmWorkJobVO workJob = null; - - _vmDao.lockRow(vm.getId(), true); - List pendingWorkJobs = _workJobDao.listPendingWorkJobs(VirtualMachine.Type.Instance, - vm.getId(), VmWorkStart.class.getName()); - - if (pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); - workJob = pendingWorkJobs.get(0); - } else { - workJob = new VmWorkJobVO(context.getContextId()); + Object[] result = Transaction.execute(new TransactionCallback() { + @Override + public Object[] doInTransaction(TransactionStatus status) { + VmWorkJobVO workJob = null; - workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); - workJob.setCmd(VmWorkStart.class.getName()); + _vmDao.lockRow(vm.getId(), true); + List pendingWorkJobs = _workJobDao.listPendingWorkJobs(VirtualMachine.Type.Instance, + vm.getId(), VmWorkStart.class.getName()); - workJob.setAccountId(callingAccount.getId()); - workJob.setUserId(callingUser.getId()); - workJob.setStep(VmWorkJobVO.Step.Starting); - workJob.setVmType(vm.getType()); - workJob.setVmInstanceId(vm.getId()); + if (pendingWorkJobs.size() > 0) { + assert (pendingWorkJobs.size() == 1); + workJob = pendingWorkJobs.get(0); + } else { + workJob = new VmWorkJobVO(context.getContextId()); - // save work context info (there are some duplications) - VmWorkStart workInfo = new VmWorkStart(callingUser.getId(), callingAccount.getId(), vm.getId()); - workInfo.setPlan(planToDeploy); - workInfo.setParams(params); - workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkStart.class.getName()); - _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); - } - - // Transaction syntax sugar has a cost here - context.putContextParameter("workJob", workJob); - context.putContextParameter("jobId", new Long(workJob.getId())); - } - }); - - final long jobId = (Long)context.getContextParameter("jobId"); - AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); - - return new VmStateSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), - VirtualMachine.PowerState.PowerOn, vm.getId(), null); + workJob.setAccountId(callingAccount.getId()); + workJob.setUserId(callingUser.getId()); + workJob.setStep(VmWorkJobVO.Step.Starting); + workJob.setVmType(VirtualMachine.Type.Instance); + workJob.setVmInstanceId(vm.getId()); + workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId()); + + // save work context info (there are some duplications) + VmWorkStart workInfo = new VmWorkStart(callingUser.getId(), callingAccount.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER); + workInfo.setPlan(planToDeploy); + workInfo.setParams(params); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + + _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId()); + } + + return new Object[] {workJob, workJob.getId()}; + } + }); + + final long jobId = (Long)result[1]; + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + + return new VmStateSyncOutcome((VmWorkJobVO)result[0], + VirtualMachine.PowerState.PowerOn, vm.getId(), null); } public Outcome stopVmThroughJobQueue(final String vmUuid, final boolean cleanup) { @@ -4202,100 +4334,102 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac final User user = context.getCallingUser(); final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); - - Transaction.execute(new TransactionCallbackNoReturn () { - public void doInTransactionWithoutResult(TransactionStatus status) { - _vmDao.lockRow(vm.getId(), true); - - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( - VirtualMachine.Type.Instance, vm.getId(), - VmWorkStop.class.getName()); - - VmWorkJobVO workJob = null; - if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); - workJob = pendingWorkJobs.get(0); - } else { - workJob = new VmWorkJobVO(context.getContextId()); - - workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); - workJob.setCmd(VmWorkStop.class.getName()); - - workJob.setAccountId(account.getId()); - workJob.setUserId(user.getId()); - workJob.setStep(VmWorkJobVO.Step.Prepare); - workJob.setVmType(vm.getType()); - workJob.setVmInstanceId(vm.getId()); - - // save work context info (there are some duplications) - VmWorkStop workInfo = new VmWorkStop(user.getId(), account.getId(), vm.getId(), cleanup); - workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); - - _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); - } - - context.putContextParameter("workJob", workJob); - context.putContextParameter("jobId", new Long(workJob.getId())); - } - }); - final long jobId = (Long)context.getContextParameter("jobId"); - AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); - - return new VmStateSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), - VirtualMachine.PowerState.PowerOff, vm.getId(), null); + Object[] result = Transaction.execute(new TransactionCallback() { + @Override + public Object[] doInTransaction(TransactionStatus status) { + _vmDao.lockRow(vm.getId(), true); + + List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + vm.getType(), vm.getId(), + VmWorkStop.class.getName()); + + VmWorkJobVO workJob = null; + if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { + assert (pendingWorkJobs.size() == 1); + workJob = pendingWorkJobs.get(0); + } else { + workJob = new VmWorkJobVO(context.getContextId()); + + workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkStop.class.getName()); + + workJob.setAccountId(account.getId()); + workJob.setUserId(user.getId()); + workJob.setStep(VmWorkJobVO.Step.Prepare); + workJob.setVmType(VirtualMachine.Type.Instance); + workJob.setVmInstanceId(vm.getId()); + workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId()); + + // save work context info (there are some duplications) + VmWorkStop workInfo = new VmWorkStop(user.getId(), account.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, cleanup); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + + _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId()); + } + + return new Object[] {workJob, workJob.getId()}; + } + }); + + final long jobId = (Long)result[1]; + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + + return new VmStateSyncOutcome((VmWorkJobVO)result[0], + VirtualMachine.PowerState.PowerOff, vm.getId(), null); } public Outcome rebootVmThroughJobQueue(final String vmUuid, - final Map params) { + final Map params) { final CallContext context = CallContext.current(); final Account account = context.getCallingAccount(); final User user = context.getCallingUser(); final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); - - Transaction.execute(new TransactionCallbackNoReturn () { - public void doInTransactionWithoutResult(TransactionStatus status) { - _vmDao.lockRow(vm.getId(), true); - - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( - VirtualMachine.Type.Instance, vm.getId(), - VmWorkReboot.class.getName()); - - VmWorkJobVO workJob = null; - if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); - workJob = pendingWorkJobs.get(0); - } else { - workJob = new VmWorkJobVO(context.getContextId()); - - workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); - workJob.setCmd(VmWorkReboot.class.getName()); - - workJob.setAccountId(account.getId()); - workJob.setUserId(user.getId()); - workJob.setStep(VmWorkJobVO.Step.Prepare); - workJob.setVmType(vm.getType()); - workJob.setVmInstanceId(vm.getId()); - - // save work context info (there are some duplications) - VmWorkReboot workInfo = new VmWorkReboot(user.getId(), account.getId(), vm.getId(), params); - workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); - - _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); - } - - context.putContextParameter("workJob", workJob); - context.putContextParameter("jobId", new Long(workJob.getId())); - } - }); - final long jobId = (Long)context.getContextParameter("jobId"); - AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); - - return new VmJobSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), - vm.getId()); + Object[] result = Transaction.execute(new TransactionCallback() { + @Override + public Object[] doInTransaction(TransactionStatus status) { + _vmDao.lockRow(vm.getId(), true); + + List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + VirtualMachine.Type.Instance, vm.getId(), + VmWorkReboot.class.getName()); + + VmWorkJobVO workJob = null; + if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { + assert (pendingWorkJobs.size() == 1); + workJob = pendingWorkJobs.get(0); + } else { + workJob = new VmWorkJobVO(context.getContextId()); + + workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkReboot.class.getName()); + + workJob.setAccountId(account.getId()); + workJob.setUserId(user.getId()); + workJob.setStep(VmWorkJobVO.Step.Prepare); + workJob.setVmType(VirtualMachine.Type.Instance); + workJob.setVmInstanceId(vm.getId()); + workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId()); + + // save work context info (there are some duplications) + VmWorkReboot workInfo = new VmWorkReboot(user.getId(), account.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, params); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + + _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId()); + } + + return new Object[] {workJob, workJob.getId()}; + } + }); + + final long jobId = (Long)result[1]; + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + + return new VmJobVirtualMachineOutcome((VmWorkJobVO)result[0], + vm.getId()); } public Outcome migrateVmThroughJobQueue(final String vmUuid, final long srcHostId, final DeployDestination dest) { @@ -4305,52 +4439,51 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); - Transaction.execute(new TransactionCallbackNoReturn () { - public void doInTransactionWithoutResult(TransactionStatus status) { - - _vmDao.lockRow(vm.getId(), true); - - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( - VirtualMachine.Type.Instance, vm.getId(), - VmWorkMigrate.class.getName()); - - VmWorkJobVO workJob = null; - if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); - workJob = pendingWorkJobs.get(0); - } else { - - workJob = new VmWorkJobVO(context.getContextId()); - - workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); - workJob.setCmd(VmWorkMigrate.class.getName()); - - workJob.setAccountId(account.getId()); - workJob.setUserId(user.getId()); - workJob.setVmType(vm.getType()); - workJob.setVmInstanceId(vm.getId()); - - // save work context info (there are some duplications) - VmWorkMigrate workInfo = new VmWorkMigrate(user.getId(), account.getId(), vm.getId(), srcHostId, dest); - workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); - - _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); - } - context.putContextParameter("workJob", workJob); - context.putContextParameter("jobId", new Long(workJob.getId())); - } - }); - - final long jobId = (Long)context.getContextParameter("jobId"); - AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); - - return new VmStateSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), - VirtualMachine.PowerState.PowerOn, vm.getId(), vm.getPowerHostId()); + Object[] result = Transaction.execute(new TransactionCallback() { + @Override + public Object[] doInTransaction(TransactionStatus status) { + + List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + VirtualMachine.Type.Instance, vm.getId(), + VmWorkMigrate.class.getName()); + + VmWorkJobVO workJob = null; + if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { + assert (pendingWorkJobs.size() == 1); + workJob = pendingWorkJobs.get(0); + } else { + + workJob = new VmWorkJobVO(context.getContextId()); + + workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkMigrate.class.getName()); + + workJob.setAccountId(account.getId()); + workJob.setUserId(user.getId()); + workJob.setVmType(VirtualMachine.Type.Instance); + workJob.setVmInstanceId(vm.getId()); + workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId()); + + // save work context info (there are some duplications) + VmWorkMigrate workInfo = new VmWorkMigrate(user.getId(), account.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, srcHostId, dest); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + + _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId()); + } + return new Object[] {workJob, workJob.getId()}; + } + }); + + final long jobId = (Long)result[1]; + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + + return new VmStateSyncOutcome((VmWorkJobVO)result[0], + VirtualMachine.PowerState.PowerOn, vm.getId(), vm.getPowerHostId()); } public Outcome migrateVmWithStorageThroughJobQueue( - final String vmUuid, final long srcHostId, final long destHostId, - final Map volumeToPool) { + final String vmUuid, final long srcHostId, final long destHostId, + final Map volumeToPool) { final CallContext context = CallContext.current(); final User user = context.getCallingUser(); @@ -4358,52 +4491,53 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); - Transaction.execute(new TransactionCallbackNoReturn () { - public void doInTransactionWithoutResult(TransactionStatus status) { - - _vmDao.lockRow(vm.getId(), true); - - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( - VirtualMachine.Type.Instance, vm.getId(), - VmWorkMigrateWithStorage.class.getName()); - - VmWorkJobVO workJob = null; - if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); - workJob = pendingWorkJobs.get(0); - } else { - - workJob = new VmWorkJobVO(context.getContextId()); - - workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); - workJob.setCmd(VmWorkMigrate.class.getName()); - - workJob.setAccountId(account.getId()); - workJob.setUserId(user.getId()); - workJob.setVmType(vm.getType()); - workJob.setVmInstanceId(vm.getId()); - - // save work context info (there are some duplications) - VmWorkMigrateWithStorage workInfo = new VmWorkMigrateWithStorage(user.getId(), account.getId(), vm.getId(), - srcHostId, destHostId, volumeToPool); - workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); - - _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); - } - context.putContextParameter("workJob", workJob); - context.putContextParameter("jobId", new Long(workJob.getId())); - } - }); - - final long jobId = (Long)context.getContextParameter("jobId"); - AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); - - return new VmStateSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), - VirtualMachine.PowerState.PowerOn, vm.getId(), destHostId); + Object[] result = Transaction.execute(new TransactionCallback() { + @Override + public Object[] doInTransaction(TransactionStatus status) { + + _vmDao.lockRow(vm.getId(), true); + + List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + VirtualMachine.Type.Instance, vm.getId(), + VmWorkMigrateWithStorage.class.getName()); + + VmWorkJobVO workJob = null; + if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { + assert (pendingWorkJobs.size() == 1); + workJob = pendingWorkJobs.get(0); + } else { + + workJob = new VmWorkJobVO(context.getContextId()); + + workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkMigrate.class.getName()); + + workJob.setAccountId(account.getId()); + workJob.setUserId(user.getId()); + workJob.setVmType(VirtualMachine.Type.Instance); + workJob.setVmInstanceId(vm.getId()); + workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId()); + + // save work context info (there are some duplications) + VmWorkMigrateWithStorage workInfo = new VmWorkMigrateWithStorage(user.getId(), account.getId(), vm.getId(), + VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, srcHostId, destHostId, volumeToPool); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + + _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId()); + } + return new Object[] {workJob, workJob.getId()}; + } + }); + + final long jobId = (Long)result[1]; + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + + return new VmStateSyncOutcome((VmWorkJobVO)result[0], + VirtualMachine.PowerState.PowerOn, vm.getId(), destHostId); } - + public Outcome migrateVmForScaleThroughJobQueue( - final String vmUuid, final long srcHostId, final DeployDestination dest, final Long newSvcOfferingId) { + final String vmUuid, final long srcHostId, final DeployDestination dest, final Long newSvcOfferingId) { final CallContext context = CallContext.current(); final User user = context.getCallingUser(); @@ -4411,51 +4545,51 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); - Transaction.execute(new TransactionCallbackNoReturn () { - public void doInTransactionWithoutResult(TransactionStatus status) { - - _vmDao.lockRow(vm.getId(), true); - - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( - VirtualMachine.Type.Instance, vm.getId(), - VmWorkMigrateForScale.class.getName()); - - VmWorkJobVO workJob = null; - if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); - workJob = pendingWorkJobs.get(0); - } else { - - workJob = new VmWorkJobVO(context.getContextId()); - - workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); - workJob.setCmd(VmWorkMigrate.class.getName()); - - workJob.setAccountId(account.getId()); - workJob.setUserId(user.getId()); - workJob.setVmType(vm.getType()); - workJob.setVmInstanceId(vm.getId()); - - // save work context info (there are some duplications) - VmWorkMigrateForScale workInfo = new VmWorkMigrateForScale(user.getId(), account.getId(), vm.getId(), - srcHostId, dest, newSvcOfferingId); - workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); - - _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); - } - context.putContextParameter("workJob", workJob); - context.putContextParameter("jobId", new Long(workJob.getId())); - } - }); - - final long jobId = (Long)context.getContextParameter("jobId"); - AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); - - return new VmJobSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), vm.getId()); + Object[] result = Transaction.execute(new TransactionCallback() { + @Override + public Object[] doInTransaction(TransactionStatus status) { + + List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + VirtualMachine.Type.Instance, vm.getId(), + VmWorkMigrateForScale.class.getName()); + + VmWorkJobVO workJob = null; + if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { + assert (pendingWorkJobs.size() == 1); + workJob = pendingWorkJobs.get(0); + } else { + + workJob = new VmWorkJobVO(context.getContextId()); + + workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkMigrate.class.getName()); + + workJob.setAccountId(account.getId()); + workJob.setUserId(user.getId()); + workJob.setVmType(VirtualMachine.Type.Instance); + workJob.setVmInstanceId(vm.getId()); + workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId()); + + // save work context info (there are some duplications) + VmWorkMigrateForScale workInfo = new VmWorkMigrateForScale(user.getId(), account.getId(), vm.getId(), + VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, srcHostId, dest, newSvcOfferingId); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + + _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId()); + } + + return new Object[] {workJob, workJob.getId()}; + } + }); + + final long jobId = (Long)result[1]; + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + + return new VmJobVirtualMachineOutcome((VmWorkJobVO)result[0], vm.getId()); } public Outcome migrateVmStorageThroughJobQueue( - final String vmUuid, final StoragePool destPool) { + final String vmUuid, final StoragePool destPool) { final CallContext context = CallContext.current(); final User user = context.getCallingUser(); @@ -4463,201 +4597,198 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); - Transaction.execute(new TransactionCallbackNoReturn () { - public void doInTransactionWithoutResult(TransactionStatus status) { - - _vmDao.lockRow(vm.getId(), true); - - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( - VirtualMachine.Type.Instance, vm.getId(), - VmWorkStorageMigration.class.getName()); - - VmWorkJobVO workJob = null; - if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); - workJob = pendingWorkJobs.get(0); - } else { - - workJob = new VmWorkJobVO(context.getContextId()); - - workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); - workJob.setCmd(VmWorkStorageMigration.class.getName()); - - workJob.setAccountId(account.getId()); - workJob.setUserId(user.getId()); - workJob.setVmType(vm.getType()); - workJob.setVmInstanceId(vm.getId()); - - // save work context info (there are some duplications) - VmWorkStorageMigration workInfo = new VmWorkStorageMigration(user.getId(), account.getId(), vm.getId(), - destPool); - workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); - - _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); - } - context.putContextParameter("workJob", workJob); - context.putContextParameter("jobId", new Long(workJob.getId())); - } - }); - - final long jobId = (Long)context.getContextParameter("jobId"); - AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); - - return new VmJobSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), vm.getId()); + Object[] result = Transaction.execute(new TransactionCallback() { + @Override + public Object[] doInTransaction(TransactionStatus status) { + + List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + VirtualMachine.Type.Instance, vm.getId(), + VmWorkStorageMigration.class.getName()); + + VmWorkJobVO workJob = null; + if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { + assert (pendingWorkJobs.size() == 1); + workJob = pendingWorkJobs.get(0); + } else { + + workJob = new VmWorkJobVO(context.getContextId()); + + workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkStorageMigration.class.getName()); + + workJob.setAccountId(account.getId()); + workJob.setUserId(user.getId()); + workJob.setVmType(VirtualMachine.Type.Instance); + workJob.setVmInstanceId(vm.getId()); + workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId()); + + // save work context info (there are some duplications) + VmWorkStorageMigration workInfo = new VmWorkStorageMigration(user.getId(), account.getId(), vm.getId(), + VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, destPool); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + + _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId()); + } + + return new Object[] {workJob, workJob.getId()}; + } + }); + + final long jobId = (Long)result[1]; + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + + return new VmJobVirtualMachineOutcome((VmWorkJobVO)result[0], vm.getId()); } public Outcome addVmToNetworkThroughJobQueue( - final VirtualMachine vm, final Network network, final NicProfile requested) { + final VirtualMachine vm, final Network network, final NicProfile requested) { final CallContext context = CallContext.current(); final User user = context.getCallingUser(); final Account account = context.getCallingAccount(); - Transaction.execute(new TransactionCallbackNoReturn () { - public void doInTransactionWithoutResult(TransactionStatus status) { - - _vmDao.lockRow(vm.getId(), true); - - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( - VirtualMachine.Type.Instance, vm.getId(), - VmWorkAddVmToNetwork.class.getName()); - - VmWorkJobVO workJob = null; - if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); - workJob = pendingWorkJobs.get(0); - } else { - - workJob = new VmWorkJobVO(context.getContextId()); - - workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); - workJob.setCmd(VmWorkAddVmToNetwork.class.getName()); - - workJob.setAccountId(account.getId()); - workJob.setUserId(user.getId()); - workJob.setVmType(vm.getType()); - workJob.setVmInstanceId(vm.getId()); - - // save work context info (there are some duplications) - VmWorkAddVmToNetwork workInfo = new VmWorkAddVmToNetwork(user.getId(), account.getId(), vm.getId(), - network, requested); - workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); - - _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); - } - context.putContextParameter("workJob", workJob); - context.putContextParameter("jobId", new Long(workJob.getId())); - } - }); - - final long jobId = (Long)context.getContextParameter("jobId"); - AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); - - return new VmJobSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), vm.getId()); + Object[] result = Transaction.execute(new TransactionCallback() { + @Override + public Object[] doInTransaction(TransactionStatus status) { + + List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + VirtualMachine.Type.Instance, vm.getId(), + VmWorkAddVmToNetwork.class.getName()); + + VmWorkJobVO workJob = null; + if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { + assert (pendingWorkJobs.size() == 1); + workJob = pendingWorkJobs.get(0); + } else { + + workJob = new VmWorkJobVO(context.getContextId()); + + workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkAddVmToNetwork.class.getName()); + + workJob.setAccountId(account.getId()); + workJob.setUserId(user.getId()); + workJob.setVmType(VirtualMachine.Type.Instance); + workJob.setVmInstanceId(vm.getId()); + workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId()); + + // save work context info (there are some duplications) + VmWorkAddVmToNetwork workInfo = new VmWorkAddVmToNetwork(user.getId(), account.getId(), vm.getId(), + VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, network.getId(), requested); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + + _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId()); + } + return new Object[] {workJob, workJob.getId()}; + } + }); + + final long jobId = (Long)result[1]; + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + + return new VmJobVirtualMachineOutcome((VmWorkJobVO)result[0], vm.getId()); } public Outcome removeNicFromVmThroughJobQueue( - final VirtualMachine vm, final Nic nic) { + final VirtualMachine vm, final Nic nic) { final CallContext context = CallContext.current(); final User user = context.getCallingUser(); final Account account = context.getCallingAccount(); - Transaction.execute(new TransactionCallbackNoReturn () { - public void doInTransactionWithoutResult(TransactionStatus status) { - - _vmDao.lockRow(vm.getId(), true); - - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( - VirtualMachine.Type.Instance, vm.getId(), - VmWorkRemoveNicFromVm.class.getName()); - - VmWorkJobVO workJob = null; - if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); - workJob = pendingWorkJobs.get(0); - } else { - - workJob = new VmWorkJobVO(context.getContextId()); - - workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); - workJob.setCmd(VmWorkRemoveNicFromVm.class.getName()); - - workJob.setAccountId(account.getId()); - workJob.setUserId(user.getId()); - workJob.setVmType(vm.getType()); - workJob.setVmInstanceId(vm.getId()); - - // save work context info (there are some duplications) - VmWorkRemoveNicFromVm workInfo = new VmWorkRemoveNicFromVm(user.getId(), account.getId(), vm.getId(), - nic); - workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); - - _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); - } - context.putContextParameter("workJob", workJob); - context.putContextParameter("jobId", new Long(workJob.getId())); - } - }); - - final long jobId = (Long)context.getContextParameter("jobId"); - AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); - - return new VmJobSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), vm.getId()); + Object[] result = Transaction.execute(new TransactionCallback() { + @Override + public Object[] doInTransaction(TransactionStatus status) { + + List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + VirtualMachine.Type.Instance, vm.getId(), + VmWorkRemoveNicFromVm.class.getName()); + + VmWorkJobVO workJob = null; + if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { + assert (pendingWorkJobs.size() == 1); + workJob = pendingWorkJobs.get(0); + } else { + + workJob = new VmWorkJobVO(context.getContextId()); + + workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkRemoveNicFromVm.class.getName()); + + workJob.setAccountId(account.getId()); + workJob.setUserId(user.getId()); + workJob.setVmType(VirtualMachine.Type.Instance); + workJob.setVmInstanceId(vm.getId()); + workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId()); + + // save work context info (there are some duplications) + VmWorkRemoveNicFromVm workInfo = new VmWorkRemoveNicFromVm(user.getId(), account.getId(), vm.getId(), + VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, nic.getId()); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + + _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId()); + } + return new Object[] {workJob, workJob.getId()}; + } + }); + + final long jobId = (Long)result[1]; + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + + return new VmJobVirtualMachineOutcome((VmWorkJobVO)result[0], vm.getId()); } public Outcome removeVmFromNetworkThroughJobQueue( - final VirtualMachine vm, final Network network, final URI broadcastUri) { + final VirtualMachine vm, final Network network, final URI broadcastUri) { final CallContext context = CallContext.current(); final User user = context.getCallingUser(); final Account account = context.getCallingAccount(); - Transaction.execute(new TransactionCallbackNoReturn () { - public void doInTransactionWithoutResult(TransactionStatus status) { - - _vmDao.lockRow(vm.getId(), true); - - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( - VirtualMachine.Type.Instance, vm.getId(), - VmWorkRemoveVmFromNetwork.class.getName()); - - VmWorkJobVO workJob = null; - if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); - workJob = pendingWorkJobs.get(0); - } else { - - workJob = new VmWorkJobVO(context.getContextId()); - - workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); - workJob.setCmd(VmWorkRemoveVmFromNetwork.class.getName()); - - workJob.setAccountId(account.getId()); - workJob.setUserId(user.getId()); - workJob.setVmType(vm.getType()); - workJob.setVmInstanceId(vm.getId()); - - // save work context info (there are some duplications) - VmWorkRemoveVmFromNetwork workInfo = new VmWorkRemoveVmFromNetwork(user.getId(), account.getId(), vm.getId(), - network, broadcastUri); - workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); - - _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); - } - context.putContextParameter("workJob", workJob); - context.putContextParameter("jobId", new Long(workJob.getId())); - } - }); - - final long jobId = (Long)context.getContextParameter("jobId"); - AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); - - return new VmJobSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), vm.getId()); + Object[] result = Transaction.execute(new TransactionCallback() { + @Override + public Object[] doInTransaction(TransactionStatus status) { + + List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + VirtualMachine.Type.Instance, vm.getId(), + VmWorkRemoveVmFromNetwork.class.getName()); + + VmWorkJobVO workJob = null; + if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { + assert (pendingWorkJobs.size() == 1); + workJob = pendingWorkJobs.get(0); + } else { + + workJob = new VmWorkJobVO(context.getContextId()); + + workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkRemoveVmFromNetwork.class.getName()); + + workJob.setAccountId(account.getId()); + workJob.setUserId(user.getId()); + workJob.setVmType(VirtualMachine.Type.Instance); + workJob.setVmInstanceId(vm.getId()); + workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId()); + + // save work context info (there are some duplications) + VmWorkRemoveVmFromNetwork workInfo = new VmWorkRemoveVmFromNetwork(user.getId(), account.getId(), vm.getId(), + VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, network, broadcastUri); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + + _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId()); + } + return new Object[] {workJob, workJob.getId()}; + } + }); + + final long jobId = (Long)result[1]; + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + + return new VmJobVirtualMachineOutcome((VmWorkJobVO)result[0], vm.getId()); } public Outcome reconfigureVmThroughJobQueue( - final String vmUuid, final ServiceOffering oldServiceOffering, final boolean reconfiguringOnExistingHost) { + final String vmUuid, final ServiceOffering newServiceOffering, final boolean reconfiguringOnExistingHost) { final CallContext context = CallContext.current(); final User user = context.getCallingUser(); @@ -4665,47 +4796,200 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac final VMInstanceVO vm = _vmDao.findByUuid(vmUuid); - Transaction.execute(new TransactionCallbackNoReturn () { - public void doInTransactionWithoutResult(TransactionStatus status) { - - _vmDao.lockRow(vm.getId(), true); - - List pendingWorkJobs = _workJobDao.listPendingWorkJobs( - VirtualMachine.Type.Instance, vm.getId(), - VmWorkReconfigure.class.getName()); - - VmWorkJobVO workJob = null; - if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { - assert (pendingWorkJobs.size() == 1); - workJob = pendingWorkJobs.get(0); - } else { - - workJob = new VmWorkJobVO(context.getContextId()); - - workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER); - workJob.setCmd(VmWorkReconfigure.class.getName()); - - workJob.setAccountId(account.getId()); - workJob.setUserId(user.getId()); - workJob.setVmType(vm.getType()); - workJob.setVmInstanceId(vm.getId()); - - // save work context info (there are some duplications) - VmWorkReconfigure workInfo = new VmWorkReconfigure(user.getId(), account.getId(), vm.getId(), - oldServiceOffering, reconfiguringOnExistingHost); - workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); - - _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId()); - } - context.putContextParameter("workJob", workJob); - context.putContextParameter("jobId", new Long(workJob.getId())); - } - }); - - final long jobId = (Long)context.getContextParameter("jobId"); - AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); - - return new VmJobSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), vm.getId()); + Object[] result = Transaction.execute(new TransactionCallback() { + @Override + public Object[] doInTransaction(TransactionStatus status) { + + List pendingWorkJobs = _workJobDao.listPendingWorkJobs( + VirtualMachine.Type.Instance, vm.getId(), + VmWorkReconfigure.class.getName()); + + VmWorkJobVO workJob = null; + if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) { + assert (pendingWorkJobs.size() == 1); + workJob = pendingWorkJobs.get(0); + } else { + + workJob = new VmWorkJobVO(context.getContextId()); + + workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkReconfigure.class.getName()); + + workJob.setAccountId(account.getId()); + workJob.setUserId(user.getId()); + workJob.setVmType(VirtualMachine.Type.Instance); + workJob.setVmInstanceId(vm.getId()); + workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId()); + + // save work context info (there are some duplications) + VmWorkReconfigure workInfo = new VmWorkReconfigure(user.getId(), account.getId(), vm.getId(), + VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, newServiceOffering.getId(), reconfiguringOnExistingHost); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + + _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId()); + } + return new Object[] {workJob, workJob.getId()}; + } + }); + + final long jobId = (Long)result[1]; + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + + return new VmJobVirtualMachineOutcome((VmWorkJobVO)result[0], vm.getId()); } + private Pair orchestrateStart(VmWorkStart work) throws Exception { + VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); + if (vm == null) { + s_logger.info("Unable to find vm " + work.getVmId()); + } + assert (vm != null); + + orchestrateStart(vm.getUuid(), work.getParams(), work.getPlan(), null); + return new Pair(JobInfo.Status.SUCCEEDED, null); + } + + private Pair orchestrateStop(VmWorkStop work) throws Exception { + VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); + if (vm == null) { + s_logger.info("Unable to find vm " + work.getVmId()); + } + assert (vm != null); + + orchestrateStop(vm.getUuid(), work.isCleanup()); + return new Pair(JobInfo.Status.SUCCEEDED, null); + } + + private Pair orchestrateMigrate(VmWorkMigrate work) throws Exception { + VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); + if (vm == null) { + s_logger.info("Unable to find vm " + work.getVmId()); + } + assert (vm != null); + + orchestrateMigrate(vm.getUuid(), work.getSrcHostId(), work.getDeployDestination()); + return new Pair(JobInfo.Status.SUCCEEDED, null); + } + + private Pair orchestrateMigrateWithStorage(VmWorkMigrateWithStorage work) throws Exception { + VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); + if (vm == null) { + s_logger.info("Unable to find vm " + work.getVmId()); + } + assert (vm != null); + orchestrateMigrateWithStorage(vm.getUuid(), + work.getSrcHostId(), + work.getDestHostId(), + work.getVolumeToPool()); + return new Pair(JobInfo.Status.SUCCEEDED, null); + } + + private Pair orchestrateMigrateForScale(VmWorkMigrateForScale work) throws Exception { + VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); + if (vm == null) { + s_logger.info("Unable to find vm " + work.getVmId()); + } + assert (vm != null); + orchestrateMigrateForScale(vm.getUuid(), + work.getSrcHostId(), + work.getDeployDestination(), + work.getNewServiceOfferringId()); + return new Pair(JobInfo.Status.SUCCEEDED, null); + } + + private Pair orchestrateReboot(VmWorkReboot work) throws Exception { + VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); + if (vm == null) { + s_logger.info("Unable to find vm " + work.getVmId()); + } + assert (vm != null); + orchestrateReboot(vm.getUuid(), work.getParams()); + return new Pair(JobInfo.Status.SUCCEEDED, null); + } + + private Pair orchestrateAddVmToNetwork(VmWorkAddVmToNetwork work) throws Exception { + VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); + if (vm == null) { + s_logger.info("Unable to find vm " + work.getVmId()); + } + assert (vm != null); + + Network network = _networkDao.findById(work.getNetworkId()); + NicProfile nic = orchestrateAddVmToNetwork(vm, network, + work.getRequestedNicProfile()); + + return new Pair(JobInfo.Status.SUCCEEDED, _jobMgr.marshallResultObject(nic.getId())); + } + + private Pair orchestrateRemoveNicFromVm(VmWorkRemoveNicFromVm work) throws Exception { + VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); + if (vm == null) { + s_logger.info("Unable to find vm " + work.getVmId()); + } + assert (vm != null); + NicVO nic = _entityMgr.findById(NicVO.class, work.getNicId()); + boolean result = orchestrateRemoveNicFromVm(vm, nic); + return new Pair(JobInfo.Status.SUCCEEDED, + _jobMgr.marshallResultObject(new Boolean(result))); + } + + private Pair orchestrateRemoveVmFromNetwork(VmWorkRemoveVmFromNetwork work) throws Exception { + VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); + if (vm == null) { + s_logger.info("Unable to find vm " + work.getVmId()); + } + assert (vm != null); + boolean result = orchestrateRemoveVmFromNetwork(vm, + work.getNetwork(), work.getBroadcastUri()); + return new Pair(JobInfo.Status.SUCCEEDED, + _jobMgr.marshallResultObject(new Boolean(result))); + } + + private Pair orchestrateReconfigure(VmWorkReconfigure work) throws Exception { + VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); + if (vm == null) { + s_logger.info("Unable to find vm " + work.getVmId()); + } + assert (vm != null); + + ServiceOffering newServiceOffering = _offeringDao.findById(vm.getId(), work.getNewServiceOfferingId()); + + reConfigureVm(vm.getUuid(), newServiceOffering, + work.isSameHost()); + return new Pair(JobInfo.Status.SUCCEEDED, null); + } + + private Pair orchestrateStorageMigration(VmWorkStorageMigration work) throws Exception { + VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId()); + if (vm == null) { + s_logger.info("Unable to find vm " + work.getVmId()); + } + assert (vm != null); + orchestrateStorageMigration(vm.getUuid(), work.getDestStoragePool()); + return new Pair(JobInfo.Status.SUCCEEDED, null); + } + + @Override + public Pair handleVmWorkJob(VmWork work) throws Exception { + return _jobHandlerProxy.handleVmWorkJob(work); + } + + private VmWorkJobVO createPlaceHolderWork(long instanceId) { + VmWorkJobVO workJob = new VmWorkJobVO(""); + + workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_PLACEHOLDER); + workJob.setCmd(""); + workJob.setCmdInfo(""); + + workJob.setAccountId(0); + workJob.setUserId(0); + workJob.setStep(VmWorkJobVO.Step.Starting); + workJob.setVmType(VirtualMachine.Type.Instance); + workJob.setVmInstanceId(instanceId); + workJob.setInitMsid(ManagementServerNode.getManagementServerId()); + + _workJobDao.persist(workJob); + + return workJob; + } } diff --git a/engine/orchestration/src/com/cloud/vm/VirtualMachinePowerStateSync.java b/engine/orchestration/src/com/cloud/vm/VirtualMachinePowerStateSync.java index dacc8d09067..152d0d889c6 100644 --- a/engine/orchestration/src/com/cloud/vm/VirtualMachinePowerStateSync.java +++ b/engine/orchestration/src/com/cloud/vm/VirtualMachinePowerStateSync.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -21,11 +21,13 @@ import java.util.Map; import com.cloud.agent.api.HostVmStateReportEntry; public interface VirtualMachinePowerStateSync { - - void resetHostSyncState(long hostId); - - void processHostVmStateReport(long hostId, Map report); - - // to adapt legacy ping report - void processHostVmStatePingReport(long hostId, Map report); + + void resetHostSyncState(long hostId); + + void processHostVmStateReport(long hostId, Map report); + + // to adapt legacy ping report + void processHostVmStatePingReport(long hostId, Map report); + + Map convertVmStateReport(Map states); } diff --git a/engine/orchestration/src/com/cloud/vm/VirtualMachinePowerStateSyncImpl.java b/engine/orchestration/src/com/cloud/vm/VirtualMachinePowerStateSyncImpl.java index cd4c3c05965..453890c4279 100644 --- a/engine/orchestration/src/com/cloud/vm/VirtualMachinePowerStateSyncImpl.java +++ b/engine/orchestration/src/com/cloud/vm/VirtualMachinePowerStateSyncImpl.java @@ -32,12 +32,9 @@ import com.cloud.vm.dao.VMInstanceDao; public class VirtualMachinePowerStateSyncImpl implements VirtualMachinePowerStateSync { private static final Logger s_logger = Logger.getLogger(VirtualMachinePowerStateSyncImpl.class); - @Inject - MessageBus _messageBus; - @Inject - VMInstanceDao _instanceDao; - @Inject - VirtualMachineManager _vmMgr; + @Inject MessageBus _messageBus; + @Inject VMInstanceDao _instanceDao; + @Inject VirtualMachineManager _vmMgr; public VirtualMachinePowerStateSyncImpl() { } @@ -53,7 +50,7 @@ public class VirtualMachinePowerStateSyncImpl implements VirtualMachinePowerStat if (s_logger.isDebugEnabled()) s_logger.debug("Process host VM state report from ping process. host: " + hostId); - Map translatedInfo = convertToInfos(report); + Map translatedInfo = convertVmStateReport(report); processReport(hostId, translatedInfo); } @@ -62,7 +59,7 @@ public class VirtualMachinePowerStateSyncImpl implements VirtualMachinePowerStat if (s_logger.isDebugEnabled()) s_logger.debug("Process host VM state report from ping process. host: " + hostId); - Map translatedInfo = convertToInfos(report); + Map translatedInfo = convertVmStateReport(report); processReport(hostId, translatedInfo); } @@ -74,16 +71,19 @@ public class VirtualMachinePowerStateSyncImpl implements VirtualMachinePowerStat s_logger.debug("VM state report. host: " + hostId + ", vm id: " + entry.getKey() + ", power state: " + entry.getValue()); if (_instanceDao.updatePowerState(entry.getKey(), hostId, entry.getValue())) { - if (s_logger.isDebugEnabled()) s_logger.debug("VM state report is updated. host: " + hostId + ", vm id: " + entry.getKey() + ", power state: " + entry.getValue()); _messageBus.publish(null, VirtualMachineManager.Topics.VM_POWER_STATE, PublishScope.GLOBAL, entry.getKey()); + } else { + if (s_logger.isDebugEnabled()) + s_logger.debug("VM power state does not change, skip DB writing. vm id: " + entry.getKey()); } } } - private Map convertToInfos(Map states) { + @Override + public Map convertVmStateReport(Map states) { final HashMap map = new HashMap(); if (states == null) { return map; @@ -93,7 +93,6 @@ public class VirtualMachinePowerStateSyncImpl implements VirtualMachinePowerStat VMInstanceVO vm = findVM(entry.getKey()); if (vm != null) { map.put(vm.getId(), entry.getValue().getState()); - break; } else { s_logger.info("Unable to find matched VM in CloudStack DB. name: " + entry.getKey()); } diff --git a/engine/orchestration/src/com/cloud/vm/VmWorkAddVmToNetwork.java b/engine/orchestration/src/com/cloud/vm/VmWorkAddVmToNetwork.java index 3590c0d21f3..a56259b93ea 100644 --- a/engine/orchestration/src/com/cloud/vm/VmWorkAddVmToNetwork.java +++ b/engine/orchestration/src/com/cloud/vm/VmWorkAddVmToNetwork.java @@ -16,27 +16,25 @@ // under the License. package com.cloud.vm; -import com.cloud.network.Network; - public class VmWorkAddVmToNetwork extends VmWork { - private static final long serialVersionUID = 8861516006586736813L; + private static final long serialVersionUID = 8861516006586736813L; - Network network; - NicProfile requstedNicProfile; - - public VmWorkAddVmToNetwork(long userId, long accountId, long vmId, - Network network, NicProfile requested) { - super(userId, accountId, vmId); - - this.network = network; - this.requstedNicProfile = requested; - } - - public Network getNetwork() { - return this.network; - } - - public NicProfile getRequestedNicProfile() { - return this.requstedNicProfile; - } + Long networkId; + NicProfile requstedNicProfile; + + public VmWorkAddVmToNetwork(long userId, long accountId, long vmId, String handlerName, + Long networkId, NicProfile requested) { + super(userId, accountId, vmId, handlerName); + + this.networkId = networkId; + requstedNicProfile = requested; + } + + public Long getNetworkId() { + return networkId; + } + + public NicProfile getRequestedNicProfile() { + return requstedNicProfile; + } } diff --git a/engine/orchestration/src/com/cloud/vm/VmWorkJobDispatcher.java b/engine/orchestration/src/com/cloud/vm/VmWorkJobDispatcher.java index 7c36d8c28d5..31b2d9ca2d2 100644 --- a/engine/orchestration/src/com/cloud/vm/VmWorkJobDispatcher.java +++ b/engine/orchestration/src/com/cloud/vm/VmWorkJobDispatcher.java @@ -16,137 +16,101 @@ // under the License. package com.cloud.vm; +import java.util.Map; + import javax.inject.Inject; import org.apache.log4j.Logger; + import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.framework.jobs.AsyncJob; import org.apache.cloudstack.framework.jobs.AsyncJobDispatcher; import org.apache.cloudstack.framework.jobs.AsyncJobManager; -import org.apache.cloudstack.framework.jobs.impl.JobSerializerHelper; import org.apache.cloudstack.jobs.JobInfo; +import com.cloud.utils.Pair; import com.cloud.utils.component.AdapterBase; import com.cloud.vm.dao.VMInstanceDao; public class VmWorkJobDispatcher extends AdapterBase implements AsyncJobDispatcher { private static final Logger s_logger = Logger.getLogger(VmWorkJobDispatcher.class); - public static final String VM_WORK_QUEUE = "VmWorkJobQueue"; - public static final String VM_WORK_JOB_DISPATCHER = "VmWorkJobDispatcher"; - public static final String VM_WORK_JOB_WAKEUP_DISPATCHER = "VmWorkJobWakeupDispatcher"; - @Inject private VirtualMachineManagerImpl _vmMgr; - @Inject private AsyncJobManager _asyncJobMgr; + @Inject + private AsyncJobManager _asyncJobMgr; @Inject private VMInstanceDao _instanceDao; - - @Override + + private Map _handlers; + + public VmWorkJobDispatcher() { + } + + public Map getHandlers() { + return _handlers; + } + + public void setHandlers(Map handlers) { + _handlers = handlers; + } + + @Override public void runJob(AsyncJob job) { VmWork work = null; try { - String cmd = job.getCmd(); - assert(cmd != null); - - if(s_logger.isDebugEnabled()) - s_logger.debug("Run VM work job: " + cmd); - - Class workClz = null; - try { - workClz = Class.forName(job.getCmd()); - } catch(ClassNotFoundException e) { - s_logger.error("VM work class " + cmd + " is not found", e); + String cmd = job.getCmd(); + assert (cmd != null); + + Class workClz = null; + try { + workClz = Class.forName(job.getCmd()); + } catch (ClassNotFoundException e) { + s_logger.error("VM work class " + cmd + " is not found" + ", job origin: " + job.getRelated(), e); _asyncJobMgr.completeAsyncJob(job.getId(), JobInfo.Status.FAILED, 0, e.getMessage()); - return; - } - - work = VmWorkSerializer.deserialize(workClz, job.getCmdInfo()); + return; + } + + work = VmWorkSerializer.deserialize(workClz, job.getCmdInfo()); assert(work != null); if(work == null) { - s_logger.error("Unable to deserialize VM work " + job.getCmd() + ", job info: " + job.getCmdInfo()); + s_logger.error("Unable to deserialize VM work " + job.getCmd() + ", job info: " + job.getCmdInfo() + ", job origin: " + job.getRelated()); _asyncJobMgr.completeAsyncJob(job.getId(), JobInfo.Status.FAILED, 0, "Unable to deserialize VM work"); - return; + return; } - - CallContext.register(work.getUserId(), work.getAccountId(), job.getRelated()); - VMInstanceVO vm = _instanceDao.findById(work.getVmId()); - if (vm == null) { - s_logger.info("Unable to find vm " + work.getVmId()); - } - assert(vm != null); - if(work instanceof VmWorkStart) { - VmWorkStart workStart = (VmWorkStart)work; - _vmMgr.orchestrateStart(vm.getUuid(), workStart.getParams(), workStart.getPlan()); - _asyncJobMgr.completeAsyncJob(job.getId(), JobInfo.Status.SUCCEEDED, 0, null); - } else if(work instanceof VmWorkStop) { - VmWorkStop workStop = (VmWorkStop)work; - _vmMgr.orchestrateStop(vm.getUuid(), workStop.isCleanup()); - _asyncJobMgr.completeAsyncJob(job.getId(), JobInfo.Status.SUCCEEDED, 0, null); - } else if(work instanceof VmWorkMigrate) { - VmWorkMigrate workMigrate = (VmWorkMigrate)work; - _vmMgr.orchestrateMigrate(vm.getUuid(), workMigrate.getSrcHostId(), workMigrate.getDeployDestination()); - _asyncJobMgr.completeAsyncJob(job.getId(), JobInfo.Status.SUCCEEDED, 0, null); - } else if(work instanceof VmWorkMigrateWithStorage) { - VmWorkMigrateWithStorage workMigrateWithStorage = (VmWorkMigrateWithStorage)work; - _vmMgr.orchestrateMigrateWithStorage(vm.getUuid(), - workMigrateWithStorage.getSrcHostId(), - workMigrateWithStorage.getDestHostId(), - workMigrateWithStorage.getVolumeToPool()); - _asyncJobMgr.completeAsyncJob(job.getId(), JobInfo.Status.SUCCEEDED, 0, null); - } else if(work instanceof VmWorkMigrateForScale) { - VmWorkMigrateForScale workMigrateForScale = (VmWorkMigrateForScale)work; - _vmMgr.orchestrateMigrateForScale(vm.getUuid(), - workMigrateForScale.getSrcHostId(), - workMigrateForScale.getDeployDestination(), - workMigrateForScale.getNewServiceOfferringId()); - _asyncJobMgr.completeAsyncJob(job.getId(), JobInfo.Status.SUCCEEDED, 0, null); - } else if(work instanceof VmWorkReboot) { - VmWorkReboot workReboot = (VmWorkReboot)work; - _vmMgr.orchestrateReboot(vm.getUuid(), workReboot.getParams()); - _asyncJobMgr.completeAsyncJob(job.getId(), JobInfo.Status.SUCCEEDED, 0, null); - } else if(work instanceof VmWorkAddVmToNetwork) { - VmWorkAddVmToNetwork workAddVmToNetwork = (VmWorkAddVmToNetwork)work; - NicProfile nic = _vmMgr.orchestrateAddVmToNetwork(vm, workAddVmToNetwork.getNetwork(), - workAddVmToNetwork.getRequestedNicProfile()); - _asyncJobMgr.completeAsyncJob(job.getId(), JobInfo.Status.SUCCEEDED, 0, - JobSerializerHelper.toObjectSerializedString(nic)); - } else if(work instanceof VmWorkRemoveNicFromVm) { - VmWorkRemoveNicFromVm workRemoveNicFromVm = (VmWorkRemoveNicFromVm)work; - boolean result = _vmMgr.orchestrateRemoveNicFromVm(vm, workRemoveNicFromVm.getNic()); - _asyncJobMgr.completeAsyncJob(job.getId(), JobInfo.Status.SUCCEEDED, 0, - JobSerializerHelper.toObjectSerializedString(new Boolean(result))); - } else if(work instanceof VmWorkRemoveVmFromNetwork) { - VmWorkRemoveVmFromNetwork workRemoveVmFromNetwork = (VmWorkRemoveVmFromNetwork)work; - boolean result = _vmMgr.orchestrateRemoveVmFromNetwork(vm, - workRemoveVmFromNetwork.getNetwork(), workRemoveVmFromNetwork.getBroadcastUri()); - _asyncJobMgr.completeAsyncJob(job.getId(), JobInfo.Status.SUCCEEDED, 0, - JobSerializerHelper.toObjectSerializedString(new Boolean(result))); - } else if(work instanceof VmWorkReconfigure) { - VmWorkReconfigure workReconfigure = (VmWorkReconfigure)work; - _vmMgr.reConfigureVm(vm.getUuid(), workReconfigure.getNewServiceOffering(), - workReconfigure.isSameHost()); - _asyncJobMgr.completeAsyncJob(job.getId(), JobInfo.Status.SUCCEEDED, 0, null); - } else if(work instanceof VmWorkStorageMigration) { - VmWorkStorageMigration workStorageMigration = (VmWorkStorageMigration)work; - _vmMgr.orchestrateStorageMigration(vm.getUuid(), workStorageMigration.getDestStoragePool()); - _asyncJobMgr.completeAsyncJob(job.getId(), JobInfo.Status.SUCCEEDED, 0, null); - } else { - assert(false); - s_logger.error("Unhandled VM work command: " + job.getCmd()); - - RuntimeException e = new RuntimeException("Unsupported VM work command: " + job.getCmd()); - String exceptionJson = JobSerializerHelper.toSerializedString(e); - s_logger.error("Serialize exception object into json: " + exceptionJson); - _asyncJobMgr.completeAsyncJob(job.getId(), JobInfo.Status.FAILED, 0, exceptionJson); + if (s_logger.isDebugEnabled()) + s_logger.debug("Run VM work job: " + cmd + " for VM " + work.getVmId() + ", job origin: " + job.getRelated()); + try { + if (_handlers == null || _handlers.isEmpty()) { + s_logger.error("Invalid startup configuration, no work job handler is found. cmd: " + job.getCmd() + ", job info: " + job.getCmdInfo() + + ", job origin: " + job.getRelated()); + _asyncJobMgr.completeAsyncJob(job.getId(), JobInfo.Status.FAILED, 0, "Invalid startup configuration. no job handler is found"); + return; + } + + VmWorkJobHandler handler = _handlers.get(work.getHandlerName()); + + if (handler == null) { + s_logger.error("Unable to find work job handler. handler name: " + work.getHandlerName() + ", job cmd: " + job.getCmd() + + ", job info: " + job.getCmdInfo() + ", job origin: " + job.getRelated()); + _asyncJobMgr.completeAsyncJob(job.getId(), JobInfo.Status.FAILED, 0, "Unable to find work job handler"); + return; + } + + CallContext.register(work.getUserId(), work.getAccountId(), job.getRelated()); + + Pair result = handler.handleVmWorkJob(work); + _asyncJobMgr.completeAsyncJob(job.getId(), result.first(), 0, result.second()); + } finally { + if (s_logger.isDebugEnabled()) + s_logger.debug("Done with run of VM work job: " + cmd + " for VM " + work.getVmId() + ", job origin: " + job.getRelated()); } } catch(Throwable e) { - s_logger.error("Unable to complete " + job, e); - - String exceptionJson = JobSerializerHelper.toSerializedString(e); - s_logger.info("Serialize exception object into json: " + exceptionJson); - _asyncJobMgr.completeAsyncJob(job.getId(), JobInfo.Status.FAILED, 0, exceptionJson); + s_logger.error("Unable to complete " + job + ", job origin:" + job.getRelated(), e); + + RuntimeException ex = new RuntimeException("Job failed due to exception " + e.getMessage()); + _asyncJobMgr.completeAsyncJob(job.getId(), JobInfo.Status.FAILED, 0, _asyncJobMgr.marshallResultObject(ex)); } finally { CallContext.unregister(); } - } + } } diff --git a/engine/orchestration/src/com/cloud/vm/VmWorkJobWakeupDispatcher.java b/engine/orchestration/src/com/cloud/vm/VmWorkJobWakeupDispatcher.java new file mode 100644 index 00000000000..520a55042e3 --- /dev/null +++ b/engine/orchestration/src/com/cloud/vm/VmWorkJobWakeupDispatcher.java @@ -0,0 +1,147 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package com.cloud.vm; + +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.inject.Inject; + +import org.apache.log4j.Logger; + +import org.apache.cloudstack.context.CallContext; +import org.apache.cloudstack.framework.jobs.AsyncJob; +import org.apache.cloudstack.framework.jobs.AsyncJobDispatcher; +import org.apache.cloudstack.framework.jobs.AsyncJobManager; +import org.apache.cloudstack.framework.jobs.dao.AsyncJobJoinMapDao; +import org.apache.cloudstack.framework.jobs.dao.VmWorkJobDao; +import org.apache.cloudstack.framework.jobs.impl.AsyncJobJoinMapVO; +import org.apache.cloudstack.framework.jobs.impl.VmWorkJobVO; + +import com.cloud.user.AccountVO; +import com.cloud.user.dao.AccountDao; +import com.cloud.utils.component.AdapterBase; +import com.cloud.vm.dao.VMInstanceDao; + +/** + * Please note: VmWorkJobWakeupDispatcher is not currently in use. It is designed for event-driven based + * job processing model. + * + * Current code base uses blocking calls to wait for job completion + */ +public class VmWorkJobWakeupDispatcher extends AdapterBase implements AsyncJobDispatcher { + private static final Logger s_logger = Logger.getLogger(VmWorkJobWakeupDispatcher.class); + + @Inject + private VmWorkJobDao _workjobDao; + @Inject + private AsyncJobJoinMapDao _joinMapDao; + @Inject + private AccountDao _accountDao; + @Inject + private VMInstanceDao _instanceDao; + @Inject + private VirtualMachineManager _vmMgr; + @Inject + private AsyncJobManager _asyncJobMgr; + + private final Map _handlerMap = new HashMap(); + + @Override + public void runJob(AsyncJob job) { + try { + List joinRecords = _joinMapDao.listJoinRecords(job.getId()); + if (joinRecords.size() != 1) { + s_logger.warn("AsyncJob-" + job.getId() + + " received wakeup call with un-supported joining job number: " + joinRecords.size()); + + // if we fail wakeup-execution for any reason, avoid release sync-source if there is any + job.setSyncSource(null); + return; + } + + AsyncJobJoinMapVO joinRecord = joinRecords.get(0); + VmWorkJobVO joinedJob = _workjobDao.findById(joinRecord.getJoinJobId()); + + Class workClz = null; + try { + workClz = Class.forName(job.getCmd()); + } catch (ClassNotFoundException e) { + s_logger.error("VM work class " + job.getCmd() + " is not found", e); + return; + } + + // get original work context information from joined job + VmWork work = VmWorkSerializer.deserialize(workClz, joinedJob.getCmdInfo()); + assert (work != null); + + AccountVO account = _accountDao.findById(work.getAccountId()); + assert (account != null); + + VMInstanceVO vm = _instanceDao.findById(work.getVmId()); + assert (vm != null); + + CallContext.register(work.getUserId(), work.getAccountId(), job.getRelated()); + try { + Method handler = getHandler(joinRecord.getWakeupHandler()); + if (handler != null) { + handler.invoke(_vmMgr); + } else { + assert (false); + s_logger.error("Unable to find wakeup handler " + joinRecord.getWakeupHandler() + + " when waking up job-" + job.getId()); + } + } finally { + CallContext.unregister(); + } + } catch (Throwable e) { + s_logger.warn("Unexpected exception in waking up job-" + job.getId()); + + // if we fail wakeup-execution for any reason, avoid release sync-source if there is any + job.setSyncSource(null); + } + } + + private Method getHandler(String wakeupHandler) { + + synchronized (_handlerMap) { + Class clz = _vmMgr.getClass(); + Method method = _handlerMap.get(wakeupHandler); + if (method != null) + return method; + + try { + method = clz.getMethod(wakeupHandler); + method.setAccessible(true); + } catch (SecurityException e) { + assert (false); + s_logger.error("Unexpected exception", e); + return null; + } catch (NoSuchMethodException e) { + assert (false); + s_logger.error("Unexpected exception", e); + return null; + } + + _handlerMap.put(wakeupHandler, method); + return method; + } + } +} \ No newline at end of file diff --git a/engine/orchestration/src/com/cloud/vm/VmWorkMigrate.java b/engine/orchestration/src/com/cloud/vm/VmWorkMigrate.java index c313876b433..5bcea9a8aca 100644 --- a/engine/orchestration/src/com/cloud/vm/VmWorkMigrate.java +++ b/engine/orchestration/src/com/cloud/vm/VmWorkMigrate.java @@ -29,17 +29,18 @@ import com.cloud.storage.Volume; import com.cloud.utils.db.EntityManager; public class VmWorkMigrate extends VmWork { - private static final long serialVersionUID = 1689203333114836522L; + private static final long serialVersionUID = 1689203333114836522L; - Long zoneId; + Long zoneId; Long podId; Long clusterId; Long hostId; private Map storage; long srcHostId; - public VmWorkMigrate(long userId, long accountId, long vmId, long srcHostId, DeployDestination dst) { - super(userId, accountId, vmId); + public VmWorkMigrate(long userId, long accountId, long vmId, String handlerName, + long srcHostId, DeployDestination dst) { + super(userId, accountId, vmId, handlerName); this.srcHostId = srcHostId; zoneId = dst.getDataCenter() != null ? dst.getDataCenter().getId() : null; podId = dst.getPod() != null ? dst.getPod().getId() : null; @@ -60,7 +61,7 @@ public class VmWorkMigrate extends VmWork { Pod pod = podId != null ? s_entityMgr.findById(Pod.class, podId) : null; Cluster cluster = clusterId != null ? s_entityMgr.findById(Cluster.class, clusterId) : null; Host host = hostId != null ? s_entityMgr.findById(Host.class, hostId) : null; - + Map vols = null; if (storage != null) { diff --git a/engine/orchestration/src/com/cloud/vm/VmWorkMigrateForScale.java b/engine/orchestration/src/com/cloud/vm/VmWorkMigrateForScale.java index 8e71aa84050..0dd4d88c218 100644 --- a/engine/orchestration/src/com/cloud/vm/VmWorkMigrateForScale.java +++ b/engine/orchestration/src/com/cloud/vm/VmWorkMigrateForScale.java @@ -19,30 +19,30 @@ package com.cloud.vm; import com.cloud.deploy.DeployDestination; public class VmWorkMigrateForScale extends VmWork { - private static final long serialVersionUID = 6854870395568389613L; + private static final long serialVersionUID = 6854870395568389613L; - long srcHostId; - DeployDestination deployDestination; - Long newSvcOfferingId; - - public VmWorkMigrateForScale(long userId, long accountId, long vmId, long srcHostId, - DeployDestination dest, Long newSvcOfferingId) { - - super(userId, accountId, vmId); - this.srcHostId = srcHostId; - this.deployDestination = dest; - this.newSvcOfferingId = newSvcOfferingId; + long srcHostId; + DeployDestination deployDestination; + Long newSvcOfferingId; + + public VmWorkMigrateForScale(long userId, long accountId, long vmId, String handlerName, long srcHostId, + DeployDestination dest, Long newSvcOfferingId) { + + super(userId, accountId, vmId, handlerName); + this.srcHostId = srcHostId; + deployDestination = dest; + this.newSvcOfferingId = newSvcOfferingId; } - + public long getSrcHostId() { - return srcHostId; + return srcHostId; } - + public DeployDestination getDeployDestination() { - return this.deployDestination; + return deployDestination; } - + public Long getNewServiceOfferringId() { - return this.newSvcOfferingId; + return newSvcOfferingId; } } diff --git a/engine/orchestration/src/com/cloud/vm/VmWorkMigrateWithStorage.java b/engine/orchestration/src/com/cloud/vm/VmWorkMigrateWithStorage.java index ae91231a35f..ee30c74abfb 100644 --- a/engine/orchestration/src/com/cloud/vm/VmWorkMigrateWithStorage.java +++ b/engine/orchestration/src/com/cloud/vm/VmWorkMigrateWithStorage.java @@ -22,31 +22,31 @@ import com.cloud.storage.StoragePool; import com.cloud.storage.Volume; public class VmWorkMigrateWithStorage extends VmWork { - private static final long serialVersionUID = -5626053872453569165L; + private static final long serialVersionUID = -5626053872453569165L; - long srcHostId; - long destHostId; - Map volumeToPool; - - public VmWorkMigrateWithStorage(long userId, long accountId, long vmId, long srcHostId, - long destHostId, Map volumeToPool) { - - super(userId, accountId, vmId); - - this.srcHostId = srcHostId; - this.destHostId = destHostId; - this.volumeToPool = volumeToPool; + long srcHostId; + long destHostId; + Map volumeToPool; + + public VmWorkMigrateWithStorage(long userId, long accountId, long vmId, String handlerName, long srcHostId, + long destHostId, Map volumeToPool) { + + super(userId, accountId, vmId, handlerName); + + this.srcHostId = srcHostId; + this.destHostId = destHostId; + this.volumeToPool = volumeToPool; } - + public long getSrcHostId() { - return this.srcHostId; + return srcHostId; } - + public long getDestHostId() { - return this.destHostId; + return destHostId; } - + public Map getVolumeToPool() { - return this.volumeToPool; + return volumeToPool; } } diff --git a/engine/orchestration/src/com/cloud/vm/VmWorkReboot.java b/engine/orchestration/src/com/cloud/vm/VmWorkReboot.java index 8f50702358a..63c7d004968 100644 --- a/engine/orchestration/src/com/cloud/vm/VmWorkReboot.java +++ b/engine/orchestration/src/com/cloud/vm/VmWorkReboot.java @@ -23,46 +23,38 @@ import java.util.Map; import org.apache.cloudstack.framework.jobs.impl.JobSerializerHelper; public class VmWorkReboot extends VmWork { - private static final long serialVersionUID = 195907627459759933L; + private static final long serialVersionUID = 195907627459759933L; - // use serialization friendly map - private Map rawParams; - - public VmWorkReboot(long userId, long accountId, long vmId, Map params) { - super(userId, accountId, vmId); - - setParams(params); + // use serialization friendly map + private Map rawParams; + + public VmWorkReboot(long userId, long accountId, long vmId, String handlerName, Map params) { + super(userId, accountId, vmId, handlerName); + + setParams(params); } - - public Map getRawParams() { - return rawParams; - } - public void setRawParams(Map params) { - rawParams = params; - } - - public Map getParams() { - Map map = new HashMap(); - - if(rawParams != null) { - for(Map.Entry entry : rawParams.entrySet()) { - VirtualMachineProfile.Param key = new VirtualMachineProfile.Param(entry.getKey()); - Object val = JobSerializerHelper.fromObjectSerializedString(entry.getValue()); - map.put(key, val); - } - } - - return map; - } - - public void setParams(Map params) { - if(params != null) { - rawParams = new HashMap(); - for(Map.Entry entry : params.entrySet()) { - rawParams.put(entry.getKey().getName(), JobSerializerHelper.toObjectSerializedString( - entry.getValue() instanceof Serializable ? (Serializable)entry.getValue() : entry.getValue().toString())); - } - } - } + public Map getParams() { + Map map = new HashMap(); + + if (rawParams != null) { + for (Map.Entry entry : rawParams.entrySet()) { + VirtualMachineProfile.Param key = new VirtualMachineProfile.Param(entry.getKey()); + Object val = JobSerializerHelper.fromObjectSerializedString(entry.getValue()); + map.put(key, val); + } + } + + return map; + } + + public void setParams(Map params) { + if (params != null) { + rawParams = new HashMap(); + for (Map.Entry entry : params.entrySet()) { + rawParams.put(entry.getKey().getName(), JobSerializerHelper.toObjectSerializedString( + entry.getValue() instanceof Serializable ? (Serializable)entry.getValue() : entry.getValue().toString())); + } + } + } } diff --git a/engine/orchestration/src/com/cloud/vm/VmWorkReconfigure.java b/engine/orchestration/src/com/cloud/vm/VmWorkReconfigure.java index 48a9df35faa..17abeb24537 100644 --- a/engine/orchestration/src/com/cloud/vm/VmWorkReconfigure.java +++ b/engine/orchestration/src/com/cloud/vm/VmWorkReconfigure.java @@ -16,28 +16,27 @@ // under the License. package com.cloud.vm; -import com.cloud.offering.ServiceOffering; public class VmWorkReconfigure extends VmWork { - private static final long serialVersionUID = -4517030323758086615L; - - ServiceOffering newServiceOffering; - boolean sameHost; - - public VmWorkReconfigure(long userId, long accountId, long vmId, - ServiceOffering newServiceOffering, boolean sameHost) { - - super(userId, accountId, vmId); - - this.newServiceOffering = newServiceOffering; - this.sameHost = sameHost; + private static final long serialVersionUID = -4517030323758086615L; + + Long newServiceOfferingId; + boolean sameHost; + + public VmWorkReconfigure(long userId, long accountId, long vmId, String handlerName, + Long newServiceOfferingId, boolean sameHost) { + + super(userId, accountId, vmId, handlerName); + + this.newServiceOfferingId = newServiceOfferingId; + this.sameHost = sameHost; } - - public ServiceOffering getNewServiceOffering() { - return this.newServiceOffering; + + public Long getNewServiceOfferingId() { + return newServiceOfferingId; } - + public boolean isSameHost() { - return this.sameHost; + return sameHost; } } diff --git a/engine/orchestration/src/com/cloud/vm/VmWorkRemoveNicFromVm.java b/engine/orchestration/src/com/cloud/vm/VmWorkRemoveNicFromVm.java index b756ac35761..50f158e421d 100644 --- a/engine/orchestration/src/com/cloud/vm/VmWorkRemoveNicFromVm.java +++ b/engine/orchestration/src/com/cloud/vm/VmWorkRemoveNicFromVm.java @@ -17,17 +17,17 @@ package com.cloud.vm; public class VmWorkRemoveNicFromVm extends VmWork { - private static final long serialVersionUID = -4265657031064437923L; + private static final long serialVersionUID = -4265657031064437923L; - Nic nic; - - public VmWorkRemoveNicFromVm(long userId, long accountId, long vmId, Nic nic) { - super(userId, accountId, vmId); - - this.nic = nic; + Long nicId; + + public VmWorkRemoveNicFromVm(long userId, long accountId, long vmId, String handlerName, Long nicId) { + super(userId, accountId, vmId, handlerName); + + this.nicId = nicId; } - - public Nic getNic() { - return this.nic; + + public Long getNicId() { + return nicId; } } diff --git a/engine/orchestration/src/com/cloud/vm/VmWorkRemoveVmFromNetwork.java b/engine/orchestration/src/com/cloud/vm/VmWorkRemoveVmFromNetwork.java index d4e0ae4ef7b..535b8d00faa 100644 --- a/engine/orchestration/src/com/cloud/vm/VmWorkRemoveVmFromNetwork.java +++ b/engine/orchestration/src/com/cloud/vm/VmWorkRemoveVmFromNetwork.java @@ -21,23 +21,23 @@ import java.net.URI; import com.cloud.network.Network; public class VmWorkRemoveVmFromNetwork extends VmWork { - private static final long serialVersionUID = -5070392905642149925L; + private static final long serialVersionUID = -5070392905642149925L; - Network network; - URI broadcastUri; - - public VmWorkRemoveVmFromNetwork(long userId, long accountId, long vmId, Network network, URI broadcastUri) { - super(userId, accountId, vmId); - - this.network = network; - this.broadcastUri = broadcastUri; - } - - public Network getNetwork() { - return this.network; - } - - public URI getBroadcastUri() { - return this.broadcastUri; - } + Network network; + URI broadcastUri; + + public VmWorkRemoveVmFromNetwork(long userId, long accountId, long vmId, String handlerName, Network network, URI broadcastUri) { + super(userId, accountId, vmId, handlerName); + + this.network = network; + this.broadcastUri = broadcastUri; + } + + public Network getNetwork() { + return network; + } + + public URI getBroadcastUri() { + return broadcastUri; + } } diff --git a/engine/orchestration/src/com/cloud/vm/VmWorkStart.java b/engine/orchestration/src/com/cloud/vm/VmWorkStart.java index 7a7447f74a0..f1b2efdbeac 100644 --- a/engine/orchestration/src/com/cloud/vm/VmWorkStart.java +++ b/engine/orchestration/src/com/cloud/vm/VmWorkStart.java @@ -32,94 +32,94 @@ import com.cloud.deploy.DeploymentPlanner.ExcludeList; import com.cloud.utils.Journal; public class VmWorkStart extends VmWork { - private static final long serialVersionUID = 9038937399817468894L; + private static final long serialVersionUID = 9038937399817468894L; - private static final Logger s_logger = Logger.getLogger(VmWorkStart.class); + private static final Logger s_logger = Logger.getLogger(VmWorkStart.class); - long dcId; - Long podId; - Long clusterId; - Long hostId; - Long poolId; - ExcludeList avoids; - Long physicalNetworkId; - - String reservationId; - String journalName; - - // use serialization friendly map - private Map rawParams; + long dcId; + Long podId; + Long clusterId; + Long hostId; + Long poolId; + ExcludeList avoids; + Long physicalNetworkId; - public VmWorkStart(long userId, long accountId, long vmId) { - super(userId, accountId, vmId); - } + String reservationId; + String journalName; - public DeploymentPlan getPlan() { - - if(podId != null || clusterId != null || hostId != null || poolId != null || physicalNetworkId != null) { - // this is ugly, to work with legacy code, we need to re-construct the DeploymentPlan hard-codely - // this has to be refactored together with migrating legacy code into the new way - ReservationContext context = null; - if(reservationId != null) { - Journal journal = new Journal.LogJournal("VmWorkStart", s_logger); - context = new ReservationContextImpl(reservationId, journal, - CallContext.current().getCallingUser(), - CallContext.current().getCallingAccount()); - } - - DeploymentPlan plan = new DataCenterDeployment( - dcId, podId, clusterId, hostId, poolId, physicalNetworkId, - context); - return plan; - } - - return null; - } + // use serialization friendly map + private Map rawParams; - public void setPlan(DeploymentPlan plan) { - if(plan != null) { - dcId = plan.getDataCenterId(); - podId = plan.getPodId(); - clusterId = plan.getClusterId(); - hostId = plan.getHostId(); - poolId = plan.getPoolId(); - physicalNetworkId = plan.getPhysicalNetworkId(); - avoids = plan.getAvoids(); - - if(plan.getReservationContext() != null) - reservationId = plan.getReservationContext().getReservationId(); - } - } + public VmWorkStart(long userId, long accountId, long vmId, String handlerName) { + super(userId, accountId, vmId, handlerName); + } - public Map getRawParams() { - return rawParams; - } + public DeploymentPlan getPlan() { - public void setRawParams(Map params) { - rawParams = params; - } - - public Map getParams() { - Map map = new HashMap(); - - if(rawParams != null) { - for(Map.Entry entry : rawParams.entrySet()) { - VirtualMachineProfile.Param key = new VirtualMachineProfile.Param(entry.getKey()); - Object val = JobSerializerHelper.fromObjectSerializedString(entry.getValue()); - map.put(key, val); - } - } - - return map; - } - - public void setParams(Map params) { - if(params != null) { - rawParams = new HashMap(); - for(Map.Entry entry : params.entrySet()) { - rawParams.put(entry.getKey().getName(), JobSerializerHelper.toObjectSerializedString( - entry.getValue() instanceof Serializable ? (Serializable)entry.getValue() : entry.getValue().toString())); - } - } - } + if (podId != null || clusterId != null || hostId != null || poolId != null || physicalNetworkId != null) { + // this is ugly, to work with legacy code, we need to re-construct the DeploymentPlan hard-codely + // this has to be refactored together with migrating legacy code into the new way + ReservationContext context = null; + if (reservationId != null) { + Journal journal = new Journal.LogJournal("VmWorkStart", s_logger); + context = new ReservationContextImpl(reservationId, journal, + CallContext.current().getCallingUser(), + CallContext.current().getCallingAccount()); + } + + DeploymentPlan plan = new DataCenterDeployment( + dcId, podId, clusterId, hostId, poolId, physicalNetworkId, + context); + return plan; + } + + return null; + } + + public void setPlan(DeploymentPlan plan) { + if (plan != null) { + dcId = plan.getDataCenterId(); + podId = plan.getPodId(); + clusterId = plan.getClusterId(); + hostId = plan.getHostId(); + poolId = plan.getPoolId(); + physicalNetworkId = plan.getPhysicalNetworkId(); + avoids = plan.getAvoids(); + + if (plan.getReservationContext() != null) + reservationId = plan.getReservationContext().getReservationId(); + } + } + + public Map getRawParams() { + return rawParams; + } + + public void setRawParams(Map params) { + rawParams = params; + } + + public Map getParams() { + Map map = new HashMap(); + + if (rawParams != null) { + for (Map.Entry entry : rawParams.entrySet()) { + VirtualMachineProfile.Param key = new VirtualMachineProfile.Param(entry.getKey()); + Object val = JobSerializerHelper.fromObjectSerializedString(entry.getValue()); + map.put(key, val); + } + } + + return map; + } + + public void setParams(Map params) { + if (params != null) { + rawParams = new HashMap(); + for (Map.Entry entry : params.entrySet()) { + rawParams.put(entry.getKey().getName(), JobSerializerHelper.toObjectSerializedString( + entry.getValue() instanceof Serializable ? (Serializable)entry.getValue() : entry.getValue().toString())); + } + } + } } diff --git a/engine/orchestration/src/com/cloud/vm/VmWorkStop.java b/engine/orchestration/src/com/cloud/vm/VmWorkStop.java index 0a27057810b..6d4148000c8 100644 --- a/engine/orchestration/src/com/cloud/vm/VmWorkStop.java +++ b/engine/orchestration/src/com/cloud/vm/VmWorkStop.java @@ -17,16 +17,16 @@ package com.cloud.vm; public class VmWorkStop extends VmWork { - private static final long serialVersionUID = 202908740486785251L; - - private final boolean cleanup; - - public VmWorkStop(long userId, long accountId, long vmId, boolean cleanup) { - super(userId, accountId, vmId); + private static final long serialVersionUID = 202908740486785251L; + + private final boolean cleanup; + + public VmWorkStop(long userId, long accountId, long vmId, String handlerName, boolean cleanup) { + super(userId, accountId, vmId, handlerName); this.cleanup = cleanup; - } - - public boolean isCleanup() { - return cleanup; - } + } + + public boolean isCleanup() { + return cleanup; + } } diff --git a/engine/orchestration/src/com/cloud/vm/VmWorkStorageMigration.java b/engine/orchestration/src/com/cloud/vm/VmWorkStorageMigration.java index ba8330c9d9d..2b2f8e841ed 100644 --- a/engine/orchestration/src/com/cloud/vm/VmWorkStorageMigration.java +++ b/engine/orchestration/src/com/cloud/vm/VmWorkStorageMigration.java @@ -19,17 +19,17 @@ package com.cloud.vm; import com.cloud.storage.StoragePool; public class VmWorkStorageMigration extends VmWork { - private static final long serialVersionUID = -8677979691741157474L; + private static final long serialVersionUID = -8677979691741157474L; - StoragePool destPool; - - public VmWorkStorageMigration(long userId, long accountId, long vmId, StoragePool destPool) { - super(userId, accountId, vmId); - - this.destPool = destPool; + StoragePool destPool; + + public VmWorkStorageMigration(long userId, long accountId, long vmId, String handlerName, StoragePool destPool) { + super(userId, accountId, vmId, handlerName); + + this.destPool = destPool; } - + public StoragePool getDestStoragePool() { - return this.destPool; + return destPool; } } diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/VMEntityManagerImpl.java b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/VMEntityManagerImpl.java index 40b0f447392..36481ab5a43 100755 --- a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/VMEntityManagerImpl.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/VMEntityManagerImpl.java @@ -189,7 +189,7 @@ public class VMEntityManagerImpl implements VMEntityManager { while (true) { DeployDestination dest = null; try { - dest = _dpMgr.planDeployment(vmProfile, plan, exclude); + dest = _dpMgr.planDeployment(vmProfile, plan, exclude, null); } catch (AffinityConflictException e) { throw new CloudRuntimeException("Unable to create deployment, affinity rules associted to the VM conflict"); } diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/VirtualMachineEntityImpl.java b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/VirtualMachineEntityImpl.java index ed8909cda48..7f2e4fff240 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/VirtualMachineEntityImpl.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/VirtualMachineEntityImpl.java @@ -57,7 +57,6 @@ public class VirtualMachineEntityImpl implements VirtualMachineEntity { this.vmEntityVO.setOwner(owner); this.vmEntityVO.setHostname(hostName); this.vmEntityVO.setDisplayname(displayName); - this.vmEntityVO.setSpeed(speed); this.vmEntityVO.setComputeTags(computeTags); this.vmEntityVO.setRootDiskTags(rootDiskTags); this.vmEntityVO.setNetworkIds(networks); @@ -76,7 +75,6 @@ public class VirtualMachineEntityImpl implements VirtualMachineEntity { this.vmEntityVO.setOwner(owner); this.vmEntityVO.setHostname(hostName); this.vmEntityVO.setDisplayname(displayName); - this.vmEntityVO.setSpeed(speed); this.vmEntityVO.setComputeTags(computeTags); this.vmEntityVO.setRootDiskTags(rootDiskTags); this.vmEntityVO.setNetworkIds(networks); diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/dao/EngineHostDaoImpl.java b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/dao/EngineHostDaoImpl.java index 97ac5897d20..35d7bbced73 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/dao/EngineHostDaoImpl.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/dao/EngineHostDaoImpl.java @@ -776,7 +776,7 @@ public class EngineHostDaoImpl extends GenericDaoBase implem @Override public List search( - SearchCriteria sc, Filter filter, boolean enable_query_cache) { + SearchCriteria sc, Filter filter, boolean enableQueryCache) { // TODO Auto-generated method stub return null; } @@ -789,7 +789,7 @@ public class EngineHostDaoImpl extends GenericDaoBase implem } @Override - public List searchIncludingRemoved(SearchCriteria sc, Filter filter, Boolean lock, boolean cache, boolean enable_query_cache) { + public List searchIncludingRemoved(SearchCriteria sc, Filter filter, Boolean lock, boolean cache, boolean enableQueryCache) { // TODO Auto-generated method stub return null; } diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/orchestration/NetworkOrchestrator.java b/engine/orchestration/src/org/apache/cloudstack/engine/orchestration/NetworkOrchestrator.java index 4ad0cd7af8f..85fa530e820 100755 --- a/engine/orchestration/src/org/apache/cloudstack/engine/orchestration/NetworkOrchestrator.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/orchestration/NetworkOrchestrator.java @@ -36,8 +36,6 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; -import org.apache.log4j.Logger; - import org.apache.cloudstack.acl.ControlledEntity.ACLType; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; @@ -256,37 +254,37 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra @Inject protected IpAddressManager _ipAddrMgr; - List _networkGurus; + List networkGurus; public List getNetworkGurus() { - return _networkGurus; + return networkGurus; } - public void setNetworkGurus(List _networkGurus) { - this._networkGurus = _networkGurus; + public void setNetworkGurus(List networkGurus) { + this.networkGurus = networkGurus; } - List _networkElements; + List networkElements; public List getNetworkElements() { - return _networkElements; + return networkElements; } - public void setNetworkElements(List _networkElements) { - this._networkElements = _networkElements; + public void setNetworkElements(List networkElements) { + this.networkElements = networkElements; } @Inject NetworkDomainDao _networkDomainDao; - List _ipDeployers; + List ipDeployers; public List getIpDeployers() { - return _ipDeployers; + return ipDeployers; } - public void setIpDeployers(List _ipDeployers) { - this._ipDeployers = _ipDeployers; + public void setIpDeployers(List ipDeployers) { + this.ipDeployers = ipDeployers; } List _dhcpProviders; @@ -295,8 +293,8 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra return _dhcpProviders; } - public void setDhcpProviders(List _dhcpProviders) { - this._dhcpProviders = _dhcpProviders; + public void setDhcpProviders(List dhcpProviders) { + _dhcpProviders = dhcpProviders; } @Inject @@ -414,41 +412,37 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra NetworkOfferingVO offering = null; //#1 - quick cloud network offering if (_networkOfferingDao.findByUniqueName(NetworkOffering.QuickCloudNoServices) == null) { - offering = - _configMgr.createNetworkOffering(NetworkOffering.QuickCloudNoServices, "Offering for QuickCloud with no services", TrafficType.Guest, null, true, - Availability.Optional, null, new HashMap>(), true, Network.GuestType.Shared, false, null, true, null, - true, false, null, false, null, true); + offering = _configMgr.createNetworkOffering(NetworkOffering.QuickCloudNoServices, "Offering for QuickCloud with no services", TrafficType.Guest, null, true, + Availability.Optional, null, new HashMap>(), true, Network.GuestType.Shared, false, null, true, null, true, + false, null, false, null, true); offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } //#2 - SG enabled network offering if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultSharedNetworkOfferingWithSGService) == null) { - offering = - _configMgr.createNetworkOffering(NetworkOffering.DefaultSharedNetworkOfferingWithSGService, - "Offering for Shared Security group enabled networks", TrafficType.Guest, null, true, Availability.Optional, null, - defaultSharedNetworkOfferingProviders, true, Network.GuestType.Shared, false, null, true, null, true, false, null, false, null, true); + offering = _configMgr.createNetworkOffering(NetworkOffering.DefaultSharedNetworkOfferingWithSGService, "Offering for Shared Security group enabled networks", + TrafficType.Guest, null, true, Availability.Optional, null, defaultSharedNetworkOfferingProviders, true, Network.GuestType.Shared, false, null, true, + null, true, false, null, false, null, true); offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } //#3 - shared network offering with no SG service if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultSharedNetworkOffering) == null) { - offering = - _configMgr.createNetworkOffering(NetworkOffering.DefaultSharedNetworkOffering, "Offering for Shared networks", TrafficType.Guest, null, true, - Availability.Optional, null, defaultSharedNetworkOfferingProviders, true, Network.GuestType.Shared, false, null, true, null, true, false, - null, false, null, true); + offering = _configMgr.createNetworkOffering(NetworkOffering.DefaultSharedNetworkOffering, "Offering for Shared networks", TrafficType.Guest, null, true, + Availability.Optional, null, defaultSharedNetworkOfferingProviders, true, Network.GuestType.Shared, false, null, true, null, true, false, null, false, + null, true); offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } //#4 - default isolated offering with Source nat service if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultIsolatedNetworkOfferingWithSourceNatService) == null) { - offering = - _configMgr.createNetworkOffering(NetworkOffering.DefaultIsolatedNetworkOfferingWithSourceNatService, + offering = _configMgr.createNetworkOffering(NetworkOffering.DefaultIsolatedNetworkOfferingWithSourceNatService, "Offering for Isolated networks with Source Nat service enabled", TrafficType.Guest, null, false, Availability.Required, null, - defaultIsolatedSourceNatEnabledNetworkOfferingProviders, true, Network.GuestType.Isolated, false, null, true, null, false, false, null, - false, null, true); + defaultIsolatedSourceNatEnabledNetworkOfferingProviders, true, Network.GuestType.Isolated, false, null, true, null, false, false, null, false, null, + true); offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); @@ -456,8 +450,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra //#5 - default vpc offering with LB service if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworks) == null) { - offering = - _configMgr.createNetworkOffering(NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworks, + offering = _configMgr.createNetworkOffering(NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworks, "Offering for Isolated VPC networks with Source Nat service enabled", TrafficType.Guest, null, false, Availability.Optional, null, defaultVPCOffProviders, true, Network.GuestType.Isolated, false, null, false, null, false, false, null, false, null, true); offering.setState(NetworkOffering.State.Enabled); @@ -468,21 +461,18 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworksNoLB) == null) { //remove LB service defaultVPCOffProviders.remove(Service.Lb); - offering = - _configMgr.createNetworkOffering(NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworksNoLB, - "Offering for Isolated VPC networks with Source Nat service enabled and LB service disabled", TrafficType.Guest, null, false, - Availability.Optional, null, defaultVPCOffProviders, true, Network.GuestType.Isolated, false, null, false, null, false, false, null, false, - null, true); + offering = _configMgr.createNetworkOffering(NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworksNoLB, + "Offering for Isolated VPC networks with Source Nat service enabled and LB service disabled", TrafficType.Guest, null, false, Availability.Optional, + null, defaultVPCOffProviders, true, Network.GuestType.Isolated, false, null, false, null, false, false, null, false, null, true); offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } //#7 - isolated offering with source nat disabled if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultIsolatedNetworkOffering) == null) { - offering = - _configMgr.createNetworkOffering(NetworkOffering.DefaultIsolatedNetworkOffering, "Offering for Isolated networks with no Source Nat service", - TrafficType.Guest, null, true, Availability.Optional, null, defaultIsolatedNetworkOfferingProviders, true, Network.GuestType.Isolated, false, - null, true, null, true, false, null, false, null, true); + offering = _configMgr.createNetworkOffering(NetworkOffering.DefaultIsolatedNetworkOffering, "Offering for Isolated networks with no Source Nat service", + TrafficType.Guest, null, true, Availability.Optional, null, defaultIsolatedNetworkOfferingProviders, true, Network.GuestType.Isolated, false, null, + true, null, true, false, null, false, null, true); offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } @@ -504,10 +494,9 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra internalLbOffProviders.put(Service.SourceNat, defaultVpcProvider); if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworksWithInternalLB) == null) { - offering = - _configMgr.createNetworkOffering(NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworksWithInternalLB, - "Offering for Isolated VPC networks with Internal Lb support", TrafficType.Guest, null, false, Availability.Optional, null, - internalLbOffProviders, true, Network.GuestType.Isolated, false, null, false, null, false, false, null, false, null, true); + offering = _configMgr.createNetworkOffering(NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworksWithInternalLB, + "Offering for Isolated VPC networks with Internal Lb support", TrafficType.Guest, null, false, Availability.Optional, null, internalLbOffProviders, + true, Network.GuestType.Isolated, false, null, false, null, false, false, null, false, null, true); offering.setState(NetworkOffering.State.Enabled); offering.setInternalLb(true); offering.setPublicLb(false); @@ -537,8 +526,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra serviceCapabilityMap.put(Service.StaticNat, eip); if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultSharedEIPandELBNetworkOffering) == null) { - offering = - _configMgr.createNetworkOffering(NetworkOffering.DefaultSharedEIPandELBNetworkOffering, + offering = _configMgr.createNetworkOffering(NetworkOffering.DefaultSharedEIPandELBNetworkOffering, "Offering for Shared networks with Elastic IP and Elastic LB capabilities", TrafficType.Guest, null, true, Availability.Optional, null, netscalerServiceProviders, true, Network.GuestType.Shared, false, null, true, serviceCapabilityMap, true, false, null, false, null, true); offering.setState(NetworkOffering.State.Enabled); @@ -569,9 +557,8 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra SearchBuilder podVlanMapSB = _podVlanMapDao.createSearchBuilder(); podVlanMapSB.and("podId", podVlanMapSB.entity().getPodId(), Op.EQ); AssignIpAddressFromPodVlanSearch.join("podVlanMapSB", podVlanMapSB, podVlanMapSB.entity().getVlanDbId(), AssignIpAddressFromPodVlanSearch.entity().getVlanId(), - JoinType.INNER); - AssignIpAddressFromPodVlanSearch.join("vlan", podVlanSearch, podVlanSearch.entity().getId(), AssignIpAddressFromPodVlanSearch.entity().getVlanId(), - JoinType.INNER); + JoinType.INNER); + AssignIpAddressFromPodVlanSearch.join("vlan", podVlanSearch, podVlanSearch.entity().getId(), AssignIpAddressFromPodVlanSearch.entity().getVlanId(), JoinType.INNER); AssignIpAddressFromPodVlanSearch.done(); @@ -603,15 +590,15 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra @Override public List setupNetwork(Account owner, NetworkOffering offering, DeploymentPlan plan, String name, String displayText, boolean isDefault) - throws ConcurrentOperationException { + throws ConcurrentOperationException { return setupNetwork(owner, offering, null, plan, name, displayText, false, null, null, null, null, true); } @Override @DB - public List setupNetwork(final Account owner, final NetworkOffering offering, final Network predefined, final DeploymentPlan plan, - final String name, final String displayText, boolean errorIfAlreadySetup, final Long domainId, final ACLType aclType, final Boolean subdomainAccess, - final Long vpcId, final Boolean isDisplayNetworkEnabled) throws ConcurrentOperationException { + public List setupNetwork(final Account owner, final NetworkOffering offering, final Network predefined, final DeploymentPlan plan, final String name, + final String displayText, boolean errorIfAlreadySetup, final Long domainId, final ACLType aclType, final Boolean subdomainAccess, final Long vpcId, + final Boolean isDisplayNetworkEnabled) throws ConcurrentOperationException { Account locked = _accountDao.acquireInLockTable(owner.getId()); if (locked == null) { @@ -619,9 +606,10 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra } try { - if (predefined == null || - (offering.getTrafficType() != TrafficType.Guest && predefined.getCidr() == null && predefined.getBroadcastUri() == null && !(predefined.getBroadcastDomainType() == BroadcastDomainType.Vlan || - predefined.getBroadcastDomainType() == BroadcastDomainType.Lswitch || predefined.getBroadcastDomainType() == BroadcastDomainType.Vxlan))) { + if (predefined == null + || (offering.getTrafficType() != TrafficType.Guest && predefined.getCidr() == null && predefined.getBroadcastUri() == null && !(predefined + .getBroadcastDomainType() == BroadcastDomainType.Vlan || predefined.getBroadcastDomainType() == BroadcastDomainType.Lswitch || predefined + .getBroadcastDomainType() == BroadcastDomainType.Vxlan))) { List configs = _networksDao.listBy(owner.getId(), offering.getId(), plan.getDataCenterId()); if (configs.size() > 0) { if (s_logger.isDebugEnabled()) { @@ -629,8 +617,8 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra } if (errorIfAlreadySetup) { - InvalidParameterValueException ex = - new InvalidParameterValueException("Found existing network configuration (with specified id) for offering (with specified id)"); + InvalidParameterValueException ex = new InvalidParameterValueException( + "Found existing network configuration (with specified id) for offering (with specified id)"); ex.addProxyObject(offering.getUuid(), "offeringId"); ex.addProxyObject(configs.get(0).getUuid(), "networkConfigId"); throw ex; @@ -644,7 +632,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra long related = -1; - for (final NetworkGuru guru : _networkGurus) { + for (final NetworkGuru guru : networkGurus) { final Network network = guru.design(offering, plan, predefined, owner); if (network == null) { continue; @@ -668,13 +656,11 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra Transaction.execute(new TransactionCallbackNoReturn() { @Override public void doInTransactionWithoutResult(TransactionStatus status) { - NetworkVO vo = - new NetworkVO(id, network, offering.getId(), guru.getName(), owner.getDomainId(), owner.getId(), relatedFile, name, displayText, - predefined.getNetworkDomain(), offering.getGuestType(), plan.getDataCenterId(), plan.getPhysicalNetworkId(), aclType, - offering.getSpecifyIpRanges(), vpcId); + NetworkVO vo = new NetworkVO(id, network, offering.getId(), guru.getName(), owner.getDomainId(), owner.getId(), relatedFile, name, displayText, predefined + .getNetworkDomain(), offering.getGuestType(), plan.getDataCenterId(), plan.getPhysicalNetworkId(), aclType, offering.getSpecifyIpRanges(), vpcId); vo.setDisplayNetwork(isDisplayNetworkEnabled == null ? true : isDisplayNetworkEnabled); networks.add(_networksDao.persist(vo, vo.getGuestType() == Network.GuestType.Isolated, - finalizeServicesAndProvidersForNetwork(offering, plan.getPhysicalNetworkId()))); + finalizeServicesAndProvidersForNetwork(offering, plan.getPhysicalNetworkId()))); if (domainId != null && aclType == ACLType.Domain) { _networksDao.addDomainToNetwork(id, domainId, subdomainAccess == null ? true : subdomainAccess); @@ -700,7 +686,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra @Override @DB public void allocate(final VirtualMachineProfile vm, final LinkedHashMap networks) throws InsufficientCapacityException, - ConcurrentOperationException { + ConcurrentOperationException { Transaction.execute(new TransactionCallbackWithExceptionNoReturn() { @Override @@ -772,11 +758,11 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra @DB @Override public Pair allocateNic(NicProfile requested, Network network, Boolean isDefaultNic, int deviceId, VirtualMachineProfile vm) - throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException, ConcurrentOperationException { + throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException, ConcurrentOperationException { NetworkVO ntwkVO = _networksDao.findById(network.getId()); s_logger.debug("Allocating nic for vm " + vm.getVirtualMachine() + " in network " + network + " with requested profile " + requested); - NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, ntwkVO.getGuruName()); + NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, ntwkVO.getGuruName()); if (requested != null && requested.getMode() == null) { requested.setMode(network.getMode()); @@ -803,8 +789,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra vo = _nicDao.persist(vo); Integer networkRate = _networkModel.getNetworkRate(network.getId(), vm.getId()); - NicProfile vmNic = - new NicProfile(vo, network, vo.getBroadcastUri(), vo.getIsolationUri(), networkRate, _networkModel.isSecurityGroupSupportedInNetwork(network), + NicProfile vmNic = new NicProfile(vo, network, vo.getBroadcastUri(), vo.getIsolationUri(), networkRate, _networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vm.getHypervisorType(), network)); return new Pair(vmNic, Integer.valueOf(deviceId)); @@ -919,11 +904,11 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra @Override @DB public Pair implementNetwork(long networkId, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException, InsufficientCapacityException { + ResourceUnavailableException, InsufficientCapacityException { Pair implemented = new Pair(null, null); NetworkVO network = _networksDao.findById(networkId); - NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, network.getGuruName()); + NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, network.getGuruName()); if (isNetworkImplemented(network)) { s_logger.debug("Network id=" + networkId + " is already implemented"); implemented.set(guru, network); @@ -1018,7 +1003,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra @Override public void implementNetworkElementsAndResources(DeployDestination dest, ReservationContext context, Network network, NetworkOffering offering) - throws ConcurrentOperationException, InsufficientAddressCapacityException, ResourceUnavailableException, InsufficientCapacityException { + throws ConcurrentOperationException, InsufficientAddressCapacityException, ResourceUnavailableException, InsufficientCapacityException { // Associate a source NAT IP (if one isn't already associated with the network) if this is a // 1) 'Isolated' or 'Shared' guest virtual network in the advance zone @@ -1028,9 +1013,8 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra boolean sharedSourceNat = offering.getSharedSourceNat(); DataCenter zone = _dcDao.findById(network.getDataCenterId()); - if (!sharedSourceNat && - _networkModel.areServicesSupportedInNetwork(network.getId(), Service.SourceNat) && - (network.getGuestType() == Network.GuestType.Isolated || (network.getGuestType() == Network.GuestType.Shared && zone.getNetworkType() == NetworkType.Advanced))) { + if (!sharedSourceNat && _networkModel.areServicesSupportedInNetwork(network.getId(), Service.SourceNat) + && (network.getGuestType() == Network.GuestType.Isolated || (network.getGuestType() == Network.GuestType.Shared && zone.getNetworkType() == NetworkType.Advanced))) { List ips = null; Account owner = _entityMgr.findById(Account.class, network.getAccountId()); @@ -1051,15 +1035,15 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra } // get providers to implement List providersToImplement = getNetworkProviders(network.getId()); - for (NetworkElement element : _networkElements) { + for (NetworkElement element : networkElements) { if (providersToImplement.contains(element.getProvider())) { if (!_networkModel.isProviderEnabledInPhysicalNetwork(_networkModel.getPhysicalNetworkId(network), element.getProvider().getName())) { // The physicalNetworkId will not get translated into a uuid by the reponse serializer, // because the serializer would look up the NetworkVO class's table and retrieve the // network id instead of the physical network id. // So just throw this exception as is. We may need to TBD by changing the serializer. - throw new CloudRuntimeException("Service provider " + element.getProvider().getName() + - " either doesn't exist or is not enabled in physical network id: " + network.getPhysicalNetworkId()); + throw new CloudRuntimeException("Service provider " + element.getProvider().getName() + " either doesn't exist or is not enabled in physical network id: " + + network.getPhysicalNetworkId()); } if (s_logger.isDebugEnabled()) { @@ -1067,8 +1051,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra } if (!element.implement(network, offering, dest, context)) { - CloudRuntimeException ex = - new CloudRuntimeException("Failed to implement provider " + element.getProvider().getName() + " for network with specified id"); + CloudRuntimeException ex = new CloudRuntimeException("Failed to implement provider " + element.getProvider().getName() + " for network with specified id"); ex.addProxyObject(network.getUuid(), "networkId"); throw ex; } @@ -1080,8 +1063,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra if (!reprogramNetworkRules(network.getId(), CallContext.current().getCallingAccount(), network)) { s_logger.warn("Failed to re-program the network as a part of network " + network + " implement"); // see DataCenterVO.java - ResourceUnavailableException ex = - new ResourceUnavailableException("Unable to apply network rules as a part of network " + network + " implement", DataCenter.class, + ResourceUnavailableException ex = new ResourceUnavailableException("Unable to apply network rules as a part of network " + network + " implement", DataCenter.class, network.getDataCenterId()); ex.addProxyObject(_entityMgr.findById(DataCenter.class, network.getDataCenterId()).getUuid()); throw ex; @@ -1114,9 +1096,8 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId()); //there are no egress rules then apply the default egress rule DataCenter zone = _dcDao.findById(network.getDataCenterId()); - if ( _networkModel.areServicesSupportedInNetwork(network.getId(), Service.Firewall) && - _networkModel.areServicesSupportedInNetwork(network.getId(), Service.Firewall) && - (network.getGuestType() == Network.GuestType.Isolated || (network.getGuestType() == Network.GuestType.Shared && zone.getNetworkType() == NetworkType.Advanced))) { + if (_networkModel.areServicesSupportedInNetwork(network.getId(), Service.Firewall) && _networkModel.areServicesSupportedInNetwork(network.getId(), Service.Firewall) + && (network.getGuestType() == Network.GuestType.Isolated || (network.getGuestType() == Network.GuestType.Shared && zone.getNetworkType() == NetworkType.Advanced))) { // add default egress rule to accept the traffic _firewallMgr.applyDefaultEgressFirewallRule(network.getId(), offering.getEgressDefaultPolicy(), true); } @@ -1125,7 +1106,6 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra success = false; } - // apply port forwarding rules if (!_rulesMgr.applyPortForwardingRulesForNetwork(networkId, false, caller)) { s_logger.warn("Failed to reapply port forwarding rule(s) as a part of network id=" + networkId + " restart"); @@ -1172,11 +1152,11 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra } protected boolean prepareElement(NetworkElement element, Network network, NicProfile profile, VirtualMachineProfile vmProfile, DeployDestination dest, - ReservationContext context) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException { + ReservationContext context) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException { element.prepare(network, profile, vmProfile, dest, context); if (vmProfile.getType() == Type.User && element.getProvider() != null) { - if (_networkModel.areServicesSupportedInNetwork(network.getId(), Service.Dhcp) && - _networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.Dhcp, element.getProvider()) && element instanceof DhcpServiceProvider) { + if (_networkModel.areServicesSupportedInNetwork(network.getId(), Service.Dhcp) + && _networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.Dhcp, element.getProvider()) && element instanceof DhcpServiceProvider) { DhcpServiceProvider sp = (DhcpServiceProvider)element; Map dhcpCapabilities = element.getCapabilities().get(Service.Dhcp); String supportsMultipleSubnets = dhcpCapabilities.get(Capability.DhcpAccrossMultipleSubnets); @@ -1187,8 +1167,8 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra } sp.addDhcpEntry(network, profile, vmProfile, dest, context); } - if (_networkModel.areServicesSupportedInNetwork(network.getId(), Service.UserData) && - _networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.UserData, element.getProvider()) && element instanceof UserDataServiceProvider) { + if (_networkModel.areServicesSupportedInNetwork(network.getId(), Service.UserData) + && _networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.UserData, element.getProvider()) && element instanceof UserDataServiceProvider) { UserDataServiceProvider sp = (UserDataServiceProvider)element; sp.addPasswordAndUserdata(network, profile, vmProfile, dest, context); } @@ -1208,8 +1188,8 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra _networksDao.changeActiveNicsBy(networkId, count); } - if (nic.getVmType() == VirtualMachine.Type.User || - (nic.getVmType() == VirtualMachine.Type.DomainRouter && _networksDao.findById(networkId).getTrafficType() == TrafficType.Guest)) { + if (nic.getVmType() == VirtualMachine.Type.User + || (nic.getVmType() == VirtualMachine.Type.DomainRouter && _networksDao.findById(networkId).getTrafficType() == TrafficType.Guest)) { _networksDao.setCheckForGc(networkId); } } @@ -1217,8 +1197,8 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra } @Override - public void prepare(VirtualMachineProfile vmProfile, DeployDestination dest, ReservationContext context) throws InsufficientCapacityException, - ConcurrentOperationException, ResourceUnavailableException { + public void prepare(VirtualMachineProfile vmProfile, DeployDestination dest, ReservationContext context) throws InsufficientCapacityException, ConcurrentOperationException, + ResourceUnavailableException { List nics = _nicDao.listByVmId(vmProfile.getId()); // we have to implement default nics first - to ensure that default network elements start up first in multiple @@ -1250,11 +1230,11 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra @Override public NicProfile prepareNic(VirtualMachineProfile vmProfile, DeployDestination dest, ReservationContext context, long nicId, Network network) - throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException, ConcurrentOperationException, InsufficientCapacityException, - ResourceUnavailableException { + throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException, ConcurrentOperationException, InsufficientCapacityException, + ResourceUnavailableException { Integer networkRate = _networkModel.getNetworkRate(network.getId(), vmProfile.getId()); - NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, network.getGuruName()); + NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, network.getGuruName()); NicVO nic = _nicDao.findById(nicId); NicProfile profile = null; @@ -1290,8 +1270,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra updateNic(nic, network.getId(), 1); } else { - profile = - new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), networkRate, _networkModel.isSecurityGroupSupportedInNetwork(network), + profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), networkRate, _networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vmProfile.getHypervisorType(), network)); guru.updateNicProfile(profile, network); nic.setState(Nic.State.Reserved); @@ -1299,18 +1278,17 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra } List providersToImplement = getNetworkProviders(network.getId()); - for (NetworkElement element : _networkElements) { + for (NetworkElement element : networkElements) { if (providersToImplement.contains(element.getProvider())) { if (!_networkModel.isProviderEnabledInPhysicalNetwork(_networkModel.getPhysicalNetworkId(network), element.getProvider().getName())) { - throw new CloudRuntimeException("Service provider " + element.getProvider().getName() + - " either doesn't exist or is not enabled in physical network id: " + network.getPhysicalNetworkId()); + throw new CloudRuntimeException("Service provider " + element.getProvider().getName() + " either doesn't exist or is not enabled in physical network id: " + + network.getPhysicalNetworkId()); } if (s_logger.isDebugEnabled()) { s_logger.debug("Asking " + element.getName() + " to prepare for " + nic); } if (!prepareElement(element, network, profile, vmProfile, dest, context)) { - throw new InsufficientAddressCapacityException("unable to configure the dhcp service, due to insufficiant address capacity", Network.class, - network.getId()); + throw new InsufficientAddressCapacityException("unable to configure the dhcp service, due to insufficiant address capacity", Network.class, network.getId()); } } } @@ -1328,9 +1306,8 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra NetworkVO network = _networksDao.findById(nic.getNetworkId()); Integer networkRate = _networkModel.getNetworkRate(network.getId(), vm.getId()); - NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, network.getGuruName()); - NicProfile profile = - new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), networkRate, _networkModel.isSecurityGroupSupportedInNetwork(network), + NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, network.getGuruName()); + NicProfile profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), networkRate, _networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vm.getHypervisorType(), network)); if (guru instanceof NetworkMigrationResponder) { if (!((NetworkMigrationResponder)guru).prepareMigration(profile, network, vm, dest, context)) { @@ -1338,11 +1315,11 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra } } List providersToImplement = getNetworkProviders(network.getId()); - for (NetworkElement element : _networkElements) { + for (NetworkElement element : networkElements) { if (providersToImplement.contains(element.getProvider())) { if (!_networkModel.isProviderEnabledInPhysicalNetwork(_networkModel.getPhysicalNetworkId(network), element.getProvider().getName())) { - throw new CloudRuntimeException("Service provider " + element.getProvider().getName() + - " either doesn't exist or is not enabled in physical network id: " + network.getPhysicalNetworkId()); + throw new CloudRuntimeException("Service provider " + element.getProvider().getName() + " either doesn't exist or is not enabled in physical network id: " + + network.getPhysicalNetworkId()); } if (element instanceof NetworkMigrationResponder) { if (!((NetworkMigrationResponder)element).prepareMigration(profile, network, vm, dest, context)) { @@ -1369,7 +1346,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra public void commitNicForMigration(VirtualMachineProfile src, VirtualMachineProfile dst) { for (NicProfile nicSrc : src.getNics()) { NetworkVO network = _networksDao.findById(nicSrc.getNetworkId()); - NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, network.getGuruName()); + NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, network.getGuruName()); NicProfile nicDst = findNicProfileById(dst, nicSrc.getId()); ReservationContext src_context = new ReservationContextImpl(nicSrc.getReservationId(), null, null); ReservationContext dst_context = new ReservationContextImpl(nicDst.getReservationId(), null, null); @@ -1378,11 +1355,11 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra ((NetworkMigrationResponder)guru).commitMigration(nicSrc, network, src, src_context, dst_context); } List providersToImplement = getNetworkProviders(network.getId()); - for (NetworkElement element : _networkElements) { + for (NetworkElement element : networkElements) { if (providersToImplement.contains(element.getProvider())) { if (!_networkModel.isProviderEnabledInPhysicalNetwork(_networkModel.getPhysicalNetworkId(network), element.getProvider().getName())) { - throw new CloudRuntimeException("Service provider " + element.getProvider().getName() + - " either doesn't exist or is not enabled in physical network id: " + network.getPhysicalNetworkId()); + throw new CloudRuntimeException("Service provider " + element.getProvider().getName() + " either doesn't exist or is not enabled in physical network id: " + + network.getPhysicalNetworkId()); } if (element instanceof NetworkMigrationResponder) { ((NetworkMigrationResponder)element).commitMigration(nicSrc, network, src, src_context, dst_context); @@ -1400,7 +1377,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra public void rollbackNicForMigration(VirtualMachineProfile src, VirtualMachineProfile dst) { for (NicProfile nicDst : dst.getNics()) { NetworkVO network = _networksDao.findById(nicDst.getNetworkId()); - NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, network.getGuruName()); + NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, network.getGuruName()); NicProfile nicSrc = findNicProfileById(src, nicDst.getId()); ReservationContext src_context = new ReservationContextImpl(nicSrc.getReservationId(), null, null); ReservationContext dst_context = new ReservationContextImpl(nicDst.getReservationId(), null, null); @@ -1409,11 +1386,11 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra ((NetworkMigrationResponder)guru).rollbackMigration(nicDst, network, dst, src_context, dst_context); } List providersToImplement = getNetworkProviders(network.getId()); - for (NetworkElement element : _networkElements) { + for (NetworkElement element : networkElements) { if (providersToImplement.contains(element.getProvider())) { if (!_networkModel.isProviderEnabledInPhysicalNetwork(_networkModel.getPhysicalNetworkId(network), element.getProvider().getName())) { - throw new CloudRuntimeException("Service provider " + element.getProvider().getName() + - " either doesn't exist or is not enabled in physical network id: " + network.getPhysicalNetworkId()); + throw new CloudRuntimeException("Service provider " + element.getProvider().getName() + " either doesn't exist or is not enabled in physical network id: " + + network.getPhysicalNetworkId()); } if (element instanceof NetworkMigrationResponder) { ((NetworkMigrationResponder)element).rollbackMigration(nicDst, network, dst, src_context, dst_context); @@ -1453,12 +1430,11 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra if (originalState == Nic.State.Reserved || originalState == Nic.State.Reserving) { if (nic.getReservationStrategy() == Nic.ReservationStrategy.Start) { - NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, network.getGuruName()); + NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, network.getGuruName()); nic.setState(Nic.State.Releasing); _nicDao.update(nic.getId(), nic); - NicProfile profile = - new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), null, _networkModel.isSecurityGroupSupportedInNetwork(network), - _networkModel.getNetworkTag(vmProfile.getHypervisorType(), network)); + NicProfile profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), null, _networkModel + .isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vmProfile.getHypervisorType(), network)); if (guru.release(profile, vmProfile, nic.getReservationId())) { applyProfileToNicForRelease(nic, profile); nic.setState(Nic.State.Allocated); @@ -1484,11 +1460,11 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra Network network = networkToRelease.first(); NicProfile profile = networkToRelease.second(); List providersToImplement = getNetworkProviders(network.getId()); - for (NetworkElement element : _networkElements) { + for (NetworkElement element : networkElements) { if (providersToImplement.contains(element.getProvider())) { if (!_networkModel.isProviderEnabledInPhysicalNetwork(_networkModel.getPhysicalNetworkId(network), element.getProvider().getName())) { - throw new CloudRuntimeException("Service provider " + element.getProvider().getName() + - " either doesn't exist or is not enabled in physical network id: " + network.getPhysicalNetworkId()); + throw new CloudRuntimeException("Service provider " + element.getProvider().getName() + " either doesn't exist or is not enabled in physical network id: " + + network.getPhysicalNetworkId()); } if (s_logger.isDebugEnabled()) { s_logger.debug("Asking " + element.getName() + " to release " + profile); @@ -1519,12 +1495,22 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra } protected void removeNic(VirtualMachineProfile vm, NicVO nic) { + + if (nic.getReservationStrategy() == Nic.ReservationStrategy.Start && nic.getState() != Nic.State.Allocated) { + // Nics with reservation strategy 'Start' should go through release phase in the Nic life cycle. + // Ensure that release is performed before Nic is to be removed to avoid resource leaks. + try { + releaseNic(vm, nic.getId()); + } catch (Exception ex) { + s_logger.warn("Failed to release nic: " + nic.toString() + " as part of remove operation due to", ex); + } + } + nic.setState(Nic.State.Deallocating); _nicDao.update(nic.getId(), nic); NetworkVO network = _networksDao.findById(nic.getNetworkId()); - NicProfile profile = - new NicProfile(nic, network, null, null, null, _networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vm.getHypervisorType(), - network)); + NicProfile profile = new NicProfile(nic, network, null, null, null, _networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag( + vm.getHypervisorType(), network)); /* * We need to release the nics with a Create ReservationStrategy here @@ -1532,11 +1518,11 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra */ if (nic.getReservationStrategy() == Nic.ReservationStrategy.Create) { List providersToImplement = getNetworkProviders(network.getId()); - for (NetworkElement element : _networkElements) { + for (NetworkElement element : networkElements) { if (providersToImplement.contains(element.getProvider())) { if (!_networkModel.isProviderEnabledInPhysicalNetwork(_networkModel.getPhysicalNetworkId(network), element.getProvider().getName())) { - throw new CloudRuntimeException("Service provider " + element.getProvider().getName() + - " either doesn't exist or is not enabled in physical network id: " + network.getPhysicalNetworkId()); + throw new CloudRuntimeException("Service provider " + element.getProvider().getName() + " either doesn't exist or is not enabled in physical network id: " + + network.getPhysicalNetworkId()); } if (s_logger.isDebugEnabled()) { s_logger.debug("Asking " + element.getName() + " to release " + nic); @@ -1553,11 +1539,11 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra } // remove the dhcpservice ip if this is the last nic in subnet. - if (vm.getType() == Type.User && isDhcpAccrossMultipleSubnetsSupported(network) && isLastNicInSubnet(nic) && network.getTrafficType() == TrafficType.Guest && - network.getGuestType() == GuestType.Shared) { + if (vm.getType() == Type.User && isDhcpAccrossMultipleSubnetsSupported(network) && isLastNicInSubnet(nic) && network.getTrafficType() == TrafficType.Guest + && network.getGuestType() == GuestType.Shared) { removeDhcpServiceInSubnet(nic); } - NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, network.getGuruName()); + NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, network.getGuruName()); guru.deallocate(network, profile, vm); _nicDao.remove(nic.getId()); s_logger.debug("Removed nic id=" + nic.getId()); @@ -1627,9 +1613,9 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra @Override @DB public Network createGuestNetwork(long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId, - String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk, final long zoneId, final ACLType aclType, Boolean subdomainAccess, - final Long vpcId, final String ip6Gateway, final String ip6Cidr, final Boolean isDisplayNetworkEnabled, final String isolatedPvlan) - throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException { + String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk, final long zoneId, final ACLType aclType, Boolean subdomainAccess, + final Long vpcId, final String ip6Gateway, final String ip6Cidr, final Boolean isDisplayNetworkEnabled, final String isolatedPvlan) + throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException { final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId); // this method supports only guest network creation @@ -1641,14 +1627,13 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType); //check resource limits if (updateResourceCount) { - _resourceLimitMgr.checkResourceLimit(owner, ResourceType.network); + _resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled); } // Validate network offering if (ntwkOff.getState() != NetworkOffering.State.Enabled) { // see NetworkOfferingVO - InvalidParameterValueException ex = - new InvalidParameterValueException("Can't use specified network offering id as its stat is not " + NetworkOffering.State.Enabled); + InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its stat is not " + NetworkOffering.State.Enabled); ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId"); throw ex; } @@ -1686,8 +1671,8 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra // if zone is basic, only Shared network offerings w/o source nat service are allowed if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) { - throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + - " with disabled " + Service.SourceNat.getName() + " service are allowed"); + throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled " + + Service.SourceNat.getName() + " service are allowed"); } if (domainId == null || domainId != Domain.ROOT_DOMAIN) { @@ -1749,8 +1734,8 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra if (vlanSpecified) { //don't allow to specify vlan tag used by physical network for dynamic vlan allocation if (_dcDao.findVnet(zoneId, pNtwk.getId(), vlanId).size() > 0) { - throw new InvalidParameterValueException("The VLAN tag " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone " + - zone.getName()); + throw new InvalidParameterValueException("The VLAN tag " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone " + + zone.getName()); } String uri = BroadcastDomainType.fromString(vlanId).toString(); // For Isolated networks, don't allow to create network with vlan that already exists in the zone @@ -1777,8 +1762,8 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId()); int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId()); if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) { - throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + - " to the vlan range dedicated to the owner " + owner.getAccountName()); + throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner " + + owner.getAccountName()); } } } @@ -1787,8 +1772,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra } else { // don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or // shared network with same Vlan ID in the zone - if (_networksDao.countByZoneUriAndGuestType(zoneId, uri, GuestType.Isolated) > 0 || - _networksDao.countByZoneUriAndGuestType(zoneId, uri, GuestType.Shared) > 0) { + if (_networksDao.countByZoneUriAndGuestType(zoneId, uri, GuestType.Isolated) > 0 || _networksDao.countByZoneUriAndGuestType(zoneId, uri, GuestType.Shared) > 0) { throw new InvalidParameterValueException("There is a isolated/shared network with vlan id: " + vlanId + " already exists " + "in zone " + zoneId); } } @@ -1797,8 +1781,8 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra // If networkDomain is not specified, take it from the global configuration if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) { - Map dnsCapabilities = - _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId), Service.Dns); + Map dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId), + Service.Dns); String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification); if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) { if (networkDomain != null) { @@ -1823,8 +1807,8 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra // validate network domain if (!NetUtils.verifyDomainName(networkDomain)) { throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain " - + "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " - + "and the hyphen ('-'); can't start or end with \"-\""); + + "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " + + "and the hyphen ('-'); can't start or end with \"-\""); } } } @@ -1833,14 +1817,13 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra // In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x // limitation, remove after we introduce support for multiple ip ranges // with different Cidrs for the same Shared network - boolean cidrRequired = - zone.getNetworkType() == NetworkType.Advanced && - ntwkOff.getTrafficType() == TrafficType.Guest && - (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated && !_networkModel.areServicesSupportedByNetworkOffering( - ntwkOff.getId(), Service.SourceNat))); + boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced + && ntwkOff.getTrafficType() == TrafficType.Guest + && (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated && !_networkModel.areServicesSupportedByNetworkOffering( + ntwkOff.getId(), Service.SourceNat))); if (cidr == null && ip6Cidr == null && cidrRequired) { - throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared + - " and network of type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled"); + throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared + + " and network of type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled"); } // No cidr can be specified in Basic zone @@ -1897,8 +1880,8 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra } } - List networks = - setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId, isDisplayNetworkEnabled); + List networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId, + isDisplayNetworkEnabled); Network network = null; if (networks == null || networks.isEmpty()) { @@ -1919,7 +1902,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra } if (updateResourceCount) { - _resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network); + _resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled); } return network; @@ -1989,7 +1972,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra if (s_logger.isDebugEnabled()) { s_logger.debug("Network id=" + networkId + " is shutdown successfully, cleaning up corresponding resources now."); } - NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, networkFinal.getGuruName()); + NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, networkFinal.getGuruName()); NetworkProfile profile = convertNetworkToNetworkProfile(networkFinal.getId()); guru.shutdown(profile, _networkOfferingDao.findById(networkFinal.getNetworkOfferingId())); @@ -2053,12 +2036,12 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra // get providers to shutdown List providersToShutdown = getNetworkProviders(network.getId()); boolean success = true; - for (NetworkElement element : _networkElements) { + for (NetworkElement element : networkElements) { if (providersToShutdown.contains(element.getProvider())) { try { if (!_networkModel.isProviderEnabledInPhysicalNetwork(_networkModel.getPhysicalNetworkId(network), element.getProvider().getName())) { - s_logger.warn("Unable to complete shutdown of the network elements due to element: " + element.getName() + - " either doesn't exist or not enabled in the physical network " + _networkModel.getPhysicalNetworkId(network)); + s_logger.warn("Unable to complete shutdown of the network elements due to element: " + element.getName() + + " either doesn't exist or not enabled in the physical network " + _networkModel.getPhysicalNetworkId(network)); success = false; } if (s_logger.isDebugEnabled()) { @@ -2085,7 +2068,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra @Override @DB - public boolean destroyNetwork(long networkId, final ReservationContext context) { + public boolean destroyNetwork(long networkId, final ReservationContext context, boolean forced) { final Account callerAccount = context.getAccount(); NetworkVO network = _networksDao.findById(networkId); @@ -2128,7 +2111,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra // get updated state for the network network = _networksDao.findById(networkId); - if (network.getState() != Network.State.Allocated && network.getState() != Network.State.Setup) { + if (network.getState() != Network.State.Allocated && network.getState() != Network.State.Setup && !forced) { s_logger.debug("Network is not not in the correct state to be destroyed: " + network.getState()); return false; } @@ -2141,12 +2124,12 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra // get providers to destroy List providersToDestroy = getNetworkProviders(network.getId()); - for (NetworkElement element : _networkElements) { + for (NetworkElement element : networkElements) { if (providersToDestroy.contains(element.getProvider())) { try { if (!_networkModel.isProviderEnabledInPhysicalNetwork(_networkModel.getPhysicalNetworkId(network), element.getProvider().getName())) { - s_logger.warn("Unable to complete destroy of the network elements due to element: " + element.getName() + - " either doesn't exist or not enabled in the physical network " + _networkModel.getPhysicalNetworkId(network)); + s_logger.warn("Unable to complete destroy of the network elements due to element: " + element.getName() + + " either doesn't exist or not enabled in the physical network " + _networkModel.getPhysicalNetworkId(network)); success = false; } @@ -2181,7 +2164,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra Transaction.execute(new TransactionCallbackNoReturn() { @Override public void doInTransactionWithoutResult(TransactionStatus status) { - NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, networkFinal.getGuruName()); + NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, networkFinal.getGuruName()); guru.trash(networkFinal, _networkOfferingDao.findById(networkFinal.getNetworkOfferingId())); @@ -2208,7 +2191,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra NetworkOffering ntwkOff = _entityMgr.findById(NetworkOffering.class, networkFinal.getNetworkOfferingId()); boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, networkFinal.getAclType()); if (updateResourceCount) { - _resourceLimitMgr.decrementResourceCount(networkFinal.getAccountId(), ResourceType.network); + _resourceLimitMgr.decrementResourceCount(networkFinal.getAccountId(), ResourceType.network, networkFinal.getDisplayNetwork()); } } } @@ -2223,7 +2206,8 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra return success; } - private boolean resourceCountNeedsUpdate(NetworkOffering ntwkOff, ACLType aclType) { + @Override + public boolean resourceCountNeedsUpdate(NetworkOffering ntwkOff, ACLType aclType) { //Update resource count only for Isolated account specific non-system networks boolean updateResourceCount = (ntwkOff.getGuestType() == GuestType.Isolated && !ntwkOff.isSystemOnly() && aclType == ACLType.Account); return updateResourceCount; @@ -2331,7 +2315,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra @Override public boolean startNetwork(long networkId, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, - InsufficientCapacityException { + InsufficientCapacityException { // Check if network exists NetworkVO network = _networksDao.findById(networkId); @@ -2353,8 +2337,8 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra } @Override - public boolean restartNetwork(Long networkId, Account callerAccount, User callerUser, boolean cleanup) throws ConcurrentOperationException, - ResourceUnavailableException, InsufficientCapacityException { + public boolean restartNetwork(Long networkId, Account callerAccount, User callerUser, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException, + InsufficientCapacityException { NetworkVO network = _networksDao.findById(networkId); @@ -2405,7 +2389,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra @Override public NetworkProfile convertNetworkToNetworkProfile(long networkId) { NetworkVO network = _networksDao.findById(networkId); - NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, network.getGuruName()); + NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, network.getGuruName()); NetworkProfile profile = new NetworkProfile(network); guru.updateNetworkProfile(profile); @@ -2452,8 +2436,8 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra protected boolean isSharedNetworkWithServices(Network network) { assert (network != null); DataCenter zone = _entityMgr.findById(DataCenter.class, network.getDataCenterId()); - if (network.getGuestType() == Network.GuestType.Shared && zone.getNetworkType() == NetworkType.Advanced && - isSharedNetworkOfferingWithServices(network.getNetworkOfferingId())) { + if (network.getGuestType() == Network.GuestType.Shared && zone.getNetworkType() == NetworkType.Advanced + && isSharedNetworkOfferingWithServices(network.getNetworkOfferingId())) { return true; } return false; @@ -2461,24 +2445,24 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra protected boolean isSharedNetworkOfferingWithServices(long networkOfferingId) { NetworkOfferingVO networkOffering = _networkOfferingDao.findById(networkOfferingId); - if ((networkOffering.getGuestType() == Network.GuestType.Shared) && - (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.SourceNat) || - _networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.StaticNat) || - _networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Firewall) || - _networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.PortForwarding) || _networkModel.areServicesSupportedByNetworkOffering( - networkOfferingId, Service.Lb))) { + if ((networkOffering.getGuestType() == Network.GuestType.Shared) + && (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.SourceNat) + || _networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.StaticNat) + || _networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Firewall) + || _networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.PortForwarding) || _networkModel.areServicesSupportedByNetworkOffering( + networkOfferingId, Service.Lb))) { return true; } return false; } @Override - public List listVmNics(Long vmId, Long nicId) { + public List listVmNics(long vmId, Long nicId, Long networkId) { List result = null; - if (nicId == null) { + if (nicId == null && networkId == null) { result = _nicDao.listByVmId(vmId); } else { - result = _nicDao.listByVmIdAndNicId(vmId, nicId); + result = _nicDao.listByVmIdAndNicIdAndNtwkId(vmId, nicId, networkId); } return result; } @@ -2696,8 +2680,8 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra try { // delete default egress rule DataCenter zone = _dcDao.findById(network.getDataCenterId()); - if ( _networkModel.areServicesSupportedInNetwork(network.getId(), Service.Firewall) && - (network.getGuestType() == Network.GuestType.Isolated || (network.getGuestType() == Network.GuestType.Shared && zone.getNetworkType() == NetworkType.Advanced))) { + if (_networkModel.areServicesSupportedInNetwork(network.getId(), Service.Firewall) + && (network.getGuestType() == Network.GuestType.Isolated || (network.getGuestType() == Network.GuestType.Shared && zone.getNetworkType() == NetworkType.Advanced))) { // add default egress rule to accept the traffic _firewallMgr.applyDefaultEgressFirewallRule(network.getId(), _networkModel.getNetworkEgressDefaultPolicy(networkId), false); } @@ -2707,7 +2691,6 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra success = false; } - for (FirewallRuleVO firewallRule : firewallEgressRules) { s_logger.trace("Marking firewall egress rule " + firewallRule + " with Revoke state"); firewallRule.setState(FirewallRule.State.Revoke); @@ -2912,8 +2895,8 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra // check that provider is supported if (checkPhysicalNetwork) { if (!_pNSPDao.isServiceProviderEnabled(physicalNetworkId, provider, service)) { - throw new UnsupportedServiceException("Provider " + provider + " is either not enabled or doesn't " + "support service " + service + - " in physical network id=" + physicalNetworkId); + throw new UnsupportedServiceException("Provider " + provider + " is either not enabled or doesn't " + "support service " + service + " in physical network id=" + + physicalNetworkId); } } @@ -2969,8 +2952,8 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra @Override public NicProfile createNicForVm(Network network, NicProfile requested, ReservationContext context, VirtualMachineProfile vmProfile, boolean prepare) - throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException, ConcurrentOperationException, InsufficientCapacityException, - ResourceUnavailableException { + throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException, ConcurrentOperationException, InsufficientCapacityException, + ResourceUnavailableException { VirtualMachine vm = vmProfile.getVirtualMachine(); DataCenter dc = _entityMgr.findById(DataCenter.class, network.getDataCenterId()); @@ -3012,10 +2995,9 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra NetworkVO network = _networksDao.findById(nic.getNetworkId()); Integer networkRate = _networkModel.getNetworkRate(network.getId(), vm.getId()); - NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, network.getGuruName()); - NicProfile profile = - new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), networkRate, _networkModel.isSecurityGroupSupportedInNetwork(network), - _networkModel.getNetworkTag(vm.getHypervisorType(), network)); + NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, network.getGuruName()); + NicProfile profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), networkRate, + _networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vm.getHypervisorType(), network)); guru.updateNicProfile(profile, network); profiles.add(profile); } @@ -3157,9 +3139,9 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra } public static final ConfigKey NetworkGcWait = new ConfigKey(Integer.class, "network.gc.wait", "Advanced", "600", - "Time (in seconds) to wait before shutting down a network that's not in used", false); + "Time (in seconds) to wait before shutting down a network that's not in used", false); public static final ConfigKey NetworkGcInterval = new ConfigKey(Integer.class, "network.gc.interval", "Advanced", "600", - "Seconds to wait before checking for networks to shutdown", true); + "Seconds to wait before checking for networks to shutdown", true); @Override public ConfigKey[] getConfigKeys() { diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java b/engine/orchestration/src/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java index 7b0d968ab07..d51ed191b9d 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java @@ -38,6 +38,7 @@ import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotDataFactory; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; +import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotService; import org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator; import org.apache.cloudstack.engine.subsystem.api.storage.TemplateDataFactory; import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo; @@ -72,6 +73,8 @@ import com.cloud.exception.InsufficientStorageCapacityException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.StorageUnavailableException; import com.cloud.host.Host; +import com.cloud.host.HostVO; +import com.cloud.host.dao.HostDao; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.offering.DiskOffering; import com.cloud.offering.ServiceOffering; @@ -141,6 +144,10 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati SnapshotDataFactory snapshotFactory; @Inject ConfigDepot _configDepot; + @Inject + HostDao _hostDao; + @Inject + SnapshotService _snapshotSrv; private final StateMachine2 _volStateMachine; protected List _storagePoolAllocators; @@ -149,8 +156,8 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati return _storagePoolAllocators; } - public void setStoragePoolAllocators(List _storagePoolAllocators) { - this._storagePoolAllocators = _storagePoolAllocators; + public void setStoragePoolAllocators(List storagePoolAllocators) { + _storagePoolAllocators = storagePoolAllocators; } protected List _podAllocators; @@ -159,8 +166,8 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati return _podAllocators; } - public void setPodAllocators(List _podAllocators) { - this._podAllocators = _podAllocators; + public void setPodAllocators(List podAllocators) { + _podAllocators = podAllocators; } protected VolumeOrchestrator() { @@ -169,14 +176,13 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati @Override public VolumeInfo moveVolume(VolumeInfo volume, long destPoolDcId, Long destPoolPodId, Long destPoolClusterId, HypervisorType dataDiskHyperType) - throws ConcurrentOperationException, StorageUnavailableException { + throws ConcurrentOperationException, StorageUnavailableException { // Find a destination storage pool with the specified criteria DiskOffering diskOffering = _entityMgr.findById(DiskOffering.class, volume.getDiskOfferingId()); ; - DiskProfile dskCh = - new DiskProfile(volume.getId(), volume.getVolumeType(), volume.getName(), diskOffering.getId(), diskOffering.getDiskSize(), diskOffering.getTagsArray(), - diskOffering.getUseLocalStorage(), diskOffering.isRecreatable(), null); + DiskProfile dskCh = new DiskProfile(volume.getId(), volume.getVolumeType(), volume.getName(), diskOffering.getId(), diskOffering.getDiskSize(), + diskOffering.getTagsArray(), diskOffering.getUseLocalStorage(), diskOffering.isRecreatable(), null); dskCh.setHyperType(dataDiskHyperType); DataCenter destPoolDataCenter = _entityMgr.findById(DataCenter.class, destPoolDcId); Pod destPoolPod = _entityMgr.findById(Pod.class, destPoolPodId); @@ -197,8 +203,7 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati } public VolumeVO allocateDuplicateVolumeVO(Volume oldVol, Long templateId) { - VolumeVO newVol = - new VolumeVO(oldVol.getVolumeType(), oldVol.getName(), oldVol.getDataCenterId(), oldVol.getDomainId(), oldVol.getAccountId(), oldVol.getDiskOfferingId(), + VolumeVO newVol = new VolumeVO(oldVol.getVolumeType(), oldVol.getName(), oldVol.getDataCenterId(), oldVol.getDomainId(), oldVol.getAccountId(), oldVol.getDiskOfferingId(), oldVol.getSize(), oldVol.getMinIops(), oldVol.getMaxIops(), oldVol.get_iScsiName()); if (templateId != null) { newVol.setTemplateId(templateId); @@ -253,8 +258,7 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati @DB @Override - public VolumeInfo createVolumeFromSnapshot(Volume volume, Snapshot snapshot, UserVm vm) - throws StorageUnavailableException { + public VolumeInfo createVolumeFromSnapshot(Volume volume, Snapshot snapshot, UserVm vm) throws StorageUnavailableException { Account account = _entityMgr.findById(Account.class, volume.getAccountId()); final HashSet poolsToAvoid = new HashSet(); @@ -269,24 +273,24 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati String msg = "There are no available storage pools to store the volume in"; - if(vm != null){ + if (vm != null) { Pod podofVM = _entityMgr.findById(Pod.class, vm.getPodIdToDeployIn()); - if(podofVM != null){ + if (podofVM != null) { pod = new Pair(podofVM, podofVM.getId()); } } - if(vm != null && pod != null){ + if (vm != null && pod != null) { //if VM is running use the hostId to find the clusterID. If it is stopped, refer the cluster where the ROOT volume of the VM exists. Long hostId = null; Long clusterId = null; - if(vm.getState() == State.Running){ + if (vm.getState() == State.Running) { hostId = vm.getHostId(); - if(hostId != null){ + if (hostId != null) { Host vmHost = _entityMgr.findById(Host.class, hostId); clusterId = vmHost.getClusterId(); } - }else{ + } else { List rootVolumesOfVm = _volsDao.findByInstanceAndType(vm.getId(), Volume.Type.ROOT); if (rootVolumesOfVm.size() != 1) { throw new CloudRuntimeException("The VM " + vm.getHostName() + " has more than one ROOT volume and is in an invalid state. Please contact Cloud Support."); @@ -303,15 +307,15 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati if (pool == null) { //pool could not be found in the VM's pod/cluster. - if(s_logger.isDebugEnabled()){ - s_logger.debug("Could not find any storage pool to create Volume in the pod/cluster of the provided VM "+vm.getUuid()); + if (s_logger.isDebugEnabled()) { + s_logger.debug("Could not find any storage pool to create Volume in the pod/cluster of the provided VM " + vm.getUuid()); } StringBuilder addDetails = new StringBuilder(msg); addDetails.append(", Could not find any storage pool to create Volume in the pod/cluster of the VM "); addDetails.append(vm.getUuid()); msg = addDetails.toString(); } - }else{ + } else { // Determine what pod to store the volume in while ((pod = findPod(null, null, dc, account.getId(), podsToAvoid)) != null) { podsToAvoid.add(pod.first().getId()); @@ -319,6 +323,13 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati while ((pool = findStoragePool(dskCh, dc, pod.first(), null, null, null, poolsToAvoid)) != null) { break; } + + if (pool != null) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Found a suitable pool for create volume: " + pool.getId()); + } + break; + } } } @@ -330,6 +341,16 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati VolumeInfo vol = volFactory.getVolume(volume.getId()); DataStore store = dataStoreMgr.getDataStore(pool.getId(), DataStoreRole.Primary); SnapshotInfo snapInfo = snapshotFactory.getSnapshot(snapshot.getId(), DataStoreRole.Image); + // sync snapshot to region store if necessary + DataStore snapStore = snapInfo.getDataStore(); + long snapVolId = snapInfo.getVolumeId(); + try { + _snapshotSrv.syncVolumeSnapshotsToRegionStore(snapVolId, snapStore); + } catch (Exception ex) { + // log but ignore the sync error to avoid any potential S3 down issue, it should be sync next time + s_logger.warn(ex.getMessage(), ex); + } + // create volume on primary from snapshot AsyncCallFuture future = volService.createVolumeFromSnapshot(vol, store, snapInfo); try { VolumeApiResult result = future.get(); @@ -356,16 +377,16 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati } return new DiskProfile(volume.getId(), volume.getVolumeType(), volume.getName(), diskOffering.getId(), ss.getSize(), diskOffering.getTagsArray(), - diskOffering.getUseLocalStorage(), diskOffering.isRecreatable(), Storage.ImageFormat.ISO != template.getFormat() ? template.getId() : null); + diskOffering.getUseLocalStorage(), diskOffering.isRecreatable(), Storage.ImageFormat.ISO != template.getFormat() ? template.getId() : null); } else { - return new DiskProfile(volume.getId(), volume.getVolumeType(), volume.getName(), diskOffering.getId(), diskOffering.getDiskSize(), - diskOffering.getTagsArray(), diskOffering.getUseLocalStorage(), diskOffering.isRecreatable(), null); + return new DiskProfile(volume.getId(), volume.getVolumeType(), volume.getName(), diskOffering.getId(), diskOffering.getDiskSize(), diskOffering.getTagsArray(), + diskOffering.getUseLocalStorage(), diskOffering.isRecreatable(), null); } } @DB public VolumeInfo copyVolumeFromSecToPrimary(VolumeInfo volume, VirtualMachine vm, VirtualMachineTemplate template, DataCenter dc, Pod pod, Long clusterId, - ServiceOffering offering, DiskOffering diskOffering, List avoids, long size, HypervisorType hyperType) throws NoTransitionException { + ServiceOffering offering, DiskOffering diskOffering, List avoids, long size, HypervisorType hyperType) throws NoTransitionException { final HashSet avoidPools = new HashSet(avoids); DiskProfile dskCh = createDiskCharacteristics(volume, template, dc, diskOffering); @@ -392,13 +413,12 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati } @DB - public VolumeInfo createVolume(VolumeInfo volume, VirtualMachine vm, VirtualMachineTemplate template, DataCenter dc, Pod pod, Long clusterId, - ServiceOffering offering, DiskOffering diskOffering, List avoids, long size, HypervisorType hyperType) { - StoragePool pool = null; + public VolumeInfo createVolume(VolumeInfo volume, VirtualMachine vm, VirtualMachineTemplate template, DataCenter dc, Pod pod, Long clusterId, ServiceOffering offering, + DiskOffering diskOffering, List avoids, long size, HypervisorType hyperType) { + // update the volume's hypervisor_ss_reserve from its disk offering (used for managed storage) + volume = updateHypervisorSnapshotReserveForVolume(diskOffering, volume, hyperType); - if (diskOffering != null && diskOffering.isCustomized()) { - diskOffering.setDiskSize(size); - } + StoragePool pool = null; DiskProfile dskCh = null; if (volume.getVolumeType() == Type.ROOT && Storage.ImageFormat.ISO != template.getFormat()) { @@ -407,14 +427,18 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati dskCh = createDiskCharacteristics(volume, template, dc, diskOffering); } + if (diskOffering != null && diskOffering.isCustomized()) { + dskCh.setSize(size); + } + dskCh.setHyperType(hyperType); final HashSet avoidPools = new HashSet(avoids); pool = findStoragePool(dskCh, dc, pod, clusterId, vm.getHostId(), vm, avoidPools); if (pool == null) { - s_logger.warn("Unable to find storage pool when create volume " + volume.getName()); - throw new CloudRuntimeException("Unable to find storage pool when create volume" + volume.getName()); + s_logger.warn("Unable to find suitable primary storage when creating volume " + volume.getName()); + throw new CloudRuntimeException("Unable to find suitable primary storage when creating volume " + volume.getName()); } if (s_logger.isDebugEnabled()) { @@ -426,7 +450,6 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati AsyncCallFuture future = null; boolean isNotCreatedFromTemplate = volume.getTemplateId() == null ? true : false; if (isNotCreatedFromTemplate) { - volume = updateHypervisorSnapshotReserveForVolume(diskOffering, volume, hyperType); future = volService.createVolumeAsync(volume, store); } else { TemplateInfo templ = tmplFactory.getTemplate(template.getId(), DataStoreRole.Image); @@ -541,7 +564,7 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati protected DiskProfile toDiskProfile(Volume vol, DiskOffering offering) { return new DiskProfile(vol.getId(), vol.getVolumeType(), vol.getName(), offering.getId(), vol.getSize(), offering.getTagsArray(), offering.getUseLocalStorage(), - offering.isRecreatable(), vol.getTemplateId()); + offering.isRecreatable(), vol.getTemplateId()); } @Override @@ -551,8 +574,8 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati } else { size = (size * 1024 * 1024 * 1024); } - VolumeVO vol = - new VolumeVO(type, name, vm.getDataCenterId(), owner.getDomainId(), owner.getId(), offering.getId(), size, offering.getMinIops(), offering.getMaxIops(), null); + VolumeVO vol = new VolumeVO(type, name, vm.getDataCenterId(), owner.getDomainId(), owner.getId(), offering.getId(), size, offering.getMinIops(), offering.getMaxIops(), + null); if (vm != null) { vol.setInstanceId(vm.getId()); } @@ -571,16 +594,8 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati // Save usage event and update resource count for user vm volumes if (vm.getType() == VirtualMachine.Type.User) { - UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, - vol.getAccountId(), - vol.getDataCenterId(), - vol.getId(), - vol.getName(), - offering.getId(), - null, - size, - Volume.class.getName(), - vol.getUuid()); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, vol.getAccountId(), vol.getDataCenterId(), vol.getId(), vol.getName(), offering.getId(), null, size, + Volume.class.getName(), vol.getUuid()); _resourceLimitMgr.incrementResourceCount(vm.getAccountId(), ResourceType.volume); _resourceLimitMgr.incrementResourceCount(vm.getAccountId(), ResourceType.primary_storage, new Long(vol.getSize())); @@ -589,16 +604,15 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati } @Override - public DiskProfile allocateTemplatedVolume(Type type, String name, DiskOffering offering, Long rootDisksize, VirtualMachineTemplate template, VirtualMachine vm, - Account owner) { + public DiskProfile allocateTemplatedVolume(Type type, String name, DiskOffering offering, Long rootDisksize, VirtualMachineTemplate template, VirtualMachine vm, Account owner) { assert (template.getFormat() != ImageFormat.ISO) : "ISO is not a template really...."; Long size = _tmpltMgr.getTemplateSize(template.getId(), vm.getDataCenterId()); if (rootDisksize != null) { size = (rootDisksize * 1024 * 1024 * 1024); } - VolumeVO vol = - new VolumeVO(type, name, vm.getDataCenterId(), owner.getDomainId(), owner.getId(), offering.getId(), size, offering.getMinIops(), offering.getMaxIops(), null); + VolumeVO vol = new VolumeVO(type, name, vm.getDataCenterId(), owner.getDomainId(), owner.getId(), offering.getId(), size, offering.getMinIops(), offering.getMaxIops(), + null); vol.setFormat(getSupportedImageFormatForCluster(template.getHypervisorType())); if (vm != null) { vol.setInstanceId(vm.getId()); @@ -623,8 +637,8 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati offeringId = offering.getId(); - UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, vol.getAccountId(), vol.getDataCenterId(), vol.getId(), vol.getName(), offeringId, null, - size, Volume.class.getName(), vol.getUuid()); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, vol.getAccountId(), vol.getDataCenterId(), vol.getId(), vol.getName(), offeringId, null, size, + Volume.class.getName(), vol.getUuid()); _resourceLimitMgr.incrementResourceCount(vm.getAccountId(), ResourceType.volume); _resourceLimitMgr.incrementResourceCount(vm.getAccountId(), ResourceType.primary_storage, new Long(vol.getSize())); @@ -641,29 +655,29 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati return ImageFormat.OVA; } else if (hyperType == HypervisorType.Ovm) { return ImageFormat.RAW; + } else if (hyperType == HypervisorType.Hyperv) { + return ImageFormat.VHD; } else { return null; } } private VolumeInfo copyVolume(StoragePool rootDiskPool, VolumeInfo volume, VirtualMachine vm, VirtualMachineTemplate rootDiskTmplt, DataCenter dcVO, Pod pod, - DiskOffering diskVO, ServiceOffering svo, HypervisorType rootDiskHyperType) throws NoTransitionException { + DiskOffering diskVO, ServiceOffering svo, HypervisorType rootDiskHyperType) throws NoTransitionException { if (!volume.getFormat().equals(getSupportedImageFormatForCluster(rootDiskHyperType))) { - throw new InvalidParameterValueException("Failed to attach volume to VM since volumes format " + volume.getFormat().getFileExtension() + - " is not compatible with the vm hypervisor type"); + throw new InvalidParameterValueException("Failed to attach volume to VM since volumes format " + volume.getFormat().getFileExtension() + + " is not compatible with the vm hypervisor type"); } - VolumeInfo volumeOnPrimary = - copyVolumeFromSecToPrimary(volume, vm, rootDiskTmplt, dcVO, pod, rootDiskPool.getClusterId(), svo, diskVO, new ArrayList(), volume.getSize(), - rootDiskHyperType); + VolumeInfo volumeOnPrimary = copyVolumeFromSecToPrimary(volume, vm, rootDiskTmplt, dcVO, pod, rootDiskPool.getClusterId(), svo, diskVO, new ArrayList(), + volume.getSize(), rootDiskHyperType); return volumeOnPrimary; } @Override - public VolumeInfo createVolumeOnPrimaryStorage(VirtualMachine vm, Volume rootVolumeOfVm, VolumeInfo volume, HypervisorType rootDiskHyperType) - throws NoTransitionException { + public VolumeInfo createVolumeOnPrimaryStorage(VirtualMachine vm, Volume rootVolumeOfVm, VolumeInfo volume, HypervisorType rootDiskHyperType) throws NoTransitionException { VirtualMachineTemplate rootDiskTmplt = _entityMgr.findById(VirtualMachineTemplate.class, vm.getTemplateId()); DataCenter dcVO = _entityMgr.findById(DataCenter.class, vm.getDataCenterId()); Pod pod = _entityMgr.findById(Pod.class, vm.getPodIdToDeployIn()); @@ -697,8 +711,8 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati long vmTemplateId = vm.getTemplateId(); if (volTemplateId != null && volTemplateId.longValue() != vmTemplateId) { if (s_logger.isDebugEnabled()) { - s_logger.debug("switchVolume: Old Volume's templateId: " + volTemplateId + " does not match the VM's templateId: " + vmTemplateId + - ", updating templateId in the new Volume"); + s_logger.debug("switchVolume: Old Volume's templateId: " + volTemplateId + " does not match the VM's templateId: " + vmTemplateId + + ", updating templateId in the new Volume"); } templateIdToUse = vmTemplateId; } @@ -755,8 +769,7 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati for (VolumeVO vol : volumesForVm) { if (vol.getVolumeType().equals(Type.ROOT)) { // Destroy volume if not already destroyed - boolean volumeAlreadyDestroyed = - (vol.getState() == Volume.State.Destroy || vol.getState() == Volume.State.Expunged || vol.getState() == Volume.State.Expunging); + boolean volumeAlreadyDestroyed = (vol.getState() == Volume.State.Destroy || vol.getState() == Volume.State.Expunged || vol.getState() == Volume.State.Expunging); if (!volumeAlreadyDestroyed) { volService.destroyVolume(vol.getId()); } else { @@ -786,6 +799,22 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati } } + @Override + public void disconnectVolumesFromHost(long vmId, long hostId) { + HostVO host = _hostDao.findById(hostId); + + List volumesForVm = _volsDao.findByInstance(vmId); + + if (volumesForVm != null) { + for (VolumeVO volumeForVm : volumesForVm) { + VolumeInfo volumeInfo = volFactory.getVolume(volumeForVm.getId()); + DataStore dataStore = dataStoreMgr.getDataStore(volumeForVm.getPoolId(), DataStoreRole.Primary); + + volService.disconnectVolumeFromHost(volumeInfo, host, dataStore); + } + } + } + @Override @DB public Volume migrateVolume(Volume volume, StoragePool destPool) throws StorageUnavailableException { @@ -997,8 +1026,7 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati if (s_logger.isDebugEnabled()) { s_logger.debug("Local volume " + vol + " cannot be recreated on storagepool " + assignedPool + " assigned by deploymentPlanner"); } - throw new CloudRuntimeException("Local volume " + vol + " cannot be recreated on storagepool " + assignedPool + - " assigned by deploymentPlanner"); + throw new CloudRuntimeException("Local volume " + vol + " cannot be recreated on storagepool " + assignedPool + " assigned by deploymentPlanner"); } else { //Check if storage migration is enabled in config if (StorageHAMigrationEnabled.value()) { @@ -1022,7 +1050,7 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati } else { if (vol.getPoolId() == null) { throw new StorageUnavailableException("Volume has no pool associate and also no storage pool assigned in DeployDestination, Unable to create " + vol, - Volume.class, vol.getId()); + Volume.class, vol.getId()); } if (s_logger.isDebugEnabled()) { s_logger.debug("No need to recreate the volume: " + vol + ", since it already has a pool assigned: " + vol.getPoolId() + ", adding disk to VM"); @@ -1069,6 +1097,14 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati // retry one more time in case of template reload is required for Vmware case AsyncCallFuture future = null; if (templateId == null) { + DiskOffering diskOffering = _entityMgr.findById(DiskOffering.class, volume.getDiskOfferingId()); + HypervisorType hyperType = vm.getVirtualMachine().getHypervisorType(); + + // update the volume's hypervisor_ss_reserve from its disk offering (used for managed storage) + updateHypervisorSnapshotReserveForVolume(diskOffering, volume, hyperType); + + volume = volFactory.getVolume(newVol.getId(), destPool); + future = volService.createVolumeAsync(volume, destPool); } else { TemplateInfo templ = tmplFactory.getTemplate(templateId, DataStoreRole.Image); @@ -1086,6 +1122,16 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati throw new StorageUnavailableException("Unable to create " + newVol + ":" + result.getResult(), destPool.getId()); } } + + StoragePoolVO storagePool = _storagePoolDao.findById(destPool.getId()); + + if (newVol.getVolumeType() == Type.DATADISK && storagePool.isManaged()) { + long hostId = vm.getVirtualMachine().getHostId(); + Host host = _hostDao.findById(hostId); + + volService.connectVolumeToHost(volFactory.getVolume(newVol.getId()), host, destPool); + } + newVol = _volsDao.findById(newVol.getId()); break; //break out of template-redeploy retry loop } catch (InterruptedException e) { @@ -1101,8 +1147,7 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati } @Override - public void prepare(VirtualMachineProfile vm, DeployDestination dest) throws StorageUnavailableException, InsufficientStorageCapacityException, - ConcurrentOperationException { + public void prepare(VirtualMachineProfile vm, DeployDestination dest) throws StorageUnavailableException, InsufficientStorageCapacityException, ConcurrentOperationException { if (dest == null) { if (s_logger.isDebugEnabled()) { @@ -1157,18 +1202,18 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati return true; } - public static final ConfigKey MaxVolumeSize = new ConfigKey(Long.class, "storage.max.volume.size", "Storage", "2000", - "The maximum size for a volume (in GB).", true); + public static final ConfigKey MaxVolumeSize = new ConfigKey(Long.class, "storage.max.volume.size", "Storage", "2000", "The maximum size for a volume (in GB).", + true); public static final ConfigKey RecreatableSystemVmEnabled = new ConfigKey(Boolean.class, "recreate.systemvm.enabled", "Advanced", "false", - "If true, will recreate system vm root disk whenever starting system vm", true); + "If true, will recreate system vm root disk whenever starting system vm", true); public static final ConfigKey StorageHAMigrationEnabled = new ConfigKey(Boolean.class, "enable.ha.storage.migration", "Storage", "true", - "Enable/disable storage migration across primary storage during HA", true); + "Enable/disable storage migration across primary storage during HA", true); @Override public ConfigKey[] getConfigKeys() { - return new ConfigKey[] {RecreatableSystemVmEnabled, MaxVolumeSize, StorageHAMigrationEnabled}; + return new ConfigKey[] {RecreatableSystemVmEnabled, MaxVolumeSize, StorageHAMigrationEnabled, CustomDiskOfferingMaxSize, CustomDiskOfferingMinSize}; } @Override diff --git a/engine/orchestration/test/com/cloud/vm/VirtualMachineManagerImplTest.java b/engine/orchestration/test/com/cloud/vm/VirtualMachineManagerImplTest.java index 2c308f0161f..997855d2b24 100644 --- a/engine/orchestration/test/com/cloud/vm/VirtualMachineManagerImplTest.java +++ b/engine/orchestration/test/com/cloud/vm/VirtualMachineManagerImplTest.java @@ -34,7 +34,6 @@ import org.junit.Before; import org.junit.Test; import org.mockito.Matchers; import org.mockito.Mock; -import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.Spy; diff --git a/engine/schema/resources/META-INF/cloudstack/core/spring-engine-schema-core-daos-context.xml b/engine/schema/resources/META-INF/cloudstack/core/spring-engine-schema-core-daos-context.xml index e7caa203cc6..d1a68ede322 100644 --- a/engine/schema/resources/META-INF/cloudstack/core/spring-engine-schema-core-daos-context.xml +++ b/engine/schema/resources/META-INF/cloudstack/core/spring-engine-schema-core-daos-context.xml @@ -36,7 +36,7 @@ - + @@ -45,7 +45,7 @@ - + @@ -54,7 +54,7 @@ - + @@ -63,7 +63,7 @@ - + @@ -72,7 +72,7 @@ - + @@ -81,7 +81,7 @@ - + @@ -90,7 +90,7 @@ - + @@ -99,7 +99,7 @@ - + @@ -109,7 +109,7 @@ - + @@ -171,20 +171,18 @@ - - - - - + + + + - + - @@ -251,6 +249,7 @@ + @@ -327,7 +326,12 @@ - + + + + + + diff --git a/engine/schema/src/com/cloud/alert/AlertVO.java b/engine/schema/src/com/cloud/alert/AlertVO.java index ade505d2e3f..70ef469f52b 100755 --- a/engine/schema/src/com/cloud/alert/AlertVO.java +++ b/engine/schema/src/com/cloud/alert/AlertVO.java @@ -72,8 +72,8 @@ public class AlertVO implements Alert { @Column(name = "archived") private boolean archived; - - @Column(name="name") + + @Column(name = "name") private String name; public AlertVO() { @@ -188,7 +188,6 @@ public class AlertVO implements Alert { return name; } - public void setName(String name) { this.name = name; } diff --git a/engine/schema/src/com/cloud/alert/dao/AlertDao.java b/engine/schema/src/com/cloud/alert/dao/AlertDao.java index 89128b43748..e61092e4394 100755 --- a/engine/schema/src/com/cloud/alert/dao/AlertDao.java +++ b/engine/schema/src/com/cloud/alert/dao/AlertDao.java @@ -28,9 +28,9 @@ public interface AlertDao extends GenericDao { // This is for backward compatibility AlertVO getLastAlert(short type, long dataCenterId, Long podId); - public boolean deleteAlert(List Ids, String type, Date startDate, Date endDate, Long zoneId); + public boolean deleteAlert(List ids, String type, Date startDate, Date endDate, Long zoneId); - public boolean archiveAlert(List Ids, String type, Date startDate, Date endDate, Long zoneId); + public boolean archiveAlert(List ids, String type, Date startDate, Date endDate, Long zoneId); public List listOlderAlerts(Date oldTime); } diff --git a/engine/schema/src/com/cloud/alert/dao/AlertDaoImpl.java b/engine/schema/src/com/cloud/alert/dao/AlertDaoImpl.java index f8304038599..865b8d1898c 100755 --- a/engine/schema/src/com/cloud/alert/dao/AlertDaoImpl.java +++ b/engine/schema/src/com/cloud/alert/dao/AlertDaoImpl.java @@ -90,11 +90,11 @@ public class AlertDaoImpl extends GenericDaoBase implements Alert } @Override - public boolean archiveAlert(List Ids, String type, Date startDate, Date endDate, Long zoneId) { + public boolean archiveAlert(List ids, String type, Date startDate, Date endDate, Long zoneId) { SearchCriteria sc = AlertSearchByIdsAndType.create(); - if (Ids != null) { - sc.setParameters("id", Ids.toArray(new Object[Ids.size()])); + if (ids != null) { + sc.setParameters("id", ids.toArray(new Object[ids.size()])); } if (type != null) { sc.setParameters("type", type); @@ -112,7 +112,7 @@ public class AlertDaoImpl extends GenericDaoBase implements Alert boolean result = true; ; List alerts = listBy(sc); - if (Ids != null && alerts.size() < Ids.size()) { + if (ids != null && alerts.size() < ids.size()) { result = false; return result; } diff --git a/engine/schema/src/com/cloud/capacity/dao/CapacityDao.java b/engine/schema/src/com/cloud/capacity/dao/CapacityDao.java index 079d9a87649..a900e64c127 100755 --- a/engine/schema/src/com/cloud/capacity/dao/CapacityDao.java +++ b/engine/schema/src/com/cloud/capacity/dao/CapacityDao.java @@ -46,11 +46,14 @@ public interface CapacityDao extends GenericDao { Pair, Map> orderPodsByAggregateCapacity(long zoneId, short capacityType); List findCapacityBy(Integer capacityType, Long zoneId, - Long podId, Long clusterId, String resourceState); - List listCapacitiesGroupedByLevelAndType(Integer capacityType, Long zoneId, Long podId, Long clusterId, int level, Long limit); + Long podId, Long clusterId, String resourceState); + + List listCapacitiesGroupedByLevelAndType(Integer capacityType, Long zoneId, Long podId, Long clusterId, int level, Long limit); + void updateCapacityState(Long dcId, Long podId, Long clusterId, - Long hostId, String capacityState); - List listClustersCrossingThreshold(short capacityType, Long zoneId, String ConfigName, long computeRequested); + Long hostId, String capacityState); + + List listClustersCrossingThreshold(short capacityType, Long zoneId, String configName, long computeRequested); float findClusterConsumption(Long clusterId, short capacityType, long computeRequested); } diff --git a/engine/schema/src/com/cloud/capacity/dao/CapacityDaoImpl.java b/engine/schema/src/com/cloud/capacity/dao/CapacityDaoImpl.java index 7919ed5bcd4..b7784f22390 100755 --- a/engine/schema/src/com/cloud/capacity/dao/CapacityDaoImpl.java +++ b/engine/schema/src/com/cloud/capacity/dao/CapacityDaoImpl.java @@ -27,9 +27,6 @@ import java.util.Map; import javax.ejb.Local; import javax.inject.Inject; -import com.cloud.dc.ClusterDetailsDao; -import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; -import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; @@ -165,23 +162,29 @@ public class CapacityDaoImpl extends GenericDaoBase implements * * */ - private static final String LIST_CLUSTERS_CROSSING_THRESHOLD = "SELECT clusterList.cluster_id " + - "FROM ( SELECT cluster.cluster_id cluster_id, ( (sum(cluster.used) + sum(cluster.reserved) + ?)/sum(cluster.total) ) ratio, cluster.configValue value " + - "FROM ( SELECT capacity.cluster_id cluster_id, capacity.used_capacity used, capacity.reserved_capacity reserved, capacity.total_capacity * overcommit.value total, " + - "CASE (SELECT count(*) FROM `cloud`.`cluster_details` details WHERE details.cluster_id = capacity.cluster_id AND details.name = ? ) " + - "WHEN 1 THEN ( CASE WHEN (SELECT details.value FROM `cloud`.`cluster_details` details WHERE details.cluster_id = capacity.cluster_id AND details.name = ?) is NULL " + - "THEN (SELECT config.value FROM `cloud`.`configuration` config WHERE config.name = ?)" + - "ELSE (SELECT details.value FROM `cloud`.`cluster_details` details WHERE details.cluster_id = capacity.cluster_id AND details.name = ? ) END )" + - "ELSE ( SELECT config.value FROM `cloud`.`configuration` config WHERE config.name = ?) " + - "END configValue " + - "FROM `cloud`.`op_host_capacity` capacity INNER JOIN `cloud`.`cluster_details` overcommit ON overcommit.cluster_id = capacity.cluster_id " + - "WHERE capacity.data_center_id = ? AND capacity.capacity_type = ? AND capacity.total_capacity > 0 AND overcommit.name = ?) cluster " + + private static final String LIST_CLUSTERS_CROSSING_THRESHOLD = "SELECT clusterList.cluster_id " + + + "FROM (SELECT cluster.cluster_id cluster_id, ( (sum(cluster.used) + sum(cluster.reserved) + ?)/sum(cluster.total) ) ratio, cluster.configValue value " + + + "FROM (SELECT capacity.cluster_id cluster_id, capacity.used_capacity used, capacity.reserved_capacity reserved, capacity.total_capacity * overcommit.value total, " + + + "CASE (SELECT count(*) FROM `cloud`.`cluster_details` details WHERE details.cluster_id = capacity.cluster_id AND details.name = ? ) " + + + "WHEN 1 THEN (CASE WHEN (SELECT details.value FROM `cloud`.`cluster_details` details WHERE details.cluster_id = capacity.cluster_id AND details.name = ?) is NULL " + + + "THEN (SELECT config.value FROM `cloud`.`configuration` config WHERE config.name = ?)" + + "ELSE (SELECT details.value FROM `cloud`.`cluster_details` details WHERE details.cluster_id = capacity.cluster_id AND details.name = ? ) END )" + + "ELSE (SELECT config.value FROM `cloud`.`configuration` config WHERE config.name = ?) " + + "END configValue " + + "FROM `cloud`.`op_host_capacity` capacity INNER JOIN `cloud`.`cluster_details` overcommit ON overcommit.cluster_id = capacity.cluster_id " + + "WHERE capacity.data_center_id = ? AND capacity.capacity_type = ? AND capacity.total_capacity > 0 AND overcommit.name = ?) cluster " + - "GROUP BY cluster.cluster_id) clusterList " + - "WHERE clusterList.ratio > clusterList.value; "; + "GROUP BY cluster.cluster_id) clusterList " + + "WHERE clusterList.ratio > clusterList.value; "; - private static final String FIND_CLUSTER_CONSUMPTION_RATIO = "select ( (sum(capacity.used_capacity) + sum(capacity.reserved_capacity) + ?)/sum(capacity.total_capacity) ) " + - "from op_host_capacity capacity where cluster_id = ? and capacity_type = ?;"; + private static final String FIND_CLUSTER_CONSUMPTION_RATIO = "select ( (sum(capacity.used_capacity) + sum(capacity.reserved_capacity) + ?)/sum(capacity.total_capacity) ) " + + + "from op_host_capacity capacity where cluster_id = ? and capacity_type = ?;"; public CapacityDaoImpl() { _hostIdTypeSearch = createSearchBuilder(); @@ -206,7 +209,7 @@ public class CapacityDaoImpl extends GenericDaoBase implements } @Override - public List listClustersCrossingThreshold(short capacityType, Long zoneId, String configName, long compute_requested) { + public List listClustersCrossingThreshold(short capacityType, Long zoneId, String configName, long computeRequested) { TransactionLegacy txn = TransactionLegacy.currentTxn(); PreparedStatement pstmt = null; @@ -216,7 +219,7 @@ public class CapacityDaoImpl extends GenericDaoBase implements // we need to check with disabled thresholds of each cluster if not defined at cluster consider the global value try { pstmt = txn.prepareAutoCloseStatement(sql.toString()); - pstmt.setLong(1, compute_requested); + pstmt.setLong(1, computeRequested); pstmt.setString(2, configName); pstmt.setString(3, configName); pstmt.setString(4, configName); @@ -260,7 +263,7 @@ public class CapacityDaoImpl extends GenericDaoBase implements }*/ @Override - public List findCapacityBy(Integer capacityType, Long zoneId, Long podId, Long clusterId, String resource_state) { + public List findCapacityBy(Integer capacityType, Long zoneId, Long podId, Long clusterId, String resourceState) { TransactionLegacy txn = TransactionLegacy.currentTxn(); PreparedStatement pstmt = null; @@ -288,10 +291,10 @@ public class CapacityDaoImpl extends GenericDaoBase implements try { pstmt = txn.prepareAutoCloseStatement(sql.toString()); - pstmt.setString(1, resource_state); - pstmt.setString(2, resource_state); - pstmt.setString(3, resource_state); - pstmt.setString(4, resource_state); + pstmt.setString(1, resourceState); + pstmt.setString(2, resourceState); + pstmt.setString(3, resourceState); + pstmt.setString(4, resourceState); for (int i = 0; i < resourceIdList.size(); i++) { pstmt.setLong(5 + i, resourceIdList.get(i)); } @@ -893,7 +896,7 @@ public class CapacityDaoImpl extends GenericDaoBase implements } @Override - public float findClusterConsumption(Long clusterId, short capacityType, long computeRequested){ + public float findClusterConsumption(Long clusterId, short capacityType, long computeRequested) { TransactionLegacy txn = TransactionLegacy.currentTxn(); StringBuilder sql = new StringBuilder(FIND_CLUSTER_CONSUMPTION_RATIO); PreparedStatement pstmt = null; diff --git a/engine/schema/src/com/cloud/dc/dao/DataCenterDaoImpl.java b/engine/schema/src/com/cloud/dc/dao/DataCenterDaoImpl.java index 9c6b553a7a5..a355a9ca99f 100755 --- a/engine/schema/src/com/cloud/dc/dao/DataCenterDaoImpl.java +++ b/engine/schema/src/com/cloud/dc/dao/DataCenterDaoImpl.java @@ -70,7 +70,7 @@ public class DataCenterDaoImpl extends GenericDaoBase implem @Inject protected DataCenterIpAddressDao _ipAllocDao = null; @Inject - protected DataCenterLinkLocalIpAddressDao _LinkLocalIpAllocDao = null; + protected DataCenterLinkLocalIpAddressDao _linkLocalIpAllocDao = null; @Inject protected DataCenterVnetDao _vnetAllocDao = null; @Inject @@ -179,12 +179,12 @@ public class DataCenterDaoImpl extends GenericDaoBase implem @Override public void releaseLinkLocalIpAddress(long nicId, String reservationId) { - _LinkLocalIpAllocDao.releaseIpAddress(nicId, reservationId); + _linkLocalIpAllocDao.releaseIpAddress(nicId, reservationId); } @Override public void releaseLinkLocalIpAddress(String ipAddress, long dcId, Long instanceId) { - _LinkLocalIpAllocDao.releaseIpAddress(ipAddress, dcId, instanceId); + _linkLocalIpAllocDao.releaseIpAddress(ipAddress, dcId, instanceId); } @Override @@ -194,7 +194,7 @@ public class DataCenterDaoImpl extends GenericDaoBase implem @Override public boolean deleteLinkLocalIpAddressByPod(long podId) { - return _LinkLocalIpAllocDao.deleteIpAddressByPod(podId); + return _linkLocalIpAllocDao.deleteIpAddressByPod(podId); } @Override @@ -265,7 +265,7 @@ public class DataCenterDaoImpl extends GenericDaoBase implem @Override public String allocateLinkLocalIpAddress(long dcId, long podId, long instanceId, String reservationId) { - DataCenterLinkLocalIpAddressVO vo = _LinkLocalIpAllocDao.takeIpAddress(dcId, podId, instanceId, reservationId); + DataCenterLinkLocalIpAddressVO vo = _linkLocalIpAllocDao.takeIpAddress(dcId, podId, instanceId, reservationId); if (vo == null) { return null; } @@ -294,7 +294,7 @@ public class DataCenterDaoImpl extends GenericDaoBase implem @Override public void addLinkLocalIpAddress(long dcId, long podId, String start, String end) { - _LinkLocalIpAllocDao.addIpRange(dcId, podId, start, end); + _linkLocalIpAllocDao.addIpRange(dcId, podId, start, end); } @Override diff --git a/engine/schema/src/com/cloud/event/dao/UsageEventDaoImpl.java b/engine/schema/src/com/cloud/event/dao/UsageEventDaoImpl.java index f9261a96b87..4e35bf5de96 100644 --- a/engine/schema/src/com/cloud/event/dao/UsageEventDaoImpl.java +++ b/engine/schema/src/com/cloud/event/dao/UsageEventDaoImpl.java @@ -54,6 +54,10 @@ public class UsageEventDaoImpl extends GenericDaoBase implem private static final String COPY_ALL_EVENTS = "INSERT INTO cloud_usage.usage_event (id, type, account_id, created, zone_id, resource_id, resource_name, offering_id, template_id, size, resource_type, virtual_size) " + "SELECT id, type, account_id, created, zone_id, resource_id, resource_name, offering_id, template_id, size, resource_type, virtual_size FROM cloud.usage_event vmevt WHERE vmevt.id <= ?"; + private static final String COPY_EVENT_DETAILS = "INSERT INTO cloud_usage.usage_event_details (id, usage_event_id, name, value) " + + "SELECT id, usage_event_id, name, value FROM cloud.usage_event_details vmevtDetails WHERE vmevtDetails.usage_event_id > ? and vmevtDetails.usage_event_id <= ? "; + private static final String COPY_ALL_EVENT_DETAILS = "INSERT INTO cloud_usage.usage_event_details (id, usage_event_id, name, value) " + + "SELECT id, usage_event_id, name, value FROM cloud.usage_event_details vmevtDetails WHERE vmevtDetails.usage_event_id <= ?"; private static final String MAX_EVENT = "select max(id) from cloud.usage_event where created <= ?"; @Inject protected UsageEventDetailsDao usageEventDetailsDao; @@ -96,6 +100,7 @@ public class UsageEventDaoImpl extends GenericDaoBase implem long recentEventId = getMostRecentEventId(); long maxEventId = getMaxEventId(endDate); TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB); + // Copy events from cloud db to usage db String sql = COPY_EVENTS; if (recentEventId == 0) { if (s_logger.isDebugEnabled()) { @@ -115,12 +120,39 @@ public class UsageEventDaoImpl extends GenericDaoBase implem pstmt.setLong(i++, maxEventId); pstmt.executeUpdate(); txn.commit(); - return findRecentEvents(endDate); } catch (Exception ex) { txn.rollback(); s_logger.error("error copying events from cloud db to usage db", ex); throw new CloudRuntimeException(ex.getMessage()); } + + // Copy event details from cloud db to usage db + sql = COPY_EVENT_DETAILS; + if (recentEventId == 0) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("no recent event date, copying all event detailss"); + } + sql = COPY_ALL_EVENT_DETAILS; + } + + pstmt = null; + try { + txn.start(); + pstmt = txn.prepareAutoCloseStatement(sql); + int i = 1; + if (recentEventId != 0) { + pstmt.setLong(i++, recentEventId); + } + pstmt.setLong(i++, maxEventId); + pstmt.executeUpdate(); + txn.commit(); + } catch (Exception ex) { + txn.rollback(); + s_logger.error("error copying event details from cloud db to usage db", ex); + throw new CloudRuntimeException(ex.getMessage()); + } + + return findRecentEvents(endDate); } @DB diff --git a/engine/schema/src/com/cloud/event/dao/UsageEventDetailsDao.java b/engine/schema/src/com/cloud/event/dao/UsageEventDetailsDao.java index 229bef0bb63..aee5a5754fb 100644 --- a/engine/schema/src/com/cloud/event/dao/UsageEventDetailsDao.java +++ b/engine/schema/src/com/cloud/event/dao/UsageEventDetailsDao.java @@ -23,7 +23,6 @@ import com.cloud.event.UsageEventDetailsVO; import com.cloud.utils.db.GenericDao; public interface UsageEventDetailsDao extends GenericDao { - Map findDetails(long eventId); void persist(long eventId, Map details); diff --git a/engine/schema/src/com/cloud/event/dao/UsageEventDetailsDaoImpl.java b/engine/schema/src/com/cloud/event/dao/UsageEventDetailsDaoImpl.java index 2126fff45c6..35d77c12b08 100644 --- a/engine/schema/src/com/cloud/event/dao/UsageEventDetailsDaoImpl.java +++ b/engine/schema/src/com/cloud/event/dao/UsageEventDetailsDaoImpl.java @@ -16,17 +16,11 @@ // under the License. package com.cloud.event.dao; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ejb.Local; -import com.cloud.utils.exception.CloudRuntimeException; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; @@ -41,8 +35,6 @@ import com.cloud.utils.db.TransactionLegacy; public class UsageEventDetailsDaoImpl extends GenericDaoBase implements UsageEventDetailsDao { public static final Logger s_logger = Logger.getLogger(UsageEventDetailsDaoImpl.class.getName()); - private static final String EVENT_DETAILS_QUERY = "SELECT details.id, details.usage_event_id, details.name, details.value FROM `cloud`.`usage_event_details` details WHERE details.usage_event_id = ?"; - protected final SearchBuilder EventDetailsSearch; protected final SearchBuilder DetailSearch; @@ -79,45 +71,6 @@ public class UsageEventDetailsDaoImpl extends GenericDaoBase findDetails(long eventId) { - Connection conn = null; - PreparedStatement pstmt = null; - ResultSet resultSet = null; - Map details = new HashMap(); - try { - conn = TransactionLegacy.getStandaloneConnection(); - - pstmt = conn.prepareStatement(EVENT_DETAILS_QUERY); - pstmt.setLong(1, eventId); - resultSet = pstmt.executeQuery(); - - while (resultSet.next()) { - details.put(resultSet.getString(3), resultSet.getString(4)); - } - - } catch (SQLException e) { - throw new CloudRuntimeException("Error while executing SQL prepared statement", e); - } catch (Throwable e) { - throw new CloudRuntimeException("Caught: " + e); - } finally { - if (pstmt != null) { - try { - pstmt.close(); - } catch (SQLException e) { - } - } - if (conn != null) { - try { - conn.close(); - } catch (SQLException e) { - } - } - } - - return details; - } - @Override public void persist(long eventId, Map details) { TransactionLegacy txn = TransactionLegacy.currentTxn(); diff --git a/engine/schema/src/com/cloud/network/as/AutoScalePolicyVO.java b/engine/schema/src/com/cloud/network/as/AutoScalePolicyVO.java index 6a104c2cb3e..b69907c51c3 100644 --- a/engine/schema/src/com/cloud/network/as/AutoScalePolicyVO.java +++ b/engine/schema/src/com/cloud/network/as/AutoScalePolicyVO.java @@ -59,9 +59,9 @@ public class AutoScalePolicyVO implements AutoScalePolicy, InternalIdentity { @Column(name = "quiet_time", updatable = true, nullable = false) private int quietTime; - @Column(name = "last_quiet_time", updatable = true) - @Temporal(value = TemporalType.TIMESTAMP) - private Date lastQuiteTime; + @Column(name = "last_quiet_time", updatable = true) + @Temporal(value = TemporalType.TIMESTAMP) + private Date lastQuiteTime; @Column(name = "action", updatable = false, nullable = false) private String action; @@ -75,14 +75,14 @@ public class AutoScalePolicyVO implements AutoScalePolicy, InternalIdentity { public AutoScalePolicyVO() { } - public AutoScalePolicyVO(long domainId, long accountId, int duration, - int quietTime, Date lastQuiteTime, String action) { + public AutoScalePolicyVO(long domainId, long accountId, int duration, + int quietTime, Date lastQuiteTime, String action) { this.uuid = UUID.randomUUID().toString(); this.domainId = domainId; this.accountId = accountId; this.duration = duration; this.quietTime = quietTime; - this.lastQuiteTime = lastQuiteTime; + this.lastQuiteTime = lastQuiteTime; this.action = action; } @@ -121,10 +121,10 @@ public class AutoScalePolicyVO implements AutoScalePolicy, InternalIdentity { return quietTime; } - @Override - public Date getLastQuiteTime() { - return lastQuiteTime; - } + @Override + public Date getLastQuiteTime() { + return lastQuiteTime; + } @Override public String getAction() { @@ -147,7 +147,7 @@ public class AutoScalePolicyVO implements AutoScalePolicy, InternalIdentity { this.quietTime = quietTime; } - public void setLastQuiteTime(Date lastQuiteTime) { - this.lastQuiteTime = lastQuiteTime; - } + public void setLastQuiteTime(Date lastQuiteTime) { + this.lastQuiteTime = lastQuiteTime; + } } diff --git a/engine/schema/src/com/cloud/network/as/AutoScaleVmGroupVO.java b/engine/schema/src/com/cloud/network/as/AutoScaleVmGroupVO.java index 4d41583fd84..d8612b0da50 100644 --- a/engine/schema/src/com/cloud/network/as/AutoScaleVmGroupVO.java +++ b/engine/schema/src/com/cloud/network/as/AutoScaleVmGroupVO.java @@ -71,9 +71,9 @@ public class AutoScaleVmGroupVO implements AutoScaleVmGroup, InternalIdentity { @Column(name = "interval") private int interval; - @Column(name = "last_interval", updatable = true) - @Temporal(value = TemporalType.TIMESTAMP) - private Date lastInterval; + @Column(name = "last_interval", updatable = true) + @Temporal(value = TemporalType.TIMESTAMP) + private Date lastInterval; @Column(name = "profile_id") private long profileId; @@ -90,9 +90,9 @@ public class AutoScaleVmGroupVO implements AutoScaleVmGroup, InternalIdentity { public AutoScaleVmGroupVO() { } - public AutoScaleVmGroupVO(long lbRuleId, long zoneId, long domainId, - long accountId, int minMembers, int maxMembers, int memberPort, - int interval, Date lastInterval, long profileId, String state) { + public AutoScaleVmGroupVO(long lbRuleId, long zoneId, long domainId, + long accountId, int minMembers, int maxMembers, int memberPort, + int interval, Date lastInterval, long profileId, String state) { this.uuid = UUID.randomUUID().toString(); this.loadBalancerId = lbRuleId; @@ -105,7 +105,7 @@ public class AutoScaleVmGroupVO implements AutoScaleVmGroup, InternalIdentity { this.zoneId = zoneId; this.state = state; this.interval = interval; - this.lastInterval = lastInterval; + this.lastInterval = lastInterval; } @Override @@ -157,10 +157,10 @@ public class AutoScaleVmGroupVO implements AutoScaleVmGroup, InternalIdentity { return interval; } - @Override - public Date getLastInterval() { - return lastInterval; - } + @Override + public Date getLastInterval() { + return lastInterval; + } @Override public long getProfileId() { @@ -196,9 +196,9 @@ public class AutoScaleVmGroupVO implements AutoScaleVmGroup, InternalIdentity { this.interval = interval; } - public void setLastInterval(Date lastInterval) { - this.lastInterval = lastInterval; - } + public void setLastInterval(Date lastInterval) { + this.lastInterval = lastInterval; + } public void setLoadBalancerId(Long loadBalancerId) { this.loadBalancerId = loadBalancerId; diff --git a/engine/schema/src/com/cloud/network/as/AutoScaleVmGroupVmMapVO.java b/engine/schema/src/com/cloud/network/as/AutoScaleVmGroupVmMapVO.java index d70f9bfba37..038f0d76825 100644 --- a/engine/schema/src/com/cloud/network/as/AutoScaleVmGroupVmMapVO.java +++ b/engine/schema/src/com/cloud/network/as/AutoScaleVmGroupVmMapVO.java @@ -28,35 +28,35 @@ import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name = ("autoscale_vmgroup_vm_map")) public class AutoScaleVmGroupVmMapVO implements InternalIdentity { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - private long id; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; - @Column(name = "vmgroup_id") - private long vmGroupId; + @Column(name = "vmgroup_id") + private long vmGroupId; - @Column(name = "instance_id") - private long instanceId; + @Column(name = "instance_id") + private long instanceId; - public AutoScaleVmGroupVmMapVO() { - } + public AutoScaleVmGroupVmMapVO() { + } - public AutoScaleVmGroupVmMapVO(long vmGroupId, long instanceId) { - this.vmGroupId = vmGroupId; - this.instanceId = instanceId; - } + public AutoScaleVmGroupVmMapVO(long vmGroupId, long instanceId) { + this.vmGroupId = vmGroupId; + this.instanceId = instanceId; + } - public long getId() { - return id; - } + public long getId() { + return id; + } - public long getVmGroupId() { - return vmGroupId; - } + public long getVmGroupId() { + return vmGroupId; + } - public long getInstanceId() { - return instanceId; - } + public long getInstanceId() { + return instanceId; + } } diff --git a/engine/schema/src/com/cloud/network/as/dao/AutoScalePolicyConditionMapDao.java b/engine/schema/src/com/cloud/network/as/dao/AutoScalePolicyConditionMapDao.java index a9cfd188cc2..cc6dc10a649 100644 --- a/engine/schema/src/com/cloud/network/as/dao/AutoScalePolicyConditionMapDao.java +++ b/engine/schema/src/com/cloud/network/as/dao/AutoScalePolicyConditionMapDao.java @@ -26,7 +26,7 @@ public interface AutoScalePolicyConditionMapDao extends GenericDao findByPolicyId(long id); + List findByPolicyId(long id); } diff --git a/engine/schema/src/com/cloud/network/as/dao/AutoScalePolicyConditionMapDaoImpl.java b/engine/schema/src/com/cloud/network/as/dao/AutoScalePolicyConditionMapDaoImpl.java index 557a6731af0..fd4bfd57175 100644 --- a/engine/schema/src/com/cloud/network/as/dao/AutoScalePolicyConditionMapDaoImpl.java +++ b/engine/schema/src/com/cloud/network/as/dao/AutoScalePolicyConditionMapDaoImpl.java @@ -56,14 +56,14 @@ public class AutoScalePolicyConditionMapDaoImpl extends GenericDaoBase sc = createSearchCriteria(); sc.addAnd("policyId", SearchCriteria.Op.EQ, policyId); - return expunge(sc) > 0; - } + return expunge(sc) > 0; + } - @Override - public List findByPolicyId(long policyId) { - SearchCriteria sc = createSearchCriteria(); - sc.addAnd("policyId", SearchCriteria.Op.EQ, policyId); + @Override + public List findByPolicyId(long policyId) { + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("policyId", SearchCriteria.Op.EQ, policyId); - return listBy(sc); - } + return listBy(sc); + } } diff --git a/engine/schema/src/com/cloud/network/as/dao/AutoScaleVmGroupVmMapDao.java b/engine/schema/src/com/cloud/network/as/dao/AutoScaleVmGroupVmMapDao.java index b7234e7a64c..1a8acf3c00a 100644 --- a/engine/schema/src/com/cloud/network/as/dao/AutoScaleVmGroupVmMapDao.java +++ b/engine/schema/src/com/cloud/network/as/dao/AutoScaleVmGroupVmMapDao.java @@ -22,10 +22,10 @@ import com.cloud.network.as.AutoScaleVmGroupVmMapVO; import com.cloud.utils.db.GenericDao; public interface AutoScaleVmGroupVmMapDao extends GenericDao { - public Integer countByGroup(long vmGroupId); + public Integer countByGroup(long vmGroupId); - public List listByGroup(long vmGroupId); + public List listByGroup(long vmGroupId); - public int remove(long vmGroupId, long vmId); + public int remove(long vmGroupId, long vmId); } diff --git a/engine/schema/src/com/cloud/network/as/dao/AutoScaleVmGroupVmMapDaoImpl.java b/engine/schema/src/com/cloud/network/as/dao/AutoScaleVmGroupVmMapDaoImpl.java index 494092d65d5..463477c74c6 100644 --- a/engine/schema/src/com/cloud/network/as/dao/AutoScaleVmGroupVmMapDaoImpl.java +++ b/engine/schema/src/com/cloud/network/as/dao/AutoScaleVmGroupVmMapDaoImpl.java @@ -27,30 +27,30 @@ import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchCriteria; @Component -@Local(value={AutoScaleVmGroupVmMapDao.class}) +@Local(value = {AutoScaleVmGroupVmMapDao.class}) public class AutoScaleVmGroupVmMapDaoImpl extends GenericDaoBase implements AutoScaleVmGroupVmMapDao { - @Override - public Integer countByGroup(long vmGroupId) { + @Override + public Integer countByGroup(long vmGroupId) { - SearchCriteria sc = createSearchCriteria(); - sc.addAnd("vmGroupId", SearchCriteria.Op.EQ, vmGroupId); - return getCount(sc); - } + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("vmGroupId", SearchCriteria.Op.EQ, vmGroupId); + return getCount(sc); + } - @Override - public List listByGroup(long vmGroupId) { - SearchCriteria sc = createSearchCriteria(); - sc.addAnd("vmGroupId", SearchCriteria.Op.EQ, vmGroupId); - return listBy(sc); - } + @Override + public List listByGroup(long vmGroupId) { + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("vmGroupId", SearchCriteria.Op.EQ, vmGroupId); + return listBy(sc); + } - @Override - public int remove(long vmGroupId, long vmId) { - SearchCriteria sc = createSearchCriteria(); - sc.addAnd("vmGroupId", SearchCriteria.Op.EQ, vmGroupId); - sc.addAnd("instanceId", SearchCriteria.Op.EQ, vmId); - return remove(sc); - } + @Override + public int remove(long vmGroupId, long vmId) { + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("vmGroupId", SearchCriteria.Op.EQ, vmGroupId); + sc.addAnd("instanceId", SearchCriteria.Op.EQ, vmId); + return remove(sc); + } } diff --git a/engine/schema/src/com/cloud/network/dao/ExternalFirewallDeviceDao.java b/engine/schema/src/com/cloud/network/dao/ExternalFirewallDeviceDao.java index bb3ebef0e75..b67130b72f0 100644 --- a/engine/schema/src/com/cloud/network/dao/ExternalFirewallDeviceDao.java +++ b/engine/schema/src/com/cloud/network/dao/ExternalFirewallDeviceDao.java @@ -34,25 +34,25 @@ public interface ExternalFirewallDeviceDao extends GenericDao listByPhysicalNetworkAndProvider(long physicalNetworkId, String provider_name); + List listByPhysicalNetworkAndProvider(long physicalNetworkId, String providerName); /** * list the firewall devices added in to this physical network by their allocation state * @param physicalNetworkId physical Network Id - * @param provider_name netwrok service provider name + * @param providerName netwrok service provider name * @param allocationState firewall device allocation state * @return list of ExternalFirewallDeviceVO for the devices in the physical network with a device allocation state */ - List listByProviderAndDeviceAllocationState(long physicalNetworkId, String provider_name, FirewallDeviceAllocationState allocationState); + List listByProviderAndDeviceAllocationState(long physicalNetworkId, String providerName, FirewallDeviceAllocationState allocationState); /** * list the load balancer devices added in to this physical network by the device status (enabled/disabled) * @param physicalNetworkId physical Network Id - * @param provider_name netwrok service provider name + * @param providerName netwrok service provider name * @param state firewall device status * @return list of ExternalFirewallDeviceVO for the devices in the physical network with a device state */ - List listByProviderAndDeviceStaus(long physicalNetworkId, String provider_name, FirewallDeviceState state); + List listByProviderAndDeviceStaus(long physicalNetworkId, String providerName, FirewallDeviceState state); } diff --git a/engine/schema/src/com/cloud/network/dao/ExternalFirewallDeviceVO.java b/engine/schema/src/com/cloud/network/dao/ExternalFirewallDeviceVO.java index 2e49ba83423..141eb530fd0 100644 --- a/engine/schema/src/com/cloud/network/dao/ExternalFirewallDeviceVO.java +++ b/engine/schema/src/com/cloud/network/dao/ExternalFirewallDeviceVO.java @@ -80,10 +80,10 @@ public class ExternalFirewallDeviceVO implements InternalIdentity, Identity { Free, Allocated } - public ExternalFirewallDeviceVO(long hostId, long physicalNetworkId, String provider_name, String device_name, long capacity, boolean dedicated) { + public ExternalFirewallDeviceVO(long hostId, long physicalNetworkId, String providerName, String deviceName, long capacity, boolean dedicated) { this.physicalNetworkId = physicalNetworkId; - this.providerName = provider_name; - this.deviceName = device_name; + this.providerName = providerName; + this.deviceName = deviceName; this.hostId = hostId; this.deviceState = FirewallDeviceState.Disabled; this.allocationState = FirewallDeviceAllocationState.Free; diff --git a/engine/schema/src/com/cloud/network/dao/ExternalLoadBalancerDeviceDao.java b/engine/schema/src/com/cloud/network/dao/ExternalLoadBalancerDeviceDao.java index b7555989f04..91254474e99 100644 --- a/engine/schema/src/com/cloud/network/dao/ExternalLoadBalancerDeviceDao.java +++ b/engine/schema/src/com/cloud/network/dao/ExternalLoadBalancerDeviceDao.java @@ -34,36 +34,36 @@ public interface ExternalLoadBalancerDeviceDao extends GenericDao listByPhysicalNetworkAndProvider(long physicalNetworkId, String provider_name); + List listByPhysicalNetworkAndProvider(long physicalNetworkId, String providerName); /** * list the load balancer devices added in to this physical network by their allocation state * @param physicalNetworkId physical Network Id - * @param provider_name netwrok service provider name + * @param providerName netwrok service provider name * @param allocationState load balancer device allocation state * @return list of ExternalLoadBalancerDeviceVO for the devices in the physical network with a device allocation state */ - List listByProviderAndDeviceAllocationState(long physicalNetworkId, String provider_name, LBDeviceAllocationState allocationState); + List listByProviderAndDeviceAllocationState(long physicalNetworkId, String providerName, LBDeviceAllocationState allocationState); /** * list the load balancer devices added in to this physical network by the device status (enabled/disabled) * @param physicalNetworkId physical Network Id - * @param provider_name netwrok service provider name + * @param providerName netwrok service provider name * @param state load balancer device status * @return list of ExternalLoadBalancerDeviceVO for the devices in the physical network with a device state */ - List listByProviderAndDeviceStaus(long physicalNetworkId, String provider_name, LBDeviceState state); + List listByProviderAndDeviceStaus(long physicalNetworkId, String providerName, LBDeviceState state); /** * list the load balancer devices added in to this physical network by the managed type (external/cloudstack managed) * @param physicalNetworkId physical Network Id - * @param provider_name netwrok service provider name + * @param providerName netwrok service provider name * @param managed managed type * @return list of ExternalLoadBalancerDeviceVO for the devices in to this physical network of a managed type */ - List listByProviderAndManagedType(long physicalNetworkId, String provider_name, boolean managed); + List listByProviderAndManagedType(long physicalNetworkId, String providerName, boolean managed); /** * Find the external load balancer device that is provisioned as GSLB service provider in the pyshical network diff --git a/engine/schema/src/com/cloud/network/dao/ExternalLoadBalancerDeviceDaoImpl.java b/engine/schema/src/com/cloud/network/dao/ExternalLoadBalancerDeviceDaoImpl.java index 432b4a2eb9d..da23bcfad05 100644 --- a/engine/schema/src/com/cloud/network/dao/ExternalLoadBalancerDeviceDaoImpl.java +++ b/engine/schema/src/com/cloud/network/dao/ExternalLoadBalancerDeviceDaoImpl.java @@ -87,18 +87,18 @@ public class ExternalLoadBalancerDeviceDaoImpl extends GenericDaoBase listByPhysicalNetworkAndProvider(long physicalNetworkId, String provider_name) { + public List listByPhysicalNetworkAndProvider(long physicalNetworkId, String providerName) { SearchCriteria sc = physicalNetworkServiceProviderSearch.create(); sc.setParameters("physicalNetworkId", physicalNetworkId); - sc.setParameters("providerName", provider_name); + sc.setParameters("providerName", providerName); return search(sc, null); } @Override - public List listByProviderAndDeviceAllocationState(long physicalNetworkId, String provider_name, LBDeviceAllocationState state) { + public List listByProviderAndDeviceAllocationState(long physicalNetworkId, String providerName, LBDeviceAllocationState state) { SearchCriteria sc = allocationStateSearch.create(); sc.setParameters("physicalNetworkId", physicalNetworkId); - sc.setParameters("providerName", provider_name); + sc.setParameters("providerName", providerName); sc.setParameters("allocationState", state); sc.setParameters("exclusiveGslbProvider", false); return search(sc, null); diff --git a/engine/schema/src/com/cloud/network/dao/ExternalLoadBalancerDeviceVO.java b/engine/schema/src/com/cloud/network/dao/ExternalLoadBalancerDeviceVO.java index d82d5370fe5..80bec1b8152 100644 --- a/engine/schema/src/com/cloud/network/dao/ExternalLoadBalancerDeviceVO.java +++ b/engine/schema/src/com/cloud/network/dao/ExternalLoadBalancerDeviceVO.java @@ -103,11 +103,11 @@ public class ExternalLoadBalancerDeviceVO implements InternalIdentity, Identity Provider // This state is set only for device that can dynamically provision LB appliances } - public ExternalLoadBalancerDeviceVO(long hostId, long physicalNetworkId, String provider_name, String device_name, long capacity, boolean dedicated, + public ExternalLoadBalancerDeviceVO(long hostId, long physicalNetworkId, String providerName, String deviceName, long capacity, boolean dedicated, boolean gslbProvider) { this.physicalNetworkId = physicalNetworkId; - this.providerName = provider_name; - this.deviceName = device_name; + this.providerName = providerName; + this.deviceName = deviceName; this.hostId = hostId; this.state = LBDeviceState.Disabled; this.allocationState = LBDeviceAllocationState.Free; @@ -119,14 +119,14 @@ public class ExternalLoadBalancerDeviceVO implements InternalIdentity, Identity this.gslbProvider = gslbProvider; this.gslbSitePublicIP = null; this.gslbSitePrivateIP = null; - if (device_name.equalsIgnoreCase(ExternalNetworkDeviceManager.NetworkDevice.NetscalerSDXLoadBalancer.getName())) { + if (deviceName.equalsIgnoreCase(ExternalNetworkDeviceManager.NetworkDevice.NetscalerSDXLoadBalancer.getName())) { this.allocationState = LBDeviceAllocationState.Provider; } } - public ExternalLoadBalancerDeviceVO(long hostId, long physicalNetworkId, String provider_name, String device_name, long capacity, boolean dedicated, boolean managed, + public ExternalLoadBalancerDeviceVO(long hostId, long physicalNetworkId, String providerName, String deviceName, long capacity, boolean dedicated, boolean managed, long parentHostId) { - this(hostId, physicalNetworkId, provider_name, device_name, capacity, dedicated, false); + this(hostId, physicalNetworkId, providerName, deviceName, capacity, dedicated, false); this.isManagedDevice = managed; this.parentHostId = parentHostId; } diff --git a/engine/schema/src/com/cloud/network/dao/FirewallRulesCidrsDao.java b/engine/schema/src/com/cloud/network/dao/FirewallRulesCidrsDao.java index f6e7b0eb2d2..55c454860ef 100644 --- a/engine/schema/src/com/cloud/network/dao/FirewallRulesCidrsDao.java +++ b/engine/schema/src/com/cloud/network/dao/FirewallRulesCidrsDao.java @@ -18,6 +18,7 @@ package com.cloud.network.dao; import java.util.List; +import com.cloud.utils.db.DB; import com.cloud.utils.db.GenericDao; public interface FirewallRulesCidrsDao extends GenericDao { @@ -26,4 +27,6 @@ public interface FirewallRulesCidrsDao extends GenericDao getSourceCidrs(long firewallRuleId); + @DB + List listByFirewallRuleId(long firewallRuleId); } diff --git a/engine/schema/src/com/cloud/network/dao/FirewallRulesCidrsDaoImpl.java b/engine/schema/src/com/cloud/network/dao/FirewallRulesCidrsDaoImpl.java index 8c0c468f65b..9f288003499 100644 --- a/engine/schema/src/com/cloud/network/dao/FirewallRulesCidrsDaoImpl.java +++ b/engine/schema/src/com/cloud/network/dao/FirewallRulesCidrsDaoImpl.java @@ -39,6 +39,7 @@ public class FirewallRulesCidrsDaoImpl extends GenericDaoBase listByFirewallRuleId(long firewallRuleId) { + SearchCriteria sc = CidrsSearch.create(); + sc.setParameters("firewallRuleId", firewallRuleId); + + List results = search(sc, null); + + return results; + } + @Override @DB public void persist(long firewallRuleId, List sourceCidrs) { diff --git a/engine/schema/src/com/cloud/network/dao/FirewallRulesCidrsVO.java b/engine/schema/src/com/cloud/network/dao/FirewallRulesCidrsVO.java index e6871bb35ad..ce50e170c64 100644 --- a/engine/schema/src/com/cloud/network/dao/FirewallRulesCidrsVO.java +++ b/engine/schema/src/com/cloud/network/dao/FirewallRulesCidrsVO.java @@ -64,4 +64,8 @@ public class FirewallRulesCidrsVO implements InternalIdentity { return sourceCidrList; } + public void setSourceCidrList(String sourceCidrList) { + this.sourceCidrList = sourceCidrList; + } + } diff --git a/engine/schema/src/com/cloud/network/dao/LoadBalancerCertMapDaoImpl.java b/engine/schema/src/com/cloud/network/dao/LoadBalancerCertMapDaoImpl.java index c84b97dbc60..9986337218f 100644 --- a/engine/schema/src/com/cloud/network/dao/LoadBalancerCertMapDaoImpl.java +++ b/engine/schema/src/com/cloud/network/dao/LoadBalancerCertMapDaoImpl.java @@ -55,9 +55,9 @@ public class LoadBalancerCertMapDaoImpl extends GenericDaoBase sc = findByLbRuleId.create(); - sc.setParameters("loadBalancerId", LbId); + sc.setParameters("loadBalancerId", lbId); return findOneBy(sc); } diff --git a/engine/schema/src/com/cloud/network/dao/NetworkDaoImpl.java b/engine/schema/src/com/cloud/network/dao/NetworkDaoImpl.java index 13fb64e4e9f..0c556c843d9 100644 --- a/engine/schema/src/com/cloud/network/dao/NetworkDaoImpl.java +++ b/engine/schema/src/com/cloud/network/dao/NetworkDaoImpl.java @@ -195,6 +195,7 @@ public class NetworkDaoImpl extends GenericDaoBase implements N NetworksRegularUserCanCreateSearch = createSearchBuilder(Long.class); NetworksRegularUserCanCreateSearch.and("aclType", NetworksRegularUserCanCreateSearch.entity().getAclType(), Op.EQ); + NetworksRegularUserCanCreateSearch.and("displayNetwork", NetworksRegularUserCanCreateSearch.entity().getDisplayNetwork(), Op.EQ); NetworksRegularUserCanCreateSearch.select(null, Func.COUNT, NetworksRegularUserCanCreateSearch.entity().getId()); SearchBuilder join4 = _accountsDao.createSearchBuilder(); join4.and("account", join4.entity().getAccountId(), Op.EQ); @@ -549,6 +550,7 @@ public class NetworkDaoImpl extends GenericDaoBase implements N public long countNetworksUserCanCreate(long ownerId) { SearchCriteria sc = NetworksRegularUserCanCreateSearch.create(); sc.setParameters("aclType", ACLType.Account); + sc.setParameters("displayNetwork", 1); sc.setJoinParameters("accounts", "account", ownerId); sc.setJoinParameters("ntwkOff", "specifyVlan", false); return customSearch(sc, null).get(0); diff --git a/engine/schema/src/com/cloud/network/dao/OvsProviderDao.java b/engine/schema/src/com/cloud/network/dao/OvsProviderDao.java index 2cd21c64c5b..692ec869a17 100644 --- a/engine/schema/src/com/cloud/network/dao/OvsProviderDao.java +++ b/engine/schema/src/com/cloud/network/dao/OvsProviderDao.java @@ -22,9 +22,9 @@ import com.cloud.network.element.OvsProviderVO; import com.cloud.utils.db.GenericDao; public interface OvsProviderDao extends GenericDao { - public OvsProviderVO findByNspId(long nspId); + public OvsProviderVO findByNspId(long nspId); - public List listByEnabled(boolean enabled); + public List listByEnabled(boolean enabled); - public OvsProviderVO findByIdAndEnabled(long id, boolean enabled); + public OvsProviderVO findByIdAndEnabled(long id, boolean enabled); } diff --git a/engine/schema/src/com/cloud/network/dao/OvsProviderDaoImpl.java b/engine/schema/src/com/cloud/network/dao/OvsProviderDaoImpl.java index ec20d4ccc6f..ee13197c0bc 100644 --- a/engine/schema/src/com/cloud/network/dao/OvsProviderDaoImpl.java +++ b/engine/schema/src/com/cloud/network/dao/OvsProviderDaoImpl.java @@ -32,42 +32,42 @@ import com.cloud.utils.db.SearchCriteria; @Local(value = OvsProviderDao.class) @DB() public class OvsProviderDaoImpl extends GenericDaoBase - implements OvsProviderDao { - final SearchBuilder AllFieldsSearch; + implements OvsProviderDao { + final SearchBuilder AllFieldsSearch; - public OvsProviderDaoImpl() { - super(); - AllFieldsSearch = createSearchBuilder(); - AllFieldsSearch.and("id", AllFieldsSearch.entity().getId(), - SearchCriteria.Op.EQ); - AllFieldsSearch.and("nsp_id", AllFieldsSearch.entity().getNspId(), - SearchCriteria.Op.EQ); - AllFieldsSearch.and("uuid", AllFieldsSearch.entity().getUuid(), - SearchCriteria.Op.EQ); - AllFieldsSearch.and("enabled", AllFieldsSearch.entity().isEnabled(), - SearchCriteria.Op.EQ); - AllFieldsSearch.done(); - } + public OvsProviderDaoImpl() { + super(); + AllFieldsSearch = createSearchBuilder(); + AllFieldsSearch.and("id", AllFieldsSearch.entity().getId(), + SearchCriteria.Op.EQ); + AllFieldsSearch.and("nsp_id", AllFieldsSearch.entity().getNspId(), + SearchCriteria.Op.EQ); + AllFieldsSearch.and("uuid", AllFieldsSearch.entity().getUuid(), + SearchCriteria.Op.EQ); + AllFieldsSearch.and("enabled", AllFieldsSearch.entity().isEnabled(), + SearchCriteria.Op.EQ); + AllFieldsSearch.done(); + } - @Override - public OvsProviderVO findByNspId(long nspId) { - SearchCriteria sc = AllFieldsSearch.create(); - sc.setParameters("nsp_id", nspId); - return findOneBy(sc); - } + @Override + public OvsProviderVO findByNspId(long nspId) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("nsp_id", nspId); + return findOneBy(sc); + } - @Override - public List listByEnabled(boolean enabled) { - SearchCriteria sc = AllFieldsSearch.create(); - sc.setParameters("enabled", enabled); - return listBy(sc); - } + @Override + public List listByEnabled(boolean enabled) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("enabled", enabled); + return listBy(sc); + } - @Override - public OvsProviderVO findByIdAndEnabled(long id, boolean enabled) { - SearchCriteria sc = AllFieldsSearch.create(); - sc.setParameters("id", id); - sc.setParameters("enabled", enabled); - return findOneBy(sc); - } + @Override + public OvsProviderVO findByIdAndEnabled(long id, boolean enabled) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("id", id); + sc.setParameters("enabled", enabled); + return findOneBy(sc); + } } diff --git a/engine/schema/src/com/cloud/network/dao/SslCertDaoImpl.java b/engine/schema/src/com/cloud/network/dao/SslCertDaoImpl.java index cab001bf922..99354c5dbc2 100644 --- a/engine/schema/src/com/cloud/network/dao/SslCertDaoImpl.java +++ b/engine/schema/src/com/cloud/network/dao/SslCertDaoImpl.java @@ -33,7 +33,7 @@ public class SslCertDaoImpl extends GenericDaoBase implements S listByAccountId = createSearchBuilder(); listByAccountId.and("accountId", listByAccountId.entity().getAccountId(), SearchCriteria.Op.EQ); listByAccountId.done(); - } + } @Override public List listByAccountId(Long accountId) { diff --git a/engine/schema/src/com/cloud/network/element/OvsProviderVO.java b/engine/schema/src/com/cloud/network/element/OvsProviderVO.java index ddcc9c3b7ec..09ea59d0440 100644 --- a/engine/schema/src/com/cloud/network/element/OvsProviderVO.java +++ b/engine/schema/src/com/cloud/network/element/OvsProviderVO.java @@ -32,68 +32,68 @@ import com.cloud.utils.db.GenericDao; @Entity @Table(name = ("ovs_providers")) public class OvsProviderVO implements OvsProvider { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - long id; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + long id; - @Column(name = "nsp_id") - private long nspId; + @Column(name = "nsp_id") + private long nspId; - @Column(name = "uuid") - private String uuid; + @Column(name = "uuid") + private String uuid; - @Column(name = "enabled") - private boolean enabled; + @Column(name = "enabled") + private boolean enabled; - @Column(name = GenericDao.REMOVED_COLUMN) - Date removed; + @Column(name = GenericDao.REMOVED_COLUMN) + Date removed; - public OvsProviderVO() { - this.uuid = UUID.randomUUID().toString(); - } + public OvsProviderVO() { + this.uuid = UUID.randomUUID().toString(); + } - public OvsProviderVO(long nspId) { - this.nspId = nspId; - this.uuid = UUID.randomUUID().toString(); - } + public OvsProviderVO(long nspId) { + this.nspId = nspId; + this.uuid = UUID.randomUUID().toString(); + } - @Override - public long getNspId() { - return nspId; - } + @Override + public long getNspId() { + return nspId; + } - public String getUuid() { - return uuid; - } + public String getUuid() { + return uuid; + } - @Override - public long getId() { - return id; - } + @Override + public long getId() { + return id; + } - public Date getRemoved() { - return removed; - } + public Date getRemoved() { + return removed; + } - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } - @Override - public boolean isEnabled() { - return this.enabled; - } + @Override + public boolean isEnabled() { + return this.enabled; + } - public void setId(long id) { - this.id = id; - } + public void setId(long id) { + this.id = id; + } - public void setNspId(long nspId) { - this.nspId = nspId; - } + public void setNspId(long nspId) { + this.nspId = nspId; + } - public void setUuid(String uuid) { - this.uuid = uuid; - } + public void setUuid(String uuid) { + this.uuid = uuid; + } } diff --git a/engine/schema/src/com/cloud/network/security/dao/VmRulesetLogDaoImpl.java b/engine/schema/src/com/cloud/network/security/dao/VmRulesetLogDaoImpl.java index cfc3da5d970..c941055ef8d 100644 --- a/engine/schema/src/com/cloud/network/security/dao/VmRulesetLogDaoImpl.java +++ b/engine/schema/src/com/cloud/network/security/dao/VmRulesetLogDaoImpl.java @@ -41,7 +41,7 @@ import com.cloud.utils.db.TransactionLegacy; public class VmRulesetLogDaoImpl extends GenericDaoBase implements VmRulesetLogDao { protected static Logger s_logger = Logger.getLogger(VmRulesetLogDaoImpl.class); private SearchBuilder VmIdSearch; - private String INSERT_OR_UPDATE = "INSERT INTO op_vm_ruleset_log (instance_id, created, logsequence) " + private String InsertOrUpdateSQl = "INSERT INTO op_vm_ruleset_log (instance_id, created, logsequence) " + " VALUES(?, now(), 1) ON DUPLICATE KEY UPDATE logsequence=logsequence+1"; private static HashMap cachedPrepStmtStrings = new HashMap(); final static private int cacheStringSizes[] = {512, 256, 128, 64, 32, 16, 8, 4, 2, 1}; @@ -160,7 +160,7 @@ public class VmRulesetLogDaoImpl extends GenericDaoBase im int count = 0; boolean success = true; try { - stmtInsert = txn.prepareAutoCloseStatement(INSERT_OR_UPDATE); + stmtInsert = txn.prepareAutoCloseStatement(InsertOrUpdateSQl); txn.start(); for (Long vmId : workItems) { diff --git a/engine/schema/src/com/cloud/offerings/NetworkOfferingVO.java b/engine/schema/src/com/cloud/offerings/NetworkOfferingVO.java index a0234621deb..bf078074948 100755 --- a/engine/schema/src/com/cloud/offerings/NetworkOfferingVO.java +++ b/engine/schema/src/com/cloud/offerings/NetworkOfferingVO.java @@ -479,8 +479,8 @@ public class NetworkOfferingVO implements NetworkOffering { return this.concurrentConnections; } - public void setConcurrentConnections(Integer concurrent_connections) { - this.concurrentConnections = concurrent_connections; + public void setConcurrentConnections(Integer concurrentConnections) { + this.concurrentConnections = concurrentConnections; } public void setPublicLb(boolean publicLb) { diff --git a/engine/schema/src/com/cloud/service/ServiceOfferingVO.java b/engine/schema/src/com/cloud/service/ServiceOfferingVO.java index f1cc39b9326..3873dd272f4 100755 --- a/engine/schema/src/com/cloud/service/ServiceOfferingVO.java +++ b/engine/schema/src/com/cloud/service/ServiceOfferingVO.java @@ -62,10 +62,10 @@ public class ServiceOfferingVO extends DiskOfferingVO implements ServiceOffering private String hostTag; @Column(name = "default_use") - private boolean default_use; + private boolean defaultUse; @Column(name = "vm_type") - private String vm_type; + private String vmType; @Column(name = "sort_key") int sortKey; @@ -89,7 +89,7 @@ public class ServiceOfferingVO extends DiskOfferingVO implements ServiceOffering } public ServiceOfferingVO(String name, Integer cpu, Integer ramSize, Integer speed, Integer rateMbps, Integer multicastRateMbps, boolean offerHA, String displayText, - boolean useLocalStorage, boolean recreatable, String tags, boolean systemUse, VirtualMachine.Type vm_type, boolean defaultUse) { + boolean useLocalStorage, boolean recreatable, String tags, boolean systemUse, VirtualMachine.Type vmType, boolean defaultUse) { super(name, displayText, false, tags, recreatable, useLocalStorage, systemUse, true); this.cpu = cpu; this.ramSize = ramSize; @@ -97,14 +97,14 @@ public class ServiceOfferingVO extends DiskOfferingVO implements ServiceOffering this.rateMbps = rateMbps; this.multicastRateMbps = multicastRateMbps; this.offerHA = offerHA; - this.limitCpuUse = false; - this.volatileVm = false; - this.default_use = defaultUse; - this.vm_type = vm_type == null ? null : vm_type.toString().toLowerCase(); + limitCpuUse = false; + volatileVm = false; + this.defaultUse = defaultUse; + this.vmType = vmType == null ? null : vmType.toString().toLowerCase(); } public ServiceOfferingVO(String name, Integer cpu, Integer ramSize, Integer speed, Integer rateMbps, Integer multicastRateMbps, boolean offerHA, boolean limitCpuUse, - boolean volatileVm, String displayText, boolean useLocalStorage, boolean recreatable, String tags, boolean systemUse, VirtualMachine.Type vm_type, + boolean volatileVm, String displayText, boolean useLocalStorage, boolean recreatable, String tags, boolean systemUse, VirtualMachine.Type vmType, Long domainId) { super(name, displayText, false, tags, recreatable, useLocalStorage, systemUse, true, domainId); this.cpu = cpu; @@ -115,12 +115,12 @@ public class ServiceOfferingVO extends DiskOfferingVO implements ServiceOffering this.offerHA = offerHA; this.limitCpuUse = limitCpuUse; this.volatileVm = volatileVm; - this.vm_type = vm_type == null ? null : vm_type.toString().toLowerCase(); + this.vmType = vmType == null ? null : vmType.toString().toLowerCase(); } public ServiceOfferingVO(String name, Integer cpu, Integer ramSize, Integer speed, Integer rateMbps, Integer multicastRateMbps, boolean offerHA, boolean limitResourceUse, boolean volatileVm, String displayText, boolean useLocalStorage, boolean recreatable, String tags, boolean systemUse, - VirtualMachine.Type vm_type, Long domainId, String hostTag) { + VirtualMachine.Type vmType, Long domainId, String hostTag) { this(name, cpu, ramSize, @@ -135,14 +135,14 @@ public class ServiceOfferingVO extends DiskOfferingVO implements ServiceOffering recreatable, tags, systemUse, - vm_type, + vmType, domainId); this.hostTag = hostTag; } public ServiceOfferingVO(String name, Integer cpu, Integer ramSize, Integer speed, Integer rateMbps, Integer multicastRateMbps, boolean offerHA, boolean limitResourceUse, boolean volatileVm, String displayText, boolean useLocalStorage, boolean recreatable, String tags, boolean systemUse, - VirtualMachine.Type vm_type, Long domainId, String hostTag, String deploymentPlanner) { + VirtualMachine.Type vmType, Long domainId, String hostTag, String deploymentPlanner) { this(name, cpu, ramSize, @@ -157,24 +157,33 @@ public class ServiceOfferingVO extends DiskOfferingVO implements ServiceOffering recreatable, tags, systemUse, - vm_type, + vmType, domainId, hostTag); this.deploymentPlanner = deploymentPlanner; } public ServiceOfferingVO(ServiceOfferingVO offering) { - super(offering.getId(), offering.getName(), offering.getDisplayText(), false, offering.getTags(), offering.isRecreatable(), offering.getUseLocalStorage(), offering.getSystemUse(), true, offering.getDomainId()); - this.cpu = offering.getCpu(); - this.ramSize = offering.getRamSize(); - this.speed = offering.getSpeed(); - this.rateMbps = offering.getRateMbps(); - this.multicastRateMbps = offering.getMulticastRateMbps(); - this.offerHA = offering.getOfferHA(); - this.limitCpuUse = offering.getLimitCpuUse(); - this.volatileVm = offering.getVolatileVm(); - this.hostTag = offering.getHostTag(); - this.vm_type = offering.getSystemVmType(); + super(offering.getId(), + offering.getName(), + offering.getDisplayText(), + false, + offering.getTags(), + offering.isRecreatable(), + offering.getUseLocalStorage(), + offering.getSystemUse(), + true, + offering.getDomainId()); + cpu = offering.getCpu(); + ramSize = offering.getRamSize(); + speed = offering.getSpeed(); + rateMbps = offering.getRateMbps(); + multicastRateMbps = offering.getMulticastRateMbps(); + offerHA = offering.getOfferHA(); + limitCpuUse = offering.getLimitCpuUse(); + volatileVm = offering.getVolatileVm(); + hostTag = offering.getHostTag(); + vmType = offering.getSystemVmType(); } @Override @@ -197,7 +206,7 @@ public class ServiceOfferingVO extends DiskOfferingVO implements ServiceOffering @Override public boolean getDefaultUse() { - return default_use; + return defaultUse; } @Override @@ -267,7 +276,7 @@ public class ServiceOfferingVO extends DiskOfferingVO implements ServiceOffering @Override public String getSystemVmType() { - return vm_type; + return vmType; } @Override @@ -316,6 +325,6 @@ public class ServiceOfferingVO extends DiskOfferingVO implements ServiceOffering } public void setDynamicFlag(boolean isdynamic) { - this.isDynamic = isdynamic; + isDynamic = isdynamic; } } diff --git a/engine/schema/src/com/cloud/service/dao/ServiceOfferingDao.java b/engine/schema/src/com/cloud/service/dao/ServiceOfferingDao.java index ecab8d2943c..ab818538d2a 100644 --- a/engine/schema/src/com/cloud/service/dao/ServiceOfferingDao.java +++ b/engine/schema/src/com/cloud/service/dao/ServiceOfferingDao.java @@ -34,7 +34,7 @@ public interface ServiceOfferingDao extends GenericDao List findServiceOfferingByDomainId(Long domainId); - List findSystemOffering(Long domainId, Boolean isSystem, String vm_type); + List findSystemOffering(Long domainId, Boolean isSystem, String vmType); ServiceOfferingVO persistDeafultServiceOffering(ServiceOfferingVO offering); diff --git a/engine/schema/src/com/cloud/service/dao/ServiceOfferingDaoImpl.java b/engine/schema/src/com/cloud/service/dao/ServiceOfferingDaoImpl.java index 5d423e0a1e7..1905d9e41f6 100644 --- a/engine/schema/src/com/cloud/service/dao/ServiceOfferingDaoImpl.java +++ b/engine/schema/src/com/cloud/service/dao/ServiceOfferingDaoImpl.java @@ -25,10 +25,10 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.persistence.EntityExistsException; -import com.cloud.event.UsageEventVO; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; +import com.cloud.event.UsageEventVO; import com.cloud.service.ServiceOfferingDetailsVO; import com.cloud.service.ServiceOfferingVO; import com.cloud.utils.db.DB; @@ -128,11 +128,11 @@ public class ServiceOfferingDaoImpl extends GenericDaoBase findSystemOffering(Long domainId, Boolean isSystem, String vm_type) { + public List findSystemOffering(Long domainId, Boolean isSystem, String vmType) { SearchCriteria sc = SystemServiceOffering.create(); sc.setParameters("domainId", domainId); sc.setParameters("system", isSystem); - sc.setParameters("vm_type", vm_type); + sc.setParameters("vm_type", vmType); return listBy(sc); } @@ -211,7 +211,7 @@ public class ServiceOfferingDaoImpl extends GenericDaoBase dynamicOffering = userVmDetailsDao.listDetailsKeyPairs(vmId); - return getcomputeOffering(offering, dynamicOffering); + return getcomputeOffering(offering, dynamicOffering); } return offering; } diff --git a/engine/schema/src/com/cloud/storage/DiskOfferingVO.java b/engine/schema/src/com/cloud/storage/DiskOfferingVO.java index 1ff62ab7f24..d1a48d20c91 100755 --- a/engine/schema/src/com/cloud/storage/DiskOfferingVO.java +++ b/engine/schema/src/com/cloud/storage/DiskOfferingVO.java @@ -207,7 +207,7 @@ public class DiskOfferingVO implements DiskOffering { } public DiskOfferingVO(long id, String name, String displayText, boolean mirrored, String tags, boolean recreatable, - boolean useLocalStorage, boolean systemUse, boolean customized, Long domainId) { + boolean useLocalStorage, boolean systemUse, boolean customized, Long domainId) { this.id = id; type = Type.Service; this.name = name; diff --git a/engine/schema/src/com/cloud/storage/VolumeVO.java b/engine/schema/src/com/cloud/storage/VolumeVO.java index 944847f9298..901e07c70ef 100755 --- a/engine/schema/src/com/cloud/storage/VolumeVO.java +++ b/engine/schema/src/com/cloud/storage/VolumeVO.java @@ -587,7 +587,6 @@ public class VolumeVO implements Volume { this.state = state; } - @Override public void setHypervisorSnapshotReserve(Integer hypervisorSnapshotReserve) { this.hypervisorSnapshotReserve = hypervisorSnapshotReserve; } diff --git a/engine/schema/src/com/cloud/storage/dao/SnapshotDao.java b/engine/schema/src/com/cloud/storage/dao/SnapshotDao.java index d42ef66d4e1..f55352b2ef2 100644 --- a/engine/schema/src/com/cloud/storage/dao/SnapshotDao.java +++ b/engine/schema/src/com/cloud/storage/dao/SnapshotDao.java @@ -57,13 +57,4 @@ public interface SnapshotDao extends GenericDao, StateDao listAllByStatus(Snapshot.State... status); - /** - * Gets the Total Secondary Storage space (in bytes) used by snapshots - * allocated for an account - * - * @param account - * @return total Secondary Storage space allocated - */ - long secondaryStorageUsedForAccount(long accountId); - } diff --git a/engine/schema/src/com/cloud/storage/dao/SnapshotDaoImpl.java b/engine/schema/src/com/cloud/storage/dao/SnapshotDaoImpl.java index f15319849c7..204447c6909 100644 --- a/engine/schema/src/com/cloud/storage/dao/SnapshotDaoImpl.java +++ b/engine/schema/src/com/cloud/storage/dao/SnapshotDaoImpl.java @@ -36,7 +36,6 @@ import com.cloud.storage.Snapshot.Type; import com.cloud.storage.SnapshotVO; import com.cloud.storage.Volume; import com.cloud.storage.VolumeVO; -import com.cloud.storage.dao.VolumeDaoImpl.SumCount; import com.cloud.tags.dao.ResourceTagDao; import com.cloud.utils.db.DB; import com.cloud.utils.db.Filter; @@ -46,7 +45,6 @@ import com.cloud.utils.db.JoinBuilder.JoinType; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria.Func; -import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.TransactionLegacy; import com.cloud.vm.VMInstanceVO; import com.cloud.vm.dao.VMInstanceDao; @@ -72,7 +70,6 @@ public class SnapshotDaoImpl extends GenericDaoBase implements private SearchBuilder InstanceIdSearch; private SearchBuilder StatusSearch; private GenericSearchBuilder CountSnapshotsByAccount; - private GenericSearchBuilder secondaryStorageSearch; @Inject ResourceTagDao _tagsDao; @Inject @@ -178,6 +175,7 @@ public class SnapshotDaoImpl extends GenericDaoBase implements CountSnapshotsByAccount = createSearchBuilder(Long.class); CountSnapshotsByAccount.select(null, Func.COUNT, null); CountSnapshotsByAccount.and("account", CountSnapshotsByAccount.entity().getAccountId(), SearchCriteria.Op.EQ); + CountSnapshotsByAccount.and("status", CountSnapshotsByAccount.entity().getState(), SearchCriteria.Op.NIN); CountSnapshotsByAccount.and("removed", CountSnapshotsByAccount.entity().getRemoved(), SearchCriteria.Op.NULL); CountSnapshotsByAccount.done(); @@ -193,12 +191,6 @@ public class SnapshotDaoImpl extends GenericDaoBase implements InstanceIdSearch.join("instanceSnapshots", volumeSearch, volumeSearch.entity().getId(), InstanceIdSearch.entity().getVolumeId(), JoinType.INNER); InstanceIdSearch.done(); - - secondaryStorageSearch = createSearchBuilder(SumCount.class); - secondaryStorageSearch.select("sum", Func.SUM, secondaryStorageSearch.entity().getSize()); - secondaryStorageSearch.and("accountId", secondaryStorageSearch.entity().getAccountId(), Op.EQ); - secondaryStorageSearch.and("isRemoved", secondaryStorageSearch.entity().getRemoved(), Op.NULL); - secondaryStorageSearch.done(); } @Override @@ -277,6 +269,7 @@ public class SnapshotDaoImpl extends GenericDaoBase implements public Long countSnapshotsForAccount(long accountId) { SearchCriteria sc = CountSnapshotsByAccount.create(); sc.setParameters("account", accountId); + sc.setParameters("status", State.Error, State.Destroyed); return customSearch(sc, null).get(0); } @@ -333,15 +326,4 @@ public class SnapshotDaoImpl extends GenericDaoBase implements return true; } - @Override - public long secondaryStorageUsedForAccount(long accountId) { - SearchCriteria sc = secondaryStorageSearch.create(); - sc.setParameters("accountId", accountId); - List storageSpace = customSearch(sc, null); - if (storageSpace != null) { - return storageSpace.get(0).sum; - } else { - return 0; - } - } } diff --git a/engine/schema/src/com/cloud/storage/dao/SnapshotDetailsVO.java b/engine/schema/src/com/cloud/storage/dao/SnapshotDetailsVO.java index 9bc4b4c4726..35a724435e7 100644 --- a/engine/schema/src/com/cloud/storage/dao/SnapshotDetailsVO.java +++ b/engine/schema/src/com/cloud/storage/dao/SnapshotDetailsVO.java @@ -44,6 +44,10 @@ public class SnapshotDetailsVO implements ResourceDetail { @Column(name = "value") String value; + public SnapshotDetailsVO() { + + } + public SnapshotDetailsVO(Long resourceId, String name, String value) { this.resourceId = resourceId; this.name = name; diff --git a/engine/schema/src/com/cloud/storage/dao/VMTemplateHostDaoImpl.java b/engine/schema/src/com/cloud/storage/dao/VMTemplateHostDaoImpl.java index 6cd614d0efc..3d067a2bead 100755 --- a/engine/schema/src/com/cloud/storage/dao/VMTemplateHostDaoImpl.java +++ b/engine/schema/src/com/cloud/storage/dao/VMTemplateHostDaoImpl.java @@ -64,8 +64,8 @@ public class VMTemplateHostDaoImpl extends GenericDaoBase TemplateStatusSearch; protected final SearchBuilder TemplateStatesSearch; protected final SearchBuilder updateStateSearch; - protected SearchBuilder ZONE_TEMPLATE_SEARCH; - protected SearchBuilder LOCAL_SECONDARY_STORAGE_SEARCH; + protected SearchBuilder ZoneTemplateSearch; + protected SearchBuilder LocalSecondaryStorageSearch; protected static final String UPDATE_TEMPLATE_HOST_REF = "UPDATE template_host_ref SET download_state = ?, download_pct= ?, last_updated = ? " + ", error_str = ?, local_path = ?, job_id = ? " + "WHERE host_id = ? and type_id = ?"; @@ -131,25 +131,25 @@ public class VMTemplateHostDaoImpl extends GenericDaoBase params) throws ConfigurationException { boolean result = super.configure(name, params); - ZONE_TEMPLATE_SEARCH = createSearchBuilder(); - ZONE_TEMPLATE_SEARCH.and("template_id", ZONE_TEMPLATE_SEARCH.entity().getTemplateId(), SearchCriteria.Op.EQ); - ZONE_TEMPLATE_SEARCH.and("state", ZONE_TEMPLATE_SEARCH.entity().getDownloadState(), SearchCriteria.Op.EQ); + ZoneTemplateSearch = createSearchBuilder(); + ZoneTemplateSearch.and("template_id", ZoneTemplateSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); + ZoneTemplateSearch.and("state", ZoneTemplateSearch.entity().getDownloadState(), SearchCriteria.Op.EQ); SearchBuilder hostSearch = _hostDao.createSearchBuilder(); hostSearch.and("zone_id", hostSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); - ZONE_TEMPLATE_SEARCH.join("tmplHost", hostSearch, hostSearch.entity().getId(), ZONE_TEMPLATE_SEARCH.entity().getHostId(), JoinBuilder.JoinType.INNER); - ZONE_TEMPLATE_SEARCH.done(); + ZoneTemplateSearch.join("tmplHost", hostSearch, hostSearch.entity().getId(), ZoneTemplateSearch.entity().getHostId(), JoinBuilder.JoinType.INNER); + ZoneTemplateSearch.done(); - LOCAL_SECONDARY_STORAGE_SEARCH = createSearchBuilder(); - LOCAL_SECONDARY_STORAGE_SEARCH.and("template_id", LOCAL_SECONDARY_STORAGE_SEARCH.entity().getTemplateId(), SearchCriteria.Op.EQ); - LOCAL_SECONDARY_STORAGE_SEARCH.and("state", LOCAL_SECONDARY_STORAGE_SEARCH.entity().getDownloadState(), SearchCriteria.Op.EQ); + LocalSecondaryStorageSearch = createSearchBuilder(); + LocalSecondaryStorageSearch.and("template_id", LocalSecondaryStorageSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); + LocalSecondaryStorageSearch.and("state", LocalSecondaryStorageSearch.entity().getDownloadState(), SearchCriteria.Op.EQ); SearchBuilder localSecondaryHost = _hostDao.createSearchBuilder(); localSecondaryHost.and("private_ip_address", localSecondaryHost.entity().getPrivateIpAddress(), SearchCriteria.Op.EQ); localSecondaryHost.and("state", localSecondaryHost.entity().getStatus(), SearchCriteria.Op.EQ); localSecondaryHost.and("data_center_id", localSecondaryHost.entity().getDataCenterId(), SearchCriteria.Op.EQ); localSecondaryHost.and("type", localSecondaryHost.entity().getType(), SearchCriteria.Op.EQ); - LOCAL_SECONDARY_STORAGE_SEARCH.join("host", localSecondaryHost, localSecondaryHost.entity().getId(), LOCAL_SECONDARY_STORAGE_SEARCH.entity().getHostId(), + LocalSecondaryStorageSearch.join("host", localSecondaryHost, localSecondaryHost.entity().getId(), LocalSecondaryStorageSearch.entity().getHostId(), JoinBuilder.JoinType.INNER); - LOCAL_SECONDARY_STORAGE_SEARCH.done(); + LocalSecondaryStorageSearch.done(); return result; } @@ -330,7 +330,7 @@ public class VMTemplateHostDaoImpl extends GenericDaoBase listByZoneTemplate(long dcId, long templateId, boolean readyOnly) { - SearchCriteria sc = ZONE_TEMPLATE_SEARCH.create(); + SearchCriteria sc = ZoneTemplateSearch.create(); sc.setParameters("template_id", templateId); sc.setJoinParameters("tmplHost", "zone_id", dcId); if (readyOnly) { @@ -365,7 +365,7 @@ public class VMTemplateHostDaoImpl extends GenericDaoBase sc = LOCAL_SECONDARY_STORAGE_SEARCH.create(); + SearchCriteria sc = LocalSecondaryStorageSearch.create(); sc.setJoinParameters("host", "private_ip_address", computingHost.getPrivateIpAddress()); sc.setJoinParameters("host", "state", com.cloud.host.Status.Up); sc.setJoinParameters("host", "data_center_id", computingHost.getDataCenterId()); diff --git a/engine/schema/src/com/cloud/upgrade/DatabaseIntegrityChecker.java b/engine/schema/src/com/cloud/upgrade/DatabaseIntegrityChecker.java index c1120bd217f..c20a418313d 100755 --- a/engine/schema/src/com/cloud/upgrade/DatabaseIntegrityChecker.java +++ b/engine/schema/src/com/cloud/upgrade/DatabaseIntegrityChecker.java @@ -39,7 +39,7 @@ import com.cloud.utils.exception.CloudRuntimeException; @Component @Local(value = {SystemIntegrityChecker.class}) public class DatabaseIntegrityChecker extends AdapterBase implements SystemIntegrityChecker { - private final Logger s_logger = Logger.getLogger(DatabaseIntegrityChecker.class); + private static final Logger s_logger = Logger.getLogger(DatabaseIntegrityChecker.class); @Inject VersionDao _dao; diff --git a/engine/schema/src/com/cloud/upgrade/DatabaseUpgradeChecker.java b/engine/schema/src/com/cloud/upgrade/DatabaseUpgradeChecker.java index c5eea10861a..0761c9fe61c 100755 --- a/engine/schema/src/com/cloud/upgrade/DatabaseUpgradeChecker.java +++ b/engine/schema/src/com/cloud/upgrade/DatabaseUpgradeChecker.java @@ -80,7 +80,7 @@ import com.cloud.utils.exception.CloudRuntimeException; @Local(value = {SystemIntegrityChecker.class}) public class DatabaseUpgradeChecker implements SystemIntegrityChecker { - private final Logger s_logger = Logger.getLogger(DatabaseUpgradeChecker.class); + private static final Logger s_logger = Logger.getLogger(DatabaseUpgradeChecker.class); protected HashMap _upgradeMap = new HashMap(); diff --git a/engine/schema/src/com/cloud/upgrade/dao/Upgrade218to22.java b/engine/schema/src/com/cloud/upgrade/dao/Upgrade218to22.java index 5aa4b5f341d..4f0671585d7 100644 --- a/engine/schema/src/com/cloud/upgrade/dao/Upgrade218to22.java +++ b/engine/schema/src/com/cloud/upgrade/dao/Upgrade218to22.java @@ -72,10 +72,10 @@ public class Upgrade218to22 implements DbUpgrade { } protected long insertNetworkOffering(Connection conn, String name, String displayText, String trafficType, boolean systemOnly, boolean defaultNetworkOffering, - String availability, boolean dns_service, boolean gateway_service, boolean firewall_service, boolean lb_service, boolean userdata_service, boolean vpn_service, - boolean dhcp_service) { + String availability, boolean dnsService, boolean gatewayService, boolean firewallService, boolean lbService, boolean userdataService, boolean vpnService, + boolean dhcpService) { String insertSql = - "INSERT INTO network_offerings (name, display_text, nw_rate, mc_rate, concurrent_connections, traffic_type, tags, system_only, specify_vlan, service_offering_id, created, removed, `default`, availability, dns_service, gateway_service, firewall_service, lb_service, userdata_service, vpn_service, dhcp_service) " + "INSERT INTO network_offerings (name, display_text, nw_rate, mc_rate, concurrent_connections, traffic_type, tags, system_only, specify_vlan, service_offering_id, created, removed, `default`, availability, dnsService, gatewayService, firewallService, lbService, userdataService, vpnService, dhcpService) " + "VALUES (?, ?, NULL, NULL, NULL, ?, NULL, ?, 0, NULL, now(), NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; try { PreparedStatement pstmt = conn.prepareStatement(insertSql, Statement.RETURN_GENERATED_KEYS); @@ -86,13 +86,13 @@ public class Upgrade218to22 implements DbUpgrade { pstmt.setBoolean(i++, systemOnly); pstmt.setBoolean(i++, defaultNetworkOffering); pstmt.setString(i++, availability); - pstmt.setBoolean(i++, dns_service); - pstmt.setBoolean(i++, gateway_service); - pstmt.setBoolean(i++, firewall_service); - pstmt.setBoolean(i++, lb_service); - pstmt.setBoolean(i++, userdata_service); - pstmt.setBoolean(i++, vpn_service); - pstmt.setBoolean(i++, dhcp_service); + pstmt.setBoolean(i++, dnsService); + pstmt.setBoolean(i++, gatewayService); + pstmt.setBoolean(i++, firewallService); + pstmt.setBoolean(i++, lbService); + pstmt.setBoolean(i++, userdataService); + pstmt.setBoolean(i++, vpnService); + pstmt.setBoolean(i++, dhcpService); pstmt.executeUpdate(); ResultSet rs = pstmt.getGeneratedKeys(); rs.next(); diff --git a/engine/schema/src/com/cloud/upgrade/dao/Upgrade2213to2214.java b/engine/schema/src/com/cloud/upgrade/dao/Upgrade2213to2214.java index 3edefcb7d09..f3293ba5549 100644 --- a/engine/schema/src/com/cloud/upgrade/dao/Upgrade2213to2214.java +++ b/engine/schema/src/com/cloud/upgrade/dao/Upgrade2213to2214.java @@ -301,10 +301,10 @@ public class Upgrade2213to2214 implements DbUpgrade { DbUpgradeUtils.dropKeysIfExist(conn, "cloud.user_ip_address", keys, false); try { PreparedStatement pstmt = conn.prepareStatement( - "ALTER TABLE `cloud`.`user_ip_address` ADD CONSTRAINT `fk_user_ip_address__account_id` FOREIGN KEY (`account_id`) REFERENCES `account`(`id`)"); + "ALTER TABLE `cloud`.`user_ip_address` ADD CONSTRAINT `fk_user_ip_address__account_id` FOREIGN KEY (`account_id`) REFERENCES `account`(`id`)"); pstmt.executeUpdate(); pstmt = conn.prepareStatement( - "ALTER TABLE `cloud`.`user_ip_address` ADD CONSTRAINT `fk_user_ip_address__vlan_db_id` FOREIGN KEY (`vlan_db_id`) REFERENCES `vlan`(`id`) ON DELETE CASCADE"); + "ALTER TABLE `cloud`.`user_ip_address` ADD CONSTRAINT `fk_user_ip_address__vlan_db_id` FOREIGN KEY (`vlan_db_id`) REFERENCES `vlan`(`id`) ON DELETE CASCADE"); pstmt.executeUpdate(); pstmt = conn.prepareStatement( "ALTER TABLE `cloud`.`user_ip_address` ADD CONSTRAINT `fk_user_ip_address__data_center_id`" + diff --git a/engine/schema/src/com/cloud/upgrade/dao/Upgrade2214to30.java b/engine/schema/src/com/cloud/upgrade/dao/Upgrade2214to30.java index 410c1cc69c5..58dd916ea6e 100644 --- a/engine/schema/src/com/cloud/upgrade/dao/Upgrade2214to30.java +++ b/engine/schema/src/com/cloud/upgrade/dao/Upgrade2214to30.java @@ -34,6 +34,7 @@ import org.apache.log4j.Logger; import com.cloud.offering.NetworkOffering; import com.cloud.utils.crypt.DBEncryptionUtil; import com.cloud.utils.crypt.EncryptionSecretKeyChecker; +import com.cloud.utils.db.TransactionLegacy; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.script.Script; @@ -126,6 +127,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { */ PreparedStatement pstmt = null; ResultSet rs = null; + List pstmt2Close = new ArrayList(); PreparedStatement pstmtUpdate = null; try { // Load all DataCenters @@ -144,6 +146,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { String vmwareGuestLabel = getNetworkLabelFromConfig(conn, "vmware.guest.vswitch"); pstmt = conn.prepareStatement("SELECT id, domain_id, networktype, vnet, name, removed FROM `cloud`.`data_center`"); + pstmt2Close.add(pstmt); rs = pstmt.executeQuery(); while (rs.next()) { long zoneId = rs.getLong(1); @@ -165,6 +168,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { //check if public network needs to be created boolean crtPbNtwk = false; pstmt = conn.prepareStatement("SELECT * FROM `cloud`.`networks` where traffic_type=\"public\" and data_center_id=?"); + pstmt2Close.add(pstmt); pstmt.setLong(1, zoneId); ResultSet rs1 = pstmt.executeQuery(); if (rs1.next()) { @@ -174,6 +178,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { //check if there are multiple guest networks configured using network_tags PreparedStatement pstmt2 = conn.prepareStatement("SELECT distinct tag FROM `cloud`.`network_tags` t JOIN `cloud`.`networks` n ON t.network_id = n.id WHERE n.data_center_id = ? and n.removed IS NULL"); + pstmt2Close.add(pstmt2); pstmt2.setLong(1, zoneId); ResultSet rsTags = pstmt2.executeQuery(); if (rsTags.next()) { @@ -185,6 +190,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { PreparedStatement pstmt4 = conn.prepareStatement("SELECT v.* FROM `cloud`.`op_dc_vnet_alloc` v JOIN `cloud`.`networks` n ON CONCAT('vlan://' , v.vnet) = " + "n.broadcast_uri WHERE v.taken IS NOT NULL AND v.data_center_id = ? AND n.removed IS NULL"); + pstmt2Close.add(pstmt4); pstmt4.setLong(1, zoneId); ResultSet rsVNet = pstmt4.executeQuery(); @@ -213,11 +219,11 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { "Cannot upgrade this setup since it uses guest vnet and will have multiple physical networks. Please check the logs for details on how to proceed"); } rsVNet.close(); - pstmt4.close(); //Clean up any vnets that have no live networks/nics pstmt4 = conn.prepareStatement("SELECT v.id, v.vnet, v.reservation_id FROM `cloud`.`op_dc_vnet_alloc` v LEFT JOIN networks n ON CONCAT('vlan://' , v.vnet) = n.broadcast_uri WHERE v.taken IS NOT NULL AND v.data_center_id = ? AND n.broadcast_uri IS NULL AND n.removed IS NULL"); + pstmt2Close.add(pstmt4); pstmt4.setLong(1, zoneId); rsVNet = pstmt4.executeQuery(); while (rsVNet.next()) { @@ -226,6 +232,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { String reservationId = rsVNet.getString(3); //does this vnet have any nic associated? PreparedStatement pstmt5 = conn.prepareStatement("SELECT id, instance_id FROM `cloud`.`nics` where broadcast_uri = ? and removed IS NULL"); + pstmt2Close.add(pstmt5); String uri = "vlan://" + vnetValue; pstmt5.setString(1, uri); ResultSet rsNic = pstmt5.executeQuery(); @@ -355,25 +362,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { } catch (SQLException e) { throw new CloudRuntimeException("Exception while adding PhysicalNetworks", e); } finally { - if (pstmtUpdate != null) { - try { - pstmtUpdate.close(); - } catch (SQLException e) { - } - } - if (rs != null) { - try { - rs.close(); - } catch (SQLException e) { - } - } - if (pstmt != null) { - try { - pstmt.close(); - } catch (SQLException e) { - } - } - + TransactionLegacy.closePstmts(pstmt2Close); } } @@ -428,10 +417,12 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { private void encryptHostDetails(Connection conn) { s_logger.debug("Encrypting host details"); + List pstmt2Close = new ArrayList(); PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = conn.prepareStatement("select id, value from `cloud`.`host_details` where name = 'password'"); + pstmt2Close.add(pstmt); rs = pstmt.executeQuery(); while (rs.next()) { long id = rs.getLong(1); @@ -441,6 +432,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { } String encryptedValue = DBEncryptionUtil.encrypt(value); pstmt = conn.prepareStatement("update `cloud`.`host_details` set value=? where id=?"); + pstmt2Close.add(pstmt); pstmt.setBytes(1, encryptedValue.getBytes("UTF-8")); pstmt.setLong(2, id); pstmt.executeUpdate(); @@ -450,27 +442,20 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { } catch (UnsupportedEncodingException e) { throw new CloudRuntimeException("Unable encrypt host_details values ", e); } finally { - try { - if (rs != null) { - rs.close(); - } - - if (pstmt != null) { - pstmt.close(); - } - } catch (SQLException e) { - } + TransactionLegacy.closePstmts(pstmt2Close); } s_logger.debug("Done encrypting host details"); } private void encryptVNCPassword(Connection conn) { s_logger.debug("Encrypting vm_instance vnc_password"); + List pstmt2Close = new ArrayList(); PreparedStatement pstmt = null; ResultSet rs = null; try { int numRows = 0; pstmt = conn.prepareStatement("select count(id) from `cloud`.`vm_instance`"); + pstmt2Close.add(pstmt); rs = pstmt.executeQuery(); if (rs.next()) { numRows = rs.getInt(1); @@ -480,6 +465,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { int offset = 0; while (offset < numRows) { pstmt = conn.prepareStatement("select id, vnc_password from `cloud`.`vm_instance` limit " + offset + ", 500"); + pstmt2Close.add(pstmt); rs = pstmt.executeQuery(); while (rs.next()) { long id = rs.getLong(1); @@ -502,32 +488,26 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { } catch (UnsupportedEncodingException e) { throw new CloudRuntimeException("Unable encrypt vm_instance vnc_password ", e); } finally { - try { - if (rs != null) { - rs.close(); - } - - if (pstmt != null) { - pstmt.close(); - } - } catch (SQLException e) { - } + TransactionLegacy.closePstmts(pstmt2Close); } s_logger.debug("Done encrypting vm_instance vnc_password"); } private void encryptUserCredentials(Connection conn) { s_logger.debug("Encrypting user keys"); + List pstmt2Close = new ArrayList(); PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = conn.prepareStatement("select id, secret_key from `cloud`.`user`"); + pstmt2Close.add(pstmt); rs = pstmt.executeQuery(); while (rs.next()) { long id = rs.getLong(1); String secretKey = rs.getString(2); String encryptedSecretKey = DBEncryptionUtil.encrypt(secretKey); pstmt = conn.prepareStatement("update `cloud`.`user` set secret_key=? where id=?"); + pstmt2Close.add(pstmt); if (encryptedSecretKey == null) { pstmt.setNull(1, Types.VARCHAR); } else { @@ -541,32 +521,26 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { } catch (UnsupportedEncodingException e) { throw new CloudRuntimeException("Unable encrypt user secret key ", e); } finally { - try { - if (rs != null) { - rs.close(); - } - - if (pstmt != null) { - pstmt.close(); - } - } catch (SQLException e) { - } + TransactionLegacy.closePstmts(pstmt2Close); } s_logger.debug("Done encrypting user keys"); } private void encryptVPNPassword(Connection conn) { s_logger.debug("Encrypting vpn_users password"); + List pstmt2Close = new ArrayList(); PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = conn.prepareStatement("select id, password from `cloud`.`vpn_users`"); + pstmt2Close.add(pstmt); rs = pstmt.executeQuery(); while (rs.next()) { long id = rs.getLong(1); String password = rs.getString(2); String encryptedpassword = DBEncryptionUtil.encrypt(password); pstmt = conn.prepareStatement("update `cloud`.`vpn_users` set password=? where id=?"); + pstmt2Close.add(pstmt); if (encryptedpassword == null) { pstmt.setNull(1, Types.VARCHAR); } else { @@ -580,16 +554,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { } catch (UnsupportedEncodingException e) { throw new CloudRuntimeException("Unable encrypt vpn_users password ", e); } finally { - try { - if (rs != null) { - rs.close(); - } - - if (pstmt != null) { - pstmt.close(); - } - } catch (SQLException e) { - } + TransactionLegacy.closePstmts(pstmt2Close); } s_logger.debug("Done encrypting vpn_users password"); } @@ -609,12 +574,14 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { } private void createNetworkOfferingServices(Connection conn, String externalOfferingName) { + List pstmt2Close = new ArrayList(); PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = conn.prepareStatement("select id, dns_service, gateway_service, firewall_service, lb_service, userdata_service," + " vpn_service, dhcp_service, unique_name from `cloud`.`network_offerings` where traffic_type='Guest'"); + pstmt2Close.add(pstmt); rs = pstmt.executeQuery(); while (rs.next()) { boolean sharedSourceNat = false; @@ -689,6 +656,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { pstmt = conn.prepareStatement("INSERT INTO `cloud`.`ntwk_offering_service_map` (`network_offering_id`," + " `service`, `provider`, `created`) values (?,?,?, now())"); + pstmt2Close.add(pstmt); pstmt.setLong(1, id); pstmt.setString(2, service); pstmt.setString(3, services.get(service)); @@ -697,6 +665,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { //update shared source nat and dedicated lb pstmt = conn.prepareStatement("UPDATE `cloud`.`network_offerings` set shared_source_nat_service=?, dedicated_lb_service=? where id=?"); + pstmt2Close.add(pstmt); pstmt.setBoolean(1, sharedSourceNat); pstmt.setBoolean(2, dedicatedLb); pstmt.setLong(3, id); @@ -706,29 +675,23 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { } catch (SQLException e) { throw new CloudRuntimeException("Unable to create service/provider map for network offerings", e); } finally { - try { - if (rs != null) { - rs.close(); - } - - if (pstmt != null) { - pstmt.close(); - } - } catch (SQLException e) { - } + TransactionLegacy.closePstmts(pstmt2Close); } } private void updateDomainNetworkRef(Connection conn) { + List pstmt2Close = new ArrayList(); PreparedStatement pstmt = null; ResultSet rs = null; try { // update subdomain access field for existing domain specific networks pstmt = conn.prepareStatement("select value from `cloud`.`configuration` where name='allow.subdomain.network.access'"); + pstmt2Close.add(pstmt); rs = pstmt.executeQuery(); while (rs.next()) { boolean subdomainAccess = Boolean.valueOf(rs.getString(1)); pstmt = conn.prepareStatement("UPDATE `cloud`.`domain_network_ref` SET subdomain_access=?"); + pstmt2Close.add(pstmt); pstmt.setBoolean(1, subdomainAccess); pstmt.executeUpdate(); s_logger.debug("Successfully updated subdomain_access field in network_domain table with value " + subdomainAccess); @@ -736,10 +699,12 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { // convert zone level 2.2.x networks to ROOT domain 3.0 access networks pstmt = conn.prepareStatement("select id from `cloud`.`networks` where shared=true and is_domain_specific=false and traffic_type='Guest'"); + pstmt2Close.add(pstmt); rs = pstmt.executeQuery(); while (rs.next()) { long networkId = rs.getLong(1); pstmt = conn.prepareStatement("INSERT INTO `cloud`.`domain_network_ref` (domain_id, network_id, subdomain_access) VALUES (1, ?, 1)"); + pstmt2Close.add(pstmt); pstmt.setLong(1, networkId); pstmt.executeUpdate(); s_logger.debug("Successfully converted zone specific network id=" + networkId + " to the ROOT domain level network with subdomain access set to true"); @@ -748,35 +713,29 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { } catch (SQLException e) { throw new CloudRuntimeException("Unable to update domain network ref", e); } finally { - try { - if (rs != null) { - rs.close(); - } - - if (pstmt != null) { - pstmt.close(); - } - } catch (SQLException e) { - } + TransactionLegacy.closePstmts(pstmt2Close); } } protected void createNetworkServices(Connection conn) { + List pstmt2Close = new ArrayList(); PreparedStatement pstmt = null; - ResultSet rs = null; - ResultSet rs1 = null; + ResultSet networkRs = null; + ResultSet offeringRs = null; try { pstmt = conn.prepareStatement("select id, network_offering_id from `cloud`.`networks` where traffic_type='Guest'"); - rs = pstmt.executeQuery(); - while (rs.next()) { - long networkId = rs.getLong(1); - long networkOfferingId = rs.getLong(2); + pstmt2Close.add(pstmt); + networkRs = pstmt.executeQuery(); + while (networkRs.next()) { + long networkId = networkRs.getLong(1); + long networkOfferingId = networkRs.getLong(2); pstmt = conn.prepareStatement("select service, provider from `cloud`.`ntwk_offering_service_map` where network_offering_id=?"); + pstmt2Close.add(pstmt); pstmt.setLong(1, networkOfferingId); - rs1 = pstmt.executeQuery(); - while (rs1.next()) { - String service = rs1.getString(1); - String provider = rs1.getString(2); + offeringRs = pstmt.executeQuery(); + while (offeringRs.next()) { + String service = offeringRs.getString(1); + String provider = offeringRs.getString(2); pstmt = conn.prepareStatement("INSERT INTO `cloud`.`ntwk_service_map` (`network_id`, `service`, `provider`, `created`) values (?,?,?, now())"); pstmt.setLong(1, networkId); pstmt.setString(2, service); @@ -788,20 +747,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { } catch (SQLException e) { throw new CloudRuntimeException("Unable to create service/provider map for networks", e); } finally { - try { - if (rs != null) { - rs.close(); - } - - if (rs1 != null) { - rs1.close(); - } - - if (pstmt != null) { - pstmt.close(); - } - } catch (SQLException e) { - } + TransactionLegacy.closePstmts(pstmt2Close); } } @@ -826,6 +772,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { } protected void updateReduntantRouters(Connection conn) { + List pstmt2Close = new ArrayList(); PreparedStatement pstmt = null; ResultSet rs = null; ResultSet rs1 = null; @@ -833,8 +780,10 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { // get all networks that need to be updated to the redundant network offerings pstmt = conn.prepareStatement("select ni.network_id, n.network_offering_id from `cloud`.`nics` ni, `cloud`.`networks` n where ni.instance_id in (select id from `cloud`.`domain_router` where is_redundant_router=1) and n.id=ni.network_id and n.traffic_type='Guest'"); + pstmt2Close.add(pstmt); rs = pstmt.executeQuery(); pstmt = conn.prepareStatement("select count(*) from `cloud`.`network_offerings`"); + pstmt2Close.add(pstmt); rs1 = pstmt.executeQuery(); long ntwkOffCount = 0; while (rs1.next()) { @@ -843,6 +792,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { s_logger.debug("Have " + ntwkOffCount + " networkOfferings"); pstmt = conn.prepareStatement("CREATE TEMPORARY TABLE `cloud`.`network_offerings2` ENGINE=MEMORY SELECT * FROM `cloud`.`network_offerings` WHERE id=1"); + pstmt2Close.add(pstmt); pstmt.executeUpdate(); HashMap newNetworkOfferingMap = new HashMap(); @@ -856,10 +806,12 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { if (!newNetworkOfferingMap.containsKey(networkOfferingId)) { // clone the record to pstmt = conn.prepareStatement("INSERT INTO `cloud`.`network_offerings2` SELECT * FROM `cloud`.`network_offerings` WHERE id=?"); + pstmt2Close.add(pstmt); pstmt.setLong(1, networkOfferingId); pstmt.executeUpdate(); pstmt = conn.prepareStatement("SELECT unique_name FROM `cloud`.`network_offerings` WHERE id=?"); + pstmt2Close.add(pstmt); pstmt.setLong(1, networkOfferingId); rs1 = pstmt.executeQuery(); String uniqueName = null; @@ -868,6 +820,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { } pstmt = conn.prepareStatement("UPDATE `cloud`.`network_offerings2` SET id=?, redundant_router_service=1, unique_name=?, name=? WHERE id=?"); + pstmt2Close.add(pstmt); ntwkOffCount = ntwkOffCount + 1; newNetworkOfferingId = ntwkOffCount; pstmt.setLong(1, newNetworkOfferingId); @@ -877,9 +830,11 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { pstmt.executeUpdate(); pstmt = conn.prepareStatement("INSERT INTO `cloud`.`network_offerings` SELECT * from `cloud`.`network_offerings2` WHERE id=" + newNetworkOfferingId); + pstmt2Close.add(pstmt); pstmt.executeUpdate(); pstmt = conn.prepareStatement("UPDATE `cloud`.`networks` SET network_offering_id=? where id=?"); + pstmt2Close.add(pstmt); pstmt.setLong(1, newNetworkOfferingId); pstmt.setLong(2, networkId); pstmt.executeUpdate(); @@ -887,6 +842,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { newNetworkOfferingMap.put(networkOfferingId, ntwkOffCount); } else { pstmt = conn.prepareStatement("UPDATE `cloud`.`networks` SET network_offering_id=? where id=?"); + pstmt2Close.add(pstmt); newNetworkOfferingId = newNetworkOfferingMap.get(networkOfferingId); pstmt.setLong(1, newNetworkOfferingId); pstmt.setLong(2, networkId); @@ -902,52 +858,46 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { try { pstmt = conn.prepareStatement("DROP TABLE `cloud`.`network_offerings2`"); pstmt.executeUpdate(); - if (rs != null) { - rs.close(); - } - - if (rs1 != null) { - rs1.close(); - } - - if (pstmt != null) { - pstmt.close(); - } + pstmt.close(); } catch (SQLException e) { } + TransactionLegacy.closePstmts(pstmt2Close); } } protected void updateHostCapacity(Connection conn) { + List pstmt2Close = new ArrayList(); PreparedStatement pstmt = null; try { s_logger.debug("Updating op_host_capacity table, column capacity_state"); pstmt = conn.prepareStatement("UPDATE op_host_capacity, host SET op_host_capacity.capacity_state='Disabled' where host.id=op_host_capacity.host_id and op_host_capacity.capacity_type in (0,1) and host.resource_state='Disabled';"); + pstmt2Close.add(pstmt); pstmt.executeUpdate(); + pstmt = conn.prepareStatement("UPDATE op_host_capacity, cluster SET op_host_capacity.capacity_state='Disabled' where cluster.id=op_host_capacity.cluster_id and cluster.allocation_state='Disabled';"); + pstmt2Close.add(pstmt); pstmt.executeUpdate(); + pstmt = conn.prepareStatement("UPDATE op_host_capacity, host_pod_ref SET op_host_capacity.capacity_state='Disabled' where host_pod_ref.id=op_host_capacity.pod_id and host_pod_ref.allocation_state='Disabled';"); + pstmt2Close.add(pstmt); pstmt.executeUpdate(); + pstmt = conn.prepareStatement("UPDATE op_host_capacity, data_center SET op_host_capacity.capacity_state='Disabled' where data_center.id=op_host_capacity.data_center_id and data_center.allocation_state='Disabled';"); + pstmt2Close.add(pstmt); pstmt.executeUpdate(); } catch (SQLException e) { throw new CloudRuntimeException("Unable to update op_host_capacity table. ", e); } finally { - try { - if (pstmt != null) { - pstmt.close(); - } - } catch (SQLException e) { - throw new CloudRuntimeException("Unable to close statement for op_host_capacity table. ", e); - } + TransactionLegacy.closePstmts(pstmt2Close); } } protected void switchAccountSpecificNetworksToIsolated(Connection conn) { + List pstmt2Close = new ArrayList(); PreparedStatement pstmt = null; ResultSet rs = null; ResultSet rs1 = null; @@ -955,16 +905,23 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { //check if switch_to_isolated is present; if not - skip this part of the code try { pstmt = conn.prepareStatement("select switch_to_isolated from `cloud`.`networks`"); + pstmt2Close.add(pstmt); rs = pstmt.executeQuery(); } catch (Exception ex) { s_logger.debug("switch_to_isolated field is not present in networks table"); + if (pstmt != null) { + pstmt.close(); + } return; } // get all networks that need to be updated to the isolated network offering pstmt = conn.prepareStatement("select id, network_offering_id from `cloud`.`networks` where switch_to_isolated=1"); + pstmt2Close.add(pstmt); rs = pstmt.executeQuery(); + pstmt = conn.prepareStatement("select count(*) from `cloud`.`network_offerings`"); + pstmt2Close.add(pstmt); rs1 = pstmt.executeQuery(); long ntwkOffCount = 0; while (rs1.next()) { @@ -973,6 +930,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { s_logger.debug("Have " + ntwkOffCount + " networkOfferings"); pstmt = conn.prepareStatement("CREATE TEMPORARY TABLE `cloud`.`network_offerings2` ENGINE=MEMORY SELECT * FROM `cloud`.`network_offerings` WHERE id=1"); + pstmt2Close.add(pstmt); pstmt.executeUpdate(); HashMap newNetworkOfferingMap = new HashMap(); @@ -986,10 +944,12 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { if (!newNetworkOfferingMap.containsKey(networkOfferingId)) { // clone the record to pstmt = conn.prepareStatement("INSERT INTO `cloud`.`network_offerings2` SELECT * FROM `cloud`.`network_offerings` WHERE id=?"); + pstmt2Close.add(pstmt); pstmt.setLong(1, networkOfferingId); pstmt.executeUpdate(); pstmt = conn.prepareStatement("UPDATE `cloud`.`network_offerings2` SET id=?, guest_type='Isolated', unique_name=?, name=? WHERE id=?"); + pstmt2Close.add(pstmt); ntwkOffCount = ntwkOffCount + 1; newNetworkOfferingId = ntwkOffCount; String uniqueName = "Isolated w/o source nat"; @@ -1000,9 +960,11 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { pstmt.executeUpdate(); pstmt = conn.prepareStatement("INSERT INTO `cloud`.`network_offerings` SELECT * from `cloud`.`network_offerings2` WHERE id=" + newNetworkOfferingId); + pstmt2Close.add(pstmt); pstmt.executeUpdate(); pstmt = conn.prepareStatement("UPDATE `cloud`.`networks` SET network_offering_id=? where id=?"); + pstmt2Close.add(pstmt); pstmt.setLong(1, newNetworkOfferingId); pstmt.setLong(2, networkId); pstmt.executeUpdate(); @@ -1010,6 +972,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { newNetworkOfferingMap.put(networkOfferingId, ntwkOffCount); } else { pstmt = conn.prepareStatement("UPDATE `cloud`.`networks` SET network_offering_id=? where id=?"); + pstmt2Close.add(pstmt); newNetworkOfferingId = newNetworkOfferingMap.get(networkOfferingId); pstmt.setLong(1, newNetworkOfferingId); pstmt.setLong(2, networkId); @@ -1021,6 +984,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { try { pstmt = conn.prepareStatement("ALTER TABLE `cloud`.`networks` DROP COLUMN `switch_to_isolated`"); + pstmt2Close.add(pstmt); pstmt.executeUpdate(); } catch (Exception ex) { // do nothing here @@ -1032,15 +996,10 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { try { pstmt = conn.prepareStatement("DROP TABLE `cloud`.`network_offerings2`"); pstmt.executeUpdate(); - if (rs != null) { - rs.close(); - } - - if (pstmt != null) { - pstmt.close(); - } + pstmt.close(); } catch (SQLException e) { } + TransactionLegacy.closePstmts(pstmt2Close); } } @@ -1097,6 +1056,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { } protected String fixNetworksWithExternalDevices(Connection conn) { + List pstmt2Close = new ArrayList(); PreparedStatement pstmt = null; ResultSet rs = null; ResultSet rs1 = null; @@ -1106,11 +1066,13 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { try { pstmt = conn.prepareStatement("select id from `cloud`.`data_center` where lb_provider='F5BigIp' or firewall_provider='JuniperSRX' or gateway_provider='JuniperSRX'"); + pstmt2Close.add(pstmt); rs = pstmt.executeQuery(); while (rs.next()) { zoneIds.add(rs.getLong(1)); } } catch (SQLException e) { + TransactionLegacy.closePstmts(pstmt2Close); throw new CloudRuntimeException("Unable to switch networks to the new network offering", e); } @@ -1121,6 +1083,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { try { // Find the correct network offering pstmt = conn.prepareStatement("select id, network_offering_id from `cloud`.`networks` where guest_type='Virtual' and data_center_id=?"); + pstmt2Close.add(pstmt); pstmt.setLong(1, zoneId); rs = pstmt.executeQuery(); pstmt = conn.prepareStatement("select count(*) from `cloud`.`network_offerings`"); @@ -1131,6 +1094,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { } pstmt = conn.prepareStatement("CREATE TEMPORARY TABLE `cloud`.`network_offerings2` ENGINE=MEMORY SELECT * FROM `cloud`.`network_offerings` WHERE id=1"); + pstmt2Close.add(pstmt); pstmt.executeUpdate(); while (rs.next()) { @@ -1142,11 +1106,13 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { uniqueName = "Isolated with external providers"; // clone the record to pstmt = conn.prepareStatement("INSERT INTO `cloud`.`network_offerings2` SELECT * FROM `cloud`.`network_offerings` WHERE id=?"); + pstmt2Close.add(pstmt); pstmt.setLong(1, networkOfferingId); pstmt.executeUpdate(); //set the new unique name pstmt = conn.prepareStatement("UPDATE `cloud`.`network_offerings2` SET id=?, unique_name=?, name=? WHERE id=?"); + pstmt2Close.add(pstmt); ntwkOffCount = ntwkOffCount + 1; newNetworkOfferingId = ntwkOffCount; pstmt.setLong(1, newNetworkOfferingId); @@ -1158,9 +1124,11 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { pstmt = conn.prepareStatement("INSERT INTO `cloud`.`network_offerings` SELECT * from " + "`cloud`.`network_offerings2` WHERE id=" + newNetworkOfferingId); + pstmt2Close.add(pstmt); pstmt.executeUpdate(); pstmt = conn.prepareStatement("UPDATE `cloud`.`networks` SET network_offering_id=? where id=?"); + pstmt2Close.add(pstmt); pstmt.setLong(1, newNetworkOfferingId); pstmt.setLong(2, networkId); pstmt.executeUpdate(); @@ -1168,6 +1136,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { newNetworkOfferingMap.put(networkOfferingId, ntwkOffCount); } else { pstmt = conn.prepareStatement("UPDATE `cloud`.`networks` SET network_offering_id=? where id=?"); + pstmt2Close.add(pstmt); newNetworkOfferingId = newNetworkOfferingMap.get(networkOfferingId); pstmt.setLong(1, newNetworkOfferingId); pstmt.setLong(2, networkId); @@ -1183,15 +1152,10 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { try { pstmt = conn.prepareStatement("DROP TABLE `cloud`.`network_offerings2`"); pstmt.executeUpdate(); - if (rs != null) { - rs.close(); - } - - if (pstmt != null) { - pstmt.close(); - } + pstmt.close(); } catch (SQLException e) { } + TransactionLegacy.closePstmts(pstmt2Close); } } diff --git a/engine/schema/src/com/cloud/upgrade/dao/Upgrade410to420.java b/engine/schema/src/com/cloud/upgrade/dao/Upgrade410to420.java index 80497d41259..82b6d8481a5 100755 --- a/engine/schema/src/com/cloud/upgrade/dao/Upgrade410to420.java +++ b/engine/schema/src/com/cloud/upgrade/dao/Upgrade410to420.java @@ -27,11 +27,9 @@ import java.sql.SQLException; import java.sql.Types; import java.util.ArrayList; import java.util.HashMap; -import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; -import java.util.Set; import java.util.UUID; import org.apache.log4j.Logger; @@ -83,7 +81,6 @@ public class Upgrade410to420 implements DbUpgrade { persistVswitchConfiguration(conn); createPlaceHolderNics(conn); updateRemoteAccessVpn(conn); - updateSystemVmTemplates(conn); updateOverCommitRatioClusterDetails(conn); updatePrimaryStore(conn); addEgressFwRulesForSRXGuestNw(conn); @@ -634,173 +631,6 @@ public class Upgrade410to420 implements DbUpgrade { } - private void updateSystemVmTemplates(Connection conn) { - // TODO: system vm template migration after storage refactoring - PreparedStatement pstmt = null; - ResultSet rs = null; - s_logger.debug("Updating System Vm template IDs"); - try { - //Get all hypervisors in use - Set hypervisorsListInUse = new HashSet(); - try { - pstmt = conn.prepareStatement("select distinct(hypervisor_type) from `cloud`.`cluster` where removed is null"); - rs = pstmt.executeQuery(); - while (rs.next()) { - switch (HypervisorType.getType(rs.getString(1))) { - case XenServer: - hypervisorsListInUse.add(HypervisorType.XenServer); - break; - case KVM: - hypervisorsListInUse.add(HypervisorType.KVM); - break; - case VMware: - hypervisorsListInUse.add(HypervisorType.VMware); - break; - case Hyperv: - hypervisorsListInUse.add(HypervisorType.Hyperv); - break; - case LXC: - hypervisorsListInUse.add(HypervisorType.LXC); - break; - } - } - } catch (SQLException e) { - throw new CloudRuntimeException("Error while listing hypervisors in use", e); - } - - Map NewTemplateNameList = new HashMap() { - { - put(HypervisorType.XenServer, "systemvm-xenserver-4.2"); - put(HypervisorType.VMware, "systemvm-vmware-4.2"); - put(HypervisorType.KVM, "systemvm-kvm-4.2"); - put(HypervisorType.LXC, "systemvm-lxc-4.2"); - put(HypervisorType.Hyperv, "systemvm-hyperv-4.2"); - } - }; - - Map routerTemplateConfigurationNames = new HashMap() { - { - put(HypervisorType.XenServer, "router.template.xen"); - put(HypervisorType.VMware, "router.template.vmware"); - put(HypervisorType.KVM, "router.template.kvm"); - put(HypervisorType.LXC, "router.template.lxc"); - put(HypervisorType.Hyperv, "router.template.hyperv"); - } - }; - - Map newTemplateUrl = new HashMap() { - { - put(HypervisorType.XenServer, "http://download.cloud.com/templates/4.2/systemvmtemplate-2013-07-12-master-xen.vhd.bz2"); - put(HypervisorType.VMware, "http://download.cloud.com/templates/4.2/systemvmtemplate-4.2-vh7.ova"); - put(HypervisorType.KVM, "http://download.cloud.com/templates/4.2/systemvmtemplate-2013-06-12-master-kvm.qcow2.bz2"); - put(HypervisorType.LXC, "http://download.cloud.com/templates/acton/acton-systemvm-02062012.qcow2.bz2"); - put(HypervisorType.Hyperv, "http://download.cloud.com/templates/4.2/systemvmtemplate-2013-06-12-master-xen.vhd.bz2"); - } - }; - - Map newTemplateChecksum = new HashMap() { - { - put(HypervisorType.XenServer, "fb1b6e032a160d86f2c28feb5add6d83"); - put(HypervisorType.VMware, "8fde62b1089e5844a9cd3b9b953f9596"); - put(HypervisorType.KVM, "6cea42b2633841648040becb588bd8f0"); - put(HypervisorType.LXC, "2755de1f9ef2ce4d6f2bee2efbb4da92"); - put(HypervisorType.Hyperv, "fb1b6e032a160d86f2c28feb5add6d83"); - } - }; - - for (Map.Entry hypervisorAndTemplateName : NewTemplateNameList.entrySet()) { - s_logger.debug("Updating " + hypervisorAndTemplateName.getKey() + " System Vms"); - try { - //Get 4.2.0 system Vm template Id for corresponding hypervisor - pstmt = conn.prepareStatement("select id from `cloud`.`vm_template` where name = ? and removed is null order by id desc limit 1"); - pstmt.setString(1, hypervisorAndTemplateName.getValue()); - rs = pstmt.executeQuery(); - if (rs.next()) { - long templateId = rs.getLong(1); - rs.close(); - pstmt.close(); - // Mark the old system templates as removed - pstmt = - conn.prepareStatement("UPDATE `cloud`.`vm_template` SET removed = now() WHERE hypervisor_type = ? AND type = 'SYSTEM' AND removed is null"); - pstmt.setString(1, hypervisorAndTemplateName.getKey().toString()); - pstmt.executeUpdate(); - pstmt.close(); - // change template type to SYSTEM - pstmt = conn.prepareStatement("update `cloud`.`vm_template` set type='SYSTEM' where id = ?"); - pstmt.setLong(1, templateId); - pstmt.executeUpdate(); - pstmt.close(); - // update templete ID of system Vms - pstmt = conn.prepareStatement("update `cloud`.`vm_instance` set vm_template_id = ? where type <> 'User' and hypervisor_type = ?"); - pstmt.setLong(1, templateId); - pstmt.setString(2, hypervisorAndTemplateName.getKey().toString()); - pstmt.executeUpdate(); - pstmt.close(); - // Change value of global configuration parameter router.template.* for the corresponding hypervisor - pstmt = conn.prepareStatement("UPDATE `cloud`.`configuration` SET value = ? WHERE name = ?"); - pstmt.setString(1, hypervisorAndTemplateName.getValue()); - pstmt.setString(2, routerTemplateConfigurationNames.get(hypervisorAndTemplateName.getKey())); - pstmt.executeUpdate(); - pstmt.close(); - } else { - if (hypervisorsListInUse.contains(hypervisorAndTemplateName.getKey())) { - // throw new CloudRuntimeException("4.2.0 " + hypervisorAndTemplateName.getKey() + " SystemVm template not found. Cannot upgrade system Vms"); - } else { - s_logger.warn("4.2.0 " + hypervisorAndTemplateName.getKey() + " SystemVm template not found. " + hypervisorAndTemplateName.getKey() + - " hypervisor is not used, so not failing upgrade"); - // Update the latest template URLs for corresponding hypervisor - pstmt = - conn.prepareStatement("UPDATE `cloud`.`vm_template` SET url = ? , checksum = ? WHERE hypervisor_type = ? AND type = 'SYSTEM' AND removed is null order by id desc limit 1"); - pstmt.setString(1, newTemplateUrl.get(hypervisorAndTemplateName.getKey())); - pstmt.setString(2, newTemplateChecksum.get(hypervisorAndTemplateName.getKey())); - pstmt.setString(3, hypervisorAndTemplateName.getKey().toString()); - pstmt.executeUpdate(); - pstmt.close(); - } - } - } catch (SQLException e) { - throw new CloudRuntimeException("Error while updating " + hypervisorAndTemplateName.getKey() + " systemVm template", e); - } - } - try { - pstmt = conn.prepareStatement("UPDATE `cloud`.`vm_template` set dynamically_scalable = 1 where name = ? and type = 'SYSTEM'"); - pstmt.setString(1, NewTemplateNameList.get(HypervisorType.VMware)); - pstmt.executeUpdate(); - pstmt.close(); - } catch (SQLException e) { - throw new CloudRuntimeException("Error while updating dynamically_scalable flag to 1 for SYSTEM template systemvm-vmware-4.2"); - } - s_logger.debug("Updating System Vm Template IDs Complete"); - } finally { - try { - if (rs != null) { - rs.close(); - } - - if (pstmt != null) { - pstmt.close(); - } - } catch (SQLException e) { - } - } - /* - pstmt = null; - try { - pstmt = conn.prepareStatement("update vm_template set image_data_store_id = 1 where type = 'SYSTEM' or type = 'BUILTIN'"); - pstmt.executeUpdate(); - } catch (SQLException e) { - throw new CloudRuntimeException("Failed to upgrade vm template data store uuid: " + e.toString()); - } finally { - if (pstmt != null) { - try { - pstmt.close(); - } catch (SQLException e) { - } - } - } - */ - } - //KVM snapshot flag: only turn on if Customers is using snapshot; private void setKVMSnapshotFlag(Connection conn) { s_logger.debug("Verify and set the KVM snapshot flag if snapshot was used. "); @@ -3161,28 +2991,28 @@ public class Upgrade410to420 implements DbUpgrade { } } - private static void upgradeResourceCountforAccount(Connection conn, Long account_id, Long domain_id, String type, Long resource_count) throws SQLException { + private static void upgradeResourceCountforAccount(Connection conn, Long accountId, Long domainId, String type, Long resourceCount) throws SQLException { //update or insert into resource_count table. PreparedStatement pstmt = null; pstmt = conn.prepareStatement("INSERT INTO `cloud`.`resource_count` (account_id, type, count) VALUES (?,?,?) ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id), count=?"); - pstmt.setLong(1, account_id); + pstmt.setLong(1, accountId); pstmt.setString(2, type); - pstmt.setLong(3, resource_count); - pstmt.setLong(4, resource_count); + pstmt.setLong(3, resourceCount); + pstmt.setLong(4, resourceCount); pstmt.executeUpdate(); pstmt.close(); } - private static void upgradeResourceCountforDomain(Connection conn, Long domain_id, String type, Long resource_count) throws SQLException { + private static void upgradeResourceCountforDomain(Connection conn, Long domainId, String type, Long resourceCount) throws SQLException { //update or insert into resource_count table. PreparedStatement pstmt = null; pstmt = conn.prepareStatement("INSERT INTO `cloud`.`resource_count` (domain_id, type, count) VALUES (?,?,?) ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id), count=?"); - pstmt.setLong(1, domain_id); + pstmt.setLong(1, domainId); pstmt.setString(2, type); - pstmt.setLong(3, resource_count); - pstmt.setLong(4, resource_count); + pstmt.setLong(3, resourceCount); + pstmt.setLong(4, resourceCount); pstmt.executeUpdate(); pstmt.close(); } diff --git a/engine/schema/src/com/cloud/upgrade/dao/Upgrade420to421.java b/engine/schema/src/com/cloud/upgrade/dao/Upgrade420to421.java index 51fb0de8f55..c3a6b0688a7 100644 --- a/engine/schema/src/com/cloud/upgrade/dao/Upgrade420to421.java +++ b/engine/schema/src/com/cloud/upgrade/dao/Upgrade420to421.java @@ -248,28 +248,28 @@ public class Upgrade420to421 implements DbUpgrade { } } - private static void upgradeResourceCountforAccount(Connection conn, Long account_id, Long domain_id, String type, Long resource_count) throws SQLException { + private static void upgradeResourceCountforAccount(Connection conn, Long accountId, Long domainId, String type, Long resourceCount) throws SQLException { //update or insert into resource_count table. PreparedStatement pstmt = null; pstmt = conn.prepareStatement("INSERT INTO `cloud`.`resource_count` (account_id, type, count) VALUES (?,?,?) ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id), count=?"); - pstmt.setLong(1, account_id); + pstmt.setLong(1, accountId); pstmt.setString(2, type); - pstmt.setLong(3, resource_count); - pstmt.setLong(4, resource_count); + pstmt.setLong(3, resourceCount); + pstmt.setLong(4, resourceCount); pstmt.executeUpdate(); pstmt.close(); } - private static void upgradeResourceCountforDomain(Connection conn, Long domain_id, String type, Long resource_count) throws SQLException { + private static void upgradeResourceCountforDomain(Connection conn, Long domainId, String type, Long resourceCount) throws SQLException { //update or insert into resource_count table. PreparedStatement pstmt = null; pstmt = conn.prepareStatement("INSERT INTO `cloud`.`resource_count` (domain_id, type, count) VALUES (?,?,?) ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id), count=?"); - pstmt.setLong(1, domain_id); + pstmt.setLong(1, domainId); pstmt.setString(2, type); - pstmt.setLong(3, resource_count); - pstmt.setLong(4, resource_count); + pstmt.setLong(3, resourceCount); + pstmt.setLong(4, resourceCount); pstmt.executeUpdate(); pstmt.close(); } diff --git a/engine/schema/src/com/cloud/upgrade/dao/Upgrade421to430.java b/engine/schema/src/com/cloud/upgrade/dao/Upgrade421to430.java index 0673c576bc2..7e26132d9e0 100644 --- a/engine/schema/src/com/cloud/upgrade/dao/Upgrade421to430.java +++ b/engine/schema/src/com/cloud/upgrade/dao/Upgrade421to430.java @@ -18,10 +18,22 @@ package com.cloud.upgrade.dao; import java.io.File; +import java.io.UnsupportedEncodingException; import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; +import com.cloud.hypervisor.Hypervisor; +import com.cloud.utils.crypt.DBEncryptionUtil; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.script.Script; @@ -55,6 +67,295 @@ public class Upgrade421to430 implements DbUpgrade { @Override public void performDataMigration(Connection conn) { + encryptLdapConfigParams(conn); + encryptImageStoreDetails(conn); + upgradeMemoryOfSsvmOffering(conn); + updateSystemVmTemplates(conn); + } + + private void upgradeMemoryOfSsvmOffering(Connection conn) { + PreparedStatement updatePstmt = null; + PreparedStatement selectPstmt = null; + ResultSet selectResultSet = null; + int newRamSize = 512; //512MB + long serviceOfferingId = 0; + + /** + * Pick first row in service_offering table which has system vm type as secondary storage vm. User added offerings would start from 2nd row onwards. + * We should not update/modify any user-defined offering. + */ + + try { + selectPstmt = conn.prepareStatement("SELECT id FROM `cloud`.`service_offering` WHERE vm_type='secondarystoragevm'"); + updatePstmt = conn.prepareStatement("UPDATE `cloud`.`service_offering` SET ram_size=? WHERE id=?"); + selectResultSet = selectPstmt.executeQuery(); + if(selectResultSet.next()) { + serviceOfferingId = selectResultSet.getLong("id"); + } + + updatePstmt.setInt(1, newRamSize); + updatePstmt.setLong(2, serviceOfferingId); + updatePstmt.executeUpdate(); + } catch (SQLException e) { + throw new CloudRuntimeException("Unable to upgrade ram_size of service offering for secondary storage vm. ", e); + } finally { + try { + if (selectPstmt != null) { + selectPstmt.close(); + } + if (selectResultSet != null) { + selectResultSet.close(); + } + if (updatePstmt != null) { + updatePstmt.close(); + } + } catch (SQLException e) { + } + } + s_logger.debug("Done upgrading RAM for service offering of Secondary Storage VM to " + newRamSize); + } + + private void encryptLdapConfigParams(Connection conn) { + PreparedStatement pstmt = null; + + String[][] ldapParams = { {"ldap.user.object", "inetOrgPerson", "Sets the object type of users within LDAP"}, + {"ldap.username.attribute", "uid", "Sets the username attribute used within LDAP"}, {"ldap.email.attribute", "mail", "Sets the email attribute used within LDAP"}, + {"ldap.firstname.attribute", "givenname", "Sets the firstname attribute used within LDAP"}, + {"ldap.lastname.attribute", "sn", "Sets the lastname attribute used within LDAP"}, + {"ldap.group.object", "groupOfUniqueNames", "Sets the object type of groups within LDAP"}, + {"ldap.group.user.uniquemember", "uniquemember", "Sets the attribute for uniquemembers within a group"}}; + + String insertSql = "INSERT INTO `cloud`.`configuration`(category, instance, component, name, value, description) VALUES ('Secure', 'DEFAULT', 'management-server', ?, ?, " + + "?) ON DUPLICATE KEY UPDATE category='Secure';"; + + try { + + for (String[] ldapParam : ldapParams) { + String name = ldapParam[0]; + String value = ldapParam[1]; + String desc = ldapParam[2]; + String encryptedValue = DBEncryptionUtil.encrypt(value); + pstmt = conn.prepareStatement(insertSql); + pstmt.setString(1, name); + pstmt.setBytes(2, encryptedValue.getBytes("UTF-8")); + pstmt.setString(3, desc); + pstmt.executeUpdate(); + } + + /** + * if encrypted, decrypt the ldap hostname and port and then update as they are not encrypted now. + */ + pstmt = conn.prepareStatement("SELECT conf.value FROM `cloud`.`configuration` conf WHERE conf.name='ldap.hostname'"); + ResultSet resultSet = pstmt.executeQuery(); + String hostname = null; + String port; + int portNumber = 0; + if (resultSet.next()) { + hostname = DBEncryptionUtil.decrypt(resultSet.getString(1)); + } + + pstmt = conn.prepareStatement("SELECT conf.value FROM `cloud`.`configuration` conf WHERE conf.name='ldap.port'"); + resultSet = pstmt.executeQuery(); + if (resultSet.next()) { + port = DBEncryptionUtil.decrypt(resultSet.getString(1)); + if (StringUtils.isNotBlank(port)) { + portNumber = Integer.valueOf(port); + } + } + + if (StringUtils.isNotBlank(hostname)) { + pstmt = conn.prepareStatement("INSERT INTO `cloud`.`ldap_configuration`(hostname, port) VALUES(?,?)"); + pstmt.setString(1, hostname); + if (portNumber != 0) { + pstmt.setInt(2, portNumber); + } else { + pstmt.setNull(2, Types.INTEGER); + } + pstmt.executeUpdate(); + } + + } catch (SQLException e) { + throw new CloudRuntimeException("Unable to insert ldap configuration values ", e); + } catch (UnsupportedEncodingException e) { + throw new CloudRuntimeException("Unable to insert ldap configuration values ", e); + } finally { + try { + if (pstmt != null) { + pstmt.close(); + } + } catch (SQLException e) { + } + } + s_logger.debug("Done encrypting ldap Config values"); + + } + + private void updateSystemVmTemplates(Connection conn) { + PreparedStatement pstmt = null; + ResultSet rs = null; + s_logger.debug("Updating System Vm template IDs"); + try{ + //Get all hypervisors in use + Set hypervisorsListInUse = new HashSet(); + try { + pstmt = conn.prepareStatement("select distinct(hypervisor_type) from `cloud`.`cluster` where removed is null"); + rs = pstmt.executeQuery(); + while(rs.next()){ + switch (Hypervisor.HypervisorType.getType(rs.getString(1))) { + case XenServer: hypervisorsListInUse.add(Hypervisor.HypervisorType.XenServer); + break; + case KVM: hypervisorsListInUse.add(Hypervisor.HypervisorType.KVM); + break; + case VMware: hypervisorsListInUse.add(Hypervisor.HypervisorType.VMware); + break; + case Hyperv: hypervisorsListInUse.add(Hypervisor.HypervisorType.Hyperv); + break; + case LXC: hypervisorsListInUse.add(Hypervisor.HypervisorType.LXC); + break; + } + } + } catch (SQLException e) { + throw new CloudRuntimeException("Error while listing hypervisors in use", e); + } + + Map NewTemplateNameList = new HashMap(){ + { put(Hypervisor.HypervisorType.XenServer, "systemvm-xenserver-4.3"); + put(Hypervisor.HypervisorType.VMware, "systemvm-vmware-4.3"); + put(Hypervisor.HypervisorType.KVM, "systemvm-kvm-4.3"); + put(Hypervisor.HypervisorType.LXC, "systemvm-lxc-4.3"); + put(Hypervisor.HypervisorType.Hyperv, "systemvm-hyperv-4.3"); + } + }; + + Map routerTemplateConfigurationNames = new HashMap(){ + { put(Hypervisor.HypervisorType.XenServer, "router.template.xen"); + put(Hypervisor.HypervisorType.VMware, "router.template.vmware"); + put(Hypervisor.HypervisorType.KVM, "router.template.kvm"); + put(Hypervisor.HypervisorType.LXC, "router.template.lxc"); + put(Hypervisor.HypervisorType.Hyperv, "router.template.hyperv"); + } + }; + + Map newTemplateUrl = new HashMap(){ + { put(Hypervisor.HypervisorType.XenServer, "http://download.cloud.com/templates/4.3/systemvm64template-2014-01-14-master-xen.vhd.bz2"); + put(Hypervisor.HypervisorType.VMware, "http://download.cloud.com/templates/4.3/systemvm64template-2014-01-14-master-vmware.ova"); + put(Hypervisor.HypervisorType.KVM, "http://download.cloud.com/templates/4.3/systemvm64template-2014-01-14-master-kvm.qcow2.bz2"); + put(Hypervisor.HypervisorType.LXC, "http://download.cloud.com/templates/4.3/systemvm64template-2014-01-14-master-kvm.qcow2.bz2"); + put(Hypervisor.HypervisorType.Hyperv, "http://download.cloud.com/templates/4.3/systemvm64template-2013-12-23-hyperv.vhd.bz2"); + } + }; + + Map newTemplateChecksum = new HashMap(){ + { put(Hypervisor.HypervisorType.XenServer, "74b92f031cc5c2089ee89efb81344dcf"); + put(Hypervisor.HypervisorType.VMware, "ef593a061f3b7594ab0bfd9b0ed0a0d4"); + put(Hypervisor.HypervisorType.KVM, "85a1bed07bf43cbf022451cb2ecae4ff"); + put(Hypervisor.HypervisorType.LXC, "85a1bed07bf43cbf022451cb2ecae4ff"); + put(Hypervisor.HypervisorType.Hyperv, "5df45ee6ebe1b703a8805f4e1f4d0818"); + } + }; + + for (Map.Entry hypervisorAndTemplateName : NewTemplateNameList.entrySet()){ + s_logger.debug("Updating " + hypervisorAndTemplateName.getKey() + " System Vms"); + try { + //Get 4.3.0 system Vm template Id for corresponding hypervisor + pstmt = conn.prepareStatement("select id from `cloud`.`vm_template` where name = ? and removed is null order by id desc limit 1"); + pstmt.setString(1, hypervisorAndTemplateName.getValue()); + rs = pstmt.executeQuery(); + if(rs.next()){ + long templateId = rs.getLong(1); + rs.close(); + pstmt.close(); +// // Mark the old system templates as removed +// pstmt = conn.prepareStatement("UPDATE `cloud`.`vm_template` SET removed = now() WHERE hypervisor_type = ? AND type = 'SYSTEM' AND removed is null"); +// pstmt.setString(1, hypervisorAndTemplateName.getKey().toString()); +// pstmt.executeUpdate(); +// pstmt.close(); + // change template type to SYSTEM + pstmt = conn.prepareStatement("update `cloud`.`vm_template` set type='SYSTEM' where id = ?"); + pstmt.setLong(1, templateId); + pstmt.executeUpdate(); + pstmt.close(); + // update templete ID of system Vms + pstmt = conn.prepareStatement("update `cloud`.`vm_instance` set vm_template_id = ? where type <> 'User' and hypervisor_type = ?"); + pstmt.setLong(1, templateId); + pstmt.setString(2, hypervisorAndTemplateName.getKey().toString()); + pstmt.executeUpdate(); + pstmt.close(); + // Change value of global configuration parameter router.template.* for the corresponding hypervisor + pstmt = conn.prepareStatement("UPDATE `cloud`.`configuration` SET value = ? WHERE name = ?"); + pstmt.setString(1, hypervisorAndTemplateName.getValue()); + pstmt.setString(2, routerTemplateConfigurationNames.get(hypervisorAndTemplateName.getKey())); + pstmt.executeUpdate(); + pstmt.close(); + } else { + if (hypervisorsListInUse.contains(hypervisorAndTemplateName.getKey())){ + throw new CloudRuntimeException("4.3.0 " + hypervisorAndTemplateName.getKey() + " SystemVm template not found. Cannot upgrade system Vms"); + } else { + s_logger.warn("4.3.0 " + hypervisorAndTemplateName.getKey() + " SystemVm template not found. " + hypervisorAndTemplateName.getKey() + " hypervisor is not used, so not failing upgrade"); + // Update the latest template URLs for corresponding hypervisor + pstmt = conn.prepareStatement("UPDATE `cloud`.`vm_template` SET url = ? , checksum = ? WHERE hypervisor_type = ? AND type = 'SYSTEM' AND removed is null order by id desc limit 1"); + pstmt.setString(1, newTemplateUrl.get(hypervisorAndTemplateName.getKey())); + pstmt.setString(2, newTemplateChecksum.get(hypervisorAndTemplateName.getKey())); + pstmt.setString(3, hypervisorAndTemplateName.getKey().toString()); + pstmt.executeUpdate(); + pstmt.close(); + } + } + } catch (SQLException e) { + throw new CloudRuntimeException("Error while updating "+ hypervisorAndTemplateName.getKey() +" systemVm template", e); + } + } + s_logger.debug("Updating System Vm Template IDs Complete"); + } finally { + try { + if (rs != null) { + rs.close(); + } + + if (pstmt != null) { + pstmt.close(); + } + } catch (SQLException e) { + } + } + } + + private void encryptImageStoreDetails(Connection conn) { + s_logger.debug("Encrypting image store details"); + PreparedStatement pstmt = null; + ResultSet rs = null; + try { + pstmt = conn.prepareStatement("select id, value from `cloud`.`image_store_details` where name = 'key' or name = 'secretkey'"); + rs = pstmt.executeQuery(); + while (rs.next()) { + long id = rs.getLong(1); + String value = rs.getString(2); + if (value == null) { + continue; + } + String encryptedValue = DBEncryptionUtil.encrypt(value); + pstmt = conn.prepareStatement("update `cloud`.`image_store_details` set value=? where id=?"); + pstmt.setBytes(1, encryptedValue.getBytes("UTF-8")); + pstmt.setLong(2, id); + pstmt.executeUpdate(); + } + } catch (SQLException e) { + throw new CloudRuntimeException("Unable encrypt image_store_details values ", e); + } catch (UnsupportedEncodingException e) { + throw new CloudRuntimeException("Unable encrypt image_store_details values ", e); + } finally { + try { + if (rs != null) { + rs.close(); + } + + if (pstmt != null) { + pstmt.close(); + } + } catch (SQLException e) { + } + } + s_logger.debug("Done encrypting image_store_details"); } @Override diff --git a/engine/schema/src/com/cloud/upgrade/dao/Upgrade430to440.java b/engine/schema/src/com/cloud/upgrade/dao/Upgrade430to440.java index 4fcb892822a..3b967e79dc5 100644 --- a/engine/schema/src/com/cloud/upgrade/dao/Upgrade430to440.java +++ b/engine/schema/src/com/cloud/upgrade/dao/Upgrade430to440.java @@ -19,7 +19,11 @@ package com.cloud.upgrade.dao; import java.io.File; import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import com.cloud.network.Network; import org.apache.log4j.Logger; import com.cloud.utils.exception.CloudRuntimeException; @@ -50,13 +54,153 @@ public class Upgrade430to440 implements DbUpgrade { throw new CloudRuntimeException("Unable to find db/schema-4310to440.sql"); } - return new File[] { new File(script) }; + return new File[] {new File(script)}; } @Override public void performDataMigration(Connection conn) { + secondaryIpsAccountAndDomainIdsUpdate(conn); } + + + private void secondaryIpsAccountAndDomainIdsUpdate(Connection conn) { + PreparedStatement pstmt = null; + PreparedStatement pstmtVm = null; + PreparedStatement pstmtNw = null; + PreparedStatement pstmtUpdate = null; + + ResultSet rs1 = null; + ResultSet vmRs = null; + ResultSet networkRs = null; + + String secondIpsSql = "SELECT id, vmId, network_id, account_id, domain_id, ip4_address FROM `cloud`.`nic_secondary_ips`"; + + try { + pstmt = conn.prepareStatement(secondIpsSql); + rs1 = pstmt.executeQuery(); + + while(rs1.next()) { + long ipId = rs1.getLong(1); + long vmId = rs1.getLong(2); + long networkId = rs1.getLong(3); + long accountId = rs1.getLong(4); + long domainId = rs1.getLong(5); + String ipAddr = rs1.getString(6); + + pstmtVm = conn.prepareStatement("SELECT account_id, domain_id FROM `cloud`.`vm_instance` where id = ?"); + pstmtVm.setLong(1,vmId); + + vmRs = pstmtVm.executeQuery(); + + if (vmRs.next()) { + long vmAccountId = vmRs.getLong(1); + long vmDomainId = vmRs.getLong(2); + + if (vmAccountId != accountId && vmAccountId != domainId) { + // update the secondary ip accountid and domainid to vm accountid domainid + // check the network type. If network is shared accountid doaminid needs to be updated in + // in both nic_secondary_ips table and user_ip_address table + + pstmtUpdate = conn.prepareStatement("UPDATE `cloud`.`nic_secondary_ips` SET account_id = ?, domain_id= ? WHERE id = ?"); + pstmtUpdate.setLong(1, vmAccountId); + pstmtUpdate.setLong(2,vmDomainId); + pstmtUpdate.setLong(3,ipId); + pstmtUpdate.executeUpdate(); + pstmtUpdate.close(); + + pstmtNw = conn.prepareStatement("SELECT guest_type FROM `cloud`.`networks` where id = ?"); + pstmtNw.setLong(1,networkId); + + networkRs = pstmtNw.executeQuery(); + if (networkRs.next()) { + String guesttype = networkRs.getString(1); + + if (guesttype == Network.GuestType.Shared.toString()) { + pstmtUpdate = conn.prepareStatement("UPDATE `cloud`.`user_ip_address` SET account_id = ?, domain_id= ? WHERE public_ip_address = ?"); + pstmtUpdate.setLong(1,vmAccountId); + pstmtUpdate.setLong(2,vmDomainId); + pstmtUpdate.setString(3,ipAddr); + pstmtUpdate.executeUpdate(); + pstmtUpdate.close(); + + } + } + networkRs.close(); + networkRs = null; + pstmtNw.close(); + pstmtNw = null; + } + } //if + + pstmtVm.close(); + pstmtVm = null; + vmRs.close(); + vmRs = null; + } // while + + + } catch (SQLException e) { + throw new CloudRuntimeException("Exception while Moving private zone information to dedicated resources", e); + } finally { + + if (pstmt != null) { + try { + pstmt.close(); + + } catch (SQLException e) { + } + } + + + if (rs1 != null) { + try { + rs1.close(); + } catch (SQLException e) { + } + } + + + + if (pstmtVm != null) { + try { + pstmtVm.close(); + } catch (SQLException e) { + } + } + + if (vmRs != null) { + try { + vmRs.close(); + } catch (SQLException e) { + } + } + + + + if (pstmtNw != null) { + try { + pstmtNw.close(); + + } catch (SQLException e) { + } + } + + + if (networkRs != null) { + try { + networkRs.close(); + } catch (SQLException e) { + } + } + } + s_logger.debug("Done updating vm nic secondary ip account and domain ids"); + } + + + + + @Override public File[] getCleanupScripts() { String script = Script.findScript("", "db/schema-430to440-cleanup.sql"); @@ -64,6 +208,6 @@ public class Upgrade430to440 implements DbUpgrade { throw new CloudRuntimeException("Unable to find db/schema-430to440-cleanup.sql"); } - return new File[] { new File(script) }; + return new File[] {new File(script)}; } } diff --git a/engine/schema/src/com/cloud/usage/UsageVMInstanceVO.java b/engine/schema/src/com/cloud/usage/UsageVMInstanceVO.java index 8d9491f54a1..06d4876c1b3 100644 --- a/engine/schema/src/com/cloud/usage/UsageVMInstanceVO.java +++ b/engine/schema/src/com/cloud/usage/UsageVMInstanceVO.java @@ -46,14 +46,14 @@ public class UsageVMInstanceVO { @Column(name = "service_offering_id") private long serviceOfferingId; - @Column(name="cpu_cores") - private Long cpuCores; + @Column(name = "cpu_cores") + private Long cpuCores; - @Column(name="memory") - private Long memory; + @Column(name = "memory") + private Long memory; - @Column(name="cpu_speed") - private Long cpuSpeed; + @Column(name = "cpu_speed") + private Long cpuSpeed; @Column(name = "template_id") private long templateId; diff --git a/engine/schema/src/com/cloud/usage/dao/UsageDaoImpl.java b/engine/schema/src/com/cloud/usage/dao/UsageDaoImpl.java index 9582033bd69..32f63e6fb26 100644 --- a/engine/schema/src/com/cloud/usage/dao/UsageDaoImpl.java +++ b/engine/schema/src/com/cloud/usage/dao/UsageDaoImpl.java @@ -18,7 +18,6 @@ package com.cloud.usage.dao; import java.sql.PreparedStatement; import java.sql.ResultSet; -import java.sql.Timestamp; import java.sql.Types; import java.util.ArrayList; import java.util.Date; @@ -434,8 +433,8 @@ public class UsageDaoImpl extends GenericDaoBase implements Usage } else { pstmt.setNull(15, Types.BIGINT); } - pstmt.setTimestamp(16, new Timestamp(usageRecord.getStartDate().getTime())); - pstmt.setTimestamp(17, new Timestamp(usageRecord.getEndDate().getTime())); + pstmt.setString(16, DateUtil.getDateDisplayString(s_gmtTimeZone, usageRecord.getStartDate())); + pstmt.setString(17, DateUtil.getDateDisplayString(s_gmtTimeZone, usageRecord.getEndDate())); if (usageRecord.getVirtualSize() != null) { pstmt.setLong(18, usageRecord.getSize()); } else { diff --git a/engine/schema/src/com/cloud/usage/dao/UsageStorageDao.java b/engine/schema/src/com/cloud/usage/dao/UsageStorageDao.java index 6d1cde3f50f..f5408d785ff 100644 --- a/engine/schema/src/com/cloud/usage/dao/UsageStorageDao.java +++ b/engine/schema/src/com/cloud/usage/dao/UsageStorageDao.java @@ -23,7 +23,7 @@ import com.cloud.usage.UsageStorageVO; import com.cloud.utils.db.GenericDao; public interface UsageStorageDao extends GenericDao { - public void removeBy(long userId, long id, int storage_type); + public void removeBy(long userId, long id, int storageType); public void update(UsageStorageVO usage); diff --git a/engine/schema/src/com/cloud/usage/dao/UsageStorageDaoImpl.java b/engine/schema/src/com/cloud/usage/dao/UsageStorageDaoImpl.java index 175bb88ea18..77fc56f9cd1 100644 --- a/engine/schema/src/com/cloud/usage/dao/UsageStorageDaoImpl.java +++ b/engine/schema/src/com/cloud/usage/dao/UsageStorageDaoImpl.java @@ -89,7 +89,7 @@ public class UsageStorageDaoImpl extends GenericDaoBase im } @Override - public void removeBy(long accountId, long volId, int storage_type) { + public void removeBy(long accountId, long volId, int storageType) { TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB); PreparedStatement pstmt = null; try { @@ -98,7 +98,7 @@ public class UsageStorageDaoImpl extends GenericDaoBase im pstmt = txn.prepareAutoCloseStatement(sql); pstmt.setLong(1, accountId); pstmt.setLong(2, volId); - pstmt.setInt(3, storage_type); + pstmt.setInt(3, storageType); pstmt.executeUpdate(); txn.commit(); } catch (Exception e) { diff --git a/engine/schema/src/com/cloud/user/dao/AccountDaoImpl.java b/engine/schema/src/com/cloud/user/dao/AccountDaoImpl.java index 792b3265975..4bc23ed3edd 100755 --- a/engine/schema/src/com/cloud/user/dao/AccountDaoImpl.java +++ b/engine/schema/src/com/cloud/user/dao/AccountDaoImpl.java @@ -45,7 +45,7 @@ import com.cloud.utils.db.TransactionLegacy; @Local(value = {AccountDao.class}) public class AccountDaoImpl extends GenericDaoBase implements AccountDao { private static final Logger s_logger = Logger.getLogger(AccountDaoImpl.class); - private final String FIND_USER_ACCOUNT_BY_API_KEY = "SELECT u.id, u.username, u.account_id, u.secret_key, u.state, " + private static final String FIND_USER_ACCOUNT_BY_API_KEY = "SELECT u.id, u.username, u.account_id, u.secret_key, u.state, " + "a.id, a.account_name, a.type, a.domain_id, a.state " + "FROM `cloud`.`user` u, `cloud`.`account` a " + "WHERE u.account_id = a.id AND u.api_key = ? and u.removed IS NULL"; diff --git a/engine/schema/src/com/cloud/vm/dao/DomainRouterDao.java b/engine/schema/src/com/cloud/vm/dao/DomainRouterDao.java index 02cf68d7b75..e3f75fabd7e 100755 --- a/engine/schema/src/com/cloud/vm/dao/DomainRouterDao.java +++ b/engine/schema/src/com/cloud/vm/dao/DomainRouterDao.java @@ -69,7 +69,7 @@ public interface DomainRouterDao extends GenericDao { * @param podId id of the pod. null if to get all. * @return list of DomainRouterVO */ - public List listByPodId(Long podId); + public List listRunningByPodId(Long podId); /** * list virtual machine routers by pod id. pass in null to get all @@ -94,7 +94,7 @@ public interface DomainRouterDao extends GenericDao { * @param id * @return */ - public List listByDomain(Long id); + public List listRunningByDomain(Long id); List findBy(long accountId, long dcId, Role role); @@ -147,5 +147,9 @@ public interface DomainRouterDao extends GenericDao { */ void removeRouterFromGuestNetwork(long routerId, long guestNetworkId); - List listByClusterId(Long clusterId); + List listRunningByClusterId(Long clusterId); + + List listRunningByAccountId(long accountId); + + List listRunningByDataCenter(long dcId); } diff --git a/engine/schema/src/com/cloud/vm/dao/DomainRouterDaoImpl.java b/engine/schema/src/com/cloud/vm/dao/DomainRouterDaoImpl.java index 6bee6441e49..6b62f568739 100755 --- a/engine/schema/src/com/cloud/vm/dao/DomainRouterDaoImpl.java +++ b/engine/schema/src/com/cloud/vm/dao/DomainRouterDaoImpl.java @@ -54,6 +54,7 @@ import com.cloud.vm.VirtualMachine.State; public class DomainRouterDaoImpl extends GenericDaoBase implements DomainRouterDao { protected SearchBuilder AllFieldsSearch; + protected SearchBuilder RunningSearch; protected SearchBuilder IdNetworkIdStatesSearch; protected SearchBuilder HostUpSearch; protected SearchBuilder StateNetworkTypeSearch; @@ -139,10 +140,19 @@ public class DomainRouterDaoImpl extends GenericDaoBase im OutsidePodSearch.done(); clusterSearch = createSearchBuilder(); + clusterSearch.and("state", clusterSearch.entity().getState(), Op.EQ); SearchBuilder clusterHost = _hostsDao.createSearchBuilder(); clusterHost.and("clusterId", clusterHost.entity().getClusterId(), Op.EQ); clusterSearch.join("host", clusterHost, clusterSearch.entity().getHostId(), clusterHost.entity().getId(), JoinType.INNER); clusterSearch.done(); + + RunningSearch = createSearchBuilder(); + RunningSearch.and("dc", RunningSearch.entity().getDataCenterId(), Op.EQ); + RunningSearch.and("account", RunningSearch.entity().getAccountId(), Op.EQ); + RunningSearch.and("domainId", RunningSearch.entity().getDomainId(), Op.EQ); + RunningSearch.and("state", RunningSearch.entity().getState(), Op.EQ); + RunningSearch.and("podId", RunningSearch.entity().getPodIdToDeployIn(), Op.EQ); + RunningSearch.done(); } @Override @@ -200,15 +210,17 @@ public class DomainRouterDaoImpl extends GenericDaoBase im } @Override - public List listByPodId(Long podId) { - SearchCriteria sc = AllFieldsSearch.create(); + public List listRunningByPodId(Long podId) { + SearchCriteria sc = RunningSearch.create(); + sc.setParameters("state", State.Running); sc.setParameters("podId", podId); return listBy(sc); } @Override - public List listByClusterId(Long clusterId) { + public List listRunningByClusterId(Long clusterId) { SearchCriteria sc = clusterSearch.create(); + sc.setParameters("state", State.Running); sc.setJoinParameters("host", "clusterId", clusterId); return listBy(sc); } @@ -237,8 +249,9 @@ public class DomainRouterDaoImpl extends GenericDaoBase im } @Override - public List listByDomain(Long domainId) { - SearchCriteria sc = AllFieldsSearch.create(); + public List listRunningByDomain(Long domainId) { + SearchCriteria sc = RunningSearch.create(); + sc.setParameters("state", State.Running); sc.setParameters("domainId", domainId); return listBy(sc); } @@ -379,4 +392,19 @@ public class DomainRouterDaoImpl extends GenericDaoBase im return listBy(sc); } + @Override + public List listRunningByAccountId(long accountId) { + SearchCriteria sc = RunningSearch.create(); + sc.setParameters("state", State.Running); + sc.setParameters("account", accountId); + return listBy(sc); + } + + @Override + public List listRunningByDataCenter(long dcId) { + SearchCriteria sc = RunningSearch.create(); + sc.setParameters("state", State.Running); + sc.setParameters("dc", dcId); + return listBy(sc); + } } diff --git a/engine/schema/src/com/cloud/vm/dao/NicDao.java b/engine/schema/src/com/cloud/vm/dao/NicDao.java index fc934750bf3..a7ad01692cf 100644 --- a/engine/schema/src/com/cloud/vm/dao/NicDao.java +++ b/engine/schema/src/com/cloud/vm/dao/NicDao.java @@ -61,7 +61,7 @@ public interface NicDao extends GenericDao { NicVO findByIp4AddressAndNetworkIdAndInstanceId(long networkId, long instanceId, String ip4Address); - List listByVmIdAndNicId(Long vmId, Long nicId); + List listByVmIdAndNicIdAndNtwkId(long vmId, Long nicId, Long networkId); NicVO findByIp4AddressAndVmId(String ip4Address, long instance); diff --git a/engine/schema/src/com/cloud/vm/dao/NicDaoImpl.java b/engine/schema/src/com/cloud/vm/dao/NicDaoImpl.java index 2ac6a8090ef..c345bb290cf 100644 --- a/engine/schema/src/com/cloud/vm/dao/NicDaoImpl.java +++ b/engine/schema/src/com/cloud/vm/dao/NicDaoImpl.java @@ -244,10 +244,17 @@ public class NicDaoImpl extends GenericDaoBase implements NicDao { } @Override - public List listByVmIdAndNicId(Long vmId, Long nicId) { + public List listByVmIdAndNicIdAndNtwkId(long vmId, Long nicId, Long networkId) { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("instance", vmId); - sc.setParameters("nicid", nicId); + + if (nicId != null) { + sc.setParameters("nicid", nicId); + } + + if (networkId != null) { + sc.setParameters("network", networkId); + } return listBy(sc); } diff --git a/engine/schema/src/com/cloud/vm/dao/NicIpAliasDao.java b/engine/schema/src/com/cloud/vm/dao/NicIpAliasDao.java index ff3a24b3db0..b1cd02b5e76 100644 --- a/engine/schema/src/com/cloud/vm/dao/NicIpAliasDao.java +++ b/engine/schema/src/com/cloud/vm/dao/NicIpAliasDao.java @@ -50,7 +50,7 @@ public interface NicIpAliasDao extends GenericDao { List getAliasIpAddressesForNic(long nicId); - Integer countAliasIps(long NicId); + Integer countAliasIps(long nicId); public NicIpAliasVO findByIp4AddressAndVmId(String ip4Address, long vmId); diff --git a/engine/schema/src/com/cloud/vm/dao/NicSecondaryIpDao.java b/engine/schema/src/com/cloud/vm/dao/NicSecondaryIpDao.java index 9fbfa279089..39b8470b8c2 100644 --- a/engine/schema/src/com/cloud/vm/dao/NicSecondaryIpDao.java +++ b/engine/schema/src/com/cloud/vm/dao/NicSecondaryIpDao.java @@ -51,4 +51,6 @@ public interface NicSecondaryIpDao extends GenericDao { NicSecondaryIpVO findByIp4AddressAndNetworkIdAndInstanceId(long networkId, Long vmId, String vmIp); List getSecondaryIpAddressesForNic(long nicId); + + Long countByNicId(long nicId); } diff --git a/engine/schema/src/com/cloud/vm/dao/NicSecondaryIpDaoImpl.java b/engine/schema/src/com/cloud/vm/dao/NicSecondaryIpDaoImpl.java index 2f3cc290b40..29af0198b47 100644 --- a/engine/schema/src/com/cloud/vm/dao/NicSecondaryIpDaoImpl.java +++ b/engine/schema/src/com/cloud/vm/dao/NicSecondaryIpDaoImpl.java @@ -35,6 +35,7 @@ import com.cloud.utils.db.SearchCriteria.Op; public class NicSecondaryIpDaoImpl extends GenericDaoBase implements NicSecondaryIpDao { private final SearchBuilder AllFieldsSearch; private final GenericSearchBuilder IpSearch; + protected GenericSearchBuilder CountByNicId; protected NicSecondaryIpDaoImpl() { super(); @@ -50,6 +51,11 @@ public class NicSecondaryIpDaoImpl extends GenericDaoBase sc = CountByNicId.create(); + sc.setParameters("nic", nicId); + return customSearch(sc, null).get(0); + } } diff --git a/engine/schema/src/com/cloud/vm/dao/NicSecondaryIpVO.java b/engine/schema/src/com/cloud/vm/dao/NicSecondaryIpVO.java index 78b779f6a02..142de8a6935 100644 --- a/engine/schema/src/com/cloud/vm/dao/NicSecondaryIpVO.java +++ b/engine/schema/src/com/cloud/vm/dao/NicSecondaryIpVO.java @@ -33,7 +33,7 @@ import com.cloud.vm.NicSecondaryIp; @Table(name = "nic_secondary_ips") public class NicSecondaryIpVO implements NicSecondaryIp { - public NicSecondaryIpVO(Long nicId, String ipaddr, Long vmId, Long accountId, Long domainId, Long networkId) { + public NicSecondaryIpVO(long nicId, String ipaddr, long vmId, long accountId, long domainId, long networkId) { this.nicId = nicId; this.vmId = vmId; this.ip4Address = ipaddr; @@ -57,7 +57,7 @@ public class NicSecondaryIpVO implements NicSecondaryIp { long domainId; @Column(name = "account_id", updatable = false) - private Long accountId; + private long accountId; @Column(name = "ip4_address") String ip4Address; @@ -75,93 +75,53 @@ public class NicSecondaryIpVO implements NicSecondaryIp { String uuid = UUID.randomUUID().toString(); @Column(name = "vmId") - Long vmId; + long vmId; @Override public long getId() { return id; } - public void setId(long id) { - this.id = id; - } - @Override public long getNicId() { return nicId; } - public void setNicId(long nicId) { - this.nicId = nicId; - } - @Override public long getDomainId() { return domainId; } - public void setDomainId(Long domainId) { - this.domainId = domainId; - } - @Override public long getAccountId() { return accountId; } - public void setAccountId(Long accountId) { - this.accountId = accountId; - } - @Override public String getIp4Address() { return ip4Address; } - public void setIp4Address(String ip4Address) { - this.ip4Address = ip4Address; - } - public String getIp6Address() { return ip6Address; } - public void setIp6Address(String ip6Address) { - this.ip6Address = ip6Address; - } - @Override public long getNetworkId() { return networkId; } - public void setNetworkId(long networkId) { - this.networkId = networkId; - } - public Date getCreated() { return created; } - public void setCreated(Date created) { - this.created = created; - } - @Override public String getUuid() { return uuid; } - public void setUuid(String uuid) { - this.uuid = uuid; - } - @Override public long getVmId() { return vmId; } - - public void setVmId(Long vmId) { - this.vmId = vmId; - } } diff --git a/engine/schema/src/com/cloud/vm/dao/UserVmDaoImpl.java b/engine/schema/src/com/cloud/vm/dao/UserVmDaoImpl.java index b675fb61bc0..812e628e1b2 100755 --- a/engine/schema/src/com/cloud/vm/dao/UserVmDaoImpl.java +++ b/engine/schema/src/com/cloud/vm/dao/UserVmDaoImpl.java @@ -82,7 +82,7 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use "SELECT pod_id FROM cloud.vm_instance WHERE data_center_id = ? AND account_id = ? AND pod_id IS NOT NULL AND (state = 'Running' OR state = 'Stopped') " + "GROUP BY pod_id HAVING count(id) > 0 ORDER BY count(id) DESC"; - private static String VM_DETAILS = "select vm_instance.id, " + private static final String VM_DETAILS = "select vm_instance.id, " + "account.id, account.account_name, account.type, domain.name, instance_group.id, instance_group.name," + "data_center.id, data_center.name, data_center.is_security_group_enabled, host.id, host.name, " + "vm_template.id, vm_template.name, vm_template.display_text, iso.id, iso.name, " @@ -175,6 +175,7 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use CountByAccount.and("account", CountByAccount.entity().getAccountId(), SearchCriteria.Op.EQ); CountByAccount.and("type", CountByAccount.entity().getType(), SearchCriteria.Op.EQ); CountByAccount.and("state", CountByAccount.entity().getState(), SearchCriteria.Op.NIN); + CountByAccount.and("displayVm", CountByAccount.entity().isDisplayVm(), SearchCriteria.Op.EQ); CountByAccount.done(); SearchBuilder nicSearch = _nicDao.createSearchBuilder(); @@ -223,7 +224,7 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use vo.setUserData(userData); vo.setDisplayVm(displayVm); vo.setDynamicallyScalable(isDynamicallyScalable); - if (customId != null){ + if (customId != null) { vo.setUuid(customId); } @@ -560,6 +561,7 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use sc.setParameters("account", accountId); sc.setParameters("type", VirtualMachine.Type.User); sc.setParameters("state", new Object[] {State.Destroyed, State.Error, State.Expunging}); + sc.setParameters("displayVm", 1); return customSearch(sc, null).get(0); } diff --git a/engine/schema/src/com/cloud/vm/dao/VMInstanceDao.java b/engine/schema/src/com/cloud/vm/dao/VMInstanceDao.java index e6ea4a57e1c..453d222cdf2 100644 --- a/engine/schema/src/com/cloud/vm/dao/VMInstanceDao.java +++ b/engine/schema/src/com/cloud/vm/dao/VMInstanceDao.java @@ -69,6 +69,8 @@ public interface VMInstanceDao extends GenericDao, StateDao< List findVMInTransition(Date time, State... states); + List listByHostAndState(long hostId, State... states); + List listByTypes(VirtualMachine.Type... types); VMInstanceVO findByIdTypes(long id, VirtualMachine.Type... types); diff --git a/engine/schema/src/com/cloud/vm/dao/VMInstanceDaoImpl.java b/engine/schema/src/com/cloud/vm/dao/VMInstanceDaoImpl.java index f45042c8675..2f25f577f47 100644 --- a/engine/schema/src/com/cloud/vm/dao/VMInstanceDaoImpl.java +++ b/engine/schema/src/com/cloud/vm/dao/VMInstanceDaoImpl.java @@ -48,7 +48,11 @@ import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.db.SearchCriteria.Op; +import com.cloud.utils.db.Transaction; +import com.cloud.utils.db.TransactionCallback; +import com.cloud.utils.db.TransactionCallbackNoReturn; import com.cloud.utils.db.TransactionLegacy; +import com.cloud.utils.db.TransactionStatus; import com.cloud.utils.db.UpdateBuilder; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.NicVO; @@ -76,6 +80,7 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem protected SearchBuilder TypesSearch; protected SearchBuilder IdTypesSearch; protected SearchBuilder HostIdTypesSearch; + protected SearchBuilder HostIdStatesSearch; protected SearchBuilder HostIdUpTypesSearch; protected SearchBuilder HostUpSearch; protected SearchBuilder InstanceNameSearch; @@ -102,7 +107,7 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem private static final String ORDER_PODS_NUMBER_OF_VMS_FOR_ACCOUNT = "SELECT pod.id, SUM(IF(vm.state='Running' AND vm.account_id = ?, 1, 0)) FROM `cloud`.`" + "host_pod_ref` pod LEFT JOIN `cloud`.`vm_instance` vm ON pod.id = vm.pod_id WHERE pod.data_center_id = ? AND pod.removed is null " - + " GROUP BY pod.id ORDER BY 2 ASC "; + + " GROUP BY pod.id ORDER BY 2 ASC "; private static final String ORDER_HOSTS_NUMBER_OF_VMS_FOR_ACCOUNT = "SELECT host.id, SUM(IF(vm.state='Running' AND vm.account_id = ?, 1, 0)) FROM `cloud`.`host` host LEFT JOIN `cloud`.`vm_instance` vm ON host.id = vm.host_id " + @@ -182,6 +187,11 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem HostIdTypesSearch.and("types", HostIdTypesSearch.entity().getType(), Op.IN); HostIdTypesSearch.done(); + HostIdStatesSearch = createSearchBuilder(); + HostIdStatesSearch.and("hostId", HostIdStatesSearch.entity().getHostId(), Op.EQ); + HostIdStatesSearch.and("states", HostIdStatesSearch.entity().getState(), Op.IN); + HostIdStatesSearch.done(); + HostIdUpTypesSearch = createSearchBuilder(); HostIdUpTypesSearch.and("hostid", HostIdUpTypesSearch.entity().getHostId(), Op.EQ); HostIdUpTypesSearch.and("types", HostIdUpTypesSearch.entity().getType(), Op.IN); @@ -334,6 +344,15 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem return listBy(sc); } + @Override + public List listByHostAndState(long hostId, State... states) { + SearchCriteria sc = HostIdStatesSearch.create(); + sc.setParameters("hostId", hostId); + sc.setParameters("states", (Object[])states); + + return listBy(sc); + } + @Override public List listUpByHostIdTypes(long hostid, Type... types) { SearchCriteria sc = HostIdUpTypesSearch.create(); @@ -702,60 +721,66 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem } @Override - public boolean updatePowerState(long instanceId, long powerHostId, VirtualMachine.PowerState powerState) { - boolean needToUpdate = false; - TransactionLegacy txn = TransactionLegacy.currentTxn(); - txn.start(); + public boolean updatePowerState(final long instanceId, final long powerHostId, final VirtualMachine.PowerState powerState) { + return Transaction.execute(new TransactionCallback() { + @Override + public Boolean doInTransaction(TransactionStatus status) { + boolean needToUpdate = false; + VMInstanceVO instance = findById(instanceId); + if (instance != null) { + Long savedPowerHostId = instance.getPowerHostId(); + if (instance.getPowerState() != powerState || savedPowerHostId == null + || savedPowerHostId.longValue() != powerHostId) { + instance.setPowerState(powerState); + instance.setPowerHostId(powerHostId); + instance.setPowerStateUpdateCount(1); + instance.setPowerStateUpdateTime(DateUtil.currentGMTTime()); + needToUpdate = true; + update(instanceId, instance); + } else { + // to reduce DB updates, consecutive same state update for more than 3 times + if (instance.getPowerStateUpdateCount() < MAX_CONSECUTIVE_SAME_STATE_UPDATE_COUNT) { + instance.setPowerStateUpdateCount(instance.getPowerStateUpdateCount() + 1); + instance.setPowerStateUpdateTime(DateUtil.currentGMTTime()); + needToUpdate = true; + update(instanceId, instance); + } + } + } + return needToUpdate; + } + }); + } - VMInstanceVO instance = findById(instanceId); - if (instance != null) { - Long savedPowerHostId = instance.getPowerHostId(); - if (instance.getPowerState() != powerState || savedPowerHostId == null || savedPowerHostId.longValue() != powerHostId) { - instance.setPowerState(powerState); - instance.setPowerHostId(powerHostId); - instance.setPowerStateUpdateCount(1); - instance.setPowerStateUpdateTime(DateUtil.currentGMTTime()); - needToUpdate = true; - update(instanceId, instance); - } else { - // to reduce DB updates, consecutive same state update for more than 3 times - if (instance.getPowerStateUpdateCount() < MAX_CONSECUTIVE_SAME_STATE_UPDATE_COUNT) { - instance.setPowerStateUpdateCount(instance.getPowerStateUpdateCount() + 1); + @Override + public void resetVmPowerStateTracking(final long instanceId) { + Transaction.execute(new TransactionCallbackNoReturn() { + @Override + public void doInTransactionWithoutResult(TransactionStatus status) { + VMInstanceVO instance = findById(instanceId); + if (instance != null) { + instance.setPowerStateUpdateCount(0); instance.setPowerStateUpdateTime(DateUtil.currentGMTTime()); - needToUpdate = true; update(instanceId, instance); } } - } - - txn.commit(); - return needToUpdate; + }); } - @Override - public void resetVmPowerStateTracking(long instanceId) { - TransactionLegacy txn = TransactionLegacy.currentTxn(); - txn.start(); - VMInstanceVO instance = findById(instanceId); - if (instance != null) { - instance.setPowerStateUpdateCount(0); - instance.setPowerStateUpdateTime(DateUtil.currentGMTTime()); - update(instanceId, instance); - } + @Override @DB + public void resetHostPowerStateTracking(final long hostId) { + Transaction.execute(new TransactionCallbackNoReturn() { + @Override + public void doInTransactionWithoutResult(TransactionStatus status) { + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("powerHostId", SearchCriteria.Op.EQ, hostId); - txn.commit(); - } + VMInstanceVO instance = createForUpdate(); + instance.setPowerStateUpdateCount(0); + instance.setPowerStateUpdateTime(DateUtil.currentGMTTime()); - @Override - @DB - public void resetHostPowerStateTracking(long hostId) { - SearchCriteria sc = createSearchCriteria(); - sc.addAnd("powerHostId", SearchCriteria.Op.EQ, hostId); - - VMInstanceVO instance = this.createForUpdate(); - instance.setPowerStateUpdateCount(0); - instance.setPowerStateUpdateTime(DateUtil.currentGMTTime()); - - this.update(instance, sc); + update(instance, sc); + } + }); } } diff --git a/engine/schema/src/com/cloud/vm/snapshot/dao/VMSnapshotDao.java b/engine/schema/src/com/cloud/vm/snapshot/dao/VMSnapshotDao.java index 792914b0cce..e714a6e30e9 100644 --- a/engine/schema/src/com/cloud/vm/snapshot/dao/VMSnapshotDao.java +++ b/engine/schema/src/com/cloud/vm/snapshot/dao/VMSnapshotDao.java @@ -35,5 +35,5 @@ public interface VMSnapshotDao extends GenericDao, StateDao< List listByParent(Long vmSnapshotId); - VMSnapshotVO findByName(Long vm_id, String name); + VMSnapshotVO findByName(Long vmId, String name); } diff --git a/engine/schema/src/com/cloud/vm/snapshot/dao/VMSnapshotDaoImpl.java b/engine/schema/src/com/cloud/vm/snapshot/dao/VMSnapshotDaoImpl.java index 4ea6abca209..dccd19fca94 100644 --- a/engine/schema/src/com/cloud/vm/snapshot/dao/VMSnapshotDaoImpl.java +++ b/engine/schema/src/com/cloud/vm/snapshot/dao/VMSnapshotDaoImpl.java @@ -114,9 +114,9 @@ public class VMSnapshotDaoImpl extends GenericDaoBase implem } @Override - public VMSnapshotVO findByName(Long vm_id, String name) { + public VMSnapshotVO findByName(Long vmId, String name) { SearchCriteria sc = AllFieldsSearch.create(); - sc.setParameters("vm_id", vm_id); + sc.setParameters("vm_id", vmId); sc.setParameters("display_name", name); return null; } diff --git a/engine/schema/src/org/apache/cloudstack/engine/cloud/entity/api/db/VMEntityVO.java b/engine/schema/src/org/apache/cloudstack/engine/cloud/entity/api/db/VMEntityVO.java index a4a0cc9877c..19d608bbdda 100644 --- a/engine/schema/src/org/apache/cloudstack/engine/cloud/entity/api/db/VMEntityVO.java +++ b/engine/schema/src/org/apache/cloudstack/engine/cloud/entity/api/db/VMEntityVO.java @@ -145,12 +145,6 @@ public class VMEntityVO implements VirtualMachine, FiniteStateObject details; @@ -161,9 +155,6 @@ public class VMEntityVO implements VirtualMachine, FiniteStateObject computeTags; @@ -491,14 +482,6 @@ public class VMEntityVO implements VirtualMachine, FiniteStateObject getComputeTags() { return computeTags; } diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/AutoScaleVmProfileDetailVO.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/AutoScaleVmProfileDetailVO.java new file mode 100644 index 00000000000..06d7296fe13 --- /dev/null +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/AutoScaleVmProfileDetailVO.java @@ -0,0 +1,81 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.resourcedetail; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import org.apache.cloudstack.api.ResourceDetail; + +@Entity +@Table(name = "autoscale_vmprofile_details") +public class AutoScaleVmProfileDetailVO implements ResourceDetail { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "autoscale_vmprofile_id") + private long resourceId; + + @Column(name = "name") + private String name; + + @Column(name = "value", length = 1024) + private String value; + + @Column(name = "display") + private boolean display; + + public AutoScaleVmProfileDetailVO() { + } + + public AutoScaleVmProfileDetailVO(long id, String name, String value) { + this.resourceId = id; + this.name = name; + this.value = value; + } + + @Override + public long getId() { + return id; + } + + @Override + public String getName() { + return name; + } + + @Override + public String getValue() { + return value; + } + + @Override + public long getResourceId() { + return resourceId; + } + + @Override + public boolean isDisplay() { + return display; + } +} \ No newline at end of file diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/DiskOfferingDetailVO.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/DiskOfferingDetailVO.java new file mode 100644 index 00000000000..bdee3c14db0 --- /dev/null +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/DiskOfferingDetailVO.java @@ -0,0 +1,81 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.resourcedetail; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import org.apache.cloudstack.api.ResourceDetail; + +@Entity +@Table(name = "disk_offering_details") +public class DiskOfferingDetailVO implements ResourceDetail { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "offering_id") + private long resourceId; + + @Column(name = "name") + private String name; + + @Column(name = "value", length = 1024) + private String value; + + @Column(name = "display") + private boolean display; + + public DiskOfferingDetailVO() { + } + + public DiskOfferingDetailVO(long id, String name, String value) { + this.resourceId = id; + this.name = name; + this.value = value; + } + + @Override + public long getId() { + return id; + } + + @Override + public String getName() { + return name; + } + + @Override + public String getValue() { + return value; + } + + @Override + public long getResourceId() { + return resourceId; + } + + @Override + public boolean isDisplay() { + return display; + } +} \ No newline at end of file diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/NetworkACLItemDetailVO.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/NetworkACLItemDetailVO.java index fb27d374a94..5abf59cc005 100644 --- a/engine/schema/src/org/apache/cloudstack/resourcedetail/NetworkACLItemDetailVO.java +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/NetworkACLItemDetailVO.java @@ -79,4 +79,3 @@ public class NetworkACLItemDetailVO implements ResourceDetail { return display; } } - diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/NetworkACLListDetailVO.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/NetworkACLListDetailVO.java index 71cf563478a..f60ba8c1270 100644 --- a/engine/schema/src/org/apache/cloudstack/resourcedetail/NetworkACLListDetailVO.java +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/NetworkACLListDetailVO.java @@ -79,4 +79,3 @@ public class NetworkACLListDetailVO implements ResourceDetail { return display; } } - diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/Site2SiteCustomerGatewayDetailVO.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/Site2SiteCustomerGatewayDetailVO.java new file mode 100644 index 00000000000..1a2743cab81 --- /dev/null +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/Site2SiteCustomerGatewayDetailVO.java @@ -0,0 +1,81 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.resourcedetail; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import org.apache.cloudstack.api.ResourceDetail; + +@Entity +@Table(name = "s2s_customer_gateway_details") +public class Site2SiteCustomerGatewayDetailVO implements ResourceDetail { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "s2s_customer_gateway_id") + private long resourceId; + + @Column(name = "name") + private String name; + + @Column(name = "value", length = 1024) + private String value; + + @Column(name = "display") + private boolean display; + + public Site2SiteCustomerGatewayDetailVO() { + } + + public Site2SiteCustomerGatewayDetailVO(long id, String name, String value) { + this.resourceId = id; + this.name = name; + this.value = value; + } + + @Override + public long getId() { + return id; + } + + @Override + public String getName() { + return name; + } + + @Override + public String getValue() { + return value; + } + + @Override + public long getResourceId() { + return resourceId; + } + + @Override + public boolean isDisplay() { + return display; + } +} diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/Site2SiteVpnConnectionDetailVO.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/Site2SiteVpnConnectionDetailVO.java new file mode 100644 index 00000000000..9a4b616624b --- /dev/null +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/Site2SiteVpnConnectionDetailVO.java @@ -0,0 +1,81 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.resourcedetail; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import org.apache.cloudstack.api.ResourceDetail; + +@Entity +@Table(name = "s2s_vpn_connection_details") +public class Site2SiteVpnConnectionDetailVO implements ResourceDetail { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "s2s_vpn_connection_id") + private long resourceId; + + @Column(name = "name") + private String name; + + @Column(name = "value", length = 1024) + private String value; + + @Column(name = "display") + private boolean display; + + public Site2SiteVpnConnectionDetailVO() { + } + + public Site2SiteVpnConnectionDetailVO(long id, String name, String value) { + this.resourceId = id; + this.name = name; + this.value = value; + } + + @Override + public long getId() { + return id; + } + + @Override + public String getName() { + return name; + } + + @Override + public String getValue() { + return value; + } + + @Override + public long getResourceId() { + return resourceId; + } + + @Override + public boolean isDisplay() { + return display; + } +} diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/Site2SiteVpnGatewayDetailVO.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/Site2SiteVpnGatewayDetailVO.java new file mode 100644 index 00000000000..244e218218a --- /dev/null +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/Site2SiteVpnGatewayDetailVO.java @@ -0,0 +1,84 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.resourcedetail; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import org.apache.cloudstack.api.ResourceDetail; + +@Entity +@Table(name = "s2s_vpn_gateway_details") +public class Site2SiteVpnGatewayDetailVO implements ResourceDetail { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "s2s_vpn_gateway_id") + private long resourceId; + + @Column(name = "name") + private String name; + + @Column(name = "value", length = 1024) + private String value; + + @Column(name = "display") + private boolean display; + + public Site2SiteVpnGatewayDetailVO() { + } + + public Site2SiteVpnGatewayDetailVO(long id, String name, String value) { + this.resourceId = id; + this.name = name; + this.value = value; + } + + @Override + public long getId() { + return id; + } + + @Override + public String getName() { + return name; + } + + @Override + public String getValue() { + return value; + } + + @Override + public long getResourceId() { + return resourceId; + } + + @Override + public boolean isDisplay() { + return display; + } +} + + + diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/UserDetailVO.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/UserDetailVO.java new file mode 100644 index 00000000000..69f44739a5e --- /dev/null +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/UserDetailVO.java @@ -0,0 +1,81 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.resourcedetail; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import org.apache.cloudstack.api.ResourceDetail; + +@Entity +@Table(name = "user_details") +public class UserDetailVO implements ResourceDetail { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "user_id") + private long resourceId; + + @Column(name = "name") + private String name; + + @Column(name = "value", length = 1024) + private String value; + + @Column(name = "display") + private boolean display; + + public UserDetailVO() { + } + + public UserDetailVO(long id, String name, String value) { + this.resourceId = id; + this.name = name; + this.value = value; + } + + @Override + public long getId() { + return id; + } + + @Override + public String getName() { + return name; + } + + @Override + public String getValue() { + return value; + } + + @Override + public long getResourceId() { + return resourceId; + } + + @Override + public boolean isDisplay() { + return display; + } +} \ No newline at end of file diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/AutoScaleVmProfileDetailsDao.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/AutoScaleVmProfileDetailsDao.java new file mode 100644 index 00000000000..9da313a85a7 --- /dev/null +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/AutoScaleVmProfileDetailsDao.java @@ -0,0 +1,26 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.resourcedetail.dao; + +import org.apache.cloudstack.resourcedetail.AutoScaleVmProfileDetailVO; +import org.apache.cloudstack.resourcedetail.ResourceDetailsDao; + +import com.cloud.utils.db.GenericDao; + +public interface AutoScaleVmProfileDetailsDao extends GenericDao, ResourceDetailsDao { + +} diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/AutoScaleVmProfileDetailsDaoImpl.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/AutoScaleVmProfileDetailsDaoImpl.java new file mode 100644 index 00000000000..17e0316bc98 --- /dev/null +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/AutoScaleVmProfileDetailsDaoImpl.java @@ -0,0 +1,33 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.resourcedetail.dao; + +import javax.ejb.Local; + +import org.apache.cloudstack.resourcedetail.AutoScaleVmProfileDetailVO; +import org.apache.cloudstack.resourcedetail.ResourceDetailsDaoBase; +import org.springframework.stereotype.Component; + +@Component +@Local(value = {AutoScaleVmProfileDetailsDao.class}) +public class AutoScaleVmProfileDetailsDaoImpl extends ResourceDetailsDaoBase implements AutoScaleVmProfileDetailsDao { + + @Override + public void addDetail(long resourceId, String key, String value) { + super.addDetail(new AutoScaleVmProfileDetailVO(resourceId, key, value)); + } +} \ No newline at end of file diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/DiskOfferingDetailsDao.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/DiskOfferingDetailsDao.java new file mode 100644 index 00000000000..68a8614c93b --- /dev/null +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/DiskOfferingDetailsDao.java @@ -0,0 +1,26 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.resourcedetail.dao; + +import org.apache.cloudstack.resourcedetail.DiskOfferingDetailVO; +import org.apache.cloudstack.resourcedetail.ResourceDetailsDao; + +import com.cloud.utils.db.GenericDao; + +public interface DiskOfferingDetailsDao extends GenericDao, ResourceDetailsDao { + +} \ No newline at end of file diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/DiskOfferingDetailsDaoImpl.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/DiskOfferingDetailsDaoImpl.java new file mode 100644 index 00000000000..e2fc26e722a --- /dev/null +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/DiskOfferingDetailsDaoImpl.java @@ -0,0 +1,33 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.resourcedetail.dao; + +import javax.ejb.Local; + +import org.apache.cloudstack.resourcedetail.DiskOfferingDetailVO; +import org.apache.cloudstack.resourcedetail.ResourceDetailsDaoBase; +import org.springframework.stereotype.Component; + +@Component +@Local(value = {DiskOfferingDetailsDao.class}) +public class DiskOfferingDetailsDaoImpl extends ResourceDetailsDaoBase implements DiskOfferingDetailsDao { + + @Override + public void addDetail(long resourceId, String key, String value) { + super.addDetail(new DiskOfferingDetailVO(resourceId, key, value)); + } +} \ No newline at end of file diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/NetworkACLItemDetailsDaoImpl.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/NetworkACLItemDetailsDaoImpl.java index 930c77a4500..03d12820e32 100644 --- a/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/NetworkACLItemDetailsDaoImpl.java +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/NetworkACLItemDetailsDaoImpl.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -18,12 +18,13 @@ package org.apache.cloudstack.resourcedetail.dao; import javax.ejb.Local; -import org.apache.cloudstack.resourcedetail.NetworkACLItemDetailVO; -import org.apache.cloudstack.resourcedetail.ResourceDetailsDaoBase; import org.springframework.stereotype.Component; +import org.apache.cloudstack.resourcedetail.NetworkACLItemDetailVO; +import org.apache.cloudstack.resourcedetail.ResourceDetailsDaoBase; + @Component -@Local(value = { NetworkACLItemDetailsDao.class }) +@Local(value = {NetworkACLItemDetailsDao.class}) public class NetworkACLItemDetailsDaoImpl extends ResourceDetailsDaoBase implements NetworkACLItemDetailsDao { @Override diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/NetworkACLListDetailsDaoImpl.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/NetworkACLListDetailsDaoImpl.java index 0b7037f7975..e07110f3ab0 100644 --- a/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/NetworkACLListDetailsDaoImpl.java +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/NetworkACLListDetailsDaoImpl.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -18,12 +18,13 @@ package org.apache.cloudstack.resourcedetail.dao; import javax.ejb.Local; -import org.apache.cloudstack.resourcedetail.ResourceDetailsDaoBase; -import org.apache.cloudstack.resourcedetail.NetworkACLListDetailVO; import org.springframework.stereotype.Component; +import org.apache.cloudstack.resourcedetail.NetworkACLListDetailVO; +import org.apache.cloudstack.resourcedetail.ResourceDetailsDaoBase; + @Component -@Local(value = { NetworkACLListDetailsDao.class }) +@Local(value = {NetworkACLListDetailsDao.class}) public class NetworkACLListDetailsDaoImpl extends ResourceDetailsDaoBase implements NetworkACLListDetailsDao { @Override diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/Site2SiteCustomerGatewayDetailsDao.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/Site2SiteCustomerGatewayDetailsDao.java new file mode 100644 index 00000000000..0689b1c25c3 --- /dev/null +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/Site2SiteCustomerGatewayDetailsDao.java @@ -0,0 +1,26 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.resourcedetail.dao; + +import org.apache.cloudstack.resourcedetail.ResourceDetailsDao; +import org.apache.cloudstack.resourcedetail.Site2SiteCustomerGatewayDetailVO; + +import com.cloud.utils.db.GenericDao; + +public interface Site2SiteCustomerGatewayDetailsDao extends GenericDao, ResourceDetailsDao { + +} \ No newline at end of file diff --git a/server/src/com/cloud/uuididentity/IdentityServiceImpl.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/Site2SiteCustomerGatewayDetailsDaoImpl.java similarity index 56% rename from server/src/com/cloud/uuididentity/IdentityServiceImpl.java rename to engine/schema/src/org/apache/cloudstack/resourcedetail/dao/Site2SiteCustomerGatewayDetailsDaoImpl.java index 039bb318905..71e810ee33d 100644 --- a/server/src/com/cloud/uuididentity/IdentityServiceImpl.java +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/Site2SiteCustomerGatewayDetailsDaoImpl.java @@ -14,31 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.uuididentity; +package org.apache.cloudstack.resourcedetail.dao; import javax.ejb.Local; -import javax.inject.Inject; import org.springframework.stereotype.Component; -import org.apache.cloudstack.api.IdentityService; - -import com.cloud.utils.component.ManagerBase; -import com.cloud.uuididentity.dao.IdentityDao; +import org.apache.cloudstack.resourcedetail.ResourceDetailsDaoBase; +import org.apache.cloudstack.resourcedetail.Site2SiteCustomerGatewayDetailVO; @Component -@Local(value = {IdentityService.class}) -public class IdentityServiceImpl extends ManagerBase implements IdentityService { - @Inject - private IdentityDao _identityDao; +@Local(value = {Site2SiteCustomerGatewayDetailsDao.class}) +public class Site2SiteCustomerGatewayDetailsDaoImpl extends ResourceDetailsDaoBase implements Site2SiteCustomerGatewayDetailsDao { @Override - public Long getIdentityId(String tableName, String identityString) { - return _identityDao.getIdentityId(tableName, identityString); - } - - @Override - public String getIdentityUuid(String tableName, String identityString) { - return _identityDao.getIdentityUuid(tableName, identityString); + public void addDetail(long resourceId, String key, String value) { + super.addDetail(new Site2SiteCustomerGatewayDetailVO(resourceId, key, value)); } } diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/Site2SiteVpnConnectionDetailsDao.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/Site2SiteVpnConnectionDetailsDao.java new file mode 100644 index 00000000000..ceb5cf7211f --- /dev/null +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/Site2SiteVpnConnectionDetailsDao.java @@ -0,0 +1,26 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.resourcedetail.dao; + +import org.apache.cloudstack.resourcedetail.ResourceDetailsDao; +import org.apache.cloudstack.resourcedetail.Site2SiteVpnConnectionDetailVO; + +import com.cloud.utils.db.GenericDao; + +public interface Site2SiteVpnConnectionDetailsDao extends GenericDao, ResourceDetailsDao { + +} diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/Site2SiteVpnConnectionDetailsDaoImpl.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/Site2SiteVpnConnectionDetailsDaoImpl.java new file mode 100644 index 00000000000..7261df8ea1f --- /dev/null +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/Site2SiteVpnConnectionDetailsDaoImpl.java @@ -0,0 +1,32 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.resourcedetail.dao; + +import javax.ejb.Local; + +import org.apache.cloudstack.resourcedetail.ResourceDetailsDaoBase; +import org.apache.cloudstack.resourcedetail.Site2SiteVpnConnectionDetailVO; +import org.springframework.stereotype.Component; + +@Component +@Local(value = {Site2SiteVpnConnectionDetailsDao.class}) +public class Site2SiteVpnConnectionDetailsDaoImpl extends ResourceDetailsDaoBase implements Site2SiteVpnConnectionDetailsDao { + + @Override + public void addDetail(long resourceId, String key, String value) { + super.addDetail(new Site2SiteVpnConnectionDetailVO(resourceId, key, value)); + } +} diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/Site2SiteVpnGatewayDetailsDao.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/Site2SiteVpnGatewayDetailsDao.java new file mode 100644 index 00000000000..12c181f9352 --- /dev/null +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/Site2SiteVpnGatewayDetailsDao.java @@ -0,0 +1,27 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.resourcedetail.dao; + +import org.apache.cloudstack.resourcedetail.ResourceDetailsDao; +import org.apache.cloudstack.resourcedetail.Site2SiteVpnGatewayDetailVO; + +import com.cloud.utils.db.GenericDao; + +public interface Site2SiteVpnGatewayDetailsDao extends GenericDao, ResourceDetailsDao { + +} + diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/Site2SiteVpnGatewayDetailsDaoImpl.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/Site2SiteVpnGatewayDetailsDaoImpl.java new file mode 100644 index 00000000000..1e6b4809ca8 --- /dev/null +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/Site2SiteVpnGatewayDetailsDaoImpl.java @@ -0,0 +1,34 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.resourcedetail.dao; + +import javax.ejb.Local; + +import org.springframework.stereotype.Component; + +import org.apache.cloudstack.resourcedetail.ResourceDetailsDaoBase; +import org.apache.cloudstack.resourcedetail.Site2SiteVpnGatewayDetailVO; + +@Component +@Local(value = { Site2SiteVpnGatewayDetailsDao.class }) +public class Site2SiteVpnGatewayDetailsDaoImpl extends ResourceDetailsDaoBase implements Site2SiteVpnGatewayDetailsDao { + + @Override + public void addDetail(long resourceId, String key, String value) { + super.addDetail(new Site2SiteVpnGatewayDetailVO(resourceId, key, value)); + } +} diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/UserDetailsDao.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/UserDetailsDao.java new file mode 100644 index 00000000000..2ef3fea503b --- /dev/null +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/UserDetailsDao.java @@ -0,0 +1,26 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.resourcedetail.dao; + +import org.apache.cloudstack.resourcedetail.UserDetailVO; +import org.apache.cloudstack.resourcedetail.ResourceDetailsDao; + +import com.cloud.utils.db.GenericDao; + +public interface UserDetailsDao extends GenericDao, ResourceDetailsDao { + +} \ No newline at end of file diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/UserDetailsDaoImpl.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/UserDetailsDaoImpl.java new file mode 100644 index 00000000000..508185297a8 --- /dev/null +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/UserDetailsDaoImpl.java @@ -0,0 +1,33 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.resourcedetail.dao; + +import javax.ejb.Local; + +import org.apache.cloudstack.resourcedetail.ResourceDetailsDaoBase; +import org.apache.cloudstack.resourcedetail.UserDetailVO; +import org.springframework.stereotype.Component; + +@Component +@Local(value = {UserDetailsDao.class}) +public class UserDetailsDaoImpl extends ResourceDetailsDaoBase implements UserDetailsDao { + + @Override + public void addDetail(long resourceId, String key, String value) { + super.addDetail(new UserDetailVO(resourceId, key, value)); + } +} \ No newline at end of file diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/VpcDetailsDaoImpl.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/VpcDetailsDaoImpl.java index 64597231009..fb22c7c18b2 100644 --- a/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/VpcDetailsDaoImpl.java +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/VpcDetailsDaoImpl.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -18,12 +18,13 @@ package org.apache.cloudstack.resourcedetail.dao; import javax.ejb.Local; -import org.apache.cloudstack.resourcedetail.ResourceDetailsDaoBase; -import org.apache.cloudstack.resourcedetail.VpcDetailVO; import org.springframework.stereotype.Component; +import org.apache.cloudstack.resourcedetail.ResourceDetailsDaoBase; +import org.apache.cloudstack.resourcedetail.VpcDetailVO; + @Component -@Local(value = { VpcDetailsDao.class }) +@Local(value = {VpcDetailsDao.class}) public class VpcDetailsDaoImpl extends ResourceDetailsDaoBase implements VpcDetailsDao { @Override diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/VpcGatewayDetailsDao.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/VpcGatewayDetailsDao.java index 4f1691926a8..a42d0cfcb70 100644 --- a/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/VpcGatewayDetailsDao.java +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/VpcGatewayDetailsDao.java @@ -24,4 +24,3 @@ import com.cloud.utils.db.GenericDao; public interface VpcGatewayDetailsDao extends GenericDao, ResourceDetailsDao { } - diff --git a/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/VpcGatewayDetailsDaoImpl.java b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/VpcGatewayDetailsDaoImpl.java index 2b4c563a4cf..871c3631941 100644 --- a/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/VpcGatewayDetailsDaoImpl.java +++ b/engine/schema/src/org/apache/cloudstack/resourcedetail/dao/VpcGatewayDetailsDaoImpl.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -18,12 +18,13 @@ package org.apache.cloudstack.resourcedetail.dao; import javax.ejb.Local; -import org.apache.cloudstack.resourcedetail.ResourceDetailsDaoBase; -import org.apache.cloudstack.resourcedetail.VpcGatewayDetailVO; import org.springframework.stereotype.Component; +import org.apache.cloudstack.resourcedetail.ResourceDetailsDaoBase; +import org.apache.cloudstack.resourcedetail.VpcGatewayDetailVO; + @Component -@Local(value = { VpcGatewayDetailsDao.class }) +@Local(value = {VpcGatewayDetailsDao.class}) public class VpcGatewayDetailsDaoImpl extends ResourceDetailsDaoBase implements VpcGatewayDetailsDao { @Override diff --git a/engine/schema/src/org/apache/cloudstack/storage/datastore/db/SnapshotDataStoreDao.java b/engine/schema/src/org/apache/cloudstack/storage/datastore/db/SnapshotDataStoreDao.java index 67ce558ee72..e24c0351e46 100644 --- a/engine/schema/src/org/apache/cloudstack/storage/datastore/db/SnapshotDataStoreDao.java +++ b/engine/schema/src/org/apache/cloudstack/storage/datastore/db/SnapshotDataStoreDao.java @@ -49,7 +49,11 @@ public interface SnapshotDataStoreDao extends GenericDao listOnCache(long snapshotId); void updateStoreRoleToCache(long storeId); + + SnapshotDataStoreVO findLatestSnapshotForVolume(Long volumeId, DataStoreRole role); } diff --git a/engine/schema/src/org/apache/cloudstack/storage/datastore/db/TemplateDataStoreDao.java b/engine/schema/src/org/apache/cloudstack/storage/datastore/db/TemplateDataStoreDao.java index 1a12b3dc074..ab458895e46 100644 --- a/engine/schema/src/org/apache/cloudstack/storage/datastore/db/TemplateDataStoreDao.java +++ b/engine/schema/src/org/apache/cloudstack/storage/datastore/db/TemplateDataStoreDao.java @@ -24,6 +24,7 @@ import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreState import com.cloud.storage.DataStoreRole; import com.cloud.storage.VMTemplateStorageResourceAssoc; +import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; import com.cloud.utils.db.GenericDao; import com.cloud.utils.fsm.StateDao; @@ -50,12 +51,16 @@ public interface TemplateDataStoreDao extends GenericDao listByTemplate(long templateId); diff --git a/engine/service/src/main/webapp/WEB-INF/beans.xml b/engine/service/src/main/webapp/WEB-INF/beans.xml index 1be2c223e20..33bd4adb13b 100644 --- a/engine/service/src/main/webapp/WEB-INF/beans.xml +++ b/engine/service/src/main/webapp/WEB-INF/beans.xml @@ -42,7 +42,7 @@ - + @@ -51,7 +51,7 @@ - + @@ -61,7 +61,7 @@ - + diff --git a/engine/storage/datamotion/src/org/apache/cloudstack/storage/motion/AncientDataMotionStrategy.java b/engine/storage/datamotion/src/org/apache/cloudstack/storage/motion/AncientDataMotionStrategy.java index 5c1ff40d32e..fa1dce45719 100644 --- a/engine/storage/datamotion/src/org/apache/cloudstack/storage/motion/AncientDataMotionStrategy.java +++ b/engine/storage/datamotion/src/org/apache/cloudstack/storage/motion/AncientDataMotionStrategy.java @@ -18,6 +18,7 @@ */ package org.apache.cloudstack.storage.motion; +import java.util.HashMap; import java.util.Map; import javax.inject.Inject; @@ -37,6 +38,7 @@ import org.apache.cloudstack.engine.subsystem.api.storage.HostScope; import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.Event; import org.apache.cloudstack.engine.subsystem.api.storage.Scope; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; +import org.apache.cloudstack.engine.subsystem.api.storage.StorageAction; import org.apache.cloudstack.engine.subsystem.api.storage.StorageCacheManager; import org.apache.cloudstack.engine.subsystem.api.storage.StrategyPriority; import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo; @@ -191,9 +193,9 @@ public class AncientDataMotionStrategy implements DataMotionStrategy { } } - protected DataObject cacheSnapshotChain(SnapshotInfo snapshot) { + protected DataObject cacheSnapshotChain(SnapshotInfo snapshot, Scope scope) { DataObject leafData = null; - DataStore store = cacheMgr.getCacheStorage(snapshot.getDataStore().getScope()); + DataStore store = cacheMgr.getCacheStorage(scope); while (snapshot != null) { DataObject cacheData = cacheMgr.createCacheObject(snapshot, store); if (leafData == null) { @@ -204,6 +206,7 @@ public class AncientDataMotionStrategy implements DataMotionStrategy { return leafData; } + protected void deleteSnapshotCacheChain(SnapshotInfo snapshot) { while (snapshot != null) { cacheMgr.deleteCacheObject(snapshot); @@ -228,7 +231,8 @@ public class AncientDataMotionStrategy implements DataMotionStrategy { DataObject srcData = snapObj; try { if (!(storTO instanceof NfsTO)) { - srcData = cacheSnapshotChain(snapshot); + // cache snapshot to zone-wide staging store for the volume to be created + srcData = cacheSnapshotChain(snapshot, new ZoneScope(pool.getDataCenterId())); } String value = configDao.getValue(Config.CreateVolumeFromSnapshotWait.toString()); @@ -360,7 +364,7 @@ public class AncientDataMotionStrategy implements DataMotionStrategy { protected Answer migrateVolumeToPool(DataObject srcData, DataObject destData) { VolumeInfo volume = (VolumeInfo)srcData; StoragePool destPool = (StoragePool)dataStoreMgr.getDataStore(destData.getDataStore().getId(), DataStoreRole.Primary); - MigrateVolumeCommand command = new MigrateVolumeCommand(volume.getId(), volume.getPath(), destPool); + MigrateVolumeCommand command = new MigrateVolumeCommand(volume.getId(), volume.getPath(), destPool, volume.getAttachedVmName()); EndPoint ep = selector.select(volume.getDataStore()); Answer answer = null; if (ep == null) { @@ -437,8 +441,8 @@ public class AncientDataMotionStrategy implements DataMotionStrategy { boolean needCache = false; if (needCacheStorage(srcData, destData)) { needCache = true; - SnapshotInfo snapshot = (SnapshotInfo)srcData; - srcData = cacheSnapshotChain(snapshot); + SnapshotInfo snapshot = (SnapshotInfo) srcData; + srcData = cacheSnapshotChain(snapshot, snapshot.getDataStore().getScope()); } EndPoint ep = null; @@ -470,6 +474,14 @@ public class AncientDataMotionStrategy implements DataMotionStrategy { int _backupsnapshotwait = NumbersUtil.parseInt(value, Integer.parseInt(Config.BackupSnapshotWait.getDefaultValue())); DataObject cacheData = null; + SnapshotInfo snapshotInfo = (SnapshotInfo)srcData; + Object payload = snapshotInfo.getPayload(); + Boolean fullSnapshot = true; + if (payload != null) { + fullSnapshot = (Boolean)payload; + } + Map options = new HashMap(); + options.put("fullSnapshot", fullSnapshot.toString()); Answer answer = null; try { if (needCacheStorage(srcData, destData)) { @@ -478,6 +490,7 @@ public class AncientDataMotionStrategy implements DataMotionStrategy { CopyCommand cmd = new CopyCommand(srcData.getTO(), destData.getTO(), _backupsnapshotwait, VirtualMachineManager.ExecuteInSequence.value()); cmd.setCacheTO(cacheData.getTO()); + cmd.setOptions(options); EndPoint ep = selector.select(srcData, destData); if (ep == null) { String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; @@ -488,7 +501,8 @@ public class AncientDataMotionStrategy implements DataMotionStrategy { } } else { CopyCommand cmd = new CopyCommand(srcData.getTO(), destData.getTO(), _backupsnapshotwait, VirtualMachineManager.ExecuteInSequence.value()); - EndPoint ep = selector.select(srcData, destData); + cmd.setOptions(options); + EndPoint ep = selector.select(srcData, destData, StorageAction.BACKUPSNAPSHOT); if (ep == null) { String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; s_logger.error(errMsg); @@ -496,12 +510,11 @@ public class AncientDataMotionStrategy implements DataMotionStrategy { } else { answer = ep.sendMessage(cmd); } + } - // clean up cache entry in case of failure - if (answer == null || !answer.getResult()) { - if (cacheData != null) { - cacheMgr.deleteCacheObject(cacheData); - } + // clean up cache entry + if (cacheData != null) { + cacheMgr.deleteCacheObject(cacheData); } return answer; } catch (Exception e) { diff --git a/engine/storage/image/src/org/apache/cloudstack/storage/image/TemplateServiceImpl.java b/engine/storage/image/src/org/apache/cloudstack/storage/image/TemplateServiceImpl.java index dbd95e8b35f..166b523e387 100644 --- a/engine/storage/image/src/org/apache/cloudstack/storage/image/TemplateServiceImpl.java +++ b/engine/storage/image/src/org/apache/cloudstack/storage/image/TemplateServiceImpl.java @@ -41,6 +41,7 @@ import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint; import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector; import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine; import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.Event; +import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.State; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; import org.apache.cloudstack.engine.subsystem.api.storage.StorageCacheManager; import org.apache.cloudstack.engine.subsystem.api.storage.TemplateDataFactory; @@ -74,9 +75,10 @@ import com.cloud.dc.dao.DataCenterDao; import com.cloud.exception.ResourceAllocationException; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.storage.DataStoreRole; -import com.cloud.storage.ScopeType; +import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.Storage.TemplateType; import com.cloud.storage.StoragePool; +import com.cloud.storage.VMTemplateStorageResourceAssoc; import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; import com.cloud.storage.VMTemplateVO; import com.cloud.storage.VMTemplateZoneVO; @@ -392,9 +394,16 @@ public class TemplateServiceImpl implements TemplateService { s_logger.info("Template Sync did not find " + uniqueName + " on image store " + storeId + ", may request download based on available hypervisor types"); if (tmpltStore != null) { - s_logger.info("Removing leftover template " + uniqueName + " entry from template store table"); - // remove those leftover entries - _vmTemplateStoreDao.remove(tmpltStore.getId()); + if (_storeMgr.isRegionStore(store) && tmpltStore.getDownloadState() == VMTemplateStorageResourceAssoc.Status.DOWNLOADED + && tmpltStore.getState() == State.Ready + && tmpltStore.getInstallPath() == null) { + s_logger.info("Keep fake entry in template store table for migration of previous NFS to object store"); + } + else { + s_logger.info("Removing leftover template " + uniqueName + " entry from template store table"); + // remove those leftover entries + _vmTemplateStoreDao.remove(tmpltStore.getId()); + } } } } @@ -424,6 +433,17 @@ public class TemplateServiceImpl implements TemplateService { continue; } + // if this is a region store, and there is already an DOWNLOADED entry there without install_path information, which + // means that this is a duplicate entry from migration of previous NFS to staging. + if (_storeMgr.isRegionStore(store)) { + TemplateDataStoreVO tmpltStore = _vmTemplateStoreDao.findByStoreTemplate(storeId, tmplt.getId()); + if (tmpltStore != null && tmpltStore.getDownloadState() == VMTemplateStorageResourceAssoc.Status.DOWNLOADED && tmpltStore.getState() == State.Ready + && tmpltStore.getInstallPath() == null) { + s_logger.info("Skip sync template for migration of previous NFS to object store"); + continue; + } + } + if (availHypers.contains(tmplt.getHypervisorType())) { s_logger.info("Downloading template " + tmplt.getUniqueName() + " to image store " + store.getName()); associateTemplateToZone(tmplt.getId(), zoneId); @@ -665,18 +685,14 @@ public class TemplateServiceImpl implements TemplateService { return null; } - private boolean isRegionStore(DataStore store) { - if (store.getScope().getScopeType() == ScopeType.ZONE && store.getScope().getScopeId() == null) - return true; - else - return false; - } - // This routine is used to push templates currently on cache store, but not in region store to region store. // used in migrating existing NFS secondary storage to S3. @Override public void syncTemplateToRegionStore(long templateId, DataStore store) { - if (isRegionStore(store)) { + if (_storeMgr.isRegionStore(store)) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Sync template " + templateId + " from cache to object store..."); + } // if template is on region wide object store, check if it is really downloaded there (by checking install_path). Sync template to region // wide store if it is not there physically. TemplateInfo tmplOnStore = _templateFactory.getTemplate(templateId, store); @@ -706,6 +722,13 @@ public class TemplateServiceImpl implements TemplateService { @Override public AsyncCallFuture copyTemplate(TemplateInfo srcTemplate, DataStore destStore) { + // for vmware template, we need to check if ova packing is needed, since template created from snapshot does not have .ova file + // we invoke createEntityExtractURL to trigger ova packing. Ideally, we can directly use extractURL to pass to following createTemplate. + // Need to understand what is the background to use two different urls for copy and extract. + if (srcTemplate.getFormat() == ImageFormat.OVA){ + ImageStoreEntity tmpltStore = (ImageStoreEntity)srcTemplate.getDataStore(); + tmpltStore.createEntityExtractUrl(srcTemplate.getInstallPath(), srcTemplate.getFormat(), srcTemplate); + } // generate a URL from source template ssvm to download to destination data store String url = generateCopyUrl(srcTemplate); if (url == null) { diff --git a/engine/storage/integration-test/pom.xml b/engine/storage/integration-test/pom.xml index 7de60fcfb7b..7bb27e060e4 100644 --- a/engine/storage/integration-test/pom.xml +++ b/engine/storage/integration-test/pom.xml @@ -119,8 +119,6 @@ org.apache.httpcomponents httpclient - - 4.2.2 compile @@ -185,38 +183,5 @@ - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - - org.apache.maven.plugins - - - maven-antrun-plugin - - [1.7,) - - run - - - - - - - - - - - - diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/AllTests.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/AllTests.java index c475632e910..12943ffb79a 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/AllTests.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/AllTests.java @@ -23,7 +23,7 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({volumeServiceTest.class}) +@SuiteClasses({VolumeServiceTest.class}) public class AllTests { } diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/ChildTestConfiguration.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/ChildTestConfiguration.java index 9a676f9201f..69d60c26943 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/ChildTestConfiguration.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/ChildTestConfiguration.java @@ -98,14 +98,14 @@ import com.cloud.vm.snapshot.dao.VMSnapshotDaoImpl; @Configuration @ComponentScan(basePackageClasses = {NicDaoImpl.class, VMInstanceDaoImpl.class, VMTemplateHostDaoImpl.class, VolumeHostDaoImpl.class, VolumeDaoImpl.class, - VMTemplatePoolDaoImpl.class, ResourceTagsDaoImpl.class, VMTemplateDaoImpl.class, MockStorageMotionStrategy.class, ConfigurationDaoImpl.class, - ClusterDaoImpl.class, HostPodDaoImpl.class, VMTemplateZoneDaoImpl.class, VMTemplateDetailsDaoImpl.class, HostDetailsDaoImpl.class, - HostTagsDaoImpl.class, HostTransferMapDaoImpl.class, DataCenterIpAddressDaoImpl.class, DataCenterLinkLocalIpAddressDaoImpl.class, - DataCenterVnetDaoImpl.class, PodVlanDaoImpl.class, DataCenterDetailsDaoImpl.class, DiskOfferingDaoImpl.class, StoragePoolHostDaoImpl.class, - UserVmDaoImpl.class, UserVmDetailsDaoImpl.class, ServiceOfferingDaoImpl.class, CapacityDaoImpl.class, SnapshotDaoImpl.class, VMSnapshotDaoImpl.class, - OCFS2ManagerImpl.class, ClusterDetailsDaoImpl.class, SecondaryStorageVmDaoImpl.class, ConsoleProxyDaoImpl.class, StoragePoolWorkDaoImpl.class, - StorageCacheManagerImpl.class, UserDaoImpl.class, DataCenterDaoImpl.class, StoragePoolDetailsDaoImpl.class, DomainDaoImpl.class, - DownloadMonitorImpl.class, AccountDaoImpl.class, ActionEventUtils.class, EventDaoImpl.class}, + VMTemplatePoolDaoImpl.class, ResourceTagsDaoImpl.class, VMTemplateDaoImpl.class, MockStorageMotionStrategy.class, ConfigurationDaoImpl.class, + ClusterDaoImpl.class, HostPodDaoImpl.class, VMTemplateZoneDaoImpl.class, VMTemplateDetailsDaoImpl.class, HostDetailsDaoImpl.class, + HostTagsDaoImpl.class, HostTransferMapDaoImpl.class, DataCenterIpAddressDaoImpl.class, DataCenterLinkLocalIpAddressDaoImpl.class, + DataCenterVnetDaoImpl.class, PodVlanDaoImpl.class, DataCenterDetailsDaoImpl.class, DiskOfferingDaoImpl.class, StoragePoolHostDaoImpl.class, + UserVmDaoImpl.class, UserVmDetailsDaoImpl.class, ServiceOfferingDaoImpl.class, CapacityDaoImpl.class, SnapshotDaoImpl.class, VMSnapshotDaoImpl.class, + OCFS2ManagerImpl.class, ClusterDetailsDaoImpl.class, SecondaryStorageVmDaoImpl.class, ConsoleProxyDaoImpl.class, StoragePoolWorkDaoImpl.class, + StorageCacheManagerImpl.class, UserDaoImpl.class, DataCenterDaoImpl.class, StoragePoolDetailsDaoImpl.class, DomainDaoImpl.class, + DownloadMonitorImpl.class, AccountDaoImpl.class, ActionEventUtils.class, EventDaoImpl.class}, includeFilters = {@Filter(value = Library.class, type = FilterType.CUSTOM)}, useDefaultFilters = false) public class ChildTestConfiguration extends TestConfiguration { diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/CloudStackTestNGBase.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/CloudStackTestNGBase.java index 51e49431b85..7442f1d43f2 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/CloudStackTestNGBase.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/CloudStackTestNGBase.java @@ -74,7 +74,7 @@ public class CloudStackTestNGBase extends AbstractTestNGSpringContextTests { "primary-storage-want-to-add", "devcloud-secondary-storage", "s3-accesskey", "s3-secretkey", "s3-endpoint", "s3-template-bucket", "s3-usehttps", "image-install-path", "primary-storage-uuid-want-to-add", "script-path", "hypervisor"}) protected void setup(String hostuuid, String gateway, String cidr, String hostIp, String templateUrl, String localStorageUuid, String primaryStorage, - String secondaryStorage, String s3_accessKey, String s3_secretKey, String s3_endpoint, String s3_template_bucket, String s3_usehttps, String imageInstallPath, + String secondaryStorage, String s3AccessKey, String s3SecretKey, String s3Endpoint, String s3TemplateBucket, String s3Usehttps, String imageInstallPath, String primaryStorageUuid, String scriptPath, String hypervisor) { this.hostGuid = hostuuid; this.hostGateway = gateway; @@ -88,11 +88,11 @@ public class CloudStackTestNGBase extends AbstractTestNGSpringContextTests { this.hypervisor = HypervisorType.getType(hypervisor); this.setSecondaryStorage(secondaryStorage); // set S3 parameters - this.s3AccessKey = s3_accessKey; - this.s3SecretKey = s3_secretKey; - this.s3EndPoint = s3_endpoint; - this.s3TemplateBucket = s3_template_bucket; - this.s3UseHttps = Boolean.parseBoolean(s3_usehttps); + this.s3AccessKey = s3AccessKey; + this.s3SecretKey = s3SecretKey; + this.s3EndPoint = s3Endpoint; + this.s3TemplateBucket = s3TemplateBucket; + this.s3UseHttps = Boolean.parseBoolean(s3Usehttps); this.scriptPath = scriptPath; if (this.scriptPath != null) { System.setProperty("paths.script", this.getScriptPath()); diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/EndpointSelectorTest.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/EndpointSelectorTest.java index 9227c887813..b841bf2488a 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/EndpointSelectorTest.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/EndpointSelectorTest.java @@ -34,7 +34,6 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Matchers; -import org.mockito.Mockito; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/FakePrimaryDataStoreDriver.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/FakePrimaryDataStoreDriver.java index 7fb9e81b593..d277991cbe6 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/FakePrimaryDataStoreDriver.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/FakePrimaryDataStoreDriver.java @@ -18,6 +18,7 @@ */ package org.apache.cloudstack.storage.test; +import java.util.Map; import java.util.UUID; import org.apache.cloudstack.engine.subsystem.api.storage.ChapInfo; @@ -35,13 +36,27 @@ import org.apache.cloudstack.storage.to.SnapshotObjectTO; import com.cloud.agent.api.to.DataStoreTO; import com.cloud.agent.api.to.DataTO; +import com.cloud.host.Host; +import com.cloud.storage.StoragePool; +import com.cloud.storage.Volume; public class FakePrimaryDataStoreDriver implements PrimaryDataStoreDriver { boolean snapshotResult = true; @Override public ChapInfo getChapInfo(VolumeInfo volumeInfo) { - return null; //To change body of implemented methods use File | Settings | File Templates. + return null; // To change body of implemented methods, use File | Settings | File Templates. + } + + @Override + public boolean connectVolumeToHost(VolumeInfo volumeInfo, Host host, DataStore dataStore) { return false; } + + @Override + public void disconnectVolumeFromHost(VolumeInfo volumeInfo, Host host, DataStore dataStore) {} + + @Override + public long getVolumeSizeIncludingHypervisorSnapshotReserve(Volume volume, StoragePool pool) { + return volume.getSize(); } @Override @@ -106,4 +121,10 @@ public class FakePrimaryDataStoreDriver implements PrimaryDataStoreDriver { public void resize(DataObject data, AsyncCompletionCallback callback) { //To change body of implemented methods use File | Settings | File Templates. } + + @Override + public Map getCapabilities() { + // TODO Auto-generated method stub + return null; + } } diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/SnapshotTest.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/SnapshotTest.java index f1f9383bfce..cac6ea2bbd7 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/SnapshotTest.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/SnapshotTest.java @@ -277,8 +277,7 @@ public class SnapshotTest extends CloudStackTestNGBase { List hosts = new ArrayList(); hosts.add(this.host); Mockito.when(resourceMgr.listAllUpAndEnabledHosts((Type)Matchers.any(), Matchers.anyLong(), Matchers.anyLong(), Matchers.anyLong())).thenReturn(hosts); - - remoteEp = RemoteHostEndPoint.getHypervisorHostEndPoint(this.host.getId(), this.host.getPrivateIpAddress(), this.host.getPublicIpAddress()); + remoteEp = RemoteHostEndPoint.getHypervisorHostEndPoint(this.host); Mockito.when(epSelector.select(Matchers.any(DataObject.class), Matchers.any(DataObject.class))).thenReturn(remoteEp); Mockito.when(epSelector.select(Matchers.any(DataObject.class))).thenReturn(remoteEp); Mockito.when(epSelector.select(Matchers.any(DataStore.class))).thenReturn(remoteEp); diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/SnapshotTestWithFakeData.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/SnapshotTestWithFakeData.java index 88fd54d4db8..fcac783223c 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/SnapshotTestWithFakeData.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/SnapshotTestWithFakeData.java @@ -43,7 +43,6 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Matchers; -import org.mockito.Mockito; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -208,7 +207,7 @@ public class SnapshotTestWithFakeData { Snapshot.Type snapshotType = Snapshot.Type.RECURRING; SnapshotVO snapshotVO = new SnapshotVO(dcId, 2, 1, 1L, 1L, UUID.randomUUID().toString(), (short)snapshotType.ordinal(), snapshotType.name(), 100, Hypervisor.HypervisorType.XenServer); - return this.snapshotDao.persist(snapshotVO); + return snapshotDao.persist(snapshotVO); } private SnapshotVO createSnapshotInDb(Long volumeId) { @@ -216,7 +215,7 @@ public class SnapshotTestWithFakeData { SnapshotVO snapshotVO = new SnapshotVO(dcId, 2, 1, volumeId, 1L, UUID.randomUUID().toString(), (short)snapshotType.ordinal(), snapshotType.name(), 100, Hypervisor.HypervisorType.XenServer); - return this.snapshotDao.persist(snapshotVO); + return snapshotDao.persist(snapshotVO); } private VolumeInfo createVolume(Long templateId, DataStore store) { @@ -246,8 +245,8 @@ public class SnapshotTestWithFakeData { pool.setPodId(podId); pool.setScope(ScopeType.CLUSTER); pool.setStorageProviderName(DataStoreProvider.DEFAULT_PRIMARY); - pool = this.primaryDataStoreDao.persist(pool); - DataStore store = this.dataStoreManager.getPrimaryDataStore(pool.getId()); + pool = primaryDataStoreDao.persist(pool); + DataStore store = dataStoreManager.getPrimaryDataStore(pool.getId()); return store; } diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/volumeServiceTest.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/VolumeServiceTest.java similarity index 99% rename from engine/storage/integration-test/test/org/apache/cloudstack/storage/test/volumeServiceTest.java rename to engine/storage/integration-test/test/org/apache/cloudstack/storage/test/VolumeServiceTest.java index 167dd529ed1..5fe1d395330 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/volumeServiceTest.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/VolumeServiceTest.java @@ -85,7 +85,7 @@ import com.cloud.storage.dao.VolumeDao; import com.cloud.utils.component.ComponentContext; @ContextConfiguration(locations = {"classpath:/storageContext.xml"}) -public class volumeServiceTest extends CloudStackTestNGBase { +public class VolumeServiceTest extends CloudStackTestNGBase { // @Inject // ImageDataStoreProviderManager imageProviderMgr; @Inject @@ -195,7 +195,7 @@ public class volumeServiceTest extends CloudStackTestNGBase { Mockito.when(hostDao.findById(Matchers.anyLong())).thenReturn(host); Mockito.when(hostDao.findHypervisorHostInCluster(Matchers.anyLong())).thenReturn(results); List eps = new ArrayList(); - eps.add(RemoteHostEndPoint.getHypervisorHostEndPoint(host.getId(), host.getPrivateIpAddress(), host.getPublicIpAddress())); + eps.add(RemoteHostEndPoint.getHypervisorHostEndPoint(host)); Mockito.when(selector.selectAll(Matchers.any(DataStore.class))).thenReturn(eps); Mockito.when(selector.select(Matchers.any(DataObject.class))).thenReturn(eps.get(0)); Mockito.when(selector.select(Matchers.any(DataObject.class), Matchers.any(DataObject.class))).thenReturn(eps.get(0)); diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/VolumeTest.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/VolumeTest.java index c75b2e75c80..4a6151d55c9 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/VolumeTest.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/VolumeTest.java @@ -254,7 +254,7 @@ public class VolumeTest extends CloudStackTestNGBase { hosts.add(this.host); Mockito.when(resourceMgr.listAllUpAndEnabledHosts((Type)Matchers.any(), Matchers.anyLong(), Matchers.anyLong(), Matchers.anyLong())).thenReturn(hosts); - RemoteHostEndPoint ep = RemoteHostEndPoint.getHypervisorHostEndPoint(this.host.getId(), this.host.getPrivateIpAddress(), this.host.getPublicIpAddress()); + RemoteHostEndPoint ep = RemoteHostEndPoint.getHypervisorHostEndPoint(this.host); Mockito.when(epSelector.select(Matchers.any(DataObject.class), Matchers.any(DataObject.class))).thenReturn(ep); Mockito.when(epSelector.select(Matchers.any(DataObject.class))).thenReturn(ep); Mockito.when(epSelector.select(Matchers.any(DataStore.class))).thenReturn(ep); diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/VolumeTestVmware.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/VolumeTestVmware.java index 800bc6b05de..1f3aff04f33 100644 --- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/VolumeTestVmware.java +++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/VolumeTestVmware.java @@ -256,7 +256,7 @@ public class VolumeTestVmware extends CloudStackTestNGBase { hosts.add(this.host); Mockito.when(resourceMgr.listAllUpAndEnabledHosts((Type)Matchers.any(), Matchers.anyLong(), Matchers.anyLong(), Matchers.anyLong())).thenReturn(hosts); - RemoteHostEndPoint ep = RemoteHostEndPoint.getHypervisorHostEndPoint(this.host.getId(), this.host.getPrivateIpAddress(), this.host.getPublicIpAddress()); + RemoteHostEndPoint ep = RemoteHostEndPoint.getHypervisorHostEndPoint(this.host); Mockito.when(epSelector.select(Matchers.any(DataObject.class), Matchers.any(DataObject.class))).thenReturn(ep); Mockito.when(epSelector.select(Matchers.any(DataObject.class))).thenReturn(ep); Mockito.when(epSelector.select(Matchers.any(DataStore.class))).thenReturn(ep); diff --git a/engine/storage/integration-test/test/resources/StorageAllocatorTestContext.xml b/engine/storage/integration-test/test/resources/StorageAllocatorTestContext.xml index 1f5aa585f67..a981b8e9b4e 100644 --- a/engine/storage/integration-test/test/resources/StorageAllocatorTestContext.xml +++ b/engine/storage/integration-test/test/resources/StorageAllocatorTestContext.xml @@ -1,20 +1,19 @@ - - + - + - + @@ -36,10 +35,11 @@ - + - + diff --git a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotDataFactoryImpl.java b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotDataFactoryImpl.java index 6205fe40deb..16c14f3c36d 100644 --- a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotDataFactoryImpl.java +++ b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotDataFactoryImpl.java @@ -79,6 +79,18 @@ public class SnapshotDataFactoryImpl implements SnapshotDataFactory { return so; } + @Override + public SnapshotInfo getReadySnapshotOnCache(long snapshotId) { + SnapshotDataStoreVO snapStore = snapshotStoreDao.findReadyOnCache(snapshotId); + if (snapStore != null) { + DataStore store = storeMgr.getDataStore(snapStore.getDataStoreId(), DataStoreRole.ImageCache); + return getSnapshot(snapshotId, store); + } else { + return null; + } + + } + @Override public List listSnapshotOnCache(long snapshotId) { List cacheSnapshots = snapshotStoreDao.listOnCache(snapshotId); diff --git a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotObject.java b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotObject.java index 2594f1df295..9cac20de95c 100644 --- a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotObject.java +++ b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotObject.java @@ -78,6 +78,7 @@ public class SnapshotObject implements SnapshotInfo { SnapshotDataStoreDao snapshotStoreDao; @Inject StorageStrategyFactory storageStrategyFactory; + private String installPath; // temporarily set installPath before passing to resource for entries with empty installPath for object store migration case public SnapshotObject() { @@ -198,6 +199,9 @@ public class SnapshotObject implements SnapshotInfo { @Override public String getPath() { + if (installPath != null) + return installPath; + DataObjectInStore objectInStore = objectInStoreMgr.findObject(this, getDataStore()); if (objectInStore != null) { return objectInStore.getInstallPath(); @@ -205,6 +209,10 @@ public class SnapshotObject implements SnapshotInfo { return null; } + public void setPath(String installPath) { + this.installPath = installPath; + } + @Override public String getName() { return snapshot.getName(); @@ -278,6 +286,7 @@ public class SnapshotObject implements SnapshotInfo { } else if (answer instanceof CopyCmdAnswer) { SnapshotObjectTO snapshotTO = (SnapshotObjectTO)((CopyCmdAnswer)answer).getNewData(); snapshotStore.setInstallPath(snapshotTO.getPath()); + snapshotStore.setSize(snapshotTO.getPhysicalSize()); if (snapshotTO.getParentSnapshotPath() == null) { snapshotStore.setParentSnapshotId(0L); } @@ -353,12 +362,12 @@ public class SnapshotObject implements SnapshotInfo { @Override public void addPayload(Object data) { - this.payload = data; + payload = data; } @Override public Object getPayload() { - return this.payload; + return payload; } @Override diff --git a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotServiceImpl.java b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotServiceImpl.java index 9940249f486..d482e70b464 100644 --- a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotServiceImpl.java +++ b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotServiceImpl.java @@ -17,6 +17,7 @@ package org.apache.cloudstack.storage.snapshot; +import java.util.List; import java.util.concurrent.ExecutionException; import javax.inject.Inject; @@ -37,6 +38,7 @@ import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotDataFactory; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotResult; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotService; +import org.apache.cloudstack.engine.subsystem.api.storage.StorageCacheManager; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; import org.apache.cloudstack.framework.async.AsyncCallFuture; import org.apache.cloudstack.framework.async.AsyncCallbackDispatcher; @@ -49,6 +51,9 @@ import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO; import com.cloud.storage.DataStoreRole; import com.cloud.storage.Snapshot; +import com.cloud.storage.SnapshotVO; +import com.cloud.storage.dao.SnapshotDao; +import com.cloud.storage.template.TemplateConstants; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.fsm.NoTransitionException; @@ -56,13 +61,17 @@ import com.cloud.utils.fsm.NoTransitionException; public class SnapshotServiceImpl implements SnapshotService { private static final Logger s_logger = Logger.getLogger(SnapshotServiceImpl.class); @Inject + protected SnapshotDao _snapshotDao; + @Inject protected SnapshotDataStoreDao _snapshotStoreDao; @Inject - SnapshotDataFactory snapshotfactory; + SnapshotDataFactory _snapshotFactory; @Inject DataStoreManager dataStoreMgr; @Inject DataMotionService motionSrv; + @Inject + StorageCacheManager _cacheMgr; static private class CreateSnapshotContext extends AsyncRpcContext { final SnapshotInfo snapshot; @@ -216,7 +225,12 @@ public class SnapshotServiceImpl implements SnapshotService { // the same store as its parent since // we are taking delta snapshot private DataStore findSnapshotImageStore(SnapshotInfo snapshot) { - if (snapshot.getParent() == null) { + Boolean fullSnapshot = true; + Object payload = snapshot.getPayload(); + if (payload != null) { + fullSnapshot = (Boolean)payload; + } + if (fullSnapshot) { return dataStoreMgr.getImageStore(snapshot.getDataCenterId()); } else { SnapshotInfo parentSnapshot = snapshot.getParent(); @@ -239,7 +253,7 @@ public class SnapshotServiceImpl implements SnapshotService { try { snapObj.processEvent(Snapshot.Event.BackupToSecondary); - DataStore imageStore = this.findSnapshotImageStore(snapshot); + DataStore imageStore = findSnapshotImageStore(snapshot); if (imageStore == null) { throw new CloudRuntimeException("can not find an image stores"); } @@ -250,7 +264,7 @@ public class SnapshotServiceImpl implements SnapshotService { CopySnapshotContext context = new CopySnapshotContext(null, snapshot, snapshotOnImageStore, future); AsyncCallbackDispatcher caller = AsyncCallbackDispatcher.create(this); caller.setCallback(caller.getTarget().copySnapshotAsyncCallback(null, null)).setContext(context); - this.motionSrv.copyAsync(snapshot, snapshotOnImageStore, caller); + motionSrv.copyAsync(snapshot, snapshotOnImageStore, caller); } catch (Exception e) { s_logger.debug("Failed to copy snapshot", e); result.setResult("Failed to copy snapshot:" + e.toString()); @@ -301,7 +315,7 @@ public class SnapshotServiceImpl implements SnapshotService { CopyCmdAnswer answer = (CopyCmdAnswer)result.getAnswer(); destSnapshot.processEvent(Event.OperationSuccessed, result.getAnswer()); srcSnapshot.processEvent(Snapshot.Event.OperationSucceeded); - snapResult = new SnapshotResult(this.snapshotfactory.getSnapshot(destSnapshot.getId(), destSnapshot.getDataStore()), answer); + snapResult = new SnapshotResult(_snapshotFactory.getSnapshot(destSnapshot.getId(), destSnapshot.getDataStore()), answer); future.complete(snapResult); } catch (Exception e) { s_logger.debug("Failed to update snapshot state", e); @@ -386,7 +400,7 @@ public class SnapshotServiceImpl implements SnapshotService { @Override public boolean revertSnapshot(Long snapshotId) { - SnapshotInfo snapshot = snapshotfactory.getSnapshot(snapshotId, DataStoreRole.Primary); + SnapshotInfo snapshot = _snapshotFactory.getSnapshot(snapshotId, DataStoreRole.Primary); PrimaryDataStore store = (PrimaryDataStore)snapshot.getDataStore(); AsyncCallFuture future = new AsyncCallFuture(); @@ -412,4 +426,92 @@ public class SnapshotServiceImpl implements SnapshotService { return false; } + // This routine is used to push snapshots currently on cache store, but not in region store to region store. + // used in migrating existing NFS secondary storage to S3. We chose to push all volume related snapshots to handle delta snapshots smoothly. + @Override + public void syncVolumeSnapshotsToRegionStore(long volumeId, DataStore store) { + if (dataStoreMgr.isRegionStore(store)) { + // list all backed up snapshots for the given volume + List snapshots = _snapshotDao.listByStatus(volumeId, Snapshot.State.BackedUp); + if (snapshots != null) { + for (SnapshotVO snapshot : snapshots) { + syncSnapshotToRegionStore(snapshot.getId(), store); + } + } + } + } + + // push one individual snapshots currently on cache store to region store if it is not there already + private void syncSnapshotToRegionStore(long snapshotId, DataStore store) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("sync snapshot " + snapshotId + " from cache to object store..."); + } + // if snapshot is already on region wide object store, check if it is really downloaded there (by checking install_path). Sync snapshot to region + // wide store if it is not there physically. + SnapshotInfo snapOnStore = _snapshotFactory.getSnapshot(snapshotId, store); + if (snapOnStore == null) { + throw new CloudRuntimeException("Cannot find an entry in snapshot_store_ref for snapshot " + snapshotId + " on region store: " + store.getName()); + } + if (snapOnStore.getPath() == null || snapOnStore.getPath().length() == 0) { + // snapshot is not on region store yet, sync to region store + SnapshotInfo srcSnapshot = _snapshotFactory.getReadySnapshotOnCache(snapshotId); + if (srcSnapshot == null) { + throw new CloudRuntimeException("Cannot find snapshot " + snapshotId + " on cache store"); + } + AsyncCallFuture future = syncToRegionStoreAsync(srcSnapshot, store); + try { + SnapshotResult result = future.get(); + if (result.isFailed()) { + throw new CloudRuntimeException("sync snapshot from cache to region wide store failed for image store " + store.getName() + ":" + + result.getResult()); + } + _cacheMgr.releaseCacheObject(srcSnapshot); // reduce reference count for template on cache, so it can recycled by schedule + } catch (Exception ex) { + throw new CloudRuntimeException("sync snapshot from cache to region wide store failed for image store " + store.getName()); + } + } + + } + + private AsyncCallFuture syncToRegionStoreAsync(SnapshotInfo snapshot, DataStore store) { + AsyncCallFuture future = new AsyncCallFuture(); + // no need to create entry on snapshot_store_ref here, since entries are already created when updateCloudToUseObjectStore is invoked. + // But we need to set default install path so that sync can be done in the right s3 path + SnapshotInfo snapshotOnStore = _snapshotFactory.getSnapshot(snapshot, store); + String installPath = TemplateConstants.DEFAULT_SNAPSHOT_ROOT_DIR + "/" + + snapshot.getAccountId() + "/" + snapshot.getVolumeId(); + ((SnapshotObject)snapshotOnStore).setPath(installPath); + CopySnapshotContext context = new CopySnapshotContext(null, snapshot, + snapshotOnStore, future); + AsyncCallbackDispatcher caller = AsyncCallbackDispatcher + .create(this); + caller.setCallback(caller.getTarget().syncSnapshotCallBack(null, null)).setContext(context); + motionSrv.copyAsync(snapshot, snapshotOnStore, caller); + return future; + } + + protected Void syncSnapshotCallBack(AsyncCallbackDispatcher callback, + CopySnapshotContext context) { + CopyCommandResult result = callback.getResult(); + SnapshotInfo destSnapshot = context.destSnapshot; + SnapshotResult res = new SnapshotResult(destSnapshot, null); + + AsyncCallFuture future = context.future; + try { + if (result.isFailed()) { + res.setResult(result.getResult()); + // no change to existing snapshot_store_ref, will try to re-sync later if other call triggers this sync operation + } else { + // this will update install path properly, next time it will not sync anymore. + destSnapshot.processEvent(Event.OperationSuccessed, result.getAnswer()); + } + future.complete(res); + } catch (Exception e) { + s_logger.debug("Failed to process sync snapshot callback", e); + res.setResult(e.toString()); + future.complete(res); + } + + return null; + } } diff --git a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotStateMachineManagerImpl.java b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotStateMachineManagerImpl.java index 555dcb8b301..a70b0789ac4 100644 --- a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotStateMachineManagerImpl.java +++ b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotStateMachineManagerImpl.java @@ -44,7 +44,7 @@ public class SnapshotStateMachineManagerImpl implements SnapshotStateMachineMana stateMachine.addTransition(Snapshot.State.CreatedOnPrimary, Event.BackupToSecondary, Snapshot.State.BackingUp); stateMachine.addTransition(State.CreatedOnPrimary, Event.OperationNotPerformed, State.BackedUp); stateMachine.addTransition(Snapshot.State.BackingUp, Event.OperationSucceeded, Snapshot.State.BackedUp); - stateMachine.addTransition(Snapshot.State.BackingUp, Event.OperationFailed, Snapshot.State.CreatedOnPrimary); + stateMachine.addTransition(Snapshot.State.BackingUp, Event.OperationFailed, Snapshot.State.Error); stateMachine.addTransition(Snapshot.State.BackedUp, Event.DestroyRequested, Snapshot.State.Destroying); stateMachine.addTransition(Snapshot.State.BackedUp, Event.CopyingRequested, Snapshot.State.Copying); stateMachine.addTransition(Snapshot.State.Copying, Event.OperationSucceeded, Snapshot.State.BackedUp); diff --git a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/XenserverSnapshotStrategy.java b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/XenserverSnapshotStrategy.java index 14fb6180861..ad7e0f3e3d8 100644 --- a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/XenserverSnapshotStrategy.java +++ b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/XenserverSnapshotStrategy.java @@ -22,7 +22,6 @@ import javax.inject.Inject; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; - import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.Event; @@ -40,6 +39,8 @@ import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO; import org.apache.cloudstack.storage.to.SnapshotObjectTO; import com.cloud.exception.InvalidParameterValueException; +import com.cloud.hypervisor.Hypervisor; +import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.storage.CreateSnapshotPayload; import com.cloud.storage.DataStoreRole; import com.cloud.storage.Snapshot; @@ -104,29 +105,31 @@ public class XenserverSnapshotStrategy extends SnapshotStrategyBase { // determine full snapshot backup or not - boolean fullBackup = false; - if (parentSnapshot != null) { - int _deltaSnapshotMax = NumbersUtil.parseInt(configDao.getValue("snapshot.delta.max"), SnapshotManager.DELTAMAX); + boolean fullBackup = true; + SnapshotDataStoreVO parentSnapshotOnBackupStore = snapshotStoreDao.findLatestSnapshotForVolume(snapshot.getVolumeId(), DataStoreRole.Image); + HypervisorType hypervisorType = snapshot.getBaseVolume().getHypervisorType(); + if (parentSnapshotOnBackupStore != null && hypervisorType == Hypervisor.HypervisorType.XenServer) { // CS does incremental backup only for XenServer + int _deltaSnapshotMax = NumbersUtil.parseInt(configDao.getValue("snapshot.delta.max"), + SnapshotManager.DELTAMAX); int deltaSnap = _deltaSnapshotMax; - int i; - SnapshotDataStoreVO parentSnapshotOnBackupStore = null; - for (i = 1; i < deltaSnap; i++) { - parentSnapshotOnBackupStore = snapshotStoreDao.findBySnapshot(parentSnapshot.getId(), DataStoreRole.Image); - if (parentSnapshotOnBackupStore == null) { - break; - } - Long prevBackupId = parentSnapshotOnBackupStore.getParentSnapshotId(); + for (i = 1; i < deltaSnap; i++) { + Long prevBackupId = parentSnapshotOnBackupStore.getParentSnapshotId(); if (prevBackupId == 0) { break; } - parentSnapshotOnBackupStore = snapshotStoreDao.findBySnapshot(prevBackupId, DataStoreRole.Image); + if (parentSnapshotOnBackupStore == null) { + break; + } } + if (i >= deltaSnap) { fullBackup = true; + } else { + fullBackup = false; } } diff --git a/engine/storage/snapshot/src/org/apache/cloudstack/storage/vmsnapshot/DefaultVMSnapshotStrategy.java b/engine/storage/snapshot/src/org/apache/cloudstack/storage/vmsnapshot/DefaultVMSnapshotStrategy.java index 42bef7eb866..e86bd23b050 100644 --- a/engine/storage/snapshot/src/org/apache/cloudstack/storage/vmsnapshot/DefaultVMSnapshotStrategy.java +++ b/engine/storage/snapshot/src/org/apache/cloudstack/storage/vmsnapshot/DefaultVMSnapshotStrategy.java @@ -236,9 +236,9 @@ public class DefaultVMSnapshotStrategy extends ManagerBase implements VMSnapshot } } - protected void finalizeDelete(VMSnapshotVO vmSnapshot, List VolumeTOs) { + protected void finalizeDelete(VMSnapshotVO vmSnapshot, List volumeTOs) { // update volumes path - updateVolumePath(VolumeTOs); + updateVolumePath(volumeTOs); // update children's parent snapshots List children = vmSnapshotDao.listByParent(vmSnapshot.getId()); @@ -258,9 +258,9 @@ public class DefaultVMSnapshotStrategy extends ManagerBase implements VMSnapshot vmSnapshotDao.persist(vmSnapshot); } - protected void finalizeCreate(VMSnapshotVO vmSnapshot, List VolumeTOs) { + protected void finalizeCreate(VMSnapshotVO vmSnapshot, List volumeTOs) { // update volumes path - updateVolumePath(VolumeTOs); + updateVolumePath(volumeTOs); vmSnapshot.setCurrent(true); diff --git a/engine/storage/src/org/apache/cloudstack/storage/RemoteHostEndPoint.java b/engine/storage/src/org/apache/cloudstack/storage/RemoteHostEndPoint.java index 98c9db17fff..34f9c9d9068 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/RemoteHostEndPoint.java +++ b/engine/storage/src/org/apache/cloudstack/storage/RemoteHostEndPoint.java @@ -25,7 +25,8 @@ import java.util.concurrent.TimeUnit; import javax.inject.Inject; import org.apache.log4j.Logger; - +import com.cloud.vm.SecondaryStorageVmVO; +import com.cloud.vm.dao.SecondaryStorageVmDao; import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint; import org.apache.cloudstack.framework.async.AsyncCompletionCallback; import org.apache.cloudstack.managed.context.ManagedContextRunnable; @@ -57,21 +58,30 @@ public class RemoteHostEndPoint implements EndPoint { AgentManager agentMgr; @Inject protected HypervisorGuruManager _hvGuruMgr; + @Inject + protected SecondaryStorageVmDao vmDao; private ScheduledExecutorService executor; public RemoteHostEndPoint() { executor = Executors.newScheduledThreadPool(10, new NamedThreadFactory("RemoteHostEndPoint")); } - private void configure(long hostId, String hostAddress, String publicAddress) { - this.hostId = hostId; - this.hostAddress = hostAddress; - this.publicAddress = publicAddress; + private void configure(Host host) { + this.hostId = host.getId(); + this.hostAddress = host.getPrivateIpAddress(); + this.publicAddress = host.getPublicIpAddress(); + if (Host.Type.SecondaryStorageVM == host.getType()) { + String vmName = host.getName(); + SecondaryStorageVmVO ssvm = vmDao.findByInstanceName(vmName); + if (ssvm != null) { + this.publicAddress = ssvm.getPublicIpAddress(); + } + } } - public static RemoteHostEndPoint getHypervisorHostEndPoint(long hostId, String hostAddress, String publicAddress) { + public static RemoteHostEndPoint getHypervisorHostEndPoint(Host host) { RemoteHostEndPoint ep = ComponentContext.inject(RemoteHostEndPoint.class); - ep.configure(hostId, hostAddress, publicAddress); + ep.configure(host); return ep; } diff --git a/engine/storage/src/org/apache/cloudstack/storage/allocator/ClusterScopeStoragePoolAllocator.java b/engine/storage/src/org/apache/cloudstack/storage/allocator/ClusterScopeStoragePoolAllocator.java index 35737ede5e1..af228107811 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/allocator/ClusterScopeStoragePoolAllocator.java +++ b/engine/storage/src/org/apache/cloudstack/storage/allocator/ClusterScopeStoragePoolAllocator.java @@ -77,14 +77,22 @@ public class ClusterScopeStoragePoolAllocator extends AbstractStoragePoolAllocat } List pools = _storagePoolDao.findPoolsByTags(dcId, podId, clusterId, dskCh.getTags()); + s_logger.debug("Found pools matching tags: " + pools); // add remaining pools in cluster, that did not match tags, to avoid set List allPools = _storagePoolDao.findPoolsByTags(dcId, podId, clusterId, null); allPools.removeAll(pools); for (StoragePoolVO pool : allPools) { + s_logger.debug("Adding pool " + pool + " to avoid set since it did not match tags"); avoid.addPool(pool.getId()); } + // make sure our matching pool was not in avoid set + for (StoragePoolVO pool : pools) { + s_logger.debug("Removing pool " + pool + " from avoid set, must have been inserted when searching for another disk's tag"); + avoid.removePool(pool.getId()); + } + if (pools.size() == 0) { if (s_logger.isDebugEnabled()) { s_logger.debug("No storage pools available for " + ServiceOffering.StorageType.shared.toString() + " volume allocation, returning"); diff --git a/engine/storage/src/org/apache/cloudstack/storage/allocator/ZoneWideStoragePoolAllocator.java b/engine/storage/src/org/apache/cloudstack/storage/allocator/ZoneWideStoragePoolAllocator.java index 57253a787a3..8fb9c8d87ac 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/allocator/ZoneWideStoragePoolAllocator.java +++ b/engine/storage/src/org/apache/cloudstack/storage/allocator/ZoneWideStoragePoolAllocator.java @@ -89,6 +89,12 @@ public class ZoneWideStoragePoolAllocator extends AbstractStoragePoolAllocator { avoid.addPool(pool.getId()); } + // make sure our matching pool was not in avoid set + for (StoragePoolVO pool : storagePoolsByHypervisor) { + s_logger.debug("Removing pool " + pool + " from avoid set, must have been inserted when searching for another disk's tag"); + avoid.removePool(pool.getId()); + } + for (StoragePoolVO storage : storagePools) { if (suitablePools.size() == returnUpTo) { break; diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/DataStoreManagerImpl.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/DataStoreManagerImpl.java index e6b27152048..d44fb42045c 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/DataStoreManagerImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/DataStoreManagerImpl.java @@ -32,6 +32,7 @@ import org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope; import org.apache.cloudstack.storage.image.datastore.ImageStoreProviderManager; import com.cloud.storage.DataStoreRole; +import com.cloud.storage.ScopeType; import com.cloud.utils.exception.CloudRuntimeException; @Component @@ -82,6 +83,14 @@ public class DataStoreManagerImpl implements DataStoreManager { return stores.get(0); } + @Override + public boolean isRegionStore(DataStore store) { + if (store.getScope().getScopeType() == ScopeType.ZONE && store.getScope().getScopeId() == null) + return true; + else + return false; + } + @Override public DataStore getPrimaryDataStore(long storeId) { return primaryStoreMgr.getPrimaryDataStore(storeId); diff --git a/engine/storage/src/org/apache/cloudstack/storage/datastore/ObjectInDataStoreManagerImpl.java b/engine/storage/src/org/apache/cloudstack/storage/datastore/ObjectInDataStoreManagerImpl.java index 2eafacc2ae6..82164ee06d8 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/datastore/ObjectInDataStoreManagerImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/datastore/ObjectInDataStoreManagerImpl.java @@ -115,6 +115,7 @@ public class ObjectInDataStoreManagerImpl implements ObjectInDataStoreManager { ss.setDataStoreId(dataStore.getId()); ss.setRole(dataStore.getRole()); ss.setVolumeId(snapshotInfo.getVolumeId()); + ss.setSize(snapshotInfo.getSize()); // this is the virtual size of snapshot in primary storage. SnapshotDataStoreVO snapshotDataStoreVO = snapshotDataStoreDao.findParent(dataStore.getRole(), dataStore.getId(), snapshotInfo.getVolumeId()); if (snapshotDataStoreVO != null) { ss.setParentSnapshotId(snapshotDataStoreVO.getSnapshotId()); diff --git a/engine/storage/src/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java b/engine/storage/src/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java index df1c9ee0c67..51c04bf2fc2 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java +++ b/engine/storage/src/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java @@ -35,7 +35,10 @@ import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint; import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector; import org.apache.cloudstack.engine.subsystem.api.storage.Scope; +import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; +import org.apache.cloudstack.engine.subsystem.api.storage.StorageAction; import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo; +import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; import org.apache.cloudstack.storage.LocalHostEndpoint; import org.apache.cloudstack.storage.RemoteHostEndPoint; @@ -43,6 +46,7 @@ import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.Status; import com.cloud.host.dao.HostDao; +import com.cloud.hypervisor.Hypervisor; import com.cloud.storage.DataStoreRole; import com.cloud.storage.ScopeType; import com.cloud.storage.Storage.TemplateType; @@ -51,6 +55,7 @@ import com.cloud.utils.db.QueryBuilder; import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.TransactionLegacy; import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.vm.VirtualMachine; @Component public class DefaultEndPointSelector implements EndPointSelector { @@ -60,6 +65,7 @@ public class DefaultEndPointSelector implements EndPointSelector { private final String findOneHostOnPrimaryStorage = "select h.id from host h, storage_pool_host_ref s where h.status = 'Up' and h.type = 'Routing' and h.resource_state = 'Enabled' and" + " h.id = s.host_id and s.pool_id = ? "; + private String findOneHypervisorHostInScope = "select h.id from host h where h.status = 'Up' and h.hypervisor_type is not null "; protected boolean moveBetweenPrimaryImage(DataStore srcStore, DataStore destStore) { DataStoreRole srcRole = srcStore.getRole(); @@ -140,7 +146,7 @@ public class DefaultEndPointSelector implements EndPointSelector { return null; } - return RemoteHostEndPoint.getHypervisorHostEndPoint(host.getId(), host.getPrivateIpAddress(), host.getPublicIpAddress()); + return RemoteHostEndPoint.getHypervisorHostEndPoint(host); } protected EndPoint findEndPointForImageMove(DataStore srcStore, DataStore destStore) { @@ -204,6 +210,21 @@ public class DefaultEndPointSelector implements EndPointSelector { return null; } + @Override + public EndPoint select(DataObject srcData, DataObject destData, StorageAction action) { + if (action == StorageAction.BACKUPSNAPSHOT && srcData.getDataStore().getRole() == DataStoreRole.Primary) { + SnapshotInfo srcSnapshot = (SnapshotInfo)srcData; + if (srcSnapshot.getHypervisorType() == Hypervisor.HypervisorType.KVM) { + VolumeInfo volumeInfo = srcSnapshot.getBaseVolume(); + VirtualMachine vm = volumeInfo.getAttachedVM(); + if (vm != null && vm.getState() == VirtualMachine.State.Running) { + return getEndPointFromHostId(vm.getHostId()); + } + } + } + return select(srcData, destData); + } + protected EndPoint findEndpointForPrimaryStorage(DataStore store) { return findEndPointInScope(store.getScope(), findOneHostOnPrimaryStorage, store.getId()); } @@ -223,7 +244,7 @@ public class DefaultEndPointSelector implements EndPointSelector { } Collections.shuffle(ssAHosts); HostVO host = ssAHosts.get(0); - return RemoteHostEndPoint.getHypervisorHostEndPoint(host.getId(), host.getPrivateIpAddress(), host.getPublicIpAddress()); + return RemoteHostEndPoint.getHypervisorHostEndPoint(host); } private List listUpAndConnectingSecondaryStorageVmHost(Long dcId) { @@ -266,6 +287,27 @@ public class DefaultEndPointSelector implements EndPointSelector { } } + private EndPoint getEndPointFromHostId(Long hostId) { + HostVO host = hostDao.findById(hostId); + return RemoteHostEndPoint.getHypervisorHostEndPoint(host); + } + + @Override + public EndPoint select(DataObject object, StorageAction action) { + if (action == StorageAction.TAKESNAPSHOT) { + SnapshotInfo snapshotInfo = (SnapshotInfo)object; + if (snapshotInfo.getHypervisorType() == Hypervisor.HypervisorType.KVM) { + VolumeInfo volumeInfo = snapshotInfo.getBaseVolume(); + VirtualMachine vm = volumeInfo.getAttachedVM(); + if ((vm != null) && (vm.getState() == VirtualMachine.State.Running)) { + Long hostId = vm.getHostId(); + return getEndPointFromHostId(hostId); + } + } + } + return select(object); + } + @Override public EndPoint select(Scope scope, Long storeId) { return findEndPointInScope(scope, findOneHostOnPrimaryStorage, storeId); @@ -276,14 +318,15 @@ public class DefaultEndPointSelector implements EndPointSelector { List endPoints = new ArrayList(); if (store.getScope().getScopeType() == ScopeType.HOST) { HostVO host = hostDao.findById(store.getScope().getScopeId()); - endPoints.add(RemoteHostEndPoint.getHypervisorHostEndPoint(host.getId(), host.getPrivateIpAddress(), host.getPublicIpAddress())); + + endPoints.add(RemoteHostEndPoint.getHypervisorHostEndPoint(host)); } else if (store.getScope().getScopeType() == ScopeType.CLUSTER) { QueryBuilder sc = QueryBuilder.create(HostVO.class); sc.and(sc.entity().getClusterId(), Op.EQ, store.getScope().getScopeId()); sc.and(sc.entity().getStatus(), Op.EQ, Status.Up); List hosts = sc.list(); for (HostVO host : hosts) { - endPoints.add(RemoteHostEndPoint.getHypervisorHostEndPoint(host.getId(), host.getPrivateIpAddress(), host.getPublicIpAddress())); + endPoints.add(RemoteHostEndPoint.getHypervisorHostEndPoint(host)); } } else { @@ -291,4 +334,51 @@ public class DefaultEndPointSelector implements EndPointSelector { } return endPoints; } + + @Override + public EndPoint selectHypervisorHost(Scope scope) { + StringBuilder sbuilder = new StringBuilder(); + sbuilder.append(findOneHypervisorHostInScope); + if (scope.getScopeType() == ScopeType.ZONE) { + sbuilder.append(" and h.data_center_id = "); + sbuilder.append(scope.getScopeId()); + } else if (scope.getScopeType() == ScopeType.CLUSTER) { + sbuilder.append(" and h.cluster_id = "); + sbuilder.append(scope.getScopeId()); + } + sbuilder.append(" ORDER by rand() limit 1"); + + String sql = sbuilder.toString(); + PreparedStatement pstmt = null; + ResultSet rs = null; + HostVO host = null; + TransactionLegacy txn = TransactionLegacy.currentTxn(); + + try { + pstmt = txn.prepareStatement(sql); + rs = pstmt.executeQuery(); + while (rs.next()) { + long id = rs.getLong(1); + host = hostDao.findById(id); + } + } catch (SQLException e) { + s_logger.warn("can't find endpoint", e); + } finally { + try { + if (rs != null) { + rs.close(); + } + if (pstmt != null) { + pstmt.close(); + } + } catch (SQLException e) { + } + } + + if (host == null) { + return null; + } + + return RemoteHostEndPoint.getHypervisorHostEndPoint(host); + } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/helper/HypervisorHelperImpl.java b/engine/storage/src/org/apache/cloudstack/storage/helper/HypervisorHelperImpl.java index 3836c2c3d49..b41c1fa14ac 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/helper/HypervisorHelperImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/helper/HypervisorHelperImpl.java @@ -111,7 +111,8 @@ public class HypervisorHelperImpl implements HypervisorHelper { String value = configurationDao.getValue("vmsnapshot.create.wait"); int wait = NumbersUtil.parseInt(value, 1800); Long hostId = vmSnapshotHelper.pickRunningHost(virtualMachine.getId()); - VMSnapshotTO vmSnapshotTO = new VMSnapshotTO(1L, UUID.randomUUID().toString(), VMSnapshot.Type.DiskAndMemory, null, null, false, null, true); + VMSnapshotTO vmSnapshotTO = new VMSnapshotTO(1L, UUID.randomUUID().toString(), VMSnapshot.Type.Disk, null, null, false, + null, true); GuestOSVO guestOS = guestOSDao.findById(virtualMachine.getGuestOSId()); List volumeTOs = vmSnapshotHelper.getVolumeTOList(virtualMachine.getId()); CreateVMSnapshotCommand ccmd = diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/datastore/ImageStoreHelper.java b/engine/storage/src/org/apache/cloudstack/storage/image/datastore/ImageStoreHelper.java index bf5d646ef02..a4c423c861b 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/datastore/ImageStoreHelper.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/datastore/ImageStoreHelper.java @@ -26,6 +26,7 @@ import javax.inject.Inject; import org.springframework.stereotype.Component; +import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; import org.apache.cloudstack.storage.datastore.db.ImageStoreDao; import org.apache.cloudstack.storage.datastore.db.ImageStoreDetailVO; @@ -35,6 +36,7 @@ import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao; import com.cloud.storage.DataStoreRole; import com.cloud.storage.ScopeType; +import com.cloud.utils.crypt.DBEncryptionUtil; import com.cloud.utils.exception.CloudRuntimeException; @Component @@ -104,7 +106,12 @@ public class ImageStoreHelper { ImageStoreDetailVO detail = new ImageStoreDetailVO(); detail.setStoreId(store.getId()); detail.setName(key); - detail.setValue(details.get(key)); + String value = details.get(key); + // encrypt swift key or s3 secret key + if (key.equals(ApiConstants.KEY) || key.equals(ApiConstants.S3_SECRET_KEY)) { + value = DBEncryptionUtil.encrypt(value); + } + detail.setValue(value); imageStoreDetailsDao.persist(detail); } } diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageStoreDetailsDaoImpl.java b/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageStoreDetailsDaoImpl.java index 659a14894c6..56feb26e6bc 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageStoreDetailsDaoImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/db/ImageStoreDetailsDaoImpl.java @@ -24,9 +24,11 @@ import javax.ejb.Local; import org.springframework.stereotype.Component; +import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.storage.datastore.db.ImageStoreDetailVO; import org.apache.cloudstack.storage.datastore.db.ImageStoreDetailsDao; +import com.cloud.utils.crypt.DBEncryptionUtil; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; @@ -68,7 +70,12 @@ public class ImageStoreDetailsDaoImpl extends GenericDaoBase details = listBy(sc); Map detailsMap = new HashMap(); for (ImageStoreDetailVO detail : details) { - detailsMap.put(detail.getName(), detail.getValue()); + String name = detail.getName(); + String value = detail.getValue(); + if (name.equals(ApiConstants.KEY) || name.equals(ApiConstants.S3_SECRET_KEY)) { + value = DBEncryptionUtil.decrypt(value); + } + detailsMap.put(name, value); } return detailsMap; diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/db/SnapshotDataStoreDaoImpl.java b/engine/storage/src/org/apache/cloudstack/storage/image/db/SnapshotDataStoreDaoImpl.java index e40cfd00b62..28d65981065 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/db/SnapshotDataStoreDaoImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/db/SnapshotDataStoreDaoImpl.java @@ -54,8 +54,13 @@ public class SnapshotDataStoreDaoImpl extends GenericDaoBase snapshotSearch; private SearchBuilder storeSnapshotSearch; private SearchBuilder snapshotIdSearch; + private final String parentSearch = "select store_id, store_role, snapshot_id from cloud.snapshot_store_ref where store_id = ? " + " and store_role = ? and volume_id = ? and state = 'Ready'" + " order by created DESC " + " limit 1"; + private final String findLatestSnapshot = "select store_id, store_role, snapshot_id from cloud.snapshot_store_ref where " + + " store_role = ? and volume_id = ? and state = 'Ready'" + + " order by created DESC " + + " limit 1"; @Override public boolean configure(String name, Map params) throws ConfigurationException { @@ -98,6 +103,7 @@ public class SnapshotDataStoreDaoImpl extends GenericDaoBase sc = storeSnapshotSearch.create(); + sc.setParameters("snapshot_id", snapshotId); + sc.setParameters("store_role", DataStoreRole.ImageCache); + sc.setParameters("state", ObjectInDataStoreStateMachine.State.Ready); + return findOneIncludingRemovedBy(sc); + } + @Override public List listOnCache(long snapshotId) { SearchCriteria sc = storeSnapshotSearch.create(); diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/db/TemplateDataStoreDaoImpl.java b/engine/storage/src/org/apache/cloudstack/storage/image/db/TemplateDataStoreDaoImpl.java index ec770feea82..d4b0445be7e 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/image/db/TemplateDataStoreDaoImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/image/db/TemplateDataStoreDaoImpl.java @@ -301,6 +301,23 @@ public class TemplateDataStoreDaoImpl extends GenericDaoBase cacheStores = _storeMgr.getImageCacheStores(new ZoneScope(zoneId)); + if (cacheStores != null) { + for (DataStore store : cacheStores) { + List sRes = listByTemplateStoreDownloadStatus(templateId, store.getId(), + status); + if (sRes != null && sRes.size() > 0) { + Collections.shuffle(sRes); + return sRes.get(0); + } + } + } + return null; + } + @Override public TemplateDataStoreVO findByStoreTemplate(long storeId, long templateId) { SearchCriteria sc = storeTemplateSearch.create(); @@ -333,15 +350,20 @@ public class TemplateDataStoreDaoImpl extends GenericDaoBase sc = templateRoleSearch.create(); sc.setParameters("template_id", templateId); - sc.setParameters("store_role", DataStoreRole.ImageCache); + sc.setParameters("store_role", role); sc.setParameters("destroyed", false); sc.setParameters("state", ObjectInDataStoreStateMachine.State.Ready); return findOneIncludingRemovedBy(sc); } + @Override + public TemplateDataStoreVO findReadyOnCache(long templateId) { + return findReadyByTemplate(templateId, DataStoreRole.ImageCache); + } + @Override public List listOnCache(long templateId) { SearchCriteria sc = templateRoleSearch.create(); diff --git a/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeObject.java b/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeObject.java index 3b5d938f8a6..fd0f2c1e19d 100644 --- a/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeObject.java +++ b/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeObject.java @@ -22,6 +22,9 @@ import javax.inject.Inject; import org.apache.log4j.Logger; +import com.cloud.storage.DiskOfferingVO; +import com.cloud.storage.dao.DiskOfferingDao; +import com.cloud.vm.VirtualMachine; import org.apache.cloudstack.engine.subsystem.api.storage.DataObjectInStore; import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine; @@ -40,11 +43,9 @@ import com.cloud.agent.api.to.DataTO; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.offering.DiskOffering.DiskCacheMode; import com.cloud.storage.DataStoreRole; -import com.cloud.storage.DiskOfferingVO; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.Volume; import com.cloud.storage.VolumeVO; -import com.cloud.storage.dao.DiskOfferingDao; import com.cloud.storage.dao.VolumeDao; import com.cloud.utils.component.ComponentContext; import com.cloud.utils.exception.CloudRuntimeException; @@ -100,6 +101,15 @@ public class VolumeObject implements VolumeInfo { return null; } + @Override + public VirtualMachine getAttachedVM() { + Long vmId = this.volumeVO.getInstanceId(); + if (vmId != null) { + VMInstanceVO vm = vmInstanceDao.findById(vmId); + return vm; + } + return null; + } @Override public String getUuid() { return volumeVO.getUuid(); @@ -143,7 +153,6 @@ public class VolumeObject implements VolumeInfo { return volumeVO.getMaxIops(); } - @Override public void setHypervisorSnapshotReserve(Integer hypervisorSnapshotReserve) { volumeVO.setHypervisorSnapshotReserve(hypervisorSnapshotReserve); } diff --git a/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java b/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java index 9f71abd7003..3e5a5466fd0 100644 --- a/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java +++ b/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java @@ -25,6 +25,9 @@ import java.util.Map; import javax.inject.Inject; +import org.apache.log4j.Logger; +import org.springframework.stereotype.Component; + import org.apache.cloudstack.engine.cloud.entity.api.VolumeEntity; import org.apache.cloudstack.engine.subsystem.api.storage.ChapInfo; import org.apache.cloudstack.engine.subsystem.api.storage.CopyCommandResult; @@ -57,8 +60,6 @@ import org.apache.cloudstack.storage.datastore.PrimaryDataStoreProviderManager; import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreDao; import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreVO; import org.apache.cloudstack.storage.to.VolumeObjectTO; -import org.apache.log4j.Logger; -import org.springframework.stereotype.Component; import com.cloud.agent.api.Answer; import com.cloud.agent.api.storage.ListVolumeAnswer; @@ -157,6 +158,26 @@ public class VolumeServiceImpl implements VolumeService { return null; } + @Override + public boolean connectVolumeToHost(VolumeInfo volumeInfo, Host host, DataStore dataStore) { + DataStoreDriver dataStoreDriver = dataStore != null ? dataStore.getDriver() : null; + + if (dataStoreDriver instanceof PrimaryDataStoreDriver) { + return ((PrimaryDataStoreDriver)dataStoreDriver).connectVolumeToHost(volumeInfo, host, dataStore); + } + + return false; + } + + @Override + public void disconnectVolumeFromHost(VolumeInfo volumeInfo, Host host, DataStore dataStore) { + DataStoreDriver dataStoreDriver = dataStore != null ? dataStore.getDriver() : null; + + if (dataStoreDriver instanceof PrimaryDataStoreDriver) { + ((PrimaryDataStoreDriver)dataStoreDriver).disconnectVolumeFromHost(volumeInfo, host, dataStore); + } + } + @Override public AsyncCallFuture createVolumeAsync(VolumeInfo volume, DataStore dataStore) { AsyncCallFuture future = new AsyncCallFuture(); @@ -1203,7 +1224,8 @@ public class VolumeServiceImpl implements VolumeService { com.cloud.configuration.Resource.ResourceType.secondary_storage, volInfo.getSize() - volInfo.getPhysicalSize()); } catch (ResourceAllocationException e) { s_logger.warn(e.getMessage()); - _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_RESOURCE_LIMIT_EXCEEDED, volume.getDataCenterId(), volume.getPodId(), e.getMessage(), + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_RESOURCE_LIMIT_EXCEEDED, volume.getDataCenterId(), volume.getPodId(), + e.getMessage(), e.getMessage()); } finally { _resourceLimitMgr.recalculateResourceCount(volume.getAccountId(), volume.getDomainId(), @@ -1228,6 +1250,17 @@ public class VolumeServiceImpl implements VolumeService { s_logger.info("Skip downloading volume " + volumeHost.getVolumeId() + " since no download url is specified."); continue; } + + // if this is a region store, and there is already an DOWNLOADED entry there without install_path information, which + // means that this is a duplicate entry from migration of previous NFS to staging. + if (store.getScope().getScopeType() == ScopeType.REGION) { + if (volumeHost.getDownloadState() == VMTemplateStorageResourceAssoc.Status.DOWNLOADED + && volumeHost.getInstallPath() == null) { + s_logger.info("Skip sync volume for migration of previous NFS to object store"); + continue; + } + } + s_logger.debug("Volume " + volumeHost.getVolumeId() + " needs to be downloaded to " + store.getName()); // TODO: pass a callback later VolumeInfo vol = volFactory.getVolume(volumeHost.getVolumeId()); diff --git a/framework/cluster/src/com/cloud/cluster/ClusterManager.java b/framework/cluster/src/com/cloud/cluster/ClusterManager.java index f59e63cc52c..ffdf3663f7b 100644 --- a/framework/cluster/src/com/cloud/cluster/ClusterManager.java +++ b/framework/cluster/src/com/cloud/cluster/ClusterManager.java @@ -26,7 +26,6 @@ public interface ClusterManager extends Manager { "Interval to check for the heart beat between management server nodes", false); final ConfigKey HeartbeatThreshold = new ConfigKey(Integer.class, "cluster.heartbeat.threshold", "management-server", "150000", "Threshold before self-fence the management server", true); - final ConfigKey ManagementHostIPAdr = new ConfigKey("Advanced", String.class, "host", "localhost", "The ip address of management server", true); void OnReceiveClusterServicePdu(ClusterServicePdu pdu); diff --git a/framework/cluster/src/com/cloud/cluster/ClusterManagerImpl.java b/framework/cluster/src/com/cloud/cluster/ClusterManagerImpl.java index 1058da3fedd..622aa62f073 100644 --- a/framework/cluster/src/com/cloud/cluster/ClusterManagerImpl.java +++ b/framework/cluster/src/com/cloud/cluster/ClusterManagerImpl.java @@ -23,6 +23,7 @@ import java.nio.channels.SocketChannel; import java.rmi.RemoteException; import java.sql.Connection; import java.sql.SQLException; +import java.sql.SQLNonTransientException; import java.sql.SQLRecoverableException; import java.util.ArrayList; import java.util.Date; @@ -255,15 +256,15 @@ public class ClusterManagerImpl extends ManagerBase implements ClusterManager, C try { if (s_logger.isDebugEnabled()) { s_logger.debug("Cluster PDU " + getSelfPeerName() + " -> " + pdu.getDestPeer() + ". agent: " + pdu.getAgentId() + ", pdu seq: " + - pdu.getSequenceId() + ", pdu ack seq: " + pdu.getAckSequenceId() + ", json: " + pdu.getJsonPackage()); + pdu.getSequenceId() + ", pdu ack seq: " + pdu.getAckSequenceId() + ", json: " + pdu.getJsonPackage()); } long startTick = System.currentTimeMillis(); String strResult = peerService.execute(pdu); if (s_logger.isDebugEnabled()) { s_logger.debug("Cluster PDU " + getSelfPeerName() + " -> " + pdu.getDestPeer() + " completed. time: " + - (System.currentTimeMillis() - startTick) + "ms. agent: " + pdu.getAgentId() + ", pdu seq: " + pdu.getSequenceId() + - ", pdu ack seq: " + pdu.getAckSequenceId() + ", json: " + pdu.getJsonPackage()); + (System.currentTimeMillis() - startTick) + "ms. agent: " + pdu.getAgentId() + ", pdu seq: " + pdu.getSequenceId() + + ", pdu ack seq: " + pdu.getAckSequenceId() + ", json: " + pdu.getJsonPackage()); } if ("true".equals(strResult)) @@ -273,7 +274,7 @@ public class ClusterManagerImpl extends ManagerBase implements ClusterManager, C invalidatePeerService(pdu.getDestPeer()); if (s_logger.isInfoEnabled()) { s_logger.info("Exception on remote execution, peer: " + pdu.getDestPeer() + ", iteration: " + i + ", exception message :" + - e.getMessage()); + e.getMessage()); } } } @@ -563,7 +564,7 @@ public class ClusterManagerImpl extends ManagerBase implements ClusterManager, C if (profiler.getDuration() >= HeartbeatInterval.value()) { if (s_logger.isDebugEnabled()) s_logger.debug("Management server heartbeat takes too long to finish. profiler: " + profiler.toString() + ", profilerHeartbeatUpdate: " + - profilerHeartbeatUpdate.toString() + ", profilerPeerScan: " + profilerPeerScan.toString()); + profilerHeartbeatUpdate.toString() + ", profilerPeerScan: " + profilerPeerScan.toString()); } } @@ -576,21 +577,15 @@ public class ClusterManagerImpl extends ManagerBase implements ClusterManager, C } if (isRootCauseConnectionRelated(e.getCause())) { - s_logger.error("DB communication problem detected, fence it"); - queueNotification(new ClusterManagerMessage(ClusterManagerMessage.MessageType.nodeIsolated)); + invalidHeartbeatConnection(); } - - invalidHeartbeatConnection(); } catch (ActiveFencingException e) { queueNotification(new ClusterManagerMessage(ClusterManagerMessage.MessageType.nodeIsolated)); } catch (Throwable e) { s_logger.error("Unexpected exception in cluster heartbeat", e); if (isRootCauseConnectionRelated(e.getCause())) { - s_logger.error("DB communication problem detected, fence it"); - queueNotification(new ClusterManagerMessage(ClusterManagerMessage.MessageType.nodeIsolated)); + invalidHeartbeatConnection(); } - - invalidHeartbeatConnection(); } finally { txn.transitToAutoManagedConnection(TransactionLegacy.CLOUD_DB); txn.close("ClusterHeartbeat"); @@ -601,8 +596,8 @@ public class ClusterManagerImpl extends ManagerBase implements ClusterManager, C private boolean isRootCauseConnectionRelated(Throwable e) { while (e != null) { - if (e instanceof SQLRecoverableException) { - return true; + if (e instanceof SQLRecoverableException || e instanceof SQLNonTransientException) { + return true; } e = e.getCause(); @@ -625,6 +620,9 @@ public class ClusterManagerImpl extends ManagerBase implements ClusterManager, C Connection conn = TransactionLegacy.getStandaloneConnection(); if (conn != null) { _heartbeatConnection.reset(conn); + } else { + s_logger.error("DB communication problem detected, fence it"); + queueNotification(new ClusterManagerMessage(ClusterManagerMessage.MessageType.nodeIsolated)); } // The stand-alone connection does not have to be closed here because there will be another reference to it. // As a matter of fact, it will be assigned to the connection instance variable in the ConnectionConcierge class. @@ -721,7 +719,7 @@ public class ClusterManagerImpl extends ManagerBase implements ClusterManager, C } } } - break; + break; case nodeRemoved: { List l = msg.getNodes(); @@ -731,7 +729,7 @@ public class ClusterManagerImpl extends ManagerBase implements ClusterManager, C } } } - break; + break; default: break; @@ -772,7 +770,7 @@ public class ClusterManagerImpl extends ManagerBase implements ClusterManager, C s_logger.info("Found " + inactiveList.size() + " inactive management server node based on timestamp"); for (ManagementServerHostVO host : inactiveList) s_logger.info("management server node msid: " + host.getMsid() + ", name: " + host.getName() + ", service ip: " + host.getServiceIP() + - ", version: " + host.getVersion()); + ", version: " + host.getVersion()); } List downHostList = new ArrayList(); @@ -810,7 +808,7 @@ public class ClusterManagerImpl extends ManagerBase implements ClusterManager, C if (_mshostPeerDao.countStateSeenInPeers(_mshostId, _runId, ManagementServerHost.State.Down) > 0) { String msg = - "We have detected that at least one management server peer reports that this management server is down, perform active fencing to avoid split-brain situation"; + "We have detected that at least one management server peer reports that this management server is down, perform active fencing to avoid split-brain situation"; s_logger.error(msg); throw new ActiveFencingException(msg); } @@ -831,7 +829,7 @@ public class ClusterManagerImpl extends ManagerBase implements ClusterManager, C if (entry.getKey().longValue() != _mshostId.longValue()) { if (s_logger.isDebugEnabled()) { s_logger.debug("Detected management node left because of invalidated session, id:" + entry.getKey() + ", nodeIP:" + - entry.getValue().getServiceIP()); + entry.getValue().getServiceIP()); } invalidatedNodeList.add(entry.getValue()); } @@ -918,8 +916,8 @@ public class ClusterManagerImpl extends ManagerBase implements ClusterManager, C if (profiler.getDuration() >= HeartbeatInterval.value()) { if (s_logger.isDebugEnabled()) s_logger.debug("Peer scan takes too long to finish. profiler: " + profiler.toString() + ", profilerQueryActiveList: " + - profilerQueryActiveList.toString() + ", profilerSyncClusterInfo: " + profilerSyncClusterInfo.toString() + ", profilerInvalidatedNodeList: " + - profilerInvalidatedNodeList.toString() + ", profilerRemovedList: " + profilerRemovedList.toString()); + profilerQueryActiveList.toString() + ", profilerSyncClusterInfo: " + profilerSyncClusterInfo.toString() + ", profilerInvalidatedNodeList: " + + profilerInvalidatedNodeList.toString() + ", profilerRemovedList: " + profilerRemovedList.toString()); } } @@ -970,7 +968,7 @@ public class ClusterManagerImpl extends ManagerBase implements ClusterManager, C } _mshostDao.update(mshost.getId(), getCurrentRunId(), NetUtils.getHostName(), version, _clusterNodeIP, _currentServiceAdapter.getServicePort(), - DateUtil.currentGMTTime()); + DateUtil.currentGMTTime()); } return mshost; @@ -1101,7 +1099,7 @@ public class ClusterManagerImpl extends ManagerBase implements ClusterManager, C @Override public ConfigKey[] getConfigKeys() { - return new ConfigKey[] {HeartbeatInterval, HeartbeatThreshold, ManagementHostIPAdr}; + return new ConfigKey[] {HeartbeatInterval, HeartbeatThreshold}; } private boolean pingManagementNode(ManagementServerHostVO mshost) { @@ -1165,19 +1163,19 @@ public class ClusterManagerImpl extends ManagerBase implements ClusterManager, C throw new ConfigurationException(msg); } else { String msg = - "Detected another management node with localhost IP is considered as running in DB, however it is not pingable, we will continue cluster initialization with this management server node"; + "Detected another management node with localhost IP is considered as running in DB, however it is not pingable, we will continue cluster initialization with this management server node"; s_logger.info(msg); } } else { if (pingManagementNode(peer.getMsid())) { String msg = - "Detected that another management node with the same IP " + peer.getServiceIP() + + "Detected that another management node with the same IP " + peer.getServiceIP() + " is already running, please check your cluster configuration"; s_logger.error(msg); throw new ConfigurationException(msg); } else { String msg = - "Detected that another management node with the same IP " + peer.getServiceIP() + + "Detected that another management node with the same IP " + peer.getServiceIP() + " is considered as running in DB, however it is not pingable, we will continue cluster initialization with this management server node"; s_logger.info(msg); } diff --git a/framework/cluster/src/com/cloud/cluster/dao/ManagementServerHostDaoImpl.java b/framework/cluster/src/com/cloud/cluster/dao/ManagementServerHostDaoImpl.java index 2287ca7c4d0..3d0c3f56309 100644 --- a/framework/cluster/src/com/cloud/cluster/dao/ManagementServerHostDaoImpl.java +++ b/framework/cluster/src/com/cloud/cluster/dao/ManagementServerHostDaoImpl.java @@ -44,48 +44,48 @@ import com.cloud.utils.exception.CloudRuntimeException; @Local(value = {ManagementServerHostDao.class}) public class ManagementServerHostDaoImpl extends GenericDaoBase implements ManagementServerHostDao { private static final Logger s_logger = Logger.getLogger(ManagementServerHostDaoImpl.class); - + private final SearchBuilder MsIdSearch; private final SearchBuilder ActiveSearch; private final SearchBuilder InactiveSearch; private final SearchBuilder StateSearch; - @Override + @Override public void invalidateRunSession(long id, long runid) { - TransactionLegacy txn = TransactionLegacy.currentTxn(); + TransactionLegacy txn = TransactionLegacy.currentTxn(); PreparedStatement pstmt = null; try { pstmt = txn.prepareAutoCloseStatement("update mshost set runid=0, state='Down' where id=? and runid=?"); pstmt.setLong(1, id); pstmt.setLong(2, runid); - + pstmt.executeUpdate(); } catch (SQLException e) { - throw new CloudRuntimeException("DB exception on " + pstmt.toString(), e); + throw new CloudRuntimeException("DB exception on " + pstmt.toString(), e); } - } - - @Override + } + + @Override public ManagementServerHostVO findByMsid(long msid) { SearchCriteria sc = MsIdSearch.create(); sc.setParameters("msid", msid); - - List l = listIncludingRemovedBy(sc); + + List l = listIncludingRemovedBy(sc); if (l != null && l.size() > 0) { return l.get(0); } - - return null; - } - - @Override + + return null; + } + + @Override @DB - public void update(long id, long runid, String name, String version, String serviceIP, int servicePort, Date lastUpdate) { + public void update(long id, long runid, String name, String version, String serviceIP, int servicePort, Date lastUpdate) { TransactionLegacy txn = TransactionLegacy.currentTxn(); PreparedStatement pstmt = null; try { txn.start(); - + pstmt = txn.prepareAutoCloseStatement("update mshost set name=?, version=?, service_ip=?, service_port=?, last_update=?, removed=null, alert_count=0, runid=?, state=? where id=?"); pstmt.setString(1, name); @@ -96,48 +96,48 @@ public class ManagementServerHostDaoImpl extends GenericDaoBase getActiveList(Date cutTime) { - SearchCriteria sc = ActiveSearch.create(); - sc.setParameters("lastUpdateTime", cutTime); - - return listIncludingRemovedBy(sc); - } + } - @Override + @Override + public List getActiveList(Date cutTime) { + SearchCriteria sc = ActiveSearch.create(); + sc.setParameters("lastUpdateTime", cutTime); + + return listIncludingRemovedBy(sc); + } + + @Override public List getInactiveList(Date cutTime) { - SearchCriteria sc = InactiveSearch.create(); - sc.setParameters("lastUpdateTime", cutTime); - - return listIncludingRemovedBy(sc); - } - - @Override + SearchCriteria sc = InactiveSearch.create(); + sc.setParameters("lastUpdateTime", cutTime); + + return listIncludingRemovedBy(sc); + } + + @Override @DB - public int increaseAlertCount(long id) { + public int increaseAlertCount(long id) { TransactionLegacy txn = TransactionLegacy.currentTxn(); PreparedStatement pstmt = null; int changedRows = 0; try { txn.start(); - + pstmt = txn.prepareAutoCloseStatement("update mshost set alert_count=alert_count+1 where id=? and alert_count=0"); pstmt.setLong(1, id); - + changedRows = pstmt.executeUpdate(); txn.commit(); } catch (Exception e) { s_logger.warn("Unexpected exception, ", e); throw new RuntimeException(e.getMessage(), e); } - - return changedRows; - } - - protected ManagementServerHostDaoImpl() { - MsIdSearch = createSearchBuilder(); - MsIdSearch.and("msid", MsIdSearch.entity().getMsid(), SearchCriteria.Op.EQ); - MsIdSearch.done(); - - ActiveSearch = createSearchBuilder(); - ActiveSearch.and("lastUpdateTime", ActiveSearch.entity().getLastUpdateTime(), SearchCriteria.Op.GT); - ActiveSearch.and("removed", ActiveSearch.entity().getRemoved(), SearchCriteria.Op.NULL); - ActiveSearch.done(); - InactiveSearch = createSearchBuilder(); - InactiveSearch.and("lastUpdateTime", InactiveSearch.entity().getLastUpdateTime(), SearchCriteria.Op.LTEQ); - InactiveSearch.and("removed", InactiveSearch.entity().getRemoved(), SearchCriteria.Op.NULL); - InactiveSearch.done(); - - StateSearch = createSearchBuilder(); - StateSearch.and("state", StateSearch.entity().getState(), SearchCriteria.Op.IN); - StateSearch.done(); - } - - @Override + return changedRows; + } + + protected ManagementServerHostDaoImpl() { + MsIdSearch = createSearchBuilder(); + MsIdSearch.and("msid", MsIdSearch.entity().getMsid(), SearchCriteria.Op.EQ); + MsIdSearch.done(); + + ActiveSearch = createSearchBuilder(); + ActiveSearch.and("lastUpdateTime", ActiveSearch.entity().getLastUpdateTime(), SearchCriteria.Op.GT); + ActiveSearch.and("removed", ActiveSearch.entity().getRemoved(), SearchCriteria.Op.NULL); + ActiveSearch.done(); + + InactiveSearch = createSearchBuilder(); + InactiveSearch.and("lastUpdateTime", InactiveSearch.entity().getLastUpdateTime(), SearchCriteria.Op.LTEQ); + InactiveSearch.and("removed", InactiveSearch.entity().getRemoved(), SearchCriteria.Op.NULL); + InactiveSearch.done(); + + StateSearch = createSearchBuilder(); + StateSearch.and("state", StateSearch.entity().getState(), SearchCriteria.Op.IN); + StateSearch.done(); + } + + @Override public void update(long id, long runId, State state, Date lastUpdate) { - TransactionLegacy txn = TransactionLegacy.currentTxn(); + TransactionLegacy txn = TransactionLegacy.currentTxn(); PreparedStatement pstmt = null; try { pstmt = txn.prepareAutoCloseStatement("update mshost set state=?, last_update=? where id=? and runid=?"); @@ -218,9 +218,9 @@ public class ManagementServerHostDaoImpl extends GenericDaoBase listBy(ManagementServerHost.State... states) { - SearchCriteria sc = StateSearch.create(); + SearchCriteria sc = StateSearch.create(); sc.setParameters("state", (Object[])states); - + return listBy(sc); - } - - @Override - public List listOrphanMsids() { - List orphanList = new ArrayList(); - - TransactionLegacy txn = TransactionLegacy.currentTxn(); + } + + @Override + public List listOrphanMsids() { + List orphanList = new ArrayList(); + + TransactionLegacy txn = TransactionLegacy.currentTxn(); PreparedStatement pstmt = null; try { pstmt = @@ -250,26 +250,26 @@ public class ManagementServerHostDaoImpl extends GenericDaoBase sc = StateSearch.create(); + return orphanList; + } + + @Override + public ManagementServerHostVO findOneInUpState(Filter filter) { + SearchCriteria sc = StateSearch.create(); sc.setParameters("state", ManagementServerHost.State.Up); - - List mshosts = listBy(sc, filter); + + List mshosts = listBy(sc, filter); if (mshosts != null && mshosts.size() > 0) { - return mshosts.get(0); + return mshosts.get(0); } return null; - } - + } + } diff --git a/framework/config/src/org/apache/cloudstack/framework/config/ConfigDepot.java b/framework/config/src/org/apache/cloudstack/framework/config/ConfigDepot.java index 8592745c7e7..1ed37ab9969 100644 --- a/framework/config/src/org/apache/cloudstack/framework/config/ConfigDepot.java +++ b/framework/config/src/org/apache/cloudstack/framework/config/ConfigDepot.java @@ -16,7 +16,7 @@ // under the License. package org.apache.cloudstack.framework.config; -import java.util.List; +import java.util.Set; /** * ConfigDepot is a repository of configurations. @@ -26,5 +26,9 @@ public interface ConfigDepot { ConfigKey get(String paramName); - List> getConfigListByScope(String scope); + Set> getConfigListByScope(String scope); + + void set(ConfigKey key, T value); + + void createOrUpdateConfigObject(String componentName, ConfigKey key, String value); } diff --git a/framework/config/src/org/apache/cloudstack/framework/config/impl/ConfigDepotImpl.java b/framework/config/src/org/apache/cloudstack/framework/config/impl/ConfigDepotImpl.java index 15933de60ff..c1ab6b89101 100644 --- a/framework/config/src/org/apache/cloudstack/framework/config/impl/ConfigDepotImpl.java +++ b/framework/config/src/org/apache/cloudstack/framework/config/impl/ConfigDepotImpl.java @@ -27,15 +27,14 @@ import java.util.Set; import javax.annotation.PostConstruct; import javax.inject.Inject; -import org.apache.commons.lang.ObjectUtils; -import org.apache.log4j.Logger; - import org.apache.cloudstack.framework.config.ConfigDepot; import org.apache.cloudstack.framework.config.ConfigDepotAdmin; import org.apache.cloudstack.framework.config.ConfigKey; import org.apache.cloudstack.framework.config.Configurable; import org.apache.cloudstack.framework.config.ScopedConfigStorage; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; +import org.apache.commons.lang.ObjectUtils; +import org.apache.log4j.Logger; import com.cloud.utils.Pair; import com.cloud.utils.exception.CloudRuntimeException; @@ -77,14 +76,14 @@ public class ConfigDepotImpl implements ConfigDepot, ConfigDepotAdmin { HashMap>> _allKeys = new HashMap>>(1007); - HashMap>> _scopeLevelConfigsMap = new HashMap>>(); + HashMap>> _scopeLevelConfigsMap = new HashMap>>(); public ConfigDepotImpl() { ConfigKey.init(this); - _scopeLevelConfigsMap.put(ConfigKey.Scope.Zone, new ArrayList>()); - _scopeLevelConfigsMap.put(ConfigKey.Scope.Cluster, new ArrayList>()); - _scopeLevelConfigsMap.put(ConfigKey.Scope.StoragePool, new ArrayList>()); - _scopeLevelConfigsMap.put(ConfigKey.Scope.Account, new ArrayList>()); + _scopeLevelConfigsMap.put(ConfigKey.Scope.Zone, new HashSet>()); + _scopeLevelConfigsMap.put(ConfigKey.Scope.Cluster, new HashSet>()); + _scopeLevelConfigsMap.put(ConfigKey.Scope.StoragePool, new HashSet>()); + _scopeLevelConfigsMap.put(ConfigKey.Scope.Account, new HashSet>()); } @Override @@ -116,23 +115,10 @@ public class ConfigDepotImpl implements ConfigDepot, ConfigDepotAdmin { } _allKeys.put(key.key(), new Pair>(configurable.getConfigComponentName(), key)); - ConfigurationVO vo = _configDao.findById(key.key()); - if (vo == null) { - vo = new ConfigurationVO(configurable.getConfigComponentName(), key); - vo.setUpdated(date); - _configDao.persist(vo); - } else { - if (vo.isDynamic() != key.isDynamic() || !ObjectUtils.equals(vo.getDescription(), key.description()) || - !ObjectUtils.equals(vo.getDefaultValue(), key.defaultValue())) { - vo.setDynamic(key.isDynamic()); - vo.setDescription(key.description()); - vo.setDefaultValue(key.defaultValue()); - vo.setUpdated(date); - _configDao.persist(vo); - } - } - if (key.scope() != ConfigKey.Scope.Global) { - List> currentConfigs = _scopeLevelConfigsMap.get(key.scope()); + createOrupdateConfigObject(date, configurable.getConfigComponentName(), key, null); + + if ((key.scope() != null) && (key.scope() != ConfigKey.Scope.Global)) { + Set> currentConfigs = _scopeLevelConfigsMap.get(key.scope()); currentConfigs.add(key); } } @@ -140,6 +126,28 @@ public class ConfigDepotImpl implements ConfigDepot, ConfigDepotAdmin { _configured.add(configurable); } + private void createOrupdateConfigObject(Date date, String componentName, ConfigKey key, String value) { + ConfigurationVO vo = _configDao.findById(key.key()); + if (vo == null) { + vo = new ConfigurationVO(componentName, key); + vo.setUpdated(date); + if (value != null) { + vo.setValue(value); + } + _configDao.persist(vo); + } else { + if (vo.isDynamic() != key.isDynamic() || !ObjectUtils.equals(vo.getDescription(), key.description()) || !ObjectUtils.equals(vo.getDefaultValue(), key.defaultValue()) + || !ObjectUtils.equals(vo.getScope(), key.scope().toString())) { + vo.setDynamic(key.isDynamic()); + vo.setDescription(key.description()); + vo.setDefaultValue(key.defaultValue()); + vo.setScope(key.scope().toString()); + vo.setUpdated(date); + _configDao.persist(vo); + } + } + } + @Override public void populateConfiguration(Configurable configurable) { populateConfiguration(new Date(), configurable); @@ -170,7 +178,7 @@ public class ConfigDepotImpl implements ConfigDepot, ConfigDepotAdmin { @Inject public void setScopedStorages(List scopedStorages) { - this._scopedStorages = scopedStorages; + _scopedStorages = scopedStorages; } public List getConfigurables() { @@ -179,12 +187,22 @@ public class ConfigDepotImpl implements ConfigDepot, ConfigDepotAdmin { @Inject public void setConfigurables(List configurables) { - this._configurables = configurables; + _configurables = configurables; } @Override - public List> getConfigListByScope(String scope) { + public Set> getConfigListByScope(String scope) { return _scopeLevelConfigsMap.get(ConfigKey.Scope.valueOf(scope)); } + @Override + public void set(ConfigKey key, T value) { + _configDao.update(key.key(), value.toString()); + } + + @Override + public void createOrUpdateConfigObject(String componentName, ConfigKey key, String value) { + createOrupdateConfigObject(new Date(), componentName, key, value); + + } } diff --git a/framework/config/test/org/apache/cloudstack/framework/config/impl/ConfigDepotAdminTest.java b/framework/config/test/org/apache/cloudstack/framework/config/impl/ConfigDepotAdminTest.java index 245e9a6d49e..da76804eb77 100644 --- a/framework/config/test/org/apache/cloudstack/framework/config/impl/ConfigDepotAdminTest.java +++ b/framework/config/test/org/apache/cloudstack/framework/config/impl/ConfigDepotAdminTest.java @@ -39,8 +39,8 @@ import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import com.cloud.utils.db.EntityManager; public class ConfigDepotAdminTest extends TestCase { - private final ConfigKey DynamicIntCK = new ConfigKey(Integer.class, "dynIntKey", "Advance", "10", "Test Key", true); - private final ConfigKey StaticIntCK = new ConfigKey(Integer.class, "statIntKey", "Advance", "10", "Test Key", false); + private final static ConfigKey DynamicIntCK = new ConfigKey(Integer.class, "dynIntKey", "Advance", "10", "Test Key", true); + private final static ConfigKey StaticIntCK = new ConfigKey(Integer.class, "statIntKey", "Advance", "10", "Test Key", false); @Mock Configurable _configurable; diff --git a/framework/db/src/com/cloud/utils/db/GenericDao.java b/framework/db/src/com/cloud/utils/db/GenericDao.java index 14169ff9545..cb401cd7000 100755 --- a/framework/db/src/com/cloud/utils/db/GenericDao.java +++ b/framework/db/src/com/cloud/utils/db/GenericDao.java @@ -160,14 +160,14 @@ public interface GenericDao { * Search for the entity beans using the sql SQL_CACHE option * @param sc * @param filter - * @param enable_query_cache + * @param enableQueryCache * @return list of entity beans. */ - List search(SearchCriteria sc, Filter filter, final boolean enable_query_cache); + List search(SearchCriteria sc, Filter filter, final boolean enableQueryCache); List searchIncludingRemoved(SearchCriteria sc, final Filter filter, final Boolean lock, final boolean cache); - List searchIncludingRemoved(SearchCriteria sc, final Filter filter, final Boolean lock, final boolean cache, final boolean enable_query_cache); + List searchIncludingRemoved(SearchCriteria sc, final Filter filter, final Boolean lock, final boolean cache, final boolean enableQueryCache); /** * Customized search with SearchCritiria diff --git a/framework/db/src/com/cloud/utils/db/GenericDaoBase.java b/framework/db/src/com/cloud/utils/db/GenericDaoBase.java index 8e6f6a45b69..f282428b8de 100755 --- a/framework/db/src/com/cloud/utils/db/GenericDaoBase.java +++ b/framework/db/src/com/cloud/utils/db/GenericDaoBase.java @@ -346,14 +346,14 @@ public abstract class GenericDaoBase extends Compone } @DB() - protected List search(SearchCriteria sc, final Filter filter, final Boolean lock, final boolean cache, final boolean enable_query_cache) { + protected List search(SearchCriteria sc, final Filter filter, final Boolean lock, final boolean cache, final boolean enableQueryCache) { if (_removed != null) { if (sc == null) { sc = createSearchCriteria(); } sc.addAnd(_removed.second().field.getName(), SearchCriteria.Op.NULL); } - return searchIncludingRemoved(sc, filter, lock, cache, enable_query_cache); + return searchIncludingRemoved(sc, filter, lock, cache, enableQueryCache); } @Override @@ -362,13 +362,13 @@ public abstract class GenericDaoBase extends Compone } @Override - public List searchIncludingRemoved(SearchCriteria sc, final Filter filter, final Boolean lock, final boolean cache, final boolean enable_query_cache) { + public List searchIncludingRemoved(SearchCriteria sc, final Filter filter, final Boolean lock, final boolean cache, final boolean enableQueryCache) { String clause = sc != null ? sc.getWhereClause() : null; if (clause != null && clause.length() == 0) { clause = null; } - final StringBuilder str = createPartialSelectSql(sc, clause != null, enable_query_cache); + final StringBuilder str = createPartialSelectSql(sc, clause != null, enableQueryCache); if (clause != null) { str.append(clause); } @@ -658,9 +658,21 @@ public abstract class GenericDaoBase extends Compone } } + /** + * Get a value from a result set. + * + * @param type + * the expected type of the result + * @param rs + * the result set + * @param index + * the index of the column + * @return the result in the requested type + * @throws SQLException + */ @DB() @SuppressWarnings("unchecked") - protected M getObject(Class type, ResultSet rs, int index) throws SQLException { + protected static M getObject(Class type, ResultSet rs, int index) throws SQLException { if (type == String.class) { byte[] bytes = rs.getBytes(index); if (bytes != null) { @@ -681,12 +693,12 @@ public abstract class GenericDaoBase extends Compone return (M)new Integer(rs.getInt(index)); } } else if (type == long.class) { - return (M)new Long(rs.getLong(index)); + return (M) (Long) rs.getLong(index); } else if (type == Long.class) { if (rs.getObject(index) == null) { return null; } else { - return (M)new Long(rs.getLong(index)); + return (M) (Long) rs.getLong(index); } } else if (type == Date.class) { final Object data = rs.getDate(index); @@ -696,44 +708,44 @@ public abstract class GenericDaoBase extends Compone return (M)DateUtil.parseDateString(s_gmtTimeZone, rs.getString(index)); } } else if (type == short.class) { - return (M)new Short(rs.getShort(index)); + return (M) (Short) rs.getShort(index); } else if (type == Short.class) { if (rs.getObject(index) == null) { return null; } else { - return (M)new Short(rs.getShort(index)); + return (M) (Short) rs.getShort(index); } } else if (type == boolean.class) { - return (M)new Boolean(rs.getBoolean(index)); + return (M) (Boolean) rs.getBoolean(index); } else if (type == Boolean.class) { if (rs.getObject(index) == null) { return null; } else { - return (M)new Boolean(rs.getBoolean(index)); + return (M) (Boolean) rs.getBoolean(index); } } else if (type == float.class) { - return (M)new Float(rs.getFloat(index)); + return (M) (Float) rs.getFloat(index); } else if (type == Float.class) { if (rs.getObject(index) == null) { return null; } else { - return (M)new Float(rs.getFloat(index)); + return (M) (Float) rs.getFloat(index); } } else if (type == double.class) { - return (M)new Double(rs.getDouble(index)); + return (M) (Double) rs.getDouble(index); } else if (type == Double.class) { if (rs.getObject(index) == null) { return null; } else { - return (M)new Double(rs.getDouble(index)); + return (M) (Double) rs.getDouble(index); } } else if (type == byte.class) { - return (M)new Byte(rs.getByte(index)); + return (M) (Byte) rs.getByte(index); } else if (type == Byte.class) { if (rs.getObject(index) == null) { return null; } else { - return (M)new Byte(rs.getByte(index)); + return (M) (Byte) rs.getByte(index); } } else if (type == Calendar.class) { final Object data = rs.getDate(index); @@ -896,11 +908,11 @@ public abstract class GenericDaoBase extends Compone } @DB() - protected List listBy(final SearchCriteria sc, final Filter filter, final boolean enable_query_cache) { + protected List listBy(final SearchCriteria sc, final Filter filter, final boolean enableQueryCache) { if (_removed != null) { sc.addAnd(_removed.second().field.getName(), SearchCriteria.Op.NULL); } - return listIncludingRemovedBy(sc, filter, enable_query_cache); + return listIncludingRemovedBy(sc, filter, enableQueryCache); } @DB() @@ -909,8 +921,8 @@ public abstract class GenericDaoBase extends Compone } @DB() - protected List listIncludingRemovedBy(final SearchCriteria sc, final Filter filter, final boolean enable_query_cache) { - return searchIncludingRemoved(sc, filter, null, false, enable_query_cache); + protected List listIncludingRemovedBy(final SearchCriteria sc, final Filter filter, final boolean enableQueryCache) { + return searchIncludingRemoved(sc, filter, null, false, enableQueryCache); } @DB() @@ -1194,8 +1206,8 @@ public abstract class GenericDaoBase extends Compone } @DB() - protected StringBuilder createPartialSelectSql(SearchCriteria sc, final boolean whereClause, final boolean enable_query_cache) { - StringBuilder sql = new StringBuilder(enable_query_cache ? _partialQueryCacheSelectSql.first() : _partialSelectSql.first()); + protected StringBuilder createPartialSelectSql(SearchCriteria sc, final boolean whereClause, final boolean enableQueryCache) { + StringBuilder sql = new StringBuilder(enableQueryCache ? _partialQueryCacheSelectSql.first() : _partialSelectSql.first()); if (sc != null && !sc.isSelectAll()) { sql.delete(7, sql.indexOf(" FROM")); sc.getSelect(sql, 7); @@ -1281,8 +1293,8 @@ public abstract class GenericDaoBase extends Compone @Override @DB() - public List search(final SearchCriteria sc, final Filter filter, final boolean enable_query_cache) { - return search(sc, filter, null, false, enable_query_cache); + public List search(final SearchCriteria sc, final Filter filter, final boolean enableQueryCache) { + return search(sc, filter, null, false, enableQueryCache); } @Override diff --git a/framework/db/src/com/cloud/utils/db/Merovingian2.java b/framework/db/src/com/cloud/utils/db/Merovingian2.java index 59dff2dd383..6eeea9f3850 100644 --- a/framework/db/src/com/cloud/utils/db/Merovingian2.java +++ b/framework/db/src/com/cloud/utils/db/Merovingian2.java @@ -52,7 +52,7 @@ public class Merovingian2 extends StandardMBean implements MerovingianMBean { private static final String SELECT_THREAD_LOCKS_SQL = SELECT_SQL + " WHERE mac=? AND ip=?"; private static final String CLEANUP_THREAD_LOCKS_SQL = "DELETE FROM op_lock WHERE mac=? AND ip=? AND thread=?"; - TimeZone s_gmtTimeZone = TimeZone.getTimeZone("GMT"); + TimeZone _gmtTimeZone = TimeZone.getTimeZone("GMT"); private final long _msId; @@ -184,7 +184,7 @@ public class Merovingian2 extends StandardMBean implements MerovingianMBean { pstmt.setLong(2, _msId); pstmt.setString(3, threadName); pstmt.setInt(4, threadId); - pstmt.setString(5, DateUtil.getDateDisplayString(s_gmtTimeZone, new Date())); + pstmt.setString(5, DateUtil.getDateDisplayString(_gmtTimeZone, new Date())); try { int rows = pstmt.executeUpdate(); if (rows == 1) { diff --git a/framework/db/src/com/cloud/utils/db/SqlGenerator.java b/framework/db/src/com/cloud/utils/db/SqlGenerator.java index 2c24f62ced5..befe34b59e2 100755 --- a/framework/db/src/com/cloud/utils/db/SqlGenerator.java +++ b/framework/db/src/com/cloud/utils/db/SqlGenerator.java @@ -567,10 +567,10 @@ public class SqlGenerator { return sql.toString(); } - public Pair buildSelectSql(boolean enable_query_cache) { + public Pair buildSelectSql(boolean enableQueryCache) { StringBuilder sql = new StringBuilder("SELECT "); - sql.append(enable_query_cache ? "SQL_CACHE " : ""); + sql.append(enableQueryCache ? "SQL_CACHE " : ""); ArrayList attrs = new ArrayList(); diff --git a/framework/db/src/com/cloud/utils/db/TransactionLegacy.java b/framework/db/src/com/cloud/utils/db/TransactionLegacy.java index e5cece182d2..ac0ea21d1f1 100755 --- a/framework/db/src/com/cloud/utils/db/TransactionLegacy.java +++ b/framework/db/src/com/cloud/utils/db/TransactionLegacy.java @@ -769,7 +769,7 @@ public class TransactionLegacy { try { // we should only close db connection when it is not user managed - if (this._dbId != CONNECTED_DB) { + if (_dbId != CONNECTED_DB) { if (s_connLogger.isTraceEnabled()) { s_connLogger.trace("Closing DB connection: dbconn" + System.identityHashCode(_conn)); } @@ -1203,7 +1203,7 @@ public class TransactionLegacy { final ConnectionFactory connectionFactory = new DriverManagerConnectionFactory("jdbc:mysql://localhost:3306/" + database, "cloud", "cloud"); final PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true); return new PoolingDataSource( - /* connectionPool */poolableConnectionFactory.getPool()); + /* connectionPool */poolableConnectionFactory.getPool()); } /** @@ -1212,6 +1212,26 @@ public class TransactionLegacy { * @param conn */ protected void setConnection(Connection conn) { - this._conn = conn; + _conn = conn; } + + /** + * Receives a list of {@link PreparedStatement} and quietly closes all of them, which + * triggers also closing their dependent objects, like a {@link ResultSet} + * + * @param pstmt2Close + */ + public static void closePstmts(List pstmt2Close) { + for (PreparedStatement pstmt : pstmt2Close) { + try { + if (pstmt != null && !pstmt.isClosed()) { + pstmt.close(); + } + } catch (SQLException e) { + // It's not possible to recover from this and we need to continue closing + e.printStackTrace(); + } + } + } + } diff --git a/framework/db/test/com/cloud/utils/db/GenericDaoBaseTest.java b/framework/db/test/com/cloud/utils/db/GenericDaoBaseTest.java new file mode 100644 index 00000000000..b7febcb8994 --- /dev/null +++ b/framework/db/test/com/cloud/utils/db/GenericDaoBaseTest.java @@ -0,0 +1,134 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.utils.db; + +import java.sql.ResultSet; +import java.sql.SQLException; + +import junit.framework.Assert; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.runners.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class GenericDaoBaseTest { + @Mock + ResultSet resultSet; + + @Test + public void getObjectBoolean() throws SQLException { + Mockito.when(resultSet.getObject(1)).thenReturn(false); + Mockito.when(resultSet.getBoolean(1)).thenReturn(false); + Assert.assertFalse(GenericDaoBase + .getObject(Boolean.class, resultSet, 1)); + Mockito.verify(resultSet).getBoolean(1); + } + + @Test + public void getObjectPrimitiveBoolean() throws SQLException { + Mockito.when(resultSet.getObject(1)).thenReturn(false); + Mockito.when(resultSet.getBoolean(1)).thenReturn(false); + Assert.assertFalse(GenericDaoBase + .getObject(boolean.class, resultSet, 1)); + Mockito.verify(resultSet).getBoolean(1); + } + + @Test + public void getObjectPrimitiveShort() throws SQLException { + Mockito.when(resultSet.getObject(1)).thenReturn((short) 1); + Mockito.when(resultSet.getShort(1)).thenReturn((short) 1); + Assert.assertEquals(Short.valueOf((short) 1), + GenericDaoBase.getObject(short.class, resultSet, 1)); + Mockito.verify(resultSet).getShort(1); + } + + @Test + public void getObjectShort() throws SQLException { + Mockito.when(resultSet.getObject(1)).thenReturn((short) 1); + Mockito.when(resultSet.getShort(1)).thenReturn((short) 1); + Assert.assertEquals(Short.valueOf((short) 1), + GenericDaoBase.getObject(Short.class, resultSet, 1)); + Mockito.verify(resultSet).getShort(1); + } + + @Test + public void getObjectFloat() throws SQLException { + Mockito.when(resultSet.getObject(1)).thenReturn(0.1f); + Mockito.when(resultSet.getFloat(1)).thenReturn(0.1f); + Assert.assertEquals(0.1f, + GenericDaoBase.getObject(Float.class, resultSet, 1)); + Mockito.verify(resultSet).getFloat(1); + } + + @Test + public void getObjectPrimitiveFloat() throws SQLException { + Mockito.when(resultSet.getObject(1)).thenReturn(0.1f); + Mockito.when(resultSet.getFloat(1)).thenReturn(0.1f); + Assert.assertEquals(0.1f, + GenericDaoBase.getObject(float.class, resultSet, 1)); + Mockito.verify(resultSet).getFloat(1); + } + + @Test + public void getObjectPrimitiveDouble() throws SQLException { + Mockito.when(resultSet.getObject(1)).thenReturn(0.1d); + Mockito.when(resultSet.getDouble(1)).thenReturn(0.1d); + Assert.assertEquals(0.1d, + GenericDaoBase.getObject(double.class, resultSet, 1)); + Mockito.verify(resultSet).getDouble(1); + } + + @Test + public void getObjectDouble() throws SQLException { + Mockito.when(resultSet.getObject(1)).thenReturn(0.1d); + Mockito.when(resultSet.getDouble(1)).thenReturn(0.1d); + Assert.assertEquals(0.1d, + GenericDaoBase.getObject(Double.class, resultSet, 1)); + Mockito.verify(resultSet).getDouble(1); + } + + @Test + public void getObjectLong() throws SQLException { + Mockito.when(resultSet.getObject(1)).thenReturn(1l); + Mockito.when(resultSet.getLong(1)).thenReturn(1l); + Assert.assertEquals((Long) 1l, + GenericDaoBase.getObject(Long.class, resultSet, 1)); + Mockito.verify(resultSet).getLong(1); + } + + @Test + public void getObjectPrimitiveLong() throws SQLException { + Mockito.when(resultSet.getObject(1)).thenReturn(1l); + Mockito.when(resultSet.getLong(1)).thenReturn(1l); + Assert.assertEquals((Long) 1l, + GenericDaoBase.getObject(long.class, resultSet, 1)); + Mockito.verify(resultSet).getLong(1); + } + + @Test + public void getObjectPrimitiveByte() throws SQLException { + Mockito.when(resultSet.getObject(1)).thenReturn((byte) 1); + Mockito.when(resultSet.getByte(1)).thenReturn((byte) 1); + Assert.assertTrue((byte) 1 == GenericDaoBase.getObject(byte.class, + resultSet, 1)); + Mockito.verify(resultSet).getByte(1); + } + +} diff --git a/framework/db/test/com/cloud/utils/db/GlobalLockTest.java b/framework/db/test/com/cloud/utils/db/GlobalLockTest.java index 8b0720b5ee9..c26f2486018 100644 --- a/framework/db/test/com/cloud/utils/db/GlobalLockTest.java +++ b/framework/db/test/com/cloud/utils/db/GlobalLockTest.java @@ -28,7 +28,7 @@ import com.cloud.utils.Profiler; @ContextConfiguration(locations = "classpath:/testContext.xml") public class GlobalLockTest { public static final Logger s_logger = Logger.getLogger(GlobalLockTest.class); - private final static GlobalLock _workLock = GlobalLock.getInternLock("SecurityGroupWork"); + private final static GlobalLock WorkLock = GlobalLock.getInternLock("SecurityGroupWork"); public static class Worker implements Runnable { int id = 0; @@ -47,7 +47,7 @@ public class GlobalLockTest { try { Profiler p = new Profiler(); p.start(); - locked = _workLock.lock(timeoutSeconds); + locked = WorkLock.lock(timeoutSeconds); p.stop(); System.out.println("Thread " + id + " waited " + p.getDuration() + " ms, locked=" + locked); if (locked) { @@ -56,7 +56,7 @@ public class GlobalLockTest { } catch (InterruptedException e) { } finally { if (locked) { - boolean unlocked = _workLock.unlock(); + boolean unlocked = WorkLock.unlock(); System.out.println("Thread " + id + " unlocked=" + unlocked); } } diff --git a/framework/ipc/src/org/apache/cloudstack/framework/messagebus/MessageDispatcher.java b/framework/ipc/src/org/apache/cloudstack/framework/messagebus/MessageDispatcher.java index a2d9a7bced0..e93bbc2ad4a 100644 --- a/framework/ipc/src/org/apache/cloudstack/framework/messagebus/MessageDispatcher.java +++ b/framework/ipc/src/org/apache/cloudstack/framework/messagebus/MessageDispatcher.java @@ -20,17 +20,24 @@ package org.apache.cloudstack.framework.messagebus; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; +import org.apache.log4j.Logger; + public class MessageDispatcher implements MessageSubscriber { - private static Map, Method> s_handlerCache = new HashMap, Method>(); + private static final Logger s_logger = Logger.getLogger(MessageDispatcher.class); + + private static Map, List> s_handlerCache = new HashMap, List>(); private static Map s_targetMap = new HashMap(); private Object _targetObject; public MessageDispatcher(Object targetObject) { _targetObject = targetObject; + buildHandlerMethodCache(targetObject.getClass()); } @Override @@ -67,10 +74,13 @@ public class MessageDispatcher implements MessageSubscriber { try { handler.invoke(target, subject, senderAddress, args); } catch (IllegalArgumentException e) { + s_logger.error("Unexpected exception when calling " + target.getClass().getName() + "." + handler.getName(), e); throw new RuntimeException("IllegalArgumentException when invoking event handler for subject: " + subject); } catch (IllegalAccessException e) { + s_logger.error("Unexpected exception when calling " + target.getClass().getName() + "." + handler.getName(), e); throw new RuntimeException("IllegalAccessException when invoking event handler for subject: " + subject); } catch (InvocationTargetException e) { + s_logger.error("Unexpected exception when calling " + target.getClass().getName() + "." + handler.getName(), e); throw new RuntimeException("InvocationTargetException when invoking event handler for subject: " + subject); } @@ -79,18 +89,18 @@ public class MessageDispatcher implements MessageSubscriber { public static Method resolveHandler(Class handlerClz, String subject) { synchronized (s_handlerCache) { - Method handler = s_handlerCache.get(handlerClz); - if (handler != null) - return handler; + List handlerList = s_handlerCache.get(handlerClz); + if (handlerList != null) { + for (Method method : handlerList) { + MessageHandler annotation = method.getAnnotation(MessageHandler.class); + assert (annotation != null); - for (Method method : handlerClz.getMethods()) { - MessageHandler annotation = method.getAnnotation(MessageHandler.class); - if (annotation != null) { if (match(annotation.topic(), subject)) { - s_handlerCache.put(handlerClz, method); return method; } } + } else { + s_logger.error("Handler class " + handlerClz.getName() + " is not registered"); } } @@ -100,4 +110,40 @@ public class MessageDispatcher implements MessageSubscriber { private static boolean match(String expression, String param) { return param.matches(expression); } + + private void buildHandlerMethodCache(Class handlerClz) { + if (s_logger.isInfoEnabled()) + s_logger.info("Build message handler cache for " + handlerClz.getName()); + + synchronized (s_handlerCache) { + List handlerList = s_handlerCache.get(handlerClz); + if (handlerList == null) { + handlerList = new ArrayList(); + s_handlerCache.put(handlerClz, handlerList); + + Class clz = handlerClz; + while (clz != null && clz != Object.class) { + for (Method method : clz.getDeclaredMethods()) { + MessageHandler annotation = method.getAnnotation(MessageHandler.class); + if (annotation != null) { + // allow private member access via reflection + method.setAccessible(true); + handlerList.add(method); + + if (s_logger.isInfoEnabled()) + s_logger.info("Add message handler " + handlerClz.getName() + "." + method.getName() + " to cache"); + } + } + + clz = clz.getSuperclass(); + } + } else { + if (s_logger.isInfoEnabled()) + s_logger.info("Message handler for class " + handlerClz.getName() + " is already in cache"); + } + } + + if (s_logger.isInfoEnabled()) + s_logger.info("Done building message handler cache for " + handlerClz.getName()); + } } diff --git a/framework/jobs/src/org/apache/cloudstack/framework/jobs/AsyncJobExecutionContext.java b/framework/jobs/src/org/apache/cloudstack/framework/jobs/AsyncJobExecutionContext.java index 6eaff885609..20125f43e66 100644 --- a/framework/jobs/src/org/apache/cloudstack/framework/jobs/AsyncJobExecutionContext.java +++ b/framework/jobs/src/org/apache/cloudstack/framework/jobs/AsyncJobExecutionContext.java @@ -18,6 +18,7 @@ package org.apache.cloudstack.framework.jobs; import org.apache.log4j.Logger; +import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.framework.jobs.dao.AsyncJobJoinMapDao; import org.apache.cloudstack.framework.jobs.impl.AsyncJobJoinMapVO; import org.apache.cloudstack.framework.jobs.impl.JobSerializerHelper; @@ -30,131 +31,155 @@ import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceUnavailableException; public class AsyncJobExecutionContext { + private static final Logger s_logger = Logger.getLogger(AsyncJobExecutionContext.class); + private AsyncJob _job; - - static private AsyncJobManager _jobMgr; - static private AsyncJobJoinMapDao _joinMapDao; + + static private AsyncJobManager s_jobMgr; + static private AsyncJobJoinMapDao s_joinMapDao; public static void init(AsyncJobManager jobMgr, AsyncJobJoinMapDao joinMapDao) { - _jobMgr = jobMgr; - _joinMapDao = joinMapDao; + s_jobMgr = jobMgr; + s_joinMapDao = joinMapDao; } - - private static ManagedThreadLocal s_currentExectionContext = new ManagedThreadLocal(); - public AsyncJobExecutionContext() { - } - - public AsyncJobExecutionContext(AsyncJob job) { - _job = job; - } - - public SyncQueueItem getSyncSource() { - return _job.getSyncSource(); - } - - public void resetSyncSource() { - _job.setSyncSource(null); - } - - public AsyncJob getJob() { - return _job; - } - - public void setJob(AsyncJob job) { - _job = job; - } - - public boolean isJobDispatchedBy(String jobDispatcherName) { - assert(jobDispatcherName != null); - if(_job != null && _job.getDispatcher() != null && _job.getDispatcher().equals(jobDispatcherName)) - return true; - - return false; + private static ManagedThreadLocal s_currentExectionContext = new ManagedThreadLocal(); + + public AsyncJobExecutionContext() { } - + + public AsyncJobExecutionContext(AsyncJob job) { + _job = job; + } + + public SyncQueueItem getSyncSource() { + return _job.getSyncSource(); + } + + public void resetSyncSource() { + _job.setSyncSource(null); + } + + public AsyncJob getJob() { + return _job; + } + + public void setJob(AsyncJob job) { + _job = job; + } + + public boolean isJobDispatchedBy(String jobDispatcherName) { + assert (jobDispatcherName != null); + if (_job != null && _job.getDispatcher() != null && _job.getDispatcher().equals(jobDispatcherName)) + return true; + + return false; + } + public void completeAsyncJob(JobInfo.Status jobStatus, int resultCode, String resultObject) { assert (_job != null); - _jobMgr.completeAsyncJob(_job.getId(), jobStatus, resultCode, resultObject); + s_jobMgr.completeAsyncJob(_job.getId(), jobStatus, resultCode, resultObject); } - + public void updateAsyncJobStatus(int processStatus, String resultObject) { assert (_job != null); - _jobMgr.updateAsyncJobStatus(_job.getId(), processStatus, resultObject); + s_jobMgr.updateAsyncJobStatus(_job.getId(), processStatus, resultObject); } - + public void updateAsyncJobAttachment(String instanceType, Long instanceId) { assert (_job != null); - _jobMgr.updateAsyncJobAttachment(_job.getId(), instanceType, instanceId); + s_jobMgr.updateAsyncJobAttachment(_job.getId(), instanceType, instanceId); } - + public void logJobJournal(AsyncJob.JournalType journalType, String journalText, String journalObjJson) { assert (_job != null); - _jobMgr.logJobJournal(_job.getId(), journalType, journalText, journalObjJson); - } + s_jobMgr.logJobJournal(_job.getId(), journalType, journalText, journalObjJson); + } public void log(Logger logger, String journalText) { - _jobMgr.logJobJournal(_job.getId(), AsyncJob.JournalType.SUCCESS, journalText, null); + s_jobMgr.logJobJournal(_job.getId(), AsyncJob.JournalType.SUCCESS, journalText, null); logger.debug(journalText); } public void joinJob(long joinJobId) { assert (_job != null); - _jobMgr.joinJob(_job.getId(), joinJobId); - } - - public void joinJob(long joinJobId, String wakeupHandler, String wakeupDispatcher, String[] wakeupTopcisOnMessageBus, long wakeupIntervalInMilliSeconds, - long timeoutInMilliSeconds) { - assert (_job != null); - _jobMgr.joinJob(_job.getId(), joinJobId, wakeupHandler, wakeupDispatcher, wakeupTopcisOnMessageBus, wakeupIntervalInMilliSeconds, timeoutInMilliSeconds); - } - - // - // check failure exception before we disjoin the worker job - // TODO : it is ugly and this will become unnecessary after we switch to full-async mode - // - public void disjoinJob(long joinedJobId) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException { - assert (_job != null); - - AsyncJobJoinMapVO record = _joinMapDao.getJoinRecord(_job.getId(), joinedJobId); - if (record.getJoinStatus() == JobInfo.Status.FAILED && record.getJoinResult() != null) { - Object exception = JobSerializerHelper.fromObjectSerializedString(record.getJoinResult()); - if (exception != null && exception instanceof Exception) { - if (exception instanceof InsufficientCapacityException) - throw (InsufficientCapacityException)exception; - else if (exception instanceof ConcurrentOperationException) - throw (ConcurrentOperationException)exception; - else if (exception instanceof ResourceUnavailableException) - throw (ResourceUnavailableException)exception; - else - throw new RuntimeException((Exception)exception); - } - } - - _jobMgr.disjoinJob(_job.getId(), joinedJobId); - } - - public void completeJoin(JobInfo.Status joinStatus, String joinResult) { - assert (_job != null); - _jobMgr.completeJoin(_job.getId(), joinStatus, joinResult); - } - - public void completeJobAndJoin(JobInfo.Status joinStatus, String joinResult) { - assert (_job != null); - _jobMgr.completeJoin(_job.getId(), joinStatus, joinResult); - _jobMgr.completeAsyncJob(_job.getId(), joinStatus, 0, null); + s_jobMgr.joinJob(_job.getId(), joinJobId); + } + + public void joinJob(long joinJobId, String wakeupHandler, String wakeupDispatcher, + String[] wakeupTopcisOnMessageBus, long wakeupIntervalInMilliSeconds, long timeoutInMilliSeconds) { + assert (_job != null); + s_jobMgr.joinJob(_job.getId(), joinJobId, wakeupHandler, wakeupDispatcher, wakeupTopcisOnMessageBus, + wakeupIntervalInMilliSeconds, timeoutInMilliSeconds); + } + + // + // check failure exception before we disjoin the worker job, work job usually fails with exception + // this will help propogate exception between jobs + // TODO : it is ugly and this will become unnecessary after we switch to full-async mode + // + public void disjoinJob(long joinedJobId) throws InsufficientCapacityException, + ConcurrentOperationException, ResourceUnavailableException { + assert (_job != null); + + AsyncJobJoinMapVO record = s_joinMapDao.getJoinRecord(_job.getId(), joinedJobId); + s_jobMgr.disjoinJob(_job.getId(), joinedJobId); + + if (record.getJoinStatus() == JobInfo.Status.FAILED) { + if (record.getJoinResult() != null) { + Object exception = JobSerializerHelper.fromObjectSerializedString(record.getJoinResult()); + if (exception != null && exception instanceof Exception) { + if (exception instanceof InsufficientCapacityException) { + s_logger.error("Job " + joinedJobId + " failed with InsufficientCapacityException"); + throw (InsufficientCapacityException)exception; + } + else if (exception instanceof ConcurrentOperationException) { + s_logger.error("Job " + joinedJobId + " failed with ConcurrentOperationException"); + throw (ConcurrentOperationException)exception; + } + else if (exception instanceof ResourceUnavailableException) { + s_logger.error("Job " + joinedJobId + " failed with ResourceUnavailableException"); + throw (ResourceUnavailableException)exception; + } + else { + s_logger.error("Job " + joinedJobId + " failed with exception"); + throw new RuntimeException((Exception)exception); + } + } + } else { + s_logger.error("Job " + joinedJobId + " failed without providing an error object"); + throw new RuntimeException("Job " + joinedJobId + " failed without providing an error object"); + } + } + } + + public void completeJoin(JobInfo.Status joinStatus, String joinResult) { + assert (_job != null); + s_jobMgr.completeJoin(_job.getId(), joinStatus, joinResult); + } + + public void completeJobAndJoin(JobInfo.Status joinStatus, String joinResult) { + assert (_job != null); + s_jobMgr.completeJoin(_job.getId(), joinStatus, joinResult); + s_jobMgr.completeAsyncJob(_job.getId(), joinStatus, 0, null); + } + + public static AsyncJobExecutionContext getCurrentExecutionContext() { + AsyncJobExecutionContext context = s_currentExectionContext.get(); + if (context == null) { + // TODO, this has security implicitions + s_logger.warn("Job is executed without a context, setup psudo job for the executing thread"); + context = registerPseudoExecutionContext(CallContext.current().getCallingAccountId(), + CallContext.current().getCallingUserId()); + } + return context; } - public static AsyncJobExecutionContext getCurrentExecutionContext() { - AsyncJobExecutionContext context = s_currentExectionContext.get(); - return context; - } - public static AsyncJobExecutionContext registerPseudoExecutionContext(long accountId, long userId) { AsyncJobExecutionContext context = s_currentExectionContext.get(); if (context == null) { context = new AsyncJobExecutionContext(); - context.setJob(_jobMgr.getPseudoJob(accountId, userId)); + context.setJob(s_jobMgr.getPseudoJob(accountId, userId)); setCurrentExecutionContext(context); } @@ -166,9 +191,13 @@ public class AsyncJobExecutionContext { setCurrentExecutionContext(null); return context; } - + // This is intended to be package level access for AsyncJobManagerImpl only. public static void setCurrentExecutionContext(AsyncJobExecutionContext currentContext) { - s_currentExectionContext.set(currentContext); - } + s_currentExectionContext.set(currentContext); + } + + public static String getOriginJobContextId() { + return String.valueOf(CallContext.current().getContextId()); + } } diff --git a/framework/jobs/src/org/apache/cloudstack/framework/jobs/AsyncJobManager.java b/framework/jobs/src/org/apache/cloudstack/framework/jobs/AsyncJobManager.java index d1a4a9d5930..67733ed1c90 100644 --- a/framework/jobs/src/org/apache/cloudstack/framework/jobs/AsyncJobManager.java +++ b/framework/jobs/src/org/apache/cloudstack/framework/jobs/AsyncJobManager.java @@ -16,6 +16,7 @@ // under the License. package org.apache.cloudstack.framework.jobs; +import java.io.Serializable; import java.util.List; import org.apache.cloudstack.framework.jobs.impl.AsyncJobVO; @@ -41,8 +42,8 @@ public interface AsyncJobManager extends Manager { void updateAsyncJobStatus(long jobId, int processStatus, String resultObject); void updateAsyncJobAttachment(long jobId, String instanceType, Long instanceId); - - void logJobJournal(long jobId, AsyncJob.JournalType journalType, String journalText, String journalObjJson); + void logJobJournal(long jobId, AsyncJob.JournalType journalType, String + journalText, String journalObjJson); /** * A running thread inside management server can have a 1:1 linked pseudo job. @@ -81,8 +82,8 @@ public interface AsyncJobManager extends Manager { * @param wakeupIntervalInMilliSeconds * @param timeoutInMilliSeconds */ - void joinJob(long jobId, long joinJobId, String wakeupHandler, String wakupDispatcher, String[] wakeupTopicsOnMessageBus, long wakeupIntervalInMilliSeconds, - long timeoutInMilliSeconds); + void joinJob(long jobId, long joinJobId, String wakeupHandler, String wakupDispatcher, + String[] wakeupTopicsOnMessageBus, long wakeupIntervalInMilliSeconds, long timeoutInMilliSeconds); /** * Dis-join two related jobs @@ -124,4 +125,7 @@ public interface AsyncJobManager extends Manager { AsyncJob queryJob(long jobId, boolean updatePollTime); + String marshallResultObject(Serializable obj); + + Object unmarshallResultObject(AsyncJob job); } diff --git a/framework/jobs/src/org/apache/cloudstack/framework/jobs/dao/VmWorkJobDao.java b/framework/jobs/src/org/apache/cloudstack/framework/jobs/dao/VmWorkJobDao.java index a3dbddf0eb6..44e39e40291 100644 --- a/framework/jobs/src/org/apache/cloudstack/framework/jobs/dao/VmWorkJobDao.java +++ b/framework/jobs/src/org/apache/cloudstack/framework/jobs/dao/VmWorkJobDao.java @@ -35,4 +35,6 @@ public interface VmWorkJobDao extends GenericDao { void updateStep(long workJobId, Step step); void expungeCompletedWorkJobs(Date cutDate); + + void expungeLeftoverWorkJobs(long msid); } diff --git a/framework/jobs/src/org/apache/cloudstack/framework/jobs/dao/VmWorkJobDaoImpl.java b/framework/jobs/src/org/apache/cloudstack/framework/jobs/dao/VmWorkJobDaoImpl.java index 5e0ffb68c39..cf3e17392b5 100644 --- a/framework/jobs/src/org/apache/cloudstack/framework/jobs/dao/VmWorkJobDaoImpl.java +++ b/framework/jobs/src/org/apache/cloudstack/framework/jobs/dao/VmWorkJobDaoImpl.java @@ -16,8 +16,11 @@ // under the License. package org.apache.cloudstack.framework.jobs.dao; +import java.sql.PreparedStatement; +import java.sql.SQLException; import java.util.Date; import java.util.List; +import java.util.TimeZone; import javax.annotation.PostConstruct; @@ -31,13 +34,16 @@ import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria.Op; +import com.cloud.utils.db.Transaction; +import com.cloud.utils.db.TransactionCallbackNoReturn; +import com.cloud.utils.db.TransactionLegacy; +import com.cloud.utils.db.TransactionStatus; import com.cloud.vm.VirtualMachine; public class VmWorkJobDaoImpl extends GenericDaoBase implements VmWorkJobDao { protected SearchBuilder PendingWorkJobSearch; protected SearchBuilder PendingWorkJobByCommandSearch; - protected SearchBuilder ExpungeWorkJobSearch; public VmWorkJobDaoImpl() { } @@ -48,7 +54,6 @@ public class VmWorkJobDaoImpl extends GenericDaoBase implemen PendingWorkJobSearch.and("jobStatus", PendingWorkJobSearch.entity().getStatus(), Op.EQ); PendingWorkJobSearch.and("vmType", PendingWorkJobSearch.entity().getVmType(), Op.EQ); PendingWorkJobSearch.and("vmInstanceId", PendingWorkJobSearch.entity().getVmInstanceId(), Op.EQ); - PendingWorkJobSearch.and("step", PendingWorkJobSearch.entity().getStep(), Op.NEQ); PendingWorkJobSearch.done(); PendingWorkJobByCommandSearch = createSearchBuilder(); @@ -58,11 +63,6 @@ public class VmWorkJobDaoImpl extends GenericDaoBase implemen PendingWorkJobByCommandSearch.and("step", PendingWorkJobByCommandSearch.entity().getStep(), Op.NEQ); PendingWorkJobByCommandSearch.and("cmd", PendingWorkJobByCommandSearch.entity().getCmd(), Op.EQ); PendingWorkJobByCommandSearch.done(); - - ExpungeWorkJobSearch = createSearchBuilder(); - ExpungeWorkJobSearch.and("lastUpdated", ExpungeWorkJobSearch.entity().getLastUpdated(), Op.LT); - ExpungeWorkJobSearch.and("jobStatus", ExpungeWorkJobSearch.entity().getStatus(), Op.NEQ); - ExpungeWorkJobSearch.done(); } @Override @@ -115,11 +115,80 @@ public class VmWorkJobDaoImpl extends GenericDaoBase implemen } @Override - public void expungeCompletedWorkJobs(Date cutDate) { - SearchCriteria sc = ExpungeWorkJobSearch.create(); - sc.setParameters("lastUpdated", cutDate); - sc.setParameters("jobStatus", JobInfo.Status.IN_PROGRESS); + public void expungeCompletedWorkJobs(final Date cutDate) { + // current DAO machenism does not support following usage + /* + SearchCriteria sc = ExpungeWorkJobSearch.create(); + sc.setParameters("lastUpdated",cutDate); + sc.setParameters("jobStatus", JobInfo.Status.IN_PROGRESS); - expunge(sc); + expunge(sc); + */ + Transaction.execute(new TransactionCallbackNoReturn() { + @Override + public void doInTransactionWithoutResult(TransactionStatus status) { + TransactionLegacy txn = TransactionLegacy.currentTxn(); + + PreparedStatement pstmt = null; + try { + pstmt = txn.prepareAutoCloseStatement( + "DELETE FROM vm_work_job WHERE id IN (SELECT id FROM async_job WHERE job_dispatcher='VmWorkJobDispatcher' AND job_status != 0 AND last_updated < ?)"); + pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate)); + + pstmt.execute(); + } catch (SQLException e) { + } catch (Throwable e) { + } + + try { + pstmt = txn.prepareAutoCloseStatement( + "DELETE FROM async_job WHERE job_dispatcher='VmWorkJobDispatcher' AND job_status != 0 AND last_updated < ?"); + pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate)); + + pstmt.execute(); + } catch (SQLException e) { + } catch (Throwable e) { + } + } + }); + } + + @Override + public void expungeLeftoverWorkJobs(final long msid) { + // current DAO machenism does not support following usage + /* + SearchCriteria sc = ExpungePlaceHolderWorkJobSearch.create(); + sc.setParameters("dispatcher", "VmWorkJobPlaceHolder"); + sc.setParameters("msid", msid); + + expunge(sc); + */ + Transaction.execute(new TransactionCallbackNoReturn() { + @Override + public void doInTransactionWithoutResult(TransactionStatus status) { + TransactionLegacy txn = TransactionLegacy.currentTxn(); + + PreparedStatement pstmt = null; + try { + pstmt = txn.prepareAutoCloseStatement( + "DELETE FROM vm_work_job WHERE id IN (SELECT id FROM async_job WHERE (job_dispatcher='VmWorkJobPlaceHolder' OR job_dispatcher='VmWorkJobDispatcher') AND job_init_msid=?)"); + pstmt.setLong(1, msid); + + pstmt.execute(); + } catch (SQLException e) { + } catch (Throwable e) { + } + + try { + pstmt = txn.prepareAutoCloseStatement( + "DELETE FROM async_job WHERE (job_dispatcher='VmWorkJobPlaceHolder' OR job_dispatcher='VmWorkJobDispatcher') AND job_init_msid=?"); + pstmt.setLong(1, msid); + + pstmt.execute(); + } catch (SQLException e) { + } catch (Throwable e) { + } + } + }); } } diff --git a/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java b/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java index 39f48188fc0..c3ac0e67b8f 100644 --- a/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java +++ b/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java @@ -17,6 +17,7 @@ package org.apache.cloudstack.framework.jobs.impl; +import java.io.Serializable; import java.util.Arrays; import java.util.Collections; import java.util.Date; @@ -240,6 +241,8 @@ public class AsyncJobManagerImpl extends ManagerBase implements AsyncJobManager, if (resultObject != null) { job.setResult(resultObject); + } else { + job.setResult(null); } job.setLastUpdated(DateUtil.currentGMTTime()); @@ -472,7 +475,9 @@ public class AsyncJobManagerImpl extends ManagerBase implements AsyncJobManager, if (jobDispatcher != null) { jobDispatcher.runJob(job); } else { - s_logger.error("Unable to find a wakeup dispatcher from the joined job: " + job); + // TODO, job wakeup is not in use yet + if (s_logger.isTraceEnabled()) + s_logger.trace("Unable to find a wakeup dispatcher from the joined job: " + job); } } else { AsyncJobDispatcher jobDispatcher = getDispatcher(job.getDispatcher()); @@ -593,7 +598,7 @@ public class AsyncJobManagerImpl extends ManagerBase implements AsyncJobManager, msgDetector.open(_messageBus, topics); try { long startTick = System.currentTimeMillis(); - while (System.currentTimeMillis() - startTick < timeoutInMiliseconds) { + while (timeoutInMiliseconds < 0 || System.currentTimeMillis() - startTick < timeoutInMiliseconds) { msgDetector.waitAny(checkIntervalInMilliSeconds); job = _jobDao.findById(job.getId()); if (job.getStatus().done()) { @@ -611,6 +616,21 @@ public class AsyncJobManagerImpl extends ManagerBase implements AsyncJobManager, return false; } + @Override + public String marshallResultObject(Serializable obj) { + if (obj != null) + return JobSerializerHelper.toObjectSerializedString(obj); + + return null; + } + + @Override + public Object unmarshallResultObject(AsyncJob job) { + if(job.getResult() != null) + return JobSerializerHelper.fromObjectSerializedString(job.getResult()); + return null; + } + private void checkQueue(long queueId) { while (true) { try { diff --git a/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/OutcomeImpl.java b/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/OutcomeImpl.java index c65d9c5b3b3..bf7d54a3153 100644 --- a/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/OutcomeImpl.java +++ b/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/OutcomeImpl.java @@ -51,7 +51,9 @@ public class OutcomeImpl implements Outcome { @Override public AsyncJob getJob() { - return _job; + // always reload job so that we retrieve the latest job result + AsyncJob job = s_jobMgr.getAsyncJob(_job.getId()); + return job; } @Override @@ -110,13 +112,11 @@ public class OutcomeImpl implements Outcome { @Override public void execute(Task task) { // TODO Auto-generated method stub - } @Override public void execute(Task task, long wait, TimeUnit unit) { // TODO Auto-generated method stub - } public Predicate getPredicate() { diff --git a/framework/managed-context/src/main/java/org/apache/cloudstack/managed/threadlocal/ManagedThreadLocal.java b/framework/managed-context/src/main/java/org/apache/cloudstack/managed/threadlocal/ManagedThreadLocal.java index 57377bcb0fd..2db3aafcf5c 100644 --- a/framework/managed-context/src/main/java/org/apache/cloudstack/managed/threadlocal/ManagedThreadLocal.java +++ b/framework/managed-context/src/main/java/org/apache/cloudstack/managed/threadlocal/ManagedThreadLocal.java @@ -35,7 +35,7 @@ public class ManagedThreadLocal extends ThreadLocal { } }; - private static boolean VALIDATE_CONTEXT = false; + private static boolean s_validateContext = false; private static final Logger log = LoggerFactory.getLogger(ManagedThreadLocal.class); @SuppressWarnings("unchecked") @@ -70,13 +70,13 @@ public class ManagedThreadLocal extends ThreadLocal { } private static void validateInContext(Object tl) { - if (VALIDATE_CONTEXT && !ManagedContextUtils.isInContext()) { + if (s_validateContext && !ManagedContextUtils.isInContext()) { String msg = "Using a managed thread local in a non managed context this WILL cause errors at runtime. TL [" + tl + "]"; log.error(msg, new IllegalStateException(msg)); } } public static void setValidateInContext(boolean validate) { - VALIDATE_CONTEXT = validate; + s_validateContext = validate; } } diff --git a/framework/pom.xml b/framework/pom.xml index c7e61dffade..505c49e99c4 100644 --- a/framework/pom.xml +++ b/framework/pom.xml @@ -40,5 +40,6 @@ managed-context spring/lifecycle spring/module + security diff --git a/framework/security/pom.xml b/framework/security/pom.xml new file mode 100644 index 00000000000..42627f524a8 --- /dev/null +++ b/framework/security/pom.xml @@ -0,0 +1,60 @@ + + + 4.0.0 + cloud-framework-security + Apache CloudStack Framework - Security + + org.apache.cloudstack + cloudstack-framework + 4.4.0-SNAPSHOT + ../pom.xml + + + + org.apache.cloudstack + cloud-utils + ${project.version} + + + org.apache.cloudstack + cloud-api + ${project.version} + + + org.apache.cloudstack + cloud-framework-ipc + ${project.version} + + + commons-codec + commons-codec + + + org.apache.cloudstack + cloud-framework-db + ${project.version} + + + org.apache.cloudstack + cloud-framework-config + ${project.version} + + + diff --git a/framework/security/resources/META-INF/cloudstack/core/spring-framework-security-core-context.xml b/framework/security/resources/META-INF/cloudstack/core/spring-framework-security-core-context.xml new file mode 100644 index 00000000000..fe05bc11bb8 --- /dev/null +++ b/framework/security/resources/META-INF/cloudstack/core/spring-framework-security-core-context.xml @@ -0,0 +1,32 @@ + + + + + + diff --git a/framework/security/src/org/apache/cloudstack/framework/security/keys/KeysManager.java b/framework/security/src/org/apache/cloudstack/framework/security/keys/KeysManager.java new file mode 100644 index 00000000000..d6d2e0149d2 --- /dev/null +++ b/framework/security/src/org/apache/cloudstack/framework/security/keys/KeysManager.java @@ -0,0 +1,38 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.framework.security.keys; + +import org.apache.cloudstack.framework.config.ConfigKey; + +/** + * + * Started this file to manage keys. Will be needed by other services. + * + */ +public interface KeysManager { + final ConfigKey EncryptionKey = new ConfigKey("Hidden", String.class, "security.encryption.key", null, "base64 encoded key data", false); + final ConfigKey EncryptionIV = new ConfigKey("Hidden", String.class, "security.encryption.iv", null, "base64 encoded IV data", false); + final ConfigKey HashKey = new ConfigKey("Hidden", String.class, "security.hash.key", null, "for generic key-ed hash", false); + + String getEncryptionKey(); + + String getEncryptionIV(); + + void resetEncryptionKeyIV(); + + String getHashKey(); +} diff --git a/framework/security/src/org/apache/cloudstack/framework/security/keys/KeysManagerImpl.java b/framework/security/src/org/apache/cloudstack/framework/security/keys/KeysManagerImpl.java new file mode 100644 index 00000000000..550bd155c95 --- /dev/null +++ b/framework/security/src/org/apache/cloudstack/framework/security/keys/KeysManagerImpl.java @@ -0,0 +1,127 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.framework.security.keys; + +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; + +import javax.inject.Inject; +import javax.net.ssl.KeyManager; + +import org.apache.commons.codec.binary.Base64; +import org.apache.log4j.Logger; + +import org.apache.cloudstack.framework.config.ConfigDepot; +import org.apache.cloudstack.framework.config.ConfigKey; +import org.apache.cloudstack.framework.config.Configurable; +import org.apache.cloudstack.framework.config.dao.ConfigurationDao; +import org.apache.cloudstack.framework.config.impl.ConfigurationVO; + +import com.cloud.utils.db.DB; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +/** + * To be perfectly honest, I'm not sure why we need this class. This used + * to be in ManagementServerImpl. I moved the functionality because it seems + * many features will need this. However, the right thing will be for setup + * and upgrade to take care of key generation. Here, the methods appear to + * mainly be used for dynamic generation. I added this class because after + * talking to Kelven, we think there will be other functionalities we need + * to centralize to this class. We'll see how that works out. + * + * There's multiple problems here that we need to fix. + * - Multiple servers can be generating keys. This is not atomic. + * - The functionality of generating the keys should be moved over to setup/upgrade. + * + */ +public class KeysManagerImpl implements KeysManager, Configurable { + private static final Logger s_logger = Logger.getLogger(KeysManagerImpl.class); + + @Inject + ConfigurationDao _configDao; + @Inject + ConfigDepot _configDepot; + + @Override + public String getHashKey() { + String value = HashKey.value(); + if (value == null) { + _configDepot.set(HashKey, getBase64EncodedRandomKey(128)); + } + + return HashKey.value(); + } + + @Override + public String getEncryptionKey() { + String value = EncryptionKey.value(); + if (value == null) { + _configDepot.set(EncryptionKey, getBase64EncodedRandomKey(128)); + } + return EncryptionKey.value(); + } + + @Override + public String getEncryptionIV() { + String value = EncryptionIV.value(); + if (value == null) { + _configDepot.set(EncryptionIV, getBase64EncodedRandomKey(128)); + } + return EncryptionIV.value(); + } + + private static String getBase64EncodedRandomKey(int nBits) { + SecureRandom random; + try { + random = SecureRandom.getInstance("SHA1PRNG"); + byte[] keyBytes = new byte[nBits / 8]; + random.nextBytes(keyBytes); + return Base64.encodeBase64URLSafeString(keyBytes); + } catch (NoSuchAlgorithmException e) { + s_logger.error("Unhandled exception: ", e); + } + return null; + } + + @Override + @DB + public void resetEncryptionKeyIV() { + + SearchBuilder sb = _configDao.createSearchBuilder(); + sb.and("name1", sb.entity().getName(), SearchCriteria.Op.EQ); + sb.or("name2", sb.entity().getName(), SearchCriteria.Op.EQ); + sb.done(); + + SearchCriteria sc = sb.create(); + sc.setParameters("name1", EncryptionKey.key()); + sc.setParameters("name2", EncryptionIV.key()); + + _configDao.expunge(sc); + } + + @Override + public String getConfigComponentName() { + return KeyManager.class.getSimpleName(); + } + + @Override + public ConfigKey[] getConfigKeys() { + return new ConfigKey[] {EncryptionKey, EncryptionIV, HashKey}; + } + +} diff --git a/engine/schema/src/com/cloud/keystore/KeystoreDao.java b/framework/security/src/org/apache/cloudstack/framework/security/keystore/KeystoreDao.java similarity index 95% rename from engine/schema/src/com/cloud/keystore/KeystoreDao.java rename to framework/security/src/org/apache/cloudstack/framework/security/keystore/KeystoreDao.java index 333eb249ec3..e60e4b004c6 100644 --- a/engine/schema/src/com/cloud/keystore/KeystoreDao.java +++ b/framework/security/src/org/apache/cloudstack/framework/security/keystore/KeystoreDao.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.keystore; +package org.apache.cloudstack.framework.security.keystore; import java.util.List; diff --git a/engine/schema/src/com/cloud/keystore/KeystoreDaoImpl.java b/framework/security/src/org/apache/cloudstack/framework/security/keystore/KeystoreDaoImpl.java similarity index 98% rename from engine/schema/src/com/cloud/keystore/KeystoreDaoImpl.java rename to framework/security/src/org/apache/cloudstack/framework/security/keystore/KeystoreDaoImpl.java index 6c51a26713d..cd24611a86e 100644 --- a/engine/schema/src/com/cloud/keystore/KeystoreDaoImpl.java +++ b/framework/security/src/org/apache/cloudstack/framework/security/keystore/KeystoreDaoImpl.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.keystore; +package org.apache.cloudstack.framework.security.keystore; import java.sql.PreparedStatement; import java.util.Collections; diff --git a/server/src/com/cloud/keystore/KeystoreManager.java b/framework/security/src/org/apache/cloudstack/framework/security/keystore/KeystoreManager.java similarity index 60% rename from server/src/com/cloud/keystore/KeystoreManager.java rename to framework/security/src/org/apache/cloudstack/framework/security/keystore/KeystoreManager.java index 8a7d553bef5..3b99947c4b5 100644 --- a/server/src/com/cloud/keystore/KeystoreManager.java +++ b/framework/security/src/org/apache/cloudstack/framework/security/keystore/KeystoreManager.java @@ -14,12 +14,44 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.keystore; +package org.apache.cloudstack.framework.security.keystore; -import com.cloud.agent.api.SecStorageSetupCommand.Certificates; +import com.cloud.agent.api.LogLevel; +import com.cloud.agent.api.LogLevel.Log4jLevel; import com.cloud.utils.component.Manager; public interface KeystoreManager extends Manager { + public static class Certificates { + @LogLevel(Log4jLevel.Off) + private String privKey; + @LogLevel(Log4jLevel.Off) + private String privCert; + @LogLevel(Log4jLevel.Off) + private String certChain; + + public Certificates() { + + } + + public Certificates(String prvKey, String privCert, String certChain) { + privKey = prvKey; + this.privCert = privCert; + this.certChain = certChain; + } + + public String getPrivKey() { + return privKey; + } + + public String getPrivCert() { + return privCert; + } + + public String getCertChain() { + return certChain; + } + } + boolean validateCertificate(String certificate, String key, String domainSuffix); void saveCertificate(String name, String certificate, String key, String domainSuffix); diff --git a/server/src/com/cloud/keystore/KeystoreManagerImpl.java b/framework/security/src/org/apache/cloudstack/framework/security/keystore/KeystoreManagerImpl.java similarity index 95% rename from server/src/com/cloud/keystore/KeystoreManagerImpl.java rename to framework/security/src/org/apache/cloudstack/framework/security/keystore/KeystoreManagerImpl.java index 2b798fe094c..306083492af 100644 --- a/server/src/com/cloud/keystore/KeystoreManagerImpl.java +++ b/framework/security/src/org/apache/cloudstack/framework/security/keystore/KeystoreManagerImpl.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.keystore; +package org.apache.cloudstack.framework.security.keystore; import java.io.IOException; import java.security.KeyStore; @@ -33,7 +33,6 @@ import javax.inject.Inject; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.agent.api.SecStorageSetupCommand; import com.cloud.utils.Ternary; import com.cloud.utils.component.ManagerBase; import com.cloud.utils.exception.CloudRuntimeException; @@ -123,7 +122,7 @@ public class KeystoreManagerImpl extends ManagerBase implements KeystoreManager } @Override - public SecStorageSetupCommand.Certificates getCertificates(String name) { + public Certificates getCertificates(String name) { KeystoreVO ksVo = _ksDao.findByName(name); if (ksVo == null) { return null; @@ -140,7 +139,7 @@ public class KeystoreManagerImpl extends ManagerBase implements KeystoreManager } certChain = chains.toString(); } - SecStorageSetupCommand.Certificates certs = new SecStorageSetupCommand.Certificates(prvKey, prvCert, certChain); + Certificates certs = new Certificates(prvKey, prvCert, certChain); return certs; } diff --git a/engine/schema/src/com/cloud/keystore/KeystoreVO.java b/framework/security/src/org/apache/cloudstack/framework/security/keystore/KeystoreVO.java similarity index 97% rename from engine/schema/src/com/cloud/keystore/KeystoreVO.java rename to framework/security/src/org/apache/cloudstack/framework/security/keystore/KeystoreVO.java index 66dfac10058..2e4b9febd9d 100644 --- a/engine/schema/src/com/cloud/keystore/KeystoreVO.java +++ b/framework/security/src/org/apache/cloudstack/framework/security/keystore/KeystoreVO.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.keystore; +package org.apache.cloudstack.framework.security.keystore; import javax.persistence.Column; import javax.persistence.Entity; diff --git a/framework/spring/lifecycle/src/main/java/org/apache/cloudstack/spring/lifecycle/registry/ExtensionRegistry.java b/framework/spring/lifecycle/src/main/java/org/apache/cloudstack/spring/lifecycle/registry/ExtensionRegistry.java index 6927d2f5fda..321e365e2c1 100644 --- a/framework/spring/lifecycle/src/main/java/org/apache/cloudstack/spring/lifecycle/registry/ExtensionRegistry.java +++ b/framework/spring/lifecycle/src/main/java/org/apache/cloudstack/spring/lifecycle/registry/ExtensionRegistry.java @@ -159,7 +159,6 @@ public class ExtensionRegistry implements Registry, Configurable, BeanNa if (name == null) { for (String part : beanName.replaceAll("([A-Z])", " $1").split("\\s+")) { part = StringUtils.capitalize(part.toLowerCase()); - ; name = name == null ? part : name + " " + part; } @@ -219,7 +218,7 @@ public class ExtensionRegistry implements Registry, Configurable, BeanNa @Override public void setBeanName(String name) { - this.beanName = name; + beanName = name; } public List getPreRegistered() { diff --git a/framework/spring/module/pom.xml b/framework/spring/module/pom.xml index 14bcfbef6f7..33196a73ec2 100644 --- a/framework/spring/module/pom.xml +++ b/framework/spring/module/pom.xml @@ -20,6 +20,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 cloud-framework-spring-module + Apache CloudStack Framework - Spring Module org.apache.cloudstack cloud-maven-standard diff --git a/packaging/centos63/cloud.spec b/packaging/centos63/cloud.spec index 893628d55d2..83c598b07a7 100644 --- a/packaging/centos63/cloud.spec +++ b/packaging/centos63/cloud.spec @@ -43,7 +43,7 @@ Group: System Environment/Libraries Source0: %{name}-%{_maventag}.tgz BuildRoot: %{_tmppath}/%{name}-%{_maventag}-%{release}-build -BuildRequires: java-1.6.0-openjdk-devel +BuildRequires: java-1.7.0-openjdk-devel BuildRequires: tomcat6 BuildRequires: ws-commons-util BuildRequires: jpackage-utils @@ -60,7 +60,7 @@ intelligent IaaS cloud implementation. %package management Summary: CloudStack management server UI Requires: tomcat6 -Requires: java >= 1.6.0 +Requires: java >= 1.7.0 Requires: python Requires: bash Requires: bzip2 @@ -111,7 +111,8 @@ The Apache CloudStack files shared between agent and management server %package agent Summary: CloudStack Agent for KVM hypervisors -Requires: java >= 1.6.0 +Requires: openssh-clients +Requires: java >= 1.7.0 Requires: %{name}-common = %{_ver} Requires: libvirt Requires: bridge-utils @@ -125,6 +126,8 @@ Requires: jakarta-commons-daemon Requires: jakarta-commons-daemon-jsvc Requires: perl Requires: libvirt-python +Requires: qemu-img +Requires: qemu-kvm Provides: cloud-agent Obsoletes: cloud-agent < 4.1.0 Obsoletes: cloud-agent-libs < 4.1.0 @@ -135,7 +138,7 @@ The CloudStack agent for KVM hypervisors %package usage Summary: CloudStack Usage calculation server -Requires: java >= 1.6.0 +Requires: java >= 1.7.0 Requires: jsvc Requires: jakarta-commons-daemon Requires: jakarta-commons-daemon-jsvc diff --git a/parents/checkstyle/pom.xml b/parents/checkstyle/pom.xml deleted file mode 100644 index 3e4a28b9802..00000000000 --- a/parents/checkstyle/pom.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - 4.0.0 - Apache CloudStack Checkstyle Configuration - checkstyle - - org.apache.cloudstack - cloud-maven-standard - 4.4.0-SNAPSHOT - ../../maven-standard/pom.xml - - diff --git a/parents/checkstyle/src/main/resources/tooling/checkstyle.xml b/parents/checkstyle/src/main/resources/tooling/checkstyle.xml deleted file mode 100644 index 289ad6778e8..00000000000 --- a/parents/checkstyle/src/main/resources/tooling/checkstyle.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java b/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java index de14007aaf1..1316a92ccb1 100644 --- a/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java +++ b/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java @@ -125,8 +125,8 @@ public class StaticRoleBasedAPIAccessChecker extends AdapterBase implements APIC } @Inject - public void setServices(List _services) { - this._services = _services; + public void setServices(List services) { + this._services = services; } } diff --git a/plugins/api/discovery/src/org/apache/cloudstack/discovery/ApiDiscoveryServiceImpl.java b/plugins/api/discovery/src/org/apache/cloudstack/discovery/ApiDiscoveryServiceImpl.java index 39d965d810c..cb691a9c8ed 100755 --- a/plugins/api/discovery/src/org/apache/cloudstack/discovery/ApiDiscoveryServiceImpl.java +++ b/plugins/api/discovery/src/org/apache/cloudstack/discovery/ApiDiscoveryServiceImpl.java @@ -262,8 +262,8 @@ public class ApiDiscoveryServiceImpl extends ComponentLifecycleBase implements A return _apiAccessCheckers; } - public void setApiAccessCheckers(List _apiAccessCheckers) { - this._apiAccessCheckers = _apiAccessCheckers; + public void setApiAccessCheckers(List apiAccessCheckers) { + this._apiAccessCheckers = apiAccessCheckers; } public List getServices() { @@ -271,7 +271,7 @@ public class ApiDiscoveryServiceImpl extends ComponentLifecycleBase implements A } @Inject - public void setServices(List _services) { - this._services = _services; + public void setServices(List services) { + this._services = services; } } diff --git a/plugins/api/discovery/test/org/apache/cloudstack/discovery/ApiDiscoveryTest.java b/plugins/api/discovery/test/org/apache/cloudstack/discovery/ApiDiscoveryTest.java index f861ae986b0..30cb0bc87ae 100644 --- a/plugins/api/discovery/test/org/apache/cloudstack/discovery/ApiDiscoveryTest.java +++ b/plugins/api/discovery/test/org/apache/cloudstack/discovery/ApiDiscoveryTest.java @@ -46,9 +46,9 @@ import com.cloud.user.UserVO; import com.cloud.utils.component.PluggableService; public class ApiDiscoveryTest { - private static APIChecker _apiChecker = mock(APIChecker.class); - private static PluggableService _pluggableService = mock(PluggableService.class); - private static ApiDiscoveryServiceImpl _discoveryService = new ApiDiscoveryServiceImpl(); + private static APIChecker s_apiChecker = mock(APIChecker.class); + private static PluggableService s_pluggableService = mock(PluggableService.class); + private static ApiDiscoveryServiceImpl s_discoveryService = new ApiDiscoveryServiceImpl(); private static Class testCmdClass = ListApisCmd.class; private static User testUser; @@ -65,23 +65,23 @@ public class ApiDiscoveryTest { testApiAsync = false; testUser = new UserVO(); - _discoveryService._apiAccessCheckers = mock(List.class); - _discoveryService._services = mock(List.class); + s_discoveryService._apiAccessCheckers = mock(List.class); + s_discoveryService._services = mock(List.class); - when(_apiChecker.checkAccess(any(User.class), anyString())).thenReturn(true); - when(_pluggableService.getCommands()).thenReturn(new ArrayList>()); - when(_discoveryService._apiAccessCheckers.iterator()).thenReturn(Arrays.asList(_apiChecker).iterator()); - when(_discoveryService._services.iterator()).thenReturn(Arrays.asList(_pluggableService).iterator()); + when(s_apiChecker.checkAccess(any(User.class), anyString())).thenReturn(true); + when(s_pluggableService.getCommands()).thenReturn(new ArrayList>()); + when(s_discoveryService._apiAccessCheckers.iterator()).thenReturn(Arrays.asList(s_apiChecker).iterator()); + when(s_discoveryService._services.iterator()).thenReturn(Arrays.asList(s_pluggableService).iterator()); Set> cmdClasses = new HashSet>(); cmdClasses.add(ListApisCmd.class); - _discoveryService.start(); - _discoveryService.cacheResponseMap(cmdClasses); + s_discoveryService.start(); + s_discoveryService.cacheResponseMap(cmdClasses); } @Test public void verifyListSingleApi() throws Exception { - ListResponse responses = (ListResponse)_discoveryService.listApis(testUser, testApiName); + ListResponse responses = (ListResponse)s_discoveryService.listApis(testUser, testApiName); ApiDiscoveryResponse response = responses.getResponses().get(0); assertTrue("No. of response items should be one", responses.getCount() == 1); assertEquals("Error in api name", testApiName, response.getName()); @@ -92,7 +92,7 @@ public class ApiDiscoveryTest { @Test public void verifyListApis() throws Exception { - ListResponse responses = (ListResponse)_discoveryService.listApis(testUser, null); + ListResponse responses = (ListResponse)s_discoveryService.listApis(testUser, null); assertTrue("No. of response items > 1", responses.getCount() == 1); for (ApiDiscoveryResponse response : responses.getResponses()) { assertFalse("API name is empty", response.getName().isEmpty()); diff --git a/plugins/api/rate-limit/test/org/apache/cloudstack/ratelimit/ApiRateLimitTest.java b/plugins/api/rate-limit/test/org/apache/cloudstack/ratelimit/ApiRateLimitTest.java index c90704258e9..0091b15b10d 100644 --- a/plugins/api/rate-limit/test/org/apache/cloudstack/ratelimit/ApiRateLimitTest.java +++ b/plugins/api/rate-limit/test/org/apache/cloudstack/ratelimit/ApiRateLimitTest.java @@ -46,50 +46,50 @@ import com.cloud.user.UserVO; public class ApiRateLimitTest { - static ApiRateLimitServiceImpl _limitService = new ApiRateLimitServiceImpl(); - static AccountService _accountService = mock(AccountService.class); - static ConfigurationDao _configDao = mock(ConfigurationDao.class); - private static long acctIdSeq = 5L; - private static Account testAccount; + static ApiRateLimitServiceImpl s_limitService = new ApiRateLimitServiceImpl(); + static AccountService s_accountService = mock(AccountService.class); + static ConfigurationDao s_configDao = mock(ConfigurationDao.class); + private static long s_acctIdSeq = 5L; + private static Account s_testAccount; @BeforeClass public static void setUp() throws ConfigurationException { - when(_configDao.getValue(Config.ApiLimitInterval.key())).thenReturn(null); - when(_configDao.getValue(Config.ApiLimitMax.key())).thenReturn(null); - when(_configDao.getValue(Config.ApiLimitCacheSize.key())).thenReturn(null); - when(_configDao.getValue(Config.ApiLimitEnabled.key())).thenReturn("true"); // enable api rate limiting - _limitService._configDao = _configDao; + when(s_configDao.getValue(Config.ApiLimitInterval.key())).thenReturn(null); + when(s_configDao.getValue(Config.ApiLimitMax.key())).thenReturn(null); + when(s_configDao.getValue(Config.ApiLimitCacheSize.key())).thenReturn(null); + when(s_configDao.getValue(Config.ApiLimitEnabled.key())).thenReturn("true"); // enable api rate limiting + s_limitService._configDao = s_configDao; - _limitService.configure("ApiRateLimitTest", Collections. emptyMap()); + s_limitService.configure("ApiRateLimitTest", Collections. emptyMap()); - _limitService._accountService = _accountService; + s_limitService._accountService = s_accountService; // Standard responses - AccountVO acct = new AccountVO(acctIdSeq); + AccountVO acct = new AccountVO(s_acctIdSeq); acct.setType(Account.ACCOUNT_TYPE_NORMAL); acct.setAccountName("demo"); - testAccount = acct; + s_testAccount = acct; - when(_accountService.getAccount(5L)).thenReturn(testAccount); - when(_accountService.isRootAdmin(Account.ACCOUNT_TYPE_NORMAL)).thenReturn(false); + when(s_accountService.getAccount(5L)).thenReturn(s_testAccount); + when(s_accountService.isRootAdmin(Account.ACCOUNT_TYPE_NORMAL)).thenReturn(false); } @Before public void testSetUp() { // reset counter for each test - _limitService.resetApiLimit(null); + s_limitService.resetApiLimit(null); } private User createFakeUser() { UserVO user = new UserVO(); - user.setAccountId(acctIdSeq); + user.setAccountId(s_acctIdSeq); return user; } private boolean isUnderLimit(User key) { try { - _limitService.checkAccess(key, null); + s_limitService.checkAccess(key, null); return true; } catch (RequestLimitException ex) { return false; @@ -99,8 +99,8 @@ public class ApiRateLimitTest { @Test public void sequentialApiAccess() { int allowedRequests = 1; - _limitService.setMaxAllowed(allowedRequests); - _limitService.setTimeToLive(1); + s_limitService.setMaxAllowed(allowedRequests); + s_limitService.setTimeToLive(1); User key = createFakeUser(); assertTrue("Allow for the first request", isUnderLimit(key)); @@ -111,8 +111,8 @@ public class ApiRateLimitTest { @Test public void canDoReasonableNumberOfApiAccessPerSecond() throws Exception { int allowedRequests = 200; - _limitService.setMaxAllowed(allowedRequests); - _limitService.setTimeToLive(1); + s_limitService.setMaxAllowed(allowedRequests); + s_limitService.setTimeToLive(1); User key = createFakeUser(); @@ -126,8 +126,8 @@ public class ApiRateLimitTest { @Test public void multipleClientsCanAccessWithoutBlocking() throws Exception { int allowedRequests = 200; - _limitService.setMaxAllowed(allowedRequests); - _limitService.setTimeToLive(1); + s_limitService.setMaxAllowed(allowedRequests); + s_limitService.setTimeToLive(1); final User key = createFakeUser(); @@ -180,8 +180,8 @@ public class ApiRateLimitTest { @Test public void expiryOfCounterIsSupported() throws Exception { int allowedRequests = 1; - _limitService.setMaxAllowed(allowedRequests); - _limitService.setTimeToLive(1); + s_limitService.setMaxAllowed(allowedRequests); + s_limitService.setTimeToLive(1); User key = this.createFakeUser(); @@ -196,8 +196,8 @@ public class ApiRateLimitTest { @Test public void verifyResetCounters() throws Exception { int allowedRequests = 1; - _limitService.setMaxAllowed(allowedRequests); - _limitService.setTimeToLive(1); + s_limitService.setMaxAllowed(allowedRequests); + s_limitService.setTimeToLive(1); User key = this.createFakeUser(); @@ -205,7 +205,7 @@ public class ApiRateLimitTest { assertFalse("Another request should be blocked", isUnderLimit(key)); - _limitService.resetApiLimit(key.getAccountId()); + s_limitService.resetApiLimit(key.getAccountId()); assertTrue("Another request should be allowed after reset counter", isUnderLimit(key)); } @@ -213,8 +213,8 @@ public class ApiRateLimitTest { @Test public void verifySearchCounter() throws Exception { int allowedRequests = 10; - _limitService.setMaxAllowed(allowedRequests); - _limitService.setTimeToLive(1); + s_limitService.setMaxAllowed(allowedRequests); + s_limitService.setTimeToLive(1); User key = this.createFakeUser(); @@ -222,7 +222,7 @@ public class ApiRateLimitTest { assertTrue("Issued 5 requests", isUnderLimit(key)); } - ApiLimitResponse response = _limitService.searchApiLimit(testAccount); + ApiLimitResponse response = s_limitService.searchApiLimit(s_testAccount); assertEquals("apiIssued is incorrect", 5, response.getApiIssued()); assertEquals("apiAllowed is incorrect", 5, response.getApiAllowed()); // using <= to account for inaccurate System.currentTimeMillis() clock in Windows environment @@ -234,9 +234,9 @@ public class ApiRateLimitTest { public void disableApiLimit() throws Exception { try { int allowedRequests = 200; - _limitService.setMaxAllowed(allowedRequests); - _limitService.setTimeToLive(1); - _limitService.setEnabled(false); + s_limitService.setMaxAllowed(allowedRequests); + s_limitService.setTimeToLive(1); + s_limitService.setEnabled(false); User key = createFakeUser(); @@ -244,7 +244,7 @@ public class ApiRateLimitTest { assertTrue("We should allow more than " + allowedRequests + " requests per second when api throttling is disabled.", isUnderLimit(key)); } } finally { - _limitService.setEnabled(true); // enable api throttling to avoid + s_limitService.setEnabled(true); // enable api throttling to avoid // impacting other testcases } diff --git a/plugins/deployment-planners/implicit-dedication/test/org/apache/cloudstack/implicitplanner/ImplicitPlannerTest.java b/plugins/deployment-planners/implicit-dedication/test/org/apache/cloudstack/implicitplanner/ImplicitPlannerTest.java index 110fd7b4437..4182193a17f 100644 --- a/plugins/deployment-planners/implicit-dedication/test/org/apache/cloudstack/implicitplanner/ImplicitPlannerTest.java +++ b/plugins/deployment-planners/implicit-dedication/test/org/apache/cloudstack/implicitplanner/ImplicitPlannerTest.java @@ -59,7 +59,6 @@ import org.apache.cloudstack.test.utils.SpringUtils; import com.cloud.capacity.Capacity; import com.cloud.capacity.CapacityManager; -import com.cloud.capacity.CapacityVO; import com.cloud.capacity.dao.CapacityDao; import com.cloud.dc.ClusterDetailsDao; import com.cloud.dc.DataCenterVO; diff --git a/plugins/event-bus/inmemory/pom.xml b/plugins/event-bus/inmemory/pom.xml new file mode 100644 index 00000000000..1bde8b8d843 --- /dev/null +++ b/plugins/event-bus/inmemory/pom.xml @@ -0,0 +1,40 @@ + + + 4.0.0 + cloud-mom-inmemory + Apache CloudStack Plugin - In Memory Event Bus + + org.apache.cloudstack + cloudstack-plugins + 4.4.0-SNAPSHOT + ../../pom.xml + + + + org.apache.cloudstack + cloud-framework-events + ${project.version} + + + + install + + diff --git a/plugins/event-bus/inmemory/src/org/apache/cloudstack/mom/inmemory/InMemoryEventBus.java b/plugins/event-bus/inmemory/src/org/apache/cloudstack/mom/inmemory/InMemoryEventBus.java new file mode 100644 index 00000000000..99d0a12eb3b --- /dev/null +++ b/plugins/event-bus/inmemory/src/org/apache/cloudstack/mom/inmemory/InMemoryEventBus.java @@ -0,0 +1,163 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.cloudstack.mom.inmemory; + +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; + +import com.cloud.utils.Pair; +import org.apache.log4j.Logger; + +import org.apache.cloudstack.framework.events.Event; +import org.apache.cloudstack.framework.events.EventBus; +import org.apache.cloudstack.framework.events.EventBusException; +import org.apache.cloudstack.framework.events.EventSubscriber; +import org.apache.cloudstack.framework.events.EventTopic; + +import com.cloud.utils.component.ManagerBase; + +@Local(value = EventBus.class) +public class InMemoryEventBus extends ManagerBase implements EventBus { + + private String name; + private static final Logger s_logger = Logger.getLogger(InMemoryEventBus.class); + private static ConcurrentHashMap> s_subscribers; + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + s_subscribers = new ConcurrentHashMap>(); + return true; + } + + @Override + public void setName(String name) { + this.name = name; + } + + @Override + public UUID subscribe(EventTopic topic, EventSubscriber subscriber) throws EventBusException { + if (subscriber == null || topic == null) { + throw new EventBusException("Invalid EventSubscriber/EventTopic object passed."); + } + UUID subscriberId = UUID.randomUUID(); + + s_subscribers.put(subscriberId, new Pair(topic, subscriber)); + return subscriberId; + } + + @Override + public void unsubscribe(UUID subscriberId, EventSubscriber subscriber) throws EventBusException { + if (s_subscribers != null && s_subscribers.isEmpty()) { + throw new EventBusException("There are no registered subscribers to unregister."); + } + if (s_subscribers.get(subscriberId) == null) { + throw new EventBusException("No subscriber found with subscriber id " + subscriberId); + } + s_subscribers.remove(subscriberId); + } + + @Override + public void publish(Event event) throws EventBusException { + if (s_subscribers == null || s_subscribers.isEmpty()) { + return; // no subscriber to publish to, so just return + } + + for (UUID subscriberId : s_subscribers.keySet()) { + Pair subscriberDetails = s_subscribers.get(subscriberId); + // if the event matches subscribers interested event topic then call back the subscriber with the event + if (isEventMatchesTopic(event, subscriberDetails.first())) { + EventSubscriber subscriber = subscriberDetails.second(); + subscriber.onEvent(event); + } + } + } + + @Override + public String getName() { + return _name; + } + + @Override + public boolean start() { + return true; + } + + @Override + public boolean stop() { + return true; + } + + private String replaceNullWithWildcard(String key) { + if (key == null || key.isEmpty()) { + return "*"; + } else { + return key; + } + } + + private boolean isEventMatchesTopic(Event event, EventTopic topic) { + + String eventTopicSource = replaceNullWithWildcard(topic.getEventSource()); + eventTopicSource = eventTopicSource.replace(".", "-"); + String eventSource = replaceNullWithWildcard(event.getEventSource()); + eventSource = eventSource.replace(".", "-"); + if (eventTopicSource != "*" && eventSource != "*" && !eventTopicSource.equalsIgnoreCase(eventSource)) { + return false; + } + + String eventTopicCategory = replaceNullWithWildcard(topic.getEventCategory()); + eventTopicCategory = eventTopicCategory.replace(".", "-"); + String eventCategory = replaceNullWithWildcard(event.getEventCategory()); + eventCategory = eventCategory.replace(".", "-"); + if (eventTopicCategory != "*" && eventCategory != "*" && !eventTopicCategory.equalsIgnoreCase(eventCategory)) { + return false; + } + + String eventTopicType = replaceNullWithWildcard(topic.getEventType()); + eventTopicType = eventTopicType.replace(".", "-"); + String eventType = replaceNullWithWildcard(event.getEventType()); + eventType = eventType.replace(".", "-"); + if (eventTopicType != "*" && eventType != "*" && !eventTopicType.equalsIgnoreCase(eventType)) { + return false; + } + + String eventTopicResourceType = replaceNullWithWildcard(topic.getResourceType()); + eventTopicResourceType = eventTopicResourceType.replace(".", "-"); + String resourceType = replaceNullWithWildcard(event.getResourceType()); + resourceType = resourceType.replace(".", "-"); + if (eventTopicResourceType != "*" && resourceType != "*" && !eventTopicResourceType.equalsIgnoreCase(resourceType)) { + return false; + } + + String resourceUuid = replaceNullWithWildcard(event.getResourceUUID()); + resourceUuid = resourceUuid.replace(".", "-"); + String eventTopicresourceUuid = replaceNullWithWildcard(topic.getResourceUUID()); + eventTopicresourceUuid = eventTopicresourceUuid.replace(".", "-"); + if (resourceUuid != "*" && eventTopicresourceUuid != "*" && !resourceUuid.equalsIgnoreCase(eventTopicresourceUuid)) { + return false; + } + + return true; + } +} diff --git a/plugins/event-bus/rabbitmq/src/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java b/plugins/event-bus/rabbitmq/src/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java index c1a4ee2bb98..8ad7033400b 100644 --- a/plugins/event-bus/rabbitmq/src/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java +++ b/plugins/event-bus/rabbitmq/src/org/apache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java @@ -70,13 +70,13 @@ public class RabbitMQEventBus extends ManagerBase implements EventBus { private static Integer retryInterval; // hashmap to book keep the registered subscribers - private static ConcurrentHashMap> _subscribers; + private static ConcurrentHashMap> s_subscribers; // connection to AMQP server, - private static Connection _connection = null; + private static Connection s_connection = null; // AMQP server should consider messages acknowledged once delivered if _autoAck is true - private static boolean _autoAck = true; + private static boolean s_autoAck = true; private ExecutorService executorService; private static DisconnectHandler disconnectHandler; @@ -114,7 +114,7 @@ public class RabbitMQEventBus extends ManagerBase implements EventBus { throw new ConfigurationException("Invalid port number/retry interval"); } - _subscribers = new ConcurrentHashMap>(); + s_subscribers = new ConcurrentHashMap>(); executorService = Executors.newCachedThreadPool(); disconnectHandler = new DisconnectHandler(); @@ -173,7 +173,7 @@ public class RabbitMQEventBus extends ManagerBase implements EventBus { String bindingKey = createBindingKey(topic); // store the subscriber details before creating channel - _subscribers.put(queueName, new Ternary(bindingKey, null, subscriber)); + s_subscribers.put(queueName, new Ternary(bindingKey, null, subscriber)); // create a channel dedicated for this subscription Connection connection = getConnection(); @@ -185,10 +185,10 @@ public class RabbitMQEventBus extends ManagerBase implements EventBus { channel.queueBind(queueName, amqpExchangeName, bindingKey); // register a callback handler to receive the events that a subscriber subscribed to - channel.basicConsume(queueName, _autoAck, queueName, new DefaultConsumer(channel) { + channel.basicConsume(queueName, s_autoAck, queueName, new DefaultConsumer(channel) { @Override public void handleDelivery(String queueName, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { - Ternary queueDetails = _subscribers.get(queueName); + Ternary queueDetails = s_subscribers.get(queueName); if (queueDetails != null) { EventSubscriber subscriber = queueDetails.third(); String routingKey = envelope.getRoutingKey(); @@ -207,9 +207,9 @@ public class RabbitMQEventBus extends ManagerBase implements EventBus { }); // update the channel details for the subscription - Ternary queueDetails = _subscribers.get(queueName); + Ternary queueDetails = s_subscribers.get(queueName); queueDetails.second(channel); - _subscribers.put(queueName, queueDetails); + s_subscribers.put(queueName, queueDetails); } catch (AlreadyClosedException closedException) { s_logger.warn("Connection to AMQP service is lost. Subscription:" + queueName + " will be active after reconnection"); @@ -227,10 +227,10 @@ public class RabbitMQEventBus extends ManagerBase implements EventBus { try { String classname = subscriber.getClass().getName(); String queueName = UUID.nameUUIDFromBytes(classname.getBytes()).toString(); - Ternary queueDetails = _subscribers.get(queueName); + Ternary queueDetails = s_subscribers.get(queueName); Channel channel = queueDetails.second(); channel.basicCancel(queueName); - _subscribers.remove(queueName, queueDetails); + s_subscribers.remove(queueName, queueDetails); } catch (Exception e) { throw new EventBusException("Failed to unsubscribe from event bus due to " + e.getMessage()); } @@ -330,7 +330,7 @@ public class RabbitMQEventBus extends ManagerBase implements EventBus { } private synchronized Connection getConnection() throws Exception { - if (_connection == null) { + if (s_connection == null) { try { return createConnection(); } catch (Exception e) { @@ -338,7 +338,7 @@ public class RabbitMQEventBus extends ManagerBase implements EventBus { throw e; } } else { - return _connection; + return s_connection; } } @@ -352,8 +352,8 @@ public class RabbitMQEventBus extends ManagerBase implements EventBus { factory.setPort(port); Connection connection = factory.newConnection(); connection.addShutdownListener(disconnectHandler); - _connection = connection; - return _connection; + s_connection = connection; + return s_connection; } catch (Exception e) { throw e; } @@ -361,25 +361,25 @@ public class RabbitMQEventBus extends ManagerBase implements EventBus { private synchronized void closeConnection() { try { - if (_connection != null) { - _connection.close(); + if (s_connection != null) { + s_connection.close(); } } catch (Exception e) { s_logger.warn("Failed to close connection to AMQP server due to " + e.getMessage()); } - _connection = null; + s_connection = null; } private synchronized void abortConnection() { - if (_connection == null) + if (s_connection == null) return; try { - _connection.abort(); + s_connection.abort(); } catch (Exception e) { s_logger.warn("Failed to abort connection due to " + e.getMessage()); } - _connection = null; + s_connection = null; } private String replaceNullWithWildcard(String key) { @@ -458,9 +458,9 @@ public class RabbitMQEventBus extends ManagerBase implements EventBus { @Override public boolean stop() { - if (_connection.isOpen()) { - for (String subscriberId : _subscribers.keySet()) { - Ternary subscriberDetails = _subscribers.get(subscriberId); + if (s_connection.isOpen()) { + for (String subscriberId : s_subscribers.keySet()) { + Ternary subscriberDetails = s_subscribers.get(subscriberId); Channel channel = subscriberDetails.second(); String queueName = subscriberId; try { @@ -483,10 +483,10 @@ public class RabbitMQEventBus extends ManagerBase implements EventBus { public void shutdownCompleted(ShutdownSignalException shutdownSignalException) { if (!shutdownSignalException.isInitiatedByApplication()) { - for (String subscriberId : _subscribers.keySet()) { - Ternary subscriberDetails = _subscribers.get(subscriberId); + for (String subscriberId : s_subscribers.keySet()) { + Ternary subscriberDetails = s_subscribers.get(subscriberId); subscriberDetails.second(null); - _subscribers.put(subscriberId, subscriberDetails); + s_subscribers.put(subscriberId, subscriberDetails); } abortConnection(); // disconnected to AMQP server, so abort the connection and channels @@ -524,8 +524,8 @@ public class RabbitMQEventBus extends ManagerBase implements EventBus { } // prepare consumer on AMQP server for each of subscriber - for (String subscriberId : _subscribers.keySet()) { - Ternary subscriberDetails = _subscribers.get(subscriberId); + for (String subscriberId : s_subscribers.keySet()) { + Ternary subscriberDetails = s_subscribers.get(subscriberId); String bindingKey = subscriberDetails.first(); EventSubscriber subscriber = subscriberDetails.third(); @@ -538,11 +538,11 @@ public class RabbitMQEventBus extends ManagerBase implements EventBus { channel.queueBind(subscriberId, amqpExchangeName, bindingKey); // register a callback handler to receive the events that a subscriber subscribed to - channel.basicConsume(subscriberId, _autoAck, subscriberId, new DefaultConsumer(channel) { + channel.basicConsume(subscriberId, s_autoAck, subscriberId, new DefaultConsumer(channel) { @Override public void handleDelivery(String queueName, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { - Ternary subscriberDetails = _subscribers.get(queueName); // queue name == subscriber ID + Ternary subscriberDetails = s_subscribers.get(queueName); // queue name == subscriber ID if (subscriberDetails != null) { EventSubscriber subscriber = subscriberDetails.third(); @@ -565,7 +565,7 @@ public class RabbitMQEventBus extends ManagerBase implements EventBus { // update the channel details for the subscription subscriberDetails.second(channel); - _subscribers.put(subscriberId, subscriberDetails); + s_subscribers.put(subscriberId, subscriberDetails); } } catch (Exception e) { s_logger.warn("Failed to recreate queues and binding for the subscribers due to " + e.getMessage()); diff --git a/plugins/file-systems/netapp/src/com/cloud/netapp/NetappDefaultAllocatorImpl.java b/plugins/file-systems/netapp/src/com/cloud/netapp/NetappDefaultAllocatorImpl.java index f42be33f27d..01418252ebf 100644 --- a/plugins/file-systems/netapp/src/com/cloud/netapp/NetappDefaultAllocatorImpl.java +++ b/plugins/file-systems/netapp/src/com/cloud/netapp/NetappDefaultAllocatorImpl.java @@ -16,18 +16,15 @@ // under the License. package com.cloud.netapp; -import java.io.IOException; import java.rmi.ServerException; import java.util.HashMap; import java.util.List; -import netapp.manage.NaException; - import org.apache.log4j.Logger; public class NetappDefaultAllocatorImpl implements NetappAllocator { - private static HashMap _poolNameToLastVolumeIdAllocated = new HashMap(); - private NetappManager _netappMgr; + private static HashMap s_poolNameToLastVolumeIdAllocated = new HashMap(); + private final NetappManager _netappMgr; public static final Logger s_logger = Logger.getLogger(NetappDefaultAllocatorImpl.class.getName()); public NetappDefaultAllocatorImpl(NetappManager netappMgr) { @@ -67,8 +64,6 @@ public class NetappDefaultAllocatorImpl implements NetappAllocator { * @param poolName * @param lunSizeGb * @return -- the selected volume to create the lun on - * @throws IOException - * @throws NaException */ @Override public synchronized NetappVolumeVO chooseVolumeFromPool(String poolName, long lunSizeGb) { @@ -81,14 +76,14 @@ public class NetappDefaultAllocatorImpl implements NetappAllocator { } //get the index of the record from the map - if (_poolNameToLastVolumeIdAllocated.get(poolName) == null) { + if (s_poolNameToLastVolumeIdAllocated.get(poolName) == null) { pos = 0; } else { - pos = _poolNameToLastVolumeIdAllocated.get(poolName); + pos = s_poolNameToLastVolumeIdAllocated.get(poolName); } //update for RR effect - _poolNameToLastVolumeIdAllocated.put(poolName, (pos + 1) % volumesOnPoolAscending.size()); + s_poolNameToLastVolumeIdAllocated.put(poolName, (pos + 1) % volumesOnPoolAscending.size()); //now iterate over the records Object[] volumesOnPoolAscendingArray = volumesOnPoolAscending.toArray(); diff --git a/plugins/file-systems/netapp/src/com/cloud/netapp/NetappManagerImpl.java b/plugins/file-systems/netapp/src/com/cloud/netapp/NetappManagerImpl.java index 10a619c2f38..510e6c6b260 100644 --- a/plugins/file-systems/netapp/src/com/cloud/netapp/NetappManagerImpl.java +++ b/plugins/file-systems/netapp/src/com/cloud/netapp/NetappManagerImpl.java @@ -31,10 +31,8 @@ import javax.inject.Inject; import javax.naming.ConfigurationException; import netapp.manage.NaAPIFailedException; -import netapp.manage.NaAuthenticationException; import netapp.manage.NaElement; import netapp.manage.NaException; -import netapp.manage.NaProtocolException; import netapp.manage.NaServer; import org.apache.log4j.Logger; @@ -208,10 +206,7 @@ public class NetappManagerImpl extends ManagerBase implements NetappManager { * @param volName -- name of volume to destroy * @throws ResourceInUseException * @throws NaException - * @throws IOException - * @throws NaProtocolException * @throws NaAPIFailedException - * @throws NaAuthenticationException */ @Override @DB diff --git a/plugins/ha-planners/skip-heurestics/pom.xml b/plugins/ha-planners/skip-heurestics/pom.xml new file mode 100644 index 00000000000..223789a287f --- /dev/null +++ b/plugins/ha-planners/skip-heurestics/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + cloud-plugin-planner-skip-heurestics + Apache CloudStack Plugin - Skip Heurestics Planner + + org.apache.cloudstack + cloudstack-plugins + 4.4.0-SNAPSHOT + ../../pom.xml + + diff --git a/scripts/network/domr/deleteipAlias.sh b/plugins/ha-planners/skip-heurestics/resources/META-INF/cloudstack/skip-heurestics/module.properties old mode 100755 new mode 100644 similarity index 74% rename from scripts/network/domr/deleteipAlias.sh rename to plugins/ha-planners/skip-heurestics/resources/META-INF/cloudstack/skip-heurestics/module.properties index 6816edd524c..dfe0641ba4a --- a/scripts/network/domr/deleteipAlias.sh +++ b/plugins/ha-planners/skip-heurestics/resources/META-INF/cloudstack/skip-heurestics/module.properties @@ -1,4 +1,3 @@ -#!/usr/bin/env bash # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information @@ -15,11 +14,5 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. - -usage() { - printf " %s routerip \n" $(basename $0) >&2 -} - -set -x -cert="/root/.ssh/id_rsa.cloud" -ssh -p 3922 -q -o StrictHostKeyChecking=no -i $cert root@$1 "/root/deleteIpAlias.sh $2 $3" +name=skip-heurestics +parent=planner diff --git a/plugins/ha-planners/skip-heurestics/resources/META-INF/cloudstack/skip-heurestics/spring-skip-heurestics-context.xml b/plugins/ha-planners/skip-heurestics/resources/META-INF/cloudstack/skip-heurestics/spring-skip-heurestics-context.xml new file mode 100644 index 00000000000..93a015874af --- /dev/null +++ b/plugins/ha-planners/skip-heurestics/resources/META-INF/cloudstack/skip-heurestics/spring-skip-heurestics-context.xml @@ -0,0 +1,26 @@ + + + + + + + + + + diff --git a/plugins/ha-planners/skip-heurestics/src/com/cloud/deploy/SkipHeuresticsPlanner.java b/plugins/ha-planners/skip-heurestics/src/com/cloud/deploy/SkipHeuresticsPlanner.java new file mode 100644 index 00000000000..b67d112f825 --- /dev/null +++ b/plugins/ha-planners/skip-heurestics/src/com/cloud/deploy/SkipHeuresticsPlanner.java @@ -0,0 +1,61 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.deploy; + +import com.cloud.vm.VirtualMachineProfile; +import org.apache.log4j.Logger; + + +import javax.ejb.Local; +import javax.naming.ConfigurationException; +import java.util.List; +import java.util.Map; + +@Local(value=HAPlanner.class) +public class SkipHeuresticsPlanner extends FirstFitPlanner implements HAPlanner { + private static final Logger s_logger = Logger.getLogger(SkipHeuresticsPlanner.class); + + + /** + * This method should remove the clusters crossing capacity threshold + * to avoid further vm allocation on it. + * + * In case of HA, we shouldn't consider this threshold as we have reserved the capacity for such emergencies. + */ + @Override + protected void removeClustersCrossingThreshold(List clusterListForVmAllocation, ExcludeList avoid, + VirtualMachineProfile vmProfile, DeploymentPlan plan){ + if (s_logger.isDebugEnabled()) { + s_logger.debug("Deploying vm during HA process, so skipping disable threshold check"); + } + return; + } + + @Override + public boolean canHandle(VirtualMachineProfile vm, DeploymentPlan plan, ExcludeList avoid) { + return true; + } + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + super.configure(name, params); + + return true; + + } + +} \ No newline at end of file diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BareMetalPingServiceImpl.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BareMetalPingServiceImpl.java index 8a87285bc3b..66bbb618e20 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BareMetalPingServiceImpl.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BareMetalPingServiceImpl.java @@ -41,7 +41,7 @@ import com.cloud.agent.api.baremetal.IpmISetBootDevCommand; import com.cloud.agent.api.baremetal.IpmISetBootDevCommand.BootDev; import com.cloud.agent.api.baremetal.PreparePxeServerAnswer; import com.cloud.agent.api.baremetal.PreparePxeServerCommand; -import com.cloud.agent.api.baremetal.prepareCreateTemplateCommand; +import com.cloud.agent.api.baremetal.PrepareCreateTemplateCommand; import com.cloud.baremetal.database.BaremetalPxeDao; import com.cloud.baremetal.database.BaremetalPxeVO; import com.cloud.baremetal.networkservice.BaremetalPxeManager.BaremetalPxeType; @@ -148,7 +148,7 @@ public class BareMetalPingServiceImpl extends BareMetalPxeServiceBase implements } try { - prepareCreateTemplateCommand cmd = new prepareCreateTemplateCommand(ip, mac, mask, gateway, dns, templateUrl); + PrepareCreateTemplateCommand cmd = new PrepareCreateTemplateCommand(ip, mac, mask, gateway, dns, templateUrl); Answer ans = _agentMgr.send(pxeServerId, cmd); return ans.getResult(); } catch (Exception e) { diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartPxeResource.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartPxeResource.java index 6fc6a28ddbb..b677a63b03e 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartPxeResource.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartPxeResource.java @@ -42,7 +42,7 @@ import com.cloud.vm.VirtualMachine.State; public class BaremetalKickStartPxeResource extends BaremetalPxeResourceBase { private static final Logger s_logger = Logger.getLogger(BaremetalKickStartPxeResource.class); - private static final String _name = "BaremetalKickStartPxeResource"; + private static final String Name = "BaremetalKickStartPxeResource"; String _tftpDir; @Override diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPingPxeResource.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPingPxeResource.java index ddad9b6dbb2..a7fd77ee43f 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPingPxeResource.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPingPxeResource.java @@ -39,7 +39,7 @@ import com.cloud.agent.api.PingCommand; import com.cloud.agent.api.PingRoutingCommand; import com.cloud.agent.api.baremetal.PreparePxeServerAnswer; import com.cloud.agent.api.baremetal.PreparePxeServerCommand; -import com.cloud.agent.api.baremetal.prepareCreateTemplateCommand; +import com.cloud.agent.api.baremetal.PrepareCreateTemplateCommand; import com.cloud.agent.api.routing.VmDataCommand; import com.cloud.utils.script.Script; import com.cloud.utils.ssh.SSHCmdHelper; @@ -47,7 +47,7 @@ import com.cloud.vm.VirtualMachine.State; public class BaremetalPingPxeResource extends BaremetalPxeResourceBase { private static final Logger s_logger = Logger.getLogger(BaremetalPingPxeResource.class); - private static final String _name = "BaremetalPingPxeResource"; + private static final String Name = "BaremetalPingPxeResource"; String _storageServer; String _pingDir; String _share; @@ -175,7 +175,7 @@ public class BaremetalPingPxeResource extends BaremetalPxeResourceBase { } } - protected Answer execute(prepareCreateTemplateCommand cmd) { + protected Answer execute(PrepareCreateTemplateCommand cmd) { com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(_ip, 22); try { sshConnection.connect(null, 60000, 60000); @@ -207,8 +207,8 @@ public class BaremetalPingPxeResource extends BaremetalPxeResourceBase { public Answer executeRequest(Command cmd) { if (cmd instanceof PreparePxeServerCommand) { return execute((PreparePxeServerCommand)cmd); - } else if (cmd instanceof prepareCreateTemplateCommand) { - return execute((prepareCreateTemplateCommand)cmd); + } else if (cmd instanceof PrepareCreateTemplateCommand) { + return execute((PrepareCreateTemplateCommand)cmd); } else if (cmd instanceof VmDataCommand) { return execute((VmDataCommand)cmd); } else { diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalUserdataElement.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalUserdataElement.java index b60a67bea55..4689fbc8f85 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalUserdataElement.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalUserdataElement.java @@ -85,7 +85,7 @@ public class BaremetalUserdataElement extends AdapterBase implements NetworkElem } @Override - public boolean saveSSHKey(Network network, NicProfile nic, VirtualMachineProfile vm, String SSHPublicKey) throws ResourceUnavailableException { + public boolean saveSSHKey(Network network, NicProfile nic, VirtualMachineProfile vm, String sshPublicKey) throws ResourceUnavailableException { // TODO Auto-generated method stub return false; } diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/AgentService.Designer.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/AgentService.Designer.cs index 854427732aa..4bf424fa4b9 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/AgentService.Designer.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/AgentService.Designer.cs @@ -45,7 +45,7 @@ namespace CloudStack.Plugin.AgentShell private void InitializeComponent() { components = new System.ComponentModel.Container(); - this.ServiceName = "CloudStack ServerResource"; + this.ServiceName = Program.serviceName; } #endregion diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/AgentService.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/AgentService.cs index e1870973511..9d66a5cd1bf 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/AgentService.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/AgentService.cs @@ -47,7 +47,7 @@ namespace CloudStack.Plugin.AgentShell logger.Info("Starting CloudStack agent"); InitializeComponent(); - UriBuilder baseUri = new UriBuilder("http", AgentSettings.Default.private_ip_address, AgentSettings.Default.port); + UriBuilder baseUri = new UriBuilder("https", AgentSettings.Default.private_ip_address, AgentSettings.Default.port); var config = new HttpSelfHostConfiguration(baseUri.Uri); diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/App.config b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/App.config index 68ab80ee555..3ec08bd29c9 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/App.config +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/App.config @@ -10,9 +10,9 @@ - + - + @@ -25,13 +25,14 @@ + - + @@ -95,7 +96,7 @@ 2048 - 10.102.192.150 + 0.0.0.0 diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/Program.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/Program.cs index e84350020c4..7545644fb70 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/Program.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/Program.cs @@ -29,7 +29,13 @@ namespace CloudStack.Plugin.AgentShell static class Program { private static ILog logger = LogManager.GetLogger(typeof(Program)); - private static string serviceName = "CloudStack ServerResource"; + public const string serviceName = "CloudStack Hyper-V Agent"; + private static string option = null; + private static string user = null; + private static string password = null; + private const string install = "--install"; + private const string uninstall = "--uninstall"; + private const string console = "--console"; /// /// Application entry point allows service to run in console application or as a Windows service. @@ -39,33 +45,100 @@ namespace CloudStack.Plugin.AgentShell { if (args.Length == 0) { - logger.InfoFormat("CloudStack ServerResource running as Windows Service"); + logger.InfoFormat(serviceName + " running as Windows Service"); ServiceBase[] ServicesToRun = new ServiceBase[] { new AgentService() }; ServiceBase.Run(ServicesToRun); } - else if (args.Length == 1) + else if (ParseArguments(args)) { - logger.DebugFormat("CloudStack ServerResource arg is ", args[0]); - switch (args[0]) + switch (option) { - case "--install": - logger.InfoFormat("Installing and running CloudStack ServerResource "); + case install: + logger.InfoFormat("Installing and running " + serviceName); InstallService(); StartService(); break; - case "--uninstall": - logger.InfoFormat("stopping and uninstalling CloudStack ServerResource "); + case uninstall: + logger.InfoFormat("Stopping and uninstalling " + serviceName); StopService(); UninstallService(); break; - case "--console": - logger.InfoFormat("CloudStack ServerResource running as console app"); + case console: + logger.InfoFormat(serviceName + " is running as console application"); new AgentService().RunConsole(args); break; default: throw new NotImplementedException(); } } + else + { + string argumentExample = "--(install/uninstall/console) [-u ] [-p ].\n" + + " For example:\n " + + " --install -u domain1\\user1 -p mypwd\n"+ + " --uninstall"; + logger.Error("Invalid arguments passed for installing\\uninstalling the service. \n" + argumentExample); + } + } + + static private Boolean ParseArguments(string[] args) + { + logger.DebugFormat(serviceName + " arg is ", args[0]); + int argIndex = 0; + while (argIndex < args.Length) + { + switch (args[argIndex]) + { + case install: + case uninstall: + case console: + option = args[argIndex]; + argIndex++; + break; + case "-u": + user = args[argIndex+1]; + argIndex+=2; + break; + case "-p": + password = args[argIndex+1]; + argIndex+=2; + break; + default: + argIndex++; + // Unrecognised argument. Do nothing; + break; + } + } + + // Validate arguments + return ValidateArguments(); + } + + private static Boolean ValidateArguments() + { + Boolean argsValid = false; + switch (option) + { + case uninstall: + case install: + case console: + argsValid = true; + break; + default: + break; + } + + return argsValid; + } + + public static string GetPassword() + { + return password; + } + + public static string GetUser() + { + return user; } private static bool IsInstalled() diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/ProjectInstaller.Designer.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/ProjectInstaller.Designer.cs index a10cbb002fd..2c6ffe24462 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/ProjectInstaller.Designer.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/AgentShell/ProjectInstaller.Designer.cs @@ -44,33 +44,46 @@ namespace CloudStack.Plugin.AgentShell /// private void InitializeComponent() { - this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller(); - this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller(); - // - // serviceProcessInstaller1 - // - this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem; - this.serviceProcessInstaller1.Password = null; - this.serviceProcessInstaller1.Username = null; - // - // serviceInstaller1 - // - this.serviceInstaller1.Description = "CloudStack Agent"; - this.serviceInstaller1.DisplayName = "CloudStack ServerResource"; - this.serviceInstaller1.ServiceName = "CloudStack ServerResource"; - this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic; - // + this.serviceProcessInstaller = new System.ServiceProcess.ServiceProcessInstaller(); + this.serviceInstaller = new System.ServiceProcess.ServiceInstaller(); + // + // serviceProcessInstaller + // + string user = Program.GetUser(); + string password = Program.GetPassword(); + + if (string.IsNullOrEmpty(user)) + { + this.serviceProcessInstaller.Account = System.ServiceProcess.ServiceAccount.LocalSystem; + this.serviceProcessInstaller.Password = null; + this.serviceProcessInstaller.Username = null; + } + else + { + this.serviceProcessInstaller.Account = System.ServiceProcess.ServiceAccount.User; + this.serviceProcessInstaller.Password = password; + this.serviceProcessInstaller.Username = user; + } + + // + // serviceInstaller + // + this.serviceInstaller.Description = "CloudStack agent for managing a hyper-v host"; + this.serviceInstaller.DisplayName = Program.serviceName; + this.serviceInstaller.ServiceName = Program.serviceName; + this.serviceInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic; + // // ProjectInstaller - // + // this.Installers.AddRange(new System.Configuration.Install.Installer[] { - this.serviceProcessInstaller1, - this.serviceInstaller1}); + this.serviceProcessInstaller, + this.serviceInstaller}); } #endregion - private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1; - private System.ServiceProcess.ServiceInstaller serviceInstaller1; + private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller; + private System.ServiceProcess.ServiceInstaller serviceInstaller; } } diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/App.config b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/App.config index 1bf17d4791f..0e75ef9b5f4 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/App.config +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/App.config @@ -24,7 +24,7 @@ 8 - 10.1.1.1 + 0.0.0.0 Routing @@ -45,13 +45,13 @@ 34359738368 - camldonall01.citrite.net + 0.0.0.0 1 - 10.70.176.1 + 0.0.0.0 2 diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/CloudStackTypes.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/CloudStackTypes.cs index ce1b1e8c6eb..c336a3821e3 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/CloudStackTypes.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/CloudStackTypes.cs @@ -61,7 +61,7 @@ namespace HypervResource get { string uncPath = null; - if (uri.Scheme.Equals("cifs") || uri.Scheme.Equals("networkfilesystem")) + if (uri != null && (uri.Scheme.Equals("cifs") || uri.Scheme.Equals("networkfilesystem"))) { uncPath = @"\\" + uri.Host + uri.LocalPath; } @@ -73,8 +73,13 @@ namespace HypervResource { get { - var queryDictionary = System.Web.HttpUtility.ParseQueryString(uri.Query); - return System.Web.HttpUtility.UrlDecode(queryDictionary["user"]); + string user = null; + if (uri != null) + { + var queryDictionary = System.Web.HttpUtility.ParseQueryString(uri.Query); + user = System.Web.HttpUtility.UrlDecode(queryDictionary["user"]); + } + return user; } } @@ -82,8 +87,13 @@ namespace HypervResource { get { - var queryDictionary = System.Web.HttpUtility.ParseQueryString(uri.Query); - return System.Web.HttpUtility.UrlDecode(queryDictionary["password"]); + string password = null; + if (uri != null) + { + var queryDictionary = System.Web.HttpUtility.ParseQueryString(uri.Query); + password = System.Web.HttpUtility.UrlDecode(queryDictionary["password"]); + } + return password; } } @@ -91,12 +101,17 @@ namespace HypervResource { get { - var queryDictionary = System.Web.HttpUtility.ParseQueryString(uri.Query); - if (queryDictionary["domain"] != null) + string domain = null; + if (uri != null) { - return System.Web.HttpUtility.UrlDecode(queryDictionary["domain"]); + var queryDictionary = System.Web.HttpUtility.ParseQueryString(uri.Query); + if (queryDictionary["domain"] != null) + { + domain = System.Web.HttpUtility.UrlDecode(queryDictionary["domain"]); + } + else domain = uri.Host; } - else return uri.Host; + return domain; } } @@ -153,17 +168,48 @@ namespace HypervResource get { string fileName = null; - if (this.primaryDataStore.isLocal) + if (this.primaryDataStore != null) { - fileName = Path.Combine(this.primaryDataStore.Path, this.name); + PrimaryDataStoreTO store = this.primaryDataStore; + if (store.isLocal) + { + fileName = Path.Combine(store.Path, this.name); + } + else + { + fileName = @"\\" + store.uri.Host + store.uri.LocalPath + @"\" + this.name; + fileName = Utils.NormalizePath(fileName); + } + } + else if (this.nfsDataStore != null) + { + if (this.path != null && File.Exists(this.path)) + { + fileName = this.path; + } + else + { + fileName = this.nfsDataStore.UncPath; + if (this.path != null) + { + fileName += @"\" + this.path; + } + + fileName = Utils.NormalizePath(fileName); + if (Directory.Exists(fileName)) + { + fileName = Utils.NormalizePath(fileName + @"\" + this.name); + } + } } else { - fileName = @"\\" + this.primaryDataStore.uri.Host + this.primaryDataStore.uri.LocalPath + @"\" + this.name; - fileName = fileName.Replace(@"/", @"\"); + String errMsg = "Invalid dataStore in VolumeObjectTO spec"; + logger.Error(errMsg); + throw new InvalidDataException(errMsg); } - if (this.format != null) + if (fileName != null && !Path.HasExtension(fileName) && this.format != null) { fileName = fileName + "." + this.format.ToLowerInvariant(); } @@ -175,9 +221,11 @@ namespace HypervResource public dynamic dataStore; public string format; public string name; + public string path; public string uuid; public ulong size; public PrimaryDataStoreTO primaryDataStore; + public NFSTO nfsDataStore; public static VolumeObjectTO ParseJson(dynamic json) { @@ -196,15 +244,17 @@ namespace HypervResource dataStore = volumeObjectTOJson.dataStore, format = ((string)volumeObjectTOJson.format), name = (string)volumeObjectTOJson.name, + path = volumeObjectTOJson.path, uuid = (string)volumeObjectTOJson.uuid, size = (ulong)volumeObjectTOJson.size }; result.primaryDataStore = PrimaryDataStoreTO.ParseJson(volumeObjectTOJson.dataStore); + result.nfsDataStore = NFSTO.ParseJson(volumeObjectTOJson.dataStore); // Assert - if (result.dataStore == null || result.primaryDataStore == null) + if (result.dataStore == null || (result.primaryDataStore == null && result.nfsDataStore == null)) { - String errMsg = "VolumeObjectTO missing primary dataStore in spec " + volumeObjectTOJson.ToString(); + String errMsg = "VolumeObjectTO missing dataStore in spec " + Utils.CleanString(volumeObjectTOJson.ToString()); logger.Error(errMsg); throw new ArgumentNullException(errMsg); } @@ -220,22 +270,48 @@ namespace HypervResource { logger.Info("No image format in VolumeObjectTO, going to use format from first file that matches " + volInfo.FullFileName); - string path = volInfo.primaryDataStore.Path; - if (!volInfo.primaryDataStore.isLocal) + string path = null; + if (volInfo.primaryDataStore != null) { - path = volInfo.primaryDataStore.UncPath; + if (volInfo.primaryDataStore.isLocal) + { + path = volInfo.primaryDataStore.Path; + } + else + { + path = volInfo.primaryDataStore.UncPath; + } } - - string[] choices = choices = Directory.GetFiles(path, volInfo.name + ".vhd*"); - if (choices.Length != 1) + else if (volInfo.nfsDataStore != null) { - String errMsg = "Tried to guess file extension, but cannot find file corresponding to " + Path.Combine(volInfo.primaryDataStore.Path, volInfo.name); // format being guessed. - logger.Debug(errMsg); + path = volInfo.nfsDataStore.UncPath; + if (volInfo.path != null) + { + path += @"\" + volInfo.path; + } } else { - string[] splitFileName = choices[0].Split(new char[] { '.' }); - volInfo.format = splitFileName[splitFileName.Length - 1]; + String errMsg = "VolumeObjectTO missing dataStore in spec " + Utils.CleanString(volInfo.ToString()); + logger.Error(errMsg); + throw new ArgumentNullException(errMsg); + } + + path = Utils.NormalizePath(path); + if (Directory.Exists(path)) + { + string[] choices = choices = Directory.GetFiles(path, volInfo.name + ".vhd*"); + if (choices.Length != 1) + { + String errMsg = "Tried to guess file extension, but cannot find file corresponding to " + + Path.Combine(volInfo.primaryDataStore.Path, volInfo.name); + logger.Debug(errMsg); + } + else + { + string[] splitFileName = choices[0].Split(new char[] { '.' }); + volInfo.format = splitFileName[splitFileName.Length - 1]; + } } logger.Debug("Going to use file " + volInfo.FullFileName); } @@ -252,20 +328,34 @@ namespace HypervResource { get { - if (String.IsNullOrEmpty(this.path)) + string fileName = null; + if (this.primaryDataStore != null) { - string fileName = null; - if (this.primaryDataStore.isLocal) + PrimaryDataStoreTO store = this.primaryDataStore; + if (store.isLocal) { - fileName = Path.Combine(this.primaryDataStore.Path, this.name); + fileName = Path.Combine(store.Path, this.name); } else { - fileName = @"\\" + this.primaryDataStore.uri.Host + this.primaryDataStore.uri.LocalPath + @"\" + this.name; + fileName = @"\\" + store.uri.Host + store.uri.LocalPath + @"\" + this.name; } - return fileName +'.' + this.format.ToLowerInvariant(); + fileName = fileName + '.' + this.format.ToLowerInvariant(); } - return this.path; + else if (this.nfsDataStoreTO != null) + { + NFSTO store = this.nfsDataStoreTO; + fileName = store.UncPath + @"\" + this.path + @"\" + this.name; + if (!this.format.Equals("RAW")) + { + fileName = fileName + '.' + this.format.ToLowerInvariant(); + } + } + else + { + fileName = this.path; + } + return Utils.NormalizePath(fileName); } } @@ -278,6 +368,8 @@ namespace HypervResource public PrimaryDataStoreTO primaryDataStore = null; public string path; public string checksum; + public string size; + public string id; public static TemplateObjectTO ParseJson(dynamic json) { @@ -292,7 +384,9 @@ namespace HypervResource name = (string)templateObjectTOJson.name, uuid = (string)templateObjectTOJson.uuid, path = (string)templateObjectTOJson.path, - checksum = (string)templateObjectTOJson.checksum + checksum = (string)templateObjectTOJson.checksum, + size = (string)templateObjectTOJson.size, + id = (string)templateObjectTOJson.id }; result.s3DataStoreTO = S3TO.ParseJson(templateObjectTOJson.imageDataStore); result.nfsDataStoreTO = NFSTO.ParseJson(templateObjectTOJson.imageDataStore); @@ -406,7 +500,9 @@ namespace HypervResource public class DiskTO { public string type; + public string diskSequence = null; public TemplateObjectTO templateObjectTO = null; + public VolumeObjectTO volumeObjectTO = null; public static DiskTO ParseJson(dynamic json) { @@ -416,7 +512,9 @@ namespace HypervResource result = new DiskTO() { templateObjectTO = TemplateObjectTO.ParseJson(json.data), + volumeObjectTO = VolumeObjectTO.ParseJson(json.data), type = (string)json.type, + diskSequence = json.diskSeq }; } @@ -592,6 +690,20 @@ namespace HypervResource public String entityType; } + public class NicDetails + { + [JsonProperty("macAddress")] + public string macaddress; + [JsonProperty("vlanid")] + public int vlanid; + public NicDetails() { } + public NicDetails(String macaddress, int vlanid) + { + this.macaddress = macaddress; + this.vlanid = vlanid; + } + } + /// /// Fully qualified named for a number of types used in CloudStack. Used to specify the intended type for JSON serialised objects. /// @@ -640,6 +752,10 @@ namespace HypervResource public const string GetVmDiskStatsCommand = "com.cloud.agent.api.GetVmDiskStatsCommand"; public const string GetVmStatsAnswer = "com.cloud.agent.api.GetVmStatsAnswer"; public const string GetVmStatsCommand = "com.cloud.agent.api.GetVmStatsCommand"; + public const string GetVmConfigCommand = "com.cloud.agent.api.GetVmConfigCommand"; + public const string GetVmConfigAnswer = "com.cloud.agent.api.GetVmConfigAnswer"; + public const string ModifyVmNicConfigCommand = "com.cloud.agent.api.ModifyVmNicConfigCommand"; + public const string ModifyVmNicConfigAnswer = "com.cloud.agent.api.ModifyVmNicConfigAnswer"; public const string GetVncPortAnswer = "com.cloud.agent.api.GetVncPortAnswer"; public const string GetVncPortCommand = "com.cloud.agent.api.GetVncPortCommand"; public const string HostStatsEntry = "com.cloud.agent.api.HostStatsEntry"; diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/HypervResourceController.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/HypervResourceController.cs index f5008123930..ebb3bce2cf8 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/HypervResourceController.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/HypervResourceController.cs @@ -31,6 +31,7 @@ using System.IO; using System.Linq; using System.Net; using System.Net.Http; +using System.Text; using System.Security.Cryptography; using System.Security.Principal; using System.Web.Http; @@ -141,7 +142,7 @@ namespace HypervResource public static HypervResourceControllerConfig config = new HypervResourceControllerConfig(); private static ILog logger = LogManager.GetLogger(typeof(HypervResourceController)); - private static string systemVmIso; + private string systemVmIso = ""; Dictionary contextMap = new Dictionary(); public static void Initialize() @@ -179,19 +180,6 @@ namespace HypervResource try { - NFSTO share = new NFSTO(); - String uriStr = (String)cmd.secondaryStorage; - share.uri = new Uri(uriStr); - - string systemVmIso = (string)cmd.systemVmIso; - string defaultDataPath = wmiCallsV2.GetDefaultDataRoot(); - string isoPath = Path.Combine(defaultDataPath, Path.GetFileName(systemVmIso)); - if (!File.Exists(isoPath)) - { - logger.Info("File " + isoPath + " not found. Copying it from the secondary share."); - Utils.DownloadCifsFileToLocalFile(systemVmIso, share, isoPath); - } - HypervResourceController.systemVmIso = isoPath; result = true; } catch (Exception sysEx) @@ -219,7 +207,7 @@ namespace HypervResource { using (log4net.NDC.Push(Guid.NewGuid().ToString())) { - logger.Info(CloudStackTypes.AttachCommand + cmd.ToString()); + logger.Info(CloudStackTypes.AttachCommand + Utils.CleanString(cmd.ToString())); string details = null; bool result = false; @@ -228,18 +216,32 @@ namespace HypervResource { string vmName = (string)cmd.vmName; DiskTO disk = DiskTO.ParseJson(cmd.disk); - TemplateObjectTO dataStore = disk.templateObjectTO; - if (dataStore.nfsDataStoreTO != null) + if (disk.type.Equals("ISO")) { + TemplateObjectTO dataStore = disk.templateObjectTO; NFSTO share = dataStore.nfsDataStoreTO; Utils.ConnectToRemote(share.UncPath, share.Domain, share.User, share.Password); - - // The share is mapped, now attach the iso - string isoPath = Path.Combine(share.UncPath.Replace('/', Path.DirectorySeparatorChar), dataStore.path); - wmiCallsV2.AttachIso(vmName, isoPath); + string diskPath = Utils.NormalizePath(Path.Combine(share.UncPath, dataStore.path)); + wmiCallsV2.AttachIso(vmName, diskPath); result = true; } + else if (disk.type.Equals("DATADISK")) + { + VolumeObjectTO volume = disk.volumeObjectTO; + PrimaryDataStoreTO primary = volume.primaryDataStore; + if (!primary.isLocal) + { + Utils.ConnectToRemote(primary.UncPath, primary.Domain, primary.User, primary.Password); + } + string diskPath = Utils.NormalizePath(volume.FullFileName); + wmiCallsV2.AttachDisk(vmName, diskPath, disk.diskSequence); + result = true; + } + else + { + details = "Invalid disk type to be attached to vm " + vmName; + } } catch (Exception sysEx) { @@ -251,6 +253,7 @@ namespace HypervResource { result = result, details = details, + disk = cmd.disk, contextMap = contextMap }; @@ -265,7 +268,7 @@ namespace HypervResource { using (log4net.NDC.Push(Guid.NewGuid().ToString())) { - logger.Info(CloudStackTypes.DettachCommand + cmd.ToString()); + logger.Info(CloudStackTypes.DettachCommand + Utils.CleanString(cmd.ToString())); string details = null; bool result = false; @@ -274,17 +277,27 @@ namespace HypervResource { string vmName = (string)cmd.vmName; DiskTO disk = DiskTO.ParseJson(cmd.disk); - TemplateObjectTO dataStore = disk.templateObjectTO; - if (dataStore.nfsDataStoreTO != null) + if (disk.type.Equals("ISO")) { + TemplateObjectTO dataStore = disk.templateObjectTO; NFSTO share = dataStore.nfsDataStoreTO; - // The share is mapped, now attach the iso - string isoPath = Path.Combine(share.UncPath.Replace('/', Path.DirectorySeparatorChar), - dataStore.path.Replace('/', Path.DirectorySeparatorChar)); - wmiCallsV2.DetachDisk(vmName, isoPath); + string diskPath = Utils.NormalizePath(Path.Combine(share.UncPath, dataStore.path)); + wmiCallsV2.DetachDisk(vmName, diskPath); result = true; } + else if (disk.type.Equals("DATADISK")) + { + VolumeObjectTO volume = disk.volumeObjectTO; + PrimaryDataStoreTO primary = volume.primaryDataStore; + string diskPath = Utils.NormalizePath(volume.FullFileName); + wmiCallsV2.DetachDisk(vmName, diskPath); + result = true; + } + else + { + details = "Invalid disk type to be dettached from vm " + vmName; + } } catch (Exception sysEx) { @@ -410,11 +423,69 @@ namespace HypervResource } } + // POST api/HypervResource/DeleteCommand + [HttpPost] + [ActionName(CloudStackTypes.DeleteCommand)] + public JContainer DeleteCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.DestroyCommand + cmd.ToString()); + + string details = null; + bool result = false; + + try + { + // Assert + String errMsg = "No 'volume' details in " + CloudStackTypes.DestroyCommand + " " + cmd.ToString(); + VolumeObjectTO destVolumeObjectTO = VolumeObjectTO.ParseJson(cmd.data); + + if (destVolumeObjectTO.name == null) + { + logger.Error(errMsg); + throw new ArgumentException(errMsg); + } + + String path = destVolumeObjectTO.FullFileName; + if (!File.Exists(path)) + { + logger.Info(CloudStackTypes.DestroyCommand + ", but volume at pass already deleted " + path); + } + + string vmName = (string)cmd.vmName; + if (!string.IsNullOrEmpty(vmName) && File.Exists(path)) + { + // Make sure that this resource is removed from the VM + wmiCallsV2.DetachDisk(vmName, path); + } + + File.Delete(path); + result = true; + } + catch (Exception sysEx) + { + details = CloudStackTypes.DestroyCommand + " failed due to " + sysEx.Message; + logger.Error(details, sysEx); + } + + object ansContent = new + { + result = result, + details = details, + contextMap = contextMap + }; + + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer); + } + } + + private static JArray ReturnCloudStackTypedJArray(object ansContent, string ansType) { JObject ansObj = Utils.CreateCloudStackObject(ansType, ansContent); JArray answer = new JArray(ansObj); - logger.Info(ansObj.ToString()); + logger.Info(Utils.CleanString(ansObj.ToString())); return answer; } @@ -425,7 +496,7 @@ namespace HypervResource { using (log4net.NDC.Push(Guid.NewGuid().ToString())) { - logger.Info(CloudStackTypes.CreateCommand + cmd.ToString()); + logger.Info(CloudStackTypes.CreateCommand + Utils.CleanString(cmd.ToString())); string details = null; bool result = false; @@ -532,7 +603,7 @@ namespace HypervResource { using (log4net.NDC.Push(Guid.NewGuid().ToString())) { - logger.Info(CloudStackTypes.PrimaryStorageDownloadCommand + cmd.ToString()); + logger.Info(CloudStackTypes.PrimaryStorageDownloadCommand + Utils.CleanString(cmd.ToString())); string details = null; bool result = false; long size = 0; @@ -679,7 +750,6 @@ namespace HypervResource } // POST api/HypervResource/CheckHealthCommand - // TODO: create test [HttpPost] [ActionName(CloudStackTypes.CheckHealthCommand)] public JContainer CheckHealthCommand([FromBody]dynamic cmd) @@ -697,6 +767,24 @@ namespace HypervResource } } + // POST api/HypervResource/CheckOnHostCommand + [HttpPost] + [ActionName(CloudStackTypes.CheckOnHostCommand)] + public JContainer CheckOnHostCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.CheckOnHostCommand + cmd.ToString()); + object ansContent = new + { + result = true, + details = "resource is alive", + contextMap = contextMap + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CheckOnHostAnswer); + } + } + // POST api/HypervResource/CheckSshCommand // TODO: create test [HttpPost] @@ -783,7 +871,7 @@ namespace HypervResource { using (log4net.NDC.Push(Guid.NewGuid().ToString())) { - logger.Info(CloudStackTypes.CreateStoragePoolCommand + cmd.ToString()); + logger.Info(CloudStackTypes.CreateStoragePoolCommand + Utils.CleanString(cmd.ToString())); object ansContent = new { result = true, @@ -801,7 +889,7 @@ namespace HypervResource { using (log4net.NDC.Push(Guid.NewGuid().ToString())) { - logger.Info(CloudStackTypes.ModifyStoragePoolCommand + cmd.ToString()); + logger.Info(CloudStackTypes.ModifyStoragePoolCommand + Utils.CleanString(cmd.ToString())); string details = null; string localPath; StoragePoolType poolType; @@ -822,18 +910,23 @@ namespace HypervResource var tInfo = new Dictionary(); long capacityBytes = 0; long availableBytes = 0; + string hostPath = null; if (poolType == StoragePoolType.Filesystem) { GetCapacityForLocalPath(localPath, out capacityBytes, out availableBytes); + hostPath = localPath; } else if (poolType == StoragePoolType.NetworkFilesystem) { NFSTO share = new NFSTO(); String uriStr = "cifs://" + (string)cmd.pool.host + (string)cmd.pool.path; share.uri = new Uri(uriStr); + hostPath = Utils.NormalizePath(share.UncPath); + // Check access to share. Utils.ConnectToRemote(share.UncPath, share.Domain, share.User, share.Password); Utils.GetShareDetails(share.UncPath, out capacityBytes, out availableBytes); + config.setPrimaryStorage((string)cmd.pool.uuid, hostPath); } else { @@ -845,8 +938,8 @@ namespace HypervResource { uuid = uuid, host = cmd.pool.host, - localPath = cmd.pool.host, - hostPath = cmd.localPath, + hostPath = cmd.pool.path, + localPath = hostPath, poolType = cmd.pool.type, capacityBytes = capacityBytes, availableBytes = availableBytes @@ -856,6 +949,7 @@ namespace HypervResource { result = result, details = details, + localPath = hostPath, templateInfo = tInfo, poolInfo = poolInfo, contextMap = contextMap @@ -888,6 +982,24 @@ namespace HypervResource return true; } + // POST api/HypervResource/PlugNicCommand + [HttpPost] + [ActionName(CloudStackTypes.PlugNicCommand)] + public JContainer PlugNicCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.PlugNicCommand + cmd.ToString()); + object ansContent = new + { + result = true, + details = "instead of plug, change he network settings", + contextMap = contextMap + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.PlugNicAnswer); + } + } + // POST api/HypervResource/CleanupNetworkRulesCmd [HttpPost] @@ -951,13 +1063,46 @@ namespace HypervResource { using (log4net.NDC.Push(Guid.NewGuid().ToString())) { - logger.Info(CloudStackTypes.StartCommand + cmd.ToString()); // TODO: Security hole? VM data printed to log + logger.Info(CloudStackTypes.StartCommand + Utils.CleanString(cmd.ToString())); string details = null; bool result = false; try { - wmiCallsV2.DeployVirtualMachine(cmd, systemVmIso); + string systemVmIsoPath = systemVmIso; + lock (systemVmIso) + { + systemVmIsoPath = systemVmIso; + String uriStr = (String)cmd.secondaryStorage; + if (!String.IsNullOrEmpty(uriStr)) + { + if (String.IsNullOrEmpty(systemVmIsoPath) || !File.Exists(systemVmIsoPath)) + { + NFSTO share = new NFSTO(); + share.uri = new Uri(uriStr); + string defaultDataPath = wmiCallsV2.GetDefaultDataRoot(); + + string secondaryPath = Utils.NormalizePath(Path.Combine(share.UncPath, "systemvm")); + string[] choices = choices = Directory.GetFiles(secondaryPath, "systemvm*.iso"); + if (choices.Length != 1) + { + String errMsg = "Couldn't locate the systemvm iso on " + secondaryPath; + logger.Debug(errMsg); + } + else + { + systemVmIsoPath = Utils.NormalizePath(Path.Combine(defaultDataPath, Path.GetFileName(choices[0]))); + if (!File.Exists(systemVmIsoPath)) + { + Utils.DownloadCifsFileToLocalFile(choices[0], share, systemVmIsoPath); + } + systemVmIso = systemVmIsoPath; + } + } + } + } + + wmiCallsV2.DeployVirtualMachine(cmd, systemVmIsoPath); result = true; } catch (Exception wmiEx) @@ -1017,7 +1162,7 @@ namespace HypervResource { using (log4net.NDC.Push(Guid.NewGuid().ToString())) { - logger.Info(CloudStackTypes.CreateObjectCommand + cmd.ToString()); + logger.Info(CloudStackTypes.CreateObjectCommand + Utils.CleanString(cmd.ToString())); bool result = false; string details = null; @@ -1027,7 +1172,7 @@ namespace HypervResource VolumeObjectTO volume = VolumeObjectTO.ParseJson(cmd.data); PrimaryDataStoreTO primary = volume.primaryDataStore; ulong volumeSize = volume.size; - string volumeName = volume.name + ".vhdx"; + string volumeName = volume.name + ".vhd"; string volumePath = null; if (primary.isLocal) @@ -1037,7 +1182,7 @@ namespace HypervResource else { volumePath = @"\\" + primary.uri.Host + primary.uri.LocalPath + @"\" + volumeName; - volumePath = volumePath.Replace('/', '\\'); + volumePath = Utils.NormalizePath(volumePath); Utils.ConnectToRemote(primary.UncPath, primary.Domain, primary.User, primary.Password); } @@ -1083,6 +1228,7 @@ namespace HypervResource object ansContent = new { result = true, + willMigrate = true, details = "success - NOP for MaintainCommand", _reconnect = false, contextMap = contextMap @@ -1136,6 +1282,88 @@ namespace HypervResource } } + // POST api/HypervResource/ModifyVmVnicVlanCommand + [HttpPost] + [ActionName(CloudStackTypes.ModifyVmNicConfigCommand)] + public JContainer ModifyVmNicConfigCommand([FromBody]dynamic cmd) + { + + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.ModifyVmNicConfigCommand + cmd.ToString()); + bool result = false; + String vmName = cmd.vmName; + uint vlan = (uint)cmd.vlan; + string macAddress = cmd.macAddress; + wmiCallsV2.ModifyVmVLan(vmName, vlan, macAddress); + + result = true; + + object ansContent = new + { + vmName = vmName, + result = result, + contextMap = contextMap + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.ModifyVmNicConfigAnswer); + } + + } + + // POST api/HypervResource/GetVmConfigCommand + [HttpPost] + [ActionName(CloudStackTypes.GetVmConfigCommand)] + public JContainer GetVmConfigCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.GetVmConfigCommand + cmd.ToString()); + bool result = false; + String vmName = cmd.vmName; + ComputerSystem vm = wmiCallsV2.GetComputerSystem(vmName); + List nicDetails = new List(); + var nicSettingsViaVm = wmiCallsV2.GetEthernetPortSettings(vm); + NicDetails nic = null; + String[] macAddress = new String[nicSettingsViaVm.Length]; + int index = 0; + foreach (SyntheticEthernetPortSettingData item in nicSettingsViaVm) + { + macAddress[index++] = item.Address; + } + + index = 0; + var ethernetConnections = wmiCallsV2.GetEthernetConnections(vm); + int vlanid = 1; + foreach (EthernetPortAllocationSettingData item in ethernetConnections) + { + EthernetSwitchPortVlanSettingData vlanSettings = wmiCallsV2.GetVlanSettings(item); + if (vlanSettings == null) + { + vlanid = -1; + } + else + { + vlanid = vlanSettings.AccessVlanId; + } + nic = new NicDetails(macAddress[index++], vlanid); + nicDetails.Add(nic); + } + + result = true; + + object ansContent = new + { + vmName = vmName, + nics = nicDetails, + result = result, + contextMap = contextMap + }; + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.GetVmConfigAnswer); + } + } + + + // POST api/HypervResource/GetVmStatsCommand [HttpPost] [ActionName(CloudStackTypes.GetVmStatsCommand)] @@ -1187,39 +1415,58 @@ namespace HypervResource using (log4net.NDC.Push(Guid.NewGuid().ToString())) { // Log command *after* we've removed security details from the command. + logger.Info(CloudStackTypes.CopyCommand + Utils.CleanString(cmd.ToString())); bool result = false; string details = null; object newData = null; + TemplateObjectTO destTemplateObjectTO = null; + VolumeObjectTO destVolumeObjectTO = null; + VolumeObjectTO srcVolumeObjectTO = null; + TemplateObjectTO srcTemplateObjectTO = null; try { dynamic timeout = cmd.wait; // TODO: Useful? - TemplateObjectTO srcTemplateObjectTO = TemplateObjectTO.ParseJson(cmd.srcTO); - TemplateObjectTO destTemplateObjectTO = TemplateObjectTO.ParseJson(cmd.destTO); - VolumeObjectTO destVolumeObjectTO = VolumeObjectTO.ParseJson(cmd.destTO); - - logger.Info(CloudStackTypes.CopyCommand + cmd.ToString()); + srcTemplateObjectTO = TemplateObjectTO.ParseJson(cmd.srcTO); + destTemplateObjectTO = TemplateObjectTO.ParseJson(cmd.destTO); + srcVolumeObjectTO = VolumeObjectTO.ParseJson(cmd.srcTO); + destVolumeObjectTO = VolumeObjectTO.ParseJson(cmd.destTO); string destFile = null; - if (destTemplateObjectTO != null && destTemplateObjectTO.primaryDataStore != null) + if (destTemplateObjectTO != null) { - destFile = destTemplateObjectTO.FullFileName; - if (!destTemplateObjectTO.primaryDataStore.isLocal) + if (destTemplateObjectTO.primaryDataStore != null) { - PrimaryDataStoreTO primary = destTemplateObjectTO.primaryDataStore; - Utils.ConnectToRemote(primary.UncPath, primary.Domain, primary.User, primary.Password); + destFile = destTemplateObjectTO.FullFileName; + if (!destTemplateObjectTO.primaryDataStore.isLocal) + { + PrimaryDataStoreTO primary = destTemplateObjectTO.primaryDataStore; + Utils.ConnectToRemote(primary.UncPath, primary.Domain, primary.User, primary.Password); + } + } + else if (destTemplateObjectTO.nfsDataStoreTO != null) + { + destFile = destTemplateObjectTO.FullFileName; + NFSTO store = destTemplateObjectTO.nfsDataStoreTO; + Utils.ConnectToRemote(store.UncPath, store.Domain, store.User, store.Password); } } - // Already exists? + // Template already downloaded? if (destFile != null && File.Exists(destFile) && !String.IsNullOrEmpty(destTemplateObjectTO.checksum)) { // TODO: checksum fails us, because it is of the compressed image. // ASK: should we store the compressed or uncompressed version or is the checksum not calculated correctly? + logger.Debug(CloudStackTypes.CopyCommand + " calling VerifyChecksum to see if we already have the file at " + destFile); result = VerifyChecksum(destFile, destTemplateObjectTO.checksum); + if (!result) + { + result = true; + logger.Debug(CloudStackTypes.CopyCommand + " existing file has different checksum " + destFile); + } } // Do we have to create a new one? @@ -1301,28 +1548,116 @@ namespace HypervResource // Create volume from a template? else if (srcTemplateObjectTO != null && destVolumeObjectTO != null) { - if (destVolumeObjectTO.format == null) + // VolumeObjectTO guesses file extension based on existing files + // this can be wrong if the previous file had a different file type + var guessedDestFile = destVolumeObjectTO.FullFileName; + if (File.Exists(guessedDestFile)) { - destVolumeObjectTO.format = srcTemplateObjectTO.format; + logger.Info("Deleting existing file " + guessedDestFile); + File.Delete(guessedDestFile); } - destFile = destVolumeObjectTO.FullFileName; - string srcFile = srcTemplateObjectTO.FullFileName; + destVolumeObjectTO.format = srcTemplateObjectTO.format; + destFile = destVolumeObjectTO.FullFileName; + if (File.Exists(destFile)) + { + logger.Info("Deleting existing file " + destFile); + File.Delete(destFile); + } + + string srcFile = srcTemplateObjectTO.FullFileName; if (!File.Exists(srcFile)) { details = "Local template file missing from " + srcFile; } else { - if (File.Exists(destFile)) - { - logger.Info("Deleting existing file " + destFile); - File.Delete(destFile); - } - // TODO: thin provision instead of copying the full file. File.Copy(srcFile, destFile); - newData = cmd.destTO; + destVolumeObjectTO.path = destFile; + JObject ansObj = Utils.CreateCloudStackObject(CloudStackTypes.VolumeObjectTO, destVolumeObjectTO); + newData = ansObj; + result = true; + } + } + else if (srcVolumeObjectTO != null && destVolumeObjectTO != null) + { + var guessedDestFile = destVolumeObjectTO.FullFileName; + if (File.Exists(guessedDestFile)) + { + logger.Info("Deleting existing file " + guessedDestFile); + File.Delete(guessedDestFile); + } + + destVolumeObjectTO.format = srcVolumeObjectTO.format; + destFile = destVolumeObjectTO.FullFileName; + if (File.Exists(destFile)) + { + logger.Info("Deleting existing file " + destFile); + File.Delete(destFile); + } + + string srcFile = srcVolumeObjectTO.FullFileName; + if (!File.Exists(srcFile)) + { + details = "Local template file missing from " + srcFile; + } + else + { + // Create the directory before copying the files. CreateDirectory + // doesn't do anything if the directory is already present. + Directory.CreateDirectory(Path.GetDirectoryName(destFile)); + File.Copy(srcFile, destFile); + // Create volumeto object deserialize and send it + destVolumeObjectTO.path = destFile; + JObject ansObj = Utils.CreateCloudStackObject(CloudStackTypes.VolumeObjectTO, destVolumeObjectTO); + newData = ansObj; + result = true; + } + } + else if (srcVolumeObjectTO != null && destTemplateObjectTO != null) + { + var guessedDestFile = destTemplateObjectTO.FullFileName; + if (File.Exists(guessedDestFile)) + { + logger.Info("Deleting existing file " + guessedDestFile); + File.Delete(guessedDestFile); + } + + destTemplateObjectTO.format = srcVolumeObjectTO.format; + destFile = destTemplateObjectTO.FullFileName; + if (File.Exists(destFile)) + { + logger.Info("Deleting existing file " + destFile); + File.Delete(destFile); + } + + string srcFile = srcVolumeObjectTO.FullFileName; + if (!File.Exists(srcFile)) + { + details = "Local template file missing from " + srcFile; + } + else + { + // Create the directory before copying the files. CreateDirectory + // doesn't do anything if the directory is already present. + Directory.CreateDirectory(Path.GetDirectoryName(destFile)); + File.Copy(srcFile, destFile); + + FileInfo destFileInfo = new FileInfo(destFile); + // Write the template.properties file + PostCreateTemplate(Path.GetDirectoryName(destFile), destTemplateObjectTO.id, destTemplateObjectTO.name, + destFileInfo.Length.ToString(), srcVolumeObjectTO.size.ToString(), destTemplateObjectTO.format); + + TemplateObjectTO destTemplateObject = new TemplateObjectTO(); + destTemplateObject.size = srcVolumeObjectTO.size.ToString(); + destTemplateObject.format = srcVolumeObjectTO.format; + destTemplateObject.path = destFile; + destTemplateObject.nfsDataStoreTO = destTemplateObjectTO.nfsDataStoreTO; + destTemplateObject.checksum = destTemplateObjectTO.checksum; + newData = destTemplateObject; + JObject ansObj = Utils.CreateCloudStackObject(CloudStackTypes.TemplateObjectTO, destTemplateObject); + newData = ansObj; result = true; } } @@ -1343,13 +1678,37 @@ namespace HypervResource { result = result, details = details, - newData = cmd.destTO, + newData = newData, contextMap = contextMap }; return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CopyCmdAnswer); } } + private static void PostCreateTemplate(string path, string templateId, string templateUuid, string physicalSize, string virtualSize, string format) + { + string templatePropFile = Path.Combine(path, "template.properties"); + using (StreamWriter sw = new StreamWriter(File.Open(templatePropFile, FileMode.Create), Encoding.GetEncoding("iso-8859-1"))) + { + if (format != null) + { + format = format.ToLower(); + } + + sw.NewLine = "\n"; + sw.WriteLine("id=" + templateId); + sw.WriteLine("filename=" + templateUuid + "." + format); + sw.WriteLine(format + ".filename=" + templateUuid + "." + format); + sw.WriteLine("uniquename=" + templateUuid); + sw.WriteLine(format + "=true"); + sw.WriteLine("virtualsize=" + virtualSize); + sw.WriteLine(format + ".virtualsize=" + virtualSize); + sw.WriteLine("size=" + physicalSize); + sw.WriteLine(format + ".size=" + physicalSize); + sw.WriteLine("public=false"); + } + } + private static bool VerifyChecksum(string destFile, string checksum) { string localChecksum = BitConverter.ToString(CalcFileChecksum(destFile)).Replace("-", "").ToLower(); @@ -1358,7 +1717,7 @@ namespace HypervResource { return true; } - return true; + return false; } /// @@ -1432,7 +1791,7 @@ namespace HypervResource { using (log4net.NDC.Push(Guid.NewGuid().ToString())) { - logger.Info(CloudStackTypes.GetStorageStatsCommand + cmd.ToString()); + logger.Info(CloudStackTypes.GetStorageStatsCommand + Utils.CleanString(cmd.ToString())); bool result = false; string details = null; long capacity = 0; @@ -1440,11 +1799,42 @@ namespace HypervResource long used = 0; try { - string localPath = (string)cmd.localPath; - GetCapacityForLocalPath(localPath, out capacity, out available); - used = capacity - available; - result = true; - logger.Debug(CloudStackTypes.GetStorageStatsCommand + " set used bytes to " + used); + StoragePoolType poolType; + string poolId = (string)cmd.id; + string hostPath = null; + if (!Enum.TryParse((string)cmd.pooltype, out poolType)) + { + details = "Request to get unsupported pool type: " + ((string)cmd.pooltype == null ? "NULL" : (string)cmd.pooltype) + "in cmd " + + JsonConvert.SerializeObject(cmd); + logger.Error(details); + } + else if (poolType == StoragePoolType.Filesystem) + { + hostPath = (string)cmd.localPath;; + GetCapacityForLocalPath(hostPath, out capacity, out available); + used = capacity - available; + result = true; + } + else if (poolType == StoragePoolType.NetworkFilesystem) + { + string sharePath = config.getPrimaryStorage((string)cmd.id); + if (sharePath != null) + { + hostPath = sharePath; + Utils.GetShareDetails(sharePath, out capacity, out available); + used = capacity - available; + result = true; + } + } + else + { + result = false; + } + + if (result) + { + logger.Debug(CloudStackTypes.GetStorageStatsCommand + " set used bytes for " + hostPath + " to " + used); + } } catch (Exception ex) { @@ -1609,21 +1999,39 @@ namespace HypervResource dynamic strtRouteCmd = cmdArray[0][CloudStackTypes.StartupRoutingCommand]; // Insert networking details - strtRouteCmd.privateIpAddress = config.PrivateIpAddress; - strtRouteCmd.privateNetmask = config.PrivateNetmask; - strtRouteCmd.privateMacAddress = config.PrivateMacAddress; - strtRouteCmd.storageIpAddress = config.PrivateIpAddress; - strtRouteCmd.storageNetmask = config.PrivateNetmask; - strtRouteCmd.storageMacAddress = config.PrivateMacAddress; - strtRouteCmd.gatewayIpAddress = config.GatewayIpAddress; + string privateIpAddress = strtRouteCmd.privateIpAddress; + string subnet; + System.Net.NetworkInformation.NetworkInterface privateNic = GetNicInfoFromIpAddress(privateIpAddress, out subnet); + strtRouteCmd.privateIpAddress = privateIpAddress; + strtRouteCmd.privateNetmask = subnet; + strtRouteCmd.privateMacAddress = privateNic.GetPhysicalAddress().ToString(); + string storageip = strtRouteCmd.storageIpAddress; + System.Net.NetworkInformation.NetworkInterface storageNic = GetNicInfoFromIpAddress(storageip, out subnet); + + strtRouteCmd.storageIpAddress = storageip; + strtRouteCmd.storageNetmask = subnet; + strtRouteCmd.storageMacAddress = storageNic.GetPhysicalAddress().ToString(); + strtRouteCmd.gatewayIpAddress = storageNic.GetPhysicalAddress().ToString(); + strtRouteCmd.caps = "hvm"; + dynamic details = strtRouteCmd.hostDetails; + if (details != null) + { + string productVersion = System.Environment.OSVersion.Version.Major.ToString() + "." + + System.Environment.OSVersion.Version.Minor.ToString(); + details.Add("product_version", productVersion); + details.Add("rdp.server.port", 2179); + } + // Detect CPUs, speed, memory uint cores; uint mhz; - wmiCallsV2.GetProcessorResources(out cores, out mhz); + uint sockets; + wmiCallsV2.GetProcessorResources(out sockets, out cores, out mhz); strtRouteCmd.cpus = cores; strtRouteCmd.speed = mhz; + strtRouteCmd.cpuSockets = sockets; ulong memoryKBs; ulong freeMemoryKBs; wmiCallsV2.GetMemoryResources(out memoryKBs, out freeMemoryKBs); @@ -1693,12 +2101,53 @@ namespace HypervResource } } + // POST api/HypervResource/GetVncPortCommand + [HttpPost] + [ActionName(CloudStackTypes.GetVncPortCommand)] + public JContainer GetVncPortCommand([FromBody]dynamic cmd) + { + using (log4net.NDC.Push(Guid.NewGuid().ToString())) + { + logger.Info(CloudStackTypes.GetVncPortCommand + cmd.ToString()); + + string details = null; + bool result = false; + string address = null; + int port = -9; + + try + { + string vmName = (string)cmd.name; + var sys = wmiCallsV2.GetComputerSystem(vmName); + address = "instanceId=" + sys.Name ; + result = true; + } + catch (Exception sysEx) + { + details = CloudStackTypes.GetVncPortAnswer + " failed due to " + sysEx.Message; + logger.Error(details, sysEx); + } + + object ansContent = new + { + result = result, + details = details, + address = address, + port = port + }; + + return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.GetVncPortAnswer); + } + } + public static System.Net.NetworkInformation.NetworkInterface GetNicInfoFromIpAddress(string ipAddress, out string subnet) { System.Net.NetworkInformation.NetworkInterface[] nics = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); + System.Net.NetworkInformation.NetworkInterface defaultnic = null; foreach (var nic in nics) { subnet = null; + defaultnic = nic; // TODO: use to remove NETMASK and MAC from the config file, and to validate the IPAddress. var nicProps = nic.GetIPProperties(); bool found = false; @@ -1716,7 +2165,9 @@ namespace HypervResource } return nic; } - throw new ArgumentException("No NIC for ipAddress " + ipAddress); + var defaultSubnet = defaultnic.GetIPProperties().UnicastAddresses[0]; + subnet = defaultSubnet.IPv4Mask.ToString(); + return defaultnic; } public static void GetCapacityForLocalPath(string localStoragePath, out long capacityBytes, out long availableBytes) diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/IWmiCallsV2.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/IWmiCallsV2.cs index 99ce35276b7..9042d7c5e12 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/IWmiCallsV2.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/IWmiCallsV2.cs @@ -27,9 +27,10 @@ namespace HypervResource { public interface IWmiCallsV2 { - System.Management.ManagementPath AddDiskDriveToVm(ComputerSystem vm, string vhdfile, string cntrllerAddr, string driveResourceType); + System.Management.ManagementPath AddDiskDriveToIdeController(ComputerSystem vm, string vhdfile, string cntrllerAddr, string driveResourceType); ComputerSystem AddUserData(ComputerSystem vm, string userData); void AttachIso(string displayName, string iso); + void AttachDisk(string vmName, string diskPath, string addressOnController); void CreateDynamicVirtualHardDisk(ulong MaxInternalSize, string Path); SyntheticEthernetPortSettingData CreateNICforVm(ComputerSystem vm, string mac); ComputerSystem CreateVM(string name, long memory_mb, int vcpus); @@ -51,7 +52,7 @@ namespace HypervResource KvpExchangeComponentSettingData GetKvpSettings(VirtualSystemSettingData vmSettings); void GetMemoryResources(out ulong physicalRamKBs, out ulong freeMemoryKBs); MemorySettingData GetMemSettings(VirtualSystemSettingData vmSettings); - void GetProcessorResources(out uint cores, out uint mhz); + void GetProcessorResources(out uint sockets, out uint cores, out uint mhz); void GetProcessorUsageInfo(out double cpuUtilization); ProcessorSettingData GetProcSettings(VirtualSystemSettingData vmSettings); ResourceAllocationSettingData.ResourceAllocationSettingDataCollection GetResourceAllocationSettings(VirtualSystemSettingData vmSettings); @@ -65,5 +66,6 @@ namespace HypervResource void patchSystemVmIso(string vmName, string systemVmIso); void SetState(ComputerSystem vm, ushort requiredState); Dictionary GetVmSync(String privateIpAddress); + void ModifyVmVLan(string vmName, uint vlanid, string mac); } } diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/Utils.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/Utils.cs index 0f7505d67d8..6ebc5bf7f23 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/Utils.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/Utils.cs @@ -56,6 +56,16 @@ namespace HypervResource return objContent; } + public static string NormalizePath(string path) + { + if (!String.IsNullOrEmpty(path)) + { + path = path.Replace('/', Path.DirectorySeparatorChar); + } + + return path; + } + /// /// Copy file on network share to local volume. /// @@ -80,7 +90,7 @@ namespace HypervResource if (filePathRelativeToShare.EndsWith(".iso") || filePathRelativeToShare.EndsWith(".vhd") || filePathRelativeToShare.EndsWith(".vhdx")) { dest = Path.Combine(cifsShareDetails.UncPath, filePathRelativeToShare); - dest = dest.Replace('/', Path.DirectorySeparatorChar); + dest = Utils.NormalizePath(dest); } // if the filePathRelativeToShare string don't have filename and only a dir point then find the vhd files in that folder and use // In the clean setup, first copy command wont be having the filename it contains onlyu dir path. @@ -117,7 +127,7 @@ namespace HypervResource { NETRESOURCE nr = new NETRESOURCE(); nr.dwType = RESOURCETYPE_DISK; - nr.lpRemoteName = remoteUNC.Replace('/', Path.DirectorySeparatorChar); + nr.lpRemoteName = Utils.NormalizePath(remoteUNC); if (domain != null) { username = domain + @"\" + username; @@ -154,6 +164,16 @@ namespace HypervResource capacity = totalNumberOfBytes > 0 ? (long)totalNumberOfBytes : 0; } + public static string CleanString(string stringToClean) + { + string cleanString = null; + string regexQueryString = "(&|%26)?(password|accesskey|secretkey)(=|%3D).*?(?=(%26|[&'\"]))"; + string regexJson = "\"(password|accesskey|secretkey)\":\".*?\",?"; + cleanString = System.Text.RegularExpressions.Regex.Replace(stringToClean, regexQueryString, ""); + cleanString = System.Text.RegularExpressions.Regex.Replace(cleanString, regexJson, ""); + return cleanString; + } + // from http://stackoverflow.com/a/2541569/939250 #region imports [DllImport("advapi32.dll", SetLastError = true)] diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/WmiCallsV2.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/WmiCallsV2.cs index c6c039a9bed..b9694f00eca 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/WmiCallsV2.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/WmiCallsV2.cs @@ -207,14 +207,14 @@ namespace HypervResource return new SyntheticEthernetPortSettingData(newResourcePaths[0]); } - public const string IDE_HARDDISK_CONTROLLER = "Microsoft:Hyper-V:Emulated IDE Controller"; + public const string IDE_CONTROLLER = "Microsoft:Hyper-V:Emulated IDE Controller"; public const string SCSI_CONTROLLER = "Microsoft:Hyper-V:Synthetic SCSI Controller"; - public const string IDE_HARDDISK_DRIVE = "Microsoft:Hyper-V:Synthetic Disk Drive"; - public const string IDE_ISO_DRIVE = "Microsoft:Hyper-V:Synthetic DVD Drive"; + public const string HARDDISK_DRIVE = "Microsoft:Hyper-V:Synthetic Disk Drive"; + public const string ISO_DRIVE = "Microsoft:Hyper-V:Synthetic DVD Drive"; // TODO: names harvested from Msvm_ResourcePool, not clear how to create new instances - public const string IDE_ISO_DISK = "Microsoft:Hyper-V:Virtual CD/DVD Disk"; // For IDE_ISO_DRIVE - public const string IDE_HARDDISK_DISK = "Microsoft:Hyper-V:Virtual Hard Disk"; // For IDE_HARDDISK_DRIVE + public const string ISO_DISK = "Microsoft:Hyper-V:Virtual CD/DVD Disk"; // For IDE_ISO_DRIVE + public const string HARDDISK_DISK = "Microsoft:Hyper-V:Virtual Hard Disk"; // For IDE_HARDDISK_DRIVE /// /// Create new VM. By default we start it. @@ -280,7 +280,7 @@ namespace HypervResource var newVm = CreateVM(vmName, memSize, vcpus); // Add a SCSI controller for attaching/detaching data volumes. - AddScsiControllerToVm(newVm); + AddScsiController(newVm); foreach (var diskDrive in diskDrives) { @@ -335,21 +335,22 @@ namespace HypervResource NFSTO share = templateInfo.nfsDataStoreTO; Utils.ConnectToRemote(share.UncPath, share.Domain, share.User, share.Password); // The share is mapped, now attach the iso - isoPath = Path.Combine(share.UncPath.Replace('/', Path.DirectorySeparatorChar), templateInfo.path); + isoPath = Utils.NormalizePath(Path.Combine(share.UncPath, templateInfo.path)); } string driveType = diskDrive.type; - string ideCtrllr = "0"; string driveResourceType = null; switch (driveType) { case "ROOT": ideCtrllr = "0"; - driveResourceType = IDE_HARDDISK_DRIVE; + driveResourceType = HARDDISK_DRIVE; break; case "ISO": ideCtrllr = "1"; - driveResourceType = IDE_ISO_DRIVE; + driveResourceType = ISO_DRIVE; + break; + case "DATADISK": break; default: // TODO: double check exception type @@ -360,12 +361,20 @@ namespace HypervResource logger.Error(errMsg, ex); throw ex; } - logger.DebugFormat("Create disk type {1} (Named: {0}), on vm {2} {3}", diskName, driveResourceType, vmName, - string.IsNullOrEmpty(vhdFile) ? " no disk to insert" : ", inserting disk" +vhdFile ); - AddDiskDriveToVm(newVm, vhdFile, ideCtrllr, driveResourceType); - if (isoPath != null) + + logger.DebugFormat("Create disk type {1} (Named: {0}), on vm {2} {3}", diskName, driveResourceType, vmName, + string.IsNullOrEmpty(vhdFile) ? " no disk to insert" : ", inserting disk" + vhdFile); + if (driveType.Equals("DATADISK")) { - AttachIso(vmName, isoPath); + AttachDisk(vmName, vhdFile, (string)diskDrive.diskSeq); + } + else + { + AddDiskDriveToIdeController(newVm, vhdFile, ideCtrllr, driveResourceType); + if (isoPath != null) + { + AttachIso(vmName, isoPath); + } } } @@ -381,9 +390,17 @@ namespace HypervResource string mac = nic.mac; string vlan = null; string isolationUri = nic.isolationUri; - if (isolationUri != null && isolationUri.StartsWith("vlan://") && !isolationUri.Equals("vlan://untagged")) + string broadcastUri = nic.broadcastUri; + if ( (broadcastUri != null ) || (isolationUri != null && isolationUri.StartsWith("vlan://")) && !isolationUri.Equals("vlan://untagged")) { - vlan = isolationUri.Substring("vlan://".Length); + if (broadcastUri != null && broadcastUri.StartsWith("storage")) + { + vlan = broadcastUri.Substring("storage://".Length); + } + else + { + vlan = isolationUri.Substring("vlan://".Length); + } int tmp; if (!int.TryParse(vlan, out tmp)) { @@ -426,6 +443,7 @@ namespace HypervResource nicCount++; } + // pass the boot args for the VM using KVP component. // We need to pass the boot args to system vm's to get them configured with cloudstack configuration. // Add new user data @@ -436,13 +454,6 @@ namespace HypervResource String bootargs = bootArgs; AddUserData(vm, bootargs); - - // Get existing KVP - //var vmSettings = GetVmSettings(vm); - //var kvpInfo = GetKvpSettings(vmSettings); - //logger.DebugFormat("Boot Args presisted on the VM are ", kvpInfo); - //AddUserData(vm, bootargs); - // Verify key added to subsystem //kvpInfo = GetKvpSettings(vmSettings); @@ -453,7 +464,10 @@ namespace HypervResource // call patch systemvm iso only for systemvms if (vmName.StartsWith("r-") || vmName.StartsWith("s-") || vmName.StartsWith("v-")) { - patchSystemVmIso(vmName, systemVmIso); + if (systemVmIso != null && systemVmIso.Length != 0) + { + patchSystemVmIso(vmName, systemVmIso); + } } logger.DebugFormat("Starting VM {0}", vmName); @@ -463,17 +477,16 @@ namespace HypervResource if (vmName.StartsWith("r-") || vmName.StartsWith("s-") || vmName.StartsWith("v-")) { System.Threading.Thread.Sleep(90000); - SetState(newVm, RequiredState.Reset); // wait for the second boot and then return with sucesss //if publicIPAddress is empty or null don't ping the ip - if (publicIpAddress.Equals("") == true) + /*if (publicIpAddress.Equals("") == true) { System.Threading.Thread.Sleep(90000); } else { pingResource(publicIpAddress); - } + }*/ } logger.InfoFormat("Started VM {0}", vmName); return newVm; @@ -485,7 +498,7 @@ namespace HypervResource PingReply pingReply = null; IPAddress ipAddress = null; Ping pingSender = new Ping(); - int numberOfPings = 4; + int numberOfPings = 6; int pingTimeout = 1000; int byteSize = 32; byte[] buffer = new byte[byteSize]; @@ -563,16 +576,36 @@ namespace HypervResource public void patchSystemVmIso(String vmName, String systemVmIso) { ComputerSystem vmObject = GetComputerSystem(vmName); - AddDiskDriveToVm(vmObject, "", "1", IDE_ISO_DRIVE); + AddDiskDriveToIdeController(vmObject, "", "1", ISO_DRIVE); AttachIso(vmName, systemVmIso); } + public void AttachDisk(string vmName, string diskPath, string addressOnController) + { + logger.DebugFormat("Got request to attach disk {0} to vm {1}", diskPath, vmName); + + ComputerSystem vm = GetComputerSystem(vmName); + if (vm == null) + { + logger.DebugFormat("VM {0} not found", vmName); + return; + } + else + { + ManagementPath newDrivePath = GetDiskDriveOnScsiController(vm, addressOnController); + if (newDrivePath == null) + { + newDrivePath = AttachDiskDriveToScsiController(vm, addressOnController); + } + InsertDiskImage(vm, diskPath, HARDDISK_DISK, newDrivePath); + } + } /// /// /// /// IDE_HARDDISK_DRIVE or IDE_ISO_DRIVE - public ManagementPath AddDiskDriveToVm(ComputerSystem vm, string vhdfile, string cntrllerAddr, string driveResourceType) + public ManagementPath AddDiskDriveToIdeController(ComputerSystem vm, string vhdfile, string cntrllerAddr, string driveResourceType) { logger.DebugFormat("Creating DISK for VM {0} (GUID {1}) by attaching {2}", vm.ElementName, @@ -582,11 +615,11 @@ namespace HypervResource // Determine disk type for drive and assert drive type valid string diskResourceSubType = null; switch(driveResourceType) { - case IDE_HARDDISK_DRIVE: - diskResourceSubType = IDE_HARDDISK_DISK; + case HARDDISK_DRIVE: + diskResourceSubType = HARDDISK_DISK; break; - case IDE_ISO_DRIVE: - diskResourceSubType = IDE_ISO_DISK; + case ISO_DRIVE: + diskResourceSubType = ISO_DISK; break; default: var errMsg = string.Format( @@ -599,7 +632,7 @@ namespace HypervResource throw ex; } - ManagementPath newDrivePath = AttachNewDriveToVm(vm, cntrllerAddr, driveResourceType); + ManagementPath newDrivePath = AttachNewDrive(vm, cntrllerAddr, driveResourceType); // If there's not disk to insert, we are done. if (String.IsNullOrEmpty(vhdfile)) @@ -626,7 +659,7 @@ namespace HypervResource } else { - RemoveStorageImageFromVm(vm, diskFileName); + RemoveStorageImage(vm, diskFileName); } } @@ -635,7 +668,7 @@ namespace HypervResource /// /// /// - private void RemoveStorageImageFromVm(ComputerSystem vm, string diskFileName) + private void RemoveStorageImage(ComputerSystem vm, string diskFileName) { // Obtain StorageAllocationSettingData for disk StorageAllocationSettingData.StorageAllocationSettingDataCollection storageSettingsObjs = StorageAllocationSettingData.GetInstances(); @@ -671,13 +704,13 @@ namespace HypervResource RemoveStorageResource(imageToRemove.Path, vm); - logger.InfoFormat("REmoved disk image {0} from VM {1} (GUID {2}): the disk image is not attached.", + logger.InfoFormat("Removed disk image {0} from VM {1} (GUID {2}): the disk image is not attached.", diskFileName, vm.ElementName, vm.Name); } - private ManagementPath AttachNewDriveToVm(ComputerSystem vm, string cntrllerAddr, string driveType) + private ManagementPath AttachNewDrive(ComputerSystem vm, string cntrllerAddr, string driveType) { // Disk drives are attached to a 'Parent' IDE controller. We IDE Controller's settings for the 'Path', which our new Disk drive will use to reference it. VirtualSystemSettingData vmSettings = GetVmSettings(vm); @@ -719,7 +752,7 @@ namespace HypervResource return newDrivePaths[0]; } - private ManagementPath AddScsiControllerToVm(ComputerSystem vm) + private ManagementPath AddScsiController(ComputerSystem vm) { // A description of the controller is created by modifying a clone of the default ResourceAllocationSettingData for scsi controller string scsiQuery = String.Format("ResourceSubType LIKE \"{0}\" AND InstanceID LIKE \"%Default\"", SCSI_CONTROLLER); @@ -751,6 +784,66 @@ namespace HypervResource return newResourcePaths[0]; } + private ManagementPath GetDiskDriveOnScsiController(ComputerSystem vm, string addrOnController) + { + VirtualSystemSettingData vmSettings = GetVmSettings(vm); + var wmiObjCollection = GetResourceAllocationSettings(vmSettings); + foreach (ResourceAllocationSettingData wmiObj in wmiObjCollection) + { + if (wmiObj.ResourceSubType == HARDDISK_DRIVE) + { + ResourceAllocationSettingData parent = new ResourceAllocationSettingData(new ManagementObject(wmiObj.Parent)); + if (parent.ResourceSubType == SCSI_CONTROLLER && wmiObj.AddressOnParent == addrOnController) + { + return wmiObj.Path; + } + } + } + return null; + } + + private ManagementPath AttachDiskDriveToScsiController(ComputerSystem vm, string addrOnController) + { + // Disk drives are attached to a 'Parent' Scsi controller. + VirtualSystemSettingData vmSettings = GetVmSettings(vm); + var ctrller = GetScsiControllerSettings(vmSettings); + + // A description of the drive is created by modifying a clone of the default ResourceAllocationSettingData for that drive type + string defaultDriveQuery = String.Format("ResourceSubType LIKE \"{0}\" AND InstanceID LIKE \"%Default\"", HARDDISK_DRIVE); + var newDiskDriveSettings = CloneResourceAllocationSetting(defaultDriveQuery); + + // Set IDE controller and address on the controller for the new drive + newDiskDriveSettings.LateBoundObject["Parent"] = ctrller.Path.ToString(); + newDiskDriveSettings.LateBoundObject["AddressOnParent"] = addrOnController; + newDiskDriveSettings.CommitObject(); + + // Add this new disk drive to the VM + logger.DebugFormat("Creating disk drive type {0}, parent IDE controller is {1} and address on controller is {2}", + newDiskDriveSettings.ResourceSubType, + newDiskDriveSettings.Parent, + newDiskDriveSettings.AddressOnParent); + string[] newDriveResource = new string[] { newDiskDriveSettings.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20) }; + ManagementPath[] newDrivePaths = AddVirtualResource(newDriveResource, vm); + + // assert + if (newDrivePaths.Length != 1) + { + var errMsg = string.Format( + "Failed to add disk drive type {3} to VM {0} (GUID {1}): number of resource created {2}", + vm.ElementName, + vm.Name, + newDrivePaths.Length, + HARDDISK_DRIVE); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + logger.DebugFormat("New disk drive type {0} WMI path is {1}s", + newDiskDriveSettings.ResourceSubType, + newDrivePaths[0].Path); + return newDrivePaths[0]; + } + private void InsertDiskImage(ComputerSystem vm, string diskImagePath, string diskResourceSubType, ManagementPath drivePath) { @@ -792,16 +885,14 @@ namespace HypervResource /// Create Msvm_StorageAllocationSettingData corresponding to the ISO image, and /// associate this with the VM's DVD drive. /// - private void AttachIsoToVm(ComputerSystem vm, string isoPath) + private void AttachIso(ComputerSystem vm, string isoPath) { // Disk drives are attached to a 'Parent' IDE controller. We IDE Controller's settings for the 'Path', which our new Disk drive will use to reference it. VirtualSystemSettingData vmSettings = GetVmSettings(vm); var driveWmiObj = GetDvdDriveSettings(vmSettings); - InsertDiskImage(vm, isoPath, IDE_ISO_DISK, driveWmiObj.Path); + InsertDiskImage(vm, isoPath, ISO_DISK, driveWmiObj.Path); } - - private static ResourceAllocationSettingData CloneResourceAllocationSetting(string wmiQuery) { var defaultDiskDriveSettingsObjs = ResourceAllocationSettingData.GetInstances(wmiQuery); @@ -819,6 +910,37 @@ namespace HypervResource return new ResourceAllocationSettingData((ManagementBaseObject)defaultDiskDriveSettings.LateBoundObject.Clone()); } + + // Modify the systemvm nic's VLAN id + public void ModifyVmVLan(string vmName, uint vlanid, String mac) + { + ComputerSystem vm = GetComputerSystem(vmName); + SyntheticEthernetPortSettingData[] nicSettingsViaVm = GetEthernetPortSettings(vm); + // Obtain controller for Hyper-V virtualisation subsystem + VirtualSystemManagementService vmMgmtSvc = GetVirtualisationSystemManagementService(); + string normalisedMAC = string.Join("", (mac.Split(new char[] { ':' }))); + int index = 0; + foreach (SyntheticEthernetPortSettingData item in nicSettingsViaVm) + { + if (normalisedMAC.ToLower().Equals(item.Address.ToLower())) + { + break; + } + index++; + } + + //TODO: make sure the index wont be out of range. + + EthernetPortAllocationSettingData[] ethernetConnections = GetEthernetConnections(vm); + EthernetSwitchPortVlanSettingData vlanSettings = GetVlanSettings(ethernetConnections[index]); + + //Assign configuration to new NIC + vlanSettings.LateBoundObject["AccessVlanId"] = vlanid; + vlanSettings.LateBoundObject["OperationMode"] = 1; + ModifyFeatureVmResources(vmMgmtSvc, vm, new String[] { + vlanSettings.LateBoundObject.GetText(TextFormat.CimDtd20)}); + } + public void AttachIso(string displayName, string iso) { logger.DebugFormat("Got request to attach iso {0} to vm {1}", iso, displayName); @@ -831,7 +953,7 @@ namespace HypervResource } else { - AttachIsoToVm(vm, iso); + AttachIso(vm, iso); } } @@ -1330,6 +1452,36 @@ namespace HypervResource return vSwitch; } + + private static void ModifyFeatureVmResources(VirtualSystemManagementService vmMgmtSvc, ComputerSystem vm, string[] resourceSettings) + { + // Resource settings are changed through the management service + System.Management.ManagementPath jobPath; + System.Management.ManagementPath[] results; + + var ret_val = vmMgmtSvc.ModifyFeatureSettings( + resourceSettings, + out jobPath, + out results); + + // If the Job is done asynchronously + if (ret_val == ReturnCode.Started) + { + JobCompleted(jobPath); + } + else if (ret_val != ReturnCode.Completed) + { + var errMsg = string.Format( + "Failed to update VM {0} (GUID {1}) due to {2} (ModifyVirtualSystem call), existing VM not deleted", + vm.ElementName, + vm.Name, + ReturnCode.ToString(ret_val)); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + } + private static void ModifyVmResources(VirtualSystemManagementService vmMgmtSvc, ComputerSystem vm, string[] resourceSettings) { // Resource settings are changed through the management service @@ -1478,7 +1630,7 @@ namespace HypervResource // Is there a template we can use to fill in the settings? var newVirtHDSettings = VirtualHardDiskSettingData.CreateInstance(); newVirtHDSettings.LateBoundObject["Type"] = 3; // Dynamic - newVirtHDSettings.LateBoundObject["Format"] = 3; // VHDX + newVirtHDSettings.LateBoundObject["Format"] = 2; // VHD newVirtHDSettings.LateBoundObject["Path"] = Path; newVirtHDSettings.LateBoundObject["MaxInternalSize"] = MaxInternalSize; newVirtHDSettings.LateBoundObject["BlockSize"] = 0; // Use defaults @@ -1648,16 +1800,18 @@ namespace HypervResource } } - public void GetProcessorResources(out uint cores, out uint mhz) + public void GetProcessorResources(out uint sockets, out uint cores, out uint mhz) { // Processor processors cores = 0; mhz = 0; + sockets = 0; Processor.ProcessorCollection procCol = Processor.GetInstances(); foreach (Processor procInfo in procCol) { cores += procInfo.NumberOfCores; mhz = procInfo.MaxClockSpeed; + sockets++; } } @@ -1824,7 +1978,7 @@ namespace HypervResource foreach (ResourceAllocationSettingData wmiObj in wmiObjCollection) { - if (wmiObj.ResourceSubType == IDE_HARDDISK_CONTROLLER && wmiObj.Address == cntrllerAddr) + if (wmiObj.ResourceSubType == IDE_CONTROLLER && wmiObj.Address == cntrllerAddr) { return wmiObj; } @@ -1839,6 +1993,26 @@ namespace HypervResource throw ex; } + public ResourceAllocationSettingData GetScsiControllerSettings(VirtualSystemSettingData vmSettings) + { + var wmiObjCollection = GetResourceAllocationSettings(vmSettings); + + foreach (ResourceAllocationSettingData wmiObj in wmiObjCollection) + { + if (wmiObj.ResourceSubType == SCSI_CONTROLLER) + { + return wmiObj; + } + } + + var errMsg = string.Format( + "Cannot find the Microsoft Synthetic SCSI Controller in VirtualSystemSettingData {1}", + vmSettings.Path.Path); + var ex = new WmiException(errMsg); + logger.Error(errMsg, ex); + throw ex; + } + /// /// VM resources, typically hardware a described by a generic MSVM_ResourceAllocationSettingData object. The hardware type being /// described is identified in two ways: in general terms using an enum in the ResourceType field, and in terms of the implementation diff --git a/plugins/hypervisors/hyperv/pom.xml b/plugins/hypervisors/hyperv/pom.xml index 162fd641023..fca7cd93680 100644 --- a/plugins/hypervisors/hyperv/pom.xml +++ b/plugins/hypervisors/hyperv/pom.xml @@ -90,7 +90,6 @@ org.apache.maven.plugins maven-surefire-plugin - 2.12 diff --git a/plugins/hypervisors/hyperv/resources/META-INF/cloudstack/core/spring-hyperv-core-context.xml b/plugins/hypervisors/hyperv/resources/META-INF/cloudstack/core/spring-hyperv-core-context.xml new file mode 100644 index 00000000000..84d50ca97e0 --- /dev/null +++ b/plugins/hypervisors/hyperv/resources/META-INF/cloudstack/core/spring-hyperv-core-context.xml @@ -0,0 +1,32 @@ + + + + + + diff --git a/plugins/hypervisors/hyperv/resources/META-INF/cloudstack/hyperv-compute/spring-hyperv-compute-context.xml b/plugins/hypervisors/hyperv/resources/META-INF/cloudstack/hyperv-compute/spring-hyperv-compute-context.xml index 63521618df5..a128fbc8876 100644 --- a/plugins/hypervisors/hyperv/resources/META-INF/cloudstack/hyperv-compute/spring-hyperv-compute-context.xml +++ b/plugins/hypervisors/hyperv/resources/META-INF/cloudstack/hyperv-compute/spring-hyperv-compute-context.xml @@ -20,5 +20,7 @@ - + + + diff --git a/plugins/hypervisors/hyperv/src/com/cloud/ha/HypervInvestigator.java b/plugins/hypervisors/hyperv/src/com/cloud/ha/HypervInvestigator.java new file mode 100644 index 00000000000..cebfb7ac70c --- /dev/null +++ b/plugins/hypervisors/hyperv/src/com/cloud/ha/HypervInvestigator.java @@ -0,0 +1,77 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.cloud.ha; + +import com.cloud.agent.AgentManager; +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.CheckOnHostCommand; +import com.cloud.host.Host; +import com.cloud.host.HostVO; +import com.cloud.host.Status; +import com.cloud.host.dao.HostDao; +import com.cloud.hypervisor.Hypervisor; +import com.cloud.resource.ResourceManager; +import com.cloud.utils.component.AdapterBase; +import org.apache.log4j.Logger; + +import javax.ejb.Local; +import javax.inject.Inject; +import java.util.List; + +@Local(value=Investigator.class) +public class HypervInvestigator extends AdapterBase implements Investigator { + private final static Logger s_logger = Logger.getLogger(HypervInvestigator.class); + @Inject HostDao _hostDao; + @Inject AgentManager _agentMgr; + @Inject ResourceManager _resourceMgr; + + @Override + public Boolean isVmAlive(com.cloud.vm.VirtualMachine vm, Host host) { + Status status = isAgentAlive(host); + if (status == null) { + return null; + } + return status == Status.Up ? true : null; + } + + @Override + public Status isAgentAlive(Host agent) { + if (agent.getHypervisorType() != Hypervisor.HypervisorType.Hyperv) { + return null; + } + CheckOnHostCommand cmd = new CheckOnHostCommand(agent); + List neighbors = _resourceMgr.listHostsInClusterByStatus(agent.getClusterId(), Status.Up); + for (HostVO neighbor : neighbors) { + if (neighbor.getId() == agent.getId() || neighbor.getHypervisorType() != Hypervisor.HypervisorType.Hyperv) { + continue; + } + + try { + Answer answer = _agentMgr.easySend(neighbor.getId(), cmd); + if (answer != null) { + return answer.getResult() ? Status.Down : Status.Up; + } + } catch (Exception e) { + s_logger.debug("Failed to send command to host: " + neighbor.getId()); + } + } + + return null; + } +} diff --git a/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/discoverer/HypervServerDiscoverer.java b/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/discoverer/HypervServerDiscoverer.java index 2a630c7e6db..371a6187407 100644 --- a/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/discoverer/HypervServerDiscoverer.java +++ b/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/discoverer/HypervServerDiscoverer.java @@ -16,12 +16,8 @@ // under the License. package com.cloud.hypervisor.hyperv.discoverer; -import java.io.File; -import java.io.IOException; import java.net.InetAddress; import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; import java.net.UnknownHostException; import java.util.HashMap; import java.util.List; @@ -35,10 +31,6 @@ import javax.naming.ConfigurationException; import org.apache.log4j.Logger; -import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; -import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; -import org.apache.cloudstack.utils.identity.ManagementServerNode; - import com.cloud.agent.AgentManager; import com.cloud.agent.Listener; import com.cloud.agent.api.AgentControlAnswer; @@ -51,7 +43,6 @@ import com.cloud.agent.api.SetupCommand; import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupRoutingCommand; import com.cloud.alert.AlertManager; -import com.cloud.configuration.Config; import com.cloud.dc.ClusterDetailsDao; import com.cloud.dc.ClusterVO; import com.cloud.dc.DataCenterVO; @@ -77,13 +68,7 @@ import com.cloud.resource.ResourceManager; import com.cloud.resource.ResourceStateAdapter; import com.cloud.resource.ServerResource; import com.cloud.resource.UnableDeleteHostException; -import com.cloud.storage.JavaStorageLayer; import com.cloud.storage.StorageLayer; -import com.cloud.utils.FileUtil; -import com.cloud.utils.NumbersUtil; -import com.cloud.utils.db.GlobalLock; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.script.Script; /** * Methods to discover and managem a Hyper-V agent. Prepares a @@ -114,8 +99,6 @@ public class HypervServerDiscoverer extends DiscovererBase implements Discoverer private HostPodDao _podDao; @Inject private DataCenterDao _dcDao; - @Inject - DataStoreManager _dataStoreMgr; // TODO: AgentManager and AlertManager not being used to transmit info, // may want to reconsider. @@ -172,17 +155,8 @@ public class HypervServerDiscoverer extends DiscovererBase implements Discoverer s_logger.debug("Setting up host " + agentId); } - String secondaryStorageUri = getSecondaryStorageStoreUrl(cluster.getDataCenterId()); - if (secondaryStorageUri == null) { - s_logger.debug("Secondary storage uri for dc " + cluster.getDataCenterId() + " couldn't be obtained"); - } else { - prepareSecondaryStorageStore(secondaryStorageUri); - } - HostEnvironment env = new HostEnvironment(); SetupCommand setup = new SetupCommand(env); - setup.setSecondaryStorage(secondaryStorageUri); - setup.setSystemVmIso("systemvm/" + getSystemVMIsoFileNameOnDatastore()); if (!host.isSetup()) { setup.setNeedSetup(true); } @@ -309,7 +283,6 @@ public class HypervServerDiscoverer extends DiscovererBase implements Discoverer params.put("cluster", Long.toString(clusterId)); params.put("guid", guidWithTail); params.put("ipaddress", agentIp); - params.put("sec.storage.url", getSecondaryStorageStoreUrl(dcId)); // Hyper-V specific settings Map details = new HashMap(); @@ -352,175 +325,6 @@ public class HypervServerDiscoverer extends DiscovererBase implements Discoverer return null; } - private void prepareSecondaryStorageStore(String storageUrl) { - String mountPoint = getMountPoint(storageUrl); - - GlobalLock lock = GlobalLock.getInternLock("prepare.systemvm"); - try { - if (lock.lock(3600)) { - try { - File patchFolder = new File(mountPoint + "/systemvm"); - if (!patchFolder.exists()) { - if (!patchFolder.mkdirs()) { - String msg = "Unable to create systemvm folder on secondary storage. location: " + patchFolder.toString(); - s_logger.error(msg); - throw new CloudRuntimeException(msg); - } - } - - File srcIso = getSystemVMPatchIsoFile(); - File destIso = new File(mountPoint + "/systemvm/" + getSystemVMIsoFileNameOnDatastore()); - if (!destIso.exists()) { - s_logger.info("Copy System VM patch ISO file to secondary storage. source ISO: " + srcIso.getAbsolutePath() + ", destination: " + - destIso.getAbsolutePath()); - try { - FileUtil.copyfile(srcIso, destIso); - } catch (IOException e) { - s_logger.error("Unexpected exception ", e); - - String msg = "Unable to copy systemvm ISO on secondary storage. src location: " + srcIso.toString() + ", dest location: " + destIso; - s_logger.error(msg); - throw new CloudRuntimeException(msg); - } - } else { - if (s_logger.isTraceEnabled()) { - s_logger.trace("SystemVM ISO file " + destIso.getPath() + " already exists"); - } - } - } finally { - lock.unlock(); - } - } - } finally { - lock.releaseRef(); - } - } - - private String getMountPoint(String storageUrl) { - String mountPoint = null; - synchronized (_storageMounts) { - mountPoint = _storageMounts.get(storageUrl); - if (mountPoint != null) { - return mountPoint; - } - - URI uri; - try { - uri = new URI(storageUrl); - } catch (URISyntaxException e) { - s_logger.error("Invalid storage URL format ", e); - throw new CloudRuntimeException("Unable to create mount point due to invalid storage URL format " + storageUrl); - } - - mountPoint = mount(File.separator + File.separator + uri.getHost() + uri.getPath(), _mountParent, uri.getScheme(), uri.getQuery()); - if (mountPoint == null) { - s_logger.error("Unable to create mount point for " + storageUrl); - return "/mnt/sec"; - } - - _storageMounts.put(storageUrl, mountPoint); - return mountPoint; - } - } - - protected String mount(String path, String parent, String scheme, String query) { - String mountPoint = setupMountPoint(parent); - if (mountPoint == null) { - s_logger.warn("Unable to create a mount point"); - return null; - } - - Script script = null; - String result = null; - if (scheme.equals("cifs")) { - Script command = new Script(true, "mount", _timeout, s_logger); - command.add("-t", "cifs"); - command.add(path); - command.add(mountPoint); - - if (query != null) { - query = query.replace('&', ','); - command.add("-o", query); - } - result = command.execute(); - } - - if (result != null) { - s_logger.warn("Unable to mount " + path + " due to " + result); - File file = new File(mountPoint); - if (file.exists()) { - file.delete(); - } - return null; - } - - // Change permissions for the mountpoint - script = new Script(true, "chmod", _timeout, s_logger); - script.add("-R", "777", mountPoint); - result = script.execute(); - if (result != null) { - s_logger.warn("Unable to set permissions for " + mountPoint + " due to " + result); - } - return mountPoint; - } - - private String setupMountPoint(String parent) { - String mountPoint = null; - long mshostId = ManagementServerNode.getManagementServerId(); - for (int i = 0; i < 10; i++) { - String mntPt = parent + File.separator + String.valueOf(mshostId) + "." + Integer.toHexString(_rand.nextInt(Integer.MAX_VALUE)); - File file = new File(mntPt); - if (!file.exists()) { - if (_storage.mkdir(mntPt)) { - mountPoint = mntPt; - break; - } - } - s_logger.error("Unable to create mount: " + mntPt); - } - - return mountPoint; - } - - private String getSystemVMIsoFileNameOnDatastore() { - String version = this.getClass().getPackage().getImplementationVersion(); - String fileName = "systemvm-" + version + ".iso"; - return fileName.replace(':', '-'); - } - - private File getSystemVMPatchIsoFile() { - // locate systemvm.iso - URL url = this.getClass().getClassLoader().getResource("vms/systemvm.iso"); - File isoFile = null; - if (url != null) { - isoFile = new File(url.getPath()); - } - - if (isoFile == null || !isoFile.exists()) { - isoFile = new File("/usr/share/cloudstack-common/vms/systemvm.iso"); - } - - assert (isoFile != null); - if (!isoFile.exists()) { - s_logger.error("Unable to locate systemvm.iso in your setup at " + isoFile.toString()); - } - return isoFile; - } - - private String getSecondaryStorageStoreUrl(long zoneId) { - String secUrl = null; - DataStore secStore = _dataStoreMgr.getImageStore(zoneId); - if (secStore != null) { - secUrl = secStore.getUri(); - } - - if (secUrl == null) { - s_logger.warn("Secondary storage uri couldn't be retrieved"); - } - - return secUrl; - } - /** * Encapsulate GUID calculation in public method to allow access to test * programs. Works by converting a string to a GUID using @@ -545,25 +349,6 @@ public class HypervServerDiscoverer extends DiscovererBase implements Discoverer @Override public final boolean configure(final String name, final Map params) throws ConfigurationException { super.configure(name, params); - - _mountParent = (String)params.get(Config.MountParent.key()); - if (_mountParent == null) { - _mountParent = File.separator + "mnt"; - } - - if (_instance != null) { - _mountParent = _mountParent + File.separator + _instance; - } - - String value = (String)params.get("scripts.timeout"); - _timeout = NumbersUtil.parseInt(value, 30) * 1000; - - _storage = (StorageLayer)params.get(StorageLayer.InstanceConfigKey); - if (_storage == null) { - _storage = new JavaStorageLayer(); - _storage.configure("StorageLayer", params); - } - // TODO: allow timeout on we HTTPRequests to be configured _agentMgr.registerForHostEvents(this, true, false, true); _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); diff --git a/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/guru/HypervGuru.java b/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/guru/HypervGuru.java index 5845038bbff..1d9e7f619f9 100644 --- a/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/guru/HypervGuru.java +++ b/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/guru/HypervGuru.java @@ -16,15 +16,30 @@ // under the License. package com.cloud.hypervisor.hyperv.guru; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + import javax.ejb.Local; import javax.inject.Inject; +import com.cloud.agent.api.to.NicTO; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.HypervisorGuru; import com.cloud.hypervisor.HypervisorGuruBase; import com.cloud.storage.GuestOSVO; import com.cloud.storage.dao.GuestOSDao; +import com.cloud.exception.InsufficientAddressCapacityException; +import com.cloud.hypervisor.hyperv.manager.HypervManager; +import com.cloud.network.NetworkModel; +import com.cloud.network.Networks.TrafficType; +import com.cloud.network.dao.NetworkDao; +import com.cloud.network.dao.NetworkVO; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.vm.NicProfile; +import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; /** @@ -35,6 +50,9 @@ public class HypervGuru extends HypervisorGuruBase implements HypervisorGuru { @Inject private GuestOSDao _guestOsDao; + @Inject HypervManager _hypervMgr; + @Inject NetworkDao _networkDao; + @Inject NetworkModel _networkMgr; @Override public final HypervisorType getHypervisorType() { @@ -51,6 +69,78 @@ public class HypervGuru extends HypervisorGuruBase implements HypervisorGuru { @Override public final VirtualMachineTO implement(VirtualMachineProfile vm) { VirtualMachineTO to = toVirtualMachineTO(vm); + List nicProfiles = vm.getNics(); + + if(vm.getVirtualMachine().getType() == VirtualMachine.Type.DomainRouter) { + + NicProfile publicNicProfile = null; + for(NicProfile nicProfile : nicProfiles) { + if(nicProfile.getTrafficType() == TrafficType.Public) { + publicNicProfile = nicProfile; + break; + } + } + + if(publicNicProfile != null) { + NicTO[] nics = to.getNics(); + + // reserve extra NICs + NicTO[] expandedNics = new NicTO[nics.length + _hypervMgr.getRouterExtraPublicNics()]; + int i = 0; + int deviceId = -1; + for(i = 0; i < nics.length; i++) { + expandedNics[i] = nics[i]; + if(nics[i].getDeviceId() > deviceId) + deviceId = nics[i].getDeviceId(); + } + deviceId++; + + long networkId = publicNicProfile.getNetworkId(); + NetworkVO network = _networkDao.findById(networkId); + + for(; i < nics.length + _hypervMgr.getRouterExtraPublicNics(); i++) { + NicTO nicTo = new NicTO(); + nicTo.setDeviceId(deviceId++); + nicTo.setBroadcastType(publicNicProfile.getBroadcastType()); + nicTo.setType(publicNicProfile.getTrafficType()); + nicTo.setIp("0.0.0.0"); + nicTo.setNetmask("255.255.255.255"); + nicTo.setName(publicNicProfile.getName()); + + try { + String mac = _networkMgr.getNextAvailableMacAddressInNetwork(networkId); + nicTo.setMac(mac); + } catch (InsufficientAddressCapacityException e) { + throw new CloudRuntimeException("unable to allocate mac address on network: " + networkId); + } + nicTo.setDns1(publicNicProfile.getDns1()); + nicTo.setDns2(publicNicProfile.getDns2()); + if (publicNicProfile.getGateway() != null) { + nicTo.setGateway(publicNicProfile.getGateway()); + } else { + nicTo.setGateway(network.getGateway()); + } + nicTo.setDefaultNic(false); + nicTo.setBroadcastUri(publicNicProfile.getBroadCastUri()); + nicTo.setIsolationuri(publicNicProfile.getIsolationUri()); + + Integer networkRate = _networkMgr.getNetworkRate(network.getId(), null); + nicTo.setNetworkRateMbps(networkRate); + + expandedNics[i] = nicTo; + } + to.setNics(expandedNics); + } + + StringBuffer sbMacSequence = new StringBuffer(); + for(NicTO nicTo : sortNicsByDeviceId(to.getNics())) { + sbMacSequence.append(nicTo.getMac()).append("|"); + } + sbMacSequence.deleteCharAt(sbMacSequence.length() - 1); + String bootArgs = to.getBootArgs(); + to.setBootArgs(bootArgs + " nic_macs=" + sbMacSequence.toString()); + + } // Determine the VM's OS description GuestOSVO guestOS = _guestOsDao.findById(vm.getVirtualMachine().getGuestOSId()); @@ -59,6 +149,29 @@ public class HypervGuru extends HypervisorGuruBase implements HypervisorGuru { return to; } + private NicTO[] sortNicsByDeviceId(NicTO[] nics) { + + List listForSort = new ArrayList(); + for (NicTO nic : nics) { + listForSort.add(nic); + } + Collections.sort(listForSort, new Comparator() { + + @Override + public int compare(NicTO arg0, NicTO arg1) { + if (arg0.getDeviceId() < arg1.getDeviceId()) { + return -1; + } else if (arg0.getDeviceId() == arg1.getDeviceId()) { + return 0; + } + + return 1; + } + }); + + return listForSort.toArray(new NicTO[0]); + } + @Override public final boolean trackVmHostChange() { return false; diff --git a/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/manager/HypervManager.java b/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/manager/HypervManager.java new file mode 100644 index 00000000000..5821fe4dcae --- /dev/null +++ b/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/manager/HypervManager.java @@ -0,0 +1,25 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// +package com.cloud.hypervisor.hyperv.manager; + +import com.cloud.utils.component.Manager; + +public interface HypervManager extends Manager { + public String prepareSecondaryStorageStore(long zoneId); + int getRouterExtraPublicNics(); +} diff --git a/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/manager/HypervManagerImpl.java b/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/manager/HypervManagerImpl.java new file mode 100644 index 00000000000..71a619a0ad5 --- /dev/null +++ b/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/manager/HypervManagerImpl.java @@ -0,0 +1,384 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// +package com.cloud.hypervisor.hyperv.manager; + +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import java.util.Random; + +import javax.ejb.Local; +import javax.inject.Inject; +import javax.naming.ConfigurationException; + +import org.apache.log4j.Logger; + +import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; +import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; +import org.apache.cloudstack.framework.config.dao.ConfigurationDao; +import org.apache.cloudstack.utils.identity.ManagementServerNode; + +import com.cloud.configuration.Config; +import com.cloud.storage.JavaStorageLayer; +import com.cloud.storage.StorageLayer; +import com.cloud.utils.FileUtil; +import com.cloud.utils.NumbersUtil; +import com.cloud.utils.db.GlobalLock; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.utils.script.Script; +import com.cloud.vm.dao.NicDao; +import com.cloud.vm.dao.VMInstanceDao; + +@Local(value = {HypervManager.class}) +public class HypervManagerImpl implements HypervManager { + public static final Logger s_logger = Logger.getLogger(HypervManagerImpl.class); + + private String name; + private int runLevel; + private Map params; + + private int _timeout; + Random _rand = new Random(System.currentTimeMillis()); + + Map _storageMounts = new HashMap(); + StorageLayer _storage; + + @Inject ConfigurationDao _configDao; + @Inject DataStoreManager _dataStoreMgr; + @Inject VMInstanceDao _vminstanceDao; + @Inject NicDao _nicDao; + int _routerExtraPublicNics = 2; + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + if (params != null) { + String value = (String)params.get("scripts.timeout"); + _timeout = NumbersUtil.parseInt(value, 30) * 1000; + _storage = (StorageLayer)params.get(StorageLayer.InstanceConfigKey); + } + + if (_storage == null) { + _storage = new JavaStorageLayer(); + _storage.configure("StorageLayer", params); + } + _routerExtraPublicNics = NumbersUtil.parseInt(_configDao.getValue(Config.RouterExtraPublicNics.key()), 2); + return true; + } + + @Override + public boolean start() { + startupCleanup(getMountParent()); + return true; + } + + @Override + public boolean stop() { + shutdownCleanup(); + return true; + } + + @Override + public void setName(String name) { + this.name = name; + } + + @Override + public String getName() { + return name; + } + + @Override + public void setConfigParams(Map params) { + this.params = params; + } + + @Override + public Map getConfigParams() { + return params; + } + + @Override + public int getRunLevel() { + return runLevel; + } + + @Override + public void setRunLevel(int level) { + runLevel = level; + } + + public String prepareSecondaryStorageStore(long zoneId) { + String secondaryStorageUri = getSecondaryStorageStoreUrl(zoneId); + if (secondaryStorageUri == null) { + s_logger.debug("Secondary storage uri for dc " + zoneId + " couldn't be obtained"); + } else { + prepareSecondaryStorageStore(secondaryStorageUri); + } + + return secondaryStorageUri; + } + + private String getSecondaryStorageStoreUrl(long zoneId) { + String secUrl = null; + DataStore secStore = _dataStoreMgr.getImageStore(zoneId); + if (secStore != null) { + secUrl = secStore.getUri(); + } + + if (secUrl == null) { + s_logger.warn("Secondary storage uri couldn't be retrieved"); + } + + return secUrl; + } + + private void prepareSecondaryStorageStore(String storageUrl) { + String mountPoint = getMountPoint(storageUrl); + + GlobalLock lock = GlobalLock.getInternLock("prepare.systemvm"); + try { + if (lock.lock(3600)) { + try { + File patchFolder = new File(mountPoint + "/systemvm"); + if (!patchFolder.exists()) { + if (!patchFolder.mkdirs()) { + String msg = "Unable to create systemvm folder on secondary storage. location: " + patchFolder.toString(); + s_logger.error(msg); + throw new CloudRuntimeException(msg); + } + } + + File srcIso = getSystemVMPatchIsoFile(); + File destIso = new File(mountPoint + "/systemvm/" + getSystemVMIsoFileNameOnDatastore()); + if (!destIso.exists()) { + s_logger.info("Copy System VM patch ISO file to secondary storage. source ISO: " + + srcIso.getAbsolutePath() + ", destination: " + destIso.getAbsolutePath()); + try { + FileUtil.copyfile(srcIso, destIso); + } catch (IOException e) { + s_logger.error("Unexpected exception ", e); + + String msg = "Unable to copy systemvm ISO on secondary storage. src location: " + srcIso.toString() + ", dest location: " + destIso; + s_logger.error(msg); + throw new CloudRuntimeException(msg); + } + } else { + if (s_logger.isTraceEnabled()) { + s_logger.trace("SystemVM ISO file " + destIso.getPath() + " already exists"); + } + } + } finally { + lock.unlock(); + } + } + } finally { + lock.releaseRef(); + } + } + + private String getMountPoint(String storageUrl) { + String mountPoint = null; + synchronized (_storageMounts) { + mountPoint = _storageMounts.get(storageUrl); + if (mountPoint != null) { + return mountPoint; + } + + URI uri; + try { + uri = new URI(storageUrl); + } catch (URISyntaxException e) { + s_logger.error("Invalid storage URL format ", e); + throw new CloudRuntimeException("Unable to create mount point due to invalid storage URL format " + storageUrl); + } + + mountPoint = mount(File.separator + File.separator + uri.getHost() + uri.getPath(), getMountParent(), + uri.getScheme(), uri.getQuery()); + if (mountPoint == null) { + s_logger.error("Unable to create mount point for " + storageUrl); + return "/mnt/sec"; + } + + _storageMounts.put(storageUrl, mountPoint); + return mountPoint; + } + } + + protected String mount(String path, String parent, String scheme, String query) { + String mountPoint = setupMountPoint(parent); + if (mountPoint == null) { + s_logger.warn("Unable to create a mount point"); + return null; + } + + Script script = null; + String result = null; + if (scheme.equals("cifs")) { + String user = System.getProperty("user.name"); + Script command = new Script(true, "mount", _timeout, s_logger); + command.add("-t", "cifs"); + command.add(path); + command.add(mountPoint); + + if (user != null) { + command.add("-o", "uid=" + user + ",gid=" + user); + } + + if (query != null) { + query = query.replace('&', ','); + command.add("-o", query); + } + + result = command.execute(); + } + + if (result != null) { + s_logger.warn("Unable to mount " + path + " due to " + result); + File file = new File(mountPoint); + if (file.exists()) { + file.delete(); + } + return null; + } + + // Change permissions for the mountpoint + script = new Script(true, "chmod", _timeout, s_logger); + script.add("-R", "777", mountPoint); + result = script.execute(); + if (result != null) { + s_logger.warn("Unable to set permissions for " + mountPoint + " due to " + result); + } + return mountPoint; + } + + private String setupMountPoint(String parent) { + String mountPoint = null; + long mshostId = ManagementServerNode.getManagementServerId(); + for (int i = 0; i < 10; i++) { + String mntPt = parent + File.separator + String.valueOf(mshostId) + "." + Integer.toHexString(_rand.nextInt(Integer.MAX_VALUE)); + File file = new File(mntPt); + if (!file.exists()) { + if (_storage.mkdir(mntPt)) { + mountPoint = mntPt; + break; + } + } + s_logger.error("Unable to create mount: " + mntPt); + } + + return mountPoint; + } + + private String getSystemVMIsoFileNameOnDatastore() { + String version = this.getClass().getPackage().getImplementationVersion(); + String fileName = "systemvm-" + version + ".iso"; + return fileName.replace(':', '-'); + } + + private File getSystemVMPatchIsoFile() { + // locate systemvm.iso + URL url = this.getClass().getClassLoader().getResource("vms/systemvm.iso"); + File isoFile = null; + if (url != null) { + isoFile = new File(url.getPath()); + } + + if (isoFile == null || !isoFile.exists()) { + isoFile = new File("/usr/share/cloudstack-common/vms/systemvm.iso"); + } + + assert (isoFile != null); + if (!isoFile.exists()) { + s_logger.error("Unable to locate systemvm.iso in your setup at " + isoFile.toString()); + } + return isoFile; + } + + private String getMountParent() { + String mountParent = _configDao.getValue(Config.MountParent.key()); + if (mountParent == null) { + mountParent = File.separator + "mnt"; + } + + String instance = _configDao.getValue(Config.InstanceName.key()); + if (instance == null) { + instance = "DEFAULT"; + } + + if (instance != null) { + mountParent = mountParent + File.separator + instance; + } + + return mountParent; + } + + private void startupCleanup(String parent) { + s_logger.info("Cleanup mounted mount points used in previous session"); + + long mshostId = ManagementServerNode.getManagementServerId(); + + // cleanup left-over NFS mounts from previous session + String[] mounts = _storage.listFiles(parent + File.separator + String.valueOf(mshostId) + ".*"); + if (mounts != null && mounts.length > 0) { + for (String mountPoint : mounts) { + s_logger.info("umount NFS mount from previous session: " + mountPoint); + + String result = null; + Script command = new Script(true, "umount", _timeout, s_logger); + command.add(mountPoint); + result = command.execute(); + if (result != null) { + s_logger.warn("Unable to umount " + mountPoint + " due to " + result); + } + File file = new File(mountPoint); + if (file.exists()) { + file.delete(); + } + } + } + } + + private void shutdownCleanup() { + s_logger.info("Cleanup mounted mount points used in current session"); + + for (String mountPoint : _storageMounts.values()) { + s_logger.info("umount NFS mount: " + mountPoint); + + String result = null; + Script command = new Script(true, "umount", _timeout, s_logger); + command.add(mountPoint); + result = command.execute(); + if (result != null) { + s_logger.warn("Unable to umount " + mountPoint + " due to " + result); + } + File file = new File(mountPoint); + if (file.exists()) { + file.delete(); + } + } + } + + @Override + public int getRouterExtraPublicNics() { + return _routerExtraPublicNics; + } +} \ No newline at end of file diff --git a/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/resource/HypervDirectConnectResource.java b/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/resource/HypervDirectConnectResource.java index f61e5ff4401..2f645906317 100644 --- a/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/resource/HypervDirectConnectResource.java +++ b/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/resource/HypervDirectConnectResource.java @@ -19,25 +19,45 @@ package com.cloud.hypervisor.hyperv.resource; import java.io.File; import java.io.IOException; import java.net.ConnectException; +import java.net.InetSocketAddress; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.channels.SocketChannel; +import java.rmi.RemoteException; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.UUID; +import javax.annotation.PostConstruct; import javax.ejb.Local; +import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.lang.StringEscapeUtils; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.ssl.AllowAllHostnameVerifier; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.conn.BasicClientConnectionManager; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; @@ -51,12 +71,18 @@ import com.cloud.agent.api.CheckS2SVpnConnectionsCommand; import com.cloud.agent.api.Command; import com.cloud.agent.api.GetDomRVersionAnswer; import com.cloud.agent.api.GetDomRVersionCmd; +import com.cloud.agent.api.GetVmConfigAnswer; +import com.cloud.agent.api.GetVmConfigAnswer.NicDetails; +import com.cloud.agent.api.GetVmConfigCommand; import com.cloud.agent.api.HostVmStateReportEntry; +import com.cloud.agent.api.ModifyVmNicConfigAnswer; +import com.cloud.agent.api.ModifyVmNicConfigCommand; import com.cloud.agent.api.NetworkUsageAnswer; import com.cloud.agent.api.NetworkUsageCommand; import com.cloud.agent.api.PingCommand; import com.cloud.agent.api.PingRoutingCommand; import com.cloud.agent.api.PingTestCommand; +import com.cloud.agent.api.StartCommand; import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupRoutingCommand; import com.cloud.agent.api.StartupRoutingCommand.VmState; @@ -73,9 +99,11 @@ import com.cloud.agent.api.routing.IpAssocAnswer; import com.cloud.agent.api.routing.IpAssocCommand; import com.cloud.agent.api.routing.LoadBalancerConfigCommand; import com.cloud.agent.api.routing.NetworkElementCommand; +import com.cloud.agent.api.routing.RemoteAccessVpnCfgCommand; import com.cloud.agent.api.routing.SavePasswordCommand; import com.cloud.agent.api.routing.SetFirewallRulesAnswer; import com.cloud.agent.api.routing.SetFirewallRulesCommand; +import com.cloud.agent.api.routing.SetMonitorServiceCommand; import com.cloud.agent.api.routing.SetPortForwardingRulesAnswer; import com.cloud.agent.api.routing.SetPortForwardingRulesCommand; import com.cloud.agent.api.routing.SetSourceNatAnswer; @@ -86,16 +114,21 @@ import com.cloud.agent.api.routing.SetStaticRouteAnswer; import com.cloud.agent.api.routing.SetStaticRouteCommand; import com.cloud.agent.api.routing.Site2SiteVpnCfgCommand; import com.cloud.agent.api.routing.VmDataCommand; +import com.cloud.agent.api.routing.VpnUsersCfgCommand; import com.cloud.agent.api.to.DhcpTO; import com.cloud.agent.api.to.FirewallRuleTO; import com.cloud.agent.api.to.IpAddressTO; import com.cloud.agent.api.to.PortForwardingRuleTO; import com.cloud.agent.api.to.StaticNatRuleTO; +import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.dc.DataCenter.NetworkType; +import com.cloud.exception.InternalErrorException; import com.cloud.host.Host.Type; import com.cloud.hypervisor.Hypervisor; +import com.cloud.hypervisor.hyperv.manager.HypervManager; import com.cloud.network.HAProxyConfigurator; import com.cloud.network.LoadBalancerConfigurator; +import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.RouterPrivateIpStrategy; import com.cloud.network.rules.FirewallRule; import com.cloud.resource.ServerResource; @@ -105,8 +138,10 @@ import com.cloud.utils.Pair; import com.cloud.utils.StringUtils; import com.cloud.utils.net.NetUtils; import com.cloud.utils.ssh.SshHelper; +import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineName; + /** * Implementation of dummy resource to be returned from discoverer. **/ @@ -121,12 +156,12 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S private String _clusterId; private String _guid; private String _agentIp; - private int _port = DEFAULT_AGENT_PORT; - protected final long _ops_timeout = 900000; // 15 minutes time out to time + private final int _port = DEFAULT_AGENT_PORT; + protected final long _opsTimeout = 900000; // 15 minutes time out to time protected final int _retry = 24; protected final int _sleep = 10000; - protected final int DEFAULT_DOMR_SSHPORT = 3922; + protected static final int DEFAULT_DOMR_SSHPORT = 3922; private String _clusterGuid; @@ -137,6 +172,15 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S private String _username; private String _password; + private static HypervManager s_hypervMgr; + @Inject + HypervManager _hypervMgr; + + @PostConstruct + void init() { + s_hypervMgr = _hypervMgr; + } + @Override public final Type getType() { return Type.Routing; @@ -168,8 +212,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S s_logger.debug("Generated StartupRoutingCommand for _agentIp \"" + _agentIp + "\""); - // TODO: does version need to be hard coded. - defaultStartRoutCmd.setVersion("4.2.0"); + defaultStartRoutCmd.setVersion(this.getClass().getPackage().getImplementationVersion()); // Specifics of the host's resource capacity and network configuration // comes from the host itself. CloudStack sanity checks network @@ -283,7 +326,9 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S URI agentUri = null; try { String cmdName = StartupCommand.class.getName(); - agentUri = new URI("http", null, _agentIp, _port, "/api/HypervResource/" + cmdName, null, null); + agentUri = + new URI("https", null, _agentIp, _port, + "/api/HypervResource/" + cmdName, null, null); } catch (URISyntaxException e) { // TODO add proper logging String errMsg = "Could not generate URI for Hyper-V agent"; @@ -320,7 +365,9 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S Answer answer = null; try { String cmdName = cmd.getClass().getName(); - agentUri = new URI("http", null, _agentIp, _port, "/api/HypervResource/" + cmdName, null, null); + agentUri = + new URI("https", null, _agentIp, _port, + "/api/HypervResource/" + cmdName, null, null); } catch (URISyntaxException e) { // TODO add proper logging String errMsg = "Could not generate URI for Hyper-V agent"; @@ -365,11 +412,31 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S } else if (clazz == Site2SiteVpnCfgCommand.class) { answer = execute((Site2SiteVpnCfgCommand)cmd); } else if (clazz == CheckS2SVpnConnectionsCommand.class) { - answer = execute((CheckS2SVpnConnectionsCommand)cmd); + answer = execute((CheckS2SVpnConnectionsCommand) cmd); + } else if (clazz == RemoteAccessVpnCfgCommand.class) { + answer = execute((RemoteAccessVpnCfgCommand) cmd); + } else if (clazz == VpnUsersCfgCommand.class) { + answer = execute((VpnUsersCfgCommand) cmd); } else if (clazz == SetStaticRouteCommand.class) { - answer = execute((SetStaticRouteCommand)cmd); + answer = execute((SetStaticRouteCommand) cmd); + } else if (clazz == SetMonitorServiceCommand.class) { + answer = execute((SetMonitorServiceCommand) cmd); } else { - // Else send the cmd to hyperv agent. + if (clazz == StartCommand.class) { + VirtualMachineTO vmSpec = ((StartCommand)cmd).getVirtualMachine(); + if (vmSpec.getType() != VirtualMachine.Type.User) { + if (s_hypervMgr != null) { + String secondary = s_hypervMgr.prepareSecondaryStorageStore(Long.parseLong(_zoneId)); + if (secondary != null) { + ((StartCommand)cmd).setSecondaryStorage(secondary); + } + } else { + s_logger.error("Hyperv manager isn't available. Couldn't check and copy the systemvm iso."); + } + } + } + + // Send the cmd to hyperv agent. String ansStr = postHttpRequest(s_gson.toJson(cmd), agentUri); if (ansStr == null) { return Answer.createUnsupportedCommandAnswer(cmd); @@ -377,14 +444,95 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S // Only Answer instances are returned by remote agents. // E.g. see Response.getAnswers() Answer[] result = s_gson.fromJson(ansStr, Answer[].class); - s_logger.debug("executeRequest received response " + s_gson.toJson(result)); + String logResult = cleanPassword(StringEscapeUtils.unescapeJava(result.toString())); + s_logger.debug("executeRequest received response " + logResult); if (result.length > 0) { return result[0]; } } return answer; } + protected Answer execute(final RemoteAccessVpnCfgCommand cmd) { + String controlIp = getRouterSshControlIp(cmd); + StringBuffer argsBuf = new StringBuffer(); + if (cmd.isCreate()) { + argsBuf.append(" -r ").append(cmd.getIpRange()).append(" -p ").append(cmd.getPresharedKey()).append(" -s ").append(cmd.getVpnServerIp()).append(" -l ").append(cmd.getLocalIp()) + .append(" -c "); + } else { + argsBuf.append(" -d ").append(" -s ").append(cmd.getVpnServerIp()); + } + argsBuf.append(" -C ").append(cmd.getLocalCidr()); + argsBuf.append(" -i ").append(cmd.getPublicInterface()); + + try { + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Executing /opt/cloud/bin/vpn_lt2p.sh "); + } + + Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/opt/cloud/bin/vpn_l2tp.sh " + argsBuf.toString()); + + if (!result.first()) { + s_logger.error("RemoteAccessVpnCfg command on domR failed, message: " + result.second()); + + return new Answer(cmd, false, "RemoteAccessVpnCfg command failed due to " + result.second()); + } + + if (s_logger.isInfoEnabled()) { + s_logger.info("RemoteAccessVpnCfg command on domain router " + argsBuf.toString() + " completed"); + } + + } catch (Throwable e) { + if (e instanceof RemoteException) { + s_logger.warn(e.getMessage()); + } + + String msg = "RemoteAccessVpnCfg command failed due to " + e.getMessage(); + s_logger.error(msg, e); + return new Answer(cmd, false, msg); + } + + return new Answer(cmd); + } + + protected Answer execute(final VpnUsersCfgCommand cmd) { + + String controlIp = getRouterSshControlIp(cmd); + for (VpnUsersCfgCommand.UsernamePassword userpwd : cmd.getUserpwds()) { + StringBuffer argsBuf = new StringBuffer(); + if (!userpwd.isAdd()) { + argsBuf.append(" -U ").append(userpwd.getUsername()); + } else { + argsBuf.append(" -u ").append(userpwd.getUsernamePassword()); + } + + try { + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Executing /opt/cloud/bin/vpn_lt2p.sh "); + } + + Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/opt/cloud/bin/vpn_l2tp.sh " + argsBuf.toString()); + + if (!result.first()) { + s_logger.error("VpnUserCfg command on domR failed, message: " + result.second()); + + return new Answer(cmd, false, "VpnUserCfg command failed due to " + result.second()); + } + } catch (Throwable e) { + if (e instanceof RemoteException) { + s_logger.warn(e.getMessage()); + } + + String msg = "VpnUserCfg command failed due to " + e.getMessage(); + s_logger.error(msg, e); + return new Answer(cmd, false, msg); + } + } + + return new Answer(cmd); + } private SetStaticRouteAnswer execute(SetStaticRouteCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SetStaticRouteCommand: " + s_gson.toJson(cmd)); @@ -567,65 +715,6 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S } } - // - // find mac address of a specified ethx device - // ip address show ethx | grep link/ether | sed -e 's/^[ \t]*//' | cut -d' ' -f2 - // returns - // eth0:xx.xx.xx.xx - - // - // list IP with eth devices - // ifconfig ethx |grep -B1 "inet addr" | awk '{ if ( $1 == "inet" ) { print $2 } else if ( $2 == "Link" ) { printf "%s:" ,$1 } }' - // | awk -F: '{ print $1 ": " $3 }' - // - // returns - // eth0:xx.xx.xx.xx - // - // - - private int findRouterEthDeviceIndex(String domrName, String routerIp, String mac) throws Exception { - - s_logger.info("findRouterEthDeviceIndex. mac: " + mac); - - // TODO : this is a temporary very inefficient solution, will refactor it later - Pair result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "ls /proc/sys/net/ipv4/conf"); - - // when we dynamically plug in a new NIC into virtual router, it may take time to show up in guest OS - // we use a waiting loop here as a workaround to synchronize activities in systems - long startTick = System.currentTimeMillis(); - while (System.currentTimeMillis() - startTick < 15000) { - if (result.first()) { - String[] tokens = result.second().split("\\s+"); - for (String token : tokens) { - if (!("all".equalsIgnoreCase(token) || "default".equalsIgnoreCase(token) || "lo".equalsIgnoreCase(token))) { - String cmd = String.format("ip address show %s | grep link/ether | sed -e 's/^[ \t]*//' | cut -d' ' -f2", token); - - if (s_logger.isDebugEnabled()) - s_logger.debug("Run domr script " + cmd); - Pair result2 = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, - // TODO need to find the dev index inside router based on IP address - cmd); - if (s_logger.isDebugEnabled()) - s_logger.debug("result: " + result2.first() + ", output: " + result2.second()); - - if (result2.first() && result2.second().trim().equalsIgnoreCase(mac.trim())) - return Integer.parseInt(token.substring(3)); - } - } - } - - s_logger.warn("can not find intereface associated with mac: " + mac + ", guest OS may still at loading state, retry..."); - - try { - Thread.currentThread(); - Thread.sleep(1000); - } catch (InterruptedException e) { - } - } - - return -1; - } - protected Answer execute(SetPortForwardingRulesCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SetPortForwardingRulesCommand: " + s_gson.toJson(cmd)); @@ -930,14 +1019,16 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S String args = " -v " + vmIpAddress; if (s_logger.isDebugEnabled()) { - s_logger.debug("Run command on domain router " + controlIp + ", /opt/cloud/bin/savepassword.sh " + args + " -p " + StringUtils.getMaskedPasswordForDisplay(cmd.getPassword())); + s_logger.debug("Run command on domain router " + controlIp + ", /opt/cloud/bin/savepassword.sh " + args + " -p " + + StringUtils.getMaskedPasswordForDisplay(cmd.getPassword())); } args += " -p " + password; try { - Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/opt/cloud/bin/savepassword.sh " + args); + Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/opt/cloud/bin/savepassword.sh " + + args); if (!result.first()) { s_logger.error("savepassword command on domain router " + controlIp + " failed, message: " + result.second()); @@ -1029,74 +1120,35 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource VmDataCommand: " + s_gson.toJson(cmd)); } - - String routerPrivateIpAddress = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String controlIp = getRouterSshControlIp(cmd); + Map> data = new HashMap>(); + data.put(cmd.getVmIpAddress(), cmd.getVmData()); - String vmIpAddress = cmd.getVmIpAddress(); - List vmData = cmd.getVmData(); - String[] vmDataArgs = new String[vmData.size() * 2 + 4]; - vmDataArgs[0] = "routerIP"; - vmDataArgs[1] = routerPrivateIpAddress; - vmDataArgs[2] = "vmIP"; - vmDataArgs[3] = vmIpAddress; - int i = 4; - for (String[] vmDataEntry : vmData) { - String folder = vmDataEntry[0]; - String file = vmDataEntry[1]; - String contents = (vmDataEntry[2] != null) ? vmDataEntry[2] : "none"; + String json = new Gson().toJson(data); + s_logger.debug("VM data JSON IS:" + json); - vmDataArgs[i] = folder + "," + file; - vmDataArgs[i + 1] = contents; - i += 2; - } + json = Base64.encodeBase64String(json.getBytes()); - String content = encodeDataArgs(vmDataArgs); - String tmpFileName = UUID.randomUUID().toString(); - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Run vm_data command on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", data: " + content); - } + String args = "-d " + json; try { - SshHelper.scpTo(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/tmp", content.getBytes(), tmpFileName, null); - - try { - Pair result = - SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/root/userdata.py " + tmpFileName); - - if (!result.first()) { - s_logger.error("vm_data command on domain router " + controlIp + " failed. messge: " + result.second()); - return new Answer(cmd, false, "VmDataCommand failed due to " + result.second()); - } - } finally { - - SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "rm /tmp/" + tmpFileName); + Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/opt/cloud/bin/vmdata.py " + args); + if (!result.first()) { + s_logger.error("vm_data command on domain router " + controlIp + " failed. messge: " + result.second()); + return new Answer(cmd, false, "VmDataCommand failed due to " + result.second()); } if (s_logger.isInfoEnabled()) { s_logger.info("vm_data command on domain router " + controlIp + " completed"); } - } catch (Throwable e) { - String msg = "VmDataCommand failed due to " + e; + String msg = "VmDataCommand failed due to " + e.getMessage(); s_logger.error(msg, e); return new Answer(cmd, false, msg); } return new Answer(cmd); } - private String encodeDataArgs(String[] dataArgs) { - StringBuilder sb = new StringBuilder(); - - for (String arg : dataArgs) { - sb.append(arg); - sb.append("\n"); - } - - return sb.toString(); - } - protected Answer execute(DhcpEntryCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource DhcpEntryCommand: " + s_gson.toJson(cmd)); @@ -1245,6 +1297,102 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S return new Answer(cmd); } + // + // find mac address of a specified ethx device + // ip address show ethx | grep link/ether | sed -e 's/^[ \t]*//' | cut -d' ' -f2 + // returns + // eth0:xx.xx.xx.xx + + // + // list IP with eth devices + // ifconfig ethx |grep -B1 "inet addr" | awk '{ if ( $1 == "inet" ) { print $2 } else if ( $2 == "Link" ) { printf "%s:" ,$1 } }' + // | awk -F: '{ print $1 ": " $3 }' + // + // returns + // eth0:xx.xx.xx.xx + // + // + + private int findRouterEthDeviceIndex(String domrName, String routerIp, String mac) throws Exception { + + s_logger.info("findRouterEthDeviceIndex. mac: " + mac); + + // TODO : this is a temporary very inefficient solution, will refactor it later + Pair result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, + "ls /proc/sys/net/ipv4/conf"); + + // when we dynamically plug in a new NIC into virtual router, it may take time to show up in guest OS + // we use a waiting loop here as a workaround to synchronize activities in systems + long startTick = System.currentTimeMillis(); + while (System.currentTimeMillis() - startTick < 15000) { + if (result.first()) { + String[] tokens = result.second().split("\\s+"); + for (String token : tokens) { + if (!("all".equalsIgnoreCase(token) || "default".equalsIgnoreCase(token) || "lo".equalsIgnoreCase(token))) { + String cmd = String.format("ip address show %s | grep link/ether | sed -e 's/^[ \t]*//' | cut -d' ' -f2", token); + + if (s_logger.isDebugEnabled()) + s_logger.debug("Run domr script " + cmd); + Pair result2 = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, + // TODO need to find the dev index inside router based on IP address + cmd); + if (s_logger.isDebugEnabled()) + s_logger.debug("result: " + result2.first() + ", output: " + result2.second()); + + if (result2.first() && result2.second().trim().equalsIgnoreCase(mac.trim())) + return Integer.parseInt(token.substring(3)); + } + } + } + + s_logger.warn("can not find intereface associated with mac: " + mac + ", guest OS may still at loading state, retry..."); + + } + + return -1; + } + + private Pair findRouterFreeEthDeviceIndex(String routerIp) throws Exception { + + s_logger.info("findRouterFreeEthDeviceIndex. mac: "); + + // TODO : this is a temporary very inefficient solution, will refactor it later + Pair result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, + "ip address | grep DOWN| cut -f2 -d :"); + + // when we dynamically plug in a new NIC into virtual router, it may take time to show up in guest OS + // we use a waiting loop here as a workaround to synchronize activities in systems + long startTick = System.currentTimeMillis(); + while (System.currentTimeMillis() - startTick < 15000) { + if (result.first() && !result.second().isEmpty()) { + String[] tokens = result.second().split("\\n"); + for (String token : tokens) { + if (!("all".equalsIgnoreCase(token) || "default".equalsIgnoreCase(token) || "lo".equalsIgnoreCase(token))) { + //String cmd = String.format("ip address show %s | grep link/ether | sed -e 's/^[ \t]*//' | cut -d' ' -f2", token); + //TODO: don't check for eth0,1,2, as they will be empty by default. + //String cmd = String.format("ip address show %s ", token); + String cmd = String.format("ip address show %s | grep link/ether | sed -e 's/^[ \t]*//' | cut -d' ' -f2", token); + if (s_logger.isDebugEnabled()) + s_logger.debug("Run domr script " + cmd); + Pair result2 = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, + // TODO need to find the dev index inside router based on IP address + cmd); + if (s_logger.isDebugEnabled()) + s_logger.debug("result: " + result2.first() + ", output: " + result2.second()); + + if (result2.first() && result2.second().trim().length() > 0) + return new Pair(Integer.parseInt(token.trim().substring(3)), result2.second().trim()) ; + } + } + } + + //s_logger.warn("can not find intereface associated with mac: , guest OS may still at loading state, retry..."); + + } + + return new Pair(-1, ""); + } + protected Answer execute(IpAssocCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource IPAssocCommand: " + s_gson.toJson(cmd)); @@ -1260,7 +1408,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S String controlIp = getRouterSshControlIp(cmd); for (IpAddressTO ip : ips) { assignPublicIpAddress(routerName, controlIp, ip.getPublicIp(), ip.isAdd(), ip.isFirstIP(), ip.isSourceNat(), ip.getBroadcastUri(), ip.getVlanGateway(), - ip.getVlanNetmask(), ip.getVifMacAddress()); + ip.getVlanNetmask(), ip.getVifMacAddress()); results[i++] = ip.getPublicIp() + " - success"; } @@ -1278,16 +1426,97 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S return new IpAssocAnswer(cmd, results); } + protected int getVmNics(String vmName, int vlanid) { + GetVmConfigCommand vmConfig = new GetVmConfigCommand(vmName); + URI agentUri = null; + int nicposition = -1; + try { + String cmdName = GetVmConfigCommand.class.getName(); + agentUri = + new URI("https", null, _agentIp, _port, + "/api/HypervResource/" + cmdName, null, null); + } catch (URISyntaxException e) { + String errMsg = "Could not generate URI for Hyper-V agent"; + s_logger.error(errMsg, e); + } + String ansStr = postHttpRequest(s_gson.toJson(vmConfig), agentUri); + Answer[] result = s_gson.fromJson(ansStr, Answer[].class); + s_logger.debug("executeRequest received response " + + s_gson.toJson(result)); + if (result.length > 0) { + GetVmConfigAnswer ans = ((GetVmConfigAnswer)result[0]); + List nics = ans.getNics(); + for (NicDetails nic : nics) { + if (nic.getVlanid() == vlanid) { + nicposition = nics.indexOf(nic); + break; + } + } + } + return nicposition; + } + + protected void modifyNicVlan(String vmName, int vlanId, String macAddress) { + ModifyVmNicConfigCommand modifynic = new ModifyVmNicConfigCommand(vmName, vlanId, macAddress); + URI agentUri = null; + try { + String cmdName = ModifyVmNicConfigCommand.class.getName(); + agentUri = + new URI("https", null, _agentIp, _port, + "/api/HypervResource/" + cmdName, null, null); + } catch (URISyntaxException e) { + String errMsg = "Could not generate URI for Hyper-V agent"; + s_logger.error(errMsg, e); + } + String ansStr = postHttpRequest(s_gson.toJson(modifynic), agentUri); + Answer[] result = s_gson.fromJson(ansStr, Answer[].class); + s_logger.debug("executeRequest received response " + + s_gson.toJson(result)); + if (result.length > 0) { + ModifyVmNicConfigAnswer ans = ((ModifyVmNicConfigAnswer)result[0]); + } + } + protected void assignPublicIpAddress(final String vmName, final String privateIpAddress, final String publicIpAddress, final boolean add, final boolean firstIP, - final boolean sourceNat, final String vlanId, final String vlanGateway, final String vlanNetmask, final String vifMacAddress) throws Exception { + final boolean sourceNat, final String broadcastId, final String vlanGateway, final String vlanNetmask, final String vifMacAddress) throws Exception { + + URI broadcastUri = BroadcastDomainType.fromString(broadcastId); + if (BroadcastDomainType.getSchemeValue(broadcastUri) != BroadcastDomainType.Vlan) { + throw new InternalErrorException("Unable to assign a public IP to a VIF on network " + broadcastId); + } + int vlanId = Integer.parseInt(BroadcastDomainType.getValue(broadcastUri)); + + int publicNicInfo = -1; + publicNicInfo = getVmNics(vmName, vlanId); boolean addVif = false; - if (add) { + if (add && publicNicInfo == -1) { if (s_logger.isDebugEnabled()) { s_logger.debug("Plug new NIC to associate" + privateIpAddress + " to " + publicIpAddress); } addVif = true; } else if (!add && firstIP) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Unplug NIC " + publicNicInfo); + } + } + + if (addVif) { + Pair nicdevice = findRouterFreeEthDeviceIndex(privateIpAddress); + publicNicInfo = nicdevice.first(); + if (publicNicInfo > 0) { + modifyNicVlan(vmName, vlanId, nicdevice.second()); + // After modifying the vnic on VR, check the VR VNics config in the host and get the device position + publicNicInfo = getVmNics(vmName, vlanId); + // As a new nic got activated in the VR. add the entry in the NIC's table. + networkUsage(privateIpAddress, "addVif", "eth" + publicNicInfo); + } + else { + // we didn't find any eth device available in VR to configure the ip range with new VLAN + String msg = "No Nic is available on DomR VIF to associate/disassociate IP with."; + s_logger.error(msg); + throw new InternalErrorException(msg); + } } String args = null; @@ -1309,8 +1538,8 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S args += publicIpAddress + "/" + cidrSize; args += " -c "; - args += "eth" + "2"; // currently hardcoding to eth 2 (which is default public ipd)//publicNicInfo.first(); + args += "eth" + publicNicInfo; args += " -g "; args += vlanGateway; @@ -1323,7 +1552,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S } Pair result = - SshHelper.sshExecute(privateIpAddress, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/opt/cloud/bin/ipassoc.sh " + args); + SshHelper.sshExecute(privateIpAddress, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/opt/cloud/bin/ipassoc.sh " + args); if (!result.first()) { s_logger.error("ipassoc command on domain router " + privateIpAddress + " failed. message: " + result.second()); @@ -1420,6 +1649,35 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S return stats; } + protected Answer execute(SetMonitorServiceCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource SetMonitorServiceCommand: " + s_gson.toJson(cmd)); + } + + String controlIp = getRouterSshControlIp(cmd); + String config = cmd.getConfiguration(); + + String args = ""; + + args += " -c " + config; + + try { + Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/opt/cloud/bin/monitor_service.sh " + args); + + if (!result.first()) { + String msg= "monitor_service.sh failed on domain router " + controlIp + " failed " + result.second(); + s_logger.error(msg); + return new Answer(cmd, false, msg); + } + + return new Answer(cmd); + + } catch (Throwable e) { + s_logger.error("Unexpected exception: " + e.toString(), e); + return new Answer(cmd, false, "SetMonitorServiceCommand failed due to " + e); + } + } + protected CheckSshAnswer execute(CheckSshCommand cmd) { String vmName = cmd.getName(); String privateIp = cmd.getIp(); @@ -1512,10 +1770,37 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S // comment to use Apache HttpClient // http://stackoverflow.com/a/2793153/939250, but final comment is to // use Apache. - s_logger.debug("POST request to" + agentUri.toString() + " with contents" + jsonCmd); + String logMessage = StringEscapeUtils.unescapeJava(jsonCmd); + logMessage = cleanPassword(logMessage); + s_logger.debug("POST request to " + agentUri.toString() + + " with contents " + logMessage); // Create request - HttpClient httpClient = new DefaultHttpClient(); + HttpClient httpClient = null; + TrustStrategy easyStrategy = new TrustStrategy() { + @Override + public boolean isTrusted(X509Certificate[] chain, String authType) + throws CertificateException { + return true; + } + }; + + try { + SSLSocketFactory sf = new SSLSocketFactory(easyStrategy, new AllowAllHostnameVerifier()); + SchemeRegistry registry = new SchemeRegistry(); + registry.register(new Scheme("https", DEFAULT_AGENT_PORT, sf)); + ClientConnectionManager ccm = new BasicClientConnectionManager(registry); + httpClient = new DefaultHttpClient(ccm); + } catch (KeyManagementException e) { + s_logger.error("failed to initialize http client " + e.getMessage()); + } catch (UnrecoverableKeyException e) { + s_logger.error("failed to initialize http client " + e.getMessage()); + } catch (NoSuchAlgorithmException e) { + s_logger.error("failed to initialize http client " + e.getMessage()); + } catch (KeyStoreException e) { + s_logger.error("failed to initialize http client " + e.getMessage()); + } + String result = null; // TODO: are there timeout settings and worker thread settings to tweak? @@ -1528,7 +1813,8 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S StringEntity cmdJson = new StringEntity(jsonCmd); request.addHeader("content-type", "application/json"); request.setEntity(cmdJson); - s_logger.debug("Sending cmd to " + agentUri.toString() + " cmd data:" + jsonCmd); + s_logger.debug("Sending cmd to " + agentUri.toString() + + " cmd data:" + logMessage); HttpResponse response = httpClient.execute(request); // Unsupported commands will not route. @@ -1545,7 +1831,8 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S return null; } else { result = EntityUtils.toString(response.getEntity()); - s_logger.debug("POST response is" + result); + String logResult = cleanPassword(StringEscapeUtils.unescapeJava(result)); + s_logger.debug("POST response is " + logResult); } } catch (ClientProtocolException protocolEx) { // Problem with HTTP message exchange @@ -1576,19 +1863,22 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S @Override public final boolean configure(final String name, final Map params) throws ConfigurationException { /* todo: update, make consistent with the xen server equivalent. */ - _guid = (String)params.get("guid"); - _zoneId = (String)params.get("zone"); - _podId = (String)params.get("pod"); - _clusterId = (String)params.get("cluster"); - _agentIp = (String)params.get("ipaddress"); // was agentIp - _name = name; - _clusterGuid = (String)params.get("cluster.guid"); - _username = (String)params.get("url"); - _password = (String)params.get("password"); - _username = (String)params.get("username"); + if (params != null) { + _guid = (String)params.get("guid"); + _zoneId = (String)params.get("zone"); + _podId = (String)params.get("pod"); + _clusterId = (String)params.get("cluster"); + _agentIp = (String)params.get("ipaddress"); // was agentIp + _name = name; + + _clusterGuid = (String)params.get("cluster.guid"); + _username = (String)params.get("url"); + _password = (String)params.get("password"); + _username = (String)params.get("username"); + _configureCalled = true; + } - _configureCalled = true; return true; } @@ -1626,20 +1916,19 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S // at least have tried _retry times, this is to coordinate with system // VM patching/rebooting time that may need int retry = _retry; - while (System.currentTimeMillis() - startTick <= _ops_timeout || --retry > 0) { + while (System.currentTimeMillis() - startTick <= _opsTimeout || --retry > 0) { SocketChannel sch = null; try { s_logger.info("Trying to connect to " + ipAddress); sch = SocketChannel.open(); sch.configureBlocking(true); sch.socket().setSoTimeout(5000); - // we need to connect to the public ip address to check the status of the VM - /* + // we need to connect to the control ip address to check the status of the system vm InetSocketAddress addr = new InetSocketAddress(ipAddress, port); - sch.connect(addr);*/ + sch.connect(addr); return null; } catch (IOException e) { - s_logger.info("Could not connect to " + ipAddress + " due to " + e.toString()); + s_logger.info("Could] not connect to " + ipAddress + " due to " + e.toString()); if (e instanceof ConnectException) { // if connection is refused because of VM is being started, // we give it more sleep time @@ -1669,4 +1958,22 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S return "Unable to connect"; } + public static String cleanPassword(String logString) { + String cleanLogString = null; + if (logString != null) { + cleanLogString = logString; + String[] temp = logString.split(","); + int i = 0; + if (temp != null) { + while (i < temp.length) { + temp[i] = StringUtils.cleanString(temp[i]); + i++; + } + List stringList = new ArrayList(); + Collections.addAll(stringList, temp); + cleanLogString = StringUtils.join(stringList, ","); + } + } + return cleanLogString; + } } diff --git a/plugins/hypervisors/kvm/pom.xml b/plugins/hypervisors/kvm/pom.xml index 81cc372116e..5eba1e08f83 100644 --- a/plugins/hypervisors/kvm/pom.xml +++ b/plugins/hypervisors/kvm/pom.xml @@ -67,7 +67,6 @@ org.apache.maven.plugins maven-dependency-plugin - 2.5.1 copy-dependencies @@ -85,7 +84,6 @@ org.apache.maven.plugins maven-surefire-plugin - 2.14 **/Qemu*.java diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java index 48c789dac51..57b111e6e34 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java @@ -42,7 +42,7 @@ public class BridgeVifDriver extends VifDriverBase { private static final Logger s_logger = Logger.getLogger(BridgeVifDriver.class); private int _timeout; - private static final Object _vnetBridgeMonitor = new Object(); + private final Object _vnetBridgeMonitor = new Object(); private String _modifyVlanPath; private String _modifyVxlanPath; private String bridgeNameSchema; @@ -120,7 +120,8 @@ public class BridgeVifDriver extends VifDriverBase { intf.defBridgeNet(_bridges.get("linklocal"), null, nic.getMac(), getGuestNicModel(guestOsType)); } else if (nic.getType() == Networks.TrafficType.Public) { Integer networkRateKBps = (nic.getNetworkRateMbps() != null && nic.getNetworkRateMbps().intValue() != -1) ? nic.getNetworkRateMbps().intValue() * 128 : 0; - if (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan && !vNetId.equalsIgnoreCase("untagged")) { + if (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan && !vNetId.equalsIgnoreCase("untagged") || + nic.getBroadcastType() == Networks.BroadcastDomainType.Vxlan) { if (trafficLabel != null && !trafficLabel.isEmpty()) { s_logger.debug("creating a vNet dev and bridge for public traffic per traffic label " + trafficLabel); String brName = createVnetBr(vNetId, trafficLabel, protocol); diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/KVMHABase.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/KVMHABase.java index 6f6fbc3d4ca..fdaaeb31c45 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/KVMHABase.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/KVMHABase.java @@ -31,7 +31,7 @@ import com.cloud.utils.script.Script; public class KVMHABase { private static final Logger s_logger = Logger.getLogger(KVMHABase.class); private long _timeout = 60000; /* 1 minutes */ - protected static String _heartBeatPath; + protected static String s_heartBeatPath; protected long _heartBeatUpdateTimeout = 60000; protected long _heartBeatUpdateFreq = 60000; protected long _heartBeatUpdateMaxRetry = 3; diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/KVMHAChecker.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/KVMHAChecker.java index 02312ceeebd..c2af191cae6 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/KVMHAChecker.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/KVMHAChecker.java @@ -44,7 +44,7 @@ public class KVMHAChecker extends KVMHABase implements Callable { List results = new ArrayList(); for (NfsStoragePool pool : _pools) { - Script cmd = new Script(_heartBeatPath, _heartBeatCheckerTimeout, s_logger); + Script cmd = new Script(s_heartBeatPath, _heartBeatCheckerTimeout, s_logger); cmd.add("-i", pool._poolIp); cmd.add("-p", pool._poolMountSourcePath); cmd.add("-m", pool._mountDestPath); diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/KVMHAMonitor.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/KVMHAMonitor.java index 58ba808372c..4628fae55df 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/KVMHAMonitor.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/KVMHAMonitor.java @@ -42,7 +42,7 @@ public class KVMHAMonitor extends KVMHABase implements Runnable { this._storagePool.put(pool._poolUUID, pool); } this._hostIP = host; - KVMHABase._heartBeatPath = scriptPath; + KVMHABase.s_heartBeatPath = scriptPath; } public void addStoragePool(NfsStoragePool pool) { @@ -109,7 +109,7 @@ public class KVMHAMonitor extends KVMHABase implements Runnable { String result = null; for (int i = 0; i < 5; i++) { - Script cmd = new Script(_heartBeatPath, _heartBeatUpdateTimeout, s_logger); + Script cmd = new Script(s_heartBeatPath, _heartBeatUpdateTimeout, s_logger); cmd.add("-i", primaryStoragePool._poolIp); cmd.add("-p", primaryStoragePool._poolMountSourcePath); cmd.add("-m", primaryStoragePool._mountDestPath); @@ -124,7 +124,7 @@ public class KVMHAMonitor extends KVMHABase implements Runnable { if (result != null) { s_logger.warn("write heartbeat failed: " + result + "; reboot the host"); - Script cmd = new Script(_heartBeatPath, _heartBeatUpdateTimeout, s_logger); + Script cmd = new Script(s_heartBeatPath, _heartBeatUpdateTimeout, s_logger); cmd.add("-i", primaryStoragePool._poolIp); cmd.add("-p", primaryStoragePool._poolMountSourcePath); cmd.add("-m", primaryStoragePool._mountDestPath); diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtCapXMLParser.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtCapXMLParser.java index fe2fb5dcc1e..2f12d21eb24 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtCapXMLParser.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtCapXMLParser.java @@ -31,7 +31,7 @@ public class LibvirtCapXMLParser extends LibvirtXMLParser { private boolean _osType = false; private boolean _domainTypeKVM = false; private boolean _emulatorFlag = false; - private boolean _archTypex86_64 = false; + private boolean _archTypex8664 = false; private final StringBuffer _emulator = new StringBuffer(); private final StringBuffer _capXML = new StringBuffer(); private static final Logger s_logger = Logger.getLogger(LibvirtCapXMLParser.class); @@ -50,7 +50,7 @@ public class LibvirtCapXMLParser extends LibvirtXMLParser { } else if (qName.equalsIgnoreCase("emulator")) { _emulatorFlag = false; } else if (qName.equalsIgnoreCase("arch")) { - _archTypex86_64 = false; + _archTypex8664 = false; } else if (_host) { _capXML.append("<").append("/").append(qName).append(">"); } @@ -81,7 +81,7 @@ public class LibvirtCapXMLParser extends LibvirtXMLParser { } else if (qName.equalsIgnoreCase("arch")) { for (int i = 0; i < attributes.getLength(); i++) { if (attributes.getQName(i).equalsIgnoreCase("name") && attributes.getValue(i).equalsIgnoreCase("x86_64")) { - _archTypex86_64 = true; + _archTypex8664 = true; } } } else if (qName.equalsIgnoreCase("domain")) { @@ -90,7 +90,7 @@ public class LibvirtCapXMLParser extends LibvirtXMLParser { _domainTypeKVM = true; } } - } else if (qName.equalsIgnoreCase("emulator") && _domainTypeKVM && _archTypex86_64) { + } else if (qName.equalsIgnoreCase("emulator") && _domainTypeKVM && _archTypex8664) { _emulatorFlag = true; _emulator.delete(0, _emulator.length()); } else if (_host) { diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java index 3596f8d3c71..fd0078c6970 100755 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java @@ -16,73 +16,12 @@ // under the License. package com.cloud.hypervisor.kvm.resource; -import java.io.BufferedOutputStream; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.InetAddress; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.URLConnection; -import java.text.DateFormat; -import java.text.MessageFormat; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.ejb.Local; -import javax.naming.ConfigurationException; - -import org.apache.commons.io.FileUtils; -import org.apache.log4j.Logger; -import org.libvirt.Connect; -import org.libvirt.Domain; -import org.libvirt.DomainBlockStats; -import org.libvirt.DomainInfo; -import org.libvirt.DomainInterfaceStats; -import org.libvirt.DomainSnapshot; -import org.libvirt.LibvirtException; -import org.libvirt.NodeInfo; - import com.ceph.rados.IoCTX; import com.ceph.rados.Rados; import com.ceph.rados.RadosException; import com.ceph.rbd.Rbd; import com.ceph.rbd.RbdException; import com.ceph.rbd.RbdImage; - -import org.apache.cloudstack.storage.command.StorageSubSystemCommand; -import org.apache.cloudstack.storage.to.PrimaryDataStoreTO; -import org.apache.cloudstack.storage.to.VolumeObjectTO; -import org.apache.cloudstack.utils.qemu.QemuImg; -import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat; -import org.apache.cloudstack.utils.qemu.QemuImgException; -import org.apache.cloudstack.utils.qemu.QemuImgFile; - import com.cloud.agent.api.Answer; import com.cloud.agent.api.AttachIsoCommand; import com.cloud.agent.api.AttachVolumeAnswer; @@ -155,7 +94,6 @@ import com.cloud.agent.api.RebootCommand; import com.cloud.agent.api.RebootRouterCommand; import com.cloud.agent.api.SecurityGroupRuleAnswer; import com.cloud.agent.api.SecurityGroupRulesCmd; -import com.cloud.agent.api.SetupGuestNetworkAnswer; import com.cloud.agent.api.SetupGuestNetworkCommand; import com.cloud.agent.api.StartAnswer; import com.cloud.agent.api.StartCommand; @@ -174,14 +112,9 @@ import com.cloud.agent.api.check.CheckSshCommand; import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand; import com.cloud.agent.api.proxy.ConsoleProxyLoadAnswer; import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand; -import com.cloud.agent.api.routing.IpAssocAnswer; import com.cloud.agent.api.routing.IpAssocCommand; import com.cloud.agent.api.routing.IpAssocVpcCommand; import com.cloud.agent.api.routing.NetworkElementCommand; -import com.cloud.agent.api.routing.SetMonitorServiceCommand; -import com.cloud.agent.api.routing.SetNetworkACLAnswer; -import com.cloud.agent.api.routing.SetNetworkACLCommand; -import com.cloud.agent.api.routing.SetSourceNatAnswer; import com.cloud.agent.api.routing.SetSourceNatCommand; import com.cloud.agent.api.storage.CopyVolumeAnswer; import com.cloud.agent.api.storage.CopyVolumeCommand; @@ -202,6 +135,7 @@ import com.cloud.agent.api.to.NicTO; import com.cloud.agent.api.to.StorageFilerTO; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.agent.api.to.VolumeTO; +import com.cloud.agent.resource.virtualnetwork.VirtualRouterDeployer; import com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource; import com.cloud.dc.Vlan; import com.cloud.exception.InternalErrorException; @@ -251,17 +185,77 @@ import com.cloud.storage.template.Processor.FormatInfo; import com.cloud.storage.template.QCOW2Processor; import com.cloud.storage.template.TemplateLocation; import com.cloud.storage.template.TemplateProp; +import com.cloud.utils.ExecutionResult; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.PropertiesUtil; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.NetUtils; import com.cloud.utils.script.OutputInterpreter; +import com.cloud.utils.script.OutputInterpreter.AllLinesParser; import com.cloud.utils.script.Script; +import com.cloud.utils.ssh.SshHelper; import com.cloud.vm.DiskProfile; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine.PowerState; import com.cloud.vm.VirtualMachine.State; +import org.apache.cloudstack.storage.command.StorageSubSystemCommand; +import org.apache.cloudstack.storage.to.PrimaryDataStoreTO; +import org.apache.cloudstack.storage.to.VolumeObjectTO; +import org.apache.cloudstack.utils.qemu.QemuImg; +import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat; +import org.apache.cloudstack.utils.qemu.QemuImgException; +import org.apache.cloudstack.utils.qemu.QemuImgFile; +import org.apache.commons.io.FileUtils; +import org.apache.log4j.Logger; +import org.libvirt.Connect; +import org.libvirt.Domain; +import org.libvirt.DomainBlockStats; +import org.libvirt.DomainInfo; +import org.libvirt.DomainInterfaceStats; +import org.libvirt.DomainSnapshot; +import org.libvirt.LibvirtException; +import org.libvirt.NodeInfo; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.InetAddress; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLConnection; +import java.text.DateFormat; +import java.text.MessageFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * LibvirtComputingResource execute requests on the computing/routing host using @@ -286,7 +280,7 @@ import com.cloud.vm.VirtualMachine.State; * pool | the parent of the storage pool hierarchy * } **/ @Local(value = {ServerResource.class}) -public class LibvirtComputingResource extends ServerResourceBase implements ServerResource { +public class LibvirtComputingResource extends ServerResourceBase implements ServerResource, VirtualRouterDeployer { private static final Logger s_logger = Logger.getLogger(LibvirtComputingResource.class); private String _modifyVlanPath; @@ -301,7 +295,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv private String _ovsPvlanDhcpHostPath; private String _ovsPvlanVmPath; private String _routerProxyPath; - private String _ovsTunnelPath; + private String _ovsTunnelPath; private String _host; private String _dcId; private String _pod; @@ -311,9 +305,9 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv private long _hvVersion; private long _kernelVersion; private KVMHAMonitor _monitor; - private final String _SSHKEYSPATH = "/root/.ssh"; - private final String _SSHPRVKEYPATH = _SSHKEYSPATH + File.separator + "id_rsa.cloud"; - private final String _SSHPUBKEYPATH = _SSHKEYSPATH + File.separator + "id_rsa.pub.cloud"; + private static final String SSHKEYSPATH = "/root/.ssh"; + private static final String SSHPRVKEYPATH = SSHKEYSPATH + File.separator + "id_rsa.cloud"; + private static final String SSHPUBKEYPATH = SSHKEYSPATH + File.separator + "id_rsa.pub.cloud"; private String _mountPoint = "/mnt"; StorageLayer _storage; private KVMStoragePoolManager _storagePoolMgr; @@ -323,6 +317,59 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv protected static final String DEFAULT_OVS_VIF_DRIVER_CLASS_NAME = "com.cloud.hypervisor.kvm.resource.OvsVifDriver"; protected static final String DEFAULT_BRIDGE_VIF_DRIVER_CLASS_NAME = "com.cloud.hypervisor.kvm.resource.BridgeVifDriver"; + @Override + public ExecutionResult executeInVR(String routerIp, String script, String args) { + final Script command = new Script(_routerProxyPath, _timeout, s_logger); + final AllLinesParser parser = new AllLinesParser(); + command.add(script); + command.add(routerIp); + if (args != null) { + command.add(args); + } + String details = command.execute(parser); + if (details == null) { + details = parser.getLines(); + } + return new ExecutionResult(command.getExitValue() == 0, details); + } + + @Override + public ExecutionResult createFileInVR(String routerIp, String path, String filename, String content) { + File permKey = new File("/root/.ssh/id_rsa.cloud"); + String error = null; + + try { + SshHelper.scpTo(routerIp, 3922, "root", permKey, null, path, content.getBytes(), filename, null); + } catch (Exception e) { + s_logger.warn("Fail to create file " + path + filename + " in VR " + routerIp, e); + error = e.getMessage(); + } + return new ExecutionResult(error == null, error); + } + + @Override + public ExecutionResult prepareCommand(NetworkElementCommand cmd) { + //Update IP used to access router + cmd.setRouterAccessIp(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP)); + assert cmd.getRouterAccessIp() != null; + + if (cmd instanceof IpAssocVpcCommand) { + return prepareNetworkElementCommand((IpAssocVpcCommand)cmd); + } else if (cmd instanceof IpAssocCommand) { + return prepareNetworkElementCommand((IpAssocCommand)cmd); + } else if (cmd instanceof SetupGuestNetworkCommand) { + return prepareNetworkElementCommand((SetupGuestNetworkCommand)cmd); + } else if (cmd instanceof SetSourceNatCommand) { + return prepareNetworkElementCommand((SetSourceNatCommand)cmd); + } + return new ExecutionResult(true, null); + } + + @Override + public ExecutionResult cleanupCommand(NetworkElementCommand cmd) { + return new ExecutionResult(true, null); + } + private static final class KeyValueInterpreter extends OutputInterpreter { private final Map map = new HashMap(); @@ -355,8 +402,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv return null; } - protected static MessageFormat SnapshotXML = new MessageFormat(" " + " {0}" + " " - + " {1}" + " " + " "); + protected static final MessageFormat SnapshotXML = new MessageFormat(" " + " {0}" + " " + + " {1}" + " " + " "); protected HypervisorType _hypervisorType; protected String _hypervisorURI; @@ -374,13 +421,14 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv protected String _privateIp; protected String _pool; protected String _localGateway; - private boolean _can_bridge_firewall; + private boolean _canBridgeFirewall; protected String _localStoragePath; protected String _localStorageUUID; + protected boolean _noMemBalloon = false; protected String _guestCpuMode; protected String _guestCpuModel; private final Map _pifs = new HashMap(); - private final Map _vmStats = new ConcurrentHashMap(); + private final Map _vmStats = new ConcurrentHashMap(); protected boolean _disconnected = true; protected int _timeout; @@ -538,7 +586,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv params.put("domr.scripts.dir", domrScriptsDir); - _virtRouterResource = new VirtualRoutingResource(); + _virtRouterResource = new VirtualRoutingResource(this); success = _virtRouterResource.configure(name, params); if (!success) { @@ -607,10 +655,10 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv throw new ConfigurationException("Unable to find the security_group.py"); } - _ovsTunnelPath = Script.findScript(networkScriptsDir, "ovstunnel.py"); - if (_ovsTunnelPath == null) { - throw new ConfigurationException("Unable to find the ovstunnel.py"); - } + _ovsTunnelPath = Script.findScript(networkScriptsDir, "ovstunnel.py"); + if (_ovsTunnelPath == null) { + throw new ConfigurationException("Unable to find the ovstunnel.py"); + } _routerProxyPath = Script.findScript("scripts/network/domr/", "router_proxy.sh"); if (_routerProxyPath == null) { @@ -724,6 +772,11 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv value = (String)params.get("cmds.timeout"); _cmdsTimeout = NumbersUtil.parseInt(value, 7200) * 1000; + value = (String) params.get("vm.memballoon.disable"); + if (Boolean.parseBoolean(value)) { + _noMemBalloon = true; + } + value = (String)params.get("host.reserved.mem.mb"); _dom0MinMem = NumbersUtil.parseInt(value, 0) * 1024 * 1024; @@ -745,7 +798,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv /* Does node support HVM guest? If not, exit */ if (!IsHVMEnabled(conn)) { throw new ConfigurationException("NO HVM support on this machine, please make sure: " + "1. VT/SVM is supported by your CPU, or is enabled in BIOS. " - + "2. kvm modules are loaded (kvm, kvm_amd|kvm_intel)"); + + "2. kvm modules are loaded (kvm, kvm_amd|kvm_intel)"); } } @@ -765,7 +818,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv if (_hypervisorLibvirtVersion < (9 * 1000 + 10)) { s_logger.warn("LibVirt version 0.9.10 required for guest cpu mode, but version " + prettyVersion(_hypervisorLibvirtVersion) + - " detected, so it will be disabled"); + " detected, so it will be disabled"); _guestCpuMode = ""; _guestCpuModel = ""; } @@ -796,13 +849,13 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } switch (_bridgeType) { - case OPENVSWITCH: - getOvsPifs(); - break; - case NATIVE: - default: - getPifs(); - break; + case OPENVSWITCH: + getOvsPifs(); + break; + case NATIVE: + default: + getPifs(); + break; } if (_pifs.get("private") == null) { @@ -816,7 +869,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } s_logger.debug("Found pif: " + _pifs.get("private") + " on " + _privBridgeName + ", pif: " + _pifs.get("public") + " on " + _publicBridgeName); - _can_bridge_firewall = can_bridge_firewall(_pifs.get("public")); + _canBridgeFirewall = can_bridge_firewall(_pifs.get("public")); _localGateway = Script.runSimpleBashScript("ip route |grep default|awk '{print $3}'"); if (_localGateway == null) { @@ -989,6 +1042,17 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } } + // public creates bridges on a pif, if private bridge not found try pif direct + // This addresses the unnecessary requirement of someone to create an unused bridge just for traffic label + if (_pifs.get("public") == null) { + s_logger.debug("public traffic label '" + _publicBridgeName+ "' not found as bridge, looking for physical interface"); + File dev = new File("/sys/class/net/" + _publicBridgeName); + if (dev.exists()) { + s_logger.debug("public traffic label '" + _publicBridgeName + "' found as a physical device"); + _pifs.put("public", _publicBridgeName); + } + } + s_logger.debug("done looking for pifs, no more bridges"); } @@ -1042,8 +1106,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv for (int i = 0; i < interfaces.length; i++) { String fname = interfaces[i].getName(); s_logger.debug("matchPifFileInDirectory: file name '" + fname + "'"); - if (fname.startsWith("eth") || fname.startsWith("bond") || fname.startsWith("vlan") || fname.startsWith("vxlan") || fname.startsWith("em") || - fname.matches("^p\\d+p\\d+.*")) { + if (fname.startsWith("eth") || fname.startsWith("bond") || fname.startsWith("vlan") || fname.startsWith("vx") || fname.startsWith("em") || + fname.matches("^p\\d+p\\d+.*")) { return fname; } } @@ -1088,7 +1152,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv command.add("-c"); command.add("ovs-vsctl br-exists " + networkName); String result = command.execute(null); - if ("Ok".equals(result)) { + if ("0".equals(result)) { return true; } else { return false; @@ -1130,7 +1194,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv This also makes sure we never have any old "garbage" defined in libvirt which might haunt us. - */ + */ // check for existing inactive vm definition and remove it // this can sometimes happen during crashes, etc @@ -1248,16 +1312,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv return execute((PlugNicCommand)cmd); } else if (cmd instanceof UnPlugNicCommand) { return execute((UnPlugNicCommand)cmd); - } else if (cmd instanceof SetupGuestNetworkCommand) { - return execute((SetupGuestNetworkCommand)cmd); - } else if (cmd instanceof SetNetworkACLCommand) { - return execute((SetNetworkACLCommand)cmd); - } else if (cmd instanceof SetSourceNatCommand) { - return execute((SetSourceNatCommand)cmd); - } else if (cmd instanceof IpAssocVpcCommand) { - return execute((IpAssocVpcCommand)cmd); - } else if (cmd instanceof IpAssocCommand) { - return execute((IpAssocCommand)cmd); } else if (cmd instanceof NetworkElementCommand) { return _virtRouterResource.executeRequest(cmd); } else if (cmd instanceof CheckSshCommand) { @@ -1280,21 +1334,19 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv return storageHandler.handleStorageCommands((StorageSubSystemCommand)cmd); } else if (cmd instanceof PvlanSetupCommand) { return execute((PvlanSetupCommand)cmd); - } else if (cmd instanceof SetMonitorServiceCommand) { - return execute((SetMonitorServiceCommand)cmd); } else if (cmd instanceof CheckOnHostCommand) { return execute((CheckOnHostCommand)cmd); - } else if (cmd instanceof OvsFetchInterfaceCommand) { - return execute((OvsFetchInterfaceCommand) cmd); - } else if (cmd instanceof OvsSetupBridgeCommand) { - return execute((OvsSetupBridgeCommand) cmd); - } else if (cmd instanceof OvsDestroyBridgeCommand) { - return execute((OvsDestroyBridgeCommand) cmd); - } else if (cmd instanceof OvsCreateTunnelCommand) { - return execute((OvsCreateTunnelCommand) cmd); - } else if (cmd instanceof OvsDestroyTunnelCommand) { - return execute((OvsDestroyTunnelCommand) cmd); - } else { + } else if (cmd instanceof OvsFetchInterfaceCommand) { + return execute((OvsFetchInterfaceCommand)cmd); + } else if (cmd instanceof OvsSetupBridgeCommand) { + return execute((OvsSetupBridgeCommand)cmd); + } else if (cmd instanceof OvsDestroyBridgeCommand) { + return execute((OvsDestroyBridgeCommand)cmd); + } else if (cmd instanceof OvsCreateTunnelCommand) { + return execute((OvsCreateTunnelCommand)cmd); + } else if (cmd instanceof OvsDestroyTunnelCommand) { + return execute((OvsDestroyTunnelCommand)cmd); + } else { s_logger.warn("Unsupported command "); return Answer.createUnsupportedCommandAnswer(cmd); } @@ -1304,173 +1356,173 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } private OvsFetchInterfaceAnswer execute(OvsFetchInterfaceCommand cmd) { - String label = cmd.getLabel(); - s_logger.debug("Will look for network with name-label:" + label); - try { - String ipadd = Script.runSimpleBashScript("ifconfig " + label + " | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'"); - String mask = Script.runSimpleBashScript("ifconfig " + label + " | grep 'inet addr:' | cut -d: -f4"); - String mac = Script.runSimpleBashScript("ifconfig " + label + " | grep HWaddr | awk -F \" \" '{print $5}'"); - return new OvsFetchInterfaceAnswer(cmd, true, "Interface " + label - + " retrieved successfully", ipadd, mask, mac); + String label = cmd.getLabel(); + s_logger.debug("Will look for network with name-label:" + label); + try { + String ipadd = Script.runSimpleBashScript("ifconfig " + label + " | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'"); + String mask = Script.runSimpleBashScript("ifconfig " + label + " | grep 'inet addr:' | cut -d: -f4"); + String mac = Script.runSimpleBashScript("ifconfig " + label + " | grep HWaddr | awk -F \" \" '{print $5}'"); + return new OvsFetchInterfaceAnswer(cmd, true, "Interface " + label + + " retrieved successfully", ipadd, mask, mac); - } catch (Exception e) { - s_logger.warn("Caught execption when fetching interface", e); - return new OvsFetchInterfaceAnswer(cmd, false, "EXCEPTION:" - + e.getMessage()); - } + } catch (Exception e) { + s_logger.warn("Caught execption when fetching interface", e); + return new OvsFetchInterfaceAnswer(cmd, false, "EXCEPTION:" + + e.getMessage()); + } } - private Answer execute(OvsSetupBridgeCommand cmd) { - findOrCreateTunnelNetwork(cmd.getKey()); - configureTunnelNetwork(cmd.getNetworkId(), cmd.getHostId(), - cmd.getKey()); - s_logger.debug("OVS Bridge configured"); - return new Answer(cmd, true, null); - } + private Answer execute(OvsSetupBridgeCommand cmd) { + findOrCreateTunnelNetwork(cmd.getKey()); + configureTunnelNetwork(cmd.getNetworkId(), cmd.getHostId(), + cmd.getKey()); + s_logger.debug("OVS Bridge configured"); + return new Answer(cmd, true, null); + } - private Answer execute(OvsDestroyBridgeCommand cmd) { - destroyTunnelNetwork(cmd.getKey()); - s_logger.debug("OVS Bridge destroyed"); - return new Answer(cmd, true, null); - } + private Answer execute(OvsDestroyBridgeCommand cmd) { + destroyTunnelNetwork(cmd.getKey()); + s_logger.debug("OVS Bridge destroyed"); + return new Answer(cmd, true, null); + } - private synchronized void destroyTunnelNetwork(int key) { - try { - findOrCreateTunnelNetwork(key); - String bridge = "OVSTunnel" + key; - Script cmd = new Script(_ovsTunnelPath, _timeout, s_logger); - cmd.add("destroy_ovs_bridge"); - cmd.add("--bridge", bridge); - String result = cmd.execute(); - if (result != null) { - // TODO: Should make this error not fatal? - // Can Concurrent VM shutdown/migration/reboot events can cause - // this method - // to be executed on a bridge which has already been removed? - throw new CloudRuntimeException("Unable to remove OVS bridge " + bridge); - } - return; - } catch (Exception e) { - s_logger.warn("destroyTunnelNetwork failed:", e); - return; - } - } + private synchronized void destroyTunnelNetwork(int key) { + try { + findOrCreateTunnelNetwork(key); + String bridge = "OVSTunnel" + key; + Script cmd = new Script(_ovsTunnelPath, _timeout, s_logger); + cmd.add("destroy_ovs_bridge"); + cmd.add("--bridge", bridge); + String result = cmd.execute(); + if (result != null) { + // TODO: Should make this error not fatal? + // Can Concurrent VM shutdown/migration/reboot events can cause + // this method + // to be executed on a bridge which has already been removed? + throw new CloudRuntimeException("Unable to remove OVS bridge " + bridge); + } + return; + } catch (Exception e) { + s_logger.warn("destroyTunnelNetwork failed:", e); + return; + } + } - private synchronized boolean findOrCreateTunnelNetwork(long key) { - try { - String nwName = "OVSTunnel" + key; - if (checkNetwork(nwName)) { - return true; - } - // if not found, create a new one - Map otherConfig = new HashMap(); - otherConfig.put("ovs-host-setup", ""); - Script.runSimpleBashScript("ovs-vsctl -- --may-exist add-br " - + nwName + " -- set bridge " + nwName - + " other_config:ovs_host_setup='-1'"); - s_logger.debug("### KVM network for tunnels created:" + nwName); - } catch (Exception e) { - s_logger.warn("createTunnelNetwork failed", e); - } - return true; - } + private synchronized boolean findOrCreateTunnelNetwork(long key) { + try { + String nwName = "OVSTunnel" + key; + if (checkNetwork(nwName)) { + return true; + } + // if not found, create a new one + Map otherConfig = new HashMap(); + otherConfig.put("ovs-host-setup", ""); + Script.runSimpleBashScript("ovs-vsctl -- --may-exist add-br " + + nwName + " -- set bridge " + nwName + + " other_config:ovs_host_setup='-1'"); + s_logger.debug("### KVM network for tunnels created:" + nwName); + } catch (Exception e) { + s_logger.warn("createTunnelNetwork failed", e); + } + return true; + } - private synchronized boolean configureTunnelNetwork(long networkId, - long hostId, int key) { - try { - findOrCreateTunnelNetwork(key); - String nwName = "OVSTunnel" + key; - String configuredHosts = Script - .runSimpleBashScript("ovs-vsctl get bridge " + nwName - + " other_config:ovs_host_setup"); - boolean configured = false; - if (configuredHosts != null) { - String hostIdsStr[] = configuredHosts.split(","); - for (String hostIdStr : hostIdsStr) { - if (hostIdStr.equals(((Long) hostId).toString())) { - configured = true; - break; - } - } - } - if (!configured) { - Script cmd = new Script(_ovsTunnelPath, _timeout, s_logger); - cmd.add("setup_ovs_bridge"); - cmd.add("--key", String.valueOf(key)); - cmd.add("--cs_host_id", ((Long) hostId).toString()); - cmd.add("--bridge", nwName); - String result = cmd.execute(); - if (result != null) { - throw new CloudRuntimeException( - "Unable to pre-configure OVS bridge " + nwName - + " for network ID:" + networkId); - } - } - } catch (Exception e) { - s_logger.warn("createandConfigureTunnelNetwork failed", e); - return false; - } - return true; - } + private synchronized boolean configureTunnelNetwork(long networkId, + long hostId, int key) { + try { + findOrCreateTunnelNetwork(key); + String nwName = "OVSTunnel" + key; + String configuredHosts = Script + .runSimpleBashScript("ovs-vsctl get bridge " + nwName + + " other_config:ovs_host_setup"); + boolean configured = false; + if (configuredHosts != null) { + String hostIdsStr[] = configuredHosts.split(","); + for (String hostIdStr : hostIdsStr) { + if (hostIdStr.equals(((Long)hostId).toString())) { + configured = true; + break; + } + } + } + if (!configured) { + Script cmd = new Script(_ovsTunnelPath, _timeout, s_logger); + cmd.add("setup_ovs_bridge"); + cmd.add("--key", String.valueOf(key)); + cmd.add("--cs_host_id", ((Long)hostId).toString()); + cmd.add("--bridge", nwName); + String result = cmd.execute(); + if (result != null) { + throw new CloudRuntimeException( + "Unable to pre-configure OVS bridge " + nwName + + " for network ID:" + networkId); + } + } + } catch (Exception e) { + s_logger.warn("createandConfigureTunnelNetwork failed", e); + return false; + } + return true; + } - private OvsCreateTunnelAnswer execute(OvsCreateTunnelCommand cmd) { - String bridge = "OVSTunnel" + cmd.getKey(); - try { - if (!findOrCreateTunnelNetwork(cmd.getKey())) { - s_logger.debug("Error during bridge setup"); - return new OvsCreateTunnelAnswer(cmd, false, - "Cannot create network", bridge); - } + private OvsCreateTunnelAnswer execute(OvsCreateTunnelCommand cmd) { + String bridge = "OVSTunnel" + cmd.getKey(); + try { + if (!findOrCreateTunnelNetwork(cmd.getKey())) { + s_logger.debug("Error during bridge setup"); + return new OvsCreateTunnelAnswer(cmd, false, + "Cannot create network", bridge); + } - configureTunnelNetwork(cmd.getNetworkId(), cmd.getFrom(), - cmd.getKey()); - Script command = new Script(_ovsTunnelPath, _timeout, s_logger); - command.add("create_tunnel"); - command.add("--bridge", bridge); - command.add("--remote_ip", cmd.getRemoteIp()); - command.add("--key", cmd.getKey().toString()); - command.add("--src_host", cmd.getFrom().toString()); - command.add("--dst_host", cmd.getTo().toString()); + configureTunnelNetwork(cmd.getNetworkId(), cmd.getFrom(), + cmd.getKey()); + Script command = new Script(_ovsTunnelPath, _timeout, s_logger); + command.add("create_tunnel"); + command.add("--bridge", bridge); + command.add("--remote_ip", cmd.getRemoteIp()); + command.add("--key", cmd.getKey().toString()); + command.add("--src_host", cmd.getFrom().toString()); + command.add("--dst_host", cmd.getTo().toString()); - String result = command.execute(); - if (result != null) { - return new OvsCreateTunnelAnswer(cmd, true, result, null, - bridge); - } else { - return new OvsCreateTunnelAnswer(cmd, false, result, bridge); - } - } catch (Exception e) { - s_logger.debug("Error during tunnel setup"); - s_logger.warn("Caught execption when creating ovs tunnel", e); - return new OvsCreateTunnelAnswer(cmd, false, e.getMessage(), bridge); - } - } + String result = command.execute(); + if (result != null) { + return new OvsCreateTunnelAnswer(cmd, true, result, null, + bridge); + } else { + return new OvsCreateTunnelAnswer(cmd, false, result, bridge); + } + } catch (Exception e) { + s_logger.debug("Error during tunnel setup"); + s_logger.warn("Caught execption when creating ovs tunnel", e); + return new OvsCreateTunnelAnswer(cmd, false, e.getMessage(), bridge); + } + } - private Answer execute(OvsDestroyTunnelCommand cmd) { - try { - if (!findOrCreateTunnelNetwork(cmd.getKey())) { - s_logger.warn("Unable to find tunnel network for GRE key:" - + cmd.getKey()); - return new Answer(cmd, false, "No network found"); - } + private Answer execute(OvsDestroyTunnelCommand cmd) { + try { + if (!findOrCreateTunnelNetwork(cmd.getKey())) { + s_logger.warn("Unable to find tunnel network for GRE key:" + + cmd.getKey()); + return new Answer(cmd, false, "No network found"); + } - String bridge = "OVSTunnel" + cmd.getKey(); - Script command = new Script(_ovsTunnelPath, _timeout, s_logger); - command.add("destroy_tunnel"); - command.add("--bridge", bridge); - command.add("--iface_name", cmd.getInPortName()); - String result = command.execute(); - if (result == null) { - return new Answer(cmd, true, result); - } else { - return new Answer(cmd, false, result); - } - } catch (Exception e) { - s_logger.warn("caught execption when destroy ovs tunnel", e); - return new Answer(cmd, false, e.getMessage()); - } - } + String bridge = "OVSTunnel" + cmd.getKey(); + Script command = new Script(_ovsTunnelPath, _timeout, s_logger); + command.add("destroy_tunnel"); + command.add("--bridge", bridge); + command.add("--iface_name", cmd.getInPortName()); + String result = command.execute(); + if (result == null) { + return new Answer(cmd, true, result); + } else { + return new Answer(cmd, false, result); + } + } catch (Exception e) { + s_logger.warn("caught execption when destroy ovs tunnel", e); + return new Answer(cmd, false, e.getMessage()); + } + } private CheckNetworkAnswer execute(CheckNetworkCommand cmd) { List phyNics = cmd.getPhysicalNetworkInfoList(); @@ -1502,7 +1554,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv It COULD also do it the other way around, but the code in the ManagementServerImpl shows that it always sets copyToSecondary to true - */ + */ boolean copyToSecondary = cmd.toSecondaryStorage(); String volumePath = cmd.getVolumePath(); StorageFilerTO pool = cmd.getPool(); @@ -1515,8 +1567,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } catch (CloudRuntimeException e) { if (e.getMessage().contains("not found")) { primaryPool = - _storagePoolMgr.createStoragePool(cmd.getPool().getUuid(), cmd.getPool().getHost(), cmd.getPool().getPort(), cmd.getPool().getPath(), - cmd.getPool().getUserInfo(), cmd.getPool().getType()); + _storagePoolMgr.createStoragePool(cmd.getPool().getUuid(), cmd.getPool().getHost(), cmd.getPool().getPort(), cmd.getPool().getPath(), + cmd.getPool().getUserInfo(), cmd.getPool().getType()); } else { return new CopyVolumeAnswer(cmd, false, e.getMessage(), null, null); } @@ -1630,7 +1682,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv vol = primaryPool.createPhysicalDisk(dskch.getPath(), dskch.getSize()); } VolumeTO volume = - new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), pool.getPath(), vol.getName(), vol.getName(), disksize, null); + new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), pool.getPath(), vol.getName(), vol.getName(), disksize, null); volume.setBytesReadRate(dskch.getBytesReadRate()); volume.setBytesWriteRate(dskch.getBytesWriteRate()); volume.setIopsReadRate(dskch.getIopsReadRate()); @@ -1699,7 +1751,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv if (pool.getType() == StoragePoolType.CLVM && volFormat == PhysicalDiskFormat.RAW) { return "CLVM"; } else if ((poolType == StoragePoolType.NetworkFilesystem || poolType == StoragePoolType.SharedMountPoint || poolType == StoragePoolType.Filesystem) && - volFormat == PhysicalDiskFormat.QCOW2) { + volFormat == PhysicalDiskFormat.QCOW2) { return "QCOW2"; } return null; @@ -1759,7 +1811,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } s_logger.debug("got to the stage where we execute the volume resize, params:" + path + "," + currentSize + "," + newSize + "," + type + "," + - vmInstanceName + "," + shrinkOk); + vmInstanceName + "," + shrinkOk); final Script resizecmd = new Script(_resizeVolumePath, _cmdsTimeout, s_logger); resizecmd.add("-s", String.valueOf(newSize)); resizecmd.add("-c", String.valueOf(currentSize)); @@ -1804,11 +1856,20 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv String pif = matchPifFileInDirectory(brName); Pattern pattern = Pattern.compile("(\\D+)(\\d+)(\\D*)(\\d*)"); Matcher matcher = pattern.matcher(pif); - if (matcher.find()) { - if (brName.startsWith("brvx")) { + s_logger.debug("getting broadcast uri for pif " + pif + " and bridge " + brName); + if(matcher.find()) { + if (brName.startsWith("brvx")){ return BroadcastDomainType.Vxlan.toUri(matcher.group(2)).toString(); - } else { - return BroadcastDomainType.Vlan.toUri(matcher.group(4)).toString(); + } + else{ + if (!matcher.group(4).isEmpty()) { + return BroadcastDomainType.Vlan.toUri(matcher.group(4)).toString(); + } else { + //untagged or not matching (eth|bond)#.# + s_logger.debug("failed to get vNet id from bridge " + brName + + "attached to physical interface" + pif + ", perhaps untagged interface"); + return ""; + } } } else { s_logger.debug("failed to get vNet id from bridge " + brName + "attached to physical interface" + pif); @@ -1842,7 +1903,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv List ifaces = getInterfaces(conn, dhcpName); InterfaceDef guestNic = ifaces.get(0); script.add(opr, "-b", _guestBridgeName, "-p", primaryPvlan, "-i", isolatedPvlan, "-n", dhcpName, "-d", dhcpIp, "-m", dhcpMac, "-I", - guestNic.getDevName()); + guestNic.getDevName()); } else { script.add(opr, "-b", _guestBridgeName, "-p", primaryPvlan, "-i", isolatedPvlan, "-n", dhcpName, "-d", dhcpIp, "-m", dhcpMac); } @@ -1960,25 +2021,10 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } } - private SetupGuestNetworkAnswer execute(SetupGuestNetworkCommand cmd) { + private ExecutionResult prepareNetworkElementCommand(SetupGuestNetworkCommand cmd) { Connect conn; NicTO nic = cmd.getNic(); - String routerIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - String routerGIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP); String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); - String gateway = cmd.getAccessDetail(NetworkElementCommand.GUEST_NETWORK_GATEWAY); - String cidr = Long.toString(NetUtils.getCidrSize(nic.getNetmask())); - String domainName = cmd.getNetworkDomain(); - String dns = cmd.getDefaultDns1(); - - if (dns == null || dns.isEmpty()) { - dns = cmd.getDefaultDns2(); - } else { - String dns2 = cmd.getDefaultDns2(); - if (dns2 != null && !dns2.isEmpty()) { - dns += "," + dns2; - } - } try { conn = LibvirtConnection.getConnectionByVmName(routerName); @@ -1993,75 +2039,18 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } if (routerNic == null) { - return new SetupGuestNetworkAnswer(cmd, false, "Can not find nic with mac " + nic.getMac() + " for VM " + routerName); + return new ExecutionResult(false, "Can not find nic with mac " + nic.getMac() + " for VM " + routerName); } - String dev = "eth" + nic.getDeviceId(); - String netmask = NetUtils.getSubNet(routerGIP, nic.getNetmask()); - String result = _virtRouterResource.assignGuestNetwork(dev, routerIP, routerGIP, gateway, cidr, netmask, dns, domainName); - - if (result != null) { - return new SetupGuestNetworkAnswer(cmd, false, "Creating guest network failed due to " + result); - } - return new SetupGuestNetworkAnswer(cmd, true, "success"); + return new ExecutionResult(true, null); } catch (LibvirtException e) { String msg = "Creating guest network failed due to " + e.toString(); s_logger.warn(msg, e); - return new SetupGuestNetworkAnswer(cmd, false, msg); + return new ExecutionResult(false, msg); } } - private Answer execute(SetMonitorServiceCommand cmd) { - - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - String config = cmd.getConfiguration(); - - String result = _virtRouterResource.configureMonitor(routerIp, config); - - if (result != null) { - return new Answer(cmd, false, "SetMonitorServiceCommand failed"); - } - return new Answer(cmd); - - } - - private SetNetworkACLAnswer execute(SetNetworkACLCommand cmd) { - String[] results = new String[cmd.getRules().length]; - - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - String privateGw = cmd.getAccessDetail(NetworkElementCommand.VPC_PRIVATE_GATEWAY); - - try { - String[][] rules = cmd.generateFwRules(); - String[] aclRules = rules[0]; - NicTO nic = cmd.getNic(); - String dev = "eth" + nic.getDeviceId(); - String netmask = Long.toString(NetUtils.getCidrSize(nic.getNetmask())); - StringBuilder sb = new StringBuilder(); - - for (int i = 0; i < aclRules.length; i++) { - sb.append(aclRules[i]).append(','); - } - - String rule = sb.toString(); - String result = _virtRouterResource.assignNetworkACL(routerIp, dev, nic.getIp(), netmask, rule, privateGw); - - if (result != null) { - for (int i = 0; i < results.length; i++) { - results[i] = "Failed"; - } - return new SetNetworkACLAnswer(cmd, false, results); - } - - return new SetNetworkACLAnswer(cmd, true, results); - } catch (Exception e) { - String msg = "SetNetworkACL failed due to " + e.toString(); - s_logger.error(msg, e); - return new SetNetworkACLAnswer(cmd, false, results); - } - } - - protected SetSourceNatAnswer execute(SetSourceNatCommand cmd) { + protected ExecutionResult prepareNetworkElementCommand(SetSourceNatCommand cmd) { Connect conn; String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); String routerIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); @@ -2082,34 +2071,28 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv /*skip over, no physical bridge device exists*/ } else if (pluggedVlanId == null) { /*this should only be true in the case of link local bridge*/ - return new SetSourceNatAnswer(cmd, false, "unable to find the vlan id for bridge " + pluggedVlanBr + " when attempting to set up" + pubVlan + - " on router " + routerName); + return new ExecutionResult(false, "unable to find the vlan id for bridge " + pluggedVlanBr + " when attempting to set up" + pubVlan + + " on router " + routerName); } else if (pluggedVlanId.equals(pubVlan)) { break; } devNum++; } - String dev = "eth" + devNum; - String result = _virtRouterResource.assignSourceNat(routerIP, pubIP.getPublicIp(), dev); + pubIP.setNicDevId(devNum); - if (result != null) { - return new SetSourceNatAnswer(cmd, false, "KVM plugin \"vpc_snat\" failed:" + result); - } - return new SetSourceNatAnswer(cmd, true, "success"); + return new ExecutionResult(true, "success"); } catch (LibvirtException e) { String msg = "Ip SNAT failure due to " + e.toString(); s_logger.error(msg, e); - return new SetSourceNatAnswer(cmd, false, msg); + return new ExecutionResult(false, msg); } } - protected IpAssocAnswer execute(IpAssocVpcCommand cmd) { + protected ExecutionResult prepareNetworkElementCommand(IpAssocVpcCommand cmd) { Connect conn; - String[] results = new String[cmd.getIpAddresses().length]; int i = 0; String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); - String routerIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); try { conn = LibvirtConnection.getConnectionByVmName(routerName); @@ -2123,7 +2106,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv if (pluggedVlan.equalsIgnoreCase(_linkLocalBridgeName)) { broadcastUriToNicNum.put("LinkLocal", devNum); } else if (pluggedVlan.equalsIgnoreCase(_publicBridgeName) || pluggedVlan.equalsIgnoreCase(_privBridgeName) || - pluggedVlan.equalsIgnoreCase(_guestBridgeName)) { + pluggedVlan.equalsIgnoreCase(_guestBridgeName)) { broadcastUriToNicNum.put(BroadcastDomainType.Vlan.toUri(Vlan.UNTAGGED).toString(), devNum); } else { broadcastUriToNicNum.put(getBroadcastUriFromBridge(pluggedVlan), devNum); @@ -2132,31 +2115,19 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } for (IpAddressTO ip : ips) { - String nicName = "eth" + broadcastUriToNicNum.get(ip.getBroadcastUri()); - String netmask = Long.toString(NetUtils.getCidrSize(ip.getVlanNetmask())); - String subnet = NetUtils.getSubNet(ip.getPublicIp(), ip.getVlanNetmask()); - _virtRouterResource.assignVpcIpToRouter(routerIP, ip.isAdd(), ip.getPublicIp(), nicName, ip.getVlanGateway(), netmask, subnet, ip.isSourceNat()); - results[i++] = ip.getPublicIp() + " - success"; + ip.setNicDevId(broadcastUriToNicNum.get(ip.getBroadcastUri())); } + return new ExecutionResult(true, null); } catch (LibvirtException e) { s_logger.error("Ip Assoc failure on applying one ip due to exception: ", e); - results[i++] = IpAssocAnswer.errorResult; - } catch (InternalErrorException e) { - s_logger.error("Ip Assoc failure on applying one ip due to exception: ", e); - results[i++] = IpAssocAnswer.errorResult; + return new ExecutionResult(false, e.getMessage()); } - - return new IpAssocAnswer(cmd, results); } - public Answer execute(IpAssocCommand cmd) { + public ExecutionResult prepareNetworkElementCommand(IpAssocCommand cmd) { String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - String[] results = new String[cmd.getIpAddresses().length]; - for (int i = 0; i < results.length; i++) { - results[i] = IpAssocAnswer.errorResult; - } Connect conn; try { conn = LibvirtConnection.getConnectionByVmName(routerName); @@ -2168,7 +2139,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv broadcastUriAllocatedToVM.put("LinkLocal", nicPos); } else { if (nic.getBrName().equalsIgnoreCase(_publicBridgeName) || nic.getBrName().equalsIgnoreCase(_privBridgeName) || - nic.getBrName().equalsIgnoreCase(_guestBridgeName)) { + nic.getBrName().equalsIgnoreCase(_guestBridgeName)) { broadcastUriAllocatedToVM.put(BroadcastDomainType.Vlan.toUri(Vlan.UNTAGGED).toString(), nicPos); } else { String broadcastUri = getBroadcastUriFromBridge(nic.getBrName()); @@ -2178,11 +2149,9 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv nicPos++; } IpAddressTO[] ips = cmd.getIpAddresses(); - int i = 0; - String result = null; int nicNum = 0; - boolean newNic = false; for (IpAddressTO ip : ips) { + boolean newNic = false; if (!broadcastUriAllocatedToVM.containsKey(ip.getBroadcastUri())) { /* plug a vif into router */ VifHotPlug(conn, routerName, ip.getBroadcastUri(), ip.getVifMacAddress()); @@ -2191,21 +2160,17 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } nicNum = broadcastUriAllocatedToVM.get(ip.getBroadcastUri()); networkUsage(routerIp, "addVif", "eth" + nicNum); - result = - _virtRouterResource.assignPublicIpAddress(routerName, routerIp, ip.getPublicIp(), ip.isAdd(), ip.isFirstIP(), ip.isSourceNat(), ip.getBroadcastUri(), - ip.getVlanGateway(), ip.getVlanNetmask(), ip.getVifMacAddress(), nicNum, newNic); - if (result == null) { - results[i++] = ip.getPublicIp() + " - success"; - } + ip.setNicDevId(nicNum); + ip.setNewNic(newNic); } - return new IpAssocAnswer(cmd, results); + return new ExecutionResult(true, null); } catch (LibvirtException e) { s_logger.error("ipassoccmd failed", e); - return new IpAssocAnswer(cmd, results); + return new ExecutionResult(false, e.getMessage()); } catch (InternalErrorException e) { s_logger.error("ipassoccmd failed", e); - return new IpAssocAnswer(cmd, results); + return new ExecutionResult(false, e.getMessage()); } } @@ -2342,7 +2307,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv * * These bindings will read the snapshot and write the contents to * the secondary storage directly - * + * * It will stop doing so if the amount of time spend is longer then * cmds.timeout */ @@ -2358,8 +2323,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv Rbd rbd = new Rbd(io); RbdImage image = rbd.open(snapshotDisk.getName(), snapshotName); - long startTime = System.currentTimeMillis() / 1000; - File fh = new File(snapshotDestPath); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fh)); int chunkSize = 4194304; @@ -2562,8 +2525,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } catch (CloudRuntimeException e) { if (e.getMessage().contains("not found")) { primary = - _storagePoolMgr.createStoragePool(cmd.getPool().getUuid(), cmd.getPool().getHost(), cmd.getPool().getPort(), cmd.getPool().getPath(), - cmd.getPool().getUserInfo(), cmd.getPool().getType()); + _storagePoolMgr.createStoragePool(cmd.getPool().getUuid(), cmd.getPool().getHost(), cmd.getPool().getPort(), cmd.getPool().getPath(), + cmd.getPool().getUserInfo(), cmd.getPool().getType()); } else { return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage()); } @@ -2589,8 +2552,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv s_logger.debug("Converting RBD disk " + disk.getPath() + " into template " + cmd.getUniqueName()); QemuImgFile srcFile = - new QemuImgFile(KVMPhysicalDisk.RBDStringBuilder(primary.getSourceHost(), primary.getSourcePort(), primary.getAuthUserName(), - primary.getAuthSecret(), disk.getPath())); + new QemuImgFile(KVMPhysicalDisk.RBDStringBuilder(primary.getSourceHost(), primary.getSourcePort(), primary.getAuthUserName(), + primary.getAuthSecret(), disk.getPath())); srcFile.setFormat(PhysicalDiskFormat.RAW); QemuImgFile destFile = new QemuImgFile(tmpltPath + "/" + cmd.getUniqueName() + ".qcow2"); @@ -2601,7 +2564,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv q.convert(srcFile, destFile); } catch (QemuImgException e) { s_logger.error("Failed to create new template while converting " + srcFile.getFileName() + " to " + destFile.getFileName() + " the error was: " + - e.getMessage()); + e.getMessage()); } File templateProp = new File(tmpltPath + "/template.properties"); @@ -2635,7 +2598,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv loc.save(); return new CreatePrivateTemplateAnswer(cmd, true, null, templateInstallFolder + cmd.getUniqueName() + ".qcow2", info.virtualSize, info.size, - cmd.getUniqueName(), ImageFormat.QCOW2); + cmd.getUniqueName(), ImageFormat.QCOW2); } catch (InternalErrorException e) { return new CreatePrivateTemplateAnswer(cmd, false, e.toString()); } catch (IOException e) { @@ -2706,8 +2669,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv protected Answer execute(ModifyStoragePoolCommand cmd) { KVMStoragePool storagepool = - _storagePoolMgr.createStoragePool(cmd.getPool().getUuid(), cmd.getPool().getHost(), cmd.getPool().getPort(), cmd.getPool().getPath(), cmd.getPool() - .getUserInfo(), cmd.getPool().getType()); + _storagePoolMgr.createStoragePool(cmd.getPool().getUuid(), cmd.getPool().getHost(), cmd.getPool().getPort(), cmd.getPool().getPath(), cmd.getPool() + .getUserInfo(), cmd.getPool().getType()); if (storagepool == null) { return new Answer(cmd, false, " Failed to create storage pool"); } @@ -2731,15 +2694,15 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } boolean result = - add_network_rules(cmd.getVmName(), Long.toString(cmd.getVmId()), cmd.getGuestIp(), cmd.getSignature(), Long.toString(cmd.getSeqNum()), cmd.getGuestMac(), - cmd.stringifyRules(), vif, brname, cmd.getSecIpsString()); + add_network_rules(cmd.getVmName(), Long.toString(cmd.getVmId()), cmd.getGuestIp(), cmd.getSignature(), Long.toString(cmd.getSeqNum()), cmd.getGuestMac(), + cmd.stringifyRules(), vif, brname, cmd.getSecIpsString()); if (!result) { s_logger.warn("Failed to program network rules for vm " + cmd.getVmName()); return new SecurityGroupRuleAnswer(cmd, false, "programming network rules failed"); } else { s_logger.debug("Programmed network rules for vm " + cmd.getVmName() + " guestIp=" + cmd.getGuestIp() + ",ingress numrules=" + cmd.getIngressRuleSet().length + - ",egress numrules=" + cmd.getEgressRuleSet().length); + ",egress numrules=" + cmd.getEgressRuleSet().length); return new SecurityGroupRuleAnswer(cmd); } } @@ -2830,8 +2793,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv KVMStoragePool primary = _storagePoolMgr.getStoragePool(cmd.getPooltype(), cmd.getPoolUuid()); KVMPhysicalDisk disk = primary.getPhysicalDisk(cmd.getVolumePath()); attachOrDetachDisk(conn, cmd.getAttach(), cmd.getVmName(), disk, - cmd.getDeviceId().intValue(), cmd.getBytesReadRate(), cmd.getBytesWriteRate(), cmd.getIopsReadRate(), cmd.getIopsWriteRate(), - cmd.getCacheMode()); + cmd.getDeviceId().intValue(), cmd.getBytesReadRate(), cmd.getBytesWriteRate(), cmd.getIopsReadRate(), cmd.getIopsWriteRate(), + cmd.getCacheMode()); } catch (LibvirtException e) { return new AttachVolumeAnswer(cmd, e.toString()); } catch (InternalErrorException e) { @@ -2965,15 +2928,14 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv description for the instance to be used on the target host. This is supported by libvirt-java from version 0.50.0 - */ + */ xmlDesc = dm.getXMLDesc(0).replace(_privateIp, cmd.getDestinationIp()); dconn = new Connect("qemu+tcp://" + cmd.getDestinationIp() + "/system"); /* - * Hard code lm flags: VIR_MIGRATE_LIVE(1<<0) and - * VIR_MIGRATE_PERSIST_DEST(1<<3) + * Hard code lm flag: VIR_MIGRATE_LIVE(1<<0) */ - destDomain = dm.migrate(dconn, (1 << 0) | (1 << 3), xmlDesc, vmName, "tcp:" + cmd.getDestinationIp(), _migrateSpeed); + destDomain = dm.migrate(dconn, (1 << 0), xmlDesc, vmName, "tcp:" + cmd.getDestinationIp(), _migrateSpeed); _storagePoolMgr.disconnectPhysicalDisksViaVmSpec(cmd.getVirtualMachine()); } catch (LibvirtException e) { @@ -3141,8 +3103,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv String[] splitResult = result.split(":"); int i = 0; while (i < splitResult.length - 1) { - stats[0] += (new Long(splitResult[i++])).longValue(); - stats[1] += (new Long(splitResult[i++])).longValue(); + stats[0] += Long.parseLong(splitResult[i++]); + stats[1] += Long.parseLong(splitResult[i++]); } } return stats; @@ -3183,8 +3145,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv String[] splitResult = result.split(":"); int i = 0; while (i < splitResult.length - 1) { - stats[0] += (new Long(splitResult[i++])).longValue(); - stats[1] += (new Long(splitResult[i++])).longValue(); + stats[0] += Long.parseLong(splitResult[i++]); + stats[1] += Long.parseLong(splitResult[i++]); } } return stats; @@ -3217,8 +3179,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } } - - private Answer execute(RebootCommand cmd) { + private Answer execute(RebootCommand cmd) { synchronized (_vms) { _vms.put(cmd.getVmName(), State.Starting); @@ -3299,8 +3260,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } } - - protected Answer execute(StopCommand cmd) { + protected Answer execute(StopCommand cmd) { final String vmName = cmd.getVmName(); State state = null; @@ -3345,21 +3305,21 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } protected Answer execute(ModifySshKeysCommand cmd) { - File sshKeysDir = new File(_SSHKEYSPATH); + File sshKeysDir = new File(SSHKEYSPATH); String result = null; if (!sshKeysDir.exists()) { // Change permissions for the 700 Script script = new Script("mkdir", _timeout, s_logger); script.add("-m", "700"); - script.add(_SSHKEYSPATH); + script.add(SSHKEYSPATH); script.execute(); if (!sshKeysDir.exists()) { - s_logger.debug("failed to create directory " + _SSHKEYSPATH); + s_logger.debug("failed to create directory " + SSHKEYSPATH); } } - File pubKeyFile = new File(_SSHPUBKEYPATH); + File pubKeyFile = new File(SSHPUBKEYPATH); if (!pubKeyFile.exists()) { try { pubKeyFile.createNewFile(); @@ -3376,15 +3336,15 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv pubkStream.write(pubKey.getBytes()); pubkStream.close(); } catch (FileNotFoundException e) { - result = "File" + _SSHPUBKEYPATH + "is not found:" + e.toString(); + result = "File" + SSHPUBKEYPATH + "is not found:" + e.toString(); s_logger.debug(result); } catch (IOException e) { - result = "Write file " + _SSHPUBKEYPATH + ":" + e.toString(); + result = "Write file " + SSHPUBKEYPATH + ":" + e.toString(); s_logger.debug(result); } } - File prvKeyFile = new File(_SSHPRVKEYPATH); + File prvKeyFile = new File(SSHPRVKEYPATH); if (!prvKeyFile.exists()) { try { prvKeyFile.createNewFile(); @@ -3401,15 +3361,15 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv prvKStream.write(prvKey.getBytes()); prvKStream.close(); } catch (FileNotFoundException e) { - result = "File" + _SSHPRVKEYPATH + "is not found:" + e.toString(); + result = "File" + SSHPRVKEYPATH + "is not found:" + e.toString(); s_logger.debug(result); } catch (IOException e) { - result = "Write file " + _SSHPRVKEYPATH + ":" + e.toString(); + result = "Write file " + SSHPRVKEYPATH + ":" + e.toString(); s_logger.debug(result); } Script script = new Script("chmod", _timeout, s_logger); - script.add("600", _SSHPRVKEYPATH); + script.add("600", SSHPRVKEYPATH); script.execute(); } @@ -3472,19 +3432,28 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv GuestResourceDef grd = new GuestResourceDef(); - if (vmTO.getMinRam() != vmTO.getMaxRam()) { + if (vmTO.getMinRam() != vmTO.getMaxRam() && !_noMemBalloon) { grd.setMemBalloning(true); grd.setCurrentMem(vmTO.getMinRam() / 1024); grd.setMemorySize(vmTO.getMaxRam() / 1024); } else { grd.setMemorySize(vmTO.getMaxRam() / 1024); } - grd.setVcpuNum(vmTO.getCpus()); + int vcpus = vmTO.getCpus(); + grd.setVcpuNum(vcpus); vm.addComp(grd); CpuModeDef cmd = new CpuModeDef(); cmd.setMode(_guestCpuMode); cmd.setModel(_guestCpuModel); + // multi cores per socket, for larger core configs + if (vcpus % 6 == 0) { + int sockets = vcpus / 6; + cmd.setTopology(6, sockets); + } else if (vcpus % 4 == 0) { + int sockets = vcpus / 4; + cmd.setTopology(4, sockets); + } vm.addComp(cmd); if (_hypervisorLibvirtVersion >= 9000) { @@ -3616,7 +3585,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } // pass cmdline info to system vms - if (vmSpec.getType() != VirtualMachine.Type.User) { + if (vmSpec.getType() != VirtualMachine.Type.User) { if ((conn.getVersion() < 1001000)) { // CLOUDSTACK-2823: try passCmdLine some times if kernel < 2.6.34 and qemu < 1.1.0 on hypervisor (for instance, CentOS 6.4) //wait for 5 minutes at most String controlIp = null; @@ -3741,7 +3710,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv we pass the pool's UUID as the authSecret */ disk.defNetworkBasedDisk(physicalDisk.getPath().replace("rbd:", ""), pool.getSourceHost(), pool.getSourcePort(), pool.getAuthUserName(), - pool.getUuid(), devId, diskBusType, diskProtocol.RBD); + pool.getUuid(), devId, diskBusType, diskProtocol.RBD); } else if (pool.getType() == StoragePoolType.CLVM || physicalDisk.getFormat() == PhysicalDiskFormat.RAW) { disk.defBlockBasedDisk(physicalDisk.getPath(), devId, diskBusType); } else { @@ -3837,7 +3806,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } protected synchronized String attachOrDetachISO(Connect conn, String vmName, String isoPath, boolean isAttach) throws LibvirtException, URISyntaxException, - InternalErrorException { + InternalErrorException { String isoXml = null; if (isoPath != null && isAttach) { int index = isoPath.lastIndexOf("/"); @@ -3870,8 +3839,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } protected synchronized String attachOrDetachDisk(Connect conn, - boolean attach, String vmName, KVMPhysicalDisk attachingDisk, - int devId, Long bytesReadRate, Long bytesWriteRate, Long iopsReadRate, Long iopsWriteRate, String cacheMode) throws LibvirtException, InternalErrorException { + boolean attach, String vmName, KVMPhysicalDisk attachingDisk, + int devId, Long bytesReadRate, Long bytesWriteRate, Long iopsReadRate, Long iopsWriteRate, String cacheMode) throws LibvirtException, InternalErrorException { List disks = null; Domain dm = null; DiskDef diskdef = null; @@ -3898,7 +3867,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv diskdef = new DiskDef(); if (attachingPool.getType() == StoragePoolType.RBD) { diskdef.defNetworkBasedDisk(attachingDisk.getPath(), attachingPool.getSourceHost(), attachingPool.getSourcePort(), attachingPool.getAuthUserName(), - attachingPool.getUuid(), devId, DiskDef.diskBus.VIRTIO, diskProtocol.RBD); + attachingPool.getUuid(), devId, DiskDef.diskBus.VIRTIO, diskProtocol.RBD); } else if (attachingDisk.getFormat() == PhysicalDiskFormat.QCOW2) { diskdef.defFileBasedDisk(attachingDisk.getPath(), devId, DiskDef.diskBus.VIRTIO, DiskDef.diskFmtType.QCOW2); } else if (attachingDisk.getFormat() == PhysicalDiskFormat.RAW) { @@ -3962,7 +3931,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv public PingCommand getCurrentStatus(long id) { final HashMap newStates = sync(); - if (!_can_bridge_firewall) { + if (!_canBridgeFirewall) { return new PingRoutingCommand(com.cloud.host.Host.Type.Routing, id, newStates, this.getHostVmStateReport()); } else { HashMap> nwGrpStates = syncNetworkGroups(id); @@ -3998,8 +3967,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv final List info = getHostInfo(); final StartupRoutingCommand cmd = - new StartupRoutingCommand((Integer)info.get(0), (Long)info.get(1), (Long)info.get(2), (Long)info.get(4), (String)info.get(3), _hypervisorType, - RouterPrivateIpStrategy.HostLocal); + new StartupRoutingCommand((Integer)info.get(0), (Long)info.get(1), (Long)info.get(2), (Long)info.get(4), (String)info.get(3), _hypervisorType, + RouterPrivateIpStrategy.HostLocal); cmd.setStateChanges(changes); cmd.setCpuSockets((Integer)info.get(5)); fillNetworkInformation(cmd); @@ -4009,14 +3978,15 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv cmd.setCluster(_clusterId); cmd.setGatewayIpAddress(_localGateway); cmd.setHostVmStateReport(getHostVmStateReport()); + cmd.setIqn(getIqn()); StartupStorageCommand sscmd = null; try { KVMStoragePool localStoragePool = _storagePoolMgr.createStoragePool(_localStorageUUID, "localhost", -1, _localStoragePath, "", StoragePoolType.Filesystem); com.cloud.agent.api.StoragePoolInfo pi = - new com.cloud.agent.api.StoragePoolInfo(localStoragePool.getUuid(), cmd.getPrivateIpAddress(), _localStoragePath, _localStoragePath, - StoragePoolType.Filesystem, localStoragePool.getCapacity(), localStoragePool.getAvailable()); + new com.cloud.agent.api.StoragePoolInfo(localStoragePool.getUuid(), cmd.getPrivateIpAddress(), _localStoragePath, _localStoragePath, + StoragePoolType.Filesystem, localStoragePool.getCapacity(), localStoragePool.getAvailable()); sscmd = new StartupStorageCommand(); sscmd.setPoolInfo(pi); @@ -4034,6 +4004,32 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } } + private String getIqn() { + try { + final String textToFind = "InitiatorName="; + + Script iScsiAdmCmd = new Script(true, "grep", 0, s_logger); + + iScsiAdmCmd.add(textToFind); + iScsiAdmCmd.add("/etc/iscsi/initiatorname.iscsi"); + + OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser(); + + String result = iScsiAdmCmd.execute(parser); + + if (result != null) { + return null; + } + + String textFound = parser.getLine().trim(); + + return textFound.substring(textToFind.length()); + } + catch (Exception ex) { + return null; + } + } + protected HashMap sync() { HashMap newStates; HashMap oldStates = null; @@ -4696,11 +4692,11 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } String guestOSName = KVMGuestOsMapper.getGuestOsName(guestOS); if (guestOS.startsWith("Ubuntu") || guestOSName.startsWith("Fedora 13") || guestOSName.startsWith("Fedora 12") || guestOSName.startsWith("Fedora 11") || - guestOSName.startsWith("Fedora 10") || guestOSName.startsWith("Fedora 9") || guestOSName.startsWith("CentOS 5.3") || guestOSName.startsWith("CentOS 5.4") || - guestOSName.startsWith("CentOS 5.5") || guestOS.startsWith("CentOS") || guestOS.startsWith("Fedora") || - guestOSName.startsWith("Red Hat Enterprise Linux 5.3") || guestOSName.startsWith("Red Hat Enterprise Linux 5.4") || - guestOSName.startsWith("Red Hat Enterprise Linux 5.5") || guestOSName.startsWith("Red Hat Enterprise Linux 6") || guestOS.startsWith("Debian GNU/Linux") || - guestOSName.startsWith("Other PV")) { + guestOSName.startsWith("Fedora 10") || guestOSName.startsWith("Fedora 9") || guestOSName.startsWith("CentOS 5.3") || guestOSName.startsWith("CentOS 5.4") || + guestOSName.startsWith("CentOS 5.5") || guestOS.startsWith("CentOS") || guestOS.startsWith("Fedora") || + guestOSName.startsWith("Red Hat Enterprise Linux 5.3") || guestOSName.startsWith("Red Hat Enterprise Linux 5.4") || + guestOSName.startsWith("Red Hat Enterprise Linux 5.5") || guestOSName.startsWith("Red Hat Enterprise Linux 6") || guestOS.startsWith("Debian GNU/Linux") || + guestOSName.startsWith("Other PV")) { return true; } else { return false; @@ -4821,14 +4817,14 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } } - private class vmStats { + private class VmStats { long _usedTime; long _tx; long _rx; - long _io_rd; - long _io_wr; - long _bytes_rd; - long _bytes_wr; + long _ioRead; + long _ioWrote; + long _bytesRead; + long _bytesWrote; Calendar _timestamp; } @@ -4843,7 +4839,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv stats.setEntityType("vm"); /* get cpu utilization */ - vmStats oldStats = null; + VmStats oldStats = null; Calendar now = Calendar.getInstance(); @@ -4896,29 +4892,29 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } if (oldStats != null) { - long deltaiord = io_rd - oldStats._io_rd; + long deltaiord = io_rd - oldStats._ioRead; if (deltaiord > 0) stats.setDiskReadIOs(deltaiord); - long deltaiowr = io_wr - oldStats._io_wr; + long deltaiowr = io_wr - oldStats._ioWrote; if (deltaiowr > 0) stats.setDiskWriteIOs(deltaiowr); - double deltabytesrd = bytes_rd - oldStats._bytes_rd; + double deltabytesrd = bytes_rd - oldStats._bytesRead; if (deltabytesrd > 0) stats.setDiskReadKBs(deltabytesrd / 1024); - double deltabyteswr = bytes_wr - oldStats._bytes_wr; + double deltabyteswr = bytes_wr - oldStats._bytesWrote; if (deltabyteswr > 0) stats.setDiskWriteKBs(deltabyteswr / 1024); } /* save to Hashmap */ - vmStats newStat = new vmStats(); + VmStats newStat = new VmStats(); newStat._usedTime = info.cpuTime; newStat._rx = rx; newStat._tx = tx; - newStat._io_rd = io_rd; - newStat._io_wr = io_wr; - newStat._bytes_rd = bytes_rd; - newStat._bytes_wr = bytes_wr; + newStat._ioRead = io_rd; + newStat._ioWrote = io_wr; + newStat._bytesRead = bytes_rd; + newStat._bytesWrote = bytes_wr; newStat._timestamp = now; _vmStats.put(vmName, newStat); return stats; @@ -4941,7 +4937,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } protected boolean destroy_network_rules_for_vm(Connect conn, String vmName) { - if (!_can_bridge_firewall) { + if (!_canBridgeFirewall) { return false; } String vif = null; @@ -4964,7 +4960,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } protected boolean default_network_rules(Connect conn, String vmName, NicTO nic, Long vmId, String secIpStr) { - if (!_can_bridge_firewall) { + if (!_canBridgeFirewall) { return false; } @@ -4996,7 +4992,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } protected boolean post_default_network_rules(Connect conn, String vmName, NicTO nic, Long vmId, InetAddress dhcpServerIp, String hostIp, String hostMacAddr) { - if (!_can_bridge_firewall) { + if (!_canBridgeFirewall) { return false; } @@ -5030,7 +5026,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } protected boolean default_network_rules_for_systemvm(Connect conn, String vmName) { - if (!_can_bridge_firewall) { + if (!_canBridgeFirewall) { return false; } @@ -5046,8 +5042,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } private boolean add_network_rules(String vmName, String vmId, String guestIP, String sig, String seq, String mac, String rules, String vif, String brname, - String secIps) { - if (!_can_bridge_firewall) { + String secIps) { + if (!_canBridgeFirewall) { return false; } @@ -5075,7 +5071,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv private boolean network_rules_vmSecondaryIp(Connect conn, String vmName, String secIp, String action) { - if (!_can_bridge_firewall) { + if (!_canBridgeFirewall) { return false; } @@ -5093,7 +5089,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } private boolean cleanup_rules() { - if (!_can_bridge_firewall) { + if (!_canBridgeFirewall) { return false; } Script cmd = new Script(_securityGroupPath, _timeout, s_logger); diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtConnection.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtConnection.java index 6c8da8a0640..1ebf9363d31 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtConnection.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtConnection.java @@ -28,28 +28,28 @@ import com.cloud.hypervisor.Hypervisor.HypervisorType; public class LibvirtConnection { private static final Logger s_logger = Logger.getLogger(LibvirtConnection.class); - static private Map _connections = new HashMap(); + static private Map s_connections = new HashMap(); - static private Connect _connection; - static private String _hypervisorURI; + static private Connect s_connection; + static private String s_hypervisorURI; static public Connect getConnection() throws LibvirtException { - return getConnection(_hypervisorURI); + return getConnection(s_hypervisorURI); } static public Connect getConnection(String hypervisorURI) throws LibvirtException { - Connect conn = _connections.get(hypervisorURI); + Connect conn = s_connections.get(hypervisorURI); if (conn == null) { conn = new Connect(hypervisorURI, false); - _connections.put(hypervisorURI, conn); + s_connections.put(hypervisorURI, conn); } else { try { conn.getVersion(); } catch (LibvirtException e) { s_logger.debug("Connection with libvirtd is broken, due to " + e.getMessage()); conn = new Connect(hypervisorURI, false); - _connections.put(hypervisorURI, conn); + s_connections.put(hypervisorURI, conn); } } @@ -80,7 +80,7 @@ public class LibvirtConnection { } static void initialize(String hypervisorURI) { - _hypervisorURI = hypervisorURI; + s_hypervisorURI = hypervisorURI; } static String getHypervisorURI(String hypervisorType) { diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtNetworkDef.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtNetworkDef.java index a069e08e675..f20bec418d4 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtNetworkDef.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtNetworkDef.java @@ -35,14 +35,14 @@ public class LibvirtNetworkDef { private String _brIPAddr; private String _brNetMask; private final List ipranges = new ArrayList(); - private final List dhcpMaps = new ArrayList(); + private final List dhcpMaps = new ArrayList(); - public static class dhcpMapping { + public static class DhcpMapping { String _mac; String _name; String _ip; - public dhcpMapping(String mac, String name, String ip) { + public DhcpMapping(String mac, String name, String ip) { _mac = mac; _name = name; _ip = ip; @@ -100,7 +100,7 @@ public class LibvirtNetworkDef { } public void adddhcpMapping(String mac, String host, String ip) { - dhcpMapping map = new dhcpMapping(mac, host, ip); + DhcpMapping map = new DhcpMapping(mac, host, ip); dhcpMaps.add(map); } @@ -153,7 +153,7 @@ public class LibvirtNetworkDef { for (IPRange ip : ipranges) { netBuilder.append("\n"); } - for (dhcpMapping map : dhcpMaps) { + for (DhcpMapping map : dhcpMaps) { netBuilder.append("\n"); } netBuilder.append("\n"); diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java index 9910877f2ea..5aeacdafae0 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java @@ -23,8 +23,8 @@ import java.util.Map; public class LibvirtVMDef { private String _hvsType; - private static long _libvirtVersion; - private static long _qemuVersion; + private static long s_libvirtVersion; + private static long s_qemuVersion; private String _domName; private String _domUUID; private String _desc; @@ -162,6 +162,8 @@ public class LibvirtVMDef { } if (_memBalloning) { resBuidler.append("\n" + "\n" + "\n"); + } else { + resBuidler.append("\n" + "\n" + "\n"); } if (_vcpu != -1) { resBuidler.append("" + _vcpu + "\n"); @@ -665,8 +667,8 @@ public class LibvirtVMDef { diskBuilder.append("/>\n"); if ((_deviceType != deviceType.CDROM) && - (_libvirtVersion >= 9008) && - (_qemuVersion >= 1001000) && + (s_libvirtVersion >= 9008) && + (s_qemuVersion >= 1001000) && (((_bytesReadRate != null) && (_bytesReadRate > 0)) || ((_bytesWriteRate != null) && (_bytesWriteRate > 0)) || ((_iopsReadRate != null) && (_iopsReadRate > 0)) || ((_iopsWriteRate != null) && (_iopsWriteRate > 0)))) { // not CDROM, from libvirt 0.9.8 and QEMU 1.1.0 diskBuilder.append("\n"); @@ -866,7 +868,7 @@ public class LibvirtVMDef { if (_model != null) { netBuilder.append("\n"); } - if ((_libvirtVersion >= 9004) && (_networkRateKBps > 0)) { // supported from libvirt 0.9.4 + if ((s_libvirtVersion >= 9004) && (_networkRateKBps > 0)) { // supported from libvirt 0.9.4 netBuilder.append("\n"); netBuilder.append("\n"); netBuilder.append("\n"); @@ -949,6 +951,8 @@ public class LibvirtVMDef { public static class CpuModeDef { private String _mode; private String _model; + private int _coresPerSocket = -1; + private int _sockets = -1; public void setMode(String mode) { _mode = mode; @@ -958,17 +962,34 @@ public class LibvirtVMDef { _model = model; } + public void setTopology(int coresPerSocket, int sockets) { + _coresPerSocket = coresPerSocket; + _sockets = sockets; + } + @Override public String toString() { - StringBuilder modeBuidler = new StringBuilder(); - if ("custom".equalsIgnoreCase(_mode) && _model != null) { - modeBuidler.append("" + _model + ""); + StringBuilder modeBuilder = new StringBuilder(); + + // start cpu def, adding mode, model + if ("custom".equalsIgnoreCase(_mode) && _model != null){ + modeBuilder.append("" + _model + ""); } else if ("host-model".equals(_mode)) { - modeBuidler.append(""); + modeBuilder.append(""); } else if ("host-passthrough".equals(_mode)) { - modeBuidler.append(""); + modeBuilder.append(""); + } else { + modeBuilder.append(""); } - return modeBuidler.toString(); + + // add topology + if (_sockets > 0 && _coresPerSocket > 0) { + modeBuilder.append(""); + } + + // close cpu def + modeBuilder.append(""); + return modeBuilder.toString(); } } @@ -1113,11 +1134,11 @@ public class LibvirtVMDef { } public void setLibvirtVersion(long libvirtVersion) { - _libvirtVersion = libvirtVersion; + s_libvirtVersion = libvirtVersion; } public void setQemuVersion(long qemuVersion) { - _qemuVersion = qemuVersion; + s_qemuVersion = qemuVersion; } public void setDomainName(String domainName) { diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java index dc60f077ac1..c64a472ade2 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java @@ -74,7 +74,7 @@ public class OvsVifDriver extends VifDriverBase { if (nic.getType() == Networks.TrafficType.Guest) { Integer networkRateKBps = (nic.getNetworkRateMbps() != null && nic.getNetworkRateMbps().intValue() != -1) ? nic.getNetworkRateMbps().intValue() * 128 : 0; if ((nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan || nic.getBroadcastType() == Networks.BroadcastDomainType.Pvlan) && - !vlanId.equalsIgnoreCase("untagged")) { + !vlanId.equalsIgnoreCase("untagged")) { if (trafficLabel != null && !trafficLabel.isEmpty()) { s_logger.debug("creating a vlan dev and bridge for guest traffic per traffic label " + trafficLabel); intf.defBridgeNet(_pifs.get(trafficLabel), null, nic.getMac(), getGuestNicModel(guestOsType), networkRateKBps); @@ -83,7 +83,7 @@ public class OvsVifDriver extends VifDriverBase { intf.defBridgeNet(_pifs.get("private"), null, nic.getMac(), getGuestNicModel(guestOsType), networkRateKBps); intf.setVlanTag(Integer.parseInt(vlanId)); } - } else if (nic.getBroadcastType() == Networks.BroadcastDomainType.Lswitch) { + } else if (nic.getBroadcastType() == Networks.BroadcastDomainType.Lswitch || nic.getBroadcastType() == Networks.BroadcastDomainType.OpenDaylight) { s_logger.debug("nic " + nic + " needs to be connected to LogicalSwitch " + logicalSwitchUuid); intf.setVirtualPortInterfaceId(nic.getUuid()); String brName = (trafficLabel != null && !trafficLabel.isEmpty()) ? _pifs.get(trafficLabel) : _pifs.get("private"); @@ -143,7 +143,7 @@ public class OvsVifDriver extends VifDriverBase { } if (!foundLinkLocalBr) { Script.runSimpleBashScript("ifconfig " + linkLocalBr + " 169.254.0.1;" + "ip route add " + NetUtils.getLinkLocalCIDR() + " dev " + linkLocalBr + " src " + - NetUtils.getLinkLocalGateway()); + NetUtils.getLinkLocalGateway()); } } @@ -159,7 +159,7 @@ public class OvsVifDriver extends VifDriverBase { command.add("-c"); command.add("ovs-vsctl br-exists " + bridgeName); String result = command.execute(null); - if ("Ok".equals(result)) { + if ("0".equals(result)) { return true; } else { return false; diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/iScsiAdmStorageAdaptor.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/IscsiAdmStorageAdaptor.java similarity index 96% rename from plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/iScsiAdmStorageAdaptor.java rename to plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/IscsiAdmStorageAdaptor.java index 3c500348dae..761bb377ee3 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/iScsiAdmStorageAdaptor.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/IscsiAdmStorageAdaptor.java @@ -31,28 +31,28 @@ import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.script.OutputInterpreter; import com.cloud.utils.script.Script; -public class iScsiAdmStorageAdaptor implements StorageAdaptor { - private static final Logger s_logger = Logger.getLogger(iScsiAdmStorageAdaptor.class); +public class IscsiAdmStorageAdaptor implements StorageAdaptor { + private static final Logger s_logger = Logger.getLogger(IscsiAdmStorageAdaptor.class); - private static final Map _mapStorageUuidToStoragePool = new HashMap(); + private static final Map MapStorageUuidToStoragePool = new HashMap(); @Override public KVMStoragePool createStoragePool(String uuid, String host, int port, String path, String userInfo, StoragePoolType storagePoolType) { - iScsiAdmStoragePool storagePool = new iScsiAdmStoragePool(uuid, host, port, storagePoolType, this); + IscsiAdmStoragePool storagePool = new IscsiAdmStoragePool(uuid, host, port, storagePoolType, this); - _mapStorageUuidToStoragePool.put(uuid, storagePool); + MapStorageUuidToStoragePool.put(uuid, storagePool); return storagePool; } @Override public KVMStoragePool getStoragePool(String uuid) { - return _mapStorageUuidToStoragePool.get(uuid); + return MapStorageUuidToStoragePool.get(uuid); } @Override public boolean deleteStoragePool(String uuid) { - return _mapStorageUuidToStoragePool.remove(uuid) != null; + return MapStorageUuidToStoragePool.remove(uuid) != null; } @Override diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/iScsiAdmStoragePool.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/IscsiAdmStoragePool.java similarity index 97% rename from plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/iScsiAdmStoragePool.java rename to plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/IscsiAdmStoragePool.java index 380881503ea..2cecfa3892b 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/iScsiAdmStoragePool.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/IscsiAdmStoragePool.java @@ -23,7 +23,7 @@ import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat; import com.cloud.storage.Storage.StoragePoolType; -public class iScsiAdmStoragePool implements KVMStoragePool { +public class IscsiAdmStoragePool implements KVMStoragePool { private String _uuid; private String _sourceHost; private int _sourcePort; @@ -34,7 +34,7 @@ public class iScsiAdmStoragePool implements KVMStoragePool { private String _sourceDir; private String _localPath; - public iScsiAdmStoragePool(String uuid, String host, int port, StoragePoolType storagePoolType, StorageAdaptor storageAdaptor) { + public IscsiAdmStoragePool(String uuid, String host, int port, StoragePoolType storagePoolType, StorageAdaptor storageAdaptor) { _uuid = uuid; _sourceHost = host; _sourcePort = port; diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/KVMStoragePoolManager.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/KVMStoragePoolManager.java index 08286e408cc..9e07e4bea29 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/KVMStoragePoolManager.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/KVMStoragePoolManager.java @@ -94,7 +94,7 @@ public class KVMStoragePoolManager { this._storageMapper.put("libvirt", new LibvirtStorageAdaptor(storagelayer)); // add other storage adaptors here // this._storageMapper.put("newadaptor", new NewStorageAdaptor(storagelayer)); - this._storageMapper.put(StoragePoolType.Iscsi.toString(), new iScsiAdmStorageAdaptor()); + this._storageMapper.put(StoragePoolType.Iscsi.toString(), new IscsiAdmStorageAdaptor()); } public boolean connectPhysicalDisk(StoragePoolType type, String poolUuid, String volPath, Map details) { @@ -171,6 +171,11 @@ public class KVMStoragePoolManager { KVMStoragePool pool = getStoragePool(store.getPoolType(), store.getUuid()); + if (pool == null) { + s_logger.error("Pool " + store.getUuid() + " of type " + store.getPoolType() + " was not found, skipping disconnect logic"); + continue; + } + StorageAdaptor adaptor = getStorageAdaptor(pool.getType()); // if a disk fails to disconnect, still try to disconnect remaining diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/KVMStorageProcessor.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/KVMStorageProcessor.java index db7706c2fd2..7d5d3351220 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/KVMStorageProcessor.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/KVMStorageProcessor.java @@ -102,8 +102,8 @@ import com.cloud.utils.script.Script; public class KVMStorageProcessor implements StorageProcessor { private static final Logger s_logger = Logger.getLogger(KVMStorageProcessor.class); - private KVMStoragePoolManager storagePoolMgr; - private LibvirtComputingResource resource; + private final KVMStoragePoolManager storagePoolMgr; + private final LibvirtComputingResource resource; private StorageLayer storageLayer; private String _createTmplPath; private String _manageSnapshotPath; @@ -189,6 +189,7 @@ public class KVMStorageProcessor implements StorageProcessor { } /* Copy volume to primary storage */ + s_logger.debug("Copying template to primary storage, template format is " + tmplVol.getFormat() ); KVMStoragePool primaryPool = storagePoolMgr.getStoragePool(primaryStore.getPoolType(), primaryStore.getUuid()); KVMPhysicalDisk primaryVol = null; @@ -460,7 +461,7 @@ public class KVMStorageProcessor implements StorageProcessor { KVMPhysicalDisk disk = storagePoolMgr.getPhysicalDisk(primaryStore.getPoolType(), primaryStore.getUuid(), volume.getPath()); String tmpltPath = secondaryStorage.getLocalPath() + File.separator + templateFolder; - this.storageLayer.mkdirs(tmpltPath); + storageLayer.mkdirs(tmpltPath); String templateName = UUID.randomUUID().toString(); if (primary.getType() != StoragePoolType.RBD) { @@ -512,14 +513,14 @@ public class KVMStorageProcessor implements StorageProcessor { } Map params = new HashMap(); - params.put(StorageLayer.InstanceConfigKey, this.storageLayer); + params.put(StorageLayer.InstanceConfigKey, storageLayer); Processor qcow2Processor = new QCOW2Processor(); qcow2Processor.configure("QCOW2 Processor", params); FormatInfo info = qcow2Processor.process(tmpltPath, null, templateName); - TemplateLocation loc = new TemplateLocation(this.storageLayer, tmpltPath); + TemplateLocation loc = new TemplateLocation(storageLayer, tmpltPath); loc.create(1, true, templateName); loc.addFormat(info); loc.save(); @@ -644,8 +645,11 @@ public class KVMStorageProcessor implements StorageProcessor { String snapshotRelPath = null; String vmName = snapshot.getVmName(); KVMStoragePool secondaryStoragePool = null; + Connect conn = null; + KVMPhysicalDisk snapshotDisk = null; + KVMStoragePool primaryPool = null; try { - Connect conn = LibvirtConnection.getConnectionByVmName(vmName); + conn = LibvirtConnection.getConnectionByVmName(vmName); secondaryStoragePool = storagePoolMgr.getStoragePoolByURI(secondaryStoragePoolUrl); @@ -653,8 +657,8 @@ public class KVMStorageProcessor implements StorageProcessor { snapshotRelPath = destSnapshot.getPath(); snapshotDestPath = ssPmountPath + File.separator + snapshotRelPath; - KVMPhysicalDisk snapshotDisk = storagePoolMgr.getPhysicalDisk(primaryStore.getPoolType(), primaryStore.getUuid(), volumePath); - KVMStoragePool primaryPool = snapshotDisk.getPool(); + snapshotDisk = storagePoolMgr.getPhysicalDisk(primaryStore.getPoolType(), primaryStore.getUuid(), volumePath); + primaryPool = snapshotDisk.getPool(); /** * RBD snapshots can't be copied using qemu-img, so we have to use @@ -732,46 +736,6 @@ public class KVMStorageProcessor implements StorageProcessor { } } - /* Delete the snapshot on primary */ - - DomainInfo.DomainState state = null; - Domain vm = null; - if (vmName != null) { - try { - vm = this.resource.getDomain(conn, vmName); - state = vm.getInfo().state; - } catch (LibvirtException e) { - s_logger.trace("Ignoring libvirt error.", e); - } - } - - KVMStoragePool primaryStorage = storagePoolMgr.getStoragePool(primaryStore.getPoolType(), primaryStore.getUuid()); - if (state == DomainInfo.DomainState.VIR_DOMAIN_RUNNING && !primaryStorage.isExternalSnapshot()) { - DomainSnapshot snap = vm.snapshotLookupByName(snapshotName); - snap.delete(0); - - /* - * libvirt on RHEL6 doesn't handle resume event emitted from - * qemu - */ - vm = this.resource.getDomain(conn, vmName); - state = vm.getInfo().state; - if (state == DomainInfo.DomainState.VIR_DOMAIN_PAUSED) { - vm.resume(); - } - } else { - if (primaryPool.getType() != StoragePoolType.RBD) { - Script command = new Script(_manageSnapshotPath, _cmdsTimeout, s_logger); - command.add("-d", snapshotDisk.getPath()); - command.add("-n", snapshotName); - String result = command.execute(); - if (result != null) { - s_logger.debug("Failed to backup snapshot: " + result); - return new CopyCmdAnswer("Failed to backup snapshot: " + result); - } - } - } - SnapshotObjectTO newSnapshot = new SnapshotObjectTO(); newSnapshot.setPath(snapshotRelPath + File.separator + snapshotName); return new CopyCmdAnswer(newSnapshot); @@ -782,6 +746,49 @@ public class KVMStorageProcessor implements StorageProcessor { s_logger.debug("Failed to backup snapshot: " + e.toString()); return new CopyCmdAnswer(e.toString()); } finally { + try { + /* Delete the snapshot on primary */ + DomainInfo.DomainState state = null; + Domain vm = null; + if (vmName != null) { + try { + vm = resource.getDomain(conn, vmName); + state = vm.getInfo().state; + } catch (LibvirtException e) { + s_logger.trace("Ignoring libvirt error.", e); + } + } + + KVMStoragePool primaryStorage = storagePoolMgr.getStoragePool(primaryStore.getPoolType(), + primaryStore.getUuid()); + if (state == DomainInfo.DomainState.VIR_DOMAIN_RUNNING && !primaryStorage.isExternalSnapshot()) { + DomainSnapshot snap = vm.snapshotLookupByName(snapshotName); + snap.delete(0); + + /* + * libvirt on RHEL6 doesn't handle resume event emitted from + * qemu + */ + vm = resource.getDomain(conn, vmName); + state = vm.getInfo().state; + if (state == DomainInfo.DomainState.VIR_DOMAIN_PAUSED) { + vm.resume(); + } + } else { + if (primaryPool.getType() != StoragePoolType.RBD) { + Script command = new Script(_manageSnapshotPath, _cmdsTimeout, s_logger); + command.add("-d", snapshotDisk.getPath()); + command.add("-n", snapshotName); + String result = command.execute(); + if (result != null) { + s_logger.debug("Failed to delete snapshot on primary: " + result); + // return new CopyCmdAnswer("Failed to backup snapshot: " + result); + } + } + } + } catch (Exception ex) { + s_logger.debug("Failed to delete snapshots on primary", ex); + } if (secondaryStoragePool != null) { secondaryStoragePool.delete(); } @@ -808,12 +815,12 @@ public class KVMStorageProcessor implements StorageProcessor { isoXml = iso.toString(); } - List disks = this.resource.getDisks(conn, vmName); + List disks = resource.getDisks(conn, vmName); String result = attachOrDetachDevice(conn, true, vmName, isoXml); if (result == null && !isAttach) { for (DiskDef disk : disks) { if (disk.getDeviceType() == DiskDef.deviceType.CDROM) { - this.resource.cleanupDisk(disk); + resource.cleanupDisk(disk); } } @@ -1027,7 +1034,7 @@ public class KVMStorageProcessor implements StorageProcessor { } } - protected static MessageFormat SnapshotXML = new MessageFormat(" " + " {0}" + " " + protected static final MessageFormat SnapshotXML = new MessageFormat(" " + " {0}" + " " + " {1}" + " " + " "); @Override @@ -1043,7 +1050,7 @@ public class KVMStorageProcessor implements StorageProcessor { Domain vm = null; if (vmName != null) { try { - vm = this.resource.getDomain(conn, vmName); + vm = resource.getDomain(conn, vmName); state = vm.getInfo().state; } catch (LibvirtException e) { s_logger.trace("Ignoring libvirt error.", e); @@ -1064,7 +1071,7 @@ public class KVMStorageProcessor implements StorageProcessor { * libvirt on RHEL6 doesn't handle resume event emitted from * qemu */ - vm = this.resource.getDomain(conn, vmName); + vm = resource.getDomain(conn, vmName); state = vm.getInfo().state; if (state == DomainInfo.DomainState.VIR_DOMAIN_PAUSED) { vm.resume(); @@ -1105,7 +1112,7 @@ public class KVMStorageProcessor implements StorageProcessor { } } else { /* VM is not running, create a snapshot by ourself */ - final Script command = new Script(_manageSnapshotPath, this._cmdsTimeout, s_logger); + final Script command = new Script(_manageSnapshotPath, _cmdsTimeout, s_logger); command.add("-c", disk.getPath()); command.add("-n", snapshotName); String result = command.execute(); diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/LibvirtStorageAdaptor.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/LibvirtStorageAdaptor.java index 82d0f8d41cf..bbd1c24ac99 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/LibvirtStorageAdaptor.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/LibvirtStorageAdaptor.java @@ -386,7 +386,7 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { LibvirtStoragePool libvirtPool = (LibvirtStoragePool)pool; try { - StorageVol vol = this.getVolume(libvirtPool.getPool(), volumeUuid); + StorageVol vol = getVolume(libvirtPool.getPool(), volumeUuid); KVMPhysicalDisk disk; LibvirtStorageVolumeDef voldef = getStorageVolumeDef(libvirtPool.getPool().getConnect(), vol); disk = new KVMPhysicalDisk(vol.getPath(), vol.getName(), pool); @@ -471,7 +471,7 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { String targetPath = pdef.getTargetPath(); if (targetPath != null && targetPath.equals(path)) { s_logger.debug("Storage pool utilizing path '" + path + "' already exists as pool " + poolname + - ", undefining so we can re-define with correct name " + name); + ", undefining so we can re-define with correct name " + name); if (p.isPersistent() == 1) { p.destroy(); p.undefine(); @@ -527,8 +527,8 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { String error = e.toString(); if (error.contains("Storage source conflict")) { throw new CloudRuntimeException("A pool matching this location already exists in libvirt, " + - " but has a different UUID/Name. Cannot create new pool without first " + " removing it. Check for inactive pools via 'virsh pool-list --all'. " + - error); + " but has a different UUID/Name. Cannot create new pool without first " + " removing it. Check for inactive pools via 'virsh pool-list --all'. " + + error); } else { throw new CloudRuntimeException(error); } @@ -556,7 +556,7 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { /* * Some storage pools, like RBD also have 'secret' information stored in libvirt * Destroy them if they exist - */ + */ try { s = conn.secretLookupByUUIDString(uuid); } catch (LibvirtException e) { @@ -580,7 +580,7 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { if (e.toString().contains("exit status 16")) { String targetPath = _mountPoint + File.separator + uuid; s_logger.error("deleteStoragePool removed pool from libvirt, but libvirt had trouble" + "unmounting the pool. Trying umount location " + targetPath + - "again in a few seconds"); + "again in a few seconds"); String result = Script.runSimpleBashScript("sleep 5 && umount " + targetPath); if (result == null) { s_logger.error("Succeeded in unmounting " + targetPath); @@ -624,7 +624,7 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { IoCTX io = r.ioCtxCreate(pool.getSourceDir()); Rbd rbd = new Rbd(io); - rbd.create(name, size, this.rbdFeatures, this.rbdOrder); + rbd.create(name, size, rbdFeatures, rbdOrder); r.ioCtxDestroy(io); } catch (RadosException e) { @@ -684,10 +684,8 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { @Override public boolean disconnectPhysicalDiskByPath(String localPath) { // we've only ever cleaned up ISOs that are NFS mounted - String poolUuid = null; - - if (localPath != null && localPath.startsWith(_mountPoint)) { + if (localPath != null && localPath.startsWith(_mountPoint) && localPath.endsWith(".iso")) { String[] token = localPath.split("/"); if (token.length > 3) { @@ -704,7 +702,7 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { try { Connect conn = LibvirtConnection.getConnection(); - StoragePool pool = conn.storagePoolLookupByUUIDString(poolUuid); + conn.storagePoolLookupByUUIDString(poolUuid); deleteStoragePool(poolUuid); @@ -755,7 +753,7 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { LibvirtStoragePool libvirtPool = (LibvirtStoragePool)pool; try { - StorageVol vol = this.getVolume(libvirtPool.getPool(), uuid); + StorageVol vol = getVolume(libvirtPool.getPool(), uuid); deleteVol(libvirtPool, vol); vol.free(); return true; @@ -786,7 +784,7 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { So for RBD we don't create the image, but let qemu-img do that for us. We then create a KVMPhysicalDisk object that we can return - */ + */ try { if (destPool.getType() != StoragePoolType.RBD) { disk = destPool.createPhysicalDisk(newUuid, format, template.getVirtualSize()); @@ -817,8 +815,8 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { QemuImg qemu = new QemuImg(timeout); QemuImgFile srcFile; QemuImgFile destFile = - new QemuImgFile(KVMPhysicalDisk.RBDStringBuilder(destPool.getSourceHost(), destPool.getSourcePort(), destPool.getAuthUserName(), - destPool.getAuthSecret(), disk.getPath())); + new QemuImgFile(KVMPhysicalDisk.RBDStringBuilder(destPool.getSourceHost(), destPool.getSourcePort(), destPool.getAuthUserName(), + destPool.getAuthSecret(), disk.getPath())); destFile.setFormat(format); if (srcPool.getType() != StoragePoolType.RBD) { @@ -852,9 +850,9 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { if (srcImage.isOldFormat()) { /* The source image is RBD format 1, we have to do a regular copy */ s_logger.debug("The source image " + srcPool.getSourceDir() + "/" + template.getName() + - " is RBD format 1. We have to perform a regular copy (" + template.getVirtualSize() + " bytes)"); + " is RBD format 1. We have to perform a regular copy (" + template.getVirtualSize() + " bytes)"); - rbd.create(disk.getName(), template.getVirtualSize(), this.rbdFeatures, this.rbdOrder); + rbd.create(disk.getName(), template.getVirtualSize(), rbdFeatures, rbdOrder); RbdImage destImage = rbd.open(disk.getName()); s_logger.debug("Starting to copy " + srcImage.getName() + " to " + destImage.getName() + " in Ceph pool " + srcPool.getSourceDir()); @@ -864,10 +862,10 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { rbd.close(destImage); } else { s_logger.debug("The source image " + srcPool.getSourceDir() + "/" + template.getName() + - " is RBD format 2. We will perform a RBD clone using snapshot " + this.rbdTemplateSnapName); + " is RBD format 2. We will perform a RBD clone using snapshot " + rbdTemplateSnapName); /* The source image is format 2, we can do a RBD snapshot+clone (layering) */ - rbd.clone(template.getName(), this.rbdTemplateSnapName, io, disk.getName(), this.rbdFeatures, this.rbdOrder); - s_logger.debug("Succesfully cloned " + template.getName() + "@" + this.rbdTemplateSnapName + " to " + disk.getName()); + rbd.clone(template.getName(), rbdTemplateSnapName, io, disk.getName(), rbdFeatures, rbdOrder); + s_logger.debug("Succesfully cloned " + template.getName() + "@" + rbdTemplateSnapName + " to " + disk.getName()); } rbd.close(srcImage); @@ -895,14 +893,14 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { Rbd dRbd = new Rbd(dIO); s_logger.debug("Creating " + disk.getName() + " on the destination cluster " + rDest.confGet("mon_host") + " in pool " + - destPool.getSourceDir()); - dRbd.create(disk.getName(), template.getVirtualSize(), this.rbdFeatures, this.rbdOrder); + destPool.getSourceDir()); + dRbd.create(disk.getName(), template.getVirtualSize(), rbdFeatures, rbdOrder); RbdImage srcImage = sRbd.open(template.getName()); RbdImage destImage = dRbd.open(disk.getName()); s_logger.debug("Copying " + template.getName() + " from Ceph cluster " + rSrc.confGet("mon_host") + " to " + disk.getName() + " on cluster " + - rDest.confGet("mon_host")); + rDest.confGet("mon_host")); sRbd.copy(srcImage, destImage); sRbd.close(srcImage); @@ -925,7 +923,7 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { } if (disk == null) { - throw new CloudRuntimeException("Failed to create " + disk.getPath() + " from template " + template.getName()); + throw new CloudRuntimeException("Failed to create disk from template " + template.getName()); } return disk; @@ -944,7 +942,7 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { try { String[] vols = virtPool.listVolumes(); for (String volName : vols) { - KVMPhysicalDisk disk = this.getPhysicalDisk(volName, pool); + KVMPhysicalDisk disk = getPhysicalDisk(volName, pool); disks.add(disk); } return disks; @@ -978,6 +976,7 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { String sourcePath = disk.getPath(); KVMPhysicalDisk newDisk; + s_logger.debug("copyPhysicalDisk: disk size:" + disk.getSize() + ", virtualsize:" + disk.getVirtualSize()+" format:"+disk.getFormat()); if (destPool.getType() != StoragePoolType.RBD) { if (disk.getFormat() == PhysicalDiskFormat.TAR) { newDisk = destPool.createPhysicalDisk(name, PhysicalDiskFormat.DIR, disk.getVirtualSize()); @@ -1015,7 +1014,8 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { try { Map info = qemu.info(srcFile); String backingFile = info.get(new String("backing_file")); - if (sourceFormat.equals(destFormat) && backingFile == null) { + // qcow2 templates can just be copied into place + if (sourceFormat.equals(destFormat) && backingFile == null && sourcePath.endsWith(".qcow2")) { String result = Script.runSimpleBashScript("cp -f " + sourcePath + " " + destPath, timeout); if (result != null) { throw new CloudRuntimeException("Failed to create disk: " + result); @@ -1036,11 +1036,11 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { } } else if ((srcPool.getType() != StoragePoolType.RBD) && (destPool.getType() == StoragePoolType.RBD)) { /** - * Qemu doesn't support writing to RBD format 2 directly, so we have to write to a temporary RAW file first - * which we then convert to RBD format 2. - * - * A HUGE performance gain can be achieved here if QCOW2 -> RBD format 2 can be done in one step - */ + * Qemu doesn't support writing to RBD format 2 directly, so we have to write to a temporary RAW file first + * which we then convert to RBD format 2. + * + * A HUGE performance gain can be achieved here if QCOW2 -> RBD format 2 can be done in one step + */ s_logger.debug("The source image is not RBD, but the destination is. We will convert into RBD format 2"); String sourceFile; boolean useTmpFile = false; @@ -1069,7 +1069,7 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { Rbd rbd = new Rbd(io); s_logger.debug("Creating RBD image " + name + " in Ceph pool " + destPool.getSourceDir() + " with RBD format 2"); - rbd.create(name, disk.getVirtualSize(), this.rbdFeatures, this.rbdOrder); + rbd.create(name, disk.getVirtualSize(), rbdFeatures, rbdOrder); RbdImage image = rbd.open(name); @@ -1098,10 +1098,10 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { } /* Snapshot the image and protect that snapshot so we can clone (layer) from it */ - s_logger.debug("Creating RBD snapshot " + this.rbdTemplateSnapName + " on image " + name); - image.snapCreate(this.rbdTemplateSnapName); - s_logger.debug("Protecting RBD snapshot " + this.rbdTemplateSnapName + " on image " + name); - image.snapProtect(this.rbdTemplateSnapName); + s_logger.debug("Creating RBD snapshot " + rbdTemplateSnapName + " on image " + name); + image.snapCreate(rbdTemplateSnapName); + s_logger.debug("Protecting RBD snapshot " + rbdTemplateSnapName + " on image " + name); + image.snapProtect(rbdTemplateSnapName); rbd.close(image); r.ioCtxDestroy(io); @@ -1125,8 +1125,8 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { it doesn't benefit us. It's better to keep the current code in place which works */ srcFile = - new QemuImgFile(KVMPhysicalDisk.RBDStringBuilder(srcPool.getSourceHost(), srcPool.getSourcePort(), srcPool.getAuthUserName(), srcPool.getAuthSecret(), - sourcePath)); + new QemuImgFile(KVMPhysicalDisk.RBDStringBuilder(srcPool.getSourceHost(), srcPool.getSourcePort(), srcPool.getAuthUserName(), srcPool.getAuthSecret(), + sourcePath)); srcFile.setFormat(sourceFormat); destFile = new QemuImgFile(destPath); destFile.setFormat(destFormat); diff --git a/plugins/hypervisors/kvm/src/org/apache/cloudstack/utils/qemu/QemuImg.java b/plugins/hypervisors/kvm/src/org/apache/cloudstack/utils/qemu/QemuImg.java index 8c23f1ee802..a948ca1899f 100644 --- a/plugins/hypervisors/kvm/src/org/apache/cloudstack/utils/qemu/QemuImg.java +++ b/plugins/hypervisors/kvm/src/org/apache/cloudstack/utils/qemu/QemuImg.java @@ -184,8 +184,9 @@ public class QemuImg { public void convert(QemuImgFile srcFile, QemuImgFile destFile, Map options) throws QemuImgException { Script s = new Script(_qemuImgPath, timeout); s.add("convert"); - s.add("-f"); - s.add(srcFile.getFormat().toString()); + // autodetect source format. Sometime int he future we may teach KVMPhysicalDisk about more formats, then we can explicitly pass them if necessary + //s.add("-f"); + //s.add(srcFile.getFormat().toString()); s.add("-O"); s.add(destFile.getFormat().toString()); @@ -350,4 +351,4 @@ public class QemuImg { public void resize(QemuImgFile file, long size) throws QemuImgException { this.resize(file, size, false); } -} \ No newline at end of file +} diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java index 7e812dbea6d..c8af7f8b82b 100644 --- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java +++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java @@ -69,7 +69,7 @@ public class LibvirtComputingResourceTest { int id = _random.nextInt(65534); String name = "test-instance-1"; - int cpus = _random.nextInt(7) + 1; + int cpus = _random.nextInt(2) + 1; int speed = 1024; int minRam = 256 * 1024; int maxRam = 512 * 1024; @@ -124,6 +124,7 @@ public class LibvirtComputingResourceTest { //vmStr += "\n"; //vmStr += "" + (cpus * speed) + "\n"; //vmStr += "\n"; + vmStr += ""; vmStr += "restart\n"; vmStr += "destroy\n"; vmStr += "destroy\n"; @@ -131,6 +132,146 @@ public class LibvirtComputingResourceTest { assertEquals(vmStr, vm.toString()); } + /** + This test verifies that CPU topology is properly set for hex-core + */ + @Test + public void testCreateVMFromSpecWithTopology6() { + int id = _random.nextInt(65534); + String name = "test-instance-1"; + + int cpus = 12; + int minSpeed = 1024; + int maxSpeed = 2048; + int minRam = 256 * 1024; + int maxRam = 512 * 1024; + + String os = "Ubuntu"; + boolean haEnabled = false; + boolean limitCpuUse = false; + + String vncAddr = ""; + String vncPassword = "mySuperSecretPassword"; + + LibvirtComputingResource lcr = new LibvirtComputingResource(); + VirtualMachineTO to = new VirtualMachineTO(id, name, VirtualMachine.Type.User, cpus, minSpeed, maxSpeed, minRam, maxRam, BootloaderType.HVM, os, false, false, vncPassword); + to.setVncAddr(vncAddr); + to.setUuid("b0f0a72d-7efb-3cad-a8ff-70ebf30b3af9"); + + LibvirtVMDef vm = lcr.createVMFromSpec(to); + vm.setHvsType(_hyperVisorType); + + String vmStr = "\n"; + vmStr += "" + name + "\n"; + vmStr += "b0f0a72d-7efb-3cad-a8ff-70ebf30b3af9\n"; + vmStr += "" + os + "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "" + maxRam / 1024 + "\n"; + vmStr += "" + minRam / 1024 + "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "" + cpus + "\n"; + vmStr += "\n"; + vmStr += "hvm\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += ""; + vmStr += "restart\n"; + vmStr += "destroy\n"; + vmStr += "destroy\n"; + vmStr += "\n"; + + assertEquals(vmStr, vm.toString()); + } + + /** + This test verifies that CPU topology is properly set for quad-core + */ + @Test + public void testCreateVMFromSpecWithTopology4() { + int id = _random.nextInt(65534); + String name = "test-instance-1"; + + int cpus = 8; + int minSpeed = 1024; + int maxSpeed = 2048; + int minRam = 256 * 1024; + int maxRam = 512 * 1024; + + String os = "Ubuntu"; + boolean haEnabled = false; + boolean limitCpuUse = false; + + String vncAddr = ""; + String vncPassword = "mySuperSecretPassword"; + + LibvirtComputingResource lcr = new LibvirtComputingResource(); + VirtualMachineTO to = new VirtualMachineTO(id, name, VirtualMachine.Type.User, cpus, minSpeed, maxSpeed, minRam, maxRam, BootloaderType.HVM, os, false, false, vncPassword); + to.setVncAddr(vncAddr); + to.setUuid("b0f0a72d-7efb-3cad-a8ff-70ebf30b3af9"); + + LibvirtVMDef vm = lcr.createVMFromSpec(to); + vm.setHvsType(_hyperVisorType); + + String vmStr = "\n"; + vmStr += "" + name + "\n"; + vmStr += "b0f0a72d-7efb-3cad-a8ff-70ebf30b3af9\n"; + vmStr += "" + os + "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "" + maxRam / 1024 + "\n"; + vmStr += "" + minRam / 1024 + "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "" + cpus + "\n"; + vmStr += "\n"; + vmStr += "hvm\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += "\n"; + vmStr += ""; + vmStr += "restart\n"; + vmStr += "destroy\n"; + vmStr += "destroy\n"; + vmStr += "\n"; + + assertEquals(vmStr, vm.toString()); + } + /** This test tests if the Agent can handle a vmSpec coming from a >4.1 management server. @@ -143,7 +284,7 @@ public class LibvirtComputingResourceTest { int id = _random.nextInt(65534); String name = "test-instance-1"; - int cpus = _random.nextInt(7) + 1; + int cpus = _random.nextInt(2) + 1; int minSpeed = 1024; int maxSpeed = 2048; int minRam = 256 * 1024; @@ -200,6 +341,7 @@ public class LibvirtComputingResourceTest { //vmStr += "\n"; //vmStr += "" + (cpus * minSpeed) + "\n"; //vmStr += "\n"; + vmStr += ""; vmStr += "restart\n"; vmStr += "destroy\n"; vmStr += "destroy\n"; @@ -250,14 +392,14 @@ public class LibvirtComputingResourceTest { Mockito.when(domain.interfaceStats(Matchers.anyString())).thenAnswer(new Answer() { // increment with less than a KB, so this should be less than 1 KB final static int increment = 1000; - int rx_bytes = 1000; - int tx_bytes = 1000; + int rxBytes = 1000; + int txBytes = 1000; @Override public DomainInterfaceStats answer(InvocationOnMock invocation) throws Throwable { DomainInterfaceStats domainInterfaceStats = new DomainInterfaceStats(); - domainInterfaceStats.rx_bytes = (this.rx_bytes += increment); - domainInterfaceStats.tx_bytes = (this.tx_bytes += increment); + domainInterfaceStats.rx_bytes = (rxBytes += increment); + domainInterfaceStats.tx_bytes = (txBytes += increment); return domainInterfaceStats; } @@ -268,15 +410,15 @@ public class LibvirtComputingResourceTest { // a little less than a KB final static int increment = 1000; - int rd_bytes = 0; - int wr_bytes = 1024; + int rdBytes = 0; + int wrBytes = 1024; @Override public DomainBlockStats answer(InvocationOnMock invocation) throws Throwable { DomainBlockStats domainBlockStats = new DomainBlockStats(); - domainBlockStats.rd_bytes = (rd_bytes += increment); - domainBlockStats.wr_bytes = (wr_bytes += increment); + domainBlockStats.rd_bytes = (rdBytes += increment); + domainBlockStats.wr_bytes = (wrBytes += increment); return domainBlockStats; } diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtSecretDefTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtSecretDefTest.java new file mode 100644 index 00000000000..54036b3c848 --- /dev/null +++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtSecretDefTest.java @@ -0,0 +1,55 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package com.cloud.hypervisor.kvm.resource; + +import junit.framework.TestCase; +import com.cloud.hypervisor.kvm.resource.LibvirtSecretDef.usage; + +public class LibvirtSecretDefTest extends TestCase { + + public void testVolumeSecretDef() { + String uuid = "db66f42b-a79e-4666-9910-9dfc8a024427"; + String name = "myEncryptedQCOW2"; + usage use = usage.VOLUME; + + LibvirtSecretDef def = new LibvirtSecretDef(use, uuid); + def.setVolumeVolume(name); + + String expectedXml = "\n" + uuid + "\n" + + "\n" + name + "\n\n\n"; + + assertEquals(expectedXml, def.toString()); + } + + public void testCephSecretDef() { + String uuid = "a9febe83-ac5c-467a-bf19-eb75325ec23c"; + String name = "admin"; + usage use = usage.CEPH; + + LibvirtSecretDef def = new LibvirtSecretDef(use, uuid); + def.setCephName(name); + + String expectedXml = "\n" + uuid + "\n" + + "\n" + name + "\n\n\n"; + + assertEquals(expectedXml, def.toString()); + } + +} \ No newline at end of file diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtStoragePoolDefTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtStoragePoolDefTest.java new file mode 100644 index 00000000000..687432b3d71 --- /dev/null +++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtStoragePoolDefTest.java @@ -0,0 +1,84 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package com.cloud.hypervisor.kvm.resource; + +import junit.framework.TestCase; +import com.cloud.hypervisor.kvm.resource.LibvirtStoragePoolDef.poolType; +import com.cloud.hypervisor.kvm.resource.LibvirtStoragePoolDef.authType; + +public class LibvirtStoragePoolDefTest extends TestCase { + + public void testSetGetStoragePool() { + poolType type = poolType.NETFS; + String name = "myNFSPool"; + String uuid = "d7846cb0-f610-4a5b-8d38-ee6e8d63f37b"; + String host = "127.0.0.1"; + String dir = "/export/primary"; + String targetPath = "/mnt/" + uuid; + int port = 1234; + + LibvirtStoragePoolDef pool = new LibvirtStoragePoolDef(type, name, uuid, host, port, dir, targetPath); + + assertEquals(type, pool.getPoolType()); + assertEquals(name, pool.getPoolName()); + assertEquals(host, pool.getSourceHost()); + assertEquals(port, pool.getSourcePort()); + assertEquals(dir, pool.getSourceDir()); + assertEquals(targetPath, pool.getTargetPath()); + } + + public void testNfsStoragePool() { + poolType type = poolType.NETFS; + String name = "myNFSPool"; + String uuid = "89a605bc-d470-4637-b3df-27388be452f5"; + String host = "127.0.0.1"; + String dir = "/export/primary"; + String targetPath = "/mnt/" + uuid; + + LibvirtStoragePoolDef pool = new LibvirtStoragePoolDef(type, name, uuid, host, dir, targetPath); + + String expectedXml = "\n" + name + "\n" + uuid + "\n" + + "\n\n\n\n\n" + + "" + targetPath + "\n\n\n"; + + assertEquals(expectedXml, pool.toString()); + } + + public void testRbdStoragePool() { + poolType type = poolType.RBD; + String name = "myRBDPool"; + String uuid = "921ef8b2-955a-4c18-a697-66bb9adf6131"; + String host = "127.0.0.1"; + String dir = "cloudstackrbdpool"; + String authUsername = "admin"; + String secretUuid = "08c2fa02-50d0-4a78-8903-b742d3f34934"; + authType auth = authType.CEPH; + int port = 6789; + + LibvirtStoragePoolDef pool = new LibvirtStoragePoolDef(type, name, uuid, host, port, dir, authUsername, auth, secretUuid); + + String expectedXml = "\n" + name + "\n" + uuid + "\n" + + "\n\n" + dir + "\n" + + "\n\n" + + "\n\n\n"; + + assertEquals(expectedXml, pool.toString()); + } +} \ No newline at end of file diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtVMDefTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtVMDefTest.java index 90b8c3b7a2f..aa7570c3638 100644 --- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtVMDefTest.java +++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtVMDefTest.java @@ -20,6 +20,7 @@ package com.cloud.hypervisor.kvm.resource; import junit.framework.TestCase; +import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef; public class LibvirtVMDefTest extends TestCase { @@ -65,4 +66,28 @@ public class LibvirtVMDefTest extends TestCase { } + public void testDiskDef() { + String filePath = "/var/lib/libvirt/images/disk.qcow2"; + String diskLabel = "vda"; + + DiskDef disk = new DiskDef(); + DiskDef.diskBus bus = DiskDef.diskBus.VIRTIO; + DiskDef.diskFmtType type = DiskDef.diskFmtType.QCOW2; + DiskDef.diskCacheMode cacheMode = DiskDef.diskCacheMode.WRITEBACK; + + disk.defFileBasedDisk(filePath, diskLabel, bus, type); + disk.setCacheMode(cacheMode); + + assertEquals(filePath, disk.getDiskPath()); + assertEquals(diskLabel, disk.getDiskLabel()); + assertEquals(bus, disk.getBusType()); + assertEquals(DiskDef.deviceType.DISK, disk.getDeviceType()); + + String xmlDef = disk.toString(); + String expectedXml = "\n\n" + + "\n\n\n"; + + assertEquals(xmlDef, expectedXml); + } + } diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtVifDriverTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtVifDriverTest.java index 0b7fb914853..5d135364688 100644 --- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtVifDriverTest.java +++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtVifDriverTest.java @@ -42,9 +42,9 @@ public class LibvirtVifDriverTest { private Map assertions; - final String LIBVIRT_VIF_DRIVER = "libvirt.vif.driver"; - final String FAKE_VIF_DRIVER_CLASS_NAME = "com.cloud.hypervisor.kvm.resource.FakeVifDriver"; - final String NONEXISTENT_VIF_DRIVER_CLASS_NAME = "com.cloud.hypervisor.kvm.resource.NonExistentVifDriver"; + final String LibVirtVifDriver = "libvirt.vif.driver"; + final String FakeVifDriverClassName = "com.cloud.hypervisor.kvm.resource.FakeVifDriver"; + final String NonExistentVifDriverClassName = "com.cloud.hypervisor.kvm.resource.NonExistentVifDriver"; private VifDriver fakeVifDriver, bridgeVifDriver, ovsVifDriver; @@ -64,7 +64,7 @@ public class LibvirtVifDriverTest { doReturn(bridgeVifDriver).when(res).getVifDriverClass(eq(LibvirtComputingResource.DEFAULT_BRIDGE_VIF_DRIVER_CLASS_NAME), anyMap()); doReturn(ovsVifDriver).when(res).getVifDriverClass(eq(LibvirtComputingResource.DEFAULT_OVS_VIF_DRIVER_CLASS_NAME), anyMap()); - doReturn(fakeVifDriver).when(res).getVifDriverClass(eq(FAKE_VIF_DRIVER_CLASS_NAME), anyMap()); + doReturn(fakeVifDriver).when(res).getVifDriverClass(eq(FakeVifDriverClassName), anyMap()); } catch (final ConfigurationException ex) { fail("Unexpected ConfigurationException while configuring VIF drivers: " + ex.getMessage()); @@ -120,13 +120,13 @@ public class LibvirtVifDriverTest { Map params = new HashMap(); // Switch res' bridge type for test purposes - params.put(LIBVIRT_VIF_DRIVER, LibvirtComputingResource.DEFAULT_BRIDGE_VIF_DRIVER_CLASS_NAME); + params.put(LibVirtVifDriver, LibvirtComputingResource.DEFAULT_BRIDGE_VIF_DRIVER_CLASS_NAME); res._bridgeType = BridgeType.NATIVE; configure(params); checkAllSame(bridgeVifDriver); params.clear(); - params.put(LIBVIRT_VIF_DRIVER, LibvirtComputingResource.DEFAULT_OVS_VIF_DRIVER_CLASS_NAME); + params.put(LibVirtVifDriver, LibvirtComputingResource.DEFAULT_OVS_VIF_DRIVER_CLASS_NAME); res._bridgeType = BridgeType.OPENVSWITCH; configure(params); checkAllSame(ovsVifDriver); @@ -139,13 +139,13 @@ public class LibvirtVifDriverTest { Map params = new HashMap(); // Switch res' bridge type for test purposes - params.put(LIBVIRT_VIF_DRIVER, LibvirtComputingResource.DEFAULT_OVS_VIF_DRIVER_CLASS_NAME); + params.put(LibVirtVifDriver, LibvirtComputingResource.DEFAULT_OVS_VIF_DRIVER_CLASS_NAME); res._bridgeType = BridgeType.NATIVE; configure(params); checkAllSame(ovsVifDriver); params.clear(); - params.put(LIBVIRT_VIF_DRIVER, LibvirtComputingResource.DEFAULT_BRIDGE_VIF_DRIVER_CLASS_NAME); + params.put(LibVirtVifDriver, LibvirtComputingResource.DEFAULT_BRIDGE_VIF_DRIVER_CLASS_NAME); res._bridgeType = BridgeType.OPENVSWITCH; configure(params); checkAllSame(bridgeVifDriver); @@ -155,8 +155,8 @@ public class LibvirtVifDriverTest { public void testOverrideSomeTrafficTypes() throws ConfigurationException { Map params = new HashMap(); - params.put(LIBVIRT_VIF_DRIVER + "." + "Public", FAKE_VIF_DRIVER_CLASS_NAME); - params.put(LIBVIRT_VIF_DRIVER + "." + "Guest", LibvirtComputingResource.DEFAULT_OVS_VIF_DRIVER_CLASS_NAME); + params.put(LibVirtVifDriver + "." + "Public", FakeVifDriverClassName); + params.put(LibVirtVifDriver + "." + "Guest", LibvirtComputingResource.DEFAULT_OVS_VIF_DRIVER_CLASS_NAME); res._bridgeType = BridgeType.NATIVE; configure(params); @@ -174,7 +174,7 @@ public class LibvirtVifDriverTest { @Test public void testBadTrafficType() throws ConfigurationException { Map params = new HashMap(); - params.put(LIBVIRT_VIF_DRIVER + "." + "NonExistentTrafficType", FAKE_VIF_DRIVER_CLASS_NAME); + params.put(LibVirtVifDriver + "." + "NonExistentTrafficType", FakeVifDriverClassName); res._bridgeType = BridgeType.NATIVE; configure(params); @@ -189,7 +189,7 @@ public class LibvirtVifDriverTest { @Test public void testEmptyTrafficType() throws ConfigurationException { Map params = new HashMap(); - params.put(LIBVIRT_VIF_DRIVER + ".", FAKE_VIF_DRIVER_CLASS_NAME); + params.put(LibVirtVifDriver + ".", FakeVifDriverClassName); res._bridgeType = BridgeType.NATIVE; configure(params); @@ -204,7 +204,7 @@ public class LibvirtVifDriverTest { @Test(expected = ConfigurationException.class) public void testBadVifDriverClassName() throws ConfigurationException { Map params = new HashMap(); - params.put(LIBVIRT_VIF_DRIVER + "." + "Public", NONEXISTENT_VIF_DRIVER_CLASS_NAME); + params.put(LibVirtVifDriver + "." + "Public", NonExistentVifDriverClassName); res._bridgeType = BridgeType.NATIVE; configure(params); } diff --git a/plugins/hypervisors/ovm/src/com/cloud/ovm/hypervisor/OvmHelper.java b/plugins/hypervisors/ovm/src/com/cloud/ovm/hypervisor/OvmHelper.java index 225ab0dc8ac..2eb07360fec 100755 --- a/plugins/hypervisors/ovm/src/com/cloud/ovm/hypervisor/OvmHelper.java +++ b/plugins/hypervisors/ovm/src/com/cloud/ovm/hypervisor/OvmHelper.java @@ -19,47 +19,47 @@ package com.cloud.ovm.hypervisor; import java.util.HashMap; public class OvmHelper { - private static final HashMap _ovmMap = new HashMap(); + private static final HashMap s_ovmMap = new HashMap(); public static final String ORACLE_LINUX = "Oracle Linux"; public static final String ORACLE_SOLARIS = "Oracle Solaris"; public static final String WINDOWS = "Windows"; static { - _ovmMap.put("Oracle Enterprise Linux 6.0 (32-bit)", ORACLE_LINUX); - _ovmMap.put("Oracle Enterprise Linux 6.0 (64-bit)", ORACLE_LINUX); - _ovmMap.put("Oracle Enterprise Linux 5.0 (32-bit)", ORACLE_LINUX); - _ovmMap.put("Oracle Enterprise Linux 5.0 (64-bit)", ORACLE_LINUX); - _ovmMap.put("Oracle Enterprise Linux 5.1 (32-bit)", ORACLE_LINUX); - _ovmMap.put("Oracle Enterprise Linux 5.1 (64-bit)", ORACLE_LINUX); - _ovmMap.put("Oracle Enterprise Linux 5.2 (32-bit)", ORACLE_LINUX); - _ovmMap.put("Oracle Enterprise Linux 5.2 (64-bit)", ORACLE_LINUX); - _ovmMap.put("Oracle Enterprise Linux 5.3 (32-bit)", ORACLE_LINUX); - _ovmMap.put("Oracle Enterprise Linux 5.3 (64-bit)", ORACLE_LINUX); - _ovmMap.put("Oracle Enterprise Linux 5.4 (32-bit)", ORACLE_LINUX); - _ovmMap.put("Oracle Enterprise Linux 5.4 (64-bit)", ORACLE_LINUX); - _ovmMap.put("Oracle Enterprise Linux 5.5 (32-bit)", ORACLE_LINUX); - _ovmMap.put("Oracle Enterprise Linux 5.5 (64-bit)", ORACLE_LINUX); - _ovmMap.put("Windows 7 (32-bit)", WINDOWS); - _ovmMap.put("Windows 7 (64-bit)", WINDOWS); - _ovmMap.put("Windows Server 2003 (32-bit)", WINDOWS); - _ovmMap.put("Windows Server 2003 (64-bit)", WINDOWS); - _ovmMap.put("Windows Server 2008 (32-bit)", WINDOWS); - _ovmMap.put("Windows Server 2008 (64-bit)", WINDOWS); - _ovmMap.put("Windows Server 2008 R2 (64-bit)", WINDOWS); - _ovmMap.put("Windows 2000 SP4 (32-bit)", WINDOWS); - _ovmMap.put("Windows Vista (32-bit)", WINDOWS); - _ovmMap.put("Windows XP SP2 (32-bit)", WINDOWS); - _ovmMap.put("Windows XP SP3 (32-bit)", WINDOWS); - _ovmMap.put("Sun Solaris 10(32-bit)", ORACLE_SOLARIS); - _ovmMap.put("Sun Solaris 10(64-bit)", ORACLE_SOLARIS); - _ovmMap.put("Sun Solaris 9(Experimental)", ORACLE_SOLARIS); - _ovmMap.put("Sun Solaris 8(Experimental)", ORACLE_SOLARIS); - _ovmMap.put("Sun Solaris 11 (32-bit)", ORACLE_SOLARIS); - _ovmMap.put("Sun Solaris 11 (64-bit)", ORACLE_SOLARIS); + s_ovmMap.put("Oracle Enterprise Linux 6.0 (32-bit)", ORACLE_LINUX); + s_ovmMap.put("Oracle Enterprise Linux 6.0 (64-bit)", ORACLE_LINUX); + s_ovmMap.put("Oracle Enterprise Linux 5.0 (32-bit)", ORACLE_LINUX); + s_ovmMap.put("Oracle Enterprise Linux 5.0 (64-bit)", ORACLE_LINUX); + s_ovmMap.put("Oracle Enterprise Linux 5.1 (32-bit)", ORACLE_LINUX); + s_ovmMap.put("Oracle Enterprise Linux 5.1 (64-bit)", ORACLE_LINUX); + s_ovmMap.put("Oracle Enterprise Linux 5.2 (32-bit)", ORACLE_LINUX); + s_ovmMap.put("Oracle Enterprise Linux 5.2 (64-bit)", ORACLE_LINUX); + s_ovmMap.put("Oracle Enterprise Linux 5.3 (32-bit)", ORACLE_LINUX); + s_ovmMap.put("Oracle Enterprise Linux 5.3 (64-bit)", ORACLE_LINUX); + s_ovmMap.put("Oracle Enterprise Linux 5.4 (32-bit)", ORACLE_LINUX); + s_ovmMap.put("Oracle Enterprise Linux 5.4 (64-bit)", ORACLE_LINUX); + s_ovmMap.put("Oracle Enterprise Linux 5.5 (32-bit)", ORACLE_LINUX); + s_ovmMap.put("Oracle Enterprise Linux 5.5 (64-bit)", ORACLE_LINUX); + s_ovmMap.put("Windows 7 (32-bit)", WINDOWS); + s_ovmMap.put("Windows 7 (64-bit)", WINDOWS); + s_ovmMap.put("Windows Server 2003 (32-bit)", WINDOWS); + s_ovmMap.put("Windows Server 2003 (64-bit)", WINDOWS); + s_ovmMap.put("Windows Server 2008 (32-bit)", WINDOWS); + s_ovmMap.put("Windows Server 2008 (64-bit)", WINDOWS); + s_ovmMap.put("Windows Server 2008 R2 (64-bit)", WINDOWS); + s_ovmMap.put("Windows 2000 SP4 (32-bit)", WINDOWS); + s_ovmMap.put("Windows Vista (32-bit)", WINDOWS); + s_ovmMap.put("Windows XP SP2 (32-bit)", WINDOWS); + s_ovmMap.put("Windows XP SP3 (32-bit)", WINDOWS); + s_ovmMap.put("Sun Solaris 10(32-bit)", ORACLE_SOLARIS); + s_ovmMap.put("Sun Solaris 10(64-bit)", ORACLE_SOLARIS); + s_ovmMap.put("Sun Solaris 9(Experimental)", ORACLE_SOLARIS); + s_ovmMap.put("Sun Solaris 8(Experimental)", ORACLE_SOLARIS); + s_ovmMap.put("Sun Solaris 11 (32-bit)", ORACLE_SOLARIS); + s_ovmMap.put("Sun Solaris 11 (64-bit)", ORACLE_SOLARIS); } public static String getOvmGuestType(String stdType) { - return _ovmMap.get(stdType); + return s_ovmMap.get(stdType); } } diff --git a/plugins/hypervisors/ovm/src/com/cloud/ovm/hypervisor/OvmResourceBase.java b/plugins/hypervisors/ovm/src/com/cloud/ovm/hypervisor/OvmResourceBase.java index ed25fa88526..238ac518a92 100755 --- a/plugins/hypervisors/ovm/src/com/cloud/ovm/hypervisor/OvmResourceBase.java +++ b/plugins/hypervisors/ovm/src/com/cloud/ovm/hypervisor/OvmResourceBase.java @@ -153,30 +153,30 @@ public class OvmResourceBase implements ServerResource, HypervisorResource { String _publicNetworkName; String _guestNetworkName; boolean _canBridgeFirewall; - static boolean _isHeartBeat = false; + static boolean s_isHeartBeat = false; List _bridges = null; private final Map> _vmNetworkStats = new ConcurrentHashMap>(); - private static String _ovsAgentPath = "/opt/ovs-agent-latest"; + private static String s_ovsAgentPath = "/opt/ovs-agent-latest"; // TODO vmsync { - static HashMap _stateMaps; + static HashMap s_stateMaps; protected HashMap _vms = new HashMap(50); static { - _stateMaps = new HashMap(); - _stateMaps.put("RUNNING", State.Running); - _stateMaps.put("DOWN", State.Stopped); - _stateMaps.put("ERROR", State.Error); - _stateMaps.put("SUSPEND", State.Stopped); + s_stateMaps = new HashMap(); + s_stateMaps.put("RUNNING", State.Running); + s_stateMaps.put("DOWN", State.Stopped); + s_stateMaps.put("ERROR", State.Error); + s_stateMaps.put("SUSPEND", State.Stopped); } // TODO vmsync } - static HashMap _powerStateMaps; + static HashMap s_powerStateMaps; static { - _powerStateMaps = new HashMap(); - _powerStateMaps.put("RUNNING", PowerState.PowerOn); - _powerStateMaps.put("DOWN", PowerState.PowerOff); - _powerStateMaps.put("ERROR", PowerState.PowerUnknown); - _powerStateMaps.put("SUSPEND", PowerState.PowerOff); + s_powerStateMaps = new HashMap(); + s_powerStateMaps.put("RUNNING", PowerState.PowerOn); + s_powerStateMaps.put("DOWN", PowerState.PowerOff); + s_powerStateMaps.put("ERROR", PowerState.PowerUnknown); + s_powerStateMaps.put("SUSPEND", PowerState.PowerOff); } @Override @@ -259,7 +259,7 @@ public class OvmResourceBase implements ServerResource, HypervisorResource { } /* set to false so each time ModifyStoragePoolCommand will re-setup heartbeat*/ - _isHeartBeat = false; + s_isHeartBeat = false; /* try { @@ -369,9 +369,9 @@ public class OvmResourceBase implements ServerResource, HypervisorResource { } if (s_logger.isDebugEnabled()) { - s_logger.debug("Copying " + script.getPath() + " to " + _ovsAgentPath + " on " + _ip + " with permission 0644"); + s_logger.debug("Copying " + script.getPath() + " to " + s_ovsAgentPath + " on " + _ip + " with permission 0644"); } - scp.put(script.getPath(), _ovsAgentPath, "0644"); + scp.put(script.getPath(), s_ovsAgentPath, "0644"); } sshConnection = SSHCmdHelper.acquireAuthorizedConnection(_ip, _username, _password); @@ -409,7 +409,7 @@ public class OvmResourceBase implements ServerResource, HypervisorResource { try { OvmHost.ping(_conn); HashMap newStates = sync(); - return new PingRoutingCommand(getType(), id, newStates, this.getHostVmStateReport()); + return new PingRoutingCommand(getType(), id, newStates, getHostVmStateReport()); } catch (XmlRpcException e) { s_logger.debug("Check agent status failed", e); return null; @@ -454,13 +454,13 @@ public class OvmResourceBase implements ServerResource, HypervisorResource { private void setupHeartBeat(String poolUuid) { try { - if (!_isHeartBeat) { + if (!s_isHeartBeat) { OvmHost.setupHeartBeat(_conn, poolUuid, _ip); - _isHeartBeat = true; + s_isHeartBeat = true; } } catch (Exception e) { s_logger.debug("setup heart beat for " + _ip + " failed", e); - _isHeartBeat = false; + s_isHeartBeat = false; } } @@ -786,7 +786,7 @@ public class OvmResourceBase implements ServerResource, HypervisorResource { } private State toState(String vmName, String s) { - State state = _stateMaps.get(s); + State state = s_stateMaps.get(s); if (state == null) { s_logger.debug("Unkown state " + s + " for " + vmName); state = State.Unknown; @@ -795,7 +795,7 @@ public class OvmResourceBase implements ServerResource, HypervisorResource { } private PowerState toPowerState(String vmName, String s) { - PowerState state = _powerStateMaps.get(s); + PowerState state = s_powerStateMaps.get(s); if (state == null) { s_logger.debug("Unkown state " + s + " for " + vmName); state = PowerState.PowerUnknown; diff --git a/plugins/hypervisors/ovm/src/com/cloud/ovm/object/Coder.java b/plugins/hypervisors/ovm/src/com/cloud/ovm/object/Coder.java index 9af4016da4e..9bb42ac388e 100755 --- a/plugins/hypervisors/ovm/src/com/cloud/ovm/object/Coder.java +++ b/plugins/hypervisors/ovm/src/com/cloud/ovm/object/Coder.java @@ -32,10 +32,10 @@ import com.google.gson.JsonParseException; import com.google.gson.reflect.TypeToken; public class Coder { - private static Gson _gson; - private static Gson _mapGson; + private static Gson s_gson; + private static Gson s_mapGson; - public static Object[] EMPTY_PARAMS = new Object[0]; + public static Object[] s_emptyParams = new Object[0]; private static class MapDecoder implements JsonDeserializer> { @Override @@ -59,26 +59,26 @@ public class Coder { static { GsonBuilder _builder = new GsonBuilder(); _builder.registerTypeAdapter(Map.class, new MapDecoder()); - _mapGson = _builder.create(); - _gson = new Gson(); + s_mapGson = _builder.create(); + s_gson = new Gson(); } public static String toJson(Object obj) { - return _gson.toJson(obj); + return s_gson.toJson(obj); } public static T fromJson(String str, Class clz) { - return _gson.fromJson(str, clz); + return s_gson.fromJson(str, clz); } @SuppressWarnings("unchecked") public static Map mapFromJson(String str) { - return _mapGson.fromJson(str, Map.class); + return s_mapGson.fromJson(str, Map.class); } public static List listFromJson(String str) { Type listType = new TypeToken>() { }.getType(); - return _gson.fromJson(str, listType); + return s_gson.fromJson(str, listType); } } diff --git a/plugins/hypervisors/ovm/src/com/cloud/ovm/object/OvmBridge.java b/plugins/hypervisors/ovm/src/com/cloud/ovm/object/OvmBridge.java index 19bbd854872..6d2867ea46e 100755 --- a/plugins/hypervisors/ovm/src/com/cloud/ovm/object/OvmBridge.java +++ b/plugins/hypervisors/ovm/src/com/cloud/ovm/object/OvmBridge.java @@ -42,7 +42,7 @@ public class OvmBridge extends OvmObject { } public static List getAllBridges(Connection c) throws XmlRpcException { - String res = (String)c.call("OvmNetwork.getAllBridges", Coder.EMPTY_PARAMS); + String res = (String)c.call("OvmNetwork.getAllBridges", Coder.s_emptyParams); return Coder.listFromJson(res); } diff --git a/plugins/hypervisors/ovm/src/com/cloud/ovm/object/OvmHost.java b/plugins/hypervisors/ovm/src/com/cloud/ovm/object/OvmHost.java index 32eab09e43e..ad1b2f6f2b7 100755 --- a/plugins/hypervisors/ovm/src/com/cloud/ovm/object/OvmHost.java +++ b/plugins/hypervisors/ovm/src/com/cloud/ovm/object/OvmHost.java @@ -53,7 +53,7 @@ public class OvmHost extends OvmObject { } public static Details getDetails(Connection c) throws XmlRpcException { - String res = (String)c.call("OvmHost.getDetails", Coder.EMPTY_PARAMS); + String res = (String)c.call("OvmHost.getDetails", Coder.s_emptyParams); return Coder.fromJson(res, OvmHost.Details.class); } @@ -69,7 +69,7 @@ public class OvmHost extends OvmObject { } public static Map getAllVms(Connection c) throws XmlRpcException { - String res = (String)c.call("OvmHost.getAllVms", Coder.EMPTY_PARAMS); + String res = (String)c.call("OvmHost.getAllVms", Coder.s_emptyParams); return Coder.mapFromJson(res); } diff --git a/plugins/hypervisors/simulator/src/com/cloud/agent/manager/MockAgentManagerImpl.java b/plugins/hypervisors/simulator/src/com/cloud/agent/manager/MockAgentManagerImpl.java index 85f7e856f80..0eeef82c055 100644 --- a/plugins/hypervisors/simulator/src/com/cloud/agent/manager/MockAgentManagerImpl.java +++ b/plugins/hypervisors/simulator/src/com/cloud/agent/manager/MockAgentManagerImpl.java @@ -32,6 +32,8 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import com.cloud.user.AccountManager; +import org.apache.cloudstack.context.CallContext; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; @@ -87,6 +89,7 @@ public class MockAgentManagerImpl extends ManagerBase implements MockAgentManage MockStorageManager _storageMgr = null; @Inject ResourceManager _resourceMgr; + @Inject private AccountManager _accountMgr; SimulatorSecondaryDiscoverer discoverer; @Inject @@ -303,8 +306,10 @@ public class MockAgentManagerImpl extends ManagerBase implements MockAgentManage @Override @DB public void run() { + CallContext.register(_accountMgr.getSystemUser(), _accountMgr.getSystemAccount()); if (this.mode.equalsIgnoreCase("Stop")) { handleSystemVMStop(); + CallContext.unregister(); return; } @@ -359,10 +364,12 @@ public class MockAgentManagerImpl extends ManagerBase implements MockAgentManage _resourceMgr.discoverHosts(cmd); } catch (DiscoveryException e) { s_logger.debug("Failed to discover host: " + e.toString()); + CallContext.unregister(); return; } } catch (ConfigurationException e) { s_logger.debug("Failed to load secondary storage resource: " + e.toString()); + CallContext.unregister(); return; } } diff --git a/plugins/hypervisors/simulator/src/com/cloud/resource/AgentResourceBase.java b/plugins/hypervisors/simulator/src/com/cloud/resource/AgentResourceBase.java index dbfbba05d86..3cc91155b80 100644 --- a/plugins/hypervisors/simulator/src/com/cloud/resource/AgentResourceBase.java +++ b/plugins/hypervisors/simulator/src/com/cloud/resource/AgentResourceBase.java @@ -258,8 +258,8 @@ public class AgentResourceBase implements ServerResource { return _type; } - public void setType(Host.Type _type) { - this._type = _type; + public void setType(Host.Type type) { + this._type = type; } @Override diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/guru/VMwareGuru.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/guru/VMwareGuru.java index 081c6518ce6..d72787ca86e 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/guru/VMwareGuru.java +++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/guru/VMwareGuru.java @@ -27,8 +27,12 @@ import java.util.UUID; import javax.ejb.Local; import javax.inject.Inject; +import com.cloud.dc.dao.ClusterDao; +import com.cloud.vm.dao.VMInstanceDao; import org.apache.log4j.Logger; +import org.apache.cloudstack.framework.config.ConfigKey; +import org.apache.cloudstack.framework.config.Configurable; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.storage.command.CopyCommand; import org.apache.cloudstack.storage.to.VolumeObjectTO; @@ -93,7 +97,7 @@ import com.cloud.vm.VmDetailConstants; import com.cloud.vm.dao.NicDao; @Local(value = HypervisorGuru.class) -public class VMwareGuru extends HypervisorGuruBase implements HypervisorGuru { +public class VMwareGuru extends HypervisorGuruBase implements HypervisorGuru, Configurable { private static final Logger s_logger = Logger.getLogger(VMwareGuru.class); @Inject @@ -121,12 +125,24 @@ public class VMwareGuru extends HypervisorGuruBase implements HypervisorGuru { @Inject PhysicalNetworkTrafficTypeDao _physicalNetworkTrafficTypeDao; @Inject + VMInstanceDao _vmDao; + @Inject + ClusterDao _clusterDao; + @Inject ClusterManager _clusterMgr; protected VMwareGuru() { super(); } + static final ConfigKey VmwareReserveCpu = new ConfigKey(Boolean.class, "vmware.reserve.cpu", "Advanced", "false", + "Specify whether or not to reserve CPU when not overprovisioning, In case of cpu overprovisioning we will always reserve cpu.", true, ConfigKey.Scope.Cluster, + null); + + static final ConfigKey VmwareReserveMemory = new ConfigKey(Boolean.class, "vmware.reserve.cpu", "Advanced", "false", + "Specify whether or not to reserve memory when not overprovisioning, In case of memory overprovisioning we will always reserve memory.", true, + ConfigKey.Scope.Cluster, null); + @Override public HypervisorType getHypervisorType() { return HypervisorType.VMware; @@ -188,6 +204,9 @@ public class VMwareGuru extends HypervisorGuruBase implements HypervisorGuru { } } + long clusterId = this.getClusterId(vm.getId()); + details.put(Config.VmwareReserveCpu.key(), VmwareReserveCpu.valueIn(clusterId).toString()); + details.put(Config.VmwareReserveMem.key(), VmwareReserveMemory.valueIn(clusterId).toString()); to.setDetails(details); if (vm.getVirtualMachine() instanceof DomainRouterVO) { @@ -280,6 +299,20 @@ public class VMwareGuru extends HypervisorGuruBase implements HypervisorGuru { return to; } + private long getClusterId(long vmId) { + long clusterId; + Long hostId; + + hostId = _vmDao.findById(vmId).getHostId(); + if (hostId == null) { + // If VM is in stopped state then hostId would be undefined. Hence read last host's Id instead. + hostId = _vmDao.findById(vmId).getLastHostId(); + } + clusterId = _hostDao.findById(hostId).getClusterId(); + + return clusterId; + } + private NicTO[] sortNicsByDeviceId(NicTO[] nics) { List listForSort = new ArrayList(); @@ -436,4 +469,14 @@ public class VMwareGuru extends HypervisorGuruBase implements HypervisorGuru { } return commands; } + + @Override + public String getConfigComponentName() { + return VMwareGuru.class.getSimpleName(); + } + + @Override + public ConfigKey[] getConfigKeys() { + return new ConfigKey[] {VmwareReserveCpu, VmwareReserveMemory}; + } } diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/LegacyZoneVO.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/LegacyZoneVO.java index c31dab61712..93533bc6e61 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/LegacyZoneVO.java +++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/LegacyZoneVO.java @@ -27,13 +27,15 @@ import javax.persistence.Table; import com.cloud.utils.NumbersUtil; /** -* LegacyZoneVO contains id of CloudStack zone containing clusters from multiple VMware vCetners and/or VMware Datacenters. -*/ + * LegacyZoneVO contains id of CloudStack zone containing clusters from multiple VMware vCetners and/or VMware Datacenters. + */ @Entity @Table(name = "legacy_zones") public class LegacyZoneVO implements LegacyZone { + private static final long serialVersionUID = -3979866054555152793L; + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") @@ -60,7 +62,7 @@ public class LegacyZoneVO implements LegacyZone { @Override public boolean equals(Object obj) { if (obj instanceof LegacyZoneVO) { - return ((LegacyZoneVO)obj).getId() == this.getId(); + return ((LegacyZoneVO)obj).getId() == getId(); } else { return false; } @@ -70,7 +72,7 @@ public class LegacyZoneVO implements LegacyZone { } public LegacyZoneVO(long zoneId) { - this.id = zoneId; + id = zoneId; } public LegacyZoneVO(long id, long zoneId) { diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareCleanupMaid.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareCleanupMaid.java index b7746f945c0..d3b001ae9eb 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareCleanupMaid.java +++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareCleanupMaid.java @@ -16,7 +16,6 @@ // under the License. package com.cloud.hypervisor.vmware; -import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -98,16 +97,6 @@ public class VmwareCleanupMaid { return _checkPoint; } - private synchronized static void addLeftOverVM(VmwareCleanupMaid cleanupMaid) { - List l = s_leftoverDummyVMs.get(cleanupMaid.getVCenterServer()); - if (l == null) { - l = new ArrayList(); - s_leftoverDummyVMs.put(cleanupMaid.getVCenterServer(), l); - } - - l.add(cleanupMaid); - } - public synchronized static void gcLeftOverVMs(VmwareContext context) { List l = s_leftoverDummyVMs.get(context.getServerAddress()); VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareDatacenterVO.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareDatacenterVO.java index 881b44fb074..86597b2e5c9 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareDatacenterVO.java +++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareDatacenterVO.java @@ -37,6 +37,8 @@ import com.cloud.utils.db.Encrypt; @Table(name = "vmware_data_center") public class VmwareDatacenterVO implements VmwareDatacenter { + private static final long serialVersionUID = -9114941929893819232L; + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") @@ -105,11 +107,11 @@ public class VmwareDatacenterVO implements VmwareDatacenter { } public void setVmwareDatacenterName(String name) { - this.vmwareDatacenterName = name; + vmwareDatacenterName = name; } public void setVcenterHost(String vCenterHost) { - this.vcenterHost = vCenterHost; + vcenterHost = vCenterHost; } public void setUser(String user) { @@ -134,17 +136,17 @@ public class VmwareDatacenterVO implements VmwareDatacenter { @Override public boolean equals(Object obj) { if (obj instanceof VmwareDatacenterVO) { - return ((VmwareDatacenterVO)obj).getId() == this.getId(); + return ((VmwareDatacenterVO)obj).getId() == getId(); } else { return false; } } public VmwareDatacenterVO(String guid, String name, String vCenterHost, String user, String password) { - this.uuid = UUID.randomUUID().toString(); - this.vmwareDatacenterName = name; + uuid = UUID.randomUUID().toString(); + vmwareDatacenterName = name; this.guid = guid; - this.vcenterHost = vCenterHost; + vcenterHost = vCenterHost; this.user = user; this.password = password; } @@ -155,7 +157,7 @@ public class VmwareDatacenterVO implements VmwareDatacenter { } public VmwareDatacenterVO() { - this.uuid = UUID.randomUUID().toString(); + uuid = UUID.randomUUID().toString(); } } diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareDatacenterZoneMapVO.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareDatacenterZoneMapVO.java index ae9ccbf6f95..a8d88b40502 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareDatacenterZoneMapVO.java +++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareDatacenterZoneMapVO.java @@ -32,6 +32,8 @@ import javax.persistence.Table; @Table(name = "vmware_data_center_zone_map") public class VmwareDatacenterZoneMapVO implements VmwareDatacenterZoneMap { + private static final long serialVersionUID = -2155826205976479040L; + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java index ad3620dd03f..e6ecbc9adbc 100755 --- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java +++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java @@ -126,7 +126,7 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer @Override public Map> - find(long dcId, Long podId, Long clusterId, URI url, String username, String password, List hostTags) throws DiscoveryException { + find(long dcId, Long podId, Long clusterId, URI url, String username, String password, List hostTags) throws DiscoveryException { if (s_logger.isInfoEnabled()) s_logger.info("Discover host. dc: " + dcId + ", pod: " + podId + ", cluster: " + clusterId + ", uri host: " + url.getHost()); @@ -158,7 +158,7 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer if (usernameNotProvided || passwordNotProvided) { // Retrieve credentials associated with VMware DC s_logger.info("Username and/or Password not provided while adding cluster to cloudstack zone. " - + "Hence using both username & password provided while adding VMware DC to CloudStack zone."); + + "Hence using both username & password provided while adding VMware DC to CloudStack zone."); username = vmwareDc.getUser(); password = vmwareDc.getPassword(); clusterDetails.put("username", username); @@ -166,7 +166,7 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer _clusterDetailsDao.persist(clusterId, clusterDetails); } String updatedInventoryPath = validateCluster(url, vmwareDc); - if (url.getPath() != updatedInventoryPath) { + if (!url.getPath().equals(updatedInventoryPath)) { // If url from API doesn't specify DC then update url in database with DC associated with this zone. clusterDetails.put("url", url.getScheme() + "://" + url.getHost() + updatedInventoryPath); _clusterDetailsDao.persist(clusterId, clusterDetails); @@ -252,7 +252,7 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer // Process traffic label information provided at zone level and cluster level publicTrafficLabelObj = - getTrafficInfo(TrafficType.Public, publicTrafficLabel, defaultVirtualSwitchType, paramPublicVswitchType, paramPublicVswitchName, clusterId); + getTrafficInfo(TrafficType.Public, publicTrafficLabel, defaultVirtualSwitchType, paramPublicVswitchType, paramPublicVswitchName, clusterId); // Configuration Check: A physical network cannot be shared by different types of virtual switches. // @@ -272,7 +272,7 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer if (pNetworkListGuestTraffic.contains(pNetworkPublic)) { if (publicTrafficLabelObj.getVirtualSwitchType() != guestTrafficLabelObj.getVirtualSwitchType()) { String msg = - "Both public traffic and guest traffic is over same physical network " + pNetworkPublic + + "Both public traffic and guest traffic is over same physical network " + pNetworkPublic + ". And virtual switch type chosen for each traffic is different" + ". A physical network cannot be shared by different types of virtual switches."; s_logger.error(msg); @@ -295,7 +295,7 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer } Pair vsmInfo = new Pair(false, 0L); if (nexusDVS && (guestTrafficLabelObj.getVirtualSwitchType() == VirtualSwitchType.NexusDistributedVirtualSwitch) || - ((zoneType == NetworkType.Advanced) && (publicTrafficLabelObj.getVirtualSwitchType() == VirtualSwitchType.NexusDistributedVirtualSwitch))) { + ((zoneType == NetworkType.Advanced) && (publicTrafficLabelObj.getVirtualSwitchType() == VirtualSwitchType.NexusDistributedVirtualSwitch))) { // Expect Cisco Nexus VSM details only if following 2 condition met // 1) The global config parameter vmware.use.nexus.vswitch // 2) Atleast 1 traffic type uses Nexus distributed virtual switch as backend. @@ -335,14 +335,14 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer context.registerStockObject("vsmcredentials", vsmCredentials); } } - List morHosts = _vmwareMgr.addHostToPodCluster(context, dcId, podId, clusterId, URLDecoder.decode(url.getPath())); + List morHosts = _vmwareMgr.addHostToPodCluster(context, dcId, podId, clusterId, URLDecoder.decode(url.getPath(), "UTF-8")); if (morHosts == null) s_logger.info("Found 0 hosts."); if (privateTrafficLabel != null) context.uregisterStockObject("privateTrafficLabel"); if (morHosts == null) { - s_logger.error("Unable to find host or cluster based on url: " + URLDecoder.decode(url.getPath())); + s_logger.error("Unable to find host or cluster based on url: " + URLDecoder.decode(url.getPath(), "UTF-8")); return null; } @@ -350,7 +350,7 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer clusterDetails = _clusterDetailsDao.findDetails(clusterId); if (clusterDetails.get("url") != null) { URI uriFromCluster = new URI(UriUtils.encodeURIComponent(clusterDetails.get("url"))); - morCluster = context.getHostMorByPath(URLDecoder.decode(uriFromCluster.getPath())); + morCluster = context.getHostMorByPath(URLDecoder.decode(uriFromCluster.getPath(), "UTF-8")); if (morCluster == null || !morCluster.getType().equalsIgnoreCase("ClusterComputeResource")) { s_logger.warn("Cluster url does not point to a valid vSphere cluster, url: " + clusterDetails.get("url")); @@ -491,13 +491,13 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer if (!vCenterHost.equalsIgnoreCase(url.getHost())) { msg = - "This cluster " + clusterName + " belongs to vCenter " + url.getHost() + ". But this zone is associated with VMware DC from vCenter " + vCenterHost + + "This cluster " + clusterName + " belongs to vCenter " + url.getHost() + ". But this zone is associated with VMware DC from vCenter " + vCenterHost + ". Make sure the cluster being added belongs to vCenter " + vCenterHost + " and VMware DC " + vmwareDcNameFromDb; s_logger.error(msg); throw new DiscoveryException(msg); } else if (!vmwareDcNameFromDb.equalsIgnoreCase(vmwareDcNameFromApi)) { msg = - "This cluster " + clusterName + " belongs to VMware DC " + vmwareDcNameFromApi + " .But this zone is associated with VMware DC " + vmwareDcNameFromDb + + "This cluster " + clusterName + " belongs to VMware DC " + vmwareDcNameFromApi + " .But this zone is associated with VMware DC " + vmwareDcNameFromDb + ". Make sure the cluster being added belongs to VMware DC " + vmwareDcNameFromDb + " in vCenter " + vCenterHost; s_logger.error(msg); throw new DiscoveryException(msg); @@ -567,8 +567,8 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer if (tmplt == null) { id = _tmpltDao.getNextInSequence(Long.class, "id"); VMTemplateVO template = - VMTemplateVO.createPreHostIso(id, isoName, isoName, ImageFormat.ISO, true, true, TemplateType.PERHOST, null, null, true, 64, Account.ACCOUNT_ID_SYSTEM, - null, "VMware Tools Installer ISO", false, 1, false, HypervisorType.VMware); + VMTemplateVO.createPreHostIso(id, isoName, isoName, ImageFormat.ISO, true, true, TemplateType.PERHOST, null, null, true, 64, Account.ACCOUNT_ID_SYSTEM, + null, "VMware Tools Installer ISO", false, 1, false, HypervisorType.VMware); _tmpltDao.persist(template); } else { id = tmplt.getId(); @@ -627,7 +627,7 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer } private VmwareTrafficLabel getTrafficInfo(TrafficType trafficType, String zoneWideTrafficLabel, VirtualSwitchType defaultVirtualSwitchType, String vSwitchType, - String vSwitchName, Long clusterId) { + String vSwitchName, Long clusterId) { VmwareTrafficLabel trafficLabelObj = null; Map clusterDetails = null; try { @@ -664,7 +664,7 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer } private VmwareTrafficLabel getTrafficInfo(TrafficType trafficType, String zoneWideTrafficLabel, Map clusterDetails, - VirtualSwitchType defVirtualSwitchType) { + VirtualSwitchType defVirtualSwitchType) { VmwareTrafficLabel trafficLabelObj = null; try { trafficLabelObj = new VmwareTrafficLabel(zoneWideTrafficLabel, trafficType, defVirtualSwitchType); diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareHostService.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareHostService.java index a77679faa35..91a03ca6098 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareHostService.java +++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareHostService.java @@ -21,7 +21,6 @@ import java.util.List; import com.vmware.vim25.ManagedObjectReference; import com.cloud.agent.api.Command; -import com.cloud.hypervisor.vmware.mo.DatastoreMO; import com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost; import com.cloud.hypervisor.vmware.util.VmwareContext; @@ -34,11 +33,9 @@ public interface VmwareHostService { String getWorkerName(VmwareContext context, Command cmd, int workerSequence); - ManagedObjectReference getVmfsDatastore(VmwareHypervisorHost hyperHost, String datastoreName, String storageIpAddress, int storagePortNumber, String iqn, - String initiatorChapName, String initiatorChapSecret, String mutualChapName, String mutualChapSecret) throws Exception; - - void createVmdk(Command cmd, DatastoreMO dsMo, String volumeDatastorePath, Long volumeSize) throws Exception; - + ManagedObjectReference prepareManagedStorage(VmwareHypervisorHost hyperHost, String iScsiName, + String storageHost, int storagePort, String chapInitiatorUsername, String chapInitiatorSecret, + String chapTargetUsername, String chapTargetSecret, long size, Command cmd) throws Exception; void handleDatastoreAndVmdkDetach(String iqn, String storageHost, int storagePort) throws Exception; void removeManagedTargetsFromCluster(List managedIqns) throws Exception; diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareManagerImpl.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareManagerImpl.java index 066a395d6e8..482e8a626aa 100755 --- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareManagerImpl.java +++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareManagerImpl.java @@ -40,7 +40,6 @@ import org.apache.log4j.Logger; import com.google.gson.Gson; import com.vmware.vim25.AboutInfo; -import com.vmware.vim25.HostConnectSpec; import com.vmware.vim25.ManagedObjectReference; import org.apache.cloudstack.api.command.admin.zone.AddVmwareDcCmd; @@ -94,11 +93,9 @@ import com.cloud.hypervisor.vmware.mo.DiskControllerType; import com.cloud.hypervisor.vmware.mo.HostFirewallSystemMO; import com.cloud.hypervisor.vmware.mo.HostMO; import com.cloud.hypervisor.vmware.mo.HypervisorHostHelper; -import com.cloud.hypervisor.vmware.mo.TaskMO; import com.cloud.hypervisor.vmware.mo.VirtualEthernetCardType; import com.cloud.hypervisor.vmware.mo.VmwareHostType; import com.cloud.hypervisor.vmware.resource.VmwareContextFactory; -import com.cloud.hypervisor.vmware.util.VmwareClient; import com.cloud.hypervisor.vmware.util.VmwareContext; import com.cloud.hypervisor.vmware.util.VmwareHelper; import com.cloud.network.CiscoNexusVSMDeviceVO; @@ -400,7 +397,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw @Override public List addHostToPodCluster(VmwareContext serviceContext, long dcId, Long podId, Long clusterId, String hostInventoryPath) - throws Exception { + throws Exception { ManagedObjectReference mor = null; if (serviceContext != null) { mor = serviceContext.getHostMorByPath(hostInventoryPath); @@ -415,7 +412,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw List returnedHostList = new ArrayList(); if (mor.getType().equals("ComputeResource")) { - List hosts = (List)serviceContext.getVimClient().getDynamicProperty(mor, "host"); + List hosts = serviceContext.getVimClient().getDynamicProperty(mor, "host"); assert (hosts != null && hosts.size() > 0); // For ESX host, we need to enable host firewall to allow VNC access @@ -425,7 +422,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw returnedHostList.add(hosts.get(0)); return returnedHostList; } else if (mor.getType().equals("ClusterComputeResource")) { - List hosts = (List)serviceContext.getVimClient().getDynamicProperty(mor, "host"); + List hosts = serviceContext.getVimClient().getDynamicProperty(mor, "host"); assert (hosts != null); if (hosts.size() > 0) { @@ -462,45 +459,6 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw return null; } - @Deprecated - private ManagedObjectReference - addHostToVCenterCluster(VmwareContext serviceContext, ManagedObjectReference morCluster, String host, String userName, String password) throws Exception { - - VmwareClient vclient = serviceContext.getVimClient(); - ManagedObjectReference morHost = vclient.getDecendentMoRef(morCluster, "HostSystem", host); - if (morHost == null) { - HostConnectSpec hostSpec = new HostConnectSpec(); - hostSpec.setUserName(userName); - hostSpec.setPassword(password); - hostSpec.setHostName(host); - hostSpec.setForce(true); // forcely take over the host - - ManagedObjectReference morTask = serviceContext.getService().addHostTask(morCluster, hostSpec, true, null, null); - boolean taskResult = vclient.waitForTask(morTask); - if (!taskResult) { - s_logger.error("Unable to add host " + host + " to vSphere cluster due to " + TaskMO.getTaskFailureInfo(serviceContext, morTask)); - throw new CloudRuntimeException("Unable to add host " + host + " to vSphere cluster due to " + taskResult); - } - serviceContext.waitForTaskProgressDone(morTask); - - // init morHost after it has been created - morHost = vclient.getDecendentMoRef(morCluster, "HostSystem", host); - if (morHost == null) { - throw new CloudRuntimeException( - "Successfully added host into vSphere but unable to find it later on?!. Please make sure you are either using IP address or full qualified domain name for host"); - } - } - - // For ESX host, we need to enable host firewall to allow VNC access - HostMO hostMo = new HostMO(serviceContext, morHost); - HostFirewallSystemMO firewallMo = hostMo.getHostFirewallSystemMO(); - if (firewallMo != null) { - firewallMo.enableRuleset("vncServer"); - firewallMo.refreshFirewall(); - } - return morHost; - } - @Override public String getSecondaryStorageStoreUrl(long dcId) { @@ -548,8 +506,6 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw params.put("vm.instancename.flag", _instanceNameFlag); params.put("service.console.name", _serviceConsoleName); params.put("management.portgroup.name", _managemetPortGroupName); - params.put("vmware.reserve.cpu", _reserveCpu); - params.put("vmware.reserve.mem", _reserveMem); params.put("vmware.root.disk.controller", _rootDiskController); params.put("vmware.recycle.hung.wokervm", _recycleHungWorker); params.put("ports.per.dvportgroup", _portsPerDvPortGroup); @@ -581,7 +537,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw return false; } - long startTick = Long.parseLong(tokens[0]); + Long.parseLong(tokens[0]); long msid = Long.parseLong(tokens[1]); long runid = Long.parseLong(tokens[2]); @@ -605,7 +561,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw s_logger.info("Worker VM expired, seconds elapsed: " + (System.currentTimeMillis() - startTick) / 1000); return true; } - */ + */ return false; } @@ -633,7 +589,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw _configServer.updateKeyPairs(); s_logger.info("Copy System VM patch ISO file to secondary storage. source ISO: " + srcIso.getAbsolutePath() + ", destination: " + - destIso.getAbsolutePath()); + destIso.getAbsolutePath()); try { FileUtil.copyfile(srcIso, destIso); } catch (IOException e) { @@ -906,7 +862,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw } } - protected final int DEFAULT_DOMR_SSHPORT = 3922; + protected final static int DEFAULT_DOMR_SSHPORT = 3922; protected boolean shutdownRouterVM(DomainRouterVO router) { if (s_logger.isDebugEnabled()) { @@ -1042,7 +998,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw if (vCenterHost == null) { throw new InvalidParameterValueException("Missing or invalid parameter name. " - + "Please provide valid VMware vCenter server's IP address or fully qualified domain name."); + + "Please provide valid VMware vCenter server's IP address or fully qualified domain name."); } if (zoneId == null) { @@ -1062,11 +1018,11 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw VmwareDatacenterVO associatedVmwareDc = _vmwareDcDao.findById(associatedVmwareDcId); if (associatedVmwareDc.getVcenterHost().equalsIgnoreCase(vCenterHost) && associatedVmwareDc.getVmwareDatacenterName().equalsIgnoreCase(vmwareDcName)) { s_logger.info("Ignoring API call addVmwareDc, because VMware DC " + vCenterHost + "/" + vmwareDcName + - " is already associated with specified zone with id " + zoneId); + " is already associated with specified zone with id " + zoneId); return associatedVmwareDc; } else { throw new CloudRuntimeException("Zone " + zoneId + " is already associated with a VMware datacenter. " + - "Only 1 VMware DC can be associated with a zone."); + "Only 1 VMware DC can be associated with a zone."); } } // Zone validation to check if the zone already has resources. @@ -1160,8 +1116,6 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw String userName; String password; DatacenterMO dcMo = null; - Transaction txn; - final VmwareDatacenterZoneMapVO vmwareDcZoneMap = _vmwareDcZoneMapDao.findByZoneId(zoneId); // Check if zone is associated with VMware DC if (vmwareDcZoneMap == null) { diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManager.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManager.java index fe91cae47fc..f78f370da31 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManager.java +++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManager.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.hypervisor.vmware.manager; +import org.apache.cloudstack.storage.to.TemplateObjectTO; + import com.cloud.agent.api.Answer; import com.cloud.agent.api.BackupSnapshotCommand; import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand; @@ -50,4 +52,6 @@ public interface VmwareStorageManager { boolean execute(VmwareHostService hostService, CreateEntityDownloadURLCommand cmd); public void createOva(String path, String name); + + public String createOvaForTemplate(TemplateObjectTO template); } diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImpl.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImpl.java index 040a4cfd8f3..e37bf38a5af 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImpl.java +++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImpl.java @@ -80,7 +80,7 @@ import com.cloud.storage.JavaStorageLayer; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.StorageLayer; import com.cloud.storage.Volume; -import com.cloud.storage.template.VmdkProcessor; +import com.cloud.storage.template.OVAProcessor; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.StringUtils; @@ -144,6 +144,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { _timeout = NumbersUtil.parseInt(value, 1440) * 1000; } + @Override public String createOvaForTemplate(TemplateObjectTO template) { DataStoreTO storeTO = template.getDataStore(); if (!(storeTO instanceof NfsTO)) { @@ -197,9 +198,6 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { String installPath = volume.getPath(); int index = installPath.lastIndexOf(File.separator); String volumeUuid = installPath.substring(index + 1); - String details = null; - boolean success = false; - String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl); //The real volume path String volumePath = installPath + File.separator + volumeUuid + ".ova"; @@ -350,8 +348,8 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { } snapshotBackupUuid = - backupSnapshotToSecondaryStorage(vmMo, accountId, volumeId, cmd.getVolumePath(), snapshotUuid, secondaryStorageUrl, prevSnapshotUuid, prevBackupUuid, - hostService.getWorkerName(context, cmd, 1)); + backupSnapshotToSecondaryStorage(vmMo, accountId, volumeId, cmd.getVolumePath(), snapshotUuid, secondaryStorageUrl, prevSnapshotUuid, prevBackupUuid, + hostService.getWorkerName(context, cmd, 1)); success = (snapshotBackupUuid != null); if (success) { @@ -406,7 +404,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { if (vmMo == null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find the owner VM for CreatePrivateTemplateFromVolumeCommand on host " + hyperHost.getHyperHostName() + - ", try within datacenter"); + ", try within datacenter"); } vmMo = hyperHost.findVmOnPeerHyperHost(cmd.getVmName()); @@ -418,8 +416,8 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { } Ternary result = - createTemplateFromVolume(vmMo, accountId, templateId, cmd.getUniqueName(), secondaryStoragePoolURL, volumePath, - hostService.getWorkerName(context, cmd, 0)); + createTemplateFromVolume(vmMo, accountId, templateId, cmd.getUniqueName(), secondaryStoragePoolURL, volumePath, + hostService.getWorkerName(context, cmd, 0)); return new CreatePrivateTemplateAnswer(cmd, true, null, result.first(), result.third(), result.second(), cmd.getUniqueName(), ImageFormat.OVA); @@ -476,8 +474,8 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { Pair result; if (cmd.toSecondaryStorage()) { result = - copyVolumeToSecStorage(hostService, hyperHost, cmd, vmName, volumeId, cmd.getPool().getUuid(), volumePath, secondaryStorageURL, - hostService.getWorkerName(context, cmd, 0)); + copyVolumeToSecStorage(hostService, hyperHost, cmd, vmName, volumeId, cmd.getPool().getUuid(), volumePath, secondaryStorageURL, + hostService.getWorkerName(context, cmd, 0)); } else { StorageFilerTO poolTO = cmd.getPool(); @@ -548,10 +546,10 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { // templateName: name in secondary storage // templateUuid: will be used at hypervisor layer private void copyTemplateFromSecondaryToPrimary(VmwareHypervisorHost hyperHost, DatastoreMO datastoreMo, String secondaryStorageUrl, - String templatePathAtSecondaryStorage, String templateName, String templateUuid) throws Exception { + String templatePathAtSecondaryStorage, String templateName, String templateUuid) throws Exception { s_logger.info("Executing copyTemplateFromSecondaryToPrimary. secondaryStorage: " + secondaryStorageUrl + ", templatePathAtSecondaryStorage: " + - templatePathAtSecondaryStorage + ", templateName: " + templateName); + templatePathAtSecondaryStorage + ", templateName: " + templateName); String secondaryMountPoint = _mountService.getMountPoint(secondaryStorageUrl); s_logger.info("Secondary storage mount point: " + secondaryMountPoint); @@ -586,7 +584,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName); if (vmMo == null) { String msg = - "Failed to import OVA template. secondaryStorage: " + secondaryStorageUrl + ", templatePathAtSecondaryStorage: " + templatePathAtSecondaryStorage + + "Failed to import OVA template. secondaryStorage: " + secondaryStorageUrl + ", templatePathAtSecondaryStorage: " + templatePathAtSecondaryStorage + ", templateName: " + templateName + ", templateUuid: " + templateUuid; s_logger.error(msg); throw new Exception(msg); @@ -604,7 +602,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { } private Ternary createTemplateFromVolume(VirtualMachineMO vmMo, long accountId, long templateId, String templateUniqueName, String secStorageUrl, - String volumePath, String workerVmName) throws Exception { + String volumePath, String workerVmName) throws Exception { String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl); String installPath = getTemplateRelativeDirInSecStorage(accountId, templateId); @@ -649,10 +647,10 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { clonedVm.exportVm(secondaryMountPoint + "/" + installPath, templateUniqueName, true, false); long physicalSize = new File(installFullPath + "/" + templateUniqueName + ".ova").length(); - VmdkProcessor processor = new VmdkProcessor(); + OVAProcessor processor = new OVAProcessor(); Map params = new HashMap(); params.put(StorageLayer.InstanceConfigKey, _storage); - processor.configure("VMDK Processor", params); + processor.configure("OVA Processor", params); long virtualSize = processor.getTemplateVirtualSize(installFullPath, templateUniqueName); postCreatePrivateTemplate(installFullPath, templateId, templateUniqueName, physicalSize, virtualSize); @@ -669,7 +667,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { } private Ternary createTemplateFromSnapshot(long accountId, long templateId, String templateUniqueName, String secStorageUrl, long volumeId, - String backedUpSnapshotUuid) throws Exception { + String backedUpSnapshotUuid) throws Exception { String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl); String installPath = getTemplateRelativeDirInSecStorage(accountId, templateId); @@ -771,11 +769,11 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { } long physicalSize = new File(installFullPath + "/" + templateVMDKName).length(); - VmdkProcessor processor = new VmdkProcessor(); + OVAProcessor processor = new OVAProcessor(); // long physicalSize = new File(installFullPath + "/" + templateUniqueName + ".ova").length(); Map params = new HashMap(); params.put(StorageLayer.InstanceConfigKey, _storage); - processor.configure("VMDK Processor", params); + processor.configure("OVA Processor", params); long virtualSize = processor.getTemplateVirtualSize(installFullPath, templateUniqueName); postCreatePrivateTemplate(installFullPath, templateId, templateUniqueName, physicalSize, virtualSize); @@ -853,14 +851,14 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { } private String createVolumeFromSnapshot(VmwareHypervisorHost hyperHost, DatastoreMO primaryDsMo, String newVolumeName, long accountId, long volumeId, - String secStorageUrl, String snapshotBackupUuid) throws Exception { + String secStorageUrl, String snapshotBackupUuid) throws Exception { restoreVolumeFromSecStorage(hyperHost, primaryDsMo, newVolumeName, secStorageUrl, getSnapshotRelativeDirInSecStorage(accountId, volumeId), snapshotBackupUuid); return null; } private void restoreVolumeFromSecStorage(VmwareHypervisorHost hyperHost, DatastoreMO primaryDsMo, String newVolumeName, String secStorageUrl, String secStorageDir, - String backupName) throws Exception { + String backupName) throws Exception { String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl); String srcOVAFileName = secondaryMountPoint + "/" + secStorageDir + "/" + backupName + "." + ImageFormat.OVA.getFileExtension(); @@ -920,7 +918,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { } private String backupSnapshotToSecondaryStorage(VirtualMachineMO vmMo, long accountId, long volumeId, String volumePath, String snapshotUuid, String secStorageUrl, - String prevSnapshotUuid, String prevBackupUuid, String workerVmName) throws Exception { + String prevSnapshotUuid, String prevBackupUuid, String workerVmName) throws Exception { String backupUuid = UUID.randomUUID().toString(); exportVolumeToSecondaryStroage(vmMo, volumePath, secStorageUrl, getSnapshotRelativeDirInSecStorage(accountId, volumeId), backupUuid, workerVmName); @@ -928,7 +926,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { } private void exportVolumeToSecondaryStroage(VirtualMachineMO vmMo, String volumePath, String secStorageUrl, String secStorageDir, String exportName, - String workerVmName) throws Exception { + String workerVmName) throws Exception { String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl); String exportPath = secondaryMountPoint + "/" + secStorageDir + "/" + exportName; @@ -972,40 +970,8 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { } } - private String deleteSnapshotOnSecondaryStorge(long accountId, long volumeId, String secStorageUrl, String backupUuid) throws Exception { - - String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl); - String snapshotMountRoot = secondaryMountPoint + "/" + getSnapshotRelativeDirInSecStorage(accountId, volumeId); - File file = new File(snapshotMountRoot + "/" + backupUuid + ".ovf"); - if (file.exists()) { - File snapshotdir = new File(snapshotMountRoot); - File[] ssfiles = snapshotdir.listFiles(); - // List filenames = new ArrayList(); - for (int i = 0; i < ssfiles.length; i++) { - String vmdkfile = ssfiles[i].getName(); - if (vmdkfile.toLowerCase().startsWith(backupUuid) && vmdkfile.toLowerCase().endsWith(".vmdk")) { - // filenames.add(vmdkfile); - new File(vmdkfile).delete(); - } - } - if (file.delete()) { - return null; - } - } else { - File file1 = new File(snapshotMountRoot + "/" + backupUuid + ".ova"); - if (file1.exists()) { - if (file1.delete()) { - return null; - } - } else { - return "Backup file does not exist. backupUuid: " + backupUuid; - } - } - return "Failed to delete snapshot backup file, backupUuid: " + backupUuid; - } - private Pair copyVolumeToSecStorage(VmwareHostService hostService, VmwareHypervisorHost hyperHost, CopyVolumeCommand cmd, String vmName, - long volumeId, String poolId, String volumePath, String secStorageUrl, String workerVmName) throws Exception { + long volumeId, String poolId, String volumePath, String secStorageUrl, String workerVmName) throws Exception { String volumeFolder = String.valueOf(volumeId) + "/"; VirtualMachineMO workerVm = null; @@ -1042,7 +1008,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { vmMo.createSnapshot(exportName, "Temporary snapshot for copy-volume command", false, false); exportVolumeToSecondaryStroage(vmMo, volumePath, secStorageUrl, "volumes/" + volumeFolder, exportName, - hostService.getWorkerName(hyperHost.getContext(), cmd, 1)); + hostService.getWorkerName(hyperHost.getContext(), cmd, 1)); return new Pair(volumeFolder, exportName); } finally { @@ -1065,7 +1031,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { } private Pair copyVolumeFromSecStorage(VmwareHypervisorHost hyperHost, long volumeId, DatastoreMO dsMo, String secStorageUrl, String exportName) - throws Exception { + throws Exception { String volumeFolder = String.valueOf(volumeId) + "/"; String newVolume = UUID.randomUUID().toString().replaceAll("-", ""); @@ -1084,69 +1050,54 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { s_logger.info("getOVAfromMetaFile: " + metafileName); try { strm = new FileInputStream(ova_metafile); - if (null == strm) { - String msg = "Cannot read ova meta file."; + + s_logger.info("loading properties from ova meta file: " + metafileName); + props = new Properties(); + props.load(strm); + ovaFileName = props.getProperty("ova.filename"); + s_logger.info("ovafilename: " + ovaFileName); + String ovfFileName = props.getProperty("ovf"); + s_logger.info("ovffilename: " + ovfFileName); + int diskNum = Integer.parseInt(props.getProperty("numDisks")); + if (diskNum <= 0) { + String msg = "VMDK disk file number is 0. Error"; s_logger.error(msg); throw new Exception(msg); } - - s_logger.info("loading properties from ova meta file: " + metafileName); - if (null != ova_metafile) { - props = new Properties(); - props.load(strm); - if (props == null) { - s_logger.info("getOVAfromMetaFile: props is null. "); - } + String[] disks = new String[diskNum]; + for (int i = 0; i < diskNum; i++) { + // String diskNameKey = "disk" + Integer.toString(i+1) + ".name"; // Fang use this + String diskNameKey = "disk1.name"; + disks[i] = props.getProperty(diskNameKey); + s_logger.info("diskname " + disks[i]); } - if (null != props) { - ovaFileName = props.getProperty("ova.filename"); - s_logger.info("ovafilename: " + ovaFileName); - String ovfFileName = props.getProperty("ovf"); - s_logger.info("ovffilename: " + ovfFileName); - int diskNum = Integer.parseInt(props.getProperty("numDisks")); - if (diskNum <= 0) { - String msg = "VMDK disk file number is 0. Error"; - s_logger.error(msg); - throw new Exception(msg); - } - String[] disks = new String[diskNum]; - for (int i = 0; i < diskNum; i++) { - // String diskNameKey = "disk" + Integer.toString(i+1) + ".name"; // Fang use this - String diskNameKey = "disk1.name"; - disks[i] = props.getProperty(diskNameKey); - s_logger.info("diskname " + disks[i]); - } - String exportDir = ova_metafile.getParent(); - s_logger.info("exportDir: " + exportDir); - // Important! we need to sync file system before we can safely use tar to work around a linux kernal bug(or feature) - s_logger.info("Sync file system before we package OVA..., before tar "); - s_logger.info("ova: " + ovaFileName + ", ovf:" + ovfFileName + ", vmdk:" + disks[0] + "."); - Script commandSync = new Script(true, "sync", 0, s_logger); - commandSync.execute(); - Script command = new Script(false, "tar", 0, s_logger); - command.setWorkDir(exportDir); // Fang: pass this in to the method? - command.add("-cf", ovaFileName); - command.add(ovfFileName); // OVF file should be the first file in OVA archive - for (String diskName : disks) { - command.add(diskName); - } - command.execute(); - s_logger.info("Package OVA for template in dir: " + exportDir + "cmd: " + command.toString()); - // to be safe, physically test existence of the target OVA file - if ((new File(exportDir + ovaFileName)).exists()) { - s_logger.info("ova file is created and ready to extract "); - return (ovaFileName); - } else { - String msg = exportDir + File.separator + ovaFileName + ".ova is not created as expected"; - s_logger.error(msg); - throw new Exception(msg); - } + String exportDir = ova_metafile.getParent(); + s_logger.info("exportDir: " + exportDir); + // Important! we need to sync file system before we can safely use tar to work around a linux kernal bug(or feature) + s_logger.info("Sync file system before we package OVA..., before tar "); + s_logger.info("ova: " + ovaFileName + ", ovf:" + ovfFileName + ", vmdk:" + disks[0] + "."); + Script commandSync = new Script(true, "sync", 0, s_logger); + commandSync.execute(); + Script command = new Script(false, "tar", 0, s_logger); + command.setWorkDir(exportDir); // Fang: pass this in to the method? + command.add("-cf", ovaFileName); + command.add(ovfFileName); // OVF file should be the first file in OVA archive + for (String diskName : disks) { + command.add(diskName); + } + command.execute(); + s_logger.info("Package OVA for template in dir: " + exportDir + "cmd: " + command.toString()); + // to be safe, physically test existence of the target OVA file + if ((new File(exportDir + ovaFileName)).exists()) { + s_logger.info("ova file is created and ready to extract "); + return (ovaFileName); } else { - String msg = "Error reading the ova meta file: " + metafileName; + String msg = exportDir + File.separator + ovaFileName + ".ova is not created as expected"; s_logger.error(msg); throw new Exception(msg); } } catch (Exception e) { + s_logger.error("Exception in getOVAFromMetafile", e); return null; // Do something, re-throw the exception } finally { @@ -1183,9 +1134,10 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { return "snapshots/" + accountId + "/" + volumeId; } - private long getVMSnapshotChainSize(VmwareContext context, VmwareHypervisorHost hyperHost, String fileName, String poolUuid, String exceptFileName) throws Exception { + private long getVMSnapshotChainSize(VmwareContext context, VmwareHypervisorHost hyperHost, + String fileName, ManagedObjectReference morDs, String exceptFileName) + throws Exception{ long size = 0; - ManagedObjectReference morDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, poolUuid); DatastoreMO dsMo = new DatastoreMO(context, morDs); HostDatastoreBrowserMO browserMo = dsMo.getHostDatastoreBrowserMO(); String datastorePath = "[" + dsMo.getName() + "]"; @@ -1244,15 +1196,17 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { boolean quiescevm = cmd.getTarget().getQuiescevm(); VirtualMachineMO vmMo = null; VmwareContext context = hostService.getServiceContext(cmd); - Map mapNewDisk = new HashMap(); + try { VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd); // wait if there are already VM snapshot task running ManagedObjectReference taskmgr = context.getServiceContent().getTaskManager(); - List tasks = (ArrayList)context.getVimClient().getDynamicProperty(taskmgr, "recentTask"); + List tasks = context.getVimClient().getDynamicProperty(taskmgr, "recentTask"); + for (ManagedObjectReference taskMor : tasks) { TaskInfo info = (TaskInfo)(context.getVimClient().getDynamicProperty(taskMor, "info")); + if (info.getEntityName().equals(cmd.getVmName()) && info.getName().equalsIgnoreCase("CreateSnapshot_Task")) { s_logger.debug("There is already a VM snapshot task running, wait for it"); context.getVimClient().waitForTask(taskMor); @@ -1260,12 +1214,15 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { } vmMo = hyperHost.findVmOnHyperHost(vmName); + if (vmMo == null) { vmMo = hyperHost.findVmOnPeerHyperHost(vmName); } + if (vmMo == null) { String msg = "Unable to find VM for CreateVMSnapshotCommand"; s_logger.debug(msg); + return new CreateVMSnapshotAnswer(cmd, false, msg); } else { if (vmMo.getSnapshotMor(vmSnapshotName) != null) { @@ -1273,66 +1230,145 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { } else if (!vmMo.createSnapshot(vmSnapshotName, vmSnapshotDesc, snapshotMemory, quiescevm)) { return new CreateVMSnapshotAnswer(cmd, false, "Unable to create snapshot due to esxi internal failed"); } - // find VM disk file path after creating snapshot - VirtualDisk[] vdisks = vmMo.getAllDiskDevice(); - for (int i = 0; i < vdisks.length; i++) { - List> vmdkFiles = vmMo.getDiskDatastorePathChain(vdisks[i], false); - for (Pair fileItem : vmdkFiles) { - String vmdkName = fileItem.first().split(" ")[1]; - if (vmdkName.endsWith(".vmdk")) { - vmdkName = vmdkName.substring(0, vmdkName.length() - (".vmdk").length()); - } - String baseName = extractSnapshotBaseFileName(vmdkName); - mapNewDisk.put(baseName, vmdkName); - } - } - for (VolumeObjectTO volumeTO : volumeTOs) { - String baseName = extractSnapshotBaseFileName(volumeTO.getPath()); - String newPath = mapNewDisk.get(baseName); - // get volume's chain size for this VM snapshot, exclude current volume vdisk - DataStoreTO store = volumeTO.getDataStore(); - long size = getVMSnapshotChainSize(context, hyperHost, baseName + "*.vmdk", store.getUuid(), newPath); - if (volumeTO.getVolumeType() == Volume.Type.ROOT) { - // add memory snapshot size - size = size + getVMSnapshotChainSize(context, hyperHost, cmd.getVmName() + "*.vmsn", store.getUuid(), null); - } + Map mapNewDisk = getNewDiskMap(vmMo); + + setVolumeToPathAndSize(volumeTOs, mapNewDisk, context, hyperHost, cmd.getVmName()); - volumeTO.setSize(size); - volumeTO.setPath(newPath); - } return new CreateVMSnapshotAnswer(cmd, cmd.getTarget(), volumeTOs); } } catch (Exception e) { String msg = e.getMessage(); s_logger.error("failed to create snapshot for vm:" + vmName + " due to " + msg); + try { if (vmMo.getSnapshotMor(vmSnapshotName) != null) { vmMo.removeSnapshot(vmSnapshotName, false); } } catch (Exception e1) { } + return new CreateVMSnapshotAnswer(cmd, false, e.getMessage()); } } + private Map getNewDiskMap(VirtualMachineMO vmMo) throws Exception { + Map mapNewDisk = new HashMap(); + + // find VM disk file path after creating snapshot + VirtualDisk[] vdisks = vmMo.getAllDiskDevice(); + + for (int i = 0; i < vdisks.length; i++) { + List> vmdkFiles = vmMo.getDiskDatastorePathChain(vdisks[i], false); + + for (Pair fileItem : vmdkFiles) { + String fullPath = fileItem.first(); + String baseName = null; + String vmdkName = null; + + // if this is managed storage + if (fullPath.startsWith("[-iqn.")) { // ex. [-iqn.2010-01.com.company:3y8w.vol-10.64-0] -iqn.2010-01.com.company:3y8w.vol-10.64-0-000001.vmdk + baseName = fullPath.split(" ")[0]; // ex. [-iqn.2010-01.com.company:3y8w.vol-10.64-0] + + // remove '[' and ']' + baseName = baseName.substring(1, baseName.length() - 1); + + vmdkName = fullPath; // for managed storage, vmdkName == fullPath + } + else { + vmdkName = fullPath.split(" ")[1]; + + if (vmdkName.endsWith(".vmdk")) { + vmdkName = vmdkName.substring(0, vmdkName.length() - (".vmdk").length()); + } + + String token = "/"; + + if (vmdkName.contains(token)) { + vmdkName = vmdkName.substring(vmdkName.indexOf(token) + token.length()); + } + + baseName = extractSnapshotBaseFileName(vmdkName); + } + + mapNewDisk.put(baseName, vmdkName); + } + } + + return mapNewDisk; + } + + private void setVolumeToPathAndSize(List volumeTOs, Map mapNewDisk, VmwareContext context, + VmwareHypervisorHost hyperHost, String vmName) throws Exception { + for (VolumeObjectTO volumeTO : volumeTOs) { + String oldPath = volumeTO.getPath(); + + final String baseName; + + // if this is managed storage + if (oldPath.startsWith("[-iqn.")) { // ex. [-iqn.2010-01.com.company:3y8w.vol-10.64-0] -iqn.2010-01.com.company:3y8w.vol-10.64-0-000001.vmdk + oldPath = oldPath.split(" ")[0]; // ex. [-iqn.2010-01.com.company:3y8w.vol-10.64-0] + + // remove '[' and ']' + baseName = oldPath.substring(1, oldPath.length() - 1); + } + else { + baseName = extractSnapshotBaseFileName(volumeTO.getPath()); + } + + String newPath = mapNewDisk.get(baseName); + + // get volume's chain size for this VM snapshot; exclude current volume vdisk + DataStoreTO store = volumeTO.getDataStore(); + ManagedObjectReference morDs = getDatastoreAsManagedObjectReference(baseName, hyperHost, store); + long size = getVMSnapshotChainSize(context, hyperHost, baseName + "*.vmdk", morDs, newPath); + + if (volumeTO.getVolumeType()== Volume.Type.ROOT) { + // add memory snapshot size + size += getVMSnapshotChainSize(context, hyperHost, vmName + "*.vmsn", morDs, null); + } + + volumeTO.setSize(size); + volumeTO.setPath(newPath); + } + } + + private ManagedObjectReference getDatastoreAsManagedObjectReference(String baseName, VmwareHypervisorHost hyperHost, DataStoreTO store) throws Exception { + try { + // if baseName equates to a datastore name, this should be managed storage + ManagedObjectReference morDs = hyperHost.findDatastoreByName(baseName); + + if (morDs != null) { + return morDs; + } + } + catch (Exception ex) { + } + + // not managed storage, so use the standard way of getting a ManagedObjectReference for a datastore + return HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, store.getUuid()); + } + @Override public DeleteVMSnapshotAnswer execute(VmwareHostService hostService, DeleteVMSnapshotCommand cmd) { List listVolumeTo = cmd.getVolumeTOs(); VirtualMachineMO vmMo = null; VmwareContext context = hostService.getServiceContext(cmd); - Map mapNewDisk = new HashMap(); String vmName = cmd.getVmName(); String vmSnapshotName = cmd.getTarget().getSnapshotName(); + try { VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd); vmMo = hyperHost.findVmOnHyperHost(vmName); + if (vmMo == null) { vmMo = hyperHost.findVmOnPeerHyperHost(vmName); } + if (vmMo == null) { String msg = "Unable to find VM for RevertToVMSnapshotCommand"; s_logger.debug(msg); + return new DeleteVMSnapshotAnswer(cmd, false, msg); } else { if (vmMo.getSnapshotMor(vmSnapshotName) == null) { @@ -1341,41 +1377,25 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { if (!vmMo.removeSnapshot(vmSnapshotName, false)) { String msg = "delete vm snapshot " + vmSnapshotName + " due to error occured in vmware"; s_logger.error(msg); + return new DeleteVMSnapshotAnswer(cmd, false, msg); } } + s_logger.debug("snapshot: " + vmSnapshotName + " is removed"); + // after removed snapshot, the volumes' paths have been changed for the VM, needs to report new paths to manager - VirtualDisk[] vdisks = vmMo.getAllDiskDevice(); - for (int i = 0; i < vdisks.length; i++) { - @SuppressWarnings("deprecation") - List> vmdkFiles = vmMo.getDiskDatastorePathChain(vdisks[i], false); - for (Pair fileItem : vmdkFiles) { - String vmdkName = fileItem.first().split(" ")[1]; - if (vmdkName.endsWith(".vmdk")) { - vmdkName = vmdkName.substring(0, vmdkName.length() - (".vmdk").length()); - } - String baseName = extractSnapshotBaseFileName(vmdkName); - mapNewDisk.put(baseName, vmdkName); - } - } - for (VolumeObjectTO volumeTo : listVolumeTo) { - String baseName = extractSnapshotBaseFileName(volumeTo.getPath()); - String newPath = mapNewDisk.get(baseName); - DataStoreTO store = volumeTo.getDataStore(); - long size = getVMSnapshotChainSize(context, hyperHost, baseName + "*.vmdk", store.getUuid(), newPath); - if (volumeTo.getVolumeType() == Volume.Type.ROOT) { - // add memory snapshot size - size = size + getVMSnapshotChainSize(context, hyperHost, cmd.getVmName() + "*.vmsn", store.getUuid(), null); - } - volumeTo.setSize(size); - volumeTo.setPath(newPath); - } + + Map mapNewDisk = getNewDiskMap(vmMo); + + setVolumeToPathAndSize(listVolumeTo, mapNewDisk, context, hyperHost, cmd.getVmName()); + return new DeleteVMSnapshotAnswer(cmd, listVolumeTo); } } catch (Exception e) { String msg = e.getMessage(); s_logger.error("failed to delete vm snapshot " + vmSnapshotName + " of vm " + vmName + " due to " + msg); + return new DeleteVMSnapshotAnswer(cmd, false, msg); } } @@ -1389,15 +1409,17 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { VirtualMachine.State vmState = VirtualMachine.State.Running; VirtualMachineMO vmMo = null; VmwareContext context = hostService.getServiceContext(cmd); - Map mapNewDisk = new HashMap(); + try { VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd); // wait if there are already VM revert task running ManagedObjectReference taskmgr = context.getServiceContent().getTaskManager(); - List tasks = (ArrayList)context.getVimClient().getDynamicProperty(taskmgr, "recentTask"); + List tasks = context.getVimClient().getDynamicProperty(taskmgr, "recentTask"); + for (ManagedObjectReference taskMor : tasks) { TaskInfo info = (TaskInfo)(context.getVimClient().getDynamicProperty(taskMor, "info")); + if (info.getEntityName().equals(cmd.getVmName()) && info.getName().equalsIgnoreCase("RevertToSnapshot_Task")) { s_logger.debug("There is already a VM snapshot task running, wait for it"); context.getVimClient().waitForTask(taskMor); @@ -1406,58 +1428,49 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { HostMO hostMo = (HostMO)hyperHost; vmMo = hyperHost.findVmOnHyperHost(vmName); + if (vmMo == null) { vmMo = hyperHost.findVmOnPeerHyperHost(vmName); } + if (vmMo == null) { String msg = "Unable to find VM for RevertToVMSnapshotCommand"; s_logger.debug(msg); + return new RevertToVMSnapshotAnswer(cmd, false, msg); } else { if (cmd.isReloadVm()) { vmMo.reload(); } + boolean result = false; + if (snapshotName != null) { ManagedObjectReference morSnapshot = vmMo.getSnapshotMor(snapshotName); + result = hostMo.revertToSnapshot(morSnapshot); } else { return new RevertToVMSnapshotAnswer(cmd, false, "Unable to find the snapshot by name " + snapshotName); } if (result) { - VirtualDisk[] vdisks = vmMo.getAllDiskDevice(); - // build a map - for (int i = 0; i < vdisks.length; i++) { - @SuppressWarnings("deprecation") - List> vmdkFiles = vmMo.getDiskDatastorePathChain(vdisks[i], false); - for (Pair fileItem : vmdkFiles) { - String vmdkName = fileItem.first().split(" ")[1]; - if (vmdkName.endsWith(".vmdk")) { - vmdkName = vmdkName.substring(0, vmdkName.length() - (".vmdk").length()); - } - String[] s = vmdkName.split("-"); - mapNewDisk.put(s[0], vmdkName); - } - } - String key = null; - for (VolumeObjectTO volumeTo : listVolumeTo) { - String parentUUID = volumeTo.getPath(); - String[] s = parentUUID.split("-"); - key = s[0]; - volumeTo.setPath(mapNewDisk.get(key)); - } + Map mapNewDisk = getNewDiskMap(vmMo); + + setVolumeToPathAndSize(listVolumeTo, mapNewDisk, context, hyperHost, cmd.getVmName()); + if (!snapshotMemory) { vmState = VirtualMachine.State.Stopped; } + return new RevertToVMSnapshotAnswer(cmd, listVolumeTo, vmState); } else { - return new RevertToVMSnapshotAnswer(cmd, false, "Error while reverting to snapshot due to execute in esxi"); + return new RevertToVMSnapshotAnswer(cmd, false, "Error while reverting to snapshot due to execute in ESXi"); } } } catch (Exception e) { String msg = "revert vm " + vmName + " to snapshot " + snapshotName + " failed due to " + e.getMessage(); s_logger.error(msg); + return new RevertToVMSnapshotAnswer(cmd, false, msg); } } diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareContextFactory.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareContextFactory.java index cdd0c29c9fe..11163e90d6f 100755 --- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareContextFactory.java +++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareContextFactory.java @@ -89,7 +89,7 @@ public class VmwareContextFactory { } else { // Validate current context and verify if vCenter session timeout value of the context matches the timeout value set by Admin if (!context.validate() || (context.getVimClient().getVcenterSessionTimeout() != s_vmwareMgr.getVcenterSessionTimeout())) { - s_logger.info("Validation of the context faild. dispose and create a new one"); + s_logger.info("Validation of the context failed, dispose and create a new one"); context.close(); context = create(vCenterAddress, vCenterUserName, vCenterPassword); } diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java index e34d5e1690f..407327592bc 100755 --- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java +++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java @@ -42,7 +42,6 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; -import javax.inject.Inject; import javax.naming.ConfigurationException; import org.apache.log4j.Logger; @@ -61,7 +60,6 @@ import com.vmware.vim25.DistributedVirtualPort; import com.vmware.vim25.DistributedVirtualSwitchPortConnection; import com.vmware.vim25.DistributedVirtualSwitchPortCriteria; import com.vmware.vim25.DynamicProperty; -import com.vmware.vim25.GuestInfo; import com.vmware.vim25.HostCapability; import com.vmware.vim25.HostHostBusAdapter; import com.vmware.vim25.HostInternetScsiHba; @@ -104,7 +102,6 @@ import com.vmware.vim25.VirtualMachineRelocateSpecDiskLocator; import com.vmware.vim25.VirtualMachineRuntimeInfo; import com.vmware.vim25.VmwareDistributedVirtualSwitchVlanIdSpec; -import org.apache.cloudstack.engine.orchestration.service.VolumeOrchestrationService; import org.apache.cloudstack.storage.command.DeleteCommand; import org.apache.cloudstack.storage.command.StorageSubSystemCommand; import org.apache.cloudstack.storage.to.TemplateObjectTO; @@ -117,17 +114,12 @@ import com.cloud.agent.api.AttachVolumeAnswer; import com.cloud.agent.api.AttachVolumeCommand; import com.cloud.agent.api.BackupSnapshotAnswer; import com.cloud.agent.api.BackupSnapshotCommand; -import com.cloud.agent.api.BumpUpPriorityCommand; import com.cloud.agent.api.CheckHealthAnswer; import com.cloud.agent.api.CheckHealthCommand; import com.cloud.agent.api.CheckNetworkAnswer; import com.cloud.agent.api.CheckNetworkCommand; import com.cloud.agent.api.CheckOnHostAnswer; import com.cloud.agent.api.CheckOnHostCommand; -import com.cloud.agent.api.CheckRouterAnswer; -import com.cloud.agent.api.CheckRouterCommand; -import com.cloud.agent.api.CheckS2SVpnConnectionsAnswer; -import com.cloud.agent.api.CheckS2SVpnConnectionsCommand; import com.cloud.agent.api.CheckVirtualMachineAnswer; import com.cloud.agent.api.CheckVirtualMachineCommand; import com.cloud.agent.api.Command; @@ -141,8 +133,6 @@ import com.cloud.agent.api.CreateVolumeFromSnapshotCommand; import com.cloud.agent.api.DeleteStoragePoolCommand; import com.cloud.agent.api.DeleteVMSnapshotAnswer; import com.cloud.agent.api.DeleteVMSnapshotCommand; -import com.cloud.agent.api.GetDomRVersionAnswer; -import com.cloud.agent.api.GetDomRVersionCmd; import com.cloud.agent.api.GetHostStatsAnswer; import com.cloud.agent.api.GetHostStatsCommand; import com.cloud.agent.api.GetStorageStatsAnswer; @@ -188,7 +178,6 @@ import com.cloud.agent.api.ScaleVmAnswer; import com.cloud.agent.api.ScaleVmCommand; import com.cloud.agent.api.SetupAnswer; import com.cloud.agent.api.SetupCommand; -import com.cloud.agent.api.SetupGuestNetworkAnswer; import com.cloud.agent.api.SetupGuestNetworkCommand; import com.cloud.agent.api.StartAnswer; import com.cloud.agent.api.StartCommand; @@ -208,35 +197,11 @@ import com.cloud.agent.api.ValidateSnapshotCommand; import com.cloud.agent.api.VmStatsEntry; import com.cloud.agent.api.check.CheckSshAnswer; import com.cloud.agent.api.check.CheckSshCommand; -import com.cloud.agent.api.routing.CreateIpAliasCommand; -import com.cloud.agent.api.routing.DeleteIpAliasCommand; -import com.cloud.agent.api.routing.DhcpEntryCommand; -import com.cloud.agent.api.routing.DnsMasqConfigCommand; -import com.cloud.agent.api.routing.IpAliasTO; -import com.cloud.agent.api.routing.IpAssocAnswer; import com.cloud.agent.api.routing.IpAssocCommand; import com.cloud.agent.api.routing.IpAssocVpcCommand; -import com.cloud.agent.api.routing.LoadBalancerConfigCommand; import com.cloud.agent.api.routing.NetworkElementCommand; -import com.cloud.agent.api.routing.RemoteAccessVpnCfgCommand; -import com.cloud.agent.api.routing.SavePasswordCommand; -import com.cloud.agent.api.routing.SetFirewallRulesAnswer; -import com.cloud.agent.api.routing.SetFirewallRulesCommand; -import com.cloud.agent.api.routing.SetMonitorServiceCommand; -import com.cloud.agent.api.routing.SetNetworkACLAnswer; import com.cloud.agent.api.routing.SetNetworkACLCommand; -import com.cloud.agent.api.routing.SetPortForwardingRulesAnswer; -import com.cloud.agent.api.routing.SetPortForwardingRulesCommand; -import com.cloud.agent.api.routing.SetPortForwardingRulesVpcCommand; -import com.cloud.agent.api.routing.SetSourceNatAnswer; import com.cloud.agent.api.routing.SetSourceNatCommand; -import com.cloud.agent.api.routing.SetStaticNatRulesAnswer; -import com.cloud.agent.api.routing.SetStaticNatRulesCommand; -import com.cloud.agent.api.routing.SetStaticRouteAnswer; -import com.cloud.agent.api.routing.SetStaticRouteCommand; -import com.cloud.agent.api.routing.Site2SiteVpnCfgCommand; -import com.cloud.agent.api.routing.VmDataCommand; -import com.cloud.agent.api.routing.VpnUsersCfgCommand; import com.cloud.agent.api.storage.CopyVolumeAnswer; import com.cloud.agent.api.storage.CopyVolumeCommand; import com.cloud.agent.api.storage.CreateAnswer; @@ -250,19 +215,19 @@ import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand; import com.cloud.agent.api.storage.ResizeVolumeAnswer; import com.cloud.agent.api.storage.ResizeVolumeCommand; import com.cloud.agent.api.to.DataStoreTO; -import com.cloud.agent.api.to.DhcpTO; import com.cloud.agent.api.to.DiskTO; -import com.cloud.agent.api.to.FirewallRuleTO; import com.cloud.agent.api.to.IpAddressTO; import com.cloud.agent.api.to.NfsTO; import com.cloud.agent.api.to.NicTO; -import com.cloud.agent.api.to.PortForwardingRuleTO; -import com.cloud.agent.api.to.StaticNatRuleTO; import com.cloud.agent.api.to.StorageFilerTO; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.agent.api.to.VolumeTO; +import com.cloud.agent.resource.virtualnetwork.VirtualRouterDeployer; +import com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource; +import com.cloud.configuration.Config; import com.cloud.dc.DataCenter.NetworkType; import com.cloud.dc.Vlan; +import com.cloud.exception.CloudException; import com.cloud.exception.InternalErrorException; import com.cloud.host.Host.Type; import com.cloud.hypervisor.Hypervisor.HypervisorType; @@ -293,13 +258,10 @@ import com.cloud.hypervisor.vmware.mo.VmwareHypervisorHostResourceSummary; import com.cloud.hypervisor.vmware.util.VmwareContext; import com.cloud.hypervisor.vmware.util.VmwareGuestOsMapper; import com.cloud.hypervisor.vmware.util.VmwareHelper; -import com.cloud.network.HAProxyConfigurator; -import com.cloud.network.LoadBalancerConfigurator; import com.cloud.network.Networks; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.TrafficType; import com.cloud.network.VmwareTrafficLabel; -import com.cloud.network.rules.FirewallRule; import com.cloud.resource.ServerResource; import com.cloud.serializer.GsonHelper; import com.cloud.storage.Storage; @@ -312,9 +274,11 @@ import com.cloud.storage.resource.VmwareStorageProcessor; import com.cloud.storage.resource.VmwareStorageSubsystemCommandHandler; import com.cloud.storage.template.TemplateProp; import com.cloud.utils.DateUtil; +import com.cloud.utils.ExecutionResult; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.StringUtils; +import com.cloud.utils.Ternary; import com.cloud.utils.db.DB; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.ExceptionUtil; @@ -329,23 +293,20 @@ import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.VirtualMachineName; import com.cloud.vm.VmDetailConstants; -public class VmwareResource implements StoragePoolResource, ServerResource, VmwareHostService { +public class VmwareResource implements StoragePoolResource, ServerResource, VmwareHostService, VirtualRouterDeployer { private static final Logger s_logger = Logger.getLogger(VmwareResource.class); protected String _name; - protected final long _ops_timeout = 900000; // 15 minutes time out to time + protected final long _opsTimeout = 900000; // 15 minutes time out to time - protected final int _shutdown_waitMs = 300000; // wait up to 5 minutes for shutdown - - @Inject - protected VolumeOrchestrationService volMgr; + protected final int _shutdownWaitMs = 300000; // wait up to 5 minutes for shutdown // out an operation protected final int _retry = 24; protected final int _sleep = 10000; - protected final int DEFAULT_DOMR_SSHPORT = 3922; - protected final int MAX_CMD_MBEAN = 100; + protected final int DefaultDomRSshPort = 3922; + protected final int MazCmdMBean = 100; protected String _url; protected String _dcId; @@ -362,10 +323,9 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa protected int _portsPerDvPortGroup; protected boolean _fullCloneFlag = false; protected boolean _instanceNameFlag = false; + protected boolean _reserveCpu; + protected boolean _reserveMem; - protected boolean _reserveCpu = false; - - protected boolean _reserveMem = false; protected boolean _recycleHungWorker = false; protected DiskControllerType _rootDiskController = DiskControllerType.ide; @@ -382,6 +342,8 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa protected StorageSubsystemCommandHandler storageHandler; + protected VirtualRoutingResource _vrResource; + protected static HashMap s_powerStatesTable; static { s_powerStatesTable = new HashMap(); @@ -431,26 +393,8 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa Class clz = cmd.getClass(); if (clz == CreateCommand.class) { answer = execute((CreateCommand)cmd); - } else if (clz == SetPortForwardingRulesCommand.class) { - answer = execute((SetPortForwardingRulesCommand)cmd); - } else if (clz == SetStaticNatRulesCommand.class) { - answer = execute((SetStaticNatRulesCommand)cmd); - } else if (clz == LoadBalancerConfigCommand.class) { - answer = execute((LoadBalancerConfigCommand)cmd); - } else if (clz == IpAssocCommand.class) { - answer = execute((IpAssocCommand)cmd); - } else if (clz == SavePasswordCommand.class) { - answer = execute((SavePasswordCommand)cmd); - } else if (clz == DhcpEntryCommand.class) { - answer = execute((DhcpEntryCommand)cmd); - } else if (clz == CreateIpAliasCommand.class) { - return execute((CreateIpAliasCommand)cmd); - } else if (clz == DnsMasqConfigCommand.class) { - return execute((DnsMasqConfigCommand)cmd); - } else if (clz == DeleteIpAliasCommand.class) { - return execute((DeleteIpAliasCommand)cmd); - } else if (clz == VmDataCommand.class) { - answer = execute((VmDataCommand)cmd); + } else if (cmd instanceof NetworkElementCommand) { + return _vrResource.executeRequest(cmd); } else if (clz == ReadyCommand.class) { answer = execute((ReadyCommand)cmd); } else if (clz == GetHostStatsCommand.class) { @@ -527,62 +471,32 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa answer = execute((NetworkUsageCommand)cmd); } else if (clz == StartCommand.class) { answer = execute((StartCommand)cmd); - } else if (clz == RemoteAccessVpnCfgCommand.class) { - answer = execute((RemoteAccessVpnCfgCommand)cmd); - } else if (clz == VpnUsersCfgCommand.class) { - answer = execute((VpnUsersCfgCommand)cmd); } else if (clz == CheckSshCommand.class) { answer = execute((CheckSshCommand)cmd); - } else if (clz == CheckRouterCommand.class) { - answer = execute((CheckRouterCommand)cmd); - } else if (clz == SetFirewallRulesCommand.class) { - answer = execute((SetFirewallRulesCommand)cmd); - } else if (clz == BumpUpPriorityCommand.class) { - answer = execute((BumpUpPriorityCommand)cmd); - } else if (clz == GetDomRVersionCmd.class) { - answer = execute((GetDomRVersionCmd)cmd); } else if (clz == CheckNetworkCommand.class) { answer = execute((CheckNetworkCommand)cmd); - } else if (clz == SetupGuestNetworkCommand.class) { - answer = execute((SetupGuestNetworkCommand)cmd); - } else if (clz == IpAssocVpcCommand.class) { - answer = execute((IpAssocVpcCommand)cmd); } else if (clz == PlugNicCommand.class) { answer = execute((PlugNicCommand)cmd); } else if (clz == UnPlugNicCommand.class) { answer = execute((UnPlugNicCommand)cmd); - } else if (clz == SetSourceNatCommand.class) { - answer = execute((SetSourceNatCommand)cmd); - } else if (clz == SetNetworkACLCommand.class) { - answer = execute((SetNetworkACLCommand)cmd); } else if (cmd instanceof CreateVMSnapshotCommand) { return execute((CreateVMSnapshotCommand)cmd); } else if (cmd instanceof DeleteVMSnapshotCommand) { return execute((DeleteVMSnapshotCommand)cmd); } else if (cmd instanceof RevertToVMSnapshotCommand) { return execute((RevertToVMSnapshotCommand)cmd); - } else if (clz == SetPortForwardingRulesVpcCommand.class) { - answer = execute((SetPortForwardingRulesVpcCommand)cmd); - } else if (clz == Site2SiteVpnCfgCommand.class) { - answer = execute((Site2SiteVpnCfgCommand)cmd); - } else if (clz == CheckS2SVpnConnectionsCommand.class) { - answer = execute((CheckS2SVpnConnectionsCommand)cmd); } else if (clz == ResizeVolumeCommand.class) { return execute((ResizeVolumeCommand)cmd); } else if (clz == UnregisterVMCommand.class) { - return execute((UnregisterVMCommand)cmd); + return execute((UnregisterVMCommand) cmd); } else if (cmd instanceof StorageSubSystemCommand) { - return storageHandler.handleStorageCommands((StorageSubSystemCommand)cmd); + return storageHandler.handleStorageCommands((StorageSubSystemCommand) cmd); } else if (clz == ScaleVmCommand.class) { return execute((ScaleVmCommand)cmd); } else if (clz == PvlanSetupCommand.class) { return execute((PvlanSetupCommand)cmd); - } else if (clz == SetStaticRouteCommand.class) { - answer = execute((SetStaticRouteCommand)cmd); } else if (clz == UnregisterNicCommand.class) { answer = execute((UnregisterNicCommand)cmd); - } else if (clz == SetMonitorServiceCommand.class) { - answer = execute((SetMonitorServiceCommand)cmd); } else { answer = Answer.createUnsupportedCommandAnswer(cmd); } @@ -600,12 +514,12 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa JmxUtil.registerMBean("VMware " + _morHyperHost.getValue(), "Command " + cmdSequence + "-" + cmd.getClass().getSimpleName(), mbean); _cmdMBeans.add(mbean); - if (_cmdMBeans.size() >= MAX_CMD_MBEAN) { + if (_cmdMBeans.size() >= MazCmdMBean) { PropertyMapDynamicBean mbeanToRemove = _cmdMBeans.get(0); _cmdMBeans.remove(0); JmxUtil.unregisterMBean("VMware " + _morHyperHost.getValue(), - "Command " + mbeanToRemove.getProp("Sequence") + "-" + mbeanToRemove.getProp("Name")); + "Command " + mbeanToRemove.getProp("Sequence") + "-" + mbeanToRemove.getProp("Name")); } } catch (Exception e) { if (s_logger.isTraceEnabled()) @@ -698,52 +612,6 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa return answer; } - private SetStaticRouteAnswer execute(SetStaticRouteCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource SetStaticRouteCommand: " + _gson.toJson(cmd)); - } - - boolean endResult = true; - - String controlIp = getRouterSshControlIp(cmd); - String args = ""; - String[] results = new String[cmd.getStaticRoutes().length]; - int i = 0; - - // Extract and build the arguments for the command to be sent to the VR. - String[][] rules = cmd.generateSRouteRules(); - StringBuilder sb = new StringBuilder(); - String[] srRules = rules[0]; - for (int j = 0; j < srRules.length; j++) { - sb.append(srRules[j]).append(','); - } - args += " -a " + sb.toString(); - - // Send over the command for execution, via ssh, to the VR. - try { - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - Pair result = - SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_staticroute.sh " + args); - - if (s_logger.isDebugEnabled()) - s_logger.debug("Executing script on domain router " + controlIp + ": /opt/cloud/bin/vpc_staticroute.sh " + args); - - if (!result.first()) { - s_logger.error("SetStaticRouteCommand failure on setting one rule. args: " + args); - results[i++] = "Failed"; - endResult = false; - } else { - results[i++] = null; - } - } catch (Throwable e) { - s_logger.error("SetStaticRouteCommand(args: " + args + ") failed on setting one rule due to " + VmwareHelper.getExceptionMessage(e), e); - results[i++] = "Failed"; - endResult = false; - } - return new SetStaticRouteAnswer(cmd, endResult, results); - - } - protected NetworkUsageAnswer VPCNetworkUsage(NetworkUsageCommand cmd) { String privateIp = cmd.getPrivateIP(); String option = cmd.getOption(); @@ -765,499 +633,72 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } else { return new NetworkUsageAnswer(cmd, "success", 0L, 0L); } - try { - if (s_logger.isTraceEnabled()) { - s_logger.trace("Executing /opt/cloud/bin/vpc_netusage.sh " + args + " on DomR " + privateIp); + + ExecutionResult callResult = executeInVR(privateIp, "vpc_netusage.sh", args); + + if (!callResult.isSuccess()) { + s_logger.error("Unable to execute NetworkUsage command on DomR (" + privateIp + "), domR may not be ready yet. failure due to " + callResult.getDetails()); + } + + if (option.equals("get") || option.equals("vpn")) { + String result = callResult.getDetails(); + if (result == null || result.isEmpty()) { + s_logger.error(" vpc network usage get returns empty "); } - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - - Pair resultPair = - SshHelper.sshExecute(privateIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_netusage.sh " + args); - - if (!resultPair.first()) { - throw new Exception(" vpc network usage plugin call failed "); - - } - - if (option.equals("get") || option.equals("vpn")) { - String result = resultPair.second(); - if (result == null || result.isEmpty()) { - throw new Exception(" vpc network usage get returns empty "); - } - long[] stats = new long[2]; - if (result != null) { - String[] splitResult = result.split(":"); - int i = 0; - while (i < splitResult.length - 1) { - stats[0] += (new Long(splitResult[i++])).longValue(); - stats[1] += (new Long(splitResult[i++])).longValue(); - } - return new NetworkUsageAnswer(cmd, "success", stats[0], stats[1]); + long[] stats = new long[2]; + if (result != null) { + String[] splitResult = result.split(":"); + int i = 0; + while (i < splitResult.length - 1) { + stats[0] += (new Long(splitResult[i++])).longValue(); + stats[1] += (new Long(splitResult[i++])).longValue(); } + return new NetworkUsageAnswer(cmd, "success", stats[0], stats[1]); } - return new NetworkUsageAnswer(cmd, "success", 0L, 0L); - } catch (Throwable e) { - - s_logger.error( - "Unable to execute NetworkUsage command on DomR (" + privateIp + "), domR may not be ready yet. failure due to " + VmwareHelper.getExceptionMessage(e), e); } return new NetworkUsageAnswer(cmd, "success", 0L, 0L); } - protected Answer execute(SetMonitorServiceCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource SetMonitorServiceCommand: " + _gson.toJson(cmd)); - } - - String controlIp = getRouterSshControlIp(cmd); - String config = cmd.getConfiguration(); - - String args = ""; - - args += " -c " + config; - - try { - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - Pair result = - SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/monitor_service.sh " + args); - - if (!result.first()) { - String msg = "monitor_service.sh failed on domain router " + controlIp + " failed " + result.second(); - s_logger.error(msg); - return new Answer(cmd, false, msg); - } - - return new Answer(cmd); - - } catch (Throwable e) { - s_logger.error("Unexpected exception: " + e.toString(), e); - return new Answer(cmd, false, "SetMonitorServiceCommand failed due to " + VmwareHelper.getExceptionMessage(e)); - } - } - - protected Answer execute(SetPortForwardingRulesCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource SetPortForwardingRulesCommand: " + _gson.toJson(cmd)); - } - - String controlIp = getRouterSshControlIp(cmd); - String args = ""; - String[] results = new String[cmd.getRules().length]; - int i = 0; - - boolean endResult = true; - for (PortForwardingRuleTO rule : cmd.getRules()) { - args += rule.revoked() ? " -D " : " -A "; - args += " -P " + rule.getProtocol().toLowerCase(); - args += " -l " + rule.getSrcIp(); - args += " -p " + rule.getStringSrcPortRange(); - args += " -r " + rule.getDstIp(); - args += " -d " + rule.getStringDstPortRange(); - - try { - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/firewall.sh " + args); - - if (s_logger.isDebugEnabled()) - s_logger.debug("Executing script on domain router " + controlIp + ": /root/firewall.sh " + args); - - if (!result.first()) { - s_logger.error("SetPortForwardingRulesCommand failure on setting one rule. args: " + args); - results[i++] = "Failed"; - endResult = false; - } else { - results[i++] = null; - } - } catch (Throwable e) { - s_logger.error("SetPortForwardingRulesCommand(args: " + args + ") failed on setting one rule due to " + VmwareHelper.getExceptionMessage(e), e); - results[i++] = "Failed"; - endResult = false; - } - } - - return new SetPortForwardingRulesAnswer(cmd, results, endResult); - } - - protected SetFirewallRulesAnswer execute(SetFirewallRulesCommand cmd) { - String controlIp = getRouterSshControlIp(cmd); - String[] results = new String[cmd.getRules().length]; - FirewallRuleTO[] allrules = cmd.getRules(); - FirewallRule.TrafficType trafficType = allrules[0].getTrafficType(); - String egressDefault = cmd.getAccessDetail(NetworkElementCommand.FIREWALL_EGRESS_DEFAULT); - - String[][] rules = cmd.generateFwRules(); - String args = ""; - args += " -F "; - if (trafficType == FirewallRule.TrafficType.Egress) { - args += " -E "; - if (egressDefault.equals("true")) { - args += " -P 1 "; - } else if (egressDefault.equals("System")) { - args += " -P 2 "; - } else { - args += " -P 0 "; - } - } - - StringBuilder sb = new StringBuilder(); - String[] fwRules = rules[0]; - if (fwRules.length > 0) { - for (int i = 0; i < fwRules.length; i++) { - sb.append(fwRules[i]).append(','); - } - args += " -a " + sb.toString(); - } - - try { - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - - Pair result = null; - - if (trafficType == FirewallRule.TrafficType.Egress) { - result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/firewallRule_egress.sh " + args); - } else { - result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/firewall_rule.sh " + args); - } - - if (s_logger.isDebugEnabled()) { - if (trafficType == FirewallRule.TrafficType.Egress) { - s_logger.debug("Executing script on domain router " + controlIp + ": /root/firewallRule_egress.sh " + args); - } else { - s_logger.debug("Executing script on domain router " + controlIp + ": /root/firewall_rule.sh " + args); - } - } - - if (!result.first()) { - s_logger.error("SetFirewallRulesCommand failure on setting one rule. args: " + args); - //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails - for (int i = 0; i < results.length; i++) { - results[i] = "Failed"; - } - - return new SetFirewallRulesAnswer(cmd, false, results); - } - } catch (Throwable e) { - s_logger.error("SetFirewallRulesCommand(args: " + args + ") failed on setting one rule due to " + VmwareHelper.getExceptionMessage(e), e); - //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails - for (int i = 0; i < results.length; i++) { - results[i] = "Failed"; - } - return new SetFirewallRulesAnswer(cmd, false, results); - } - - return new SetFirewallRulesAnswer(cmd, true, results); - } - - protected SetStaticNatRulesAnswer SetVPCStaticNatRules(SetStaticNatRulesCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource SetVPCStaticNatRulesCommand: " + _gson.toJson(cmd)); - } - - String[] results = new String[cmd.getRules().length]; - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - String controlIp = getRouterSshControlIp(cmd); - - int i = 0; - boolean endResult = true; - for (StaticNatRuleTO rule : cmd.getRules()) { - // Prepare command to be send to VPC VR - String args = ""; - args += rule.revoked() ? " -D" : " -A"; - args += " -l " + rule.getSrcIp(); - args += " -r " + rule.getDstIp(); - - // Invoke command on VPC VR. - try { - Pair result = - SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_staticnat.sh " + args); - - if (s_logger.isDebugEnabled()) - s_logger.debug("Executing script on domain router " + controlIp + ": /opt/cloud/bin/vpc_staticnat.sh " + args); - - if (!result.first()) { - s_logger.error("SetVPCStaticNatRulesCommand failure on setting one rule. args: " + args); - results[i++] = "Failed"; - endResult = false; - } else { - results[i++] = null; - } - } catch (Throwable e) { - s_logger.error("SetVPCStaticNatRulesCommand (args: " + args + ") failed on setting one rule due to " + VmwareHelper.getExceptionMessage(e), e); - results[i++] = "Failed"; - endResult = false; - } - } - return new SetStaticNatRulesAnswer(cmd, results, endResult); - } - - protected Answer execute(SetStaticNatRulesCommand cmd) { - - if (cmd.getVpcId() != null) { - return SetVPCStaticNatRules(cmd); - } - - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource SetFirewallRuleCommand: " + _gson.toJson(cmd)); - } - - String args = null; - String[] results = new String[cmd.getRules().length]; - int i = 0; - boolean endResult = true; - for (StaticNatRuleTO rule : cmd.getRules()) { - // 1:1 NAT needs instanceip;publicip;domrip;op - args = rule.revoked() ? " -D " : " -A "; - - args += " -l " + rule.getSrcIp(); - args += " -r " + rule.getDstIp(); - - if (rule.getProtocol() != null) { - args += " -P " + rule.getProtocol().toLowerCase(); - } - - args += " -d " + rule.getStringSrcPortRange(); - args += " -G "; - - try { - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - String controlIp = getRouterSshControlIp(cmd); - Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/firewall.sh " + args); - - if (s_logger.isDebugEnabled()) - s_logger.debug("Executing script on domain router " + controlIp + ": /root/firewall.sh " + args); - - if (!result.first()) { - s_logger.error("SetStaticNatRulesCommand failure on setting one rule. args: " + args); - results[i++] = "Failed"; - endResult = false; - } else { - results[i++] = null; - } - } catch (Throwable e) { - s_logger.error("SetStaticNatRulesCommand (args: " + args + ") failed on setting one rule due to " + VmwareHelper.getExceptionMessage(e), e); - results[i++] = "Failed"; - endResult = false; - } - } - return new SetStaticNatRulesAnswer(cmd, results, endResult); - } - - protected Answer VPCLoadBalancerConfig(final LoadBalancerConfigCommand cmd) { + @Override + public ExecutionResult createFileInVR(String routerIp, String filePath, String fileName, String content) { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); File keyFile = mgr.getSystemVMKeyFile(); - - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - String controlIp = getRouterSshControlIp(cmd); - - assert (controlIp != null); - - LoadBalancerConfigurator cfgtr = new HAProxyConfigurator(); - String[] config = cfgtr.generateConfiguration(cmd); - - String tmpCfgFilePath = "/etc/haproxy/haproxy.cfg.new"; - String tmpCfgFileContents = ""; - for (int i = 0; i < config.length; i++) { - tmpCfgFileContents += config[i]; - tmpCfgFileContents += "\n"; - } + boolean result = true; try { - SshHelper.scpTo(controlIp, DEFAULT_DOMR_SSHPORT, "root", keyFile, null, "/etc/haproxy/", tmpCfgFileContents.getBytes(), "haproxy.cfg.new", null); - - try { - String[][] rules = cfgtr.generateFwRules(cmd); - - String[] addRules = rules[LoadBalancerConfigurator.ADD]; - String[] removeRules = rules[LoadBalancerConfigurator.REMOVE]; - String[] statRules = rules[LoadBalancerConfigurator.STATS]; - - String args = ""; - String ip = cmd.getNic().getIp(); - args += " -i " + ip; - StringBuilder sb = new StringBuilder(); - if (addRules.length > 0) { - for (int i = 0; i < addRules.length; i++) { - sb.append(addRules[i]).append(','); - } - - args += " -a " + sb.toString(); - } - - sb = new StringBuilder(); - if (removeRules.length > 0) { - for (int i = 0; i < removeRules.length; i++) { - sb.append(removeRules[i]).append(','); - } - - args += " -d " + sb.toString(); - } - - sb = new StringBuilder(); - if (statRules.length > 0) { - for (int i = 0; i < statRules.length; i++) { - sb.append(statRules[i]).append(','); - } - - args += " -s " + sb.toString(); - } - - // Invoke the command - Pair result = - SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_loadbalancer.sh " + args); - - if (!result.first()) { - String msg = "LoadBalancerConfigCommand on domain router " + routerIp + " failed. message: " + result.second(); - s_logger.error(msg); - - return new Answer(cmd, false, msg); - } - - if (s_logger.isInfoEnabled()) { - s_logger.info("VPCLoadBalancerConfigCommand on domain router " + routerIp + " completed"); - } - } finally { - SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "rm " + tmpCfgFilePath); - } - return new Answer(cmd); - } catch (Throwable e) { - s_logger.error("Unexpected exception: " + e.toString(), e); - return new Answer(cmd, false, "VPCLoadBalancerConfigCommand failed due to " + VmwareHelper.getExceptionMessage(e)); + SshHelper.scpTo(routerIp, 3922, "root", keyFile, null, filePath, content.getBytes(), fileName, null); + } catch (Exception e) { + s_logger.warn("Fail to create file " + filePath + fileName + " in VR " + routerIp, e); + return new ExecutionResult(false, e.getMessage()); } + return new ExecutionResult(true, null); } - protected Answer execute(final LoadBalancerConfigCommand cmd) { + @Override + public ExecutionResult prepareCommand(NetworkElementCommand cmd) { + //Update IP used to access router + cmd.setRouterAccessIp(getRouterSshControlIp(cmd)); + assert cmd.getRouterAccessIp() != null; - if (cmd.getVpcId() != null) { - return VPCLoadBalancerConfig(cmd); - } - - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - File keyFile = mgr.getSystemVMKeyFile(); - - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - String controlIp = getRouterSshControlIp(cmd); - - assert (controlIp != null); - - LoadBalancerConfigurator cfgtr = new HAProxyConfigurator(); - String[] config = cfgtr.generateConfiguration(cmd); - - String[][] rules = cfgtr.generateFwRules(cmd); - String tmpCfgFilePath = "/tmp/" + routerIp.replace('.', '_') + ".cfg"; - String tmpCfgFileContents = ""; - for (int i = 0; i < config.length; i++) { - tmpCfgFileContents += config[i]; - tmpCfgFileContents += "\n"; - } - - try { - SshHelper.scpTo(controlIp, DEFAULT_DOMR_SSHPORT, "root", keyFile, null, "/tmp/", tmpCfgFileContents.getBytes(), routerIp.replace('.', '_') + ".cfg", null); - - try { - String[] addRules = rules[LoadBalancerConfigurator.ADD]; - String[] removeRules = rules[LoadBalancerConfigurator.REMOVE]; - String[] statRules = rules[LoadBalancerConfigurator.STATS]; - - String args = ""; - args += "-i " + routerIp; - args += " -f " + tmpCfgFilePath; - - StringBuilder sb = new StringBuilder(); - if (addRules.length > 0) { - for (int i = 0; i < addRules.length; i++) { - sb.append(addRules[i]).append(','); - } - - args += " -a " + sb.toString(); - } - - sb = new StringBuilder(); - if (removeRules.length > 0) { - for (int i = 0; i < removeRules.length; i++) { - sb.append(removeRules[i]).append(','); - } - - args += " -d " + sb.toString(); - } - - sb = new StringBuilder(); - if (statRules.length > 0) { - for (int i = 0; i < statRules.length; i++) { - sb.append(statRules[i]).append(','); - } - - args += " -s " + sb.toString(); - } - - Pair result = - SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "scp " + tmpCfgFilePath + - " /etc/haproxy/haproxy.cfg.new"); - - if (!result.first()) { - s_logger.error("Unable to copy haproxy configuration file"); - return new Answer(cmd, false, "LoadBalancerConfigCommand failed due to uanble to copy haproxy configuration file"); - } - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Run command on domain router " + routerIp + ", /root/loadbalancer.sh " + args); - } - - result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/loadbalancer.sh " + args); - - if (!result.first()) { - String msg = "LoadBalancerConfigCommand on domain router " + routerIp + " failed. message: " + result.second(); - s_logger.error(msg); - - return new Answer(cmd, false, msg); - } - - if (s_logger.isInfoEnabled()) { - s_logger.info("LoadBalancerConfigCommand on domain router " + routerIp + " completed"); - } - } finally { - SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "rm " + tmpCfgFilePath); - } - - return new Answer(cmd); - } catch (Throwable e) { - s_logger.error("Unexpected exception: " + e.toString(), e); - return new Answer(cmd, false, "LoadBalancerConfigCommand failed due to " + VmwareHelper.getExceptionMessage(e)); + if (cmd instanceof IpAssocVpcCommand) { + return prepareNetworkElementCommand((IpAssocVpcCommand)cmd); + } else if (cmd instanceof IpAssocCommand) { + return prepareNetworkElementCommand((IpAssocCommand)cmd); + } else if (cmd instanceof SetSourceNatCommand) { + return prepareNetworkElementCommand((SetSourceNatCommand)cmd); + } else if (cmd instanceof SetupGuestNetworkCommand) { + return prepareNetworkElementCommand((SetupGuestNetworkCommand)cmd); + } else if (cmd instanceof SetNetworkACLCommand) { + return prepareNetworkElementCommand((SetNetworkACLCommand)cmd); } + return new ExecutionResult(true, null); } - // - // list available ethx devices - // ls /proc/sys/net/ipv4/conf - // - private int allocRouterEthDeviceIndex(String domrName, String routerIp) throws Exception { - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - - Pair result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "ls /proc/sys/net/ipv4/conf"); - - if (result.first()) { - String[] tokens = result.second().split("\\s+"); - HashMap deviceNames = new HashMap(); - for (String token : tokens) { - if (!("all".equalsIgnoreCase(token) || "default".equalsIgnoreCase(token) || "lo".equalsIgnoreCase(token))) { - deviceNames.put(token, token); - } - } - - for (int i = 1;; i++) { - if (!deviceNames.containsKey("eth" + i)) - return i; - } - } - - return -1; + @Override + public ExecutionResult cleanupCommand(NetworkElementCommand cmd) { + return new ExecutionResult(true, null); } - // - // find mac address of a specified ethx device - // ip address show ethx | grep link/ether | sed -e 's/^[ \t]*//' | cut -d' ' -f2 - // returns - // eth0:xx.xx.xx.xx - // // list IP with eth devices // ifconfig ethx |grep -B1 "inet addr" | awk '{ if ( $1 == "inet" ) { print $2 } else if ( $2 == "Link" ) { printf "%s:" ,$1 } }' @@ -1273,7 +714,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa s_logger.info("findRouterEthDeviceIndex. mac: " + mac); // TODO : this is a temporary very inefficient solution, will refactor it later - Pair result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "ls /proc/sys/net/ipv4/conf"); + Pair result = SshHelper.sshExecute(routerIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "ls /proc/sys/net/ipv4/conf"); // when we dynamically plug in a new NIC into virtual router, it may take time to show up in guest OS // we use a waiting loop here as a workaround to synchronize activities in systems @@ -1287,9 +728,9 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa if (s_logger.isDebugEnabled()) s_logger.debug("Run domr script " + cmd); - Pair result2 = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, - // TODO need to find the dev index inside router based on IP address - cmd); + Pair result2 = SshHelper.sshExecute(routerIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, + // TODO need to find the dev index inside router based on IP address + cmd); if (s_logger.isDebugEnabled()) s_logger.debug("result: " + result2.first() + ", output: " + result2.second()); @@ -1323,77 +764,26 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa return null; } - private SetupGuestNetworkAnswer execute(SetupGuestNetworkCommand cmd) { - - s_logger.info("Executing resource SetupGuestNetworkCommand " + _gson.toJson(cmd)); - - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - + protected ExecutionResult prepareNetworkElementCommand(SetupGuestNetworkCommand cmd) { NicTO nic = cmd.getNic(); - String routerIp = getRouterSshControlIp(cmd); - String domrGIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP); - String domrName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); - String gw = cmd.getAccessDetail(NetworkElementCommand.GUEST_NETWORK_GATEWAY); - String cidr = Long.toString(NetUtils.getCidrSize(nic.getNetmask())); - String domainName = cmd.getNetworkDomain(); - String dns = cmd.getDefaultDns1(); - if (dns == null || dns.isEmpty()) { - dns = cmd.getDefaultDns2(); - } else { - String dns2 = cmd.getDefaultDns2(); - if (dns2 != null && !dns2.isEmpty()) { - dns += "," + dns2; - } - } + String domrName = + cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); try { - int ethDeviceNum = findRouterEthDeviceIndex(domrName, routerIp, nic.getMac()); - s_logger.info("find interface index. routerIp: " + routerIp + ", mac: " + nic.getMac() + ", index: " + ethDeviceNum); - - String args = (cmd.isAdd() ? "-C" : "-D"); - String dev = "eth" + ethDeviceNum; - args += " -d " + dev; - args += " -i " + domrGIP; - args += " -g " + gw; - args += " -m " + cidr; - args += " -n " + NetUtils.getSubNet(domrGIP, nic.getNetmask()); - if (dns != null && !dns.isEmpty()) { - args += " -s " + dns; - } - if (domainName != null && !domainName.isEmpty()) { - args += " -e " + domainName; - } - - Pair result = - SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_guestnw.sh " + args); - - if (!result.first()) { - String msg = "SetupGuestNetworkCommand on domain router " + routerIp + " failed. message: " + result.second(); - s_logger.error(msg); - - return new SetupGuestNetworkAnswer(cmd, false, msg); - } - - if (s_logger.isInfoEnabled()) { - s_logger.info("SetupGuestNetworkCommand on domain router " + routerIp + " completed"); - } - - return new SetupGuestNetworkAnswer(cmd, true, "success"); + int ethDeviceNum = findRouterEthDeviceIndex(domrName, routerIp, + nic.getMac()); + nic.setDeviceId(ethDeviceNum); } catch (Exception e) { - String msg = "SetupGuestNetwork failed due to " + e.toString(); + String msg = "Prepare SetupGuestNetwork failed due to " + e.toString(); s_logger.warn(msg, e); - return new SetupGuestNetworkAnswer(cmd, false, msg); + return new ExecutionResult(false, msg); } + return new ExecutionResult(true, null); } - protected IpAssocAnswer execute(IpAssocVpcCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource IpAssocVpcCommand " + _gson.toJson(cmd)); - } - String[] results = new String[cmd.getIpAddresses().length]; - int i = 0; + private ExecutionResult prepareNetworkElementCommand(IpAssocVpcCommand cmd) { String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); String routerIp = getRouterSshControlIp(cmd); @@ -1401,229 +791,58 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa IpAddressTO[] ips = cmd.getIpAddresses(); for (IpAddressTO ip : ips) { - assignVPCPublicIpAddress(routerName, routerIp, ip); - results[i++] = ip.getPublicIp() + " - success"; + int ethDeviceNum = findRouterEthDeviceIndex(routerName, routerIp, ip.getVifMacAddress()); + if (ethDeviceNum < 0) { + if (ip.isAdd()) { + throw new InternalErrorException("Failed to find DomR VIF to associate/disassociate IP with."); + } else { + s_logger.debug("VIF to deassociate IP with does not exist, return success"); + continue; + } + } + + ip.setNicDevId(ethDeviceNum); } } catch (Exception e) { - s_logger.error("Ip Assoc failure on applying one ip due to exception: ", e); - results[i++] = IpAssocAnswer.errorResult; + s_logger.error("Prepare Ip Assoc failure on applying one ip due to exception: ", e); + return new ExecutionResult(false, e.toString()); } - return new IpAssocAnswer(cmd, results); + return new ExecutionResult(true, null); } - protected SetSourceNatAnswer execute(SetSourceNatCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource SetSourceNatCommand " + _gson.toJson(cmd)); - } - - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - + protected ExecutionResult prepareNetworkElementCommand(SetSourceNatCommand cmd) { String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); String routerIp = getRouterSshControlIp(cmd); IpAddressTO pubIp = cmd.getIpAddress(); + try { int ethDeviceNum = findRouterEthDeviceIndex(routerName, routerIp, pubIp.getVifMacAddress()); - String args = ""; - args += " -A "; - args += " -l "; - args += pubIp.getPublicIp(); - - args += " -c "; - args += "eth" + ethDeviceNum; - - Pair result = - SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_snat.sh " + args); - - if (!result.first()) { - String msg = "SetupGuestNetworkCommand on domain router " + routerIp + " failed. message: " + result.second(); - s_logger.error(msg); - - return new SetSourceNatAnswer(cmd, false, msg); - } - - return new SetSourceNatAnswer(cmd, true, "success"); + pubIp.setNicDevId(ethDeviceNum); } catch (Exception e) { - String msg = "Ip SNAT failure due to " + e.toString(); + String msg = "Prepare Ip SNAT failure due to " + e.toString(); s_logger.error(msg, e); - return new SetSourceNatAnswer(cmd, false, msg); + return new ExecutionResult(false, e.toString()); } + return new ExecutionResult(true, null); } - private SetNetworkACLAnswer execute(SetNetworkACLCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource SetNetworkACLCommand " + _gson.toJson(cmd)); - } - - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); - String privateGw = cmd.getAccessDetail(NetworkElementCommand.VPC_PRIVATE_GATEWAY); + private ExecutionResult prepareNetworkElementCommand(SetNetworkACLCommand cmd) { + NicTO nic = cmd.getNic(); + String routerName = + cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); String routerIp = getRouterSshControlIp(cmd); - String[] results = new String[cmd.getRules().length]; try { - String[][] rules = cmd.generateFwRules(); - StringBuilder sb = new StringBuilder(); - String[] aclRules = rules[0]; - if (aclRules.length == 0) { - return new SetNetworkACLAnswer(cmd, true, results); - } - - for (int i = 0; i < aclRules.length; i++) { - sb.append(aclRules[i]).append(','); - } - - NicTO nic = cmd.getNic(); - int ethDeviceNum = findRouterEthDeviceIndex(routerName, routerIp, nic.getMac()); - String args = ""; - Pair result; - - if (privateGw != null) { - s_logger.debug("Private gateway configuration is set"); - args += " -d " + "eth" + ethDeviceNum; - args += " -a " + sb.toString(); - result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_privategw_acl.sh " + args); - - if (!result.first()) { - String msg = "SetNetworkACLAnswer on domain router " + routerIp + " failed. message: " + result.second(); - s_logger.error(msg); - return new SetNetworkACLAnswer(cmd, false, results); - } - } else { - args = ""; - args += " -d " + "eth" + ethDeviceNum; - args += " -i " + nic.getIp(); - args += " -m " + Long.toString(NetUtils.getCidrSize(nic.getNetmask())); - args += " -a " + sb.toString(); - - result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_acl.sh " + args); - - if (!result.first()) { - String msg = "SetNetworkACLAnswer on domain router " + routerIp + " failed. message: " + result.second(); - s_logger.error(msg); - - return new SetNetworkACLAnswer(cmd, false, results); - } - } - - return new SetNetworkACLAnswer(cmd, true, results); + int ethDeviceNum = findRouterEthDeviceIndex(routerName, routerIp, + nic.getMac()); + nic.setDeviceId(ethDeviceNum); } catch (Exception e) { - String msg = "SetNetworkACL failed due to " + e.toString(); + String msg = "Prepare SetNetworkACL failed due to " + e.toString(); s_logger.error(msg, e); - return new SetNetworkACLAnswer(cmd, false, results); + return new ExecutionResult(false, msg); } - } - - protected SetPortForwardingRulesAnswer execute(SetPortForwardingRulesVpcCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource SetPortForwardingRulesVpcCommand " + _gson.toJson(cmd)); - } - - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - - String routerIp = getRouterSshControlIp(cmd); - - String[] results = new String[cmd.getRules().length]; - int i = 0; - - boolean endResult = true; - for (PortForwardingRuleTO rule : cmd.getRules()) { - String args = ""; - args += rule.revoked() ? " -D" : " -A"; - args += " -P " + rule.getProtocol().toLowerCase(); - args += " -l " + rule.getSrcIp(); - args += " -p " + rule.getStringSrcPortRange(); - args += " -r " + rule.getDstIp(); - args += " -d " + rule.getStringDstPortRange().replace(":", "-"); - - try { - Pair sshResult = - SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_portforwarding.sh " + args); - - if (!sshResult.first()) { - results[i++] = "Failed"; - endResult = false; - } else { - results[i++] = null; - } - } catch (Exception e) { - results[i++] = "Failed"; - endResult = false; - } - } - return new SetPortForwardingRulesAnswer(cmd, results, endResult); - } - - protected Answer execute(Site2SiteVpnCfgCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource Site2SiteVpnCfgCommand " + _gson.toJson(cmd)); - } - - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - - String routerIp = getRouterSshControlIp(cmd); - - String args = ""; - if (cmd.isCreate()) { - args += " -A"; - args += " -l "; - args += cmd.getLocalPublicIp(); - args += " -n "; - args += cmd.getLocalGuestCidr(); - args += " -g "; - args += cmd.getLocalPublicGateway(); - args += " -r "; - args += cmd.getPeerGatewayIp(); - args += " -N "; - args += cmd.getPeerGuestCidrList(); - args += " -e "; - args += "\"" + cmd.getEspPolicy() + "\""; - args += " -i "; - args += "\"" + cmd.getIkePolicy() + "\""; - args += " -t "; - args += Long.toString(cmd.getIkeLifetime()); - args += " -T "; - args += Long.toString(cmd.getEspLifetime()); - args += " -s "; - args += "\"" + cmd.getIpsecPsk() + "\""; - args += " -d "; - if (cmd.getDpd()) { - args += "1"; - } else { - args += "0"; - } - if (cmd.isPassive()) { - args += " -p "; - } - } else { - args += " -D"; - args += " -r "; - args += cmd.getPeerGatewayIp(); - args += " -n "; - args += cmd.getLocalGuestCidr(); - args += " -N "; - args += cmd.getPeerGuestCidrList(); - } - - Pair result; - try { - result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/ipsectunnel.sh " + args); - - if (!result.first()) { - s_logger.error("Setup site2site VPN " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " + result.second()); - - return new Answer(cmd, false, "Setup site2site VPN falied due to " + result.second()); - } - - if (s_logger.isDebugEnabled()) { - s_logger.debug("setup site 2 site vpn on router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " completed"); - } - } catch (Throwable e) { - String msg = "Setup site2site VPN falied due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg, e); - return new Answer(cmd, false, "Setup site2site VPN failed due to " + VmwareHelper.getExceptionMessage(e)); - } - return new Answer(cmd, true, result.second()); + return new ExecutionResult(true, null); } private PlugNicAnswer execute(PlugNicCommand cmd) { @@ -1658,7 +877,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa s_logger.debug(errMsg); return new PlugNicAnswer(cmd, false, "Unable to execute PlugNicCommand due to " + errMsg); } - */ + */ // TODO need a way to specify the control of NIC device type VirtualEthernetCardType nicDeviceType = VirtualEthernetCardType.E1000; @@ -1682,13 +901,13 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa dvSwitchUuid = dataCenterMo.getDvSwitchUuid(dvsMor); s_logger.info("Preparing NIC device on dvSwitch : " + dvSwitchUuid); nic = - VmwareHelper.prepareDvNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), dvSwitchUuid, nicTo.getMac(), deviceNumber, - deviceNumber + 1, true, true); + VmwareHelper.prepareDvNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), dvSwitchUuid, nicTo.getMac(), deviceNumber, + deviceNumber + 1, true, true); } else { s_logger.info("Preparing NIC device on network " + networkInfo.second()); nic = - VmwareHelper.prepareNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), nicTo.getMac(), deviceNumber, deviceNumber + 1, true, - true); + VmwareHelper.prepareNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), nicTo.getMac(), deviceNumber, deviceNumber + 1, true, + true); } VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); @@ -1740,7 +959,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa s_logger.debug(errMsg); return new UnPlugNicAnswer(cmd, false, "Unable to execute unPlugNicCommand due to " + errMsg); } - */ + */ VirtualDevice nic = findVirtualNicDevice(vmMo, cmd.getNic().getMac()); if (nic == null) { return new UnPlugNicAnswer(cmd, true, "success"); @@ -1763,185 +982,6 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } } - protected void assignVPCPublicIpAddress(String domrName, String routerIp, IpAddressTO ip) throws Exception { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource assignVPCPublicIpAddress. domrName: " + domrName + ", routerIp: " + routerIp + ", ip: " + _gson.toJson(ip)); - } - - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - - int ethDeviceNum = findRouterEthDeviceIndex(domrName, routerIp, ip.getVifMacAddress()); - if (ethDeviceNum < 0) { - if (ip.isAdd()) { - throw new InternalErrorException("Failed to find DomR VIF to associate/disassociate IP with."); - } else { - s_logger.debug("VIF to deassociate IP with does not exist, return success"); - return; - } - } - - String args = ""; - String snatArgs = ""; - - if (ip.isAdd()) { - args += " -A "; - snatArgs += " -A "; - } else { - args += " -D "; - snatArgs += " -D "; - } - - args += " -l "; - args += ip.getPublicIp(); - - args += " -c "; - args += "eth" + ethDeviceNum; - - args += " -g "; - args += ip.getVlanGateway(); - - args += " -m "; - args += Long.toString(NetUtils.getCidrSize(ip.getVlanNetmask())); - - args += " -n "; - args += NetUtils.getSubNet(ip.getPublicIp(), ip.getVlanNetmask()); - - Pair result = - SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_ipassoc.sh " + args); - - if (!result.first()) { - throw new InternalErrorException("Unable to assign public IP address"); - } - - if (ip.isSourceNat()) { - snatArgs += " -l "; - snatArgs += ip.getPublicIp(); - snatArgs += " -c "; - snatArgs += "eth" + ethDeviceNum; - - Pair result_gateway = - SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_privateGateway.sh " + snatArgs); - - if (!result_gateway.first()) { - throw new InternalErrorException("Unable to configure source NAT for public IP address."); - } - } - } - - protected void assignPublicIpAddress(VirtualMachineMO vmMo, final String vmName, final String privateIpAddress, final String publicIpAddress, final boolean add, - final boolean firstIP, final boolean sourceNat, final String broadcastId, final String vlanGateway, final String vlanNetmask, final String vifMacAddress) - throws Exception { - - /** - * TODO support other networks - */ - URI broadcastUri = BroadcastDomainType.fromString(broadcastId); - if (BroadcastDomainType.getSchemeValue(broadcastUri) != BroadcastDomainType.Vlan) { - throw new InternalErrorException("Unable to assign a public IP to a VIF on network " + broadcastId); - } - String vlanId = BroadcastDomainType.getValue(broadcastUri); - - String publicNeworkName = HypervisorHostHelper.getPublicNetworkNamePrefix(vlanId); - Pair publicNicInfo = vmMo.getNicDeviceIndex(publicNeworkName); - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Find public NIC index, public network name: " + publicNeworkName + ", index: " + publicNicInfo.first()); - } - - boolean addVif = false; - boolean removeVif = false; - if (add && publicNicInfo.first().intValue() == -1) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Plug new NIC to associate" + privateIpAddress + " to " + publicIpAddress); - } - - addVif = true; - } else if (!add && firstIP) { - removeVif = true; - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Unplug NIC " + publicNicInfo.first()); - } - } - - if (addVif) { - plugPublicNic(vmMo, vlanId, vifMacAddress); - publicNicInfo = vmMo.getNicDeviceIndex(publicNeworkName); - if (publicNicInfo.first().intValue() >= 0) { - networkUsage(privateIpAddress, "addVif", "eth" + publicNicInfo.first()); - } - } - - if (publicNicInfo.first().intValue() < 0) { - String msg = "Failed to find DomR VIF to associate/disassociate IP with."; - s_logger.error(msg); - throw new InternalErrorException(msg); - } - - String args = null; - - if (add) { - args = " -A "; - } else { - args = " -D "; - } - - if (sourceNat) { - args += " -s "; - } - if (firstIP) { - args += " -f "; - } - String cidrSize = Long.toString(NetUtils.getCidrSize(vlanNetmask)); - args += " -l "; - args += publicIpAddress + "/" + cidrSize; - - args += " -c "; - args += "eth" + publicNicInfo.first(); - - args += " -g "; - args += vlanGateway; - - if (addVif) { - args += " -n "; - } - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Run command on domain router " + privateIpAddress + ", /opt/cloud/bin/ipassoc.sh " + args); - } - - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - Pair result = - SshHelper.sshExecute(privateIpAddress, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/ipassoc.sh " + args); - - if (!result.first()) { - s_logger.error("ipassoc command on domain router " + privateIpAddress + " failed. message: " + result.second()); - throw new Exception("ipassoc failed due to " + result.second()); - } - - if (removeVif) { - - String nicMasksStr = vmMo.getCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK); - int nicMasks = Integer.parseInt(nicMasksStr); - nicMasks &= ~(1 << publicNicInfo.first().intValue()); - vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK, String.valueOf(nicMasks)); - - HostMO hostMo = vmMo.getRunningHost(); - List networks = vmMo.getNetworksWithDetails(); - for (NetworkDetails netDetails : networks) { - if (netDetails.getGCTag() != null && netDetails.getGCTag().equalsIgnoreCase("true")) { - if (netDetails.getVMMorsOnNetwork() == null || netDetails.getVMMorsOnNetwork().length == 1) { - cleanupNetwork(hostMo, netDetails); - } - } - } - } - - if (s_logger.isInfoEnabled()) { - s_logger.info("ipassoc command on domain router " + privateIpAddress + " completed"); - } - } - private void plugPublicNic(VirtualMachineMO vmMo, final String vlanId, final String vifMacAddress) throws Exception { // TODO : probably need to set traffic shaping Pair networkInfo = null; @@ -1955,13 +995,13 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa if (VirtualSwitchType.StandardVirtualSwitch == vSwitchType) { synchronized (vmMo.getRunningHost().getMor().getValue().intern()) { networkInfo = - HypervisorHostHelper.prepareNetwork(_publicTrafficInfo.getVirtualSwitchName(), "cloud.public", vmMo.getRunningHost(), vlanId, null, null, - _ops_timeout, true, BroadcastDomainType.Vlan, null); + HypervisorHostHelper.prepareNetwork(_publicTrafficInfo.getVirtualSwitchName(), "cloud.public", vmMo.getRunningHost(), vlanId, null, null, + _opsTimeout, true, BroadcastDomainType.Vlan, null); } } else { networkInfo = - HypervisorHostHelper.prepareNetwork(_publicTrafficInfo.getVirtualSwitchName(), "cloud.public", vmMo.getRunningHost(), vlanId, null, null, null, - _ops_timeout, vSwitchType, _portsPerDvPortGroup, null, false, BroadcastDomainType.Vlan); + HypervisorHostHelper.prepareNetwork(_publicTrafficInfo.getVirtualSwitchName(), "cloud.public", vmMo.getRunningHost(), vlanId, null, null, null, + _opsTimeout, vSwitchType, _portsPerDvPortGroup, null, false, BroadcastDomainType.Vlan); } int nicIndex = allocPublicNicIndex(vmMo); @@ -2024,11 +1064,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa throw new Exception("Could not allocate a free public NIC"); } - protected Answer execute(IpAssocCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource IPAssocCommand: " + _gson.toJson(cmd)); - } - + private ExecutionResult prepareNetworkElementCommand(IpAssocCommand cmd) { int i = 0; String[] results = new String[cmd.getIpAddresses().length]; @@ -2058,450 +1094,158 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } for (IpAddressTO ip : ips) { - assignPublicIpAddress(vmMo, routerName, controlIp, ip.getPublicIp(), ip.isAdd(), ip.isFirstIP(), ip.isSourceNat(), ip.getBroadcastUri(), - ip.getVlanGateway(), ip.getVlanNetmask(), ip.getVifMacAddress()); - results[i++] = ip.getPublicIp() + " - success"; + /** + * TODO support other networks + */ + URI broadcastUri = BroadcastDomainType.fromString(ip.getBroadcastUri()); + if (BroadcastDomainType.getSchemeValue(broadcastUri) != BroadcastDomainType.Vlan) { + throw new InternalErrorException("Unable to assign a public IP to a VIF on network " + ip.getBroadcastUri()); + } + String vlanId = BroadcastDomainType.getValue(broadcastUri); + + String publicNeworkName = HypervisorHostHelper.getPublicNetworkNamePrefix(vlanId); + Pair publicNicInfo = vmMo.getNicDeviceIndex(publicNeworkName); + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Find public NIC index, public network name: " + publicNeworkName + ", index: " + publicNicInfo.first()); + } + + boolean addVif = false; + if (ip.isAdd() && publicNicInfo.first().intValue() == -1) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Plug new NIC to associate" + controlIp + " to " + ip.getPublicIp()); + } + addVif = true; + } + + if (addVif) { + plugPublicNic(vmMo, vlanId, ip.getVifMacAddress()); + publicNicInfo = vmMo.getNicDeviceIndex(publicNeworkName); + if (publicNicInfo.first().intValue() >= 0) { + networkUsage(controlIp, "addVif", "eth" + publicNicInfo.first()); + } + } + + if (publicNicInfo.first().intValue() < 0) { + String msg = "Failed to find DomR VIF to associate/disassociate IP with."; + s_logger.error(msg); + throw new InternalErrorException(msg); + } + ip.setNicDevId(publicNicInfo.first().intValue()); + ip.setNewNic(addVif); } } catch (Throwable e) { s_logger.error("Unexpected exception: " + e.toString() + " will shortcut rest of IPAssoc commands", e); - - for (; i < cmd.getIpAddresses().length; i++) { - results[i++] = IpAssocAnswer.errorResult; - } + return new ExecutionResult(false, e.toString()); } - - return new IpAssocAnswer(cmd, results); + return new ExecutionResult(true, null); } - protected Answer execute(SavePasswordCommand cmd) { - if (s_logger.isInfoEnabled()) { - - s_logger.info("Executing resource SavePasswordCommand. vmName: " + cmd.getVmName() + ", vmIp: " + cmd.getVmIpAddress() + ", password: " + - StringUtils.getMaskedPasswordForDisplay(cmd.getPassword())); - } - - String controlIp = getRouterSshControlIp(cmd); - final String password = cmd.getPassword(); - final String vmIpAddress = cmd.getVmIpAddress(); - - // Run save_password_to_domr.sh - String args = " -v " + vmIpAddress; - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Run command on domain router " + controlIp + ", /opt/cloud/bin/savepassword.sh " + args + " -p " + - StringUtils.getMaskedPasswordForDisplay(cmd.getPassword())); - } - - args += " -p " + password; + private ExecutionResult NetworkElementCommandnup(IpAssocCommand cmd) { + String[] results = new String[cmd.getIpAddresses().length]; + VmwareContext context = getServiceContext(); try { - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - Pair result = - SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/savepassword.sh " + args); + VmwareHypervisorHost hyperHost = getHyperHost(context); - if (!result.first()) { - s_logger.error("savepassword command on domain router " + controlIp + " failed, message: " + result.second()); + IpAddressTO[] ips = cmd.getIpAddresses(); + String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); + String controlIp = VmwareResource.getRouterSshControlIp(cmd); - return new Answer(cmd, false, "SavePassword failed due to " + result.second()); - } + VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(routerName); - if (s_logger.isInfoEnabled()) { - s_logger.info("savepassword command on domain router " + controlIp + " completed"); - } - - } catch (Throwable e) { - String msg = "SavePasswordCommand failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg, e); - return new Answer(cmd, false, msg); - } - return new Answer(cmd); - } - - protected Answer execute(DhcpEntryCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource DhcpEntryCommand: " + _gson.toJson(cmd)); - } - - // ssh -p 3922 -o StrictHostKeyChecking=no -i $cert root@$domr "/root/edithosts.sh $mac $ip $vm $dfltrt $ns $staticrt" >/dev/null - - String args = " -m " + cmd.getVmMac(); - if (cmd.getVmIpAddress() != null) { - args += " -4 " + cmd.getVmIpAddress(); - } - args += " -h " + cmd.getVmName(); - - if (cmd.getDefaultRouter() != null) { - args += " -d " + cmd.getDefaultRouter(); - } - - if (cmd.getDefaultDns() != null) { - args += " -n " + cmd.getDefaultDns(); - } - - if (cmd.getStaticRoutes() != null) { - args += " -s " + cmd.getStaticRoutes(); - } - - if (cmd.getVmIp6Address() != null) { - args += " -6 " + cmd.getVmIp6Address(); - args += " -u " + cmd.getDuid(); - } - - if (!cmd.isDefault()) { - args += " -N"; - } - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /root/edithosts.sh " + args); - } - - try { - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - String controlIp = getRouterSshControlIp(cmd); - Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/edithosts.sh " + args); - - if (!result.first()) { - s_logger.error("dhcp_entry command on domR " + controlIp + " failed, message: " + result.second()); - - return new Answer(cmd, false, "DhcpEntry failed due to " + result.second()); - } - - if (s_logger.isInfoEnabled()) { - s_logger.info("dhcp_entry command on domain router " + controlIp + " completed"); - } - - } catch (Throwable e) { - String msg = "DhcpEntryCommand failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg, e); - return new Answer(cmd, false, msg); - } - - return new Answer(cmd); - } - - protected Answer execute(final CreateIpAliasCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing createIpAlias command: " + _gson.toJson(cmd)); - } - cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - List ipAliasTOs = cmd.getIpAliasList(); - String args = ""; - for (IpAliasTO ipaliasto : ipAliasTOs) { - args = args + ipaliasto.getAlias_count() + ":" + ipaliasto.getRouterip() + ":" + ipaliasto.getNetmask() + "-"; - } - if (s_logger.isDebugEnabled()) { - s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /root/createIpAlias " + args); - } - - try { - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - String controlIp = getRouterSshControlIp(cmd); - Pair result = - SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/createIpAlias.sh " + args); - - if (!result.first()) { - s_logger.error("CreateIpAlias command on domr " + controlIp + " failed, message: " + result.second()); - - return new Answer(cmd, false, "createipAlias failed due to " + result.second()); - } - - if (s_logger.isInfoEnabled()) { - s_logger.info("createIpAlias command on domain router " + controlIp + " completed"); - } - - } catch (Throwable e) { - String msg = "createIpAlias failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg, e); - return new Answer(cmd, false, msg); - } - - return new Answer(cmd); - } - - protected Answer execute(final DeleteIpAliasCommand cmd) { - cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - List revokedIpAliasTOs = cmd.getDeleteIpAliasTos(); - List activeIpAliasTOs = cmd.getCreateIpAliasTos(); - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing deleteIpAlias command: " + _gson.toJson(cmd)); - } - String args = ""; - for (IpAliasTO ipAliasTO : revokedIpAliasTOs) { - args = args + ipAliasTO.getAlias_count() + ":" + ipAliasTO.getRouterip() + ":" + ipAliasTO.getNetmask() + "-"; - } - args = args + "- "; - for (IpAliasTO ipAliasTO : activeIpAliasTOs) { - args = args + ipAliasTO.getAlias_count() + ":" + ipAliasTO.getRouterip() + ":" + ipAliasTO.getNetmask() + "-"; - } - if (s_logger.isDebugEnabled()) { - s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /root/deleteIpAlias " + args); - } - - try { - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - String controlIp = getRouterSshControlIp(cmd); - Pair result = - SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/deleteIpAlias.sh " + args); - - if (!result.first()) { - s_logger.error("deleteIpAlias command on domr " + controlIp + " failed, message: " + result.second()); - - return new Answer(cmd, false, "deleteIpAlias failed due to " + result.second()); - } - - if (s_logger.isInfoEnabled()) { - s_logger.info("deleteIpAlias command on domain router " + controlIp + " completed"); - } - - } catch (Throwable e) { - String msg = "deleteIpAlias failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg, e); - return new Answer(cmd, false, msg); - } - - return new Answer(cmd); - } - - protected Answer execute(final DnsMasqConfigCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing dnsmasqConfig command: " + _gson.toJson(cmd)); - } - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - String controlIp = getRouterSshControlIp(cmd); - - assert (controlIp != null); - - List dhcpTos = cmd.getIps(); - String args = ""; - for (DhcpTO dhcpTo : dhcpTos) { - args = args + dhcpTo.getRouterIp() + ":" + dhcpTo.getGateway() + ":" + dhcpTo.getNetmask() + ":" + dhcpTo.getStartIpOfSubnet() + "-"; - } - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - File keyFile = mgr.getSystemVMKeyFile(); - - try { - Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/dnsmasq.sh " + args); - if (s_logger.isDebugEnabled()) { - s_logger.debug("Run command on domain router " + routerIp + ", /root/dnsmasq.sh"); - } - - if (!result.first()) { - s_logger.error("Unable update dnsmasq config file"); - return new Answer(cmd, false, "dnsmasq config update failed due to: " + result.second()); - } - - if (s_logger.isDebugEnabled()) { - s_logger.debug("dnsmasq config command on domain router " + routerIp + " completed"); - } - } catch (Throwable e) { - String msg = "Dnsmasqconfig command failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg, e); - return new Answer(cmd, false, msg); - } - - return new Answer(cmd); - } - - protected CheckS2SVpnConnectionsAnswer execute(CheckS2SVpnConnectionsCommand cmd) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Executing resource CheckS2SVpnConnectionsCommand: " + _gson.toJson(cmd)); - s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /opt/cloud/bin/checkbatchs2svpn.sh "); - } - - Pair result; - try { - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - String controlIp = getRouterSshControlIp(cmd); - String cmdline = "/opt/cloud/bin/checkbatchs2svpn.sh "; - for (String ip : cmd.getVpnIps()) { - cmdline += " " + ip; - } - - result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, cmdline); - - if (!result.first()) { - s_logger.error("check site-to-site vpn connections command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " + - result.second()); - - return new CheckS2SVpnConnectionsAnswer(cmd, false, result.second()); - } - - if (s_logger.isDebugEnabled()) { - s_logger.debug("check site-to-site vpn connections command on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " completed"); - } - } catch (Throwable e) { - String msg = "CheckS2SVpnConnectionsCommand failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg, e); - return new CheckS2SVpnConnectionsAnswer(cmd, false, "CheckS2SVpnConneciontsCommand failed"); - } - return new CheckS2SVpnConnectionsAnswer(cmd, true, result.second()); - } - - protected Answer execute(CheckRouterCommand cmd) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Executing resource CheckRouterCommand: " + _gson.toJson(cmd)); - s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /opt/cloud/bin/checkrouter.sh "); - } - - Pair result; - try { - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - String controlIp = getRouterSshControlIp(cmd); - result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/checkrouter.sh "); - - if (!result.first()) { - s_logger.error("check router command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " + result.second()); - - return new CheckRouterAnswer(cmd, "CheckRouter failed due to " + result.second()); - } - - if (s_logger.isDebugEnabled()) { - s_logger.debug("check router command on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " completed"); - } - } catch (Throwable e) { - String msg = "CheckRouterCommand failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg, e); - return new CheckRouterAnswer(cmd, msg); - } - return new CheckRouterAnswer(cmd, result.second(), true); - } - - protected Answer execute(GetDomRVersionCmd cmd) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Executing resource GetDomRVersionCmd: " + _gson.toJson(cmd)); - s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /opt/cloud/bin/get_template_version.sh "); - } - - Pair result; - try { - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - String controlIp = getRouterSshControlIp(cmd); - result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/get_template_version.sh "); - - if (!result.first()) { - s_logger.error("GetDomRVersionCmd on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " + result.second()); - - return new GetDomRVersionAnswer(cmd, "GetDomRVersionCmd failed due to " + result.second()); - } - - if (s_logger.isDebugEnabled()) { - s_logger.debug("GetDomRVersionCmd on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " completed"); - } - } catch (Throwable e) { - String msg = "GetDomRVersionCmd failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg, e); - return new GetDomRVersionAnswer(cmd, msg); - } - String[] lines = result.second().split("&"); - if (lines.length != 2) { - return new GetDomRVersionAnswer(cmd, result.second()); - } - return new GetDomRVersionAnswer(cmd, result.second(), lines[0], lines[1]); - } - - protected Answer execute(BumpUpPriorityCommand cmd) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Executing resource BumpUpPriorityCommand: " + _gson.toJson(cmd)); - s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /root/bumpup_priority.sh "); - } - - Pair result; - try { - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - String controlIp = getRouterSshControlIp(cmd); - result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/bumpup_priority.sh "); - - if (!result.first()) { - s_logger.error("BumpUpPriority command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " + result.second()); - - return new Answer(cmd, false, "BumpUpPriorityCommand failed due to " + result.second()); - } - - if (s_logger.isDebugEnabled()) { - s_logger.debug("BumpUpPriorityCommand on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " completed"); - } - } catch (Throwable e) { - String msg = "BumpUpPriorityCommand failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg, e); - return new Answer(cmd, false, msg); - } - if (result.second() == null || result.second().isEmpty()) { - return new Answer(cmd, true, result.second()); - } - return new Answer(cmd, false, result.second()); - } - - protected Answer execute(VmDataCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource VmDataCommand: " + _gson.toJson(cmd)); - } - - String routerPrivateIpAddress = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - String controlIp = getRouterSshControlIp(cmd); - - String vmIpAddress = cmd.getVmIpAddress(); - List vmData = cmd.getVmData(); - String[] vmDataArgs = new String[vmData.size() * 2 + 4]; - vmDataArgs[0] = "routerIP"; - vmDataArgs[1] = routerPrivateIpAddress; - vmDataArgs[2] = "vmIP"; - vmDataArgs[3] = vmIpAddress; - int i = 4; - for (String[] vmDataEntry : vmData) { - String folder = vmDataEntry[0]; - String file = vmDataEntry[1]; - String contents = (vmDataEntry[2] != null) ? vmDataEntry[2] : "none"; - - vmDataArgs[i] = folder + "," + file; - vmDataArgs[i + 1] = contents; - i += 2; - } - - String content = encodeDataArgs(vmDataArgs); - String tmpFileName = UUID.randomUUID().toString(); - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Run vm_data command on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", data: " + content); - } - - try { - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - SshHelper.scpTo(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/tmp", content.getBytes(), tmpFileName, null); - - try { - Pair result = - SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/userdata.py " + tmpFileName); - - if (!result.first()) { - s_logger.error("vm_data command on domain router " + controlIp + " failed. messge: " + result.second()); - return new Answer(cmd, false, "VmDataCommand failed due to " + result.second()); + // command may sometimes be redirect to a wrong host, we relax + // the check and will try to find it within cluster + if (vmMo == null) { + if (hyperHost instanceof HostMO) { + ClusterMO clusterMo = new ClusterMO(hyperHost.getContext(), ((HostMO)hyperHost).getParentMor()); + vmMo = clusterMo.findVmOnHyperHost(routerName); } - } finally { - - SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "rm /tmp/" + tmpFileName); } - if (s_logger.isInfoEnabled()) { - s_logger.info("vm_data command on domain router " + controlIp + " completed"); + if (vmMo == null) { + String msg = "Router " + routerName + " no longer exists to execute IPAssoc command"; + s_logger.error(msg); + throw new Exception(msg); } + for (IpAddressTO ip : ips) { + /** + * TODO support other networks + */ + URI broadcastUri = BroadcastDomainType.fromString(ip.getBroadcastUri()); + if (BroadcastDomainType.getSchemeValue(broadcastUri) != BroadcastDomainType.Vlan) { + throw new InternalErrorException("Unable to assign a public IP to a VIF on network " + ip.getBroadcastUri()); + } + String vlanId = BroadcastDomainType.getValue(broadcastUri); + + String publicNeworkName = HypervisorHostHelper.getPublicNetworkNamePrefix(vlanId); + Pair publicNicInfo = vmMo.getNicDeviceIndex(publicNeworkName); + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Find public NIC index, public network name: " + publicNeworkName + ", index: " + publicNicInfo.first()); + } + + boolean removeVif = false; + if (!ip.isAdd() && ip.isFirstIP()) { + removeVif = true; + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Unplug NIC " + publicNicInfo.first()); + } + } + + if (publicNicInfo.first().intValue() < 0) { + String msg = "Failed to find DomR VIF to associate/disassociate IP with."; + s_logger.error(msg); + throw new InternalErrorException(msg); + } + + if (removeVif) { + String nicMasksStr = vmMo.getCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK); + int nicMasks = Integer.parseInt(nicMasksStr); + nicMasks &= ~(1 << publicNicInfo.first().intValue()); + vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK, String.valueOf(nicMasks)); + + HostMO hostMo = vmMo.getRunningHost(); + List networks = vmMo.getNetworksWithDetails(); + for (NetworkDetails netDetails : networks) { + if (netDetails.getGCTag() != null && netDetails.getGCTag().equalsIgnoreCase("true")) { + if (netDetails.getVMMorsOnNetwork() == null || netDetails.getVMMorsOnNetwork().length == 1) { + cleanupNetwork(hostMo, netDetails); + } + } + } + } + } } catch (Throwable e) { - String msg = "VmDataCommand failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg, e); - return new Answer(cmd, false, msg); + s_logger.error("Unexpected exception: " + e.toString() + " will shortcut rest of IPAssoc commands", e); + return new ExecutionResult(false, e.toString()); } - return new Answer(cmd); + return new ExecutionResult(true, null); } - private String encodeDataArgs(String[] dataArgs) { - StringBuilder sb = new StringBuilder(); + @Override + public ExecutionResult executeInVR(String routerIP, String script, String args) { + Pair result; - for (String arg : dataArgs) { - sb.append(arg); - sb.append("\n"); + //TODO: Password should be masked, cannot output to log directly + if (s_logger.isDebugEnabled()) { + s_logger.debug("Run command on VR: " + routerIP + ", script: " + script + " with args: " + args); } - return sb.toString(); + try { + VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); + result = SshHelper.sshExecute(routerIP, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/" + script + " " + args); + } catch (Exception e) { + String msg = "Command failed due to " + VmwareHelper.getExceptionMessage(e); + s_logger.error(msg); + result = new Pair(false, msg); + } + if (s_logger.isDebugEnabled()) { + s_logger.debug(script + " execution result: " + result.first().toString()); + } + return new ExecutionResult(result.first(), result.second()); } protected CheckSshAnswer execute(CheckSshCommand cmd) { @@ -2595,7 +1339,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa hotaddMemoryLimitInMb = vmMo.getHotAddMemoryLimitInMb(); if (requestedMaxMemoryInMb > hotaddMemoryLimitInMb) { throw new CloudRuntimeException("Memory of VM " + vmMo.getVmName() + " cannot be scaled to " + requestedMaxMemoryInMb + "MB." + - " Requested memory limit is beyond the hotadd memory limit for this VM at the moment is " + hotaddMemoryLimitInMb + "MB."); + " Requested memory limit is beyond the hotadd memory limit for this VM at the moment is " + hotaddMemoryLimitInMb + "MB."); } // Check increment is multiple of increment size @@ -2607,7 +1351,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa // Check if license supports the feature VmwareHelper.isFeatureLicensed(hyperHost, FeatureKeyConstants.HOTPLUG); VmwareHelper.setVmScaleUpConfig(vmConfigSpec, vmSpec.getCpus(), vmSpec.getMaxSpeed(), vmSpec.getMinSpeed(), (int)requestedMaxMemoryInMb, ramMb, - vmSpec.getLimitCpuUse()); + vmSpec.getLimitCpuUse()); if (!vmMo.configureVm(vmConfigSpec)) { throw new Exception("Unable to execute ScaleVmCommand"); @@ -2645,8 +1389,9 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa DiskTO[] disks = validateDisks(vmSpec.getDisks()); assert (disks.length > 0); NicTO[] nics = vmSpec.getNics(); + Map iqnToPath = new HashMap(); - HashMap> dataStoresDetails = inferDatastoreDetailsFromDiskInfo(hyperHost, context, disks); + HashMap> dataStoresDetails = inferDatastoreDetailsFromDiskInfo(hyperHost, context, disks, iqnToPath, cmd); if ((dataStoresDetails == null) || (dataStoresDetails.isEmpty())) { String msg = "Unable to locate datastore details of the volumes to be attached"; s_logger.error(msg); @@ -2667,7 +1412,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa if (vmMo != null) { s_logger.info("VM " + vmInternalCSName + " already exists, tear down devices for reconfiguration"); if (getVmPowerState(vmMo) != PowerState.PowerOff) - vmMo.safePowerOff(_shutdown_waitMs); + vmMo.safePowerOff(_shutdownWaitMs); // retrieve disk information before we tear down diskInfoBuilder = vmMo.getDiskInfoBuilder(); @@ -2690,7 +1435,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa takeVmFromOtherHyperHost(hyperHost, vmInternalCSName); if (getVmPowerState(vmMo) != PowerState.PowerOff) - vmMo.safePowerOff(_shutdown_waitMs); + vmMo.safePowerOff(_shutdownWaitMs); diskInfoBuilder = vmMo.getDiskInfoBuilder(); hasSnapshot = vmMo.hasSnapshot(); @@ -2700,11 +1445,11 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa vmMo.tearDownDevices(new Class[] {VirtualEthernetCard.class}); vmMo.ensureScsiDeviceController(); } else { - int ramMb = (int)(vmSpec.getMinRam() / (1024 * 1024)); Pair rootDiskDataStoreDetails = null; for (DiskTO vol : disks) { if (vol.getType() == Volume.Type.ROOT) { DataStoreTO primaryStore = vol.getData().getDataStore(); + /** @todo Mike T. update this in 4.4 to support root disks on managed storage */ rootDiskDataStoreDetails = dataStoresDetails.get(primaryStore.getUuid()); } } @@ -2714,12 +1459,12 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa if (rootDiskDataStoreDetails.second().folderExists(String.format("[%s]", rootDiskDataStoreDetails.second().getName()), vmNameOnVcenter)) { s_logger.warn("WARN!!! Folder already exists on datastore for new VM " + vmNameOnVcenter + ", erase it"); rootDiskDataStoreDetails.second().deleteFile(String.format("[%s] %s/", rootDiskDataStoreDetails.second().getName(), vmNameOnVcenter), - dcMo.getMor(), false); + dcMo.getMor(), false); } - if (!hyperHost.createBlankVm(vmNameOnVcenter, vmInternalCSName, vmSpec.getCpus(), vmSpec.getMaxSpeed().intValue(), vmSpec.getMinSpeed(), - vmSpec.getLimitCpuUse(), (int)(vmSpec.getMaxRam() / (1024 * 1024)), ramMb, translateGuestOsIdentifier(vmSpec.getArch(), vmSpec.getOs()).value(), - rootDiskDataStoreDetails.first(), false)) { + if (!hyperHost.createBlankVm(vmNameOnVcenter, vmInternalCSName, vmSpec.getCpus(), vmSpec.getMaxSpeed().intValue(), + getReservedCpuMHZ(vmSpec), vmSpec.getLimitCpuUse(), (int)(vmSpec.getMaxRam() / (1024 * 1024)), getReservedMemoryMb(vmSpec), + translateGuestOsIdentifier(vmSpec.getArch(), vmSpec.getOs()).value(), rootDiskDataStoreDetails.first(), false)) { throw new Exception("Failed to create VM. vmName: " + vmInternalCSName); } } @@ -2743,17 +1488,23 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); - int ramMb = (int)(vmSpec.getMinRam() / (1024 * 1024)); String guestOsId = translateGuestOsIdentifier(vmSpec.getArch(), vmSpec.getOs()).value(); - VmwareHelper.setBasicVmConfig(vmConfigSpec, vmSpec.getCpus(), vmSpec.getMaxSpeed(), vmSpec.getMinSpeed(), (int)(vmSpec.getMaxRam() / (1024 * 1024)), ramMb, - guestOsId, vmSpec.getLimitCpuUse()); + VmwareHelper.setBasicVmConfig(vmConfigSpec, vmSpec.getCpus(), vmSpec.getMaxSpeed(), + getReservedCpuMHZ(vmSpec), (int)(vmSpec.getMaxRam() / (1024 * 1024)), getReservedMemoryMb(vmSpec), + guestOsId, vmSpec.getLimitCpuUse()); // Check for hotadd settings vmConfigSpec.setMemoryHotAddEnabled(vmMo.isMemoryHotAddSupported(guestOsId)); vmConfigSpec.setCpuHotAddEnabled(vmMo.isCpuHotAddSupported(guestOsId)); configNestedHVSupport(vmMo, vmSpec, vmConfigSpec); + // Check for multi-cores per socket settings + String coresPerSocket = vmSpec.getDetails().get("cpu.corespersocket"); + if (coresPerSocket != null) { + vmConfigSpec.setNumCoresPerSocket(NumbersUtil.parseInt(coresPerSocket, 1)); + } + VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[totalChangeDevices]; int i = 0; int ideUnitNumber = 0; @@ -2786,8 +1537,8 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); Pair isoInfo = - VmwareHelper.prepareIsoDevice(vmMo, String.format("[%s] systemvm/%s", secDsMo.getName(), mgr.getSystemVMIsoFileNameOnDatastore()), secDsMo.getMor(), - true, true, ideUnitNumber++, i + 1); + VmwareHelper.prepareIsoDevice(vmMo, String.format("[%s] systemvm/%s", secDsMo.getName(), mgr.getSystemVMIsoFileNameOnDatastore()), secDsMo.getMor(), + true, true, ideUnitNumber++, i + 1); deviceConfigSpecArray[i].setDevice(isoInfo.first()); if (isoInfo.second()) { if (s_logger.isDebugEnabled()) @@ -2817,7 +1568,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); Pair isoInfo = - VmwareHelper.prepareIsoDevice(vmMo, isoDatastoreInfo.first(), isoDatastoreInfo.second(), true, true, ideUnitNumber++, i + 1); + VmwareHelper.prepareIsoDevice(vmMo, isoDatastoreInfo.first(), isoDatastoreInfo.second(), true, true, ideUnitNumber++, i + 1); deviceConfigSpecArray[i].setDevice(isoInfo.first()); if (isoInfo.second()) { if (s_logger.isDebugEnabled()) @@ -2865,20 +1616,35 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa VolumeObjectTO volumeTO = (VolumeObjectTO)vol.getData(); DataStoreTO primaryStore = volumeTO.getDataStore(); - Pair volumeDsDetails = dataStoresDetails.get(primaryStore.getUuid()); + Map details = vol.getDetails(); + boolean managed = false; + String iScsiName = null; + + if (details != null) { + managed = Boolean.parseBoolean(details.get(DiskTO.MANAGED)); + iScsiName = details.get(DiskTO.IQN); + } + + // if the storage is managed, iScsiName should not be null + String datastoreName = managed ? VmwareResource.getDatastoreName(iScsiName) : primaryStore.getUuid(); + Pair volumeDsDetails = dataStoresDetails.get(datastoreName); + assert (volumeDsDetails != null); - String[] diskChain = syncDiskChain(dcMo, vmMo, vmSpec, vol, matchingExistingDisk, dataStoresDetails); - if (controllerKey == scsiControllerKey && VmwareHelper.isReservedScsiDeviceNumber(scsiUnitNumber)) + String[] diskChain = syncDiskChain(dcMo, vmMo, vmSpec, + vol, matchingExistingDisk, + dataStoresDetails); + if(controllerKey == scsiControllerKey && VmwareHelper.isReservedScsiDeviceNumber(scsiUnitNumber)) scsiUnitNumber++; - VirtualDevice device = - VmwareHelper.prepareDiskDevice(vmMo, null, controllerKey, diskChain, volumeDsDetails.first(), + VirtualDevice device = VmwareHelper.prepareDiskDevice(vmMo, null, controllerKey, + diskChain, + volumeDsDetails.first(), (controllerKey == ideControllerKey) ? ideUnitNumber++ : scsiUnitNumber++, i + 1); deviceConfigSpecArray[i].setDevice(device); deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD); - if (s_logger.isDebugEnabled()) + if(s_logger.isDebugEnabled()) s_logger.debug("Prepare volume at new device " + _gson.toJson(device)); i++; @@ -2916,12 +1682,12 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa dvSwitchUuid = dataCenterMo.getDvSwitchUuid(dvsMor); s_logger.info("Preparing NIC device on dvSwitch : " + dvSwitchUuid); nic = - VmwareHelper.prepareDvNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), dvSwitchUuid, nicTo.getMac(), nicUnitNumber++, - i + 1, true, true); + VmwareHelper.prepareDvNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), dvSwitchUuid, nicTo.getMac(), nicUnitNumber++, + i + 1, true, true); } else { s_logger.info("Preparing NIC device on network " + networkInfo.second()); nic = - VmwareHelper.prepareNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), nicTo.getMac(), nicUnitNumber++, i + 1, true, true); + VmwareHelper.prepareNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), nicTo.getMac(), nicUnitNumber++, i + 1, true, true); } deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); @@ -2957,7 +1723,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa if (vmSpec.getDetails() != null) keyboardLayout = vmSpec.getDetails().get(VmDetailConstants.KEYBOARD); vmConfigSpec.getExtraConfig().addAll( - Arrays.asList(configureVnc(extraOptions.toArray(new OptionValue[0]), hyperHost, vmInternalCSName, vmSpec.getVncPassword(), keyboardLayout))); + Arrays.asList(configureVnc(extraOptions.toArray(new OptionValue[0]), hyperHost, vmInternalCSName, vmSpec.getVncPassword(), keyboardLayout))); // // Configure VM @@ -2982,7 +1748,12 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } state = State.Running; - return new StartAnswer(cmd); + + StartAnswer startAnswer = new StartAnswer(cmd); + + startAnswer.setIqnToPath(iqnToPath); + + return startAnswer; } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); @@ -3003,18 +1774,70 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } } + @Override + public ManagedObjectReference prepareManagedStorage(VmwareHypervisorHost hyperHost, String iScsiName, + String storageHost, int storagePort, String chapInitiatorUsername, String chapInitiatorSecret, + String chapTargetUsername, String chapTargetSecret, long size, Command cmd) throws Exception { + ManagedObjectReference morDs = getVmfsDatastore(hyperHost, VmwareResource.getDatastoreName(iScsiName), + storageHost, storagePort, VmwareResource.trimIqn(iScsiName), chapInitiatorUsername, chapInitiatorSecret, + chapTargetUsername, chapTargetSecret); + + DatastoreMO dsMo = new DatastoreMO(getServiceContext(null), morDs); + + String volumeDatastorePath = String.format("[%s] %s.vmdk", dsMo.getName(), dsMo.getName()); + + if (!dsMo.fileExists(volumeDatastorePath)) { + createVmdk(cmd, dsMo, volumeDatastorePath, size); + } + + return morDs; + } + + int getReservedMemoryMb(VirtualMachineTO vmSpec) { + if (vmSpec.getDetails().get(Config.VmwareReserveMem.key()).equalsIgnoreCase("true")) { + return (int)(vmSpec.getMinRam() / (1024 * 1024)); + } else if (vmSpec.getMinRam() != vmSpec.getMaxRam()) { + s_logger.warn("memory overprovisioning factor is set to " + (vmSpec.getMaxRam() / vmSpec.getMinRam()) + " ignoring the flag vmware.reserve.mem"); + return (int)(vmSpec.getMinRam() / (1024 * 1024)); + } + return 0; + } + + int getReservedCpuMHZ(VirtualMachineTO vmSpec) { + if (vmSpec.getDetails().get(Config.VmwareReserveCpu.key()).equalsIgnoreCase("true")) { + return vmSpec.getMinSpeed(); + } else if (vmSpec.getMinSpeed().intValue() != vmSpec.getMaxSpeed().intValue()) { + s_logger.warn("cpu overprovisioning factor is set to " + (vmSpec.getMaxSpeed().intValue() / vmSpec.getMinSpeed().intValue()) + + " ignoring the flag vmware.reserve.cpu"); + return vmSpec.getMinSpeed(); + } + return 0; + } + // return the finalized disk chain for startup, from top to bottom private String[] syncDiskChain(DatacenterMO dcMo, VirtualMachineMO vmMo, VirtualMachineTO vmSpec, DiskTO vol, VirtualMachineDiskInfo diskInfo, - HashMap> dataStoresDetails) throws Exception { + HashMap> dataStoresDetails) throws Exception { VolumeObjectTO volumeTO = (VolumeObjectTO)vol.getData(); DataStoreTO primaryStore = volumeTO.getDataStore(); Map details = vol.getDetails(); - boolean isManaged = details != null && Boolean.parseBoolean(details.get(DiskTO.MANAGED)); + boolean isManaged = false; + String iScsiName = null; + + if (details != null) { + isManaged = Boolean.parseBoolean(details.get(DiskTO.MANAGED)); + iScsiName = details.get(DiskTO.IQN); + } + + // if the storage is managed, iScsiName should not be null + String datastoreName = isManaged ? VmwareResource.getDatastoreName(iScsiName) : primaryStore.getUuid(); + Pair volumeDsDetails = dataStoresDetails.get(datastoreName); - Pair volumeDsDetails = dataStoresDetails.get(primaryStore.getUuid()); if (volumeDsDetails == null) + { throw new Exception("Primary datastore " + primaryStore.getUuid() + " is not mounted on host."); + } + DatastoreMO dsMo = volumeDsDetails.second(); // we will honor vCenter's meta if it exists @@ -3247,7 +2070,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa boolean isManaged = details != null && Boolean.parseBoolean(details.get(DiskTO.MANAGED)); VirtualMachineDiskInfo diskInfo = - diskInfoBuilder.getDiskInfoByBackingFileBaseName(isManaged ? new DatastoreFile(volume.getPath()).getFileBaseName() : volume.getPath()); + diskInfoBuilder.getDiskInfoByBackingFileBaseName(isManaged ? new DatastoreFile(volume.getPath()).getFileBaseName() : volume.getPath()); if (diskInfo != null) { s_logger.info("Found existing disk info from volume path: " + volume.getPath()); return diskInfo; @@ -3299,11 +2122,11 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa if (vmDetails != null && vmDetails.get(VmDetailConstants.ROOK_DISK_CONTROLLER) != null) { if (vmDetails.get(VmDetailConstants.ROOK_DISK_CONTROLLER).equalsIgnoreCase("scsi")) { s_logger.info("Chose disk controller for vol " + vol.getType() + " -> scsi, based on root disk controller settings: " + - vmDetails.get(VmDetailConstants.ROOK_DISK_CONTROLLER)); + vmDetails.get(VmDetailConstants.ROOK_DISK_CONTROLLER)); controllerKey = scsiControllerKey; } else { s_logger.info("Chose disk controller for vol " + vol.getType() + " -> ide, based on root disk controller settings: " + - vmDetails.get(VmDetailConstants.ROOK_DISK_CONTROLLER)); + vmDetails.get(VmDetailConstants.ROOK_DISK_CONTROLLER)); controllerKey = ideControllerKey; } } else { @@ -3321,7 +2144,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } private void postDiskConfigBeforeStart(VirtualMachineMO vmMo, VirtualMachineTO vmSpec, DiskTO[] sortedDisks, int ideControllerKey, int scsiControllerKey) - throws Exception { + throws Exception { VirtualMachineDiskInfoBuilder diskInfoBuilder = vmMo.getDiskInfoBuilder(); @@ -3359,32 +2182,6 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa return null; } - @Deprecated - private Map validateVmDetails(Map vmDetails) { - - Map validatedDetails = new HashMap(); - - if (vmDetails != null && vmDetails.size() > 0) { - for (Map.Entry entry : vmDetails.entrySet()) { - if ("machine.id".equalsIgnoreCase(entry.getKey())) - continue; - else if ("devices.hotplug".equalsIgnoreCase(entry.getKey())) - continue; - else if ("RemoteDisplay.vnc.enabled".equalsIgnoreCase(entry.getKey())) - continue; - else if ("RemoteDisplay.vnc.password".equalsIgnoreCase(entry.getKey())) - continue; - else if ("RemoteDisplay.vnc.port".equalsIgnoreCase(entry.getKey())) - continue; - else if ("RemoteDisplay.vnc.keymap".equalsIgnoreCase(entry.getKey())) - continue; - else - validatedDetails.put(entry.getKey(), entry.getValue()); - } - } - return validatedDetails; - } - private static NicTO[] sortNicsByDeviceId(NicTO[] nics) { List listForSort = new ArrayList(); @@ -3420,7 +2217,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa public int compare(DiskTO arg0, DiskTO arg1) { if (arg0.getDiskSeq() < arg1.getDiskSeq()) { return -1; - } else if (arg0.getDiskSeq() == arg1.getDiskSeq()) { + } else if (arg0.getDiskSeq().equals(arg1.getDiskSeq())) { return 0; } @@ -3432,51 +2229,103 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } private HashMap> inferDatastoreDetailsFromDiskInfo(VmwareHypervisorHost hyperHost, VmwareContext context, - DiskTO[] disks) throws Exception { - HashMap> poolMors = new HashMap>(); + DiskTO[] disks, Map iqnToPath, Command cmd) throws Exception { + HashMap> mapIdToMors = new HashMap>(); assert (hyperHost != null) && (context != null); + for (DiskTO vol : disks) { if (vol.getType() != Volume.Type.ISO) { VolumeObjectTO volumeTO = (VolumeObjectTO)vol.getData(); DataStoreTO primaryStore = volumeTO.getDataStore(); String poolUuid = primaryStore.getUuid(); - if (poolMors.get(poolUuid) == null) { + + if (mapIdToMors.get(poolUuid) == null) { boolean isManaged = false; - String iScsiName = null; Map details = vol.getDetails(); if (details != null) { isManaged = Boolean.parseBoolean(details.get(DiskTO.MANAGED)); - iScsiName = details.get(DiskTO.IQN); } - ManagedObjectReference morDataStore = - HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, isManaged ? VmwareResource.getDatastoreName(iScsiName) : poolUuid); - if (morDataStore == null) { - String msg = "Failed to get the mounted datastore for the volume's pool " + poolUuid; - s_logger.error(msg); - throw new Exception(msg); + if (isManaged) { + String iScsiName = details.get(DiskTO.IQN); // details should not be null for managed storage (it may or may not be null for non-managed storage) + String datastoreName = VmwareResource.getDatastoreName(iScsiName); + ManagedObjectReference morDatastore = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, datastoreName); + + // if the datastore is not present, we need to discover the iSCSI device that will support it, + // create the datastore, and create a VMDK file in the datastore + if (morDatastore == null) { + morDatastore = prepareManagedStorage(hyperHost, iScsiName, + details.get(DiskTO.STORAGE_HOST), Integer.parseInt(details.get(DiskTO.STORAGE_PORT)), + details.get(DiskTO.CHAP_INITIATOR_USERNAME), details.get(DiskTO.CHAP_INITIATOR_SECRET), + details.get(DiskTO.CHAP_TARGET_USERNAME), details.get(DiskTO.CHAP_TARGET_SECRET), + Long.parseLong(details.get(DiskTO.VOLUME_SIZE)), cmd); + + DatastoreMO dsMo = new DatastoreMO(getServiceContext(), morDatastore); + String datastoreVolumePath = dsMo.getDatastorePath(dsMo.getName() + ".vmdk"); + + iqnToPath.put(iScsiName, datastoreVolumePath); + + volumeTO.setPath(datastoreVolumePath); + vol.setPath(datastoreVolumePath); + } + + mapIdToMors.put(datastoreName, new Pair(morDatastore, new DatastoreMO(context, morDatastore))); + } + else { + ManagedObjectReference morDatastore = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, poolUuid); + + if (morDatastore == null) { + String msg = "Failed to get the mounted datastore for the volume's pool " + poolUuid; + + s_logger.error(msg); + + throw new Exception(msg); + } + + mapIdToMors.put(poolUuid, new Pair(morDatastore, new DatastoreMO(context, morDatastore))); } - poolMors.put(poolUuid, new Pair(morDataStore, new DatastoreMO(context, morDataStore))); } } } - return poolMors; + + return mapIdToMors; } private DatastoreMO getDatastoreThatRootDiskIsOn(HashMap> dataStoresDetails, DiskTO disks[]) { - Pair rootDiskDataStoreDetails = null; + for (DiskTO vol : disks) { if (vol.getType() == Volume.Type.ROOT) { - DataStoreTO primaryStore = vol.getData().getDataStore(); - rootDiskDataStoreDetails = dataStoresDetails.get(primaryStore.getUuid()); + Map details = vol.getDetails(); + boolean managed = false; + + if (details != null) { + managed = Boolean.parseBoolean(details.get(DiskTO.MANAGED)); + } + + if (managed) { + String datastoreName = VmwareResource.getDatastoreName(details.get(DiskTO.IQN)); + + rootDiskDataStoreDetails = dataStoresDetails.get(datastoreName); + + break; + } + else { + DataStoreTO primaryStore = vol.getData().getDataStore(); + + rootDiskDataStoreDetails = dataStoresDetails.get(primaryStore.getUuid()); + + break; + } } } - if (rootDiskDataStoreDetails != null) + if (rootDiskDataStoreDetails != null) { return rootDiskDataStoreDetails.second(); + } + return null; } @@ -3513,24 +2362,13 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa return defaultVlan; } - private Pair prepareNetworkFromNicInfo(HostMO hostMo, NicTO nicTo, boolean configureVServiceInNexus, VirtualMachine.Type vmType) - throws Exception { - Pair switchName; - TrafficType trafficType; - VirtualSwitchType switchType; + private Pair prepareNetworkFromNicInfo(HostMO hostMo, NicTO nicTo, boolean configureVServiceInNexus, VirtualMachine.Type vmType) throws Exception { - switchName = getTargetSwitch(nicTo); - trafficType = nicTo.getType(); - // Get switch type from resource property which is dictated by cluster property - // If a virtual switch type is specified while adding cluster that will be used. - // Else If virtual switch type is specified in physical traffic label that will be used - // Else use standard vSwitch - switchType = VirtualSwitchType.StandardVirtualSwitch; - if (trafficType == TrafficType.Guest && _guestTrafficInfo != null) { - switchType = _guestTrafficInfo.getVirtualSwitchType(); - } else if (trafficType == TrafficType.Public && _publicTrafficInfo != null) { - switchType = _publicTrafficInfo.getVirtualSwitchType(); - } + Ternary switchDetails = getTargetSwitch(nicTo); + nicTo.getType(); + VirtualSwitchType switchType = VirtualSwitchType.getType(switchDetails.second()); + String switchName = switchDetails.first(); + String vlanToken = switchDetails.third(); String namePrefix = getNetworkNamePrefix(nicTo); Pair networkInfo = null; @@ -3538,13 +2376,14 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa s_logger.info("Prepare network on " + switchType + " " + switchName + " with name prefix: " + namePrefix); if (VirtualSwitchType.StandardVirtualSwitch == switchType) { - synchronized (hostMo.getMor().getValue().intern()) { - networkInfo = - HypervisorHostHelper.prepareNetwork(switchName.first(), namePrefix, hostMo, getVlanInfo(nicTo, switchName.second()), nicTo.getNetworkRateMbps(), - nicTo.getNetworkRateMulticastMbps(), _ops_timeout, !namePrefix.startsWith("cloud.private"), nicTo.getBroadcastType(), nicTo.getUuid()); + synchronized(hostMo.getMor().getValue().intern()) { + networkInfo = HypervisorHostHelper.prepareNetwork(switchName, namePrefix, hostMo, getVlanInfo(nicTo, vlanToken), nicTo.getNetworkRateMbps(), + nicTo.getNetworkRateMulticastMbps(), _opsTimeout, + !namePrefix.startsWith("cloud.private"), nicTo.getBroadcastType(), nicTo.getUuid()); } - } else { - String vlanId = getVlanInfo(nicTo, switchName.second()); + } + else { + String vlanId = getVlanInfo(nicTo, vlanToken); String svlanId = null; boolean pvlannetwork = (getPvlanInfo(nicTo) == null) ? false : true; if (vmType != null && vmType.equals(VirtualMachine.Type.DomainRouter) && pvlannetwork) { @@ -3554,48 +2393,65 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa // plumb this network to the isolated vlan. svlanId = getPvlanInfo(nicTo); } - networkInfo = - HypervisorHostHelper.prepareNetwork(switchName.first(), namePrefix, hostMo, vlanId, svlanId, nicTo.getNetworkRateMbps(), - nicTo.getNetworkRateMulticastMbps(), _ops_timeout, switchType, _portsPerDvPortGroup, nicTo.getGateway(), configureVServiceInNexus, - nicTo.getBroadcastType()); + networkInfo = HypervisorHostHelper.prepareNetwork(switchName, namePrefix, hostMo, vlanId, svlanId, + nicTo.getNetworkRateMbps(), nicTo.getNetworkRateMulticastMbps(), _opsTimeout, switchType, + _portsPerDvPortGroup, nicTo.getGateway(), configureVServiceInNexus, nicTo.getBroadcastType()); } return networkInfo; } - // return Pair - private Pair getTargetSwitch(NicTO nicTo) throws Exception { - if (nicTo.getType() == Networks.TrafficType.Guest) { - return new Pair(_guestTrafficInfo.getVirtualSwitchName(), Vlan.UNTAGGED); - } else if (nicTo.getType() == Networks.TrafficType.Public) { - return new Pair(_publicTrafficInfo.getVirtualSwitchName(), Vlan.UNTAGGED); + // return Ternary + private Ternary getTargetSwitch(NicTO nicTo) throws CloudException { + TrafficType[] supportedTrafficTypes = + new TrafficType[] { + TrafficType.Guest, + TrafficType.Public, + TrafficType.Control, + TrafficType.Management, + TrafficType.Storage + }; + + TrafficType trafficType = nicTo.getType(); + if (!Arrays.asList(supportedTrafficTypes).contains(trafficType)) { + throw new CloudException("Traffic type " + trafficType.toString() + " for nic " + nicTo.toString() + " is not supported."); } - if (nicTo.getName() != null && !nicTo.getName().isEmpty()) { + String switchName = null; + VirtualSwitchType switchType = VirtualSwitchType.StandardVirtualSwitch; + String vlanToken = Vlan.UNTAGGED; + + // Get switch details from the nicTO object + if(nicTo.getName() != null && !nicTo.getName().isEmpty()) { String[] tokens = nicTo.getName().split(","); // Format of network traffic label is ,, // If all 3 fields are mentioned then number of tokens would be 3. // If only , are mentioned then number of tokens would be 2. - if (tokens.length == 2 || tokens.length == 3) { - String vlanToken = tokens[1]; + switchName = tokens[0]; + if(tokens.length == 2 || tokens.length == 3) { + vlanToken = tokens[1]; if (vlanToken.isEmpty()) { vlanToken = Vlan.UNTAGGED; } - return new Pair(tokens[0], vlanToken); - } else { - return new Pair(nicTo.getName(), Vlan.UNTAGGED); + if (tokens.length == 3) { + switchType = VirtualSwitchType.getType(tokens[2]); + } + } + } else { + if (trafficType == TrafficType.Guest && _guestTrafficInfo != null) { + switchType = _guestTrafficInfo.getVirtualSwitchType(); + switchName = _guestTrafficInfo.getVirtualSwitchName(); + } else if (trafficType == TrafficType.Public && _publicTrafficInfo != null) { + switchType = _publicTrafficInfo.getVirtualSwitchType(); + switchName = _publicTrafficInfo.getVirtualSwitchName(); } } - if (nicTo.getType() == Networks.TrafficType.Control || nicTo.getType() == Networks.TrafficType.Management) { - return new Pair(_privateNetworkVSwitchName, Vlan.UNTAGGED); - } else if (nicTo.getType() == Networks.TrafficType.Storage) { - return new Pair(_privateNetworkVSwitchName, Vlan.UNTAGGED); - } else if (nicTo.getType() == Networks.TrafficType.Vpn) { - throw new Exception("Unsupported traffic type: " + nicTo.getType().toString()); - } else { - throw new Exception("Unsupported traffic type: " + nicTo.getType().toString()); + if (nicTo.getType() == Networks.TrafficType.Control || nicTo.getType() == Networks.TrafficType.Management || nicTo.getType() == Networks.TrafficType.Storage) { + switchName = _privateNetworkVSwitchName; } + + return new Ternary(switchName, switchType.toString(), vlanToken); } private String getNetworkNamePrefix(NicTO nicTo) throws Exception { @@ -3614,101 +2470,6 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } } - protected Answer execute(final RemoteAccessVpnCfgCommand cmd) { - String controlIp = getRouterSshControlIp(cmd); - StringBuffer argsBuf = new StringBuffer(); - if (cmd.isCreate()) { - argsBuf.append(" -r ") - .append(cmd.getIpRange()) - .append(" -p ") - .append(cmd.getPresharedKey()) - .append(" -s ") - .append(cmd.getVpnServerIp()) - .append(" -l ") - .append(cmd.getLocalIp()) - .append(" -c "); - - } else { - argsBuf.append(" -d ").append(" -s ").append(cmd.getVpnServerIp()); - } - argsBuf.append(" -C ").append(cmd.getLocalCidr()); - argsBuf.append(" -i ").append(cmd.getPublicInterface()); - - try { - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Executing /opt/cloud/bin/vpn_lt2p.sh "); - } - - Pair result = - SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpn_l2tp.sh " + argsBuf.toString()); - - if (!result.first()) { - s_logger.error("RemoteAccessVpnCfg command on domR failed, message: " + result.second()); - - return new Answer(cmd, false, "RemoteAccessVpnCfg command failed due to " + result.second()); - } - - if (s_logger.isInfoEnabled()) { - s_logger.info("RemoteAccessVpnCfg command on domain router " + argsBuf.toString() + " completed"); - } - - } catch (Throwable e) { - if (e instanceof RemoteException) { - s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); - invalidateServiceContext(); - } - - String msg = "RemoteAccessVpnCfg command failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg, e); - return new Answer(cmd, false, msg); - } - - return new Answer(cmd); - } - - protected Answer execute(final VpnUsersCfgCommand cmd) { - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - - String controlIp = getRouterSshControlIp(cmd); - for (VpnUsersCfgCommand.UsernamePassword userpwd : cmd.getUserpwds()) { - StringBuffer argsBuf = new StringBuffer(); - if (!userpwd.isAdd()) { - argsBuf.append(" -U ").append(userpwd.getUsername()); - } else { - argsBuf.append(" -u ").append(userpwd.getUsernamePassword()); - } - - try { - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Executing /opt/cloud/bin/vpn_lt2p.sh "); - } - - Pair result = - SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpn_l2tp.sh " + argsBuf.toString()); - - if (!result.first()) { - s_logger.error("VpnUserCfg command on domR failed, message: " + result.second()); - - return new Answer(cmd, false, "VpnUserCfg command failed due to " + result.second()); - } - } catch (Throwable e) { - if (e instanceof RemoteException) { - s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); - invalidateServiceContext(); - } - - String msg = "VpnUserCfg command failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg, e); - return new Answer(cmd, false, msg); - } - } - - return new Answer(cmd); - } - private VirtualMachineMO takeVmFromOtherHyperHost(VmwareHypervisorHost hyperHost, String vmName) throws Exception { VirtualMachineMO vmMo = hyperHost.findVmOnPeerHyperHost(vmName); @@ -3899,7 +2660,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK, "0"); if (getVmPowerState(vmMo) != PowerState.PowerOff) { - if (vmMo.safePowerOff(_shutdown_waitMs)) { + if (vmMo.safePowerOff(_shutdownWaitMs)) { state = State.Stopped; return new StopAnswer(cmd, "Stop VM " + cmd.getVmName() + " Succeed", true); } else { @@ -4188,8 +2949,6 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa VirtualMachineRelocateSpecDiskLocator diskLocator = null; boolean isFirstDs = true; - String srcDiskName = ""; - String srcDsName = ""; String tgtDsName = ""; String tgtDsNfsHost; String tgtDsNfsPath; @@ -4228,7 +2987,6 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa volume = entry.getKey(); filerTo = entry.getValue(); - srcDsName = volume.getPoolUuid().replace("-", ""); tgtDsName = filerTo.getUuid().replace("-", ""); tgtDsNfsHost = filerTo.getHost(); tgtDsNfsPath = filerTo.getPath(); @@ -4255,8 +3013,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa relocateSpec.setDatastore(morDsAtSource); isFirstDs = false; } - srcDiskName = - VmwareStorageLayoutHelper.getVmwareDatastorePathFromVmdkFileName(new DatastoreMO(srcHyperHost.getContext(), morDsAtSource), vmName, volume.getPath() + + VmwareStorageLayoutHelper.getVmwareDatastorePathFromVmdkFileName(new DatastoreMO(srcHyperHost.getContext(), morDsAtSource), vmName, volume.getPath() + ".vmdk"); diskLocator = new VirtualMachineRelocateSpecDiskLocator(); diskLocator.setDatastore(morDsAtSource); @@ -4322,7 +3079,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa srcHyperHost.unmountDatastore(mountedDatastore); } catch (Exception unmountEx) { s_logger.debug("Failed to unmount datastore " + mountedDatastore + " at " + _hostName + ". Seems the datastore is still being used by " + _hostName + - ". Please unmount manually to cleanup."); + ". Please unmount manually to cleanup."); } s_logger.debug("Successfully unmounted datastore " + mountedDatastore + " at " + _hostName); } @@ -4340,7 +3097,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa s_logger.info("Executing resource MigrateVolumeCommand: " + _gson.toJson(cmd)); } - final String vmName = volMgr.getVmNameFromVolumeId(cmd.getVolumeId()); + final String vmName = cmd.getAttachedVmName(); VirtualMachineMO vmMo = null; VmwareHypervisorHost srcHyperHost = null; @@ -4351,14 +3108,11 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa List diskLocators = new ArrayList(); VirtualMachineRelocateSpecDiskLocator diskLocator = null; - String srcDiskName = ""; - String srcDsName = ""; String tgtDsName = ""; try { srcHyperHost = getHyperHost(getServiceContext()); morDc = srcHyperHost.getHyperHostDatacenter(); - srcDsName = volMgr.getStoragePoolOfVolume(cmd.getVolumeId()); tgtDsName = poolTo.getUuid().replace("-", ""); // find VM in this datacenter not just in this cluster. @@ -4377,8 +3131,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa throw new Exception(msg); } - srcDiskName = - VmwareStorageLayoutHelper.getVmwareDatastorePathFromVmdkFileName(new DatastoreMO(srcHyperHost.getContext(), morDs), vmName, volumePath + ".vmdk"); + VmwareStorageLayoutHelper.getVmwareDatastorePathFromVmdkFileName(new DatastoreMO(srcHyperHost.getContext(), morDs), vmName, volumePath + ".vmdk"); diskLocator = new VirtualMachineRelocateSpecDiskLocator(); diskLocator.setDatastore(morDs); diskLocator.setDiskId(getVirtualDiskInfo(vmMo, volumePath + ".vmdk")); @@ -4448,7 +3201,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa morDatastore = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, pool.getUuid()); if (morDatastore == null) morDatastore = - hyperHost.mountDatastore(pool.getType() == StoragePoolType.VMFS, pool.getHost(), pool.getPort(), pool.getPath(), pool.getUuid().replace("-", "")); + hyperHost.mountDatastore(pool.getType() == StoragePoolType.VMFS, pool.getHost(), pool.getPort(), pool.getPath(), pool.getUuid().replace("-", "")); assert (morDatastore != null); DatastoreSummary summary = new DatastoreMO(getServiceContext(), morDatastore).getSummary(); @@ -4498,7 +3251,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa return str.replace('/', '-'); } - public static String trimIqn(String iqn) { + private static String trimIqn(String iqn) { String[] tmp = iqn.split("/"); if (tmp.length != 3) { @@ -4512,8 +3265,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa return tmp[1].trim(); } - @Override - public void createVmdk(Command cmd, DatastoreMO dsMo, String vmdkDatastorePath, Long volumeSize) throws Exception { + private void createVmdk(Command cmd, DatastoreMO dsMo, String vmdkDatastorePath, Long volumeSize) throws Exception { VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); @@ -4537,7 +3289,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); - deleteVmfsDatastore(hyperHost, getDatastoreName(iqn), storageHost, storagePort, trimIqn(iqn)); + deleteVmfsDatastore(hyperHost, VmwareResource.getDatastoreName(iqn), storageHost, storagePort, VmwareResource.trimIqn(iqn)); } protected Answer execute(AttachVolumeCommand cmd) { @@ -4562,18 +3314,11 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa ManagedObjectReference morDs = null; if (cmd.getAttach() && cmd.isManaged()) { - morDs = - getVmfsDatastore(hyperHost, getDatastoreName(cmd.get_iScsiName()), cmd.getStorageHost(), cmd.getStoragePort(), trimIqn(cmd.get_iScsiName()), - cmd.getChapInitiatorUsername(), cmd.getChapInitiatorPassword(), cmd.getChapTargetUsername(), cmd.getChapTargetPassword()); - - DatastoreMO dsMo = new DatastoreMO(getServiceContext(), morDs); - - String volumeDatastorePath = String.format("[%s] %s.vmdk", dsMo.getName(), dsMo.getName()); - - if (!dsMo.fileExists(volumeDatastorePath)) { - createVmdk(cmd, dsMo, volumeDatastorePath, cmd.getVolumeSize()); - } - } else { + morDs = prepareManagedStorage(hyperHost, cmd.get_iScsiName(), cmd.getStorageHost(), cmd.getStoragePort(), + cmd.getChapInitiatorUsername(), cmd.getChapInitiatorPassword(), + cmd.getChapTargetUsername(), cmd.getChapTargetPassword(), cmd.getVolumeSize(), cmd); + } + else { morDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, cmd.getPoolUuid()); } @@ -4657,7 +3402,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } private void addRemoveInternetScsiTargetsToAllHosts(final boolean add, final List lstTargets, - final List> lstHosts) throws Exception { + final List> lstHosts) throws Exception { VmwareContext context = getServiceContext(); ExecutorService executorService = Executors.newFixedThreadPool(lstHosts.size()); @@ -4773,9 +3518,8 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } } - @Override - public ManagedObjectReference getVmfsDatastore(VmwareHypervisorHost hyperHost, String datastoreName, String storageIpAddress, int storagePortNumber, String iqn, - String chapName, String chapSecret, String mutualChapName, String mutualChapSecret) throws Exception { + private ManagedObjectReference getVmfsDatastore(VmwareHypervisorHost hyperHost, String datastoreName, String storageIpAddress, int storagePortNumber, + String iqn, String chapName, String chapSecret, String mutualChapName, String mutualChapSecret) throws Exception { VmwareContext context = getServiceContext(); ManagedObjectReference morCluster = hyperHost.getHyperHostCluster(); ClusterMO cluster = new ClusterMO(context, morCluster); @@ -4787,25 +3531,27 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa target.setPort(storagePortNumber); target.setIScsiName(iqn); - HostInternetScsiHbaAuthenticationProperties auth = new HostInternetScsiHbaAuthenticationProperties(); + if (StringUtils.isNotBlank(chapName) && StringUtils.isNotBlank(chapSecret)) { + HostInternetScsiHbaAuthenticationProperties auth = new HostInternetScsiHbaAuthenticationProperties(); - String strAuthType = "chapRequired"; + String strAuthType = "chapRequired"; - auth.setChapAuthEnabled(true); - auth.setChapInherited(false); - auth.setChapAuthenticationType(strAuthType); - auth.setChapName(chapName); - auth.setChapSecret(chapSecret); + auth.setChapAuthEnabled(true); + auth.setChapInherited(false); + auth.setChapAuthenticationType(strAuthType); + auth.setChapName(chapName); + auth.setChapSecret(chapSecret); - if (StringUtils.isNotBlank(mutualChapName) && StringUtils.isNotBlank(mutualChapSecret)) { - auth.setMutualChapInherited(false); - auth.setMutualChapAuthenticationType(strAuthType); - auth.setMutualChapName(mutualChapName); - auth.setMutualChapSecret(mutualChapSecret); + if (StringUtils.isNotBlank(mutualChapName) && StringUtils.isNotBlank(mutualChapSecret)) { + auth.setMutualChapInherited(false); + auth.setMutualChapAuthenticationType(strAuthType); + auth.setMutualChapName(mutualChapName); + auth.setMutualChapSecret(mutualChapSecret); + } + + target.setAuthenticationProperties(auth); } - target.setAuthenticationProperties(auth); - final List lstTargets = new ArrayList(); lstTargets.add(target); @@ -4925,9 +3671,12 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa if (cmd.isAttach()) { vmMo.mountToolsInstaller(); } else { - try { - vmMo.unmountToolsInstaller(); - } catch (Throwable e) { + try{ + if (!vmMo.unmountToolsInstaller()) { + return new Answer(cmd, false, + "Failed to unmount vmware-tools installer ISO as the corresponding CDROM device is locked by VM. Please unmount the CDROM device inside the VM and ret-try."); + } + }catch(Throwable e){ vmMo.detachIso(null); } } @@ -5007,7 +3756,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa String actualSnapshotBackupUuid = null; String actualSnapshotUuid = null; return new ValidateSnapshotAnswer(cmd, false, "ValidateSnapshotCommand is not supported for vmware yet", expectedSnapshotBackupUuid, actualSnapshotBackupUuid, - actualSnapshotUuid); + actualSnapshotUuid); } protected Answer execute(ManageSnapshotCommand cmd) { @@ -5194,7 +3943,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa if (s_logger.isDebugEnabled()) { s_logger.debug("Datastore summary info, storageId: " + cmd.getStorageId() + ", localPath: " + cmd.getLocalPath() + ", poolType: " + - cmd.getPooltype() + ", capacity: " + capacity + ", free: " + free + ", used: " + used); + cmd.getPooltype() + ", capacity: " + capacity + ", free: " + free + ", used: " + used); } if (summary.getCapacity() <= 0) { @@ -5204,8 +3953,8 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa return new GetStorageStatsAnswer(cmd, capacity, used); } else { String msg = - "Could not find datastore for GetStorageStatsCommand storageId : " + cmd.getStorageId() + ", localPath: " + cmd.getLocalPath() + ", poolType: " + - cmd.getPooltype(); + "Could not find datastore for GetStorageStatsCommand storageId : " + cmd.getStorageId() + ", localPath: " + cmd.getLocalPath() + ", poolType: " + + cmd.getPooltype(); s_logger.error(msg); return new GetStorageStatsAnswer(cmd, msg); @@ -5217,7 +3966,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } String msg = - "Unable to execute GetStorageStatsCommand(storageId : " + cmd.getStorageId() + ", localPath: " + cmd.getLocalPath() + ", poolType: " + cmd.getPooltype() + + "Unable to execute GetStorageStatsCommand(storageId : " + cmd.getStorageId() + ", localPath: " + cmd.getLocalPath() + ", poolType: " + cmd.getPooltype() + ") due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new GetStorageStatsAnswer(cmd, msg); @@ -5290,12 +4039,12 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa String args = " -c 1 -n -q " + cmd.getPrivateIp(); try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/bin/ping" + args); + Pair result = SshHelper.sshExecute(controlIp, DefaultDomRSshPort, "root", mgr.getSystemVMKeyFile(), null, "/bin/ping" + args); if (result.first()) return new Answer(cmd); } catch (Exception e) { s_logger.error( - "Unable to execute ping command on DomR (" + controlIp + "), domR may not be ready yet. failure due to " + VmwareHelper.getExceptionMessage(e), e); + "Unable to execute ping command on DomR (" + controlIp + "), domR may not be ready yet. failure due to " + VmwareHelper.getExceptionMessage(e), e); } return new Answer(cmd, false, "PingTestCommand failed"); } @@ -5495,7 +4244,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa // tear down all devices first before we destroy the VM to avoid accidently delete disk backing files if (getVmPowerState(vmMo) != PowerState.PowerOff) - vmMo.safePowerOff(_shutdown_waitMs); + vmMo.safePowerOff(_shutdownWaitMs); vmMo.tearDownDevices(new Class[] { /* VirtualDisk.class, */VirtualEthernetCard.class}); vmMo.destroy(); @@ -5626,7 +4375,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } private boolean createVMFullClone(VirtualMachineMO vmTemplate, DatacenterMO dcMo, DatastoreMO dsMo, String vmdkName, ManagedObjectReference morDatastore, - ManagedObjectReference morPool) throws Exception { + ManagedObjectReference morPool) throws Exception { if (dsMo.folderExists(String.format("[%s]", dsMo.getName()), vmdkName)) dsMo.deleteFile(String.format("[%s] %s/", dsMo.getName(), vmdkName), dcMo.getMor(), false); @@ -5642,16 +4391,16 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa // to move files s_logger.info("Move volume out of volume-wrapper VM "); dsMo.moveDatastoreFile(String.format("[%s] %s/%s.vmdk", dsMo.getName(), vmdkName, vmdkName), dcMo.getMor(), dsMo.getMor(), - String.format("[%s] %s.vmdk", dsMo.getName(), vmdkName), dcMo.getMor(), true); + String.format("[%s] %s.vmdk", dsMo.getName(), vmdkName), dcMo.getMor(), true); dsMo.moveDatastoreFile(String.format("[%s] %s/%s-flat.vmdk", dsMo.getName(), vmdkName, vmdkName), dcMo.getMor(), dsMo.getMor(), - String.format("[%s] %s-flat.vmdk", dsMo.getName(), vmdkName), dcMo.getMor(), true); + String.format("[%s] %s-flat.vmdk", dsMo.getName(), vmdkName), dcMo.getMor(), true); return true; } private boolean createVMLinkedClone(VirtualMachineMO vmTemplate, DatacenterMO dcMo, DatastoreMO dsMo, String vmdkName, ManagedObjectReference morDatastore, - ManagedObjectReference morPool) throws Exception { + ManagedObjectReference morPool) throws Exception { ManagedObjectReference morBaseSnapshot = vmTemplate.getSnapshotMor("cloud.template.base"); if (morBaseSnapshot == null) { @@ -5674,10 +4423,10 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa // to move files s_logger.info("Move volume out of volume-wrapper VM "); dsMo.moveDatastoreFile(String.format("[%s] %s/%s.vmdk", dsMo.getName(), vmdkName, vmdkName), dcMo.getMor(), dsMo.getMor(), - String.format("[%s] %s.vmdk", dsMo.getName(), vmdkName), dcMo.getMor(), true); + String.format("[%s] %s.vmdk", dsMo.getName(), vmdkName), dcMo.getMor(), true); dsMo.moveDatastoreFile(String.format("[%s] %s/%s-delta.vmdk", dsMo.getName(), vmdkName, vmdkName), dcMo.getMor(), dsMo.getMor(), - String.format("[%s] %s-delta.vmdk", dsMo.getName(), vmdkName), dcMo.getMor(), true); + String.format("[%s] %s-delta.vmdk", dsMo.getName(), vmdkName), dcMo.getMor(), true); return true; } @@ -5724,8 +4473,8 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa vmMo.detachDisk(volumeDatastorePath, false); VolumeTO vol = - new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), dskch.getName(), pool.getPath(), vmdkName, dskch.getSize(), - null); + new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), dskch.getName(), pool.getPath(), vmdkName, dskch.getSize(), + null); return new CreateAnswer(cmd, vol); } finally { vmMo.detachAllDisks(); @@ -5761,7 +4510,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa dsMo.deleteFile(srcFile, dcMo.getMor(), true); VolumeTO vol = - new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), dskch.getName(), pool.getPath(), vmdkName, dskch.getSize(), null); + new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), dskch.getName(), pool.getPath(), vmdkName, dskch.getSize(), null); return new CreateAnswer(cmd, vol); } } else { @@ -5783,8 +4532,8 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa vmMo.detachDisk(volumeDatastorePath, false); VolumeTO vol = - new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), dskch.getName(), pool.getPath(), volumeUuid, dskch.getSize(), - null); + new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), dskch.getName(), pool.getPath(), volumeUuid, dskch.getSize(), + null); return new CreateAnswer(cmd, vol); } finally { s_logger.info("Destroy dummy VM after volume creation"); @@ -5983,7 +4732,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa DatastoreSummary dsSummary = dsMo.getSummary(); String address = hostMo.getHostName(); StoragePoolInfo pInfo = - new StoragePoolInfo(poolUuid, address, dsMo.getMor().getValue(), "", StoragePoolType.LVM, dsSummary.getCapacity(), dsSummary.getFreeSpace()); + new StoragePoolInfo(poolUuid, address, dsMo.getMor().getValue(), "", StoragePoolType.LVM, dsSummary.getCapacity(), dsSummary.getFreeSpace()); StartupStorageCommand cmd = new StartupStorageCommand(); cmd.setName(poolUuid); cmd.setPoolInfo(pInfo); @@ -6038,11 +4787,34 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa cmd.setName(_url); cmd.setGuid(_guid); cmd.setDataCenter(_dcId); + cmd.setIqn(getIqn()); cmd.setPod(_pod); cmd.setCluster(_cluster); cmd.setVersion(VmwareResource.class.getPackage().getImplementationVersion()); } + private String getIqn() { + try { + VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); + + if (hyperHost instanceof HostMO) { + HostMO host = (HostMO)hyperHost; + HostStorageSystemMO hostStorageSystem = host.getHostStorageSystemMO(); + + for (HostHostBusAdapter hba : hostStorageSystem.getStorageDeviceInfo().getHostBusAdapter()) { + if (hba instanceof HostInternetScsiHba) { + return ((HostInternetScsiHba)hba).getIScsiName(); + } + } + } + } + catch (Exception ex) { + s_logger.info("Could not locate an IQN for this host."); + } + + return null; + } + private void fillHostHardwareInfo(VmwareContext serviceContext, StartupRoutingCommand cmd) throws RuntimeFaultFaultMsg, RemoteException, Exception { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); @@ -6178,7 +4950,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa if (oldState != State.Starting && oldState != State.Migrating) { s_logger.debug("VM " + vm + - " is now missing from host report and VM is not at starting/migrating state, remove it from host VM-sync map, oldState: " + oldState); + " is now missing from host report and VM is not at starting/migrating state, remove it from host VM-sync map, oldState: " + oldState); _vms.remove(vm); } else { s_logger.debug("VM " + vm + " is missing from host report, but we will ignore VM " + vm + " in transition state " + oldState); @@ -6224,7 +4996,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } protected OptionValue[] configureVnc(OptionValue[] optionsToMerge, VmwareHypervisorHost hyperHost, String vmName, String vncPassword, String keyboardLayout) - throws Exception { + throws Exception { VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName); @@ -6427,7 +5199,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa PerfCounterInfo rxPerfCounterInfo = null; PerfCounterInfo txPerfCounterInfo = null; - List cInfo = (List)getServiceContext().getVimClient().getDynamicProperty(perfMgr, "perfCounter"); + List cInfo = getServiceContext().getVimClient().getDynamicProperty(perfMgr, "perfCounter"); for (PerfCounterInfo info : cInfo) { if ("net".equalsIgnoreCase(info.getGroupInfo().getKey())) { if ("transmitted".equalsIgnoreCase(info.getNameInfo().getKey())) { @@ -6446,7 +5218,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa String instanceNameCustomField = "value[" + key + "]"; ObjectContent[] ocs = - hyperHost.getVmPropertiesOnHyperHost(new String[] {"name", "summary.config.numCpu", "summary.quickStats.overallCpuUsage", instanceNameCustomField}); + hyperHost.getVmPropertiesOnHyperHost(new String[] {"name", "summary.config.numCpu", "summary.quickStats.overallCpuUsage", instanceNameCustomField}); if (ocs != null && ocs.length > 0) { for (ObjectContent oc : ocs) { List objProps = oc.getPropSet(); @@ -6468,7 +5240,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa maxCpuUsage = objProp.getVal().toString(); } } - VirtualMachineMO vmMo = new VirtualMachineMO(hyperHost.getContext(), oc.getObj()); + new VirtualMachineMO(hyperHost.getContext(), oc.getObj()); if (vmInternalCSName != null) { name = vmInternalCSName; } else { @@ -6482,13 +5254,13 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa ManagedObjectReference vmMor = hyperHost.findVmOnHyperHost(name).getMor(); assert (vmMor != null); - ArrayList vmNetworkMetrics = new ArrayList(); + ArrayList vmNetworkMetrics = new ArrayList(); // get all the metrics from the available sample period List perfMetrics = service.queryAvailablePerfMetric(perfMgr, vmMor, null, null, null); if (perfMetrics != null) { for (int index = 0; index < perfMetrics.size(); ++index) { if (((rxPerfCounterInfo != null) && (perfMetrics.get(index).getCounterId() == rxPerfCounterInfo.getKey())) || - ((txPerfCounterInfo != null) && (perfMetrics.get(index).getCounterId() == txPerfCounterInfo.getKey()))) { + ((txPerfCounterInfo != null) && (perfMetrics.get(index).getCounterId() == txPerfCounterInfo.getKey()))) { vmNetworkMetrics.add(perfMetrics.get(index)); } } @@ -6501,7 +5273,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa if (vmNetworkMetrics.size() != 0) { PerfQuerySpec qSpec = new PerfQuerySpec(); qSpec.setEntity(vmMor); - PerfMetricId[] availableMetricIds = (PerfMetricId[])vmNetworkMetrics.toArray(new PerfMetricId[0]); + PerfMetricId[] availableMetricIds = vmNetworkMetrics.toArray(new PerfMetricId[0]); qSpec.getMetricId().addAll(Arrays.asList(availableMetricIds)); List qSpecs = new ArrayList(); qSpecs.add(qSpec); @@ -6554,28 +5326,13 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa args += ethName; } - try { - if (s_logger.isTraceEnabled()) { - s_logger.trace("Executing /opt/cloud/bin/netusage.sh " + args + " on DomR " + privateIpAddress); - } + ExecutionResult result = executeInVR(privateIpAddress, "netusage.sh", args); - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - - Pair result = - SshHelper.sshExecute(privateIpAddress, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/netusage.sh " + args); - - if (!result.first()) { - return null; - } - - return result.second(); - } catch (Throwable e) { - s_logger.error( - "Unable to execute NetworkUsage command on DomR (" + privateIpAddress + "), domR may not be ready yet. failure due to " + - VmwareHelper.getExceptionMessage(e), e); + if (!result.isSuccess()) { + return null; } - return null; + return result.getDetails(); } private long[] getNetworkStats(String privateIP) { @@ -6603,7 +5360,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa // at least have tried _retry times, this is to coordinate with system // VM patching/rebooting time that may need int retry = _retry; - while (System.currentTimeMillis() - startTick <= _ops_timeout || --retry > 0) { + while (System.currentTimeMillis() - startTick <= _opsTimeout || --retry > 0) { SocketChannel sch = null; try { s_logger.info("Trying to connect to " + ipAddress); @@ -6741,7 +5498,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(context, context.getServiceContent().getCustomFieldsManager()); cfmMo.ensureCustomFieldDef("Datastore", CustomFieldConstants.CLOUD_UUID); if (_publicTrafficInfo != null && _publicTrafficInfo.getVirtualSwitchType() != VirtualSwitchType.StandardVirtualSwitch || _guestTrafficInfo != null && - _guestTrafficInfo.getVirtualSwitchType() != VirtualSwitchType.StandardVirtualSwitch) { + _guestTrafficInfo.getVirtualSwitchType() != VirtualSwitchType.StandardVirtualSwitch) { cfmMo.ensureCustomFieldDef("DistributedVirtualPortgroup", CustomFieldConstants.CLOUD_GC_DVP); } cfmMo.ensureCustomFieldDef("Network", CustomFieldConstants.CLOUD_GC); @@ -6756,7 +5513,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa Map vsmCredentials; if (_guestTrafficInfo.getVirtualSwitchType() == VirtualSwitchType.NexusDistributedVirtualSwitch || - _publicTrafficInfo.getVirtualSwitchType() == VirtualSwitchType.NexusDistributedVirtualSwitch) { + _publicTrafficInfo.getVirtualSwitchType() == VirtualSwitchType.NexusDistributedVirtualSwitch) { vsmCredentials = mgr.getNexusVSMCredentialsByClusterId(Long.parseLong(_cluster)); if (vsmCredentials != null) { s_logger.info("Stocking credentials while configuring resource."); @@ -6796,8 +5553,8 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa _portsPerDvPortGroup = intObj.intValue(); s_logger.info("VmwareResource network configuration info." + " private traffic over vSwitch: " + _privateNetworkVSwitchName + ", public traffic over " + - _publicTrafficInfo.getVirtualSwitchType() + " : " + _publicTrafficInfo.getVirtualSwitchName() + ", guest traffic over " + - _guestTrafficInfo.getVirtualSwitchType() + " : " + _guestTrafficInfo.getVirtualSwitchName()); + _publicTrafficInfo.getVirtualSwitchType() + " : " + _publicTrafficInfo.getVirtualSwitchName() + ", guest traffic over " + + _guestTrafficInfo.getVirtualSwitchType() + " : " + _guestTrafficInfo.getVirtualSwitchName()); value = params.get("vmware.create.full.clone").toString(); if (value != null && value.equalsIgnoreCase("true")) { @@ -6817,9 +5574,13 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa int timeout = NumbersUtil.parseInt(value, 1440) * 1000; VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); VmwareStorageProcessor storageProcessor = - new VmwareStorageProcessor((VmwareHostService)this, _fullCloneFlag, (VmwareStorageMount)mgr, timeout, this, _shutdown_waitMs, null); + new VmwareStorageProcessor((VmwareHostService)this, _fullCloneFlag, (VmwareStorageMount)mgr, timeout, this, _shutdownWaitMs, null); storageHandler = new VmwareStorageSubsystemCommandHandler(storageProcessor); + _vrResource = new VirtualRoutingResource(this); + if (!_vrResource.configure(name, params)) { + throw new ConfigurationException("Unable to configure VirtualRoutingResource"); + } return true; } finally { recycleServiceContext(); @@ -6855,10 +5616,16 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa @Override public VmwareContext getServiceContext(Command cmd) { - if (s_serviceContext.get() != null) - return s_serviceContext.get(); - VmwareContext context = null; + if(s_serviceContext.get() != null) { + context = s_serviceContext.get(); + if (context.validate()) { + return context; + } else { + s_logger.info("Validation of the context failed, dispose and use a new one"); + invalidateServiceContext(context); + } + } try { context = VmwareContextFactory.getContext(_vCenterAddress, _username, _password); s_serviceContext.set(context); @@ -6982,9 +5749,4 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa return new Answer(cmd, false, msg); } } - - private boolean isVMWareToolsInstalled(VirtualMachineMO vmMo) throws Exception { - GuestInfo guestInfo = vmMo.getVmGuestInfo(); - return (guestInfo != null && guestInfo.getGuestState() != null && guestInfo.getGuestState().equalsIgnoreCase("running")); - } } diff --git a/plugins/hypervisors/vmware/src/com/cloud/network/CiscoNexusVSMDeviceVO.java b/plugins/hypervisors/vmware/src/com/cloud/network/CiscoNexusVSMDeviceVO.java index afc52b56edf..0cb40286e3d 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/network/CiscoNexusVSMDeviceVO.java +++ b/plugins/hypervisors/vmware/src/com/cloud/network/CiscoNexusVSMDeviceVO.java @@ -40,6 +40,8 @@ public class CiscoNexusVSMDeviceVO implements CiscoNexusVSMDevice { // We need to know what properties a VSM has. Put them here. + private static final long serialVersionUID = 3091674059522739481L; + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") @@ -167,11 +169,11 @@ public class CiscoNexusVSMDeviceVO implements CiscoNexusVSMDevice { // Setter methods public void setHostId(long hostid) { - this.hostId = hostid; + hostId = hostid; } public void setVsmUserName(String username) { - this.vsmUserName = username; + vsmUserName = username; } public void setVsmName(String vsmName) { @@ -179,7 +181,7 @@ public class CiscoNexusVSMDeviceVO implements CiscoNexusVSMDevice { } public void setVsmPassword(String password) { - this.vsmPassword = password; + vsmPassword = password; } public void setMgmtIpAddr(String ipaddr) { @@ -187,50 +189,50 @@ public class CiscoNexusVSMDeviceVO implements CiscoNexusVSMDevice { } public void setManagementVlan(int vlan) { - this.managementVlan = vlan; + managementVlan = vlan; } public void setControlVlan(int vlan) { - this.controlVlan = vlan; + controlVlan = vlan; } public void setPacketVlan(int vlan) { - this.packetVlan = vlan; + packetVlan = vlan; } public void setStorageVlan(int vlan) { - this.storageVlan = vlan; + storageVlan = vlan; } public void setVsmDomainId(long id) { - this.vsmDomainId = id; + vsmDomainId = id; } public void setVsmConfigMode(VSMConfigMode mode) { - this.vsmConfigMode = mode; + vsmConfigMode = mode; } public void setVsmConfigState(VSMConfigState state) { - this.vsmConfigState = state; + vsmConfigState = state; } public void setVsmDeviceState(VSMDeviceState devState) { - this.vsmDeviceState = devState; + vsmDeviceState = devState; } // Constructors. public CiscoNexusVSMDeviceVO(String vsmIpAddr, String username, String password) { // Set all the VSM's properties here. - this.uuid = UUID.randomUUID().toString(); - this.setMgmtIpAddr(vsmIpAddr); - this.setVsmUserName(username); - this.setVsmPassword(password); - this.setVsmName(vsmName); - this.setVsmDeviceState(VSMDeviceState.Enabled); + uuid = UUID.randomUUID().toString(); + setMgmtIpAddr(vsmIpAddr); + setVsmUserName(username); + setVsmPassword(password); + setVsmName(vsmName); + setVsmDeviceState(VSMDeviceState.Enabled); } public CiscoNexusVSMDeviceVO() { - this.uuid = UUID.randomUUID().toString(); + uuid = UUID.randomUUID().toString(); } } diff --git a/plugins/hypervisors/vmware/src/com/cloud/network/element/CiscoNexusVSMElement.java b/plugins/hypervisors/vmware/src/com/cloud/network/element/CiscoNexusVSMElement.java index e92954e99b8..c33af27d244 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/network/element/CiscoNexusVSMElement.java +++ b/plugins/hypervisors/vmware/src/com/cloud/network/element/CiscoNexusVSMElement.java @@ -269,8 +269,6 @@ public class CiscoNexusVSMElement extends CiscoNexusVSMDeviceManagerImpl impleme throw new CloudRuntimeException(msg); } - Transaction txn; - // If VSM already exists and is mapped to a cluster, fail this operation. vsm = _vsmDao.getVSMbyIpaddress(vsmIp); if (vsm != null) { diff --git a/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareSecondaryStorageResourceHandler.java b/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareSecondaryStorageResourceHandler.java index c91d7b6f2cd..baaaf217332 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareSecondaryStorageResourceHandler.java +++ b/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareSecondaryStorageResourceHandler.java @@ -42,13 +42,11 @@ import com.cloud.hypervisor.vmware.manager.VmwareStorageManager; import com.cloud.hypervisor.vmware.manager.VmwareStorageManagerImpl; import com.cloud.hypervisor.vmware.manager.VmwareStorageMount; import com.cloud.hypervisor.vmware.mo.ClusterMO; -import com.cloud.hypervisor.vmware.mo.DatastoreMO; import com.cloud.hypervisor.vmware.mo.HostMO; import com.cloud.hypervisor.vmware.mo.VmwareHostType; import com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost; import com.cloud.hypervisor.vmware.mo.VmwareHypervisorHostNetworkSummary; import com.cloud.hypervisor.vmware.util.VmwareContext; -import com.cloud.hypervisor.vmware.util.VmwareHelper; import com.cloud.serializer.GsonHelper; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; @@ -126,7 +124,7 @@ public class VmwareSecondaryStorageResourceHandler implements SecondaryStorageRe } protected Answer execute(CreateEntityDownloadURLCommand cmd) { - boolean result = _storageMgr.execute(this, cmd); + _storageMgr.execute(this, cmd); return _resource.defaultAction(cmd); } @@ -214,18 +212,23 @@ public class VmwareSecondaryStorageResourceHandler implements SecondaryStorageRe _resource.ensureOutgoingRuleForAddress(vCenterAddress); VmwareContext context = currentContext.get(); - if (context == null) { + if (context != null) { + if(!context.validate()) { + invalidateServiceContext(context); + context = null; + } else { + context.registerStockObject("serviceconsole", cmd.getContextParam("serviceconsole")); + context.registerStockObject("manageportgroup", cmd.getContextParam("manageportgroup")); + context.registerStockObject("noderuninfo", cmd.getContextParam("noderuninfo")); + } + } + if(context == null) { s_logger.info("Open new VmwareContext. vCenter: " + vCenterAddress + ", user: " + username + ", password: " + - StringUtils.getMaskedPasswordForDisplay(password)); + StringUtils.getMaskedPasswordForDisplay(password)); VmwareSecondaryStorageContextFactory.setVcenterSessionTimeout(vCenterSessionTimeout); context = VmwareSecondaryStorageContextFactory.getContext(vCenterAddress, username, password); } - if (context != null) { - context.registerStockObject("serviceconsole", cmd.getContextParam("serviceconsole")); - context.registerStockObject("manageportgroup", cmd.getContextParam("manageportgroup")); - context.registerStockObject("noderuninfo", cmd.getContextParam("noderuninfo")); - } currentContext.set(context); return context; } catch (Exception e) { @@ -311,54 +314,10 @@ public class VmwareSecondaryStorageResourceHandler implements SecondaryStorageRe return _resource.getRootDir(storageUrl); } - private boolean validateContext(VmwareContext context, Command cmd) { - String guid = cmd.getContextParam("guid"); - assert (guid != null); - - String[] tokens = guid.split("@"); - assert (tokens != null && tokens.length == 2); - - ManagedObjectReference morHyperHost = new ManagedObjectReference(); - String[] hostTokens = tokens[0].split(":"); - assert (hostTokens.length == 2); - - morHyperHost.setType(hostTokens[0]); - morHyperHost.setValue(hostTokens[1]); - - if (morHyperHost.getType().equalsIgnoreCase("HostSystem")) { - HostMO hostMo = new HostMO(context, morHyperHost); - try { - VmwareHypervisorHostNetworkSummary netSummary = - hostMo.getHyperHostNetworkSummary(hostMo.getHostType() == VmwareHostType.ESXi ? cmd.getContextParam("manageportgroup") - : cmd.getContextParam("serviceconsole")); - assert (netSummary != null); - if (netSummary.getHostIp() != null && !netSummary.getHostIp().isEmpty()) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Context validation succeeded. Validated via host: " + netSummary.getHostIp() + ", guid: " + guid); - } - return true; - } - - s_logger.warn("Context validation failed due to invalid host network summary"); - return false; - } catch (Throwable e) { - s_logger.warn("Context validation failed due to " + VmwareHelper.getExceptionMessage(e)); - return false; - } - } - - assert (false); - return true; - } - @Override - public ManagedObjectReference getVmfsDatastore(VmwareHypervisorHost hyperHost, String datastoreName, String storageIpAddress, int storagePortNumber, String iqn, - String initiatorChapName, String initiatorChapSecret, String mutualChapName, String mutualChapSecret) throws Exception { - throw new OperationNotSupportedException(); - } - - @Override - public void createVmdk(Command cmd, DatastoreMO dsMo, String volumeDatastorePath, Long volumeSize) throws Exception { + public ManagedObjectReference prepareManagedStorage(VmwareHypervisorHost hyperHost, String iScsiName, + String storageHost, int storagePort, String chapInitiatorUsername, String chapInitiatorSecret, + String chapTargetUsername, String chapTargetSecret, long size, Command cmd) throws Exception { throw new OperationNotSupportedException(); } diff --git a/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareStorageProcessor.java b/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareStorageProcessor.java index 747d5d6925e..6157bd681c4 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareStorageProcessor.java +++ b/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareStorageProcessor.java @@ -78,7 +78,7 @@ import com.cloud.storage.JavaStorageLayer; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.StorageLayer; import com.cloud.storage.Volume; -import com.cloud.storage.template.VmdkProcessor; +import com.cloud.storage.template.OVAProcessor; import com.cloud.utils.Pair; import com.cloud.utils.Ternary; import com.cloud.utils.script.Script; @@ -92,7 +92,7 @@ public class VmwareStorageProcessor implements StorageProcessor { private VmwareStorageMount mountService; private VmwareResource resource; private Integer _timeout; - protected Integer _shutdown_waitMs; + protected Integer _shutdownWaitMs; private final Gson _gson; private final StorageLayer _storage = new JavaStorageLayer(); @@ -103,7 +103,7 @@ public class VmwareStorageProcessor implements StorageProcessor { this.mountService = mountService; _timeout = timeout; this.resource = resource; - _shutdown_waitMs = shutdownWaitMs; + _shutdownWaitMs = shutdownWaitMs; _gson = GsonHelper.getGsonLogger(); } @@ -253,16 +253,6 @@ public class VmwareStorageProcessor implements StorageProcessor { s_logger.error(msg); throw new Exception(msg); } - - s_logger.info("Move volume out of volume-wrapper VM "); - String[] vmwareLayoutFilePair = VmwareStorageLayoutHelper.getVmdkFilePairDatastorePath(dsMo, vmdkName, vmdkName, VmwareStorageLayoutType.VMWARE, true); - String[] legacyCloudStackLayoutFilePair = - VmwareStorageLayoutHelper.getVmdkFilePairDatastorePath(dsMo, vmdkName, vmdkName, VmwareStorageLayoutType.CLOUDSTACK_LEGACY, true); - - dsMo.moveDatastoreFile(vmwareLayoutFilePair[0], dcMo.getMor(), dsMo.getMor(), legacyCloudStackLayoutFilePair[0], dcMo.getMor(), true); - - dsMo.moveDatastoreFile(vmwareLayoutFilePair[1], dcMo.getMor(), dsMo.getMor(), legacyCloudStackLayoutFilePair[1], dcMo.getMor(), true); - return true; } @@ -275,15 +265,6 @@ public class VmwareStorageProcessor implements StorageProcessor { s_logger.error(msg); throw new Exception(msg); } - - s_logger.info("Move volume out of volume-wrapper VM "); - String[] vmwareLayoutFilePair = VmwareStorageLayoutHelper.getVmdkFilePairDatastorePath(dsMo, vmdkName, vmdkName, VmwareStorageLayoutType.VMWARE, false); - String[] legacyCloudStackLayoutFilePair = - VmwareStorageLayoutHelper.getVmdkFilePairDatastorePath(dsMo, vmdkName, vmdkName, VmwareStorageLayoutType.CLOUDSTACK_LEGACY, false); - - dsMo.moveDatastoreFile(vmwareLayoutFilePair[0], dcMo.getMor(), dsMo.getMor(), legacyCloudStackLayoutFilePair[0], dcMo.getMor(), true); - - dsMo.moveDatastoreFile(vmwareLayoutFilePair[1], dcMo.getMor(), dsMo.getMor(), legacyCloudStackLayoutFilePair[1], dcMo.getMor(), true); return true; } @@ -309,6 +290,7 @@ public class VmwareStorageProcessor implements StorageProcessor { DatastoreMO dsMo = new DatastoreMO(context, morDatastore); String vmdkName = volume.getName(); + String vmdkFileBaseName = null; if (srcStore == null) { // create a root volume for blank VM (created from ISO) String dummyVmName = this.hostService.getWorkerName(context, cmd, 0); @@ -319,8 +301,9 @@ public class VmwareStorageProcessor implements StorageProcessor { throw new Exception("Unable to create a dummy VM for volume creation"); } - String vmdkFilePair[] = VmwareStorageLayoutHelper.getVmdkFilePairDatastorePath(dsMo, null, vmdkName, VmwareStorageLayoutType.CLOUDSTACK_LEGACY, true // we only use the first file in the pair, linked or not will not matter - ); + vmdkFileBaseName = vmMo.getVmdkFileBaseNames().get(0); + // we only use the first file in the pair, linked or not will not matter + String vmdkFilePair[] = VmwareStorageLayoutHelper.getVmdkFilePairDatastorePath(dsMo, null, vmdkFileBaseName, VmwareStorageLayoutType.CLOUDSTACK_LEGACY, true); String volumeDatastorePath = vmdkFilePair[0]; synchronized (this) { s_logger.info("Delete file if exists in datastore to clear the way for creating the volume. file: " + volumeDatastorePath); @@ -353,6 +336,14 @@ public class VmwareStorageProcessor implements StorageProcessor { vmMo = new ClusterMO(context, morCluster).findVmOnHyperHost(vmdkName); assert (vmMo != null); + vmdkFileBaseName = vmMo.getVmdkFileBaseNames().get(0); // TO-DO: Support for base template containing multiple disks + s_logger.info("Move volume out of volume-wrapper VM "); + String[] vmwareLayoutFilePair = VmwareStorageLayoutHelper.getVmdkFilePairDatastorePath(dsMo, vmdkName, vmdkFileBaseName, VmwareStorageLayoutType.VMWARE, !_fullCloneFlag); + String[] legacyCloudStackLayoutFilePair = VmwareStorageLayoutHelper.getVmdkFilePairDatastorePath(dsMo, vmdkName, vmdkFileBaseName, VmwareStorageLayoutType.CLOUDSTACK_LEGACY, !_fullCloneFlag); + + dsMo.moveDatastoreFile(vmwareLayoutFilePair[0], dcMo.getMor(), dsMo.getMor(), legacyCloudStackLayoutFilePair[0], dcMo.getMor(), true); + dsMo.moveDatastoreFile(vmwareLayoutFilePair[1], dcMo.getMor(), dsMo.getMor(), legacyCloudStackLayoutFilePair[1], dcMo.getMor(), true); + s_logger.info("detach disks from volume-wrapper VM " + vmdkName); vmMo.detachAllDisks(); @@ -365,11 +356,11 @@ public class VmwareStorageProcessor implements StorageProcessor { // restoreVM - move the new ROOT disk into corresponding VM folder String vmInternalCSName = volume.getVmName(); if (dsMo.folderExists(String.format("[%s]", dsMo.getName()), vmInternalCSName)) { - VmwareStorageLayoutHelper.syncVolumeToVmDefaultFolder(dcMo, vmInternalCSName, dsMo, vmdkName); + VmwareStorageLayoutHelper.syncVolumeToVmDefaultFolder(dcMo, vmInternalCSName, dsMo, vmdkFileBaseName); } VolumeObjectTO newVol = new VolumeObjectTO(); - newVol.setPath(vmdkName); + newVol.setPath(vmdkFileBaseName); newVol.setSize(volume.getSize()); return new CopyCmdAnswer(newVol); } catch (Throwable e) { @@ -623,16 +614,31 @@ public class VmwareStorageProcessor implements StorageProcessor { vmMo.cloneFromCurrentSnapshot(workerVmName, 0, 4, volumeDeviceInfo.second(), VmwareHelper.getDiskDeviceDatastore(volumeDeviceInfo.first())); clonedVm = cloneResult.first(); - clonedVm.exportVm(secondaryMountPoint + "/" + installPath, templateUniqueName, true, false); + clonedVm.exportVm(secondaryMountPoint + "/" + installPath, templateUniqueName, false, false); + + // Get VMDK filename + String templateVMDKName = ""; + File[] files = new File(installFullPath).listFiles(); + if(files != null) { + for(File file : files) { + String fileName = file.getName(); + if(fileName.toLowerCase().startsWith(templateUniqueName) && fileName.toLowerCase().endsWith(".vmdk")) { + templateVMDKName += fileName; + break; + } + } + } + + long physicalSize = new File(installFullPath + "/" + templateVMDKName).length(); + OVAProcessor processor = new OVAProcessor(); - long physicalSize = new File(installFullPath + "/" + templateUniqueName + ".ova").length(); - VmdkProcessor processor = new VmdkProcessor(); Map params = new HashMap(); params.put(StorageLayer.InstanceConfigKey, _storage); - processor.configure("VMDK Processor", params); + processor.configure("OVA Processor", params); long virtualSize = processor.getTemplateVirtualSize(installFullPath, templateUniqueName); postCreatePrivateTemplate(installFullPath, templateId, templateUniqueName, physicalSize, virtualSize); + writeMetaOvaForTemplate(installFullPath, templateUniqueName + ".ovf", templateVMDKName, templateUniqueName, physicalSize); return new Ternary(installPath + "/" + templateUniqueName + ".ova", physicalSize, virtualSize); } finally { @@ -850,11 +856,11 @@ public class VmwareStorageProcessor implements StorageProcessor { } long physicalSize = new File(installFullPath + "/" + templateVMDKName).length(); - VmdkProcessor processor = new VmdkProcessor(); + OVAProcessor processor = new OVAProcessor(); // long physicalSize = new File(installFullPath + "/" + templateUniqueName + ".ova").length(); Map params = new HashMap(); params.put(StorageLayer.InstanceConfigKey, _storage); - processor.configure("VMDK Processor", params); + processor.configure("OVA Processor", params); long virtualSize = processor.getTemplateVirtualSize(installFullPath, templateUniqueName); postCreatePrivateTemplate(installFullPath, templateId, templateUniqueName, physicalSize, virtualSize); @@ -951,7 +957,7 @@ public class VmwareStorageProcessor implements StorageProcessor { String backupUuid = UUID.randomUUID().toString(); Pair snapshotInfo = exportVolumeToSecondaryStroage(vmMo, volumePath, secStorageUrl, installPath, backupUuid, workerVmName); - return new Ternary(backupUuid + "/" + backupUuid, snapshotInfo.first(), snapshotInfo.second()); + return new Ternary(backupUuid, snapshotInfo.first(), snapshotInfo.second()); } @Override @@ -994,32 +1000,26 @@ public class VmwareStorageProcessor implements StorageProcessor { CopyCmdAnswer answer = null; try { - vmMo = hyperHost.findVmOnHyperHost(vmName); - if (vmMo == null) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Unable to find owner VM for BackupSnapshotCommand on host " + hyperHost.getHyperHostName() + ", will try within datacenter"); - } - - vmMo = hyperHost.findVmOnPeerHyperHost(vmName); + if(vmName != null) { + vmMo = hyperHost.findVmOnHyperHost(vmName); if (vmMo == null) { - dsMo = new DatastoreMO(hyperHost.getContext(), morDs); - - workerVMName = hostService.getWorkerName(context, cmd, 0); - - vmMo = HypervisorHostHelper.createWorkerVM(hyperHost, dsMo, workerVMName); - - if (vmMo == null) { - throw new Exception("Failed to find the newly create or relocated VM. vmName: " + workerVMName); + if(s_logger.isDebugEnabled()) { + s_logger.debug("Unable to find owner VM for BackupSnapshotCommand on host " + hyperHost.getHyperHostName() + ", will try within datacenter"); } - workerVm = vmMo; - - // attach volume to worker VM - String datastoreVolumePath = dsMo.getDatastorePath(volumePath + ".vmdk"); - vmMo.attachDisk(new String[] {datastoreVolumePath}, morDs); - } else { - s_logger.info("Using owner VM " + vmName + " for snapshot operation"); - hasOwnerVm = true; + vmMo = hyperHost.findVmOnPeerHyperHost(vmName); } + } + if(vmMo == null) { + dsMo = new DatastoreMO(hyperHost.getContext(), morDs); + workerVMName = hostService.getWorkerName(context, cmd, 0); + vmMo = HypervisorHostHelper.createWorkerVM(hyperHost, dsMo, workerVMName); + if (vmMo == null) { + throw new Exception("Failed to find the newly create or relocated VM. vmName: " + workerVMName); + } + workerVm = vmMo; + // attach volume to worker VM + String datastoreVolumePath = dsMo.getDatastorePath(volumePath + ".vmdk"); + vmMo.attachDisk(new String[] { datastoreVolumePath }, morDs); } else { s_logger.info("Using owner VM " + vmName + " for snapshot operation"); hasOwnerVm = true; @@ -1040,8 +1040,25 @@ public class VmwareStorageProcessor implements StorageProcessor { answer = new CopyCmdAnswer(details); } else { details = "Successfully backedUp the snapshot with Uuid: " + snapshotUuid + " to secondary storage."; + + // Get snapshot physical size + long physicalSize = 0l; + String secondaryMountPoint = mountService.getMountPoint(secondaryStorageUrl); + String snapshotDir = destSnapshot.getPath() + "/" + snapshotBackupUuid; + File[] files = new File(secondaryMountPoint + "/" + snapshotDir).listFiles(); + if(files != null) { + for(File file : files) { + String fileName = file.getName(); + if(fileName.toLowerCase().startsWith(snapshotBackupUuid) && fileName.toLowerCase().endsWith(".vmdk")) { + physicalSize = new File(secondaryMountPoint + "/" + snapshotDir + "/" + fileName).length(); + break; + } + } + } + SnapshotObjectTO newSnapshot = new SnapshotObjectTO(); - newSnapshot.setPath(destSnapshot.getPath() + "/" + snapshotBackupUuid); + newSnapshot.setPath(snapshotDir + "/" + snapshotBackupUuid); + newSnapshot.setPhysicalSize(physicalSize); answer = new CopyCmdAnswer(newSnapshot); } } finally { @@ -1155,22 +1172,13 @@ public class VmwareStorageProcessor implements StorageProcessor { if (isAttach && isManaged) { Map details = disk.getDetails(); - morDs = - hostService.getVmfsDatastore(hyperHost, VmwareResource.getDatastoreName(iScsiName), storageHost, storagePort, VmwareResource.trimIqn(iScsiName), - details.get(DiskTO.CHAP_INITIATOR_USERNAME), details.get(DiskTO.CHAP_INITIATOR_SECRET), details.get(DiskTO.CHAP_TARGET_USERNAME), - details.get(DiskTO.CHAP_TARGET_SECRET)); - - DatastoreMO dsMo = new DatastoreMO(hostService.getServiceContext(null), morDs); - - String volumeDatastorePath = String.format("[%s] %s.vmdk", dsMo.getName(), dsMo.getName()); - - if (!dsMo.fileExists(volumeDatastorePath)) { - hostService.createVmdk(cmd, dsMo, volumeDatastorePath, volumeTO.getSize()); - } - } else { - morDs = - HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, - isManaged ? VmwareResource.getDatastoreName(iScsiName) : primaryStore.getUuid()); + morDs = hostService.prepareManagedStorage(hyperHost, iScsiName, storageHost, storagePort, + details.get(DiskTO.CHAP_INITIATOR_USERNAME), details.get(DiskTO.CHAP_INITIATOR_SECRET), + details.get(DiskTO.CHAP_TARGET_USERNAME), details.get(DiskTO.CHAP_TARGET_SECRET), + volumeTO.getSize(), cmd); + } + else { + morDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, isManaged ? VmwareResource.getDatastoreName(iScsiName) : primaryStore.getUuid()); } if (morDs == null) { @@ -1272,9 +1280,11 @@ public class VmwareStorageProcessor implements StorageProcessor { if (isAttach) { vmMo.mountToolsInstaller(); } else { - try { - vmMo.unmountToolsInstaller(); - } catch (Throwable e) { + try{ + if (!vmMo.unmountToolsInstaller()) { + return new AttachAnswer("Failed to unmount vmware-tools installer ISO as the corresponding CDROM device is locked by VM. Please unmount the CDROM device inside the VM and ret-try."); + } + } catch(Throwable e){ vmMo.detachIso(null); } } @@ -1455,7 +1465,7 @@ public class VmwareStorageProcessor implements StorageProcessor { // tear down all devices first before we destroy the VM to avoid accidently delete disk backing files if (VmwareResource.getVmState(vmMo) != State.Stopped) { - vmMo.safePowerOff(_shutdown_waitMs); + vmMo.safePowerOff(_shutdownWaitMs); } // call this before calling detachAllDisksExcept diff --git a/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareStorageSubsystemCommandHandler.java b/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareStorageSubsystemCommandHandler.java index 8391c6416d8..39c353931d8 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareStorageSubsystemCommandHandler.java +++ b/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareStorageSubsystemCommandHandler.java @@ -89,6 +89,9 @@ public class VmwareStorageSubsystemCommandHandler extends StorageSubsystemComman String name = path.substring(index + 1); storageManager.createOva(parentPath + File.separator + path, name); vol.setPath(path + File.separator + name + ".ova"); + } else if (srcData.getObjectType() == DataObjectType.TEMPLATE) { + // sync template from NFS cache to S3 in NFS migration to S3 case + storageManager.createOvaForTemplate((TemplateObjectTO)srcData); } else if (srcData.getObjectType() == DataObjectType.SNAPSHOT && destData.getObjectType() == DataObjectType.TEMPLATE) { //create template from snapshot on src at first, then copy it to s3 TemplateObjectTO cacheTemplate = (TemplateObjectTO)destData; diff --git a/plugins/hypervisors/vmware/src/org/apache/cloudstack/storage/motion/VmwareStorageMotionStrategy.java b/plugins/hypervisors/vmware/src/org/apache/cloudstack/storage/motion/VmwareStorageMotionStrategy.java index 3930d8ec68d..e1527f96b15 100644 --- a/plugins/hypervisors/vmware/src/org/apache/cloudstack/storage/motion/VmwareStorageMotionStrategy.java +++ b/plugins/hypervisors/vmware/src/org/apache/cloudstack/storage/motion/VmwareStorageMotionStrategy.java @@ -99,7 +99,7 @@ public class VmwareStorageMotionStrategy implements DataMotionStrategy { try { VMInstanceVO instance = instanceDao.findById(vmTo.getId()); if (instance != null) { - if (srcHost.getClusterId() == destHost.getClusterId()) { + if (srcHost.getClusterId().equals(destHost.getClusterId())) { answer = migrateVmWithVolumesWithinCluster(instance, vmTo, srcHost, destHost, volumeMap); } else { answer = migrateVmWithVolumesAcrossCluster(instance, vmTo, srcHost, destHost, volumeMap); @@ -119,7 +119,7 @@ public class VmwareStorageMotionStrategy implements DataMotionStrategy { } private Answer migrateVmWithVolumesAcrossCluster(VMInstanceVO vm, VirtualMachineTO to, Host srcHost, Host destHost, Map volumeToPool) - throws AgentUnavailableException { + throws AgentUnavailableException { // Initiate migration of a virtual machine with it's volumes. try { @@ -157,7 +157,7 @@ public class VmwareStorageMotionStrategy implements DataMotionStrategy { } private Answer migrateVmWithVolumesWithinCluster(VMInstanceVO vm, VirtualMachineTO to, Host srcHost, Host destHost, Map volumeToPool) - throws AgentUnavailableException { + throws AgentUnavailableException { // Initiate migration of a virtual machine with it's volumes. try { diff --git a/plugins/hypervisors/vmware/test/com/cloud/hypervisor/vmware/resource/VmwareResourceTest.java b/plugins/hypervisors/vmware/test/com/cloud/hypervisor/vmware/resource/VmwareResourceTest.java index 9f817add11d..2e3d41c0485 100644 --- a/plugins/hypervisors/vmware/test/com/cloud/hypervisor/vmware/resource/VmwareResourceTest.java +++ b/plugins/hypervisors/vmware/test/com/cloud/hypervisor/vmware/resource/VmwareResourceTest.java @@ -86,7 +86,7 @@ public class VmwareResourceTest { doReturn(false).when(vmSpec).getLimitCpuUse(); when(vmMo.configureVm(vmConfigSpec)).thenReturn(true); - ScaleVmAnswer answer = _resource.execute(cmd); + _resource.execute(cmd); verify(_resource).execute(cmd); } diff --git a/plugins/hypervisors/vmware/test/org/apache/cloudstack/storage/motion/VmwareStorageMotionStrategyTest.java b/plugins/hypervisors/vmware/test/org/apache/cloudstack/storage/motion/VmwareStorageMotionStrategyTest.java index 44296c93b2b..e3cc2f6056f 100644 --- a/plugins/hypervisors/vmware/test/org/apache/cloudstack/storage/motion/VmwareStorageMotionStrategyTest.java +++ b/plugins/hypervisors/vmware/test/org/apache/cloudstack/storage/motion/VmwareStorageMotionStrategyTest.java @@ -142,7 +142,7 @@ public class VmwareStorageMotionStrategyTest { when(agentMgr.send(anyLong(), isA(MigrateWithStorageCommand.class))).thenReturn(migAnswerMock); strategy.copyAsync(volumeMap, to, srcHost, destHost, caller); - assertTrue("Migration within cluster isn't successful.", this.result.isSuccess()); + assertTrue("Migration within cluster isn't successful.", result.isSuccess()); } @Test @@ -166,7 +166,7 @@ public class VmwareStorageMotionStrategyTest { when(agentMgr.send(anyLong(), isA(MigrateWithStorageCommand.class))).thenReturn(migAnswerMock); strategy.copyAsync(volumeMap, to, srcHost, destHost, caller); - assertFalse("Migration within cluster didn't fail.", this.result.isSuccess()); + assertFalse("Migration within cluster didn't fail.", result.isSuccess()); } @Test @@ -190,7 +190,7 @@ public class VmwareStorageMotionStrategyTest { when(agentMgr.send(anyLong(), isA(MigrateWithStorageCommand.class))).thenReturn(migAnswerMock); strategy.copyAsync(volumeMap, to, srcHost, destHost, caller); - assertTrue("Migration across cluster isn't successful.", this.result.isSuccess()); + assertTrue("Migration across cluster isn't successful.", result.isSuccess()); } @Test @@ -214,25 +214,20 @@ public class VmwareStorageMotionStrategyTest { when(agentMgr.send(anyLong(), isA(MigrateWithStorageCommand.class))).thenReturn(migAnswerMock); strategy.copyAsync(volumeMap, to, srcHost, destHost, caller); - assertFalse("Migration across cluster didn't fail.", this.result.isSuccess()); + assertFalse("Migration across cluster didn't fail.", result.isSuccess()); } private class MockContext extends AsyncRpcContext { - final Map volumeToPool; - final AsyncCallFuture future; - /** * @param callback */ public MockContext(AsyncCompletionCallback callback, AsyncCallFuture future, Map volumeToPool) { super(callback); - this.volumeToPool = volumeToPool; - this.future = future; } } protected Void mockCallBack(AsyncCallbackDispatcher callback, MockContext context) { - this.result = callback.getResult(); + result = callback.getResult(); return null; } diff --git a/plugins/hypervisors/xen/pom.xml b/plugins/hypervisors/xen/pom.xml index 7011218bdbc..39c0908070e 100644 --- a/plugins/hypervisors/xen/pom.xml +++ b/plugins/hypervisors/xen/pom.xml @@ -33,8 +33,6 @@ org.apache.httpcomponents httpclient - - 4.2.2 compile diff --git a/plugins/hypervisors/xen/src/com/cloud/hypervisor/XenServerGuru.java b/plugins/hypervisors/xen/src/com/cloud/hypervisor/XenServerGuru.java index bd10cb013b1..529e26125f3 100644 --- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/XenServerGuru.java +++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/XenServerGuru.java @@ -16,20 +16,56 @@ // under the License. package com.cloud.hypervisor; +import java.util.ArrayList; +import java.util.List; + import javax.ejb.Local; import javax.inject.Inject; +import com.cloud.agent.api.Command; +import com.cloud.agent.api.to.DataObjectType; +import com.cloud.agent.api.to.DataStoreTO; +import com.cloud.agent.api.to.DataTO; +import com.cloud.agent.api.to.DiskTO; +import com.cloud.agent.api.to.NfsTO; import com.cloud.agent.api.to.VirtualMachineTO; +import com.cloud.host.HostInfo; +import com.cloud.host.HostVO; +import com.cloud.host.dao.HostDao; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.storage.GuestOSVO; +import com.cloud.storage.Volume; +import com.cloud.storage.VolumeVO; import com.cloud.storage.dao.GuestOSDao; +import com.cloud.storage.dao.VolumeDao; import com.cloud.template.VirtualMachineTemplate.BootloaderType; +import com.cloud.utils.Pair; +import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; +import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint; +import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector; +import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory; +import org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope; +import org.apache.cloudstack.storage.command.CopyCommand; +import org.apache.cloudstack.storage.command.DettachCommand; +import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; +import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; + @Local(value = HypervisorGuru.class) public class XenServerGuru extends HypervisorGuruBase implements HypervisorGuru { @Inject GuestOSDao _guestOsDao; + @Inject + EndPointSelector endPointSelector; + @Inject + HostDao hostDao; + @Inject + VolumeDao _volumeDao; + @Inject + PrimaryDataStoreDao _storagePoolDao; + @Inject + VolumeDataFactory _volFactory; protected XenServerGuru() { super(); @@ -60,4 +96,66 @@ public class XenServerGuru extends HypervisorGuruBase implements HypervisorGuru public boolean trackVmHostChange() { return true; } + + @Override + public List finalizeExpungeVolumes(VirtualMachine vm) { + List commands = new ArrayList(); + + List volumes = _volumeDao.findByInstance(vm.getId()); + + if (volumes != null) { + for (VolumeVO volume : volumes) { + if (volume.getVolumeType() == Volume.Type.DATADISK) { + StoragePoolVO storagePool = _storagePoolDao.findById(volume.getPoolId()); + + // storagePool should be null if we are expunging a volume that was never + // attached to a VM that was started (the "trick" for storagePool to be null + // is that none of the VMs this volume may have been attached to were ever started, + // so the volume was never assigned to a storage pool) + if (storagePool != null && storagePool.isManaged()) { + DataTO volTO = _volFactory.getVolume(volume.getId()).getTO(); + DiskTO disk = new DiskTO(volTO, volume.getDeviceId(), volume.getPath(), volume.getVolumeType()); + + DettachCommand cmd = new DettachCommand(disk, vm.getInstanceName()); + + cmd.setManaged(true); + + cmd.setStorageHost(storagePool.getHostAddress()); + cmd.setStoragePort(storagePool.getPort()); + + cmd.set_iScsiName(volume.get_iScsiName()); + + commands.add(cmd); + } + } + } + } + + return commands; + } + + @Override + public Pair getCommandHostDelegation(long hostId, Command cmd) { + if (cmd instanceof CopyCommand) { + CopyCommand cpyCommand = (CopyCommand)cmd; + DataTO srcData = cpyCommand.getSrcTO(); + DataTO destData = cpyCommand.getDestTO(); + + if (srcData.getObjectType() == DataObjectType.SNAPSHOT && destData.getObjectType() == DataObjectType.TEMPLATE) { + DataStoreTO srcStore = srcData.getDataStore(); + DataStoreTO destStore = destData.getDataStore(); + if (srcStore instanceof NfsTO && destStore instanceof NfsTO) { + HostVO host = hostDao.findById(hostId); + EndPoint ep = endPointSelector.selectHypervisorHost(new ZoneScope(host.getDataCenterId())); + host = hostDao.findById(ep.getId()); + hostDao.loadDetails(host); + boolean snapshotHotFix = Boolean.parseBoolean(host.getDetail(HostInfo.XS620_SNAPSHOT_HOTFIX)); + if (snapshotHotFix) { + return new Pair(Boolean.TRUE, new Long(ep.getId())); + } + } + } + } + return new Pair(Boolean.FALSE, new Long(hostId)); + } } diff --git a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/discoverer/XcpServerDiscoverer.java b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/discoverer/XcpServerDiscoverer.java index 705aa4cd14b..58fe0159815 100755 --- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/discoverer/XcpServerDiscoverer.java +++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/discoverer/XcpServerDiscoverer.java @@ -34,13 +34,6 @@ import javax.persistence.EntityExistsException; import org.apache.log4j.Logger; import org.apache.xmlrpc.XmlRpcException; -import com.xensource.xenapi.Connection; -import com.xensource.xenapi.Host; -import com.xensource.xenapi.Pool; -import com.xensource.xenapi.Session; -import com.xensource.xenapi.Types.SessionAuthenticationFailed; -import com.xensource.xenapi.Types.XenAPIException; - import com.cloud.agent.AgentManager; import com.cloud.agent.Listener; import com.cloud.agent.api.AgentControlAnswer; @@ -82,6 +75,7 @@ import com.cloud.hypervisor.xen.resource.XenServer602Resource; import com.cloud.hypervisor.xen.resource.XenServer610Resource; import com.cloud.hypervisor.xen.resource.XenServer620Resource; import com.cloud.hypervisor.xen.resource.XenServerConnectionPool; +import com.cloud.hypervisor.xen.resource.Xenserver625Resource; import com.cloud.resource.Discoverer; import com.cloud.resource.DiscovererBase; import com.cloud.resource.ResourceManager; @@ -98,6 +92,12 @@ import com.cloud.utils.db.QueryBuilder; import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.HypervisorVersionChangedException; +import com.xensource.xenapi.Connection; +import com.xensource.xenapi.Host; +import com.xensource.xenapi.Pool; +import com.xensource.xenapi.Session; +import com.xensource.xenapi.Types.SessionAuthenticationFailed; +import com.xensource.xenapi.Types.XenAPIException; @Local(value = Discoverer.class) public class XcpServerDiscoverer extends DiscovererBase implements Discoverer, Listener, ResourceStateAdapter { @@ -112,6 +112,7 @@ public class XcpServerDiscoverer extends DiscovererBase implements Discoverer, L protected String _guestNic; protected boolean _setupMultipath; protected String _instance; + private String xs620snapshothotfix = "Xenserver-Vdi-Copy-HotFix"; @Inject protected AlertManager _alertMgr; @@ -149,6 +150,11 @@ public class XcpServerDiscoverer extends DiscovererBase implements Discoverer, L } } + protected boolean xenserverHotFixEnabled() { + //temporary fix, we should call xenserver api to get the hot fix is enabled or not. + return Boolean.parseBoolean(_configDao.getValue(Config.XenServerHotFix.name())); + } + @Override public Map> find(long dcId, Long podId, Long clusterId, URI url, String username, String password, List hostTags) throws DiscoveryException { @@ -189,8 +195,7 @@ public class XcpServerDiscoverer extends DiscovererBase implements Discoverer, L String hostIp = ia.getHostAddress(); Queue pass = new LinkedList(); pass.add(password); - String masterIp = _connPool.getMasterIp(hostIp, username, pass); - conn = _connPool.masterConnect(masterIp, username, pass); + conn = _connPool.getConnect(hostIp, username, pass); if (conn == null) { String msg = "Unable to get a connection to " + url; s_logger.debug(msg); @@ -274,6 +279,8 @@ public class XcpServerDiscoverer extends DiscovererBase implements Discoverer, L hostOS = record.softwareVersion.get("platform_name"); } + //Boolean xs620hotfix = record.tags.contains(xs620snapshothotfix); + Boolean xs620hotfix = xenserverHotFixEnabled(); String hostOSVer = prodVersion; String hostKernelVer = record.softwareVersion.get("linux"); @@ -303,6 +310,7 @@ public class XcpServerDiscoverer extends DiscovererBase implements Discoverer, L details.put(HostInfo.HOST_OS_VERSION, hostOSVer); details.put(HostInfo.HOST_OS_KERNEL_VERSION, hostKernelVer); details.put(HostInfo.HYPERVISOR_VERSION, xenVersion); + details.put(HostInfo.XS620_SNAPSHOT_HOTFIX, xs620hotfix.toString()); String privateNetworkLabel = _networkMgr.getDefaultManagementTrafficLabel(dcId, HypervisorType.XenServer); String storageNetworkLabel = _networkMgr.getDefaultStorageTrafficLabel(dcId, HypervisorType.XenServer); @@ -389,7 +397,7 @@ public class XcpServerDiscoverer extends DiscovererBase implements Discoverer, L password = host.getDetail("password"); pass.add(password); String address = host.getPrivateIpAddress(); - Connection hostConn = _connPool.slaveConnect(address, username, pass); + Connection hostConn = _connPool.getConnect(address, username, pass); if (hostConn == null) { continue; } @@ -402,9 +410,9 @@ public class XcpServerDiscoverer extends DiscovererBase implements Discoverer, L } catch (Exception e) { s_logger.warn("Can not get master ip address from host " + address); } finally { - try { - Session.localLogout(hostConn); - } catch (Exception e) { + try{ + Session.logout(hostConn); + } catch (Exception e ) { } hostConn.dispose(); hostConn = null; @@ -452,9 +460,21 @@ public class XcpServerDiscoverer extends DiscovererBase implements Discoverer, L return new XenServer602Resource(); else if (prodBrand.equals("XenServer") && prodVersion.equals("6.1.0")) return new XenServer610Resource(); - else if (prodBrand.equals("XenServer") && prodVersion.equals("6.2.0")) - return new XenServer620Resource(); - else if (prodBrand.equals("XenServer") && prodVersion.equals("5.6.100")) { + else if (prodBrand.equals("XenServer") && prodVersion.equals("6.2.0")) { + /* + Set tags =record.tags; + if (tags.contains(xs620snapshothotfix)) { + return new Xenserver625Resource(); + } else { + return new XenServer620Resource(); + }*/ + boolean hotfix = xenserverHotFixEnabled(); + if (hotfix) { + return new Xenserver625Resource(); + } else { + return new XenServer620Resource(); + } + } else if (prodBrand.equals("XenServer") && prodVersion.equals("5.6.100")) { String prodVersionTextShort = record.softwareVersion.get("product_version_text_short").trim(); if ("5.6 SP2".equals(prodVersionTextShort)) { return new XenServer56SP2Resource(); @@ -607,7 +627,12 @@ public class XcpServerDiscoverer extends DiscovererBase implements Discoverer, L } else if (prodBrand.equals("XenServer") && prodVersion.equals("6.1.0")) { resource = XenServer610Resource.class.getName(); } else if (prodBrand.equals("XenServer") && prodVersion.equals("6.2.0")) { - resource = XenServer620Resource.class.getName(); + String hotfix = details.get("Xenserer620HotFix"); + if (hotfix != null && hotfix.equalsIgnoreCase("Xenserver-Vdi-Copy-HotFix")) { + resource = Xenserver625Resource.class.getName(); + } else { + resource = XenServer620Resource.class.getName(); + } } else if (prodBrand.equals("XenServer") && prodVersion.equals("5.6.100")) { String prodVersionTextShort = details.get("product_version_text_short").trim(); if ("5.6 SP2".equals(prodVersionTextShort)) { @@ -748,10 +773,10 @@ public class XcpServerDiscoverer extends DiscovererBase implements Discoverer, L } @Override - protected HashMap buildConfigParams(HostVO host){ + protected HashMap buildConfigParams(HostVO host) { HashMap params = super.buildConfigParams(host); DataCenterVO zone = _dcDao.findById(host.getDataCenterId()); - if ( zone != null ) { + if (zone != null) { boolean securityGroupEnabled = zone.isSecurityGroupEnabled(); params.put("securitygroupenabled", Boolean.toString(securityGroupEnabled)); } diff --git a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixHelper.java b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixHelper.java index 605a0606d7e..2524bc31635 100644 --- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixHelper.java +++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixHelper.java @@ -27,469 +27,469 @@ import org.apache.log4j.Logger; */ public class CitrixHelper { private static final Logger s_logger = Logger.getLogger(CitrixHelper.class); - private static final HashMap _xcp100GuestOsMap = new HashMap(70); - private static final HashMap _xcp160GuestOsMap = new HashMap(70); - private static final HashMap _xenServerGuestOsMap = new HashMap(70); - private static final HashMap _xenServer56FP1GuestOsMap = new HashMap(70); - private static final HashMap _xenServer56FP2GuestOsMap = new HashMap(70); - private static final HashMap _xenServer600GuestOsMap = new HashMap(70); - private static final HashMap _xenServer602GuestOsMap = new HashMap(70); - private static final HashMap _xenServer610GuestOsMap = new HashMap(70); - private static final HashMap _xenServer620GuestOsMap = new HashMap(70); - private static final HashMap _xenServer620GuestOsMemoryMap = new HashMap(70); - private static final HashMap _xenServer610GuestOsMemoryMap = new HashMap(70); - private static final HashMap _xenServer602GuestOsMemoryMap = new HashMap(70); - private static final HashMap _xenServer600GuestOsMemoryMap = new HashMap(70); - private static final HashMap _xenServer56SP2GuestOsMemoryMap = new HashMap(70); - private static final HashMap _xenServer56FP1GuestOsMemoryMap = new HashMap(70); - private static final ArrayList _guestOsList = new ArrayList(70); + private static final HashMap Xcp100GuestOsMap = new HashMap(70); + private static final HashMap Xcp160GuestOsMap = new HashMap(70); + private static final HashMap XenServerGuestOsMap = new HashMap(70); + private static final HashMap XenServer56FP1GuestOsMap = new HashMap(70); + private static final HashMap XenServer56FP2GuestOsMap = new HashMap(70); + private static final HashMap XenServer600GuestOsMap = new HashMap(70); + private static final HashMap XenServer602GuestOsMap = new HashMap(70); + private static final HashMap XenServer610GuestOsMap = new HashMap(70); + private static final HashMap XenServer620GuestOsMap = new HashMap(70); + private static final HashMap XenServer620GuestOsMemoryMap = new HashMap(70); + private static final HashMap XenServer610GuestOsMemoryMap = new HashMap(70); + private static final HashMap XenServer602GuestOsMemoryMap = new HashMap(70); + private static final HashMap XenServer600GuestOsMemoryMap = new HashMap(70); + private static final HashMap XenServer56SP2GuestOsMemoryMap = new HashMap(70); + private static final HashMap XenServer56FP1GuestOsMemoryMap = new HashMap(70); + private static final ArrayList GuestOsList = new ArrayList(70); static { - _xcp100GuestOsMap.put("CentOS 4.5 (32-bit)", "CentOS 4.5 (32-bit)"); - _xcp100GuestOsMap.put("CentOS 4.6 (32-bit)", "CentOS 4.6 (32-bit)"); - _xcp100GuestOsMap.put("CentOS 4.7 (32-bit)", "CentOS 4.7 (32-bit)"); - _xcp100GuestOsMap.put("CentOS 4.8 (32-bit)", "CentOS 4.8 (32-bit)"); - _xcp100GuestOsMap.put("CentOS 5.0 (32-bit)", "CentOS 5 (32-bit)"); - _xcp100GuestOsMap.put("CentOS 5.0 (64-bit)", "CentOS 5 (64-bit)"); - _xcp100GuestOsMap.put("CentOS 5.1 (32-bit)", "CentOS 5 (32-bit)"); - _xcp100GuestOsMap.put("CentOS 5.1 (64-bit)", "CentOS 5 (64-bit)"); - _xcp100GuestOsMap.put("CentOS 5.2 (32-bit)", "CentOS 5 (32-bit)"); - _xcp100GuestOsMap.put("CentOS 5.2 (64-bit)", "CentOS 5 (64-bit)"); - _xcp100GuestOsMap.put("CentOS 5.3 (32-bit)", "CentOS 5 (32-bit)"); - _xcp100GuestOsMap.put("CentOS 5.3 (64-bit)", "CentOS 5 (64-bit)"); - _xcp100GuestOsMap.put("CentOS 5.4 (32-bit)", "CentOS 5 (32-bit)"); - _xcp100GuestOsMap.put("CentOS 5.4 (64-bit)", "CentOS 5 (64-bit)"); - _xcp100GuestOsMap.put("CentOS 5.5 (32-bit)", "CentOS 5 (32-bit)"); - _xcp100GuestOsMap.put("CentOS 5.5 (64-bit)", "CentOS 5 (64-bit)"); - _xcp100GuestOsMap.put("Debian GNU/Linux 5.0 (32-bit)", "Debian Lenny 5.0 (32-bit)"); - _xcp100GuestOsMap.put("Debian GNU/Linux 6(32-bit)", "Debian Squeeze 6.0 (32-bit)"); - _xcp100GuestOsMap.put("Debian GNU/Linux 6(64-bit)", "Debian Squeeze 6.0 (64-bit) (experimental)"); - _xcp100GuestOsMap.put("Debian GNU/Linux 7(32-bit)", "Debian Squeeze 6.0 (32-bit)"); - _xcp100GuestOsMap.put("Debian GNU/Linux 7(64-bit)", "Debian Squeeze 6.0 (64-bit) (experimental)"); - _xcp100GuestOsMap.put("Oracle Enterprise Linux 5.0 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xcp100GuestOsMap.put("Oracle Enterprise Linux 5.0 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xcp100GuestOsMap.put("Oracle Enterprise Linux 5.1 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xcp100GuestOsMap.put("Oracle Enterprise Linux 5.1 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xcp100GuestOsMap.put("Oracle Enterprise Linux 5.2 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xcp100GuestOsMap.put("Oracle Enterprise Linux 5.2 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xcp100GuestOsMap.put("Oracle Enterprise Linux 5.3 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xcp100GuestOsMap.put("Oracle Enterprise Linux 5.3 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xcp100GuestOsMap.put("Oracle Enterprise Linux 5.4 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xcp100GuestOsMap.put("Oracle Enterprise Linux 5.4 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xcp100GuestOsMap.put("Oracle Enterprise Linux 5.5 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xcp100GuestOsMap.put("Oracle Enterprise Linux 5.5 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xcp100GuestOsMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", "Red Hat Enterprise Linux 4.5 (32-bit)"); - _xcp100GuestOsMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", "Red Hat Enterprise Linux 4.6 (32-bit)"); - _xcp100GuestOsMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", "Red Hat Enterprise Linux 4.7 (32-bit)"); - _xcp100GuestOsMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", "Red Hat Enterprise Linux 4.8 (32-bit)"); - _xcp100GuestOsMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xcp100GuestOsMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xcp100GuestOsMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xcp100GuestOsMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xcp100GuestOsMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xcp100GuestOsMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xcp100GuestOsMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xcp100GuestOsMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xcp100GuestOsMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xcp100GuestOsMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xcp100GuestOsMap.put("Red Hat Enterprise Linux 5.5 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xcp100GuestOsMap.put("Red Hat Enterprise Linux 5.5 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xcp100GuestOsMap.put("Red Hat Enterprise Linux 6.0 (32-bit)", "Red Hat Enterprise Linux 6 (32-bit)"); - _xcp100GuestOsMap.put("Red Hat Enterprise Linux 6.0 (64-bit)", "Red Hat Enterprise Linux 6 (64-bit)"); - _xcp100GuestOsMap.put("SUSE Linux Enterprise Server 9 SP4 (32-bit)", "SUSE Linux Enterprise Server 9 SP4"); - _xcp100GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", "SUSE Linux Enterprise Server 10 SP1"); - _xcp100GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", "SUSE Linux Enterprise Server 10 SP1 x64"); - _xcp100GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", "SUSE Linux Enterprise Server 10 SP2"); - _xcp100GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", "SUSE Linux Enterprise Server 10 SP2 x64"); - _xcp100GuestOsMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", "Other install media"); - _xcp100GuestOsMap.put("SUSE Linux Enterprise Server 11 (32-bit)", "SUSE Linux Enterprise Server 11"); - _xcp100GuestOsMap.put("SUSE Linux Enterprise Server 11 (64-bit)", "SUSE Linux Enterprise Server 11 x64"); - _xcp100GuestOsMap.put("SUSE Linux Enterprise Server 11 SP1 (32-bit)", "SUSE Linux Enterprise Server 11 SP1 (32-bit)"); - _xcp100GuestOsMap.put("SUSE Linux Enterprise Server 11 SP1 (64-bit)", "SUSE Linux Enterprise Server 11 SP1 (64-bit)"); - _xcp100GuestOsMap.put("Windows 7 (32-bit)", "Windows 7 (32-bit)"); - _xcp100GuestOsMap.put("Windows 7 (64-bit)", "Windows 7 (64-bit)"); - _xcp100GuestOsMap.put("Windows Server 2003 (32-bit)", "Windows Server 2003 (32-bit)"); - _xcp100GuestOsMap.put("Windows Server 2003 (64-bit)", "Windows Server 2003 (64-bit)"); - _xcp100GuestOsMap.put("Windows Server 2003 Enterprise Edition(32-bit)", "Windows Server 2003 (32-bit)"); - _xcp100GuestOsMap.put("Windows Server 2003 Enterprise Edition(64-bit)", "Windows Server 2003 (64-bit)"); - _xcp100GuestOsMap.put("Windows Server 2003 DataCenter Edition(32-bit)", "Windows Server 2003 (32-bit)"); - _xcp100GuestOsMap.put("Windows Server 2003 DataCenter Edition(64-bit)", "Windows Server 2003 (64-bit)"); - _xcp100GuestOsMap.put("Windows Server 2003 Standard Edition(32-bit)", "Windows Server 2003 (32-bit)"); - _xcp100GuestOsMap.put("Windows Server 2003 Standard Edition(64-bit)", "Windows Server 2003 (64-bit)"); - _xcp100GuestOsMap.put("Windows Server 2008 (32-bit)", "Windows Server 2008 (32-bit)"); - _xcp100GuestOsMap.put("Windows Server 2008 (64-bit)", "Windows Server 2008 (64-bit)"); - _xcp100GuestOsMap.put("Windows Server 2008 R2 (64-bit)", "Windows Server 2008 R2 (64-bit)"); - _xcp100GuestOsMap.put("Windows XP SP3 (32-bit)", "Windows XP SP3 (32-bit)"); - _xcp100GuestOsMap.put("Windows Vista (32-bit)", "Windows Vista (32-bit)"); - _xcp100GuestOsMap.put("Ubuntu 10.04 (32-bit)", "Ubuntu Lucid Lynx 10.04 (32-bit) (experimental)"); - _xcp100GuestOsMap.put("Ubuntu 10.04 (64-bit)", "Ubuntu Lucid Lynx 10.04 (64-bit) (experimental)"); - _xcp100GuestOsMap.put("Other Linux (32-bit)", "Other install media"); - _xcp100GuestOsMap.put("Other Linux (64-bit)", "Other install media"); - _xcp100GuestOsMap.put("Other PV (32-bit)", "CentOS 5 (32-bit)"); - _xcp100GuestOsMap.put("Other PV (64-bit)", "CentOS 5 (64-bit)"); + Xcp100GuestOsMap.put("CentOS 4.5 (32-bit)", "CentOS 4.5 (32-bit)"); + Xcp100GuestOsMap.put("CentOS 4.6 (32-bit)", "CentOS 4.6 (32-bit)"); + Xcp100GuestOsMap.put("CentOS 4.7 (32-bit)", "CentOS 4.7 (32-bit)"); + Xcp100GuestOsMap.put("CentOS 4.8 (32-bit)", "CentOS 4.8 (32-bit)"); + Xcp100GuestOsMap.put("CentOS 5.0 (32-bit)", "CentOS 5 (32-bit)"); + Xcp100GuestOsMap.put("CentOS 5.0 (64-bit)", "CentOS 5 (64-bit)"); + Xcp100GuestOsMap.put("CentOS 5.1 (32-bit)", "CentOS 5 (32-bit)"); + Xcp100GuestOsMap.put("CentOS 5.1 (64-bit)", "CentOS 5 (64-bit)"); + Xcp100GuestOsMap.put("CentOS 5.2 (32-bit)", "CentOS 5 (32-bit)"); + Xcp100GuestOsMap.put("CentOS 5.2 (64-bit)", "CentOS 5 (64-bit)"); + Xcp100GuestOsMap.put("CentOS 5.3 (32-bit)", "CentOS 5 (32-bit)"); + Xcp100GuestOsMap.put("CentOS 5.3 (64-bit)", "CentOS 5 (64-bit)"); + Xcp100GuestOsMap.put("CentOS 5.4 (32-bit)", "CentOS 5 (32-bit)"); + Xcp100GuestOsMap.put("CentOS 5.4 (64-bit)", "CentOS 5 (64-bit)"); + Xcp100GuestOsMap.put("CentOS 5.5 (32-bit)", "CentOS 5 (32-bit)"); + Xcp100GuestOsMap.put("CentOS 5.5 (64-bit)", "CentOS 5 (64-bit)"); + Xcp100GuestOsMap.put("Debian GNU/Linux 5.0 (32-bit)", "Debian Lenny 5.0 (32-bit)"); + Xcp100GuestOsMap.put("Debian GNU/Linux 6(32-bit)", "Debian Squeeze 6.0 (32-bit)"); + Xcp100GuestOsMap.put("Debian GNU/Linux 6(64-bit)", "Debian Squeeze 6.0 (64-bit) (experimental)"); + Xcp100GuestOsMap.put("Debian GNU/Linux 7(32-bit)", "Debian Squeeze 6.0 (32-bit)"); + Xcp100GuestOsMap.put("Debian GNU/Linux 7(64-bit)", "Debian Squeeze 6.0 (64-bit) (experimental)"); + Xcp100GuestOsMap.put("Oracle Enterprise Linux 5.0 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + Xcp100GuestOsMap.put("Oracle Enterprise Linux 5.0 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + Xcp100GuestOsMap.put("Oracle Enterprise Linux 5.1 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + Xcp100GuestOsMap.put("Oracle Enterprise Linux 5.1 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + Xcp100GuestOsMap.put("Oracle Enterprise Linux 5.2 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + Xcp100GuestOsMap.put("Oracle Enterprise Linux 5.2 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + Xcp100GuestOsMap.put("Oracle Enterprise Linux 5.3 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + Xcp100GuestOsMap.put("Oracle Enterprise Linux 5.3 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + Xcp100GuestOsMap.put("Oracle Enterprise Linux 5.4 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + Xcp100GuestOsMap.put("Oracle Enterprise Linux 5.4 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + Xcp100GuestOsMap.put("Oracle Enterprise Linux 5.5 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + Xcp100GuestOsMap.put("Oracle Enterprise Linux 5.5 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + Xcp100GuestOsMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", "Red Hat Enterprise Linux 4.5 (32-bit)"); + Xcp100GuestOsMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", "Red Hat Enterprise Linux 4.6 (32-bit)"); + Xcp100GuestOsMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", "Red Hat Enterprise Linux 4.7 (32-bit)"); + Xcp100GuestOsMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", "Red Hat Enterprise Linux 4.8 (32-bit)"); + Xcp100GuestOsMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + Xcp100GuestOsMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + Xcp100GuestOsMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + Xcp100GuestOsMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + Xcp100GuestOsMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + Xcp100GuestOsMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + Xcp100GuestOsMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + Xcp100GuestOsMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + Xcp100GuestOsMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + Xcp100GuestOsMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + Xcp100GuestOsMap.put("Red Hat Enterprise Linux 5.5 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + Xcp100GuestOsMap.put("Red Hat Enterprise Linux 5.5 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + Xcp100GuestOsMap.put("Red Hat Enterprise Linux 6.0 (32-bit)", "Red Hat Enterprise Linux 6 (32-bit)"); + Xcp100GuestOsMap.put("Red Hat Enterprise Linux 6.0 (64-bit)", "Red Hat Enterprise Linux 6 (64-bit)"); + Xcp100GuestOsMap.put("SUSE Linux Enterprise Server 9 SP4 (32-bit)", "SUSE Linux Enterprise Server 9 SP4"); + Xcp100GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", "SUSE Linux Enterprise Server 10 SP1"); + Xcp100GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", "SUSE Linux Enterprise Server 10 SP1 x64"); + Xcp100GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", "SUSE Linux Enterprise Server 10 SP2"); + Xcp100GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", "SUSE Linux Enterprise Server 10 SP2 x64"); + Xcp100GuestOsMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", "Other install media"); + Xcp100GuestOsMap.put("SUSE Linux Enterprise Server 11 (32-bit)", "SUSE Linux Enterprise Server 11"); + Xcp100GuestOsMap.put("SUSE Linux Enterprise Server 11 (64-bit)", "SUSE Linux Enterprise Server 11 x64"); + Xcp100GuestOsMap.put("SUSE Linux Enterprise Server 11 SP1 (32-bit)", "SUSE Linux Enterprise Server 11 SP1 (32-bit)"); + Xcp100GuestOsMap.put("SUSE Linux Enterprise Server 11 SP1 (64-bit)", "SUSE Linux Enterprise Server 11 SP1 (64-bit)"); + Xcp100GuestOsMap.put("Windows 7 (32-bit)", "Windows 7 (32-bit)"); + Xcp100GuestOsMap.put("Windows 7 (64-bit)", "Windows 7 (64-bit)"); + Xcp100GuestOsMap.put("Windows Server 2003 (32-bit)", "Windows Server 2003 (32-bit)"); + Xcp100GuestOsMap.put("Windows Server 2003 (64-bit)", "Windows Server 2003 (64-bit)"); + Xcp100GuestOsMap.put("Windows Server 2003 Enterprise Edition(32-bit)", "Windows Server 2003 (32-bit)"); + Xcp100GuestOsMap.put("Windows Server 2003 Enterprise Edition(64-bit)", "Windows Server 2003 (64-bit)"); + Xcp100GuestOsMap.put("Windows Server 2003 DataCenter Edition(32-bit)", "Windows Server 2003 (32-bit)"); + Xcp100GuestOsMap.put("Windows Server 2003 DataCenter Edition(64-bit)", "Windows Server 2003 (64-bit)"); + Xcp100GuestOsMap.put("Windows Server 2003 Standard Edition(32-bit)", "Windows Server 2003 (32-bit)"); + Xcp100GuestOsMap.put("Windows Server 2003 Standard Edition(64-bit)", "Windows Server 2003 (64-bit)"); + Xcp100GuestOsMap.put("Windows Server 2008 (32-bit)", "Windows Server 2008 (32-bit)"); + Xcp100GuestOsMap.put("Windows Server 2008 (64-bit)", "Windows Server 2008 (64-bit)"); + Xcp100GuestOsMap.put("Windows Server 2008 R2 (64-bit)", "Windows Server 2008 R2 (64-bit)"); + Xcp100GuestOsMap.put("Windows XP SP3 (32-bit)", "Windows XP SP3 (32-bit)"); + Xcp100GuestOsMap.put("Windows Vista (32-bit)", "Windows Vista (32-bit)"); + Xcp100GuestOsMap.put("Ubuntu 10.04 (32-bit)", "Ubuntu Lucid Lynx 10.04 (32-bit) (experimental)"); + Xcp100GuestOsMap.put("Ubuntu 10.04 (64-bit)", "Ubuntu Lucid Lynx 10.04 (64-bit) (experimental)"); + Xcp100GuestOsMap.put("Other Linux (32-bit)", "Other install media"); + Xcp100GuestOsMap.put("Other Linux (64-bit)", "Other install media"); + Xcp100GuestOsMap.put("Other PV (32-bit)", "CentOS 5 (32-bit)"); + Xcp100GuestOsMap.put("Other PV (64-bit)", "CentOS 5 (64-bit)"); } static { - _xcp160GuestOsMap.put("CentOS 4.5 (32-bit)", "CentOS 4.5 (32-bit)"); - _xcp160GuestOsMap.put("CentOS 4.6 (32-bit)", "CentOS 4.6 (32-bit)"); - _xcp160GuestOsMap.put("CentOS 4.7 (32-bit)", "CentOS 4.7 (32-bit)"); - _xcp160GuestOsMap.put("CentOS 4.8 (32-bit)", "CentOS 4.8 (32-bit)"); - _xcp160GuestOsMap.put("CentOS 5.0 (32-bit)", "CentOS 5 (32-bit)"); - _xcp160GuestOsMap.put("CentOS 5.0 (64-bit)", "CentOS 5 (64-bit)"); - _xcp160GuestOsMap.put("CentOS 5.1 (32-bit)", "CentOS 5 (32-bit)"); - _xcp160GuestOsMap.put("CentOS 5.1 (64-bit)", "CentOS 5 (64-bit)"); - _xcp160GuestOsMap.put("CentOS 5.2 (32-bit)", "CentOS 5 (32-bit)"); - _xcp160GuestOsMap.put("CentOS 5.2 (64-bit)", "CentOS 5 (64-bit)"); - _xcp160GuestOsMap.put("CentOS 5.3 (32-bit)", "CentOS 5 (32-bit)"); - _xcp160GuestOsMap.put("CentOS 5.3 (64-bit)", "CentOS 5 (64-bit)"); - _xcp160GuestOsMap.put("CentOS 5.4 (32-bit)", "CentOS 5 (32-bit)"); - _xcp160GuestOsMap.put("CentOS 5.4 (64-bit)", "CentOS 5 (64-bit)"); - _xcp160GuestOsMap.put("CentOS 5.5 (32-bit)", "CentOS 5 (32-bit)"); - _xcp160GuestOsMap.put("CentOS 5.5 (64-bit)", "CentOS 5 (64-bit)"); - _xcp160GuestOsMap.put("CentOS 5.6 (32-bit)", "CentOS 5 (32-bit)"); - _xcp160GuestOsMap.put("CentOS 5.6 (64-bit)", "CentOS 5 (64-bit)"); - _xcp160GuestOsMap.put("CentOS 5.7 (32-bit)", "CentOS 5 (32-bit)"); - _xcp160GuestOsMap.put("CentOS 5.7 (64-bit)", "CentOS 5 (64-bit)"); - _xcp160GuestOsMap.put("CentOS 6.0 (32-bit)", "CentOS 6 (32-bit)"); - _xcp160GuestOsMap.put("CentOS 6.0 (64-bit)", "CentOS 6 (64-bit)"); - _xcp160GuestOsMap.put("CentOS 6.1 (32-bit)", "CentOS 6 (32-bit)"); - _xcp160GuestOsMap.put("CentOS 6.1 (64-bit)", "CentOS 6 (64-bit)"); - _xcp160GuestOsMap.put("CentOS 6.2 (32-bit)", "CentOS 6 (32-bit)"); - _xcp160GuestOsMap.put("CentOS 6.2 (64-bit)", "CentOS 6 (64-bit)"); - _xcp160GuestOsMap.put("Debian GNU/Linux 5.0 (32-bit)", "Debian Lenny 5.0 (32-bit)"); - _xcp160GuestOsMap.put("Debian GNU/Linux 6(32-bit)", "Debian Squeeze 6.0 (32-bit)"); - _xcp160GuestOsMap.put("Debian GNU/Linux 6(64-bit)", "Debian Squeeze 6.0 (64-bit)"); - _xcp160GuestOsMap.put("Debian GNU/Linux 7(32-bit)", "Debian Squeeze 6.0 (32-bit)"); - _xcp160GuestOsMap.put("Debian GNU/Linux 7(64-bit)", "Debian Squeeze 6.0 (64-bit)"); - _xcp160GuestOsMap.put("Oracle Enterprise Linux 5.0 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xcp160GuestOsMap.put("Oracle Enterprise Linux 5.0 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xcp160GuestOsMap.put("Oracle Enterprise Linux 5.1 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xcp160GuestOsMap.put("Oracle Enterprise Linux 5.1 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xcp160GuestOsMap.put("Oracle Enterprise Linux 5.2 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xcp160GuestOsMap.put("Oracle Enterprise Linux 5.2 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xcp160GuestOsMap.put("Oracle Enterprise Linux 5.3 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xcp160GuestOsMap.put("Oracle Enterprise Linux 5.3 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xcp160GuestOsMap.put("Oracle Enterprise Linux 5.4 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xcp160GuestOsMap.put("Oracle Enterprise Linux 5.4 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xcp160GuestOsMap.put("Oracle Enterprise Linux 5.5 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xcp160GuestOsMap.put("Oracle Enterprise Linux 5.5 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xcp160GuestOsMap.put("Oracle Enterprise Linux 5.6 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xcp160GuestOsMap.put("Oracle Enterprise Linux 5.6 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xcp160GuestOsMap.put("Oracle Enterprise Linux 5.7 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xcp160GuestOsMap.put("Oracle Enterprise Linux 5.7 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xcp160GuestOsMap.put("Oracle Enterprise Linux 6.0 (32-bit)", "Oracle Enterprise Linux 6 (32-bit)"); - _xcp160GuestOsMap.put("Oracle Enterprise Linux 6.0 (64-bit)", "Oracle Enterprise Linux 6 (64-bit)"); - _xcp160GuestOsMap.put("Oracle Enterprise Linux 6.1 (32-bit)", "Oracle Enterprise Linux 6 (32-bit)"); - _xcp160GuestOsMap.put("Oracle Enterprise Linux 6.1 (64-bit)", "Oracle Enterprise Linux 6 (64-bit)"); - _xcp160GuestOsMap.put("Oracle Enterprise Linux 6.2 (32-bit)", "Oracle Enterprise Linux 6 (32-bit)"); - _xcp160GuestOsMap.put("Oracle Enterprise Linux 6.2 (64-bit)", "Oracle Enterprise Linux 6 (64-bit)"); - _xcp160GuestOsMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", "Red Hat Enterprise Linux 4.5 (32-bit)"); - _xcp160GuestOsMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", "Red Hat Enterprise Linux 4.6 (32-bit)"); - _xcp160GuestOsMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", "Red Hat Enterprise Linux 4.7 (32-bit)"); - _xcp160GuestOsMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", "Red Hat Enterprise Linux 4.8 (32-bit)"); - _xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.5 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.5 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.6 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.6 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.7 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.7 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xcp160GuestOsMap.put("Red Hat Enterprise Linux 6.0 (32-bit)", "Red Hat Enterprise Linux 6 (32-bit)"); - _xcp160GuestOsMap.put("Red Hat Enterprise Linux 6.0 (64-bit)", "Red Hat Enterprise Linux 6 (64-bit)"); - _xcp160GuestOsMap.put("Red Hat Enterprise Linux 6.1 (32-bit)", "Red Hat Enterprise Linux 6 (32-bit)"); - _xcp160GuestOsMap.put("Red Hat Enterprise Linux 6.1 (64-bit)", "Red Hat Enterprise Linux 6 (64-bit)"); - _xcp160GuestOsMap.put("Red Hat Enterprise Linux 6.2 (32-bit)", "Red Hat Enterprise Linux 6 (32-bit)"); - _xcp160GuestOsMap.put("Red Hat Enterprise Linux 6.2 (64-bit)", "Red Hat Enterprise Linux 6 (64-bit)"); - _xcp160GuestOsMap.put("SUSE Linux Enterprise Server 9 SP4 (32-bit)", "SUSE Linux Enterprise Server 9 SP4"); - _xcp160GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", "SUSE Linux Enterprise Server 10 SP1"); - _xcp160GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", "SUSE Linux Enterprise Server 10 SP1 x64"); - _xcp160GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", "SUSE Linux Enterprise Server 10 SP2"); - _xcp160GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", "SUSE Linux Enterprise Server 10 SP2 x64"); - _xcp160GuestOsMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", "Other install media"); - _xcp160GuestOsMap.put("SUSE Linux Enterprise Server 11 (32-bit)", "SUSE Linux Enterprise Server 11"); - _xcp160GuestOsMap.put("SUSE Linux Enterprise Server 11 (64-bit)", "SUSE Linux Enterprise Server 11 x64"); - _xcp160GuestOsMap.put("SUSE Linux Enterprise Server 11 SP1 (32-bit)", "SUSE Linux Enterprise Server 11 SP1 (32-bit)"); - _xcp160GuestOsMap.put("SUSE Linux Enterprise Server 11 SP1 (64-bit)", "SUSE Linux Enterprise Server 11 SP1 (64-bit)"); - _xcp160GuestOsMap.put("Windows 7 (32-bit)", "Windows 7 (32-bit)"); - _xcp160GuestOsMap.put("Windows 7 (64-bit)", "Windows 7 (64-bit)"); - _xcp160GuestOsMap.put("Windows Server 2003 (32-bit)", "Windows Server 2003 (32-bit)"); - _xcp160GuestOsMap.put("Windows Server 2003 (64-bit)", "Windows Server 2003 (64-bit)"); - _xcp160GuestOsMap.put("Windows Server 2003 Enterprise Edition(32-bit)", "Windows Server 2003 (32-bit)"); - _xcp160GuestOsMap.put("Windows Server 2003 Enterprise Edition(64-bit)", "Windows Server 2003 (64-bit)"); - _xcp160GuestOsMap.put("Windows Server 2003 DataCenter Edition(32-bit)", "Windows Server 2003 (32-bit)"); - _xcp160GuestOsMap.put("Windows Server 2003 DataCenter Edition(64-bit)", "Windows Server 2003 (64-bit)"); - _xcp160GuestOsMap.put("Windows Server 2003 Standard Edition(32-bit)", "Windows Server 2003 (32-bit)"); - _xcp160GuestOsMap.put("Windows Server 2003 Standard Edition(64-bit)", "Windows Server 2003 (64-bit)"); - _xcp160GuestOsMap.put("Windows Server 2008 (32-bit)", "Windows Server 2008 (32-bit)"); - _xcp160GuestOsMap.put("Windows Server 2008 (64-bit)", "Windows Server 2008 (64-bit)"); - _xcp160GuestOsMap.put("Windows Server 2008 R2 (64-bit)", "Windows Server 2008 R2 (64-bit)"); - _xcp160GuestOsMap.put("Windows XP SP3 (32-bit)", "Windows XP SP3 (32-bit)"); - _xcp160GuestOsMap.put("Windows Vista (32-bit)", "Windows Vista (32-bit)"); - _xcp160GuestOsMap.put("Ubuntu 10.04 (32-bit)", "Ubuntu Lucid Lynx 10.04 (32-bit)"); - _xcp160GuestOsMap.put("Ubuntu 10.04 (64-bit)", "Ubuntu Lucid Lynx 10.04 (64-bit)"); - _xcp160GuestOsMap.put("Ubuntu 12.04 (32-bit)", "Ubuntu Precise Pangolin 12.04 (32-bit)"); - _xcp160GuestOsMap.put("Ubuntu 12.04 (64-bit)", "Ubuntu Precise Pangolin 12.04 (64-bit)"); - _xcp160GuestOsMap.put("Other Linux (32-bit)", "Other install media"); - _xcp160GuestOsMap.put("Other Linux (64-bit)", "Other install media"); - _xcp160GuestOsMap.put("Other PV (32-bit)", "CentOS 5 (32-bit)"); - _xcp160GuestOsMap.put("Other PV (64-bit)", "CentOS 5 (64-bit)"); + Xcp160GuestOsMap.put("CentOS 4.5 (32-bit)", "CentOS 4.5 (32-bit)"); + Xcp160GuestOsMap.put("CentOS 4.6 (32-bit)", "CentOS 4.6 (32-bit)"); + Xcp160GuestOsMap.put("CentOS 4.7 (32-bit)", "CentOS 4.7 (32-bit)"); + Xcp160GuestOsMap.put("CentOS 4.8 (32-bit)", "CentOS 4.8 (32-bit)"); + Xcp160GuestOsMap.put("CentOS 5.0 (32-bit)", "CentOS 5 (32-bit)"); + Xcp160GuestOsMap.put("CentOS 5.0 (64-bit)", "CentOS 5 (64-bit)"); + Xcp160GuestOsMap.put("CentOS 5.1 (32-bit)", "CentOS 5 (32-bit)"); + Xcp160GuestOsMap.put("CentOS 5.1 (64-bit)", "CentOS 5 (64-bit)"); + Xcp160GuestOsMap.put("CentOS 5.2 (32-bit)", "CentOS 5 (32-bit)"); + Xcp160GuestOsMap.put("CentOS 5.2 (64-bit)", "CentOS 5 (64-bit)"); + Xcp160GuestOsMap.put("CentOS 5.3 (32-bit)", "CentOS 5 (32-bit)"); + Xcp160GuestOsMap.put("CentOS 5.3 (64-bit)", "CentOS 5 (64-bit)"); + Xcp160GuestOsMap.put("CentOS 5.4 (32-bit)", "CentOS 5 (32-bit)"); + Xcp160GuestOsMap.put("CentOS 5.4 (64-bit)", "CentOS 5 (64-bit)"); + Xcp160GuestOsMap.put("CentOS 5.5 (32-bit)", "CentOS 5 (32-bit)"); + Xcp160GuestOsMap.put("CentOS 5.5 (64-bit)", "CentOS 5 (64-bit)"); + Xcp160GuestOsMap.put("CentOS 5.6 (32-bit)", "CentOS 5 (32-bit)"); + Xcp160GuestOsMap.put("CentOS 5.6 (64-bit)", "CentOS 5 (64-bit)"); + Xcp160GuestOsMap.put("CentOS 5.7 (32-bit)", "CentOS 5 (32-bit)"); + Xcp160GuestOsMap.put("CentOS 5.7 (64-bit)", "CentOS 5 (64-bit)"); + Xcp160GuestOsMap.put("CentOS 6.0 (32-bit)", "CentOS 6 (32-bit)"); + Xcp160GuestOsMap.put("CentOS 6.0 (64-bit)", "CentOS 6 (64-bit)"); + Xcp160GuestOsMap.put("CentOS 6.1 (32-bit)", "CentOS 6 (32-bit)"); + Xcp160GuestOsMap.put("CentOS 6.1 (64-bit)", "CentOS 6 (64-bit)"); + Xcp160GuestOsMap.put("CentOS 6.2 (32-bit)", "CentOS 6 (32-bit)"); + Xcp160GuestOsMap.put("CentOS 6.2 (64-bit)", "CentOS 6 (64-bit)"); + Xcp160GuestOsMap.put("Debian GNU/Linux 5.0 (32-bit)", "Debian Lenny 5.0 (32-bit)"); + Xcp160GuestOsMap.put("Debian GNU/Linux 6(32-bit)", "Debian Squeeze 6.0 (32-bit)"); + Xcp160GuestOsMap.put("Debian GNU/Linux 6(64-bit)", "Debian Squeeze 6.0 (64-bit)"); + Xcp160GuestOsMap.put("Debian GNU/Linux 7(32-bit)", "Debian Squeeze 6.0 (32-bit)"); + Xcp160GuestOsMap.put("Debian GNU/Linux 7(64-bit)", "Debian Squeeze 6.0 (64-bit)"); + Xcp160GuestOsMap.put("Oracle Enterprise Linux 5.0 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + Xcp160GuestOsMap.put("Oracle Enterprise Linux 5.0 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + Xcp160GuestOsMap.put("Oracle Enterprise Linux 5.1 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + Xcp160GuestOsMap.put("Oracle Enterprise Linux 5.1 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + Xcp160GuestOsMap.put("Oracle Enterprise Linux 5.2 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + Xcp160GuestOsMap.put("Oracle Enterprise Linux 5.2 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + Xcp160GuestOsMap.put("Oracle Enterprise Linux 5.3 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + Xcp160GuestOsMap.put("Oracle Enterprise Linux 5.3 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + Xcp160GuestOsMap.put("Oracle Enterprise Linux 5.4 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + Xcp160GuestOsMap.put("Oracle Enterprise Linux 5.4 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + Xcp160GuestOsMap.put("Oracle Enterprise Linux 5.5 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + Xcp160GuestOsMap.put("Oracle Enterprise Linux 5.5 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + Xcp160GuestOsMap.put("Oracle Enterprise Linux 5.6 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + Xcp160GuestOsMap.put("Oracle Enterprise Linux 5.6 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + Xcp160GuestOsMap.put("Oracle Enterprise Linux 5.7 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + Xcp160GuestOsMap.put("Oracle Enterprise Linux 5.7 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + Xcp160GuestOsMap.put("Oracle Enterprise Linux 6.0 (32-bit)", "Oracle Enterprise Linux 6 (32-bit)"); + Xcp160GuestOsMap.put("Oracle Enterprise Linux 6.0 (64-bit)", "Oracle Enterprise Linux 6 (64-bit)"); + Xcp160GuestOsMap.put("Oracle Enterprise Linux 6.1 (32-bit)", "Oracle Enterprise Linux 6 (32-bit)"); + Xcp160GuestOsMap.put("Oracle Enterprise Linux 6.1 (64-bit)", "Oracle Enterprise Linux 6 (64-bit)"); + Xcp160GuestOsMap.put("Oracle Enterprise Linux 6.2 (32-bit)", "Oracle Enterprise Linux 6 (32-bit)"); + Xcp160GuestOsMap.put("Oracle Enterprise Linux 6.2 (64-bit)", "Oracle Enterprise Linux 6 (64-bit)"); + Xcp160GuestOsMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", "Red Hat Enterprise Linux 4.5 (32-bit)"); + Xcp160GuestOsMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", "Red Hat Enterprise Linux 4.6 (32-bit)"); + Xcp160GuestOsMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", "Red Hat Enterprise Linux 4.7 (32-bit)"); + Xcp160GuestOsMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", "Red Hat Enterprise Linux 4.8 (32-bit)"); + Xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + Xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + Xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + Xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + Xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + Xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + Xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + Xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + Xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + Xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + Xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.5 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + Xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.5 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + Xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.6 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + Xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.6 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + Xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.7 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + Xcp160GuestOsMap.put("Red Hat Enterprise Linux 5.7 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + Xcp160GuestOsMap.put("Red Hat Enterprise Linux 6.0 (32-bit)", "Red Hat Enterprise Linux 6 (32-bit)"); + Xcp160GuestOsMap.put("Red Hat Enterprise Linux 6.0 (64-bit)", "Red Hat Enterprise Linux 6 (64-bit)"); + Xcp160GuestOsMap.put("Red Hat Enterprise Linux 6.1 (32-bit)", "Red Hat Enterprise Linux 6 (32-bit)"); + Xcp160GuestOsMap.put("Red Hat Enterprise Linux 6.1 (64-bit)", "Red Hat Enterprise Linux 6 (64-bit)"); + Xcp160GuestOsMap.put("Red Hat Enterprise Linux 6.2 (32-bit)", "Red Hat Enterprise Linux 6 (32-bit)"); + Xcp160GuestOsMap.put("Red Hat Enterprise Linux 6.2 (64-bit)", "Red Hat Enterprise Linux 6 (64-bit)"); + Xcp160GuestOsMap.put("SUSE Linux Enterprise Server 9 SP4 (32-bit)", "SUSE Linux Enterprise Server 9 SP4"); + Xcp160GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", "SUSE Linux Enterprise Server 10 SP1"); + Xcp160GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", "SUSE Linux Enterprise Server 10 SP1 x64"); + Xcp160GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", "SUSE Linux Enterprise Server 10 SP2"); + Xcp160GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", "SUSE Linux Enterprise Server 10 SP2 x64"); + Xcp160GuestOsMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", "Other install media"); + Xcp160GuestOsMap.put("SUSE Linux Enterprise Server 11 (32-bit)", "SUSE Linux Enterprise Server 11"); + Xcp160GuestOsMap.put("SUSE Linux Enterprise Server 11 (64-bit)", "SUSE Linux Enterprise Server 11 x64"); + Xcp160GuestOsMap.put("SUSE Linux Enterprise Server 11 SP1 (32-bit)", "SUSE Linux Enterprise Server 11 SP1 (32-bit)"); + Xcp160GuestOsMap.put("SUSE Linux Enterprise Server 11 SP1 (64-bit)", "SUSE Linux Enterprise Server 11 SP1 (64-bit)"); + Xcp160GuestOsMap.put("Windows 7 (32-bit)", "Windows 7 (32-bit)"); + Xcp160GuestOsMap.put("Windows 7 (64-bit)", "Windows 7 (64-bit)"); + Xcp160GuestOsMap.put("Windows Server 2003 (32-bit)", "Windows Server 2003 (32-bit)"); + Xcp160GuestOsMap.put("Windows Server 2003 (64-bit)", "Windows Server 2003 (64-bit)"); + Xcp160GuestOsMap.put("Windows Server 2003 Enterprise Edition(32-bit)", "Windows Server 2003 (32-bit)"); + Xcp160GuestOsMap.put("Windows Server 2003 Enterprise Edition(64-bit)", "Windows Server 2003 (64-bit)"); + Xcp160GuestOsMap.put("Windows Server 2003 DataCenter Edition(32-bit)", "Windows Server 2003 (32-bit)"); + Xcp160GuestOsMap.put("Windows Server 2003 DataCenter Edition(64-bit)", "Windows Server 2003 (64-bit)"); + Xcp160GuestOsMap.put("Windows Server 2003 Standard Edition(32-bit)", "Windows Server 2003 (32-bit)"); + Xcp160GuestOsMap.put("Windows Server 2003 Standard Edition(64-bit)", "Windows Server 2003 (64-bit)"); + Xcp160GuestOsMap.put("Windows Server 2008 (32-bit)", "Windows Server 2008 (32-bit)"); + Xcp160GuestOsMap.put("Windows Server 2008 (64-bit)", "Windows Server 2008 (64-bit)"); + Xcp160GuestOsMap.put("Windows Server 2008 R2 (64-bit)", "Windows Server 2008 R2 (64-bit)"); + Xcp160GuestOsMap.put("Windows XP SP3 (32-bit)", "Windows XP SP3 (32-bit)"); + Xcp160GuestOsMap.put("Windows Vista (32-bit)", "Windows Vista (32-bit)"); + Xcp160GuestOsMap.put("Ubuntu 10.04 (32-bit)", "Ubuntu Lucid Lynx 10.04 (32-bit)"); + Xcp160GuestOsMap.put("Ubuntu 10.04 (64-bit)", "Ubuntu Lucid Lynx 10.04 (64-bit)"); + Xcp160GuestOsMap.put("Ubuntu 12.04 (32-bit)", "Ubuntu Precise Pangolin 12.04 (32-bit)"); + Xcp160GuestOsMap.put("Ubuntu 12.04 (64-bit)", "Ubuntu Precise Pangolin 12.04 (64-bit)"); + Xcp160GuestOsMap.put("Other Linux (32-bit)", "Other install media"); + Xcp160GuestOsMap.put("Other Linux (64-bit)", "Other install media"); + Xcp160GuestOsMap.put("Other PV (32-bit)", "CentOS 5 (32-bit)"); + Xcp160GuestOsMap.put("Other PV (64-bit)", "CentOS 5 (64-bit)"); } static { - _xenServerGuestOsMap.put("CentOS 4.5 (32-bit)", "CentOS 4.5 (32-bit)"); - _xenServerGuestOsMap.put("CentOS 4.6 (32-bit)", "CentOS 4.6 (32-bit)"); - _xenServerGuestOsMap.put("CentOS 4.7 (32-bit)", "CentOS 4.7 (32-bit)"); - _xenServerGuestOsMap.put("CentOS 4.8 (32-bit)", "CentOS 4.8 (32-bit)"); - _xenServerGuestOsMap.put("CentOS 5.0 (32-bit)", "CentOS 5.0 (32-bit)"); - _xenServerGuestOsMap.put("CentOS 5.0 (64-bit)", "CentOS 5.0 (64-bit)"); - _xenServerGuestOsMap.put("CentOS 5.1 (32-bit)", "CentOS 5.1 (32-bit)"); - _xenServerGuestOsMap.put("CentOS 5.1 (64-bit)", "CentOS 5.1 (64-bit)"); - _xenServerGuestOsMap.put("CentOS 5.2 (32-bit)", "CentOS 5.2 (32-bit)"); - _xenServerGuestOsMap.put("CentOS 5.2 (64-bit)", "CentOS 5.2 (64-bit)"); - _xenServerGuestOsMap.put("CentOS 5.3 (32-bit)", "CentOS 5.3 (32-bit)"); - _xenServerGuestOsMap.put("CentOS 5.3 (64-bit)", "CentOS 5.3 (64-bit)"); - _xenServerGuestOsMap.put("CentOS 5.4 (32-bit)", "CentOS 5.4 (32-bit)"); - _xenServerGuestOsMap.put("CentOS 5.4 (64-bit)", "CentOS 5.4 (64-bit)"); - _xenServerGuestOsMap.put("Debian GNU/Linux 5.0 (32-bit)", "Debian Lenny 5.0 (32-bit)"); - _xenServerGuestOsMap.put("Debian GNU/Linux 6(32-bit)", "Debian Lenny 5.0 (32-bit)"); // This is to support Debian 6.0 in XS 5.6 - _xenServerGuestOsMap.put("Debian GNU/Linux 7(32-bit)", "Debian Lenny 5.0 (32-bit)"); // This is to support Debian 7.0 in XS 5.6 - _xenServerGuestOsMap.put("Oracle Enterprise Linux 5.0 (32-bit)", "Oracle Enterprise Linux 5.0 (32-bit)"); - _xenServerGuestOsMap.put("Oracle Enterprise Linux 5.0 (64-bit)", "Oracle Enterprise Linux 5.0 (64-bit)"); - _xenServerGuestOsMap.put("Oracle Enterprise Linux 5.1 (32-bit)", "Oracle Enterprise Linux 5.1 (32-bit)"); - _xenServerGuestOsMap.put("Oracle Enterprise Linux 5.1 (64-bit)", "Oracle Enterprise Linux 5.1 (64-bit)"); - _xenServerGuestOsMap.put("Oracle Enterprise Linux 5.2 (32-bit)", "Oracle Enterprise Linux 5.2 (32-bit)"); - _xenServerGuestOsMap.put("Oracle Enterprise Linux 5.2 (64-bit)", "Oracle Enterprise Linux 5.2 (64-bit)"); - _xenServerGuestOsMap.put("Oracle Enterprise Linux 5.3 (32-bit)", "Oracle Enterprise Linux 5.3 (32-bit)"); - _xenServerGuestOsMap.put("Oracle Enterprise Linux 5.3 (64-bit)", "Oracle Enterprise Linux 5.3 (64-bit)"); - _xenServerGuestOsMap.put("Oracle Enterprise Linux 5.4 (32-bit)", "Oracle Enterprise Linux 5.4 (32-bit)"); - _xenServerGuestOsMap.put("Oracle Enterprise Linux 5.4 (64-bit)", "Oracle Enterprise Linux 5.4 (64-bit)"); - _xenServerGuestOsMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", "Red Hat Enterprise Linux 4.5 (32-bit)"); - _xenServerGuestOsMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", "Red Hat Enterprise Linux 4.6 (32-bit)"); - _xenServerGuestOsMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", "Red Hat Enterprise Linux 4.7 (32-bit)"); - _xenServerGuestOsMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", "Red Hat Enterprise Linux 4.8 (32-bit)"); - _xenServerGuestOsMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", "Red Hat Enterprise Linux 5.0 (32-bit)"); - _xenServerGuestOsMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", "Red Hat Enterprise Linux 5.0 (64-bit)"); - _xenServerGuestOsMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", "Red Hat Enterprise Linux 5.1 (32-bit)"); - _xenServerGuestOsMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", "Red Hat Enterprise Linux 5.1 (64-bit)"); - _xenServerGuestOsMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", "Red Hat Enterprise Linux 5.2 (32-bit)"); - _xenServerGuestOsMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", "Red Hat Enterprise Linux 5.2 (64-bit)"); - _xenServerGuestOsMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", "Red Hat Enterprise Linux 5.3 (32-bit)"); - _xenServerGuestOsMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", "Red Hat Enterprise Linux 5.3 (64-bit)"); - _xenServerGuestOsMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", "Red Hat Enterprise Linux 5.4 (32-bit)"); - _xenServerGuestOsMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", "Red Hat Enterprise Linux 5.4 (64-bit)"); - _xenServerGuestOsMap.put("SUSE Linux Enterprise Server 9 SP4 (32-bit)", "SUSE Linux Enterprise Server 9 SP4 (32-bit)"); - _xenServerGuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", "SUSE Linux Enterprise Server 10 SP1 (32-bit)"); - _xenServerGuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", "SUSE Linux Enterprise Server 10 SP1 (64-bit)"); - _xenServerGuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", "SUSE Linux Enterprise Server 10 SP2 (32-bit)"); - _xenServerGuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", "SUSE Linux Enterprise Server 10 SP2 (64-bit)"); - _xenServerGuestOsMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", "SUSE Linux Enterprise Server 10 SP3 (64-bit)"); - _xenServerGuestOsMap.put("SUSE Linux Enterprise Server 11 (32-bit)", "SUSE Linux Enterprise Server 11 (32-bit)"); - _xenServerGuestOsMap.put("SUSE Linux Enterprise Server 11 (64-bit)", "SUSE Linux Enterprise Server 11 (64-bit)"); - _xenServerGuestOsMap.put("Windows 7 (32-bit)", "Windows 7 (32-bit)"); - _xenServerGuestOsMap.put("Windows 7 (64-bit)", "Windows 7 (64-bit)"); - _xenServerGuestOsMap.put("Windows Server 2003 (32-bit)", "Windows Server 2003 (32-bit)"); - _xenServerGuestOsMap.put("Windows Server 2003 (64-bit)", "Windows Server 2003 (64-bit)"); - _xenServerGuestOsMap.put("Windows Server 2003 Enterprise Edition(32-bit)", "Windows Server 2003 (32-bit)"); - _xenServerGuestOsMap.put("Windows Server 2003 Enterprise Edition(64-bit)", "Windows Server 2003 (64-bit)"); - _xenServerGuestOsMap.put("Windows Server 2003 DataCenter Edition(32-bit)", "Windows Server 2003 (32-bit)"); - _xenServerGuestOsMap.put("Windows Server 2003 DataCenter Edition(64-bit)", "Windows Server 2003 (64-bit)"); - _xenServerGuestOsMap.put("Windows Server 2008 (32-bit)", "Windows Server 2008 (32-bit)"); - _xenServerGuestOsMap.put("Windows Server 2008 (64-bit)", "Windows Server 2008 (64-bit)"); - _xenServerGuestOsMap.put("Windows Server 2008 R2 (64-bit)", "Windows Server 2008 R2 (64-bit)"); - _xenServerGuestOsMap.put("Windows 2000 SP4 (32-bit)", "Windows 2000 SP4 (32-bit)"); - _xenServerGuestOsMap.put("Windows 2000 Server SP4 (32-bit)", "Windows 2000 SP4 (32-bit)"); - _xenServerGuestOsMap.put("Windows Vista (32-bit)", "Windows Vista (32-bit)"); - _xenServerGuestOsMap.put("Windows XP SP2 (32-bit)", "Windows XP SP2 (32-bit)"); - _xenServerGuestOsMap.put("Windows XP SP3 (32-bit)", "Windows XP SP3 (32-bit)"); - _xenServerGuestOsMap.put("Other Linux (32-bit)", "Other install media"); - _xenServerGuestOsMap.put("Other Linux (64-bit)", "Other install media"); - _xenServerGuestOsMap.put("Other PV (32-bit)", "CentOS 5.4 (32-bit)"); - _xenServerGuestOsMap.put("Other PV (64-bit)", "CentOS 5.4 (64-bit)"); + XenServerGuestOsMap.put("CentOS 4.5 (32-bit)", "CentOS 4.5 (32-bit)"); + XenServerGuestOsMap.put("CentOS 4.6 (32-bit)", "CentOS 4.6 (32-bit)"); + XenServerGuestOsMap.put("CentOS 4.7 (32-bit)", "CentOS 4.7 (32-bit)"); + XenServerGuestOsMap.put("CentOS 4.8 (32-bit)", "CentOS 4.8 (32-bit)"); + XenServerGuestOsMap.put("CentOS 5.0 (32-bit)", "CentOS 5.0 (32-bit)"); + XenServerGuestOsMap.put("CentOS 5.0 (64-bit)", "CentOS 5.0 (64-bit)"); + XenServerGuestOsMap.put("CentOS 5.1 (32-bit)", "CentOS 5.1 (32-bit)"); + XenServerGuestOsMap.put("CentOS 5.1 (64-bit)", "CentOS 5.1 (64-bit)"); + XenServerGuestOsMap.put("CentOS 5.2 (32-bit)", "CentOS 5.2 (32-bit)"); + XenServerGuestOsMap.put("CentOS 5.2 (64-bit)", "CentOS 5.2 (64-bit)"); + XenServerGuestOsMap.put("CentOS 5.3 (32-bit)", "CentOS 5.3 (32-bit)"); + XenServerGuestOsMap.put("CentOS 5.3 (64-bit)", "CentOS 5.3 (64-bit)"); + XenServerGuestOsMap.put("CentOS 5.4 (32-bit)", "CentOS 5.4 (32-bit)"); + XenServerGuestOsMap.put("CentOS 5.4 (64-bit)", "CentOS 5.4 (64-bit)"); + XenServerGuestOsMap.put("Debian GNU/Linux 5.0 (32-bit)", "Debian Lenny 5.0 (32-bit)"); + XenServerGuestOsMap.put("Debian GNU/Linux 6(32-bit)", "Debian Lenny 5.0 (32-bit)"); // This is to support Debian 6.0 in XS 5.6 + XenServerGuestOsMap.put("Debian GNU/Linux 7(32-bit)", "Debian Lenny 5.0 (32-bit)"); // This is to support Debian 7.0 in XS 5.6 + XenServerGuestOsMap.put("Oracle Enterprise Linux 5.0 (32-bit)", "Oracle Enterprise Linux 5.0 (32-bit)"); + XenServerGuestOsMap.put("Oracle Enterprise Linux 5.0 (64-bit)", "Oracle Enterprise Linux 5.0 (64-bit)"); + XenServerGuestOsMap.put("Oracle Enterprise Linux 5.1 (32-bit)", "Oracle Enterprise Linux 5.1 (32-bit)"); + XenServerGuestOsMap.put("Oracle Enterprise Linux 5.1 (64-bit)", "Oracle Enterprise Linux 5.1 (64-bit)"); + XenServerGuestOsMap.put("Oracle Enterprise Linux 5.2 (32-bit)", "Oracle Enterprise Linux 5.2 (32-bit)"); + XenServerGuestOsMap.put("Oracle Enterprise Linux 5.2 (64-bit)", "Oracle Enterprise Linux 5.2 (64-bit)"); + XenServerGuestOsMap.put("Oracle Enterprise Linux 5.3 (32-bit)", "Oracle Enterprise Linux 5.3 (32-bit)"); + XenServerGuestOsMap.put("Oracle Enterprise Linux 5.3 (64-bit)", "Oracle Enterprise Linux 5.3 (64-bit)"); + XenServerGuestOsMap.put("Oracle Enterprise Linux 5.4 (32-bit)", "Oracle Enterprise Linux 5.4 (32-bit)"); + XenServerGuestOsMap.put("Oracle Enterprise Linux 5.4 (64-bit)", "Oracle Enterprise Linux 5.4 (64-bit)"); + XenServerGuestOsMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", "Red Hat Enterprise Linux 4.5 (32-bit)"); + XenServerGuestOsMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", "Red Hat Enterprise Linux 4.6 (32-bit)"); + XenServerGuestOsMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", "Red Hat Enterprise Linux 4.7 (32-bit)"); + XenServerGuestOsMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", "Red Hat Enterprise Linux 4.8 (32-bit)"); + XenServerGuestOsMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", "Red Hat Enterprise Linux 5.0 (32-bit)"); + XenServerGuestOsMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", "Red Hat Enterprise Linux 5.0 (64-bit)"); + XenServerGuestOsMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", "Red Hat Enterprise Linux 5.1 (32-bit)"); + XenServerGuestOsMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", "Red Hat Enterprise Linux 5.1 (64-bit)"); + XenServerGuestOsMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", "Red Hat Enterprise Linux 5.2 (32-bit)"); + XenServerGuestOsMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", "Red Hat Enterprise Linux 5.2 (64-bit)"); + XenServerGuestOsMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", "Red Hat Enterprise Linux 5.3 (32-bit)"); + XenServerGuestOsMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", "Red Hat Enterprise Linux 5.3 (64-bit)"); + XenServerGuestOsMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", "Red Hat Enterprise Linux 5.4 (32-bit)"); + XenServerGuestOsMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", "Red Hat Enterprise Linux 5.4 (64-bit)"); + XenServerGuestOsMap.put("SUSE Linux Enterprise Server 9 SP4 (32-bit)", "SUSE Linux Enterprise Server 9 SP4 (32-bit)"); + XenServerGuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", "SUSE Linux Enterprise Server 10 SP1 (32-bit)"); + XenServerGuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", "SUSE Linux Enterprise Server 10 SP1 (64-bit)"); + XenServerGuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", "SUSE Linux Enterprise Server 10 SP2 (32-bit)"); + XenServerGuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", "SUSE Linux Enterprise Server 10 SP2 (64-bit)"); + XenServerGuestOsMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", "SUSE Linux Enterprise Server 10 SP3 (64-bit)"); + XenServerGuestOsMap.put("SUSE Linux Enterprise Server 11 (32-bit)", "SUSE Linux Enterprise Server 11 (32-bit)"); + XenServerGuestOsMap.put("SUSE Linux Enterprise Server 11 (64-bit)", "SUSE Linux Enterprise Server 11 (64-bit)"); + XenServerGuestOsMap.put("Windows 7 (32-bit)", "Windows 7 (32-bit)"); + XenServerGuestOsMap.put("Windows 7 (64-bit)", "Windows 7 (64-bit)"); + XenServerGuestOsMap.put("Windows Server 2003 (32-bit)", "Windows Server 2003 (32-bit)"); + XenServerGuestOsMap.put("Windows Server 2003 (64-bit)", "Windows Server 2003 (64-bit)"); + XenServerGuestOsMap.put("Windows Server 2003 Enterprise Edition(32-bit)", "Windows Server 2003 (32-bit)"); + XenServerGuestOsMap.put("Windows Server 2003 Enterprise Edition(64-bit)", "Windows Server 2003 (64-bit)"); + XenServerGuestOsMap.put("Windows Server 2003 DataCenter Edition(32-bit)", "Windows Server 2003 (32-bit)"); + XenServerGuestOsMap.put("Windows Server 2003 DataCenter Edition(64-bit)", "Windows Server 2003 (64-bit)"); + XenServerGuestOsMap.put("Windows Server 2008 (32-bit)", "Windows Server 2008 (32-bit)"); + XenServerGuestOsMap.put("Windows Server 2008 (64-bit)", "Windows Server 2008 (64-bit)"); + XenServerGuestOsMap.put("Windows Server 2008 R2 (64-bit)", "Windows Server 2008 R2 (64-bit)"); + XenServerGuestOsMap.put("Windows 2000 SP4 (32-bit)", "Windows 2000 SP4 (32-bit)"); + XenServerGuestOsMap.put("Windows 2000 Server SP4 (32-bit)", "Windows 2000 SP4 (32-bit)"); + XenServerGuestOsMap.put("Windows Vista (32-bit)", "Windows Vista (32-bit)"); + XenServerGuestOsMap.put("Windows XP SP2 (32-bit)", "Windows XP SP2 (32-bit)"); + XenServerGuestOsMap.put("Windows XP SP3 (32-bit)", "Windows XP SP3 (32-bit)"); + XenServerGuestOsMap.put("Other Linux (32-bit)", "Other install media"); + XenServerGuestOsMap.put("Other Linux (64-bit)", "Other install media"); + XenServerGuestOsMap.put("Other PV (32-bit)", "CentOS 5.4 (32-bit)"); + XenServerGuestOsMap.put("Other PV (64-bit)", "CentOS 5.4 (64-bit)"); } static { - _xenServer56FP1GuestOsMap.put("CentOS 4.5 (32-bit)", "CentOS 4.5 (32-bit)"); - _xenServer56FP1GuestOsMap.put("CentOS 4.6 (32-bit)", "CentOS 4.6 (32-bit)"); - _xenServer56FP1GuestOsMap.put("CentOS 4.7 (32-bit)", "CentOS 4.7 (32-bit)"); - _xenServer56FP1GuestOsMap.put("CentOS 4.8 (32-bit)", "CentOS 4.8 (32-bit)"); - _xenServer56FP1GuestOsMap.put("CentOS 5.0 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer56FP1GuestOsMap.put("CentOS 5.0 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer56FP1GuestOsMap.put("CentOS 5.1 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer56FP1GuestOsMap.put("CentOS 5.1 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer56FP1GuestOsMap.put("CentOS 5.2 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer56FP1GuestOsMap.put("CentOS 5.2 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer56FP1GuestOsMap.put("CentOS 5.3 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer56FP1GuestOsMap.put("CentOS 5.3 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer56FP1GuestOsMap.put("CentOS 5.4 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer56FP1GuestOsMap.put("CentOS 5.4 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer56FP1GuestOsMap.put("CentOS 5.5 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer56FP1GuestOsMap.put("CentOS 5.5 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer56FP1GuestOsMap.put("Debian GNU/Linux 5.0 (32-bit)", "Debian Lenny 5.0 (32-bit)"); - _xenServer56FP1GuestOsMap.put("Debian GNU/Linux 6(32-bit)", "Debian Squeeze 6.0 (32-bit)"); - _xenServer56FP1GuestOsMap.put("Debian GNU/Linux 6(64-bit)", "Debian Squeeze 6.0 (64-bit) (experimental)"); - _xenServer56FP1GuestOsMap.put("Debian GNU/Linux 7(32-bit)", "Debian Squeeze 6.0 (32-bit)"); // This is to support Debian 7.0 in XS 5.6FP1 - _xenServer56FP1GuestOsMap.put("Debian GNU/Linux 7(64-bit)", "Debian Squeeze 6.0 (64-bit) (experimental)"); - _xenServer56FP1GuestOsMap.put("Oracle Enterprise Linux 5.0 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer56FP1GuestOsMap.put("Oracle Enterprise Linux 5.0 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer56FP1GuestOsMap.put("Oracle Enterprise Linux 5.1 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer56FP1GuestOsMap.put("Oracle Enterprise Linux 5.1 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer56FP1GuestOsMap.put("Oracle Enterprise Linux 5.2 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer56FP1GuestOsMap.put("Oracle Enterprise Linux 5.2 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer56FP1GuestOsMap.put("Oracle Enterprise Linux 5.3 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer56FP1GuestOsMap.put("Oracle Enterprise Linux 5.3 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer56FP1GuestOsMap.put("Oracle Enterprise Linux 5.4 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer56FP1GuestOsMap.put("Oracle Enterprise Linux 5.4 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer56FP1GuestOsMap.put("Oracle Enterprise Linux 5.5 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer56FP1GuestOsMap.put("Oracle Enterprise Linux 5.5 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", "Red Hat Enterprise Linux 4.5 (32-bit)"); - _xenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", "Red Hat Enterprise Linux 4.6 (32-bit)"); - _xenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", "Red Hat Enterprise Linux 4.7 (32-bit)"); - _xenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", "Red Hat Enterprise Linux 4.8 (32-bit)"); - _xenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 5.5 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 5.5 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 6.0 (32-bit)", "Red Hat Enterprise Linux 6 (32-bit) (experimental)"); - _xenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 6.0 (64-bit)", "Red Hat Enterprise Linux 6 (64-bit) (experimental)"); - _xenServer56FP1GuestOsMap.put("SUSE Linux Enterprise Server 9 SP4 (32-bit)", "SUSE Linux Enterprise Server 9 SP4 (32-bit)"); - _xenServer56FP1GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", "SUSE Linux Enterprise Server 10 SP1 (32-bit)"); - _xenServer56FP1GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", "SUSE Linux Enterprise Server 10 SP1 (64-bit)"); - _xenServer56FP1GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", "SUSE Linux Enterprise Server 10 SP2 (32-bit)"); - _xenServer56FP1GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", "SUSE Linux Enterprise Server 10 SP2 (64-bit)"); - _xenServer56FP1GuestOsMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", "SUSE Linux Enterprise Server 10 SP3 (64-bit)"); - _xenServer56FP1GuestOsMap.put("SUSE Linux Enterprise Server 11 (32-bit)", "SUSE Linux Enterprise Server 11 (32-bit)"); - _xenServer56FP1GuestOsMap.put("SUSE Linux Enterprise Server 11 (64-bit)", "SUSE Linux Enterprise Server 11 (64-bit)"); - _xenServer56FP1GuestOsMap.put("Windows 7 (32-bit)", "Windows 7 (32-bit)"); - _xenServer56FP1GuestOsMap.put("Windows 7 (64-bit)", "Windows 7 (64-bit)"); - _xenServer56FP1GuestOsMap.put("Windows Server 2003 (32-bit)", "Windows Server 2003 (32-bit)"); - _xenServer56FP1GuestOsMap.put("Windows Server 2003 (64-bit)", "Windows Server 2003 (64-bit)"); - _xenServer56FP1GuestOsMap.put("Windows Server 2003 Enterprise Edition(32-bit)", "Windows Server 2003 (32-bit)"); - _xenServer56FP1GuestOsMap.put("Windows Server 2003 Enterprise Edition(64-bit)", "Windows Server 2003 (64-bit)"); - _xenServer56FP1GuestOsMap.put("Windows Server 2003 DataCenter Edition(32-bit)", "Windows Server 2003 (32-bit)"); - _xenServer56FP1GuestOsMap.put("Windows Server 2003 DataCenter Edition(64-bit)", "Windows Server 2003 (64-bit)"); - _xenServer56FP1GuestOsMap.put("Windows Server 2008 (32-bit)", "Windows Server 2008 (32-bit)"); - _xenServer56FP1GuestOsMap.put("Windows Server 2008 (64-bit)", "Windows Server 2008 (64-bit)"); - _xenServer56FP1GuestOsMap.put("Windows Server 2008 R2 (64-bit)", "Windows Server 2008 R2 (64-bit)"); - _xenServer56FP1GuestOsMap.put("Windows 2000 SP4 (32-bit)", "Windows 2000 SP4 (32-bit)"); - _xenServer56FP1GuestOsMap.put("Windows 2000 Server SP4 (32-bit)", "Windows 2000 SP4 (32-bit)"); - _xenServer56FP1GuestOsMap.put("Windows Vista (32-bit)", "Windows Vista (32-bit)"); - _xenServer56FP1GuestOsMap.put("Windows XP SP3 (32-bit)", "Windows XP SP3 (32-bit)"); - _xenServer56FP1GuestOsMap.put("Ubuntu 10.04 (32-bit)", "Ubuntu Lucid Lynx 10.04 (32-bit) (experimental)"); - _xenServer56FP1GuestOsMap.put("Ubuntu 10.04 (64-bit)", "Ubuntu Lucid Lynx 10.04 (64-bit) (experimental)"); - _xenServer56FP1GuestOsMap.put("Other Linux (32-bit)", "Other install media"); - _xenServer56FP1GuestOsMap.put("Other Linux (64-bit)", "Other install media"); - _xenServer56FP1GuestOsMap.put("Other PV (32-bit)", "CentOS 5 (32-bit)"); - _xenServer56FP1GuestOsMap.put("Other PV (64-bit)", "CentOS 5 (64-bit)"); + XenServer56FP1GuestOsMap.put("CentOS 4.5 (32-bit)", "CentOS 4.5 (32-bit)"); + XenServer56FP1GuestOsMap.put("CentOS 4.6 (32-bit)", "CentOS 4.6 (32-bit)"); + XenServer56FP1GuestOsMap.put("CentOS 4.7 (32-bit)", "CentOS 4.7 (32-bit)"); + XenServer56FP1GuestOsMap.put("CentOS 4.8 (32-bit)", "CentOS 4.8 (32-bit)"); + XenServer56FP1GuestOsMap.put("CentOS 5.0 (32-bit)", "CentOS 5 (32-bit)"); + XenServer56FP1GuestOsMap.put("CentOS 5.0 (64-bit)", "CentOS 5 (64-bit)"); + XenServer56FP1GuestOsMap.put("CentOS 5.1 (32-bit)", "CentOS 5 (32-bit)"); + XenServer56FP1GuestOsMap.put("CentOS 5.1 (64-bit)", "CentOS 5 (64-bit)"); + XenServer56FP1GuestOsMap.put("CentOS 5.2 (32-bit)", "CentOS 5 (32-bit)"); + XenServer56FP1GuestOsMap.put("CentOS 5.2 (64-bit)", "CentOS 5 (64-bit)"); + XenServer56FP1GuestOsMap.put("CentOS 5.3 (32-bit)", "CentOS 5 (32-bit)"); + XenServer56FP1GuestOsMap.put("CentOS 5.3 (64-bit)", "CentOS 5 (64-bit)"); + XenServer56FP1GuestOsMap.put("CentOS 5.4 (32-bit)", "CentOS 5 (32-bit)"); + XenServer56FP1GuestOsMap.put("CentOS 5.4 (64-bit)", "CentOS 5 (64-bit)"); + XenServer56FP1GuestOsMap.put("CentOS 5.5 (32-bit)", "CentOS 5 (32-bit)"); + XenServer56FP1GuestOsMap.put("CentOS 5.5 (64-bit)", "CentOS 5 (64-bit)"); + XenServer56FP1GuestOsMap.put("Debian GNU/Linux 5.0 (32-bit)", "Debian Lenny 5.0 (32-bit)"); + XenServer56FP1GuestOsMap.put("Debian GNU/Linux 6(32-bit)", "Debian Squeeze 6.0 (32-bit)"); + XenServer56FP1GuestOsMap.put("Debian GNU/Linux 6(64-bit)", "Debian Squeeze 6.0 (64-bit) (experimental)"); + XenServer56FP1GuestOsMap.put("Debian GNU/Linux 7(32-bit)", "Debian Squeeze 6.0 (32-bit)"); // This is to support Debian 7.0 in XS 5.6FP1 + XenServer56FP1GuestOsMap.put("Debian GNU/Linux 7(64-bit)", "Debian Squeeze 6.0 (64-bit) (experimental)"); + XenServer56FP1GuestOsMap.put("Oracle Enterprise Linux 5.0 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer56FP1GuestOsMap.put("Oracle Enterprise Linux 5.0 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer56FP1GuestOsMap.put("Oracle Enterprise Linux 5.1 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer56FP1GuestOsMap.put("Oracle Enterprise Linux 5.1 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer56FP1GuestOsMap.put("Oracle Enterprise Linux 5.2 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer56FP1GuestOsMap.put("Oracle Enterprise Linux 5.2 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer56FP1GuestOsMap.put("Oracle Enterprise Linux 5.3 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer56FP1GuestOsMap.put("Oracle Enterprise Linux 5.3 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer56FP1GuestOsMap.put("Oracle Enterprise Linux 5.4 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer56FP1GuestOsMap.put("Oracle Enterprise Linux 5.4 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer56FP1GuestOsMap.put("Oracle Enterprise Linux 5.5 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer56FP1GuestOsMap.put("Oracle Enterprise Linux 5.5 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", "Red Hat Enterprise Linux 4.5 (32-bit)"); + XenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", "Red Hat Enterprise Linux 4.6 (32-bit)"); + XenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", "Red Hat Enterprise Linux 4.7 (32-bit)"); + XenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", "Red Hat Enterprise Linux 4.8 (32-bit)"); + XenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 5.5 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 5.5 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 6.0 (32-bit)", "Red Hat Enterprise Linux 6 (32-bit) (experimental)"); + XenServer56FP1GuestOsMap.put("Red Hat Enterprise Linux 6.0 (64-bit)", "Red Hat Enterprise Linux 6 (64-bit) (experimental)"); + XenServer56FP1GuestOsMap.put("SUSE Linux Enterprise Server 9 SP4 (32-bit)", "SUSE Linux Enterprise Server 9 SP4 (32-bit)"); + XenServer56FP1GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", "SUSE Linux Enterprise Server 10 SP1 (32-bit)"); + XenServer56FP1GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", "SUSE Linux Enterprise Server 10 SP1 (64-bit)"); + XenServer56FP1GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", "SUSE Linux Enterprise Server 10 SP2 (32-bit)"); + XenServer56FP1GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", "SUSE Linux Enterprise Server 10 SP2 (64-bit)"); + XenServer56FP1GuestOsMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", "SUSE Linux Enterprise Server 10 SP3 (64-bit)"); + XenServer56FP1GuestOsMap.put("SUSE Linux Enterprise Server 11 (32-bit)", "SUSE Linux Enterprise Server 11 (32-bit)"); + XenServer56FP1GuestOsMap.put("SUSE Linux Enterprise Server 11 (64-bit)", "SUSE Linux Enterprise Server 11 (64-bit)"); + XenServer56FP1GuestOsMap.put("Windows 7 (32-bit)", "Windows 7 (32-bit)"); + XenServer56FP1GuestOsMap.put("Windows 7 (64-bit)", "Windows 7 (64-bit)"); + XenServer56FP1GuestOsMap.put("Windows Server 2003 (32-bit)", "Windows Server 2003 (32-bit)"); + XenServer56FP1GuestOsMap.put("Windows Server 2003 (64-bit)", "Windows Server 2003 (64-bit)"); + XenServer56FP1GuestOsMap.put("Windows Server 2003 Enterprise Edition(32-bit)", "Windows Server 2003 (32-bit)"); + XenServer56FP1GuestOsMap.put("Windows Server 2003 Enterprise Edition(64-bit)", "Windows Server 2003 (64-bit)"); + XenServer56FP1GuestOsMap.put("Windows Server 2003 DataCenter Edition(32-bit)", "Windows Server 2003 (32-bit)"); + XenServer56FP1GuestOsMap.put("Windows Server 2003 DataCenter Edition(64-bit)", "Windows Server 2003 (64-bit)"); + XenServer56FP1GuestOsMap.put("Windows Server 2008 (32-bit)", "Windows Server 2008 (32-bit)"); + XenServer56FP1GuestOsMap.put("Windows Server 2008 (64-bit)", "Windows Server 2008 (64-bit)"); + XenServer56FP1GuestOsMap.put("Windows Server 2008 R2 (64-bit)", "Windows Server 2008 R2 (64-bit)"); + XenServer56FP1GuestOsMap.put("Windows 2000 SP4 (32-bit)", "Windows 2000 SP4 (32-bit)"); + XenServer56FP1GuestOsMap.put("Windows 2000 Server SP4 (32-bit)", "Windows 2000 SP4 (32-bit)"); + XenServer56FP1GuestOsMap.put("Windows Vista (32-bit)", "Windows Vista (32-bit)"); + XenServer56FP1GuestOsMap.put("Windows XP SP3 (32-bit)", "Windows XP SP3 (32-bit)"); + XenServer56FP1GuestOsMap.put("Ubuntu 10.04 (32-bit)", "Ubuntu Lucid Lynx 10.04 (32-bit) (experimental)"); + XenServer56FP1GuestOsMap.put("Ubuntu 10.04 (64-bit)", "Ubuntu Lucid Lynx 10.04 (64-bit) (experimental)"); + XenServer56FP1GuestOsMap.put("Other Linux (32-bit)", "Other install media"); + XenServer56FP1GuestOsMap.put("Other Linux (64-bit)", "Other install media"); + XenServer56FP1GuestOsMap.put("Other PV (32-bit)", "CentOS 5 (32-bit)"); + XenServer56FP1GuestOsMap.put("Other PV (64-bit)", "CentOS 5 (64-bit)"); } static { - _xenServer56FP1GuestOsMemoryMap.put("CentOS 4.5 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("CentOS 4.6 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("CentOS 4.7 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("CentOS 4.8 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("CentOS 5.0 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("CentOS 5.0 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("CentOS 5.1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("CentOS 5.1 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("CentOS 5.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("CentOS 5.2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("CentOS 5.3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("CentOS 5.3 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("CentOS 5.4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("CentOS 5.4 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("CentOS 5.5 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("CentOS 5.5 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("CentOS 5.6 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("CentOS 5.6 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("CentOS 5.7 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("CentOS 5.7 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("CentOS 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("CentOS 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("CentOS 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("CentOS 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("CentOS 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("CentOS 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Debian GNU/Linux 6(32-bit)", new MemoryValues(128l, 32 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Debian GNU/Linux 6(64-bit)", new MemoryValues(128l, 32 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Debian GNU/Linux 7(32-bit)", new MemoryValues(128l, 32 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Debian GNU/Linux 7(64-bit)", new MemoryValues(128l, 32 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.0 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.0 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.1 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.1 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.2 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.3 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.3 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.4 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.4 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.5 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.5 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.6 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.6 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.7 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.7 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.5 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.5 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.6 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.6 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.7 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.7 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - // _xenServer56FP1GuestOsMemoryMap.put("SUSE Linux Enterprise Server 9 SP4 (32-bit)", new MemoryValues(512l, 16*1024l));// ?? - _xenServer56FP1GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP4 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 SP1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("CentOS 4.5 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("CentOS 4.6 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("CentOS 4.7 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("CentOS 4.8 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("CentOS 5.0 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("CentOS 5.0 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("CentOS 5.1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("CentOS 5.1 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("CentOS 5.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("CentOS 5.2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("CentOS 5.3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("CentOS 5.3 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("CentOS 5.4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("CentOS 5.4 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("CentOS 5.5 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("CentOS 5.5 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("CentOS 5.6 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("CentOS 5.6 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("CentOS 5.7 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("CentOS 5.7 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("CentOS 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("CentOS 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("CentOS 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("CentOS 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("CentOS 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("CentOS 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Debian GNU/Linux 6(32-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Debian GNU/Linux 6(64-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Debian GNU/Linux 7(32-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Debian GNU/Linux 7(64-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.0 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.0 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.1 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.1 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.2 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.3 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.3 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.4 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.4 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.5 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.5 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.6 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.6 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.7 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 5.7 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Oracle Enterprise Linux 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.5 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.5 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.6 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.6 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.7 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.7 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + // XenServer56FP1GuestOsMemoryMap.put("SUSE Linux Enterprise Server 9 SP4 (32-bit)", new MemoryValues(512l, 16*1024l));// ?? + XenServer56FP1GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP4 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 SP1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); //_xenServer56FP1GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 SP1 (64-bit)", new MemoryValues(512l, 128*1024l)); //? //_xenServer56FP1GuestOsMemoryMap.put("Windows 7 (32-bit)", new MemoryValues(512l, 16*1024l)); //? //_xenServer56FP1GuestOsMemoryMap.put("Windows 7 (64-bit)", new MemoryValues(512l, 16*1024l)); //? @@ -506,19 +506,19 @@ public class CitrixHelper { //_xenServer56FP1GuestOsMemoryMap.put("Windows Server 2003 Standard Edition(64-bit)", new MemoryValues(512l, 16*1024l)); //_xenServer56FP1GuestOsMemoryMap.put("Windows Server 2008 (32-bit)", new MemoryValues(512l, 16*1024l)); //_xenServer56FP1GuestOsMemoryMap.put("Windows Server 2008 (64-bit)", new MemoryValues(512l, 16*1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Windows Server 2008 R2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Windows Server 2012 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Windows Server 8 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Windows Vista (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Windows XP SP3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Ubuntu 10.04 (32-bit)", new MemoryValues(128l, 512l)); - _xenServer56FP1GuestOsMemoryMap.put("Ubuntu 10.04 (64-bit)", new MemoryValues(128l, 32 * 1024l)); - // _xenServer56FP1GuestOsMemoryMap.put("Ubuntu 10.10 (32-bit)", new MemoryValues(512l, 16*1024l));//? + XenServer56FP1GuestOsMemoryMap.put("Windows Server 2008 R2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Windows Server 2012 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Windows Server 8 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Windows Vista (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Windows XP SP3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Ubuntu 10.04 (32-bit)", new MemoryValues(128l, 512l)); + XenServer56FP1GuestOsMemoryMap.put("Ubuntu 10.04 (64-bit)", new MemoryValues(128l, 32 * 1024l)); + // XenServer56FP1GuestOsMemoryMap.put("Ubuntu 10.10 (32-bit)", new MemoryValues(512l, 16*1024l));//? //_xenServer56FP1GuestOsMemoryMap.put("Ubuntu 10.10 (64-bit)", new MemoryValues(512l, 16*1024l)); //? - _xenServer56FP1GuestOsMemoryMap.put("Ubuntu 12.04 (32-bit)", new MemoryValues(128l, 32 * 1024l)); - _xenServer56FP1GuestOsMemoryMap.put("Ubuntu 12.04 (64-bit)", new MemoryValues(128l, 128 * 1024l)); - // _xenServer56FP1GuestOsMemoryMap.put("Other Linux (32-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer56FP1GuestOsMemoryMap.put("Other Linux (64-bit)", new MemoryValues(512l, 16*1024l)); + XenServer56FP1GuestOsMemoryMap.put("Ubuntu 12.04 (32-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer56FP1GuestOsMemoryMap.put("Ubuntu 12.04 (64-bit)", new MemoryValues(128l, 128 * 1024l)); + // XenServer56FP1GuestOsMemoryMap.put("Other Linux (32-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer56FP1GuestOsMemoryMap.put("Other Linux (64-bit)", new MemoryValues(512l, 16*1024l)); //_xenServer56FP1GuestOsMemoryMap.put("Other (32-bit)", new MemoryValues(512l, 16*1024l)); //_xenServer56FP1GuestOsMemoryMap.put("Other (64-bit)", new MemoryValues(512l, 16*1024l)); //_xenServer56FP1GuestOsMemoryMap.put("Other CentOS (32-bit)", new MemoryValues(512l, 16*1024l)); @@ -532,179 +532,179 @@ public class CitrixHelper { } static { - _xenServer56FP2GuestOsMap.put("CentOS 4.5 (32-bit)", "CentOS 4.5 (32-bit)"); - _xenServer56FP2GuestOsMap.put("CentOS 4.6 (32-bit)", "CentOS 4.6 (32-bit)"); - _xenServer56FP2GuestOsMap.put("CentOS 4.7 (32-bit)", "CentOS 4.7 (32-bit)"); - _xenServer56FP2GuestOsMap.put("CentOS 4.8 (32-bit)", "CentOS 4.8 (32-bit)"); - _xenServer56FP2GuestOsMap.put("CentOS 5.0 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer56FP2GuestOsMap.put("CentOS 5.0 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer56FP2GuestOsMap.put("CentOS 5.1 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer56FP2GuestOsMap.put("CentOS 5.1 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer56FP2GuestOsMap.put("CentOS 5.2 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer56FP2GuestOsMap.put("CentOS 5.2 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer56FP2GuestOsMap.put("CentOS 5.3 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer56FP2GuestOsMap.put("CentOS 5.3 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer56FP2GuestOsMap.put("CentOS 5.4 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer56FP2GuestOsMap.put("CentOS 5.4 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer56FP2GuestOsMap.put("CentOS 5.5 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer56FP2GuestOsMap.put("CentOS 5.5 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer56FP2GuestOsMap.put("Debian GNU/Linux 5.0 (32-bit)", "Debian Lenny 5.0 (32-bit)"); - _xenServer56FP2GuestOsMap.put("Debian GNU/Linux 6(32-bit)", "Debian Squeeze 6.0 (32-bit)"); - _xenServer56FP2GuestOsMap.put("Debian GNU/Linux 6(64-bit)", "Debian Squeeze 6.0 (64-bit) (experimental)"); - _xenServer56FP2GuestOsMap.put("Debian GNU/Linux 7(32-bit)", "Debian Squeeze 6.0 (32-bit)"); // This is to support Debian 7.0 in XS 5.6FP2 - _xenServer56FP2GuestOsMap.put("Debian GNU/Linux 7(64-bit)", "Debian Squeeze 6.0 (64-bit) (experimental)"); - _xenServer56FP2GuestOsMap.put("Oracle Enterprise Linux 5.0 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer56FP2GuestOsMap.put("Oracle Enterprise Linux 5.0 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer56FP2GuestOsMap.put("Oracle Enterprise Linux 5.1 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer56FP2GuestOsMap.put("Oracle Enterprise Linux 5.1 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer56FP2GuestOsMap.put("Oracle Enterprise Linux 5.2 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer56FP2GuestOsMap.put("Oracle Enterprise Linux 5.2 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer56FP2GuestOsMap.put("Oracle Enterprise Linux 5.3 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer56FP2GuestOsMap.put("Oracle Enterprise Linux 5.3 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer56FP2GuestOsMap.put("Oracle Enterprise Linux 5.4 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer56FP2GuestOsMap.put("Oracle Enterprise Linux 5.4 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer56FP2GuestOsMap.put("Oracle Enterprise Linux 5.5 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer56FP2GuestOsMap.put("Oracle Enterprise Linux 5.5 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", "Red Hat Enterprise Linux 4.5 (32-bit)"); - _xenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", "Red Hat Enterprise Linux 4.6 (32-bit)"); - _xenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", "Red Hat Enterprise Linux 4.7 (32-bit)"); - _xenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", "Red Hat Enterprise Linux 4.8 (32-bit)"); - _xenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 5.5 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 5.5 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 6.0 (32-bit)", "Red Hat Enterprise Linux 6 (32-bit)"); - _xenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 6.0 (64-bit)", "Red Hat Enterprise Linux 6 (64-bit)"); - _xenServer56FP2GuestOsMap.put("SUSE Linux Enterprise Server 9 SP4 (32-bit)", "SUSE Linux Enterprise Server 9 SP4 (32-bit)"); - _xenServer56FP2GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", "SUSE Linux Enterprise Server 10 SP1 (32-bit)"); - _xenServer56FP2GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", "SUSE Linux Enterprise Server 10 SP1 (64-bit)"); - _xenServer56FP2GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", "SUSE Linux Enterprise Server 10 SP2 (32-bit)"); - _xenServer56FP2GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", "SUSE Linux Enterprise Server 10 SP2 (64-bit)"); - _xenServer56FP2GuestOsMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", "SUSE Linux Enterprise Server 10 SP3 (64-bit)"); - _xenServer56FP2GuestOsMap.put("SUSE Linux Enterprise Server 11 (32-bit)", "SUSE Linux Enterprise Server 11 (32-bit)"); - _xenServer56FP2GuestOsMap.put("SUSE Linux Enterprise Server 11 (64-bit)", "SUSE Linux Enterprise Server 11 (64-bit)"); - _xenServer56FP2GuestOsMap.put("Windows 7 (32-bit)", "Windows 7 (32-bit)"); - _xenServer56FP2GuestOsMap.put("Windows 7 (64-bit)", "Windows 7 (64-bit)"); - _xenServer56FP2GuestOsMap.put("Windows Server 2003 (32-bit)", "Windows Server 2003 (32-bit)"); - _xenServer56FP2GuestOsMap.put("Windows Server 2003 (64-bit)", "Windows Server 2003 (64-bit)"); - _xenServer56FP2GuestOsMap.put("Windows Server 2008 (32-bit)", "Windows Server 2008 (32-bit)"); - _xenServer56FP2GuestOsMap.put("Windows Server 2008 (64-bit)", "Windows Server 2008 (64-bit)"); - _xenServer56FP2GuestOsMap.put("Windows Server 2008 R2 (64-bit)", "Windows Server 2008 R2 (64-bit)"); - _xenServer56FP2GuestOsMap.put("Windows Vista (32-bit)", "Windows Vista (32-bit)"); - _xenServer56FP2GuestOsMap.put("Windows XP SP3 (32-bit)", "Windows XP SP3 (32-bit)"); - _xenServer56FP2GuestOsMap.put("Ubuntu 10.04 (32-bit)", "Ubuntu Lucid Lynx 10.04 (32-bit) (experimental)"); - _xenServer56FP2GuestOsMap.put("Ubuntu 10.04 (64-bit)", "Ubuntu Lucid Lynx 10.04 (64-bit) (experimental)"); - _xenServer56FP2GuestOsMap.put("Other Linux (32-bit)", "Other install media"); - _xenServer56FP2GuestOsMap.put("Other Linux (64-bit)", "Other install media"); - _xenServer56FP2GuestOsMap.put("Other PV (32-bit)", "CentOS 5 (32-bit)"); - _xenServer56FP2GuestOsMap.put("Other PV (64-bit)", "CentOS 5 (64-bit)"); + XenServer56FP2GuestOsMap.put("CentOS 4.5 (32-bit)", "CentOS 4.5 (32-bit)"); + XenServer56FP2GuestOsMap.put("CentOS 4.6 (32-bit)", "CentOS 4.6 (32-bit)"); + XenServer56FP2GuestOsMap.put("CentOS 4.7 (32-bit)", "CentOS 4.7 (32-bit)"); + XenServer56FP2GuestOsMap.put("CentOS 4.8 (32-bit)", "CentOS 4.8 (32-bit)"); + XenServer56FP2GuestOsMap.put("CentOS 5.0 (32-bit)", "CentOS 5 (32-bit)"); + XenServer56FP2GuestOsMap.put("CentOS 5.0 (64-bit)", "CentOS 5 (64-bit)"); + XenServer56FP2GuestOsMap.put("CentOS 5.1 (32-bit)", "CentOS 5 (32-bit)"); + XenServer56FP2GuestOsMap.put("CentOS 5.1 (64-bit)", "CentOS 5 (64-bit)"); + XenServer56FP2GuestOsMap.put("CentOS 5.2 (32-bit)", "CentOS 5 (32-bit)"); + XenServer56FP2GuestOsMap.put("CentOS 5.2 (64-bit)", "CentOS 5 (64-bit)"); + XenServer56FP2GuestOsMap.put("CentOS 5.3 (32-bit)", "CentOS 5 (32-bit)"); + XenServer56FP2GuestOsMap.put("CentOS 5.3 (64-bit)", "CentOS 5 (64-bit)"); + XenServer56FP2GuestOsMap.put("CentOS 5.4 (32-bit)", "CentOS 5 (32-bit)"); + XenServer56FP2GuestOsMap.put("CentOS 5.4 (64-bit)", "CentOS 5 (64-bit)"); + XenServer56FP2GuestOsMap.put("CentOS 5.5 (32-bit)", "CentOS 5 (32-bit)"); + XenServer56FP2GuestOsMap.put("CentOS 5.5 (64-bit)", "CentOS 5 (64-bit)"); + XenServer56FP2GuestOsMap.put("Debian GNU/Linux 5.0 (32-bit)", "Debian Lenny 5.0 (32-bit)"); + XenServer56FP2GuestOsMap.put("Debian GNU/Linux 6(32-bit)", "Debian Squeeze 6.0 (32-bit)"); + XenServer56FP2GuestOsMap.put("Debian GNU/Linux 6(64-bit)", "Debian Squeeze 6.0 (64-bit) (experimental)"); + XenServer56FP2GuestOsMap.put("Debian GNU/Linux 7(32-bit)", "Debian Squeeze 6.0 (32-bit)"); // This is to support Debian 7.0 in XS 5.6FP2 + XenServer56FP2GuestOsMap.put("Debian GNU/Linux 7(64-bit)", "Debian Squeeze 6.0 (64-bit) (experimental)"); + XenServer56FP2GuestOsMap.put("Oracle Enterprise Linux 5.0 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer56FP2GuestOsMap.put("Oracle Enterprise Linux 5.0 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer56FP2GuestOsMap.put("Oracle Enterprise Linux 5.1 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer56FP2GuestOsMap.put("Oracle Enterprise Linux 5.1 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer56FP2GuestOsMap.put("Oracle Enterprise Linux 5.2 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer56FP2GuestOsMap.put("Oracle Enterprise Linux 5.2 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer56FP2GuestOsMap.put("Oracle Enterprise Linux 5.3 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer56FP2GuestOsMap.put("Oracle Enterprise Linux 5.3 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer56FP2GuestOsMap.put("Oracle Enterprise Linux 5.4 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer56FP2GuestOsMap.put("Oracle Enterprise Linux 5.4 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer56FP2GuestOsMap.put("Oracle Enterprise Linux 5.5 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer56FP2GuestOsMap.put("Oracle Enterprise Linux 5.5 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", "Red Hat Enterprise Linux 4.5 (32-bit)"); + XenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", "Red Hat Enterprise Linux 4.6 (32-bit)"); + XenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", "Red Hat Enterprise Linux 4.7 (32-bit)"); + XenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", "Red Hat Enterprise Linux 4.8 (32-bit)"); + XenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 5.5 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 5.5 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 6.0 (32-bit)", "Red Hat Enterprise Linux 6 (32-bit)"); + XenServer56FP2GuestOsMap.put("Red Hat Enterprise Linux 6.0 (64-bit)", "Red Hat Enterprise Linux 6 (64-bit)"); + XenServer56FP2GuestOsMap.put("SUSE Linux Enterprise Server 9 SP4 (32-bit)", "SUSE Linux Enterprise Server 9 SP4 (32-bit)"); + XenServer56FP2GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", "SUSE Linux Enterprise Server 10 SP1 (32-bit)"); + XenServer56FP2GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", "SUSE Linux Enterprise Server 10 SP1 (64-bit)"); + XenServer56FP2GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", "SUSE Linux Enterprise Server 10 SP2 (32-bit)"); + XenServer56FP2GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", "SUSE Linux Enterprise Server 10 SP2 (64-bit)"); + XenServer56FP2GuestOsMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", "SUSE Linux Enterprise Server 10 SP3 (64-bit)"); + XenServer56FP2GuestOsMap.put("SUSE Linux Enterprise Server 11 (32-bit)", "SUSE Linux Enterprise Server 11 (32-bit)"); + XenServer56FP2GuestOsMap.put("SUSE Linux Enterprise Server 11 (64-bit)", "SUSE Linux Enterprise Server 11 (64-bit)"); + XenServer56FP2GuestOsMap.put("Windows 7 (32-bit)", "Windows 7 (32-bit)"); + XenServer56FP2GuestOsMap.put("Windows 7 (64-bit)", "Windows 7 (64-bit)"); + XenServer56FP2GuestOsMap.put("Windows Server 2003 (32-bit)", "Windows Server 2003 (32-bit)"); + XenServer56FP2GuestOsMap.put("Windows Server 2003 (64-bit)", "Windows Server 2003 (64-bit)"); + XenServer56FP2GuestOsMap.put("Windows Server 2008 (32-bit)", "Windows Server 2008 (32-bit)"); + XenServer56FP2GuestOsMap.put("Windows Server 2008 (64-bit)", "Windows Server 2008 (64-bit)"); + XenServer56FP2GuestOsMap.put("Windows Server 2008 R2 (64-bit)", "Windows Server 2008 R2 (64-bit)"); + XenServer56FP2GuestOsMap.put("Windows Vista (32-bit)", "Windows Vista (32-bit)"); + XenServer56FP2GuestOsMap.put("Windows XP SP3 (32-bit)", "Windows XP SP3 (32-bit)"); + XenServer56FP2GuestOsMap.put("Ubuntu 10.04 (32-bit)", "Ubuntu Lucid Lynx 10.04 (32-bit) (experimental)"); + XenServer56FP2GuestOsMap.put("Ubuntu 10.04 (64-bit)", "Ubuntu Lucid Lynx 10.04 (64-bit) (experimental)"); + XenServer56FP2GuestOsMap.put("Other Linux (32-bit)", "Other install media"); + XenServer56FP2GuestOsMap.put("Other Linux (64-bit)", "Other install media"); + XenServer56FP2GuestOsMap.put("Other PV (32-bit)", "CentOS 5 (32-bit)"); + XenServer56FP2GuestOsMap.put("Other PV (64-bit)", "CentOS 5 (64-bit)"); } static { - _xenServer56SP2GuestOsMemoryMap.put("CentOS 4.5 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("CentOS 4.6 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("CentOS 4.7 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("CentOS 4.8 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("CentOS 5.0 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("CentOS 5.0 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("CentOS 5.1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("CentOS 5.1 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("CentOS 5.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("CentOS 5.2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("CentOS 5.3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("CentOS 5.3 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("CentOS 5.4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("CentOS 5.4 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("CentOS 5.5 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("CentOS 5.5 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("CentOS 5.6 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("CentOS 5.6 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("CentOS 5.7 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("CentOS 5.7 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("CentOS 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("CentOS 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("CentOS 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("CentOS 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("CentOS 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("CentOS 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Debian GNU/Linux 6(32-bit)", new MemoryValues(128l, 32 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Debian GNU/Linux 6(64-bit)", new MemoryValues(128l, 32 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Debian GNU/Linux 7(32-bit)", new MemoryValues(128l, 32 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Debian GNU/Linux 7(64-bit)", new MemoryValues(128l, 32 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.0 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.0 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.1 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.1 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.2 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.3 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.3 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.4 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.4 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.5 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.5 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.6 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.6 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.7 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.7 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.5 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.5 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.6 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.6 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.7 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.7 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("CentOS 4.5 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("CentOS 4.6 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("CentOS 4.7 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("CentOS 4.8 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("CentOS 5.0 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("CentOS 5.0 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("CentOS 5.1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("CentOS 5.1 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("CentOS 5.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("CentOS 5.2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("CentOS 5.3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("CentOS 5.3 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("CentOS 5.4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("CentOS 5.4 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("CentOS 5.5 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("CentOS 5.5 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("CentOS 5.6 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("CentOS 5.6 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("CentOS 5.7 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("CentOS 5.7 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("CentOS 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("CentOS 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("CentOS 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("CentOS 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("CentOS 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("CentOS 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Debian GNU/Linux 6(32-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Debian GNU/Linux 6(64-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Debian GNU/Linux 7(32-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Debian GNU/Linux 7(64-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.0 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.0 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.1 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.1 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.2 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.3 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.3 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.4 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.4 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.5 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.5 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.6 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.6 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.7 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 5.7 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Oracle Enterprise Linux 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.5 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.5 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.6 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.6 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.7 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.7 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); //_xenServer56SP2GuestOsMemoryMap.put("SUSE Linux Enterprise Server 9 SP4 (32-bit)", new MemoryValues(512l, 16*1024l));// ?? - _xenServer56SP2GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP4 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 SP1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP4 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 SP1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); //_xenServer56SP2GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 SP1 (64-bit)", new MemoryValues(512l, 128*1024l)); //? //_xenServer56SP2GuestOsMemoryMap.put("Windows 7 (32-bit)", new MemoryValues(512l, 16*1024l)); //? //_xenServer56SP2GuestOsMemoryMap.put("Windows 7 (64-bit)", new MemoryValues(512l, 16*1024l)); //? //_xenServer56SP2GuestOsMemoryMap.put("Windows 8 (32-bit)", new MemoryValues(512l, 16*1024l)); //? //_xenServer56SP2GuestOsMemoryMap.put("Windows 8 (64-bit)", new MemoryValues(512l, 16*1024l)); //? - // _xenServer56SP2GuestOsMemoryMap.put("Windows Server 2003 (32-bit)", new MemoryValues(256l, 64*1024l)); + // XenServer56SP2GuestOsMemoryMap.put("Windows Server 2003 (32-bit)", new MemoryValues(256l, 64*1024l)); //_xenServer56SP2GuestOsMemoryMap.put("Windows Server 2003 (64-bit)", new MemoryValues(256l, 128*1024l)); //_xenServer56SP2GuestOsMemoryMap.put("Windows Server 2003 PAE (32-bit)", new MemoryValues(512l, 16*1024l)); //_xenServer56SP2GuestOsMemoryMap.put("Windows Server 2003 Enterprise Edition(32-bit)", new MemoryValues(512l, 16*1024l)); @@ -715,236 +715,236 @@ public class CitrixHelper { //_xenServer56SP2GuestOsMemoryMap.put("Windows Server 2003 Standard Edition(64-bit)", new MemoryValues(512l, 16*1024l)); //_xenServer56SP2GuestOsMemoryMap.put("Windows Server 2008 (32-bit)", new MemoryValues(512l, 16*1024l)); //_xenServer56SP2GuestOsMemoryMap.put("Windows Server 2008 (64-bit)", new MemoryValues(512l, 16*1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Windows Server 2008 R2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Windows Server 2012 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Windows Server 8 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Windows Vista (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Windows XP SP3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Ubuntu 10.04 (32-bit)", new MemoryValues(128l, 512l)); - _xenServer56SP2GuestOsMemoryMap.put("Ubuntu 10.04 (64-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Windows Server 2008 R2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Windows Server 2012 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Windows Server 8 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Windows Vista (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Windows XP SP3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Ubuntu 10.04 (32-bit)", new MemoryValues(128l, 512l)); + XenServer56SP2GuestOsMemoryMap.put("Ubuntu 10.04 (64-bit)", new MemoryValues(128l, 32 * 1024l)); //_xenServer56SP2GuestOsMemoryMap.put("Ubuntu 10.10 (32-bit)", new MemoryValues(512l, 16*1024l));//? //_xenServer56SP2GuestOsMemoryMap.put("Ubuntu 10.10 (64-bit)", new MemoryValues(512l, 16*1024l)); //? - _xenServer56SP2GuestOsMemoryMap.put("Ubuntu 12.04 (32-bit)", new MemoryValues(128l, 32 * 1024l)); - _xenServer56SP2GuestOsMemoryMap.put("Ubuntu 12.04 (64-bit)", new MemoryValues(128l, 128 * 1024l)); - // _xenServer56SP2GuestOsMemoryMap.put("Other Linux (32-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer56SP2GuestOsMemoryMap.put("Other Linux (64-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer56SP2GuestOsMemoryMap.put("Other (32-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer56SP2GuestOsMemoryMap.put("Other (64-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer56SP2GuestOsMemoryMap.put("Other CentOS (32-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer56SP2GuestOsMemoryMap.put("Other CentOS (64-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer56SP2GuestOsMemoryMap.put("Other Ubuntu (32-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer56SP2GuestOsMemoryMap.put("Other Ubuntu (64-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer56SP2GuestOsMemoryMap.put("Other SUSE Linux(32-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer56SP2GuestOsMemoryMap.put("Other SUSE Linux(64-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer56SP2GuestOsMemoryMap.put("Other PV (32-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer56SP2GuestOsMemoryMap.put("Other PV (64-bit)", new MemoryValues(512l, 16*1024l)); + XenServer56SP2GuestOsMemoryMap.put("Ubuntu 12.04 (32-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer56SP2GuestOsMemoryMap.put("Ubuntu 12.04 (64-bit)", new MemoryValues(128l, 128 * 1024l)); + // XenServer56SP2GuestOsMemoryMap.put("Other Linux (32-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer56SP2GuestOsMemoryMap.put("Other Linux (64-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer56SP2GuestOsMemoryMap.put("Other (32-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer56SP2GuestOsMemoryMap.put("Other (64-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer56SP2GuestOsMemoryMap.put("Other CentOS (32-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer56SP2GuestOsMemoryMap.put("Other CentOS (64-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer56SP2GuestOsMemoryMap.put("Other Ubuntu (32-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer56SP2GuestOsMemoryMap.put("Other Ubuntu (64-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer56SP2GuestOsMemoryMap.put("Other SUSE Linux(32-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer56SP2GuestOsMemoryMap.put("Other SUSE Linux(64-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer56SP2GuestOsMemoryMap.put("Other PV (32-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer56SP2GuestOsMemoryMap.put("Other PV (64-bit)", new MemoryValues(512l, 16*1024l)); } static { - _xenServer600GuestOsMap.put("CentOS 4.5 (32-bit)", "CentOS 4.5 (32-bit)"); - _xenServer600GuestOsMap.put("CentOS 4.6 (32-bit)", "CentOS 4.6 (32-bit)"); - _xenServer600GuestOsMap.put("CentOS 4.7 (32-bit)", "CentOS 4.7 (32-bit)"); - _xenServer600GuestOsMap.put("CentOS 4.8 (32-bit)", "CentOS 4.8 (32-bit)"); - _xenServer600GuestOsMap.put("CentOS 5.0 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer600GuestOsMap.put("CentOS 5.0 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer600GuestOsMap.put("CentOS 5.1 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer600GuestOsMap.put("CentOS 5.1 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer600GuestOsMap.put("CentOS 5.2 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer600GuestOsMap.put("CentOS 5.2 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer600GuestOsMap.put("CentOS 5.3 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer600GuestOsMap.put("CentOS 5.3 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer600GuestOsMap.put("CentOS 5.4 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer600GuestOsMap.put("CentOS 5.4 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer600GuestOsMap.put("CentOS 5.5 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer600GuestOsMap.put("CentOS 5.5 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer600GuestOsMap.put("CentOS 5.6 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer600GuestOsMap.put("CentOS 5.6 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer600GuestOsMap.put("CentOS 6.0 (32-bit)", "CentOS 6.0 (32-bit) (experimental)"); - _xenServer600GuestOsMap.put("CentOS 6.0 (64-bit)", "CentOS 6.0 (64-bit) (experimental)"); - _xenServer600GuestOsMap.put("Debian GNU/Linux 5.0 (32-bit)", "Debian Lenny 5.0 (32-bit)"); - _xenServer600GuestOsMap.put("Debian GNU/Linux 6(32-bit)", "Debian Squeeze 6.0 (32-bit)"); - _xenServer600GuestOsMap.put("Debian GNU/Linux 6(64-bit)", "Debian Squeeze 6.0 (64-bit)"); - _xenServer600GuestOsMap.put("Debian GNU/Linux 7(32-bit)", "Debian Squeeze 6.0 (32-bit)"); // This is to support Debian 7.0 in XS 6.0 - _xenServer600GuestOsMap.put("Debian GNU/Linux 7(64-bit)", "Debian Squeeze 6.0 (64-bit)"); - _xenServer600GuestOsMap.put("Oracle Enterprise Linux 5.0 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer600GuestOsMap.put("Oracle Enterprise Linux 5.0 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer600GuestOsMap.put("Oracle Enterprise Linux 5.1 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer600GuestOsMap.put("Oracle Enterprise Linux 5.1 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer600GuestOsMap.put("Oracle Enterprise Linux 5.2 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer600GuestOsMap.put("Oracle Enterprise Linux 5.2 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer600GuestOsMap.put("Oracle Enterprise Linux 5.3 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer600GuestOsMap.put("Oracle Enterprise Linux 5.3 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer600GuestOsMap.put("Oracle Enterprise Linux 5.4 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer600GuestOsMap.put("Oracle Enterprise Linux 5.4 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer600GuestOsMap.put("Oracle Enterprise Linux 5.5 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer600GuestOsMap.put("Oracle Enterprise Linux 5.5 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer600GuestOsMap.put("Oracle Enterprise Linux 5.6 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer600GuestOsMap.put("Oracle Enterprise Linux 5.6 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer600GuestOsMap.put("Oracle Enterprise Linux 6.0 (32-bit)", "Oracle Enterprise Linux 6.0 (32-bit)"); - _xenServer600GuestOsMap.put("Oracle Enterprise Linux 6.0 (64-bit)", "Oracle Enterprise Linux 6.0 (64-bit)"); - _xenServer600GuestOsMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", "Red Hat Enterprise Linux 4.5 (32-bit)"); - _xenServer600GuestOsMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", "Red Hat Enterprise Linux 4.6 (32-bit)"); - _xenServer600GuestOsMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", "Red Hat Enterprise Linux 4.7 (32-bit)"); - _xenServer600GuestOsMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", "Red Hat Enterprise Linux 4.8 (32-bit)"); - _xenServer600GuestOsMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer600GuestOsMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer600GuestOsMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer600GuestOsMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer600GuestOsMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer600GuestOsMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer600GuestOsMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer600GuestOsMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer600GuestOsMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer600GuestOsMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer600GuestOsMap.put("Red Hat Enterprise Linux 5.5 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer600GuestOsMap.put("Red Hat Enterprise Linux 5.5 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer600GuestOsMap.put("Red Hat Enterprise Linux 5.6 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer600GuestOsMap.put("Red Hat Enterprise Linux 5.6 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer600GuestOsMap.put("Red Hat Enterprise Linux 6.0 (32-bit)", "Red Hat Enterprise Linux 6.0 (32-bit)"); - _xenServer600GuestOsMap.put("Red Hat Enterprise Linux 6.0 (64-bit)", "Red Hat Enterprise Linux 6.0 (64-bit)"); - _xenServer600GuestOsMap.put("SUSE Linux Enterprise Server 9 SP4 (32-bit)", "SUSE Linux Enterprise Server 9 SP4 (32-bit)"); - _xenServer600GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", "SUSE Linux Enterprise Server 10 SP1 (32-bit)"); - _xenServer600GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", "SUSE Linux Enterprise Server 10 SP1 (64-bit)"); - _xenServer600GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", "SUSE Linux Enterprise Server 10 SP2 (32-bit)"); - _xenServer600GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", "SUSE Linux Enterprise Server 10 SP2 (64-bit)"); - _xenServer600GuestOsMap.put("SUSE Linux Enterprise Server 10 SP3 (32-bit)", "SUSE Linux Enterprise Server 10 SP3 (32-bit)"); - _xenServer600GuestOsMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", "SUSE Linux Enterprise Server 10 SP3 (64-bit)"); - _xenServer600GuestOsMap.put("SUSE Linux Enterprise Server 10 SP4 (32-bit)", "SUSE Linux Enterprise Server 10 SP4 (32-bit)"); - _xenServer600GuestOsMap.put("SUSE Linux Enterprise Server 10 SP4 (64-bit)", "SUSE Linux Enterprise Server 10 SP4 (64-bit)"); - _xenServer600GuestOsMap.put("SUSE Linux Enterprise Server 11 (32-bit)", "SUSE Linux Enterprise Server 11 (32-bit)"); - _xenServer600GuestOsMap.put("SUSE Linux Enterprise Server 11 (64-bit)", "SUSE Linux Enterprise Server 11 (64-bit)"); - _xenServer600GuestOsMap.put("SUSE Linux Enterprise Server 11 SP1 (32-bit)", "SUSE Linux Enterprise Server 11 SP1 (32-bit)"); - _xenServer600GuestOsMap.put("SUSE Linux Enterprise Server 11 SP1 (64-bit)", "SUSE Linux Enterprise Server 11 SP1 (64-bit)"); - _xenServer600GuestOsMap.put("Windows 7 (32-bit)", "Windows 7 (32-bit)"); - _xenServer600GuestOsMap.put("Windows 7 (64-bit)", "Windows 7 (64-bit)"); - _xenServer600GuestOsMap.put("Windows Server 2003 (32-bit)", "Windows Server 2003 (32-bit)"); - _xenServer600GuestOsMap.put("Windows Server 2003 (64-bit)", "Windows Server 2003 (64-bit)"); - _xenServer600GuestOsMap.put("Windows Server 2003 Enterprise Edition(32-bit)", "Windows Server 2003 (32-bit)"); - _xenServer600GuestOsMap.put("Windows Server 2003 Enterprise Edition(64-bit)", "Windows Server 2003 (64-bit)"); - _xenServer600GuestOsMap.put("Windows Server 2003 DataCenter Edition(32-bit)", "Windows Server 2003 (32-bit)"); - _xenServer600GuestOsMap.put("Windows Server 2003 DataCenter Edition(64-bit)", "Windows Server 2003 (64-bit)"); - _xenServer600GuestOsMap.put("Windows Server 2003 Standard Edition(32-bit)", "Windows Server 2003 (32-bit)"); - _xenServer600GuestOsMap.put("Windows Server 2003 Standard Edition(64-bit)", "Windows Server 2003 (64-bit)"); - _xenServer600GuestOsMap.put("Windows Server 2008 (32-bit)", "Windows Server 2008 (32-bit)"); - _xenServer600GuestOsMap.put("Windows Server 2008 (64-bit)", "Windows Server 2008 (64-bit)"); - _xenServer600GuestOsMap.put("Windows Server 2008 R2 (64-bit)", "Windows Server 2008 R2 (64-bit)"); - _xenServer600GuestOsMap.put("Windows Vista (32-bit)", "Windows Vista (32-bit)"); - _xenServer600GuestOsMap.put("Windows XP SP3 (32-bit)", "Windows XP SP3 (32-bit)"); - _xenServer600GuestOsMap.put("Ubuntu 10.04 (32-bit)", "Ubuntu Lucid Lynx 10.04 (32-bit)"); - _xenServer600GuestOsMap.put("Ubuntu 10.04 (64-bit)", "Ubuntu Lucid Lynx 10.04 (64-bit)"); - _xenServer600GuestOsMap.put("Ubuntu 10.10 (32-bit)", "Ubuntu Maverick Meerkat 10.10 (32-bit) (experimental)"); - _xenServer600GuestOsMap.put("Ubuntu 10.10 (64-bit)", "Ubuntu Maverick Meerkat 10.10 (64-bit) (experimental)"); - _xenServer600GuestOsMap.put("Other Linux (32-bit)", "Other install media"); - _xenServer600GuestOsMap.put("Other Linux (64-bit)", "Other install media"); - _xenServer600GuestOsMap.put("Other (32-bit)", "Other install media"); - _xenServer600GuestOsMap.put("Other (64-bit)", "Other install media"); - _xenServer600GuestOsMap.put("Other CentOS (32-bit)", "Other install media"); - _xenServer600GuestOsMap.put("Other CentOS (64-bit)", "Other install media"); - _xenServer600GuestOsMap.put("Other Ubuntu (32-bit)", "Other install media"); - _xenServer600GuestOsMap.put("Other Ubuntu (64-bit)", "Other install media"); - _xenServer600GuestOsMap.put("Other SUSE Linux(32-bit)", "Other install media"); - _xenServer600GuestOsMap.put("Other SUSE Linux(64-bit)", "Other install media"); - _xenServer600GuestOsMap.put("Other PV (32-bit)", "CentOS 5 (32-bit)"); - _xenServer600GuestOsMap.put("Other PV (64-bit)", "CentOS 5 (64-bit)"); + XenServer600GuestOsMap.put("CentOS 4.5 (32-bit)", "CentOS 4.5 (32-bit)"); + XenServer600GuestOsMap.put("CentOS 4.6 (32-bit)", "CentOS 4.6 (32-bit)"); + XenServer600GuestOsMap.put("CentOS 4.7 (32-bit)", "CentOS 4.7 (32-bit)"); + XenServer600GuestOsMap.put("CentOS 4.8 (32-bit)", "CentOS 4.8 (32-bit)"); + XenServer600GuestOsMap.put("CentOS 5.0 (32-bit)", "CentOS 5 (32-bit)"); + XenServer600GuestOsMap.put("CentOS 5.0 (64-bit)", "CentOS 5 (64-bit)"); + XenServer600GuestOsMap.put("CentOS 5.1 (32-bit)", "CentOS 5 (32-bit)"); + XenServer600GuestOsMap.put("CentOS 5.1 (64-bit)", "CentOS 5 (64-bit)"); + XenServer600GuestOsMap.put("CentOS 5.2 (32-bit)", "CentOS 5 (32-bit)"); + XenServer600GuestOsMap.put("CentOS 5.2 (64-bit)", "CentOS 5 (64-bit)"); + XenServer600GuestOsMap.put("CentOS 5.3 (32-bit)", "CentOS 5 (32-bit)"); + XenServer600GuestOsMap.put("CentOS 5.3 (64-bit)", "CentOS 5 (64-bit)"); + XenServer600GuestOsMap.put("CentOS 5.4 (32-bit)", "CentOS 5 (32-bit)"); + XenServer600GuestOsMap.put("CentOS 5.4 (64-bit)", "CentOS 5 (64-bit)"); + XenServer600GuestOsMap.put("CentOS 5.5 (32-bit)", "CentOS 5 (32-bit)"); + XenServer600GuestOsMap.put("CentOS 5.5 (64-bit)", "CentOS 5 (64-bit)"); + XenServer600GuestOsMap.put("CentOS 5.6 (32-bit)", "CentOS 5 (32-bit)"); + XenServer600GuestOsMap.put("CentOS 5.6 (64-bit)", "CentOS 5 (64-bit)"); + XenServer600GuestOsMap.put("CentOS 6.0 (32-bit)", "CentOS 6.0 (32-bit) (experimental)"); + XenServer600GuestOsMap.put("CentOS 6.0 (64-bit)", "CentOS 6.0 (64-bit) (experimental)"); + XenServer600GuestOsMap.put("Debian GNU/Linux 5.0 (32-bit)", "Debian Lenny 5.0 (32-bit)"); + XenServer600GuestOsMap.put("Debian GNU/Linux 6(32-bit)", "Debian Squeeze 6.0 (32-bit)"); + XenServer600GuestOsMap.put("Debian GNU/Linux 6(64-bit)", "Debian Squeeze 6.0 (64-bit)"); + XenServer600GuestOsMap.put("Debian GNU/Linux 7(32-bit)", "Debian Squeeze 6.0 (32-bit)"); // This is to support Debian 7.0 in XS 6.0 + XenServer600GuestOsMap.put("Debian GNU/Linux 7(64-bit)", "Debian Squeeze 6.0 (64-bit)"); + XenServer600GuestOsMap.put("Oracle Enterprise Linux 5.0 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer600GuestOsMap.put("Oracle Enterprise Linux 5.0 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer600GuestOsMap.put("Oracle Enterprise Linux 5.1 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer600GuestOsMap.put("Oracle Enterprise Linux 5.1 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer600GuestOsMap.put("Oracle Enterprise Linux 5.2 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer600GuestOsMap.put("Oracle Enterprise Linux 5.2 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer600GuestOsMap.put("Oracle Enterprise Linux 5.3 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer600GuestOsMap.put("Oracle Enterprise Linux 5.3 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer600GuestOsMap.put("Oracle Enterprise Linux 5.4 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer600GuestOsMap.put("Oracle Enterprise Linux 5.4 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer600GuestOsMap.put("Oracle Enterprise Linux 5.5 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer600GuestOsMap.put("Oracle Enterprise Linux 5.5 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer600GuestOsMap.put("Oracle Enterprise Linux 5.6 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer600GuestOsMap.put("Oracle Enterprise Linux 5.6 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer600GuestOsMap.put("Oracle Enterprise Linux 6.0 (32-bit)", "Oracle Enterprise Linux 6.0 (32-bit)"); + XenServer600GuestOsMap.put("Oracle Enterprise Linux 6.0 (64-bit)", "Oracle Enterprise Linux 6.0 (64-bit)"); + XenServer600GuestOsMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", "Red Hat Enterprise Linux 4.5 (32-bit)"); + XenServer600GuestOsMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", "Red Hat Enterprise Linux 4.6 (32-bit)"); + XenServer600GuestOsMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", "Red Hat Enterprise Linux 4.7 (32-bit)"); + XenServer600GuestOsMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", "Red Hat Enterprise Linux 4.8 (32-bit)"); + XenServer600GuestOsMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer600GuestOsMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer600GuestOsMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer600GuestOsMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer600GuestOsMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer600GuestOsMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer600GuestOsMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer600GuestOsMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer600GuestOsMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer600GuestOsMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer600GuestOsMap.put("Red Hat Enterprise Linux 5.5 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer600GuestOsMap.put("Red Hat Enterprise Linux 5.5 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer600GuestOsMap.put("Red Hat Enterprise Linux 5.6 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer600GuestOsMap.put("Red Hat Enterprise Linux 5.6 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer600GuestOsMap.put("Red Hat Enterprise Linux 6.0 (32-bit)", "Red Hat Enterprise Linux 6.0 (32-bit)"); + XenServer600GuestOsMap.put("Red Hat Enterprise Linux 6.0 (64-bit)", "Red Hat Enterprise Linux 6.0 (64-bit)"); + XenServer600GuestOsMap.put("SUSE Linux Enterprise Server 9 SP4 (32-bit)", "SUSE Linux Enterprise Server 9 SP4 (32-bit)"); + XenServer600GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", "SUSE Linux Enterprise Server 10 SP1 (32-bit)"); + XenServer600GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", "SUSE Linux Enterprise Server 10 SP1 (64-bit)"); + XenServer600GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", "SUSE Linux Enterprise Server 10 SP2 (32-bit)"); + XenServer600GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", "SUSE Linux Enterprise Server 10 SP2 (64-bit)"); + XenServer600GuestOsMap.put("SUSE Linux Enterprise Server 10 SP3 (32-bit)", "SUSE Linux Enterprise Server 10 SP3 (32-bit)"); + XenServer600GuestOsMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", "SUSE Linux Enterprise Server 10 SP3 (64-bit)"); + XenServer600GuestOsMap.put("SUSE Linux Enterprise Server 10 SP4 (32-bit)", "SUSE Linux Enterprise Server 10 SP4 (32-bit)"); + XenServer600GuestOsMap.put("SUSE Linux Enterprise Server 10 SP4 (64-bit)", "SUSE Linux Enterprise Server 10 SP4 (64-bit)"); + XenServer600GuestOsMap.put("SUSE Linux Enterprise Server 11 (32-bit)", "SUSE Linux Enterprise Server 11 (32-bit)"); + XenServer600GuestOsMap.put("SUSE Linux Enterprise Server 11 (64-bit)", "SUSE Linux Enterprise Server 11 (64-bit)"); + XenServer600GuestOsMap.put("SUSE Linux Enterprise Server 11 SP1 (32-bit)", "SUSE Linux Enterprise Server 11 SP1 (32-bit)"); + XenServer600GuestOsMap.put("SUSE Linux Enterprise Server 11 SP1 (64-bit)", "SUSE Linux Enterprise Server 11 SP1 (64-bit)"); + XenServer600GuestOsMap.put("Windows 7 (32-bit)", "Windows 7 (32-bit)"); + XenServer600GuestOsMap.put("Windows 7 (64-bit)", "Windows 7 (64-bit)"); + XenServer600GuestOsMap.put("Windows Server 2003 (32-bit)", "Windows Server 2003 (32-bit)"); + XenServer600GuestOsMap.put("Windows Server 2003 (64-bit)", "Windows Server 2003 (64-bit)"); + XenServer600GuestOsMap.put("Windows Server 2003 Enterprise Edition(32-bit)", "Windows Server 2003 (32-bit)"); + XenServer600GuestOsMap.put("Windows Server 2003 Enterprise Edition(64-bit)", "Windows Server 2003 (64-bit)"); + XenServer600GuestOsMap.put("Windows Server 2003 DataCenter Edition(32-bit)", "Windows Server 2003 (32-bit)"); + XenServer600GuestOsMap.put("Windows Server 2003 DataCenter Edition(64-bit)", "Windows Server 2003 (64-bit)"); + XenServer600GuestOsMap.put("Windows Server 2003 Standard Edition(32-bit)", "Windows Server 2003 (32-bit)"); + XenServer600GuestOsMap.put("Windows Server 2003 Standard Edition(64-bit)", "Windows Server 2003 (64-bit)"); + XenServer600GuestOsMap.put("Windows Server 2008 (32-bit)", "Windows Server 2008 (32-bit)"); + XenServer600GuestOsMap.put("Windows Server 2008 (64-bit)", "Windows Server 2008 (64-bit)"); + XenServer600GuestOsMap.put("Windows Server 2008 R2 (64-bit)", "Windows Server 2008 R2 (64-bit)"); + XenServer600GuestOsMap.put("Windows Vista (32-bit)", "Windows Vista (32-bit)"); + XenServer600GuestOsMap.put("Windows XP SP3 (32-bit)", "Windows XP SP3 (32-bit)"); + XenServer600GuestOsMap.put("Ubuntu 10.04 (32-bit)", "Ubuntu Lucid Lynx 10.04 (32-bit)"); + XenServer600GuestOsMap.put("Ubuntu 10.04 (64-bit)", "Ubuntu Lucid Lynx 10.04 (64-bit)"); + XenServer600GuestOsMap.put("Ubuntu 10.10 (32-bit)", "Ubuntu Maverick Meerkat 10.10 (32-bit) (experimental)"); + XenServer600GuestOsMap.put("Ubuntu 10.10 (64-bit)", "Ubuntu Maverick Meerkat 10.10 (64-bit) (experimental)"); + XenServer600GuestOsMap.put("Other Linux (32-bit)", "Other install media"); + XenServer600GuestOsMap.put("Other Linux (64-bit)", "Other install media"); + XenServer600GuestOsMap.put("Other (32-bit)", "Other install media"); + XenServer600GuestOsMap.put("Other (64-bit)", "Other install media"); + XenServer600GuestOsMap.put("Other CentOS (32-bit)", "Other install media"); + XenServer600GuestOsMap.put("Other CentOS (64-bit)", "Other install media"); + XenServer600GuestOsMap.put("Other Ubuntu (32-bit)", "Other install media"); + XenServer600GuestOsMap.put("Other Ubuntu (64-bit)", "Other install media"); + XenServer600GuestOsMap.put("Other SUSE Linux(32-bit)", "Other install media"); + XenServer600GuestOsMap.put("Other SUSE Linux(64-bit)", "Other install media"); + XenServer600GuestOsMap.put("Other PV (32-bit)", "CentOS 5 (32-bit)"); + XenServer600GuestOsMap.put("Other PV (64-bit)", "CentOS 5 (64-bit)"); } static { - _xenServer600GuestOsMemoryMap.put("CentOS 4.5 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("CentOS 4.6 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("CentOS 4.7 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("CentOS 4.8 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("CentOS 5.0 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("CentOS 5.0 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("CentOS 5.1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("CentOS 5.1 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("CentOS 5.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("CentOS 5.2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("CentOS 5.3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("CentOS 5.3 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("CentOS 5.4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("CentOS 5.4 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("CentOS 5.5 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("CentOS 5.5 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("CentOS 5.6 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("CentOS 5.6 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("CentOS 5.7 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("CentOS 5.7 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("CentOS 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer600GuestOsMemoryMap.put("CentOS 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer600GuestOsMemoryMap.put("CentOS 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer600GuestOsMemoryMap.put("CentOS 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer600GuestOsMemoryMap.put("CentOS 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("CentOS 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Debian GNU/Linux 6(32-bit)", new MemoryValues(128l, 32 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Debian GNU/Linux 6(64-bit)", new MemoryValues(128l, 32 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Debian GNU/Linux 7(32-bit)", new MemoryValues(128l, 32 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Debian GNU/Linux 7(64-bit)", new MemoryValues(128l, 32 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.0 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.0 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.1 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.1 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.2 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.3 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.3 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.4 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.4 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.5 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.5 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.6 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.6 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.7 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.7 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.5 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.5 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.6 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.6 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.7 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.7 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer600GuestOsMemoryMap.put("CentOS 4.5 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("CentOS 4.6 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("CentOS 4.7 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("CentOS 4.8 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("CentOS 5.0 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("CentOS 5.0 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("CentOS 5.1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("CentOS 5.1 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("CentOS 5.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("CentOS 5.2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("CentOS 5.3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("CentOS 5.3 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("CentOS 5.4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("CentOS 5.4 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("CentOS 5.5 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("CentOS 5.5 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("CentOS 5.6 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("CentOS 5.6 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("CentOS 5.7 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("CentOS 5.7 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("CentOS 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer600GuestOsMemoryMap.put("CentOS 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer600GuestOsMemoryMap.put("CentOS 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer600GuestOsMemoryMap.put("CentOS 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer600GuestOsMemoryMap.put("CentOS 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("CentOS 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer600GuestOsMemoryMap.put("Debian GNU/Linux 6(32-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer600GuestOsMemoryMap.put("Debian GNU/Linux 6(64-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer600GuestOsMemoryMap.put("Debian GNU/Linux 7(32-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer600GuestOsMemoryMap.put("Debian GNU/Linux 7(64-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.0 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.0 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.1 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.1 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.2 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.3 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.3 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.4 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.4 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.5 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.5 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.6 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.6 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.7 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 5.7 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("Oracle Enterprise Linux 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.5 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.5 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.6 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.6 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.7 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.7 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); //_xenServer600GuestOsMemoryMap.put("SUSE Linux Enterprise Server 9 SP4 (32-bit)", new MemoryValues(512l, 16*1024l));// ?? - _xenServer600GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer600GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer600GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer600GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP4 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer600GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer600GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 SP1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer600GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer600GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer600GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP4 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer600GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer600GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 SP1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); //_xenServer600GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 SP1 (64-bit)", new MemoryValues(512l, 128*1024l)); //? //_xenServer600GuestOsMemoryMap.put("Windows 7 (32-bit)", new MemoryValues(512l, 16*1024l)); //? //_xenServer600GuestOsMemoryMap.put("Windows 7 (64-bit)", new MemoryValues(512l, 16*1024l)); //? //_xenServer600GuestOsMemoryMap.put("Windows 8 (32-bit)", new MemoryValues(512l, 16*1024l)); //? //_xenServer600GuestOsMemoryMap.put("Windows 8 (64-bit)", new MemoryValues(512l, 16*1024l)); //? - // _xenServer600GuestOsMemoryMap.put("Windows Server 2003 (32-bit)", new MemoryValues(256l, 64*1024l)); + // XenServer600GuestOsMemoryMap.put("Windows Server 2003 (32-bit)", new MemoryValues(256l, 64*1024l)); //_xenServer600GuestOsMemoryMap.put("Windows Server 2003 (64-bit)", new MemoryValues(256l, 128*1024l)); //_xenServer600GuestOsMemoryMap.put("Windows Server 2003 PAE (32-bit)", new MemoryValues(512l, 16*1024l)); //_xenServer600GuestOsMemoryMap.put("Windows Server 2003 Enterprise Edition(32-bit)", new MemoryValues(512l, 16*1024l)); @@ -955,17 +955,17 @@ public class CitrixHelper { //_xenServer600GuestOsMemoryMap.put("Windows Server 2003 Standard Edition(64-bit)", new MemoryValues(512l, 16*1024l)); //_xenServer600GuestOsMemoryMap.put("Windows Server 2008 (32-bit)", new MemoryValues(512l, 16*1024l)); //_xenServer600GuestOsMemoryMap.put("Windows Server 2008 (64-bit)", new MemoryValues(512l, 16*1024l)); - _xenServer600GuestOsMemoryMap.put("Windows Server 2008 R2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Windows Server 2012 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Windows Server 8 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Windows Vista (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Windows XP SP3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Ubuntu 10.04 (32-bit)", new MemoryValues(128l, 512l)); - _xenServer600GuestOsMemoryMap.put("Ubuntu 10.04 (64-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer600GuestOsMemoryMap.put("Windows Server 2008 R2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("Windows Server 2012 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("Windows Server 8 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("Windows Vista (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("Windows XP SP3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer600GuestOsMemoryMap.put("Ubuntu 10.04 (32-bit)", new MemoryValues(128l, 512l)); + XenServer600GuestOsMemoryMap.put("Ubuntu 10.04 (64-bit)", new MemoryValues(128l, 32 * 1024l)); //_xenServer600GuestOsMemoryMap.put("Ubuntu 10.10 (32-bit)", new MemoryValues(512l, 16*1024l));//? //_xenServer600GuestOsMemoryMap.put("Ubuntu 10.10 (64-bit)", new MemoryValues(512l, 16*1024l)); //? - _xenServer600GuestOsMemoryMap.put("Ubuntu 12.04 (32-bit)", new MemoryValues(128l, 32 * 1024l)); - _xenServer600GuestOsMemoryMap.put("Ubuntu 12.04 (64-bit)", new MemoryValues(128l, 128 * 1024l)); + XenServer600GuestOsMemoryMap.put("Ubuntu 12.04 (32-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer600GuestOsMemoryMap.put("Ubuntu 12.04 (64-bit)", new MemoryValues(128l, 128 * 1024l)); //_xenServer600GuestOsMemoryMap.put("Other Linux (32-bit)", new MemoryValues(512l, 16*1024l)); //_xenServer600GuestOsMemoryMap.put("Other Linux (64-bit)", new MemoryValues(512l, 16*1024l)); //_xenServer600GuestOsMemoryMap.put("Other (32-bit)", new MemoryValues(512l, 16*1024l)); @@ -981,215 +981,215 @@ public class CitrixHelper { } static { - _xenServer602GuestOsMap.put("CentOS 4.5 (32-bit)", "CentOS 4.5 (32-bit)"); - _xenServer602GuestOsMap.put("CentOS 4.6 (32-bit)", "CentOS 4.6 (32-bit)"); - _xenServer602GuestOsMap.put("CentOS 4.7 (32-bit)", "CentOS 4.7 (32-bit)"); - _xenServer602GuestOsMap.put("CentOS 4.8 (32-bit)", "CentOS 4.8 (32-bit)"); - _xenServer602GuestOsMap.put("CentOS 5.0 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer602GuestOsMap.put("CentOS 5.0 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer602GuestOsMap.put("CentOS 5.1 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer602GuestOsMap.put("CentOS 5.1 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer602GuestOsMap.put("CentOS 5.2 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer602GuestOsMap.put("CentOS 5.2 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer602GuestOsMap.put("CentOS 5.3 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer602GuestOsMap.put("CentOS 5.3 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer602GuestOsMap.put("CentOS 5.4 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer602GuestOsMap.put("CentOS 5.4 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer602GuestOsMap.put("CentOS 5.5 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer602GuestOsMap.put("CentOS 5.5 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer602GuestOsMap.put("CentOS 5.6 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer602GuestOsMap.put("CentOS 5.6 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer602GuestOsMap.put("CentOS 5.7 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer602GuestOsMap.put("CentOS 5.7 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer602GuestOsMap.put("CentOS 6.0 (32-bit)", "CentOS 6.0 (32-bit)"); - _xenServer602GuestOsMap.put("CentOS 6.0 (64-bit)", "CentOS 6.0 (64-bit)"); - _xenServer602GuestOsMap.put("Debian GNU/Linux 5.0 (32-bit)", "Debian Lenny 5.0 (32-bit)"); - _xenServer602GuestOsMap.put("Debian GNU/Linux 6(32-bit)", "Debian Squeeze 6.0 (32-bit)"); - _xenServer602GuestOsMap.put("Debian GNU/Linux 6(64-bit)", "Debian Squeeze 6.0 (64-bit)"); - _xenServer602GuestOsMap.put("Debian GNU/Linux 7(32-bit)", "Debian Squeeze 6.0 (32-bit)"); // This is to support Debian 7.0 in XS 6.0.2 - _xenServer602GuestOsMap.put("Debian GNU/Linux 7(64-bit)", "Debian Squeeze 6.0 (64-bit)"); - _xenServer602GuestOsMap.put("Oracle Enterprise Linux 5.0 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer602GuestOsMap.put("Oracle Enterprise Linux 5.0 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer602GuestOsMap.put("Oracle Enterprise Linux 5.1 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer602GuestOsMap.put("Oracle Enterprise Linux 5.1 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer602GuestOsMap.put("Oracle Enterprise Linux 5.2 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer602GuestOsMap.put("Oracle Enterprise Linux 5.2 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer602GuestOsMap.put("Oracle Enterprise Linux 5.3 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer602GuestOsMap.put("Oracle Enterprise Linux 5.3 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer602GuestOsMap.put("Oracle Enterprise Linux 5.4 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer602GuestOsMap.put("Oracle Enterprise Linux 5.4 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer602GuestOsMap.put("Oracle Enterprise Linux 5.5 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer602GuestOsMap.put("Oracle Enterprise Linux 5.5 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer602GuestOsMap.put("Oracle Enterprise Linux 5.6 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer602GuestOsMap.put("Oracle Enterprise Linux 5.6 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer602GuestOsMap.put("Oracle Enterprise Linux 5.7 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer602GuestOsMap.put("Oracle Enterprise Linux 5.7 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer602GuestOsMap.put("Oracle Enterprise Linux 6.0 (32-bit)", "Oracle Enterprise Linux 6.0 (32-bit)"); - _xenServer602GuestOsMap.put("Oracle Enterprise Linux 6.0 (64-bit)", "Oracle Enterprise Linux 6.0 (64-bit)"); - _xenServer602GuestOsMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", "Red Hat Enterprise Linux 4.5 (32-bit)"); - _xenServer602GuestOsMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", "Red Hat Enterprise Linux 4.6 (32-bit)"); - _xenServer602GuestOsMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", "Red Hat Enterprise Linux 4.7 (32-bit)"); - _xenServer602GuestOsMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", "Red Hat Enterprise Linux 4.8 (32-bit)"); - _xenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.5 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.5 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.6 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.6 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.7 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.7 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer602GuestOsMap.put("Red Hat Enterprise Linux 6.0 (32-bit)", "Red Hat Enterprise Linux 6.0 (32-bit)"); - _xenServer602GuestOsMap.put("Red Hat Enterprise Linux 6.0 (64-bit)", "Red Hat Enterprise Linux 6.0 (64-bit)"); - _xenServer602GuestOsMap.put("SUSE Linux Enterprise Server 9 SP4 (32-bit)", "SUSE Linux Enterprise Server 10 SP1 (32-bit)"); - _xenServer602GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", "SUSE Linux Enterprise Server 10 SP1 (32-bit)"); - _xenServer602GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", "SUSE Linux Enterprise Server 10 SP1 (64-bit)"); - _xenServer602GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", "SUSE Linux Enterprise Server 10 SP2 (32-bit)"); - _xenServer602GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", "SUSE Linux Enterprise Server 10 SP2 (64-bit)"); - _xenServer602GuestOsMap.put("SUSE Linux Enterprise Server 10 SP3 (32-bit)", "SUSE Linux Enterprise Server 10 SP3 (32-bit)"); - _xenServer602GuestOsMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", "SUSE Linux Enterprise Server 10 SP3 (64-bit)"); - _xenServer602GuestOsMap.put("SUSE Linux Enterprise Server 10 SP4 (32-bit)", "SUSE Linux Enterprise Server 10 SP4 (32-bit)"); - _xenServer602GuestOsMap.put("SUSE Linux Enterprise Server 10 SP4 (64-bit)", "SUSE Linux Enterprise Server 10 SP4 (64-bit)"); - _xenServer602GuestOsMap.put("SUSE Linux Enterprise Server 11 (32-bit)", "SUSE Linux Enterprise Server 11 (32-bit)"); - _xenServer602GuestOsMap.put("SUSE Linux Enterprise Server 11 (64-bit)", "SUSE Linux Enterprise Server 11 (64-bit)"); - _xenServer602GuestOsMap.put("SUSE Linux Enterprise Server 11 SP1 (32-bit)", "SUSE Linux Enterprise Server 11 SP1 (32-bit)"); - _xenServer602GuestOsMap.put("SUSE Linux Enterprise Server 11 SP1 (64-bit)", "SUSE Linux Enterprise Server 11 SP1 (64-bit)"); - _xenServer602GuestOsMap.put("Windows 7 (32-bit)", "Windows 7 (32-bit)"); - _xenServer602GuestOsMap.put("Windows 7 (64-bit)", "Windows 7 (64-bit)"); - _xenServer602GuestOsMap.put("Windows 8 (32-bit)", "Windows 8 (32-bit) (experimental)"); - _xenServer602GuestOsMap.put("Windows 8 (64-bit)", "Windows 8 (64-bit) (experimental)"); - _xenServer602GuestOsMap.put("Windows Server 2003 (32-bit)", "Windows Server 2003 (32-bit)"); - _xenServer602GuestOsMap.put("Windows Server 2003 (64-bit)", "Windows Server 2003 (64-bit)"); - _xenServer602GuestOsMap.put("Windows Server 2003 PAE (32-bit)", "Windows Server 2003 PAE (32-bit)"); - _xenServer602GuestOsMap.put("Windows Server 2003 Enterprise Edition(32-bit)", "Windows Server 2003 (32-bit)"); - _xenServer602GuestOsMap.put("Windows Server 2003 Enterprise Edition(64-bit)", "Windows Server 2003 (64-bit)"); - _xenServer602GuestOsMap.put("Windows Server 2003 DataCenter Edition(32-bit)", "Windows Server 2003 (32-bit)"); - _xenServer602GuestOsMap.put("Windows Server 2003 DataCenter Edition(64-bit)", "Windows Server 2003 (64-bit)"); - _xenServer602GuestOsMap.put("Windows Server 2003 Standard Edition(32-bit)", "Windows Server 2003 (32-bit)"); - _xenServer602GuestOsMap.put("Windows Server 2003 Standard Edition(64-bit)", "Windows Server 2003 (64-bit)"); - _xenServer602GuestOsMap.put("Windows Server 2008 (32-bit)", "Windows Server 2008 (32-bit)"); - _xenServer602GuestOsMap.put("Windows Server 2008 (64-bit)", "Windows Server 2008 (64-bit)"); - _xenServer602GuestOsMap.put("Windows Server 2008 R2 (64-bit)", "Windows Server 2008 R2 (64-bit)"); - _xenServer602GuestOsMap.put("Windows Server 8 (64-bit)", "Windows Server 8 (64-bit) (experimental)"); - _xenServer602GuestOsMap.put("Windows Vista (32-bit)", "Windows Vista (32-bit)"); - _xenServer602GuestOsMap.put("Windows XP SP3 (32-bit)", "Windows XP SP3 (32-bit)"); - _xenServer602GuestOsMap.put("Ubuntu 10.04 (32-bit)", "Ubuntu Lucid Lynx 10.04 (32-bit)"); - _xenServer602GuestOsMap.put("Ubuntu 10.04 (64-bit)", "Ubuntu Lucid Lynx 10.04 (64-bit)"); - _xenServer602GuestOsMap.put("Ubuntu 10.10 (32-bit)", "Ubuntu Maverick Meerkat 10.10 (32-bit) (experimental)"); - _xenServer602GuestOsMap.put("Ubuntu 10.10 (64-bit)", "Ubuntu Maverick Meerkat 10.10 (64-bit) (experimental)"); - _xenServer602GuestOsMap.put("Other Linux (32-bit)", "Other install media"); - _xenServer602GuestOsMap.put("Other Linux (64-bit)", "Other install media"); - _xenServer602GuestOsMap.put("Other (32-bit)", "Other install media"); - _xenServer602GuestOsMap.put("Other (64-bit)", "Other install media"); - _xenServer602GuestOsMap.put("Other CentOS (32-bit)", "Other install media"); - _xenServer602GuestOsMap.put("Other CentOS (64-bit)", "Other install media"); - _xenServer602GuestOsMap.put("Other Ubuntu (32-bit)", "Other install media"); - _xenServer602GuestOsMap.put("Other Ubuntu (64-bit)", "Other install media"); - _xenServer602GuestOsMap.put("Other SUSE Linux(32-bit)", "Other install media"); - _xenServer602GuestOsMap.put("Other SUSE Linux(64-bit)", "Other install media"); - _xenServer602GuestOsMap.put("Other PV (32-bit)", "CentOS 5 (32-bit)"); - _xenServer602GuestOsMap.put("Other PV (64-bit)", "CentOS 5 (64-bit)"); + XenServer602GuestOsMap.put("CentOS 4.5 (32-bit)", "CentOS 4.5 (32-bit)"); + XenServer602GuestOsMap.put("CentOS 4.6 (32-bit)", "CentOS 4.6 (32-bit)"); + XenServer602GuestOsMap.put("CentOS 4.7 (32-bit)", "CentOS 4.7 (32-bit)"); + XenServer602GuestOsMap.put("CentOS 4.8 (32-bit)", "CentOS 4.8 (32-bit)"); + XenServer602GuestOsMap.put("CentOS 5.0 (32-bit)", "CentOS 5 (32-bit)"); + XenServer602GuestOsMap.put("CentOS 5.0 (64-bit)", "CentOS 5 (64-bit)"); + XenServer602GuestOsMap.put("CentOS 5.1 (32-bit)", "CentOS 5 (32-bit)"); + XenServer602GuestOsMap.put("CentOS 5.1 (64-bit)", "CentOS 5 (64-bit)"); + XenServer602GuestOsMap.put("CentOS 5.2 (32-bit)", "CentOS 5 (32-bit)"); + XenServer602GuestOsMap.put("CentOS 5.2 (64-bit)", "CentOS 5 (64-bit)"); + XenServer602GuestOsMap.put("CentOS 5.3 (32-bit)", "CentOS 5 (32-bit)"); + XenServer602GuestOsMap.put("CentOS 5.3 (64-bit)", "CentOS 5 (64-bit)"); + XenServer602GuestOsMap.put("CentOS 5.4 (32-bit)", "CentOS 5 (32-bit)"); + XenServer602GuestOsMap.put("CentOS 5.4 (64-bit)", "CentOS 5 (64-bit)"); + XenServer602GuestOsMap.put("CentOS 5.5 (32-bit)", "CentOS 5 (32-bit)"); + XenServer602GuestOsMap.put("CentOS 5.5 (64-bit)", "CentOS 5 (64-bit)"); + XenServer602GuestOsMap.put("CentOS 5.6 (32-bit)", "CentOS 5 (32-bit)"); + XenServer602GuestOsMap.put("CentOS 5.6 (64-bit)", "CentOS 5 (64-bit)"); + XenServer602GuestOsMap.put("CentOS 5.7 (32-bit)", "CentOS 5 (32-bit)"); + XenServer602GuestOsMap.put("CentOS 5.7 (64-bit)", "CentOS 5 (64-bit)"); + XenServer602GuestOsMap.put("CentOS 6.0 (32-bit)", "CentOS 6.0 (32-bit)"); + XenServer602GuestOsMap.put("CentOS 6.0 (64-bit)", "CentOS 6.0 (64-bit)"); + XenServer602GuestOsMap.put("Debian GNU/Linux 5.0 (32-bit)", "Debian Lenny 5.0 (32-bit)"); + XenServer602GuestOsMap.put("Debian GNU/Linux 6(32-bit)", "Debian Squeeze 6.0 (32-bit)"); + XenServer602GuestOsMap.put("Debian GNU/Linux 6(64-bit)", "Debian Squeeze 6.0 (64-bit)"); + XenServer602GuestOsMap.put("Debian GNU/Linux 7(32-bit)", "Debian Squeeze 6.0 (32-bit)"); // This is to support Debian 7.0 in XS 6.0.2 + XenServer602GuestOsMap.put("Debian GNU/Linux 7(64-bit)", "Debian Squeeze 6.0 (64-bit)"); + XenServer602GuestOsMap.put("Oracle Enterprise Linux 5.0 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer602GuestOsMap.put("Oracle Enterprise Linux 5.0 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer602GuestOsMap.put("Oracle Enterprise Linux 5.1 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer602GuestOsMap.put("Oracle Enterprise Linux 5.1 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer602GuestOsMap.put("Oracle Enterprise Linux 5.2 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer602GuestOsMap.put("Oracle Enterprise Linux 5.2 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer602GuestOsMap.put("Oracle Enterprise Linux 5.3 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer602GuestOsMap.put("Oracle Enterprise Linux 5.3 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer602GuestOsMap.put("Oracle Enterprise Linux 5.4 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer602GuestOsMap.put("Oracle Enterprise Linux 5.4 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer602GuestOsMap.put("Oracle Enterprise Linux 5.5 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer602GuestOsMap.put("Oracle Enterprise Linux 5.5 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer602GuestOsMap.put("Oracle Enterprise Linux 5.6 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer602GuestOsMap.put("Oracle Enterprise Linux 5.6 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer602GuestOsMap.put("Oracle Enterprise Linux 5.7 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer602GuestOsMap.put("Oracle Enterprise Linux 5.7 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer602GuestOsMap.put("Oracle Enterprise Linux 6.0 (32-bit)", "Oracle Enterprise Linux 6.0 (32-bit)"); + XenServer602GuestOsMap.put("Oracle Enterprise Linux 6.0 (64-bit)", "Oracle Enterprise Linux 6.0 (64-bit)"); + XenServer602GuestOsMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", "Red Hat Enterprise Linux 4.5 (32-bit)"); + XenServer602GuestOsMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", "Red Hat Enterprise Linux 4.6 (32-bit)"); + XenServer602GuestOsMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", "Red Hat Enterprise Linux 4.7 (32-bit)"); + XenServer602GuestOsMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", "Red Hat Enterprise Linux 4.8 (32-bit)"); + XenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.5 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.5 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.6 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.6 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.7 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer602GuestOsMap.put("Red Hat Enterprise Linux 5.7 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer602GuestOsMap.put("Red Hat Enterprise Linux 6.0 (32-bit)", "Red Hat Enterprise Linux 6.0 (32-bit)"); + XenServer602GuestOsMap.put("Red Hat Enterprise Linux 6.0 (64-bit)", "Red Hat Enterprise Linux 6.0 (64-bit)"); + XenServer602GuestOsMap.put("SUSE Linux Enterprise Server 9 SP4 (32-bit)", "SUSE Linux Enterprise Server 10 SP1 (32-bit)"); + XenServer602GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", "SUSE Linux Enterprise Server 10 SP1 (32-bit)"); + XenServer602GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", "SUSE Linux Enterprise Server 10 SP1 (64-bit)"); + XenServer602GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", "SUSE Linux Enterprise Server 10 SP2 (32-bit)"); + XenServer602GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", "SUSE Linux Enterprise Server 10 SP2 (64-bit)"); + XenServer602GuestOsMap.put("SUSE Linux Enterprise Server 10 SP3 (32-bit)", "SUSE Linux Enterprise Server 10 SP3 (32-bit)"); + XenServer602GuestOsMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", "SUSE Linux Enterprise Server 10 SP3 (64-bit)"); + XenServer602GuestOsMap.put("SUSE Linux Enterprise Server 10 SP4 (32-bit)", "SUSE Linux Enterprise Server 10 SP4 (32-bit)"); + XenServer602GuestOsMap.put("SUSE Linux Enterprise Server 10 SP4 (64-bit)", "SUSE Linux Enterprise Server 10 SP4 (64-bit)"); + XenServer602GuestOsMap.put("SUSE Linux Enterprise Server 11 (32-bit)", "SUSE Linux Enterprise Server 11 (32-bit)"); + XenServer602GuestOsMap.put("SUSE Linux Enterprise Server 11 (64-bit)", "SUSE Linux Enterprise Server 11 (64-bit)"); + XenServer602GuestOsMap.put("SUSE Linux Enterprise Server 11 SP1 (32-bit)", "SUSE Linux Enterprise Server 11 SP1 (32-bit)"); + XenServer602GuestOsMap.put("SUSE Linux Enterprise Server 11 SP1 (64-bit)", "SUSE Linux Enterprise Server 11 SP1 (64-bit)"); + XenServer602GuestOsMap.put("Windows 7 (32-bit)", "Windows 7 (32-bit)"); + XenServer602GuestOsMap.put("Windows 7 (64-bit)", "Windows 7 (64-bit)"); + XenServer602GuestOsMap.put("Windows 8 (32-bit)", "Windows 8 (32-bit) (experimental)"); + XenServer602GuestOsMap.put("Windows 8 (64-bit)", "Windows 8 (64-bit) (experimental)"); + XenServer602GuestOsMap.put("Windows Server 2003 (32-bit)", "Windows Server 2003 (32-bit)"); + XenServer602GuestOsMap.put("Windows Server 2003 (64-bit)", "Windows Server 2003 (64-bit)"); + XenServer602GuestOsMap.put("Windows Server 2003 PAE (32-bit)", "Windows Server 2003 PAE (32-bit)"); + XenServer602GuestOsMap.put("Windows Server 2003 Enterprise Edition(32-bit)", "Windows Server 2003 (32-bit)"); + XenServer602GuestOsMap.put("Windows Server 2003 Enterprise Edition(64-bit)", "Windows Server 2003 (64-bit)"); + XenServer602GuestOsMap.put("Windows Server 2003 DataCenter Edition(32-bit)", "Windows Server 2003 (32-bit)"); + XenServer602GuestOsMap.put("Windows Server 2003 DataCenter Edition(64-bit)", "Windows Server 2003 (64-bit)"); + XenServer602GuestOsMap.put("Windows Server 2003 Standard Edition(32-bit)", "Windows Server 2003 (32-bit)"); + XenServer602GuestOsMap.put("Windows Server 2003 Standard Edition(64-bit)", "Windows Server 2003 (64-bit)"); + XenServer602GuestOsMap.put("Windows Server 2008 (32-bit)", "Windows Server 2008 (32-bit)"); + XenServer602GuestOsMap.put("Windows Server 2008 (64-bit)", "Windows Server 2008 (64-bit)"); + XenServer602GuestOsMap.put("Windows Server 2008 R2 (64-bit)", "Windows Server 2008 R2 (64-bit)"); + XenServer602GuestOsMap.put("Windows Server 8 (64-bit)", "Windows Server 8 (64-bit) (experimental)"); + XenServer602GuestOsMap.put("Windows Vista (32-bit)", "Windows Vista (32-bit)"); + XenServer602GuestOsMap.put("Windows XP SP3 (32-bit)", "Windows XP SP3 (32-bit)"); + XenServer602GuestOsMap.put("Ubuntu 10.04 (32-bit)", "Ubuntu Lucid Lynx 10.04 (32-bit)"); + XenServer602GuestOsMap.put("Ubuntu 10.04 (64-bit)", "Ubuntu Lucid Lynx 10.04 (64-bit)"); + XenServer602GuestOsMap.put("Ubuntu 10.10 (32-bit)", "Ubuntu Maverick Meerkat 10.10 (32-bit) (experimental)"); + XenServer602GuestOsMap.put("Ubuntu 10.10 (64-bit)", "Ubuntu Maverick Meerkat 10.10 (64-bit) (experimental)"); + XenServer602GuestOsMap.put("Other Linux (32-bit)", "Other install media"); + XenServer602GuestOsMap.put("Other Linux (64-bit)", "Other install media"); + XenServer602GuestOsMap.put("Other (32-bit)", "Other install media"); + XenServer602GuestOsMap.put("Other (64-bit)", "Other install media"); + XenServer602GuestOsMap.put("Other CentOS (32-bit)", "Other install media"); + XenServer602GuestOsMap.put("Other CentOS (64-bit)", "Other install media"); + XenServer602GuestOsMap.put("Other Ubuntu (32-bit)", "Other install media"); + XenServer602GuestOsMap.put("Other Ubuntu (64-bit)", "Other install media"); + XenServer602GuestOsMap.put("Other SUSE Linux(32-bit)", "Other install media"); + XenServer602GuestOsMap.put("Other SUSE Linux(64-bit)", "Other install media"); + XenServer602GuestOsMap.put("Other PV (32-bit)", "CentOS 5 (32-bit)"); + XenServer602GuestOsMap.put("Other PV (64-bit)", "CentOS 5 (64-bit)"); } static { - _xenServer602GuestOsMemoryMap.put("CentOS 4.5 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("CentOS 4.6 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("CentOS 4.7 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("CentOS 4.8 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("CentOS 5.0 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("CentOS 5.0 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("CentOS 5.1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("CentOS 5.1 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("CentOS 5.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("CentOS 5.2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("CentOS 5.3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("CentOS 5.3 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("CentOS 5.4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("CentOS 5.4 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("CentOS 5.5 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("CentOS 5.5 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("CentOS 5.6 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("CentOS 5.6 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("CentOS 5.7 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("CentOS 5.7 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("CentOS 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer602GuestOsMemoryMap.put("CentOS 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer602GuestOsMemoryMap.put("CentOS 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer602GuestOsMemoryMap.put("CentOS 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer602GuestOsMemoryMap.put("CentOS 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("CentOS 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Debian GNU/Linux 5.0 (32-bit)", new MemoryValues(128l, 32 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Debian GNU/Linux 6(32-bit)", new MemoryValues(128l, 32 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Debian GNU/Linux 6(64-bit)", new MemoryValues(128l, 32 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Debian GNU/Linux 7(32-bit)", new MemoryValues(128l, 32 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Debian GNU/Linux 7(64-bit)", new MemoryValues(128l, 32 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.0 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.0 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.1 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.1 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.2 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.3 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.3 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.4 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.4 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.5 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.5 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.6 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.6 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.7 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.7 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.5 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.5 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.6 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.6 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.7 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.7 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - // _xenServer602GuestOsMemoryMap.put("SUSE Linux Enterprise Server 9 SP4 (32-bit)", new MemoryValues(512l, 16*1024l));// ?? - _xenServer602GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer602GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer602GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer602GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP4 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer602GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer602GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 SP1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("CentOS 4.5 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("CentOS 4.6 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("CentOS 4.7 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("CentOS 4.8 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("CentOS 5.0 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("CentOS 5.0 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("CentOS 5.1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("CentOS 5.1 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("CentOS 5.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("CentOS 5.2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("CentOS 5.3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("CentOS 5.3 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("CentOS 5.4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("CentOS 5.4 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("CentOS 5.5 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("CentOS 5.5 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("CentOS 5.6 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("CentOS 5.6 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("CentOS 5.7 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("CentOS 5.7 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("CentOS 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer602GuestOsMemoryMap.put("CentOS 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer602GuestOsMemoryMap.put("CentOS 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer602GuestOsMemoryMap.put("CentOS 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer602GuestOsMemoryMap.put("CentOS 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("CentOS 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer602GuestOsMemoryMap.put("Debian GNU/Linux 5.0 (32-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer602GuestOsMemoryMap.put("Debian GNU/Linux 6(32-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer602GuestOsMemoryMap.put("Debian GNU/Linux 6(64-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer602GuestOsMemoryMap.put("Debian GNU/Linux 7(32-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer602GuestOsMemoryMap.put("Debian GNU/Linux 7(64-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.0 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.0 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.1 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.1 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.2 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.3 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.3 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.4 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.4 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.5 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.5 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.6 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.6 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.7 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 5.7 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("Oracle Enterprise Linux 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.5 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.5 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.6 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.6 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.7 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.7 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + // XenServer602GuestOsMemoryMap.put("SUSE Linux Enterprise Server 9 SP4 (32-bit)", new MemoryValues(512l, 16*1024l));// ?? + XenServer602GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer602GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer602GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer602GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP4 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer602GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer602GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 SP1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); //_xenServer602GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 SP1 (64-bit)", new MemoryValues(512l, 128*1024l)); //? //_xenServer602GuestOsMemoryMap.put("Windows 7 (32-bit)", new MemoryValues(512l, 16*1024l)); //? //_xenServer602GuestOsMemoryMap.put("Windows 7 (64-bit)", new MemoryValues(512l, 16*1024l)); //? @@ -1206,326 +1206,326 @@ public class CitrixHelper { //_xenServer602GuestOsMemoryMap.put("Windows Server 2003 Standard Edition(64-bit)", new MemoryValues(512l, 16*1024l)); //_xenServer602GuestOsMemoryMap.put("Windows Server 2008 (32-bit)", new MemoryValues(512l, 16*1024l)); //_xenServer602GuestOsMemoryMap.put("Windows Server 2008 (64-bit)", new MemoryValues(512l, 16*1024l)); - _xenServer602GuestOsMemoryMap.put("Windows Server 2008 R2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Windows Server 2012 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Windows Server 8 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Windows Vista (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Windows XP SP3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Ubuntu 10.04 (32-bit)", new MemoryValues(128l, 512l)); - _xenServer602GuestOsMemoryMap.put("Ubuntu 10.04 (64-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer602GuestOsMemoryMap.put("Windows Server 2008 R2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("Windows Server 2012 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("Windows Server 8 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("Windows Vista (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("Windows XP SP3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer602GuestOsMemoryMap.put("Ubuntu 10.04 (32-bit)", new MemoryValues(128l, 512l)); + XenServer602GuestOsMemoryMap.put("Ubuntu 10.04 (64-bit)", new MemoryValues(128l, 32 * 1024l)); //_xenServer602GuestOsMemoryMap.put("Ubuntu 10.10 (32-bit)", new MemoryValues(512l, 16*1024l));//? //_xenServer602GuestOsMemoryMap.put("Ubuntu 10.10 (64-bit)", new MemoryValues(512l, 16*1024l)); //? - _xenServer602GuestOsMemoryMap.put("Ubuntu 12.04 (32-bit)", new MemoryValues(128l, 32 * 1024l)); - _xenServer602GuestOsMemoryMap.put("Ubuntu 12.04 (64-bit)", new MemoryValues(128l, 128 * 1024l)); - // _xenServer602GuestOsMemoryMap.put("Other Linux (32-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer602GuestOsMemoryMap.put("Other Linux (64-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer602GuestOsMemoryMap.put("Other (32-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer602GuestOsMemoryMap.put("Other (64-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer602GuestOsMemoryMap.put("Other CentOS (32-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer602GuestOsMemoryMap.put("Other CentOS (64-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer602GuestOsMemoryMap.put("Other Ubuntu (32-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer602GuestOsMemoryMap.put("Other Ubuntu (64-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer602GuestOsMemoryMap.put("Other SUSE Linux(32-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer602GuestOsMemoryMap.put("Other SUSE Linux(64-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer602GuestOsMemoryMap.put("Other PV (32-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer602GuestOsMemoryMap.put("Other PV (64-bit)", new MemoryValues(512l, 16*1024l)); + XenServer602GuestOsMemoryMap.put("Ubuntu 12.04 (32-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer602GuestOsMemoryMap.put("Ubuntu 12.04 (64-bit)", new MemoryValues(128l, 128 * 1024l)); + // XenServer602GuestOsMemoryMap.put("Other Linux (32-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer602GuestOsMemoryMap.put("Other Linux (64-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer602GuestOsMemoryMap.put("Other (32-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer602GuestOsMemoryMap.put("Other (64-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer602GuestOsMemoryMap.put("Other CentOS (32-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer602GuestOsMemoryMap.put("Other CentOS (64-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer602GuestOsMemoryMap.put("Other Ubuntu (32-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer602GuestOsMemoryMap.put("Other Ubuntu (64-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer602GuestOsMemoryMap.put("Other SUSE Linux(32-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer602GuestOsMemoryMap.put("Other SUSE Linux(64-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer602GuestOsMemoryMap.put("Other PV (32-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer602GuestOsMemoryMap.put("Other PV (64-bit)", new MemoryValues(512l, 16*1024l)); } static { - _xenServer610GuestOsMap.put("CentOS 4.5 (32-bit)", "CentOS 4.5 (32-bit)"); - _xenServer610GuestOsMap.put("CentOS 4.6 (32-bit)", "CentOS 4.6 (32-bit)"); - _xenServer610GuestOsMap.put("CentOS 4.7 (32-bit)", "CentOS 4.7 (32-bit)"); - _xenServer610GuestOsMap.put("CentOS 4.8 (32-bit)", "CentOS 4.8 (32-bit)"); - _xenServer610GuestOsMap.put("CentOS 5.0 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer610GuestOsMap.put("CentOS 5.0 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer610GuestOsMap.put("CentOS 5.1 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer610GuestOsMap.put("CentOS 5.1 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer610GuestOsMap.put("CentOS 5.2 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer610GuestOsMap.put("CentOS 5.2 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer610GuestOsMap.put("CentOS 5.3 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer610GuestOsMap.put("CentOS 5.3 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer610GuestOsMap.put("CentOS 5.4 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer610GuestOsMap.put("CentOS 5.4 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer610GuestOsMap.put("CentOS 5.5 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer610GuestOsMap.put("CentOS 5.5 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer610GuestOsMap.put("CentOS 5.6 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer610GuestOsMap.put("CentOS 5.6 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer610GuestOsMap.put("CentOS 5.7 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer610GuestOsMap.put("CentOS 5.7 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer610GuestOsMap.put("CentOS 6.0 (32-bit)", "CentOS 6 (32-bit)"); - _xenServer610GuestOsMap.put("CentOS 6.0 (64-bit)", "CentOS 6 (64-bit)"); - _xenServer610GuestOsMap.put("CentOS 6.1 (32-bit)", "CentOS 6 (32-bit)"); - _xenServer610GuestOsMap.put("CentOS 6.1 (64-bit)", "CentOS 6 (64-bit)"); - _xenServer610GuestOsMap.put("CentOS 6.2 (32-bit)", "CentOS 6 (32-bit)"); - _xenServer610GuestOsMap.put("CentOS 6.2 (64-bit)", "CentOS 6 (64-bit)"); - _xenServer610GuestOsMap.put("CentOS 6.3 (32-bit)", "CentOS 6 (32-bit)"); - _xenServer610GuestOsMap.put("CentOS 6.3 (64-bit)", "CentOS 6 (64-bit)"); - _xenServer610GuestOsMap.put("Debian GNU/Linux 6(32-bit)", "Debian Squeeze 6.0 (32-bit)"); - _xenServer610GuestOsMap.put("Debian GNU/Linux 6(64-bit)", "Debian Squeeze 6.0 (64-bit)"); - _xenServer610GuestOsMap.put("Debian GNU/Linux 7(32-bit)", "Debian Squeeze 6.0 (32-bit)"); // This is to support Debian 7.0 in XS 6.1 - _xenServer610GuestOsMap.put("Debian GNU/Linux 7(64-bit)", "Debian Squeeze 6.0 (64-bit)"); - _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.0 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.0 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.1 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.1 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.2 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.2 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.3 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.3 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.4 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.4 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.5 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.5 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.6 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.6 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.7 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.7 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer610GuestOsMap.put("Oracle Enterprise Linux 6.0 (32-bit)", "Oracle Enterprise Linux 6 (32-bit)"); - _xenServer610GuestOsMap.put("Oracle Enterprise Linux 6.0 (64-bit)", "Oracle Enterprise Linux 6 (64-bit)"); - _xenServer610GuestOsMap.put("Oracle Enterprise Linux 6.1 (32-bit)", "Oracle Enterprise Linux 6 (32-bit)"); - _xenServer610GuestOsMap.put("Oracle Enterprise Linux 6.1 (64-bit)", "Oracle Enterprise Linux 6 (64-bit)"); - _xenServer610GuestOsMap.put("Oracle Enterprise Linux 6.2 (32-bit)", "Oracle Enterprise Linux 6 (32-bit)"); - _xenServer610GuestOsMap.put("Oracle Enterprise Linux 6.2 (64-bit)", "Oracle Enterprise Linux 6 (64-bit)"); - _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", "Red Hat Enterprise Linux 4.5 (32-bit)"); - _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", "Red Hat Enterprise Linux 4.6 (32-bit)"); - _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", "Red Hat Enterprise Linux 4.7 (32-bit)"); - _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", "Red Hat Enterprise Linux 4.8 (32-bit)"); - _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.5 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.5 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.6 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.6 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.7 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.7 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 6.0 (32-bit)", "Red Hat Enterprise Linux 6 (32-bit)"); - _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 6.0 (64-bit)", "Red Hat Enterprise Linux 6 (64-bit)"); - _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 6.1 (32-bit)", "Red Hat Enterprise Linux 6 (32-bit)"); - _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 6.1 (64-bit)", "Red Hat Enterprise Linux 6 (64-bit)"); - _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 6.2 (32-bit)", "Red Hat Enterprise Linux 6 (32-bit)"); - _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 6.2 (64-bit)", "Red Hat Enterprise Linux 6 (64-bit)"); - _xenServer610GuestOsMap.put("SUSE Linux Enterprise Server 9 SP4 (32-bit)", "SUSE Linux Enterprise Server 10 SP1 (32-bit)"); - _xenServer610GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", "SUSE Linux Enterprise Server 10 SP1 (32-bit)"); - _xenServer610GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", "SUSE Linux Enterprise Server 10 SP1 (64-bit)"); - _xenServer610GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", "SUSE Linux Enterprise Server 10 SP2 (32-bit)"); - _xenServer610GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", "SUSE Linux Enterprise Server 10 SP2 (64-bit)"); - _xenServer610GuestOsMap.put("SUSE Linux Enterprise Server 10 SP3 (32-bit)", "SUSE Linux Enterprise Server 10 SP3 (32-bit)"); - _xenServer610GuestOsMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", "SUSE Linux Enterprise Server 10 SP3 (64-bit)"); - _xenServer610GuestOsMap.put("SUSE Linux Enterprise Server 10 SP4 (32-bit)", "SUSE Linux Enterprise Server 10 SP4 (32-bit)"); - _xenServer610GuestOsMap.put("SUSE Linux Enterprise Server 10 SP4 (64-bit)", "SUSE Linux Enterprise Server 10 SP4 (64-bit)"); - _xenServer610GuestOsMap.put("SUSE Linux Enterprise Server 11 (32-bit)", "SUSE Linux Enterprise Server 11 (32-bit)"); - _xenServer610GuestOsMap.put("SUSE Linux Enterprise Server 11 (64-bit)", "SUSE Linux Enterprise Server 11 (64-bit)"); - _xenServer610GuestOsMap.put("SUSE Linux Enterprise Server 11 SP1 (32-bit)", "SUSE Linux Enterprise Server 11 SP1 (32-bit)"); - _xenServer610GuestOsMap.put("SUSE Linux Enterprise Server 11 SP1 (64-bit)", "SUSE Linux Enterprise Server 11 SP1 (64-bit)"); - _xenServer610GuestOsMap.put("Windows 7 (32-bit)", "Windows 7 (32-bit)"); - _xenServer610GuestOsMap.put("Windows 7 (64-bit)", "Windows 7 (64-bit)"); - _xenServer610GuestOsMap.put("Windows 8 (32-bit)", "Windows 8 (32-bit) (experimental)"); - _xenServer610GuestOsMap.put("Windows 8 (64-bit)", "Windows 8 (64-bit) (experimental)"); - _xenServer610GuestOsMap.put("Windows Server 2003 (32-bit)", "Windows Server 2003 (32-bit)"); - _xenServer610GuestOsMap.put("Windows Server 2003 (64-bit)", "Windows Server 2003 (64-bit)"); - _xenServer610GuestOsMap.put("Windows Server 2003 PAE (32-bit)", "Windows Server 2003 PAE (32-bit)"); - _xenServer610GuestOsMap.put("Windows Server 2003 Enterprise Edition(32-bit)", "Windows Server 2003 (32-bit)"); - _xenServer610GuestOsMap.put("Windows Server 2003 Enterprise Edition(64-bit)", "Windows Server 2003 (64-bit)"); - _xenServer610GuestOsMap.put("Windows Server 2003 DataCenter Edition(32-bit)", "Windows Server 2003 (32-bit)"); - _xenServer610GuestOsMap.put("Windows Server 2003 DataCenter Edition(64-bit)", "Windows Server 2003 (64-bit)"); - _xenServer610GuestOsMap.put("Windows Server 2003 Standard Edition(32-bit)", "Windows Server 2003 (32-bit)"); - _xenServer610GuestOsMap.put("Windows Server 2003 Standard Edition(64-bit)", "Windows Server 2003 (64-bit)"); - _xenServer610GuestOsMap.put("Windows Server 2008 (32-bit)", "Windows Server 2008 (32-bit)"); - _xenServer610GuestOsMap.put("Windows Server 2008 (64-bit)", "Windows Server 2008 (64-bit)"); - _xenServer610GuestOsMap.put("Windows Server 2008 R2 (64-bit)", "Windows Server 2008 R2 (64-bit)"); - _xenServer610GuestOsMap.put("Windows Server 2012 (64-bit)", "Windows Server 2012 (64-bit) (experimental)"); - _xenServer610GuestOsMap.put("Windows Server 8 (64-bit)", "Windows Server 2012 (64-bit) (experimental)"); - _xenServer610GuestOsMap.put("Windows Vista (32-bit)", "Windows Vista (32-bit)"); - _xenServer610GuestOsMap.put("Windows XP SP3 (32-bit)", "Windows XP SP3 (32-bit)"); - _xenServer610GuestOsMap.put("Ubuntu 10.04 (32-bit)", "Ubuntu Lucid Lynx 10.04 (32-bit)"); - _xenServer610GuestOsMap.put("Ubuntu 10.04 (64-bit)", "Ubuntu Lucid Lynx 10.04 (64-bit)"); - _xenServer610GuestOsMap.put("Ubuntu 10.10 (32-bit)", "Ubuntu Maverick Meerkat 10.10 (32-bit) (experimental)"); - _xenServer610GuestOsMap.put("Ubuntu 10.10 (64-bit)", "Ubuntu Maverick Meerkat 10.10 (64-bit) (experimental)"); - _xenServer610GuestOsMap.put("Ubuntu 12.04 (32-bit)", "Ubuntu Precise Pangolin 12.04 (32-bit)"); - _xenServer610GuestOsMap.put("Ubuntu 12.04 (64-bit)", "Ubuntu Precise Pangolin 12.04 (64-bit)"); - _xenServer610GuestOsMap.put("Ubuntu 11.04 (32-bit)", "Other install media"); - _xenServer610GuestOsMap.put("Ubuntu 11.04 (64-bit)", "Other install media"); - _xenServer610GuestOsMap.put("Other Linux (32-bit)", "Other install media"); - _xenServer610GuestOsMap.put("Other Linux (64-bit)", "Other install media"); - _xenServer610GuestOsMap.put("Other (32-bit)", "Other install media"); - _xenServer610GuestOsMap.put("Other (64-bit)", "Other install media"); - _xenServer610GuestOsMap.put("Other CentOS (32-bit)", "Other install media"); - _xenServer610GuestOsMap.put("Other CentOS (64-bit)", "Other install media"); - _xenServer610GuestOsMap.put("Other Ubuntu (32-bit)", "Other install media"); - _xenServer610GuestOsMap.put("Other Ubuntu (64-bit)", "Other install media"); - _xenServer610GuestOsMap.put("Other SUSE Linux(32-bit)", "Other install media"); - _xenServer610GuestOsMap.put("Other SUSE Linux(64-bit)", "Other install media"); - _xenServer610GuestOsMap.put("Other PV (32-bit)", "CentOS 5 (32-bit)"); - _xenServer610GuestOsMap.put("Other PV (64-bit)", "CentOS 5 (64-bit)"); + XenServer610GuestOsMap.put("CentOS 4.5 (32-bit)", "CentOS 4.5 (32-bit)"); + XenServer610GuestOsMap.put("CentOS 4.6 (32-bit)", "CentOS 4.6 (32-bit)"); + XenServer610GuestOsMap.put("CentOS 4.7 (32-bit)", "CentOS 4.7 (32-bit)"); + XenServer610GuestOsMap.put("CentOS 4.8 (32-bit)", "CentOS 4.8 (32-bit)"); + XenServer610GuestOsMap.put("CentOS 5.0 (32-bit)", "CentOS 5 (32-bit)"); + XenServer610GuestOsMap.put("CentOS 5.0 (64-bit)", "CentOS 5 (64-bit)"); + XenServer610GuestOsMap.put("CentOS 5.1 (32-bit)", "CentOS 5 (32-bit)"); + XenServer610GuestOsMap.put("CentOS 5.1 (64-bit)", "CentOS 5 (64-bit)"); + XenServer610GuestOsMap.put("CentOS 5.2 (32-bit)", "CentOS 5 (32-bit)"); + XenServer610GuestOsMap.put("CentOS 5.2 (64-bit)", "CentOS 5 (64-bit)"); + XenServer610GuestOsMap.put("CentOS 5.3 (32-bit)", "CentOS 5 (32-bit)"); + XenServer610GuestOsMap.put("CentOS 5.3 (64-bit)", "CentOS 5 (64-bit)"); + XenServer610GuestOsMap.put("CentOS 5.4 (32-bit)", "CentOS 5 (32-bit)"); + XenServer610GuestOsMap.put("CentOS 5.4 (64-bit)", "CentOS 5 (64-bit)"); + XenServer610GuestOsMap.put("CentOS 5.5 (32-bit)", "CentOS 5 (32-bit)"); + XenServer610GuestOsMap.put("CentOS 5.5 (64-bit)", "CentOS 5 (64-bit)"); + XenServer610GuestOsMap.put("CentOS 5.6 (32-bit)", "CentOS 5 (32-bit)"); + XenServer610GuestOsMap.put("CentOS 5.6 (64-bit)", "CentOS 5 (64-bit)"); + XenServer610GuestOsMap.put("CentOS 5.7 (32-bit)", "CentOS 5 (32-bit)"); + XenServer610GuestOsMap.put("CentOS 5.7 (64-bit)", "CentOS 5 (64-bit)"); + XenServer610GuestOsMap.put("CentOS 6.0 (32-bit)", "CentOS 6 (32-bit)"); + XenServer610GuestOsMap.put("CentOS 6.0 (64-bit)", "CentOS 6 (64-bit)"); + XenServer610GuestOsMap.put("CentOS 6.1 (32-bit)", "CentOS 6 (32-bit)"); + XenServer610GuestOsMap.put("CentOS 6.1 (64-bit)", "CentOS 6 (64-bit)"); + XenServer610GuestOsMap.put("CentOS 6.2 (32-bit)", "CentOS 6 (32-bit)"); + XenServer610GuestOsMap.put("CentOS 6.2 (64-bit)", "CentOS 6 (64-bit)"); + XenServer610GuestOsMap.put("CentOS 6.3 (32-bit)", "CentOS 6 (32-bit)"); + XenServer610GuestOsMap.put("CentOS 6.3 (64-bit)", "CentOS 6 (64-bit)"); + XenServer610GuestOsMap.put("Debian GNU/Linux 6(32-bit)", "Debian Squeeze 6.0 (32-bit)"); + XenServer610GuestOsMap.put("Debian GNU/Linux 6(64-bit)", "Debian Squeeze 6.0 (64-bit)"); + XenServer610GuestOsMap.put("Debian GNU/Linux 7(32-bit)", "Debian Squeeze 6.0 (32-bit)"); // This is to support Debian 7.0 in XS 6.1 + XenServer610GuestOsMap.put("Debian GNU/Linux 7(64-bit)", "Debian Squeeze 6.0 (64-bit)"); + XenServer610GuestOsMap.put("Oracle Enterprise Linux 5.0 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer610GuestOsMap.put("Oracle Enterprise Linux 5.0 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer610GuestOsMap.put("Oracle Enterprise Linux 5.1 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer610GuestOsMap.put("Oracle Enterprise Linux 5.1 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer610GuestOsMap.put("Oracle Enterprise Linux 5.2 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer610GuestOsMap.put("Oracle Enterprise Linux 5.2 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer610GuestOsMap.put("Oracle Enterprise Linux 5.3 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer610GuestOsMap.put("Oracle Enterprise Linux 5.3 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer610GuestOsMap.put("Oracle Enterprise Linux 5.4 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer610GuestOsMap.put("Oracle Enterprise Linux 5.4 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer610GuestOsMap.put("Oracle Enterprise Linux 5.5 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer610GuestOsMap.put("Oracle Enterprise Linux 5.5 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer610GuestOsMap.put("Oracle Enterprise Linux 5.6 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer610GuestOsMap.put("Oracle Enterprise Linux 5.6 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer610GuestOsMap.put("Oracle Enterprise Linux 5.7 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer610GuestOsMap.put("Oracle Enterprise Linux 5.7 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer610GuestOsMap.put("Oracle Enterprise Linux 6.0 (32-bit)", "Oracle Enterprise Linux 6 (32-bit)"); + XenServer610GuestOsMap.put("Oracle Enterprise Linux 6.0 (64-bit)", "Oracle Enterprise Linux 6 (64-bit)"); + XenServer610GuestOsMap.put("Oracle Enterprise Linux 6.1 (32-bit)", "Oracle Enterprise Linux 6 (32-bit)"); + XenServer610GuestOsMap.put("Oracle Enterprise Linux 6.1 (64-bit)", "Oracle Enterprise Linux 6 (64-bit)"); + XenServer610GuestOsMap.put("Oracle Enterprise Linux 6.2 (32-bit)", "Oracle Enterprise Linux 6 (32-bit)"); + XenServer610GuestOsMap.put("Oracle Enterprise Linux 6.2 (64-bit)", "Oracle Enterprise Linux 6 (64-bit)"); + XenServer610GuestOsMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", "Red Hat Enterprise Linux 4.5 (32-bit)"); + XenServer610GuestOsMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", "Red Hat Enterprise Linux 4.6 (32-bit)"); + XenServer610GuestOsMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", "Red Hat Enterprise Linux 4.7 (32-bit)"); + XenServer610GuestOsMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", "Red Hat Enterprise Linux 4.8 (32-bit)"); + XenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.5 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.5 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.6 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.6 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.7 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.7 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer610GuestOsMap.put("Red Hat Enterprise Linux 6.0 (32-bit)", "Red Hat Enterprise Linux 6 (32-bit)"); + XenServer610GuestOsMap.put("Red Hat Enterprise Linux 6.0 (64-bit)", "Red Hat Enterprise Linux 6 (64-bit)"); + XenServer610GuestOsMap.put("Red Hat Enterprise Linux 6.1 (32-bit)", "Red Hat Enterprise Linux 6 (32-bit)"); + XenServer610GuestOsMap.put("Red Hat Enterprise Linux 6.1 (64-bit)", "Red Hat Enterprise Linux 6 (64-bit)"); + XenServer610GuestOsMap.put("Red Hat Enterprise Linux 6.2 (32-bit)", "Red Hat Enterprise Linux 6 (32-bit)"); + XenServer610GuestOsMap.put("Red Hat Enterprise Linux 6.2 (64-bit)", "Red Hat Enterprise Linux 6 (64-bit)"); + XenServer610GuestOsMap.put("SUSE Linux Enterprise Server 9 SP4 (32-bit)", "SUSE Linux Enterprise Server 10 SP1 (32-bit)"); + XenServer610GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", "SUSE Linux Enterprise Server 10 SP1 (32-bit)"); + XenServer610GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", "SUSE Linux Enterprise Server 10 SP1 (64-bit)"); + XenServer610GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", "SUSE Linux Enterprise Server 10 SP2 (32-bit)"); + XenServer610GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", "SUSE Linux Enterprise Server 10 SP2 (64-bit)"); + XenServer610GuestOsMap.put("SUSE Linux Enterprise Server 10 SP3 (32-bit)", "SUSE Linux Enterprise Server 10 SP3 (32-bit)"); + XenServer610GuestOsMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", "SUSE Linux Enterprise Server 10 SP3 (64-bit)"); + XenServer610GuestOsMap.put("SUSE Linux Enterprise Server 10 SP4 (32-bit)", "SUSE Linux Enterprise Server 10 SP4 (32-bit)"); + XenServer610GuestOsMap.put("SUSE Linux Enterprise Server 10 SP4 (64-bit)", "SUSE Linux Enterprise Server 10 SP4 (64-bit)"); + XenServer610GuestOsMap.put("SUSE Linux Enterprise Server 11 (32-bit)", "SUSE Linux Enterprise Server 11 (32-bit)"); + XenServer610GuestOsMap.put("SUSE Linux Enterprise Server 11 (64-bit)", "SUSE Linux Enterprise Server 11 (64-bit)"); + XenServer610GuestOsMap.put("SUSE Linux Enterprise Server 11 SP1 (32-bit)", "SUSE Linux Enterprise Server 11 SP1 (32-bit)"); + XenServer610GuestOsMap.put("SUSE Linux Enterprise Server 11 SP1 (64-bit)", "SUSE Linux Enterprise Server 11 SP1 (64-bit)"); + XenServer610GuestOsMap.put("Windows 7 (32-bit)", "Windows 7 (32-bit)"); + XenServer610GuestOsMap.put("Windows 7 (64-bit)", "Windows 7 (64-bit)"); + XenServer610GuestOsMap.put("Windows 8 (32-bit)", "Windows 8 (32-bit) (experimental)"); + XenServer610GuestOsMap.put("Windows 8 (64-bit)", "Windows 8 (64-bit) (experimental)"); + XenServer610GuestOsMap.put("Windows Server 2003 (32-bit)", "Windows Server 2003 (32-bit)"); + XenServer610GuestOsMap.put("Windows Server 2003 (64-bit)", "Windows Server 2003 (64-bit)"); + XenServer610GuestOsMap.put("Windows Server 2003 PAE (32-bit)", "Windows Server 2003 PAE (32-bit)"); + XenServer610GuestOsMap.put("Windows Server 2003 Enterprise Edition(32-bit)", "Windows Server 2003 (32-bit)"); + XenServer610GuestOsMap.put("Windows Server 2003 Enterprise Edition(64-bit)", "Windows Server 2003 (64-bit)"); + XenServer610GuestOsMap.put("Windows Server 2003 DataCenter Edition(32-bit)", "Windows Server 2003 (32-bit)"); + XenServer610GuestOsMap.put("Windows Server 2003 DataCenter Edition(64-bit)", "Windows Server 2003 (64-bit)"); + XenServer610GuestOsMap.put("Windows Server 2003 Standard Edition(32-bit)", "Windows Server 2003 (32-bit)"); + XenServer610GuestOsMap.put("Windows Server 2003 Standard Edition(64-bit)", "Windows Server 2003 (64-bit)"); + XenServer610GuestOsMap.put("Windows Server 2008 (32-bit)", "Windows Server 2008 (32-bit)"); + XenServer610GuestOsMap.put("Windows Server 2008 (64-bit)", "Windows Server 2008 (64-bit)"); + XenServer610GuestOsMap.put("Windows Server 2008 R2 (64-bit)", "Windows Server 2008 R2 (64-bit)"); + XenServer610GuestOsMap.put("Windows Server 2012 (64-bit)", "Windows Server 2012 (64-bit) (experimental)"); + XenServer610GuestOsMap.put("Windows Server 8 (64-bit)", "Windows Server 2012 (64-bit) (experimental)"); + XenServer610GuestOsMap.put("Windows Vista (32-bit)", "Windows Vista (32-bit)"); + XenServer610GuestOsMap.put("Windows XP SP3 (32-bit)", "Windows XP SP3 (32-bit)"); + XenServer610GuestOsMap.put("Ubuntu 10.04 (32-bit)", "Ubuntu Lucid Lynx 10.04 (32-bit)"); + XenServer610GuestOsMap.put("Ubuntu 10.04 (64-bit)", "Ubuntu Lucid Lynx 10.04 (64-bit)"); + XenServer610GuestOsMap.put("Ubuntu 10.10 (32-bit)", "Ubuntu Maverick Meerkat 10.10 (32-bit) (experimental)"); + XenServer610GuestOsMap.put("Ubuntu 10.10 (64-bit)", "Ubuntu Maverick Meerkat 10.10 (64-bit) (experimental)"); + XenServer610GuestOsMap.put("Ubuntu 12.04 (32-bit)", "Ubuntu Precise Pangolin 12.04 (32-bit)"); + XenServer610GuestOsMap.put("Ubuntu 12.04 (64-bit)", "Ubuntu Precise Pangolin 12.04 (64-bit)"); + XenServer610GuestOsMap.put("Ubuntu 11.04 (32-bit)", "Other install media"); + XenServer610GuestOsMap.put("Ubuntu 11.04 (64-bit)", "Other install media"); + XenServer610GuestOsMap.put("Other Linux (32-bit)", "Other install media"); + XenServer610GuestOsMap.put("Other Linux (64-bit)", "Other install media"); + XenServer610GuestOsMap.put("Other (32-bit)", "Other install media"); + XenServer610GuestOsMap.put("Other (64-bit)", "Other install media"); + XenServer610GuestOsMap.put("Other CentOS (32-bit)", "Other install media"); + XenServer610GuestOsMap.put("Other CentOS (64-bit)", "Other install media"); + XenServer610GuestOsMap.put("Other Ubuntu (32-bit)", "Other install media"); + XenServer610GuestOsMap.put("Other Ubuntu (64-bit)", "Other install media"); + XenServer610GuestOsMap.put("Other SUSE Linux(32-bit)", "Other install media"); + XenServer610GuestOsMap.put("Other SUSE Linux(64-bit)", "Other install media"); + XenServer610GuestOsMap.put("Other PV (32-bit)", "CentOS 5 (32-bit)"); + XenServer610GuestOsMap.put("Other PV (64-bit)", "CentOS 5 (64-bit)"); } static { - _xenServer620GuestOsMap.put("CentOS 4.5 (32-bit)", "CentOS 4.5 (32-bit)"); - _xenServer620GuestOsMap.put("CentOS 4.6 (32-bit)", "CentOS 4.6 (32-bit)"); - _xenServer620GuestOsMap.put("CentOS 4.7 (32-bit)", "CentOS 4.7 (32-bit)"); - _xenServer620GuestOsMap.put("CentOS 4.8 (32-bit)", "CentOS 4.8 (32-bit)"); - _xenServer620GuestOsMap.put("CentOS 5.0 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer620GuestOsMap.put("CentOS 5.0 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer620GuestOsMap.put("CentOS 5.1 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer620GuestOsMap.put("CentOS 5.1 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer620GuestOsMap.put("CentOS 5.2 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer620GuestOsMap.put("CentOS 5.2 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer620GuestOsMap.put("CentOS 5.3 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer620GuestOsMap.put("CentOS 5.3 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer620GuestOsMap.put("CentOS 5.4 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer620GuestOsMap.put("CentOS 5.4 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer620GuestOsMap.put("CentOS 5.5 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer620GuestOsMap.put("CentOS 5.5 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer620GuestOsMap.put("CentOS 5.6 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer620GuestOsMap.put("CentOS 5.6 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer620GuestOsMap.put("CentOS 5.7 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer620GuestOsMap.put("CentOS 5.7 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer620GuestOsMap.put("CentOS 5.8 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer620GuestOsMap.put("CentOS 5.8 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer620GuestOsMap.put("CentOS 5.9 (32-bit)", "CentOS 5 (32-bit)"); - _xenServer620GuestOsMap.put("CentOS 5.9 (64-bit)", "CentOS 5 (64-bit)"); - _xenServer620GuestOsMap.put("CentOS 6.0 (32-bit)", "CentOS 6 (32-bit)"); - _xenServer620GuestOsMap.put("CentOS 6.0 (64-bit)", "CentOS 6 (64-bit)"); - _xenServer620GuestOsMap.put("CentOS 6.1 (32-bit)", "CentOS 6 (32-bit)"); - _xenServer620GuestOsMap.put("CentOS 6.1 (64-bit)", "CentOS 6 (64-bit)"); - _xenServer620GuestOsMap.put("CentOS 6.2 (32-bit)", "CentOS 6 (32-bit)"); - _xenServer620GuestOsMap.put("CentOS 6.2 (64-bit)", "CentOS 6 (64-bit)"); - _xenServer620GuestOsMap.put("CentOS 6.3 (32-bit)", "CentOS 6 (32-bit)"); - _xenServer620GuestOsMap.put("CentOS 6.3 (64-bit)", "CentOS 6 (64-bit)"); - _xenServer620GuestOsMap.put("CentOS 6.4 (32-bit)", "CentOS 6 (32-bit)"); - _xenServer620GuestOsMap.put("CentOS 6.4 (64-bit)", "CentOS 6 (64-bit)"); - _xenServer620GuestOsMap.put("Debian GNU/Linux 6(32-bit)", "Debian Squeeze 6.0 (32-bit)"); - _xenServer620GuestOsMap.put("Debian GNU/Linux 6(64-bit)", "Debian Squeeze 6.0 (64-bit)"); - _xenServer620GuestOsMap.put("Debian GNU/Linux 7(32-bit)", "Debian Wheezy 7.0 (32-bit)"); - _xenServer620GuestOsMap.put("Debian GNU/Linux 7(64-bit)", "Debian Wheezy 7.0 (64-bit)"); - _xenServer620GuestOsMap.put("Oracle Enterprise Linux 5.0 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer620GuestOsMap.put("Oracle Enterprise Linux 5.0 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer620GuestOsMap.put("Oracle Enterprise Linux 5.1 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer620GuestOsMap.put("Oracle Enterprise Linux 5.1 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer620GuestOsMap.put("Oracle Enterprise Linux 5.2 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer620GuestOsMap.put("Oracle Enterprise Linux 5.2 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer620GuestOsMap.put("Oracle Enterprise Linux 5.3 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer620GuestOsMap.put("Oracle Enterprise Linux 5.3 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer620GuestOsMap.put("Oracle Enterprise Linux 5.4 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer620GuestOsMap.put("Oracle Enterprise Linux 5.4 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer620GuestOsMap.put("Oracle Enterprise Linux 5.5 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer620GuestOsMap.put("Oracle Enterprise Linux 5.5 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer620GuestOsMap.put("Oracle Enterprise Linux 5.6 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer620GuestOsMap.put("Oracle Enterprise Linux 5.6 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer620GuestOsMap.put("Oracle Enterprise Linux 5.7 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer620GuestOsMap.put("Oracle Enterprise Linux 5.7 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer620GuestOsMap.put("Oracle Enterprise Linux 5.8 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer620GuestOsMap.put("Oracle Enterprise Linux 5.8 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer620GuestOsMap.put("Oracle Enterprise Linux 5.9 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); - _xenServer620GuestOsMap.put("Oracle Enterprise Linux 5.9 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); - _xenServer620GuestOsMap.put("Oracle Enterprise Linux 6.0 (32-bit)", "Oracle Enterprise Linux 6 (32-bit)"); - _xenServer620GuestOsMap.put("Oracle Enterprise Linux 6.0 (64-bit)", "Oracle Enterprise Linux 6 (64-bit)"); - _xenServer620GuestOsMap.put("Oracle Enterprise Linux 6.1 (32-bit)", "Oracle Enterprise Linux 6 (32-bit)"); - _xenServer620GuestOsMap.put("Oracle Enterprise Linux 6.1 (64-bit)", "Oracle Enterprise Linux 6 (64-bit)"); - _xenServer620GuestOsMap.put("Oracle Enterprise Linux 6.2 (32-bit)", "Oracle Enterprise Linux 6 (32-bit)"); - _xenServer620GuestOsMap.put("Oracle Enterprise Linux 6.2 (64-bit)", "Oracle Enterprise Linux 6 (64-bit)"); - _xenServer620GuestOsMap.put("Oracle Enterprise Linux 6.3 (32-bit)", "Oracle Enterprise Linux 6 (32-bit)"); - _xenServer620GuestOsMap.put("Oracle Enterprise Linux 6.3 (64-bit)", "Oracle Enterprise Linux 6 (64-bit)"); - _xenServer620GuestOsMap.put("Oracle Enterprise Linux 6.4 (32-bit)", "Oracle Enterprise Linux 6 (32-bit)"); - _xenServer620GuestOsMap.put("Oracle Enterprise Linux 6.4 (64-bit)", "Oracle Enterprise Linux 6 (64-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", "Red Hat Enterprise Linux 4.5 (32-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", "Red Hat Enterprise Linux 4.6 (32-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", "Red Hat Enterprise Linux 4.7 (32-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", "Red Hat Enterprise Linux 4.8 (32-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.5 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.5 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.6 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.6 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.7 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.7 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.8 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.8 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.9 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.9 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 6.0 (32-bit)", "Red Hat Enterprise Linux 6 (32-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 6.0 (64-bit)", "Red Hat Enterprise Linux 6 (64-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 6.1 (32-bit)", "Red Hat Enterprise Linux 6 (32-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 6.1 (64-bit)", "Red Hat Enterprise Linux 6 (64-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 6.2 (32-bit)", "Red Hat Enterprise Linux 6 (32-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 6.2 (64-bit)", "Red Hat Enterprise Linux 6 (64-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 6.3 (32-bit)", "Red Hat Enterprise Linux 6 (32-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 6.3 (64-bit)", "Red Hat Enterprise Linux 6 (64-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 6.4 (32-bit)", "Red Hat Enterprise Linux 6 (32-bit)"); - _xenServer620GuestOsMap.put("Red Hat Enterprise Linux 6.4 (64-bit)", "Red Hat Enterprise Linux 6 (64-bit)"); - _xenServer620GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", "SUSE Linux Enterprise Server 10 SP1 (32-bit)"); - _xenServer620GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", "SUSE Linux Enterprise Server 10 SP1 (64-bit)"); - _xenServer620GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", "SUSE Linux Enterprise Server 10 SP2 (32-bit)"); - _xenServer620GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", "SUSE Linux Enterprise Server 10 SP2 (64-bit)"); - _xenServer620GuestOsMap.put("SUSE Linux Enterprise Server 10 SP3 (32-bit)", "SUSE Linux Enterprise Server 10 SP3 (32-bit)"); - _xenServer620GuestOsMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", "SUSE Linux Enterprise Server 10 SP3 (64-bit)"); - _xenServer620GuestOsMap.put("SUSE Linux Enterprise Server 10 SP4 (32-bit)", "SUSE Linux Enterprise Server 10 SP4 (32-bit)"); - _xenServer620GuestOsMap.put("SUSE Linux Enterprise Server 10 SP4 (64-bit)", "SUSE Linux Enterprise Server 10 SP4 (64-bit)"); - _xenServer620GuestOsMap.put("SUSE Linux Enterprise Server 11 (32-bit)", "SUSE Linux Enterprise Server 11 (32-bit)"); - _xenServer620GuestOsMap.put("SUSE Linux Enterprise Server 11 (64-bit)", "SUSE Linux Enterprise Server 11 (64-bit)"); - _xenServer620GuestOsMap.put("SUSE Linux Enterprise Server 11 SP1 (32-bit)", "SUSE Linux Enterprise Server 11 SP1 (32-bit)"); - _xenServer620GuestOsMap.put("SUSE Linux Enterprise Server 11 SP1 (64-bit)", "SUSE Linux Enterprise Server 11 SP1 (64-bit)"); - _xenServer620GuestOsMap.put("SUSE Linux Enterprise Server 11 SP2 (32-bit)", "SUSE Linux Enterprise Server 11 SP2 (32-bit)"); - _xenServer620GuestOsMap.put("SUSE Linux Enterprise Server 11 SP2 (64-bit)", "SUSE Linux Enterprise Server 11 SP2 (64-bit)"); - _xenServer620GuestOsMap.put("Windows 7 (32-bit)", "Windows 7 (32-bit)"); - _xenServer620GuestOsMap.put("Windows 7 (64-bit)", "Windows 7 (64-bit)"); - _xenServer620GuestOsMap.put("Windows 7 SP1 (32-bit)", "Windows 7 SP1 (32-bit)"); - _xenServer620GuestOsMap.put("Windows 7 SP1 (64-bit)", "Windows 7 SP1 (64-bit)"); - _xenServer620GuestOsMap.put("Windows 8 (32-bit)", "Windows 8 (32-bit)"); - _xenServer620GuestOsMap.put("Windows 8 (64-bit)", "Windows 8 (64-bit)"); - _xenServer620GuestOsMap.put("Windows Server 2003 SP2 (32-bit)", "Windows Server 2003 SP2 (32-bit)"); - _xenServer620GuestOsMap.put("Windows Server 2003 SP2 (64-bit)", "Windows Server 2003 SP2 (64-bit)"); - _xenServer620GuestOsMap.put("Windows Server 2003 PAE (32-bit)", "Windows Server 2003 PAE (32-bit)"); - _xenServer620GuestOsMap.put("Windows Server 2003 Enterprise Edition(32-bit)", "Windows Server 2003 (32-bit)"); - _xenServer620GuestOsMap.put("Windows Server 2003 Enterprise Edition(64-bit)", "Windows Server 2003 (64-bit)"); - _xenServer620GuestOsMap.put("Windows Server 2003 DataCenter Edition(32-bit)", "Windows Server 2003 (32-bit)"); - _xenServer620GuestOsMap.put("Windows Server 2003 DataCenter Edition(64-bit)", "Windows Server 2003 (64-bit)"); - _xenServer620GuestOsMap.put("Windows Server 2003 Standard Edition(32-bit)", "Windows Server 2003 (32-bit)"); - _xenServer620GuestOsMap.put("Windows Server 2003 Standard Edition(64-bit)", "Windows Server 2003 (64-bit)"); - _xenServer620GuestOsMap.put("Windows Server 2008 SP2 (32-bit)", "Windows Server 2008 SP2 (32-bit)"); - _xenServer620GuestOsMap.put("Windows Server 2008 SP2 (64-bit)", "Windows Server 2008 SP2 (64-bit)"); - _xenServer620GuestOsMap.put("Windows Server 2008 R2 (64-bit)", "Windows Server 2008 R2 (64-bit)"); - _xenServer620GuestOsMap.put("Windows Server 2008 R2 SP1 (64-bit)", "Windows Server 2008 R2 SP1 (64-bit)"); - _xenServer620GuestOsMap.put("Windows Server 2012 (64-bit)", "Windows Server 2012 (64-bit)"); - _xenServer620GuestOsMap.put("Windows Vista SP2 (32-bit)", "Windows Vista (32-bit)"); - _xenServer620GuestOsMap.put("Windows XP SP3 (32-bit)", "Windows XP SP3 (32-bit)"); - _xenServer620GuestOsMap.put("Ubuntu 10.04 (32-bit)", "Ubuntu Lucid Lynx 10.04 (32-bit)"); - _xenServer620GuestOsMap.put("Ubuntu 10.04 (64-bit)", "Ubuntu Lucid Lynx 10.04 (64-bit)"); - _xenServer620GuestOsMap.put("Ubuntu 10.10 (32-bit)", "Ubuntu Maverick Meerkat 10.10 (32-bit) (experimental)"); - _xenServer620GuestOsMap.put("Ubuntu 10.10 (64-bit)", "Ubuntu Maverick Meerkat 10.10 (64-bit) (experimental)"); - _xenServer620GuestOsMap.put("Ubuntu 12.04 (32-bit)", "Ubuntu Precise Pangolin 12.04 (32-bit)"); - _xenServer620GuestOsMap.put("Ubuntu 12.04 (64-bit)", "Ubuntu Precise Pangolin 12.04 (64-bit)"); - _xenServer620GuestOsMap.put("Ubuntu 11.04 (32-bit)", "Other install media"); - _xenServer620GuestOsMap.put("Ubuntu 11.04 (64-bit)", "Other install media"); - _xenServer620GuestOsMap.put("Other Linux (32-bit)", "Other install media"); - _xenServer620GuestOsMap.put("Other Linux (64-bit)", "Other install media"); - _xenServer620GuestOsMap.put("Other (32-bit)", "Other install media"); - _xenServer620GuestOsMap.put("Other (64-bit)", "Other install media"); - _xenServer620GuestOsMap.put("Other CentOS (32-bit)", "Other install media"); - _xenServer620GuestOsMap.put("Other CentOS (64-bit)", "Other install media"); - _xenServer620GuestOsMap.put("Other Ubuntu (32-bit)", "Other install media"); - _xenServer620GuestOsMap.put("Other Ubuntu (64-bit)", "Other install media"); - _xenServer620GuestOsMap.put("Other SUSE Linux(32-bit)", "Other install media"); - _xenServer620GuestOsMap.put("Other SUSE Linux(64-bit)", "Other install media"); - _xenServer620GuestOsMap.put("Other PV (32-bit)", "CentOS 5 (32-bit)"); - _xenServer620GuestOsMap.put("Other PV (64-bit)", "CentOS 5 (64-bit)"); + XenServer620GuestOsMap.put("CentOS 4.5 (32-bit)", "CentOS 4.5 (32-bit)"); + XenServer620GuestOsMap.put("CentOS 4.6 (32-bit)", "CentOS 4.6 (32-bit)"); + XenServer620GuestOsMap.put("CentOS 4.7 (32-bit)", "CentOS 4.7 (32-bit)"); + XenServer620GuestOsMap.put("CentOS 4.8 (32-bit)", "CentOS 4.8 (32-bit)"); + XenServer620GuestOsMap.put("CentOS 5.0 (32-bit)", "CentOS 5 (32-bit)"); + XenServer620GuestOsMap.put("CentOS 5.0 (64-bit)", "CentOS 5 (64-bit)"); + XenServer620GuestOsMap.put("CentOS 5.1 (32-bit)", "CentOS 5 (32-bit)"); + XenServer620GuestOsMap.put("CentOS 5.1 (64-bit)", "CentOS 5 (64-bit)"); + XenServer620GuestOsMap.put("CentOS 5.2 (32-bit)", "CentOS 5 (32-bit)"); + XenServer620GuestOsMap.put("CentOS 5.2 (64-bit)", "CentOS 5 (64-bit)"); + XenServer620GuestOsMap.put("CentOS 5.3 (32-bit)", "CentOS 5 (32-bit)"); + XenServer620GuestOsMap.put("CentOS 5.3 (64-bit)", "CentOS 5 (64-bit)"); + XenServer620GuestOsMap.put("CentOS 5.4 (32-bit)", "CentOS 5 (32-bit)"); + XenServer620GuestOsMap.put("CentOS 5.4 (64-bit)", "CentOS 5 (64-bit)"); + XenServer620GuestOsMap.put("CentOS 5.5 (32-bit)", "CentOS 5 (32-bit)"); + XenServer620GuestOsMap.put("CentOS 5.5 (64-bit)", "CentOS 5 (64-bit)"); + XenServer620GuestOsMap.put("CentOS 5.6 (32-bit)", "CentOS 5 (32-bit)"); + XenServer620GuestOsMap.put("CentOS 5.6 (64-bit)", "CentOS 5 (64-bit)"); + XenServer620GuestOsMap.put("CentOS 5.7 (32-bit)", "CentOS 5 (32-bit)"); + XenServer620GuestOsMap.put("CentOS 5.7 (64-bit)", "CentOS 5 (64-bit)"); + XenServer620GuestOsMap.put("CentOS 5.8 (32-bit)", "CentOS 5 (32-bit)"); + XenServer620GuestOsMap.put("CentOS 5.8 (64-bit)", "CentOS 5 (64-bit)"); + XenServer620GuestOsMap.put("CentOS 5.9 (32-bit)", "CentOS 5 (32-bit)"); + XenServer620GuestOsMap.put("CentOS 5.9 (64-bit)", "CentOS 5 (64-bit)"); + XenServer620GuestOsMap.put("CentOS 6.0 (32-bit)", "CentOS 6 (32-bit)"); + XenServer620GuestOsMap.put("CentOS 6.0 (64-bit)", "CentOS 6 (64-bit)"); + XenServer620GuestOsMap.put("CentOS 6.1 (32-bit)", "CentOS 6 (32-bit)"); + XenServer620GuestOsMap.put("CentOS 6.1 (64-bit)", "CentOS 6 (64-bit)"); + XenServer620GuestOsMap.put("CentOS 6.2 (32-bit)", "CentOS 6 (32-bit)"); + XenServer620GuestOsMap.put("CentOS 6.2 (64-bit)", "CentOS 6 (64-bit)"); + XenServer620GuestOsMap.put("CentOS 6.3 (32-bit)", "CentOS 6 (32-bit)"); + XenServer620GuestOsMap.put("CentOS 6.3 (64-bit)", "CentOS 6 (64-bit)"); + XenServer620GuestOsMap.put("CentOS 6.4 (32-bit)", "CentOS 6 (32-bit)"); + XenServer620GuestOsMap.put("CentOS 6.4 (64-bit)", "CentOS 6 (64-bit)"); + XenServer620GuestOsMap.put("Debian GNU/Linux 6(32-bit)", "Debian Squeeze 6.0 (32-bit)"); + XenServer620GuestOsMap.put("Debian GNU/Linux 6(64-bit)", "Debian Squeeze 6.0 (64-bit)"); + XenServer620GuestOsMap.put("Debian GNU/Linux 7(32-bit)", "Debian Wheezy 7.0 (32-bit)"); + XenServer620GuestOsMap.put("Debian GNU/Linux 7(64-bit)", "Debian Wheezy 7.0 (64-bit)"); + XenServer620GuestOsMap.put("Oracle Enterprise Linux 5.0 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer620GuestOsMap.put("Oracle Enterprise Linux 5.0 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer620GuestOsMap.put("Oracle Enterprise Linux 5.1 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer620GuestOsMap.put("Oracle Enterprise Linux 5.1 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer620GuestOsMap.put("Oracle Enterprise Linux 5.2 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer620GuestOsMap.put("Oracle Enterprise Linux 5.2 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer620GuestOsMap.put("Oracle Enterprise Linux 5.3 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer620GuestOsMap.put("Oracle Enterprise Linux 5.3 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer620GuestOsMap.put("Oracle Enterprise Linux 5.4 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer620GuestOsMap.put("Oracle Enterprise Linux 5.4 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer620GuestOsMap.put("Oracle Enterprise Linux 5.5 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer620GuestOsMap.put("Oracle Enterprise Linux 5.5 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer620GuestOsMap.put("Oracle Enterprise Linux 5.6 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer620GuestOsMap.put("Oracle Enterprise Linux 5.6 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer620GuestOsMap.put("Oracle Enterprise Linux 5.7 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer620GuestOsMap.put("Oracle Enterprise Linux 5.7 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer620GuestOsMap.put("Oracle Enterprise Linux 5.8 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer620GuestOsMap.put("Oracle Enterprise Linux 5.8 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer620GuestOsMap.put("Oracle Enterprise Linux 5.9 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + XenServer620GuestOsMap.put("Oracle Enterprise Linux 5.9 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + XenServer620GuestOsMap.put("Oracle Enterprise Linux 6.0 (32-bit)", "Oracle Enterprise Linux 6 (32-bit)"); + XenServer620GuestOsMap.put("Oracle Enterprise Linux 6.0 (64-bit)", "Oracle Enterprise Linux 6 (64-bit)"); + XenServer620GuestOsMap.put("Oracle Enterprise Linux 6.1 (32-bit)", "Oracle Enterprise Linux 6 (32-bit)"); + XenServer620GuestOsMap.put("Oracle Enterprise Linux 6.1 (64-bit)", "Oracle Enterprise Linux 6 (64-bit)"); + XenServer620GuestOsMap.put("Oracle Enterprise Linux 6.2 (32-bit)", "Oracle Enterprise Linux 6 (32-bit)"); + XenServer620GuestOsMap.put("Oracle Enterprise Linux 6.2 (64-bit)", "Oracle Enterprise Linux 6 (64-bit)"); + XenServer620GuestOsMap.put("Oracle Enterprise Linux 6.3 (32-bit)", "Oracle Enterprise Linux 6 (32-bit)"); + XenServer620GuestOsMap.put("Oracle Enterprise Linux 6.3 (64-bit)", "Oracle Enterprise Linux 6 (64-bit)"); + XenServer620GuestOsMap.put("Oracle Enterprise Linux 6.4 (32-bit)", "Oracle Enterprise Linux 6 (32-bit)"); + XenServer620GuestOsMap.put("Oracle Enterprise Linux 6.4 (64-bit)", "Oracle Enterprise Linux 6 (64-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", "Red Hat Enterprise Linux 4.5 (32-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", "Red Hat Enterprise Linux 4.6 (32-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", "Red Hat Enterprise Linux 4.7 (32-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", "Red Hat Enterprise Linux 4.8 (32-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.5 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.5 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.6 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.6 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.7 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.7 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.8 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.8 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.9 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 5.9 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 6.0 (32-bit)", "Red Hat Enterprise Linux 6 (32-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 6.0 (64-bit)", "Red Hat Enterprise Linux 6 (64-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 6.1 (32-bit)", "Red Hat Enterprise Linux 6 (32-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 6.1 (64-bit)", "Red Hat Enterprise Linux 6 (64-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 6.2 (32-bit)", "Red Hat Enterprise Linux 6 (32-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 6.2 (64-bit)", "Red Hat Enterprise Linux 6 (64-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 6.3 (32-bit)", "Red Hat Enterprise Linux 6 (32-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 6.3 (64-bit)", "Red Hat Enterprise Linux 6 (64-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 6.4 (32-bit)", "Red Hat Enterprise Linux 6 (32-bit)"); + XenServer620GuestOsMap.put("Red Hat Enterprise Linux 6.4 (64-bit)", "Red Hat Enterprise Linux 6 (64-bit)"); + XenServer620GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", "SUSE Linux Enterprise Server 10 SP1 (32-bit)"); + XenServer620GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", "SUSE Linux Enterprise Server 10 SP1 (64-bit)"); + XenServer620GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", "SUSE Linux Enterprise Server 10 SP2 (32-bit)"); + XenServer620GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", "SUSE Linux Enterprise Server 10 SP2 (64-bit)"); + XenServer620GuestOsMap.put("SUSE Linux Enterprise Server 10 SP3 (32-bit)", "SUSE Linux Enterprise Server 10 SP3 (32-bit)"); + XenServer620GuestOsMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", "SUSE Linux Enterprise Server 10 SP3 (64-bit)"); + XenServer620GuestOsMap.put("SUSE Linux Enterprise Server 10 SP4 (32-bit)", "SUSE Linux Enterprise Server 10 SP4 (32-bit)"); + XenServer620GuestOsMap.put("SUSE Linux Enterprise Server 10 SP4 (64-bit)", "SUSE Linux Enterprise Server 10 SP4 (64-bit)"); + XenServer620GuestOsMap.put("SUSE Linux Enterprise Server 11 (32-bit)", "SUSE Linux Enterprise Server 11 (32-bit)"); + XenServer620GuestOsMap.put("SUSE Linux Enterprise Server 11 (64-bit)", "SUSE Linux Enterprise Server 11 (64-bit)"); + XenServer620GuestOsMap.put("SUSE Linux Enterprise Server 11 SP1 (32-bit)", "SUSE Linux Enterprise Server 11 SP1 (32-bit)"); + XenServer620GuestOsMap.put("SUSE Linux Enterprise Server 11 SP1 (64-bit)", "SUSE Linux Enterprise Server 11 SP1 (64-bit)"); + XenServer620GuestOsMap.put("SUSE Linux Enterprise Server 11 SP2 (32-bit)", "SUSE Linux Enterprise Server 11 SP2 (32-bit)"); + XenServer620GuestOsMap.put("SUSE Linux Enterprise Server 11 SP2 (64-bit)", "SUSE Linux Enterprise Server 11 SP2 (64-bit)"); + XenServer620GuestOsMap.put("Windows 7 (32-bit)", "Windows 7 (32-bit)"); + XenServer620GuestOsMap.put("Windows 7 (64-bit)", "Windows 7 (64-bit)"); + XenServer620GuestOsMap.put("Windows 7 SP1 (32-bit)", "Windows 7 SP1 (32-bit)"); + XenServer620GuestOsMap.put("Windows 7 SP1 (64-bit)", "Windows 7 SP1 (64-bit)"); + XenServer620GuestOsMap.put("Windows 8 (32-bit)", "Windows 8 (32-bit)"); + XenServer620GuestOsMap.put("Windows 8 (64-bit)", "Windows 8 (64-bit)"); + XenServer620GuestOsMap.put("Windows Server 2003 SP2 (32-bit)", "Windows Server 2003 SP2 (32-bit)"); + XenServer620GuestOsMap.put("Windows Server 2003 SP2 (64-bit)", "Windows Server 2003 SP2 (64-bit)"); + XenServer620GuestOsMap.put("Windows Server 2003 PAE (32-bit)", "Windows Server 2003 PAE (32-bit)"); + XenServer620GuestOsMap.put("Windows Server 2003 Enterprise Edition(32-bit)", "Windows Server 2003 (32-bit)"); + XenServer620GuestOsMap.put("Windows Server 2003 Enterprise Edition(64-bit)", "Windows Server 2003 (64-bit)"); + XenServer620GuestOsMap.put("Windows Server 2003 DataCenter Edition(32-bit)", "Windows Server 2003 (32-bit)"); + XenServer620GuestOsMap.put("Windows Server 2003 DataCenter Edition(64-bit)", "Windows Server 2003 (64-bit)"); + XenServer620GuestOsMap.put("Windows Server 2003 Standard Edition(32-bit)", "Windows Server 2003 (32-bit)"); + XenServer620GuestOsMap.put("Windows Server 2003 Standard Edition(64-bit)", "Windows Server 2003 (64-bit)"); + XenServer620GuestOsMap.put("Windows Server 2008 SP2 (32-bit)", "Windows Server 2008 SP2 (32-bit)"); + XenServer620GuestOsMap.put("Windows Server 2008 SP2 (64-bit)", "Windows Server 2008 SP2 (64-bit)"); + XenServer620GuestOsMap.put("Windows Server 2008 R2 (64-bit)", "Windows Server 2008 R2 (64-bit)"); + XenServer620GuestOsMap.put("Windows Server 2008 R2 SP1 (64-bit)", "Windows Server 2008 R2 SP1 (64-bit)"); + XenServer620GuestOsMap.put("Windows Server 2012 (64-bit)", "Windows Server 2012 (64-bit)"); + XenServer620GuestOsMap.put("Windows Vista SP2 (32-bit)", "Windows Vista (32-bit)"); + XenServer620GuestOsMap.put("Windows XP SP3 (32-bit)", "Windows XP SP3 (32-bit)"); + XenServer620GuestOsMap.put("Ubuntu 10.04 (32-bit)", "Ubuntu Lucid Lynx 10.04 (32-bit)"); + XenServer620GuestOsMap.put("Ubuntu 10.04 (64-bit)", "Ubuntu Lucid Lynx 10.04 (64-bit)"); + XenServer620GuestOsMap.put("Ubuntu 10.10 (32-bit)", "Ubuntu Maverick Meerkat 10.10 (32-bit) (experimental)"); + XenServer620GuestOsMap.put("Ubuntu 10.10 (64-bit)", "Ubuntu Maverick Meerkat 10.10 (64-bit) (experimental)"); + XenServer620GuestOsMap.put("Ubuntu 12.04 (32-bit)", "Ubuntu Precise Pangolin 12.04 (32-bit)"); + XenServer620GuestOsMap.put("Ubuntu 12.04 (64-bit)", "Ubuntu Precise Pangolin 12.04 (64-bit)"); + XenServer620GuestOsMap.put("Ubuntu 11.04 (32-bit)", "Other install media"); + XenServer620GuestOsMap.put("Ubuntu 11.04 (64-bit)", "Other install media"); + XenServer620GuestOsMap.put("Other Linux (32-bit)", "Other install media"); + XenServer620GuestOsMap.put("Other Linux (64-bit)", "Other install media"); + XenServer620GuestOsMap.put("Other (32-bit)", "Other install media"); + XenServer620GuestOsMap.put("Other (64-bit)", "Other install media"); + XenServer620GuestOsMap.put("Other CentOS (32-bit)", "Other install media"); + XenServer620GuestOsMap.put("Other CentOS (64-bit)", "Other install media"); + XenServer620GuestOsMap.put("Other Ubuntu (32-bit)", "Other install media"); + XenServer620GuestOsMap.put("Other Ubuntu (64-bit)", "Other install media"); + XenServer620GuestOsMap.put("Other SUSE Linux(32-bit)", "Other install media"); + XenServer620GuestOsMap.put("Other SUSE Linux(64-bit)", "Other install media"); + XenServer620GuestOsMap.put("Other PV (32-bit)", "CentOS 5 (32-bit)"); + XenServer620GuestOsMap.put("Other PV (64-bit)", "CentOS 5 (64-bit)"); } public static class MemoryValues { @@ -1547,99 +1547,99 @@ public class CitrixHelper { } static { - _xenServer610GuestOsMemoryMap.put("CentOS 4.5 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("CentOS 4.6 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("CentOS 4.7 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("CentOS 4.8 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("CentOS 5.0 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("CentOS 5.0 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("CentOS 5.1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("CentOS 5.1 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("CentOS 5.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("CentOS 5.2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("CentOS 5.3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("CentOS 5.3 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("CentOS 5.4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("CentOS 5.4 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("CentOS 5.5 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("CentOS 5.5 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("CentOS 5.6 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("CentOS 5.6 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("CentOS 5.7 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("CentOS 5.7 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("CentOS 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer610GuestOsMemoryMap.put("CentOS 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer610GuestOsMemoryMap.put("CentOS 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer610GuestOsMemoryMap.put("CentOS 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer610GuestOsMemoryMap.put("CentOS 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("CentOS 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Debian GNU/Linux 6(32-bit)", new MemoryValues(128l, 32 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Debian GNU/Linux 6(64-bit)", new MemoryValues(128l, 32 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Debian GNU/Linux 7(32-bit)", new MemoryValues(128l, 32 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Debian GNU/Linux 7(64-bit)", new MemoryValues(128l, 32 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.0 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.0 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.1 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.1 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.2 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.3 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.3 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.4 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.4 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.5 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.5 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.6 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.6 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.7 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.7 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.5 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.5 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.6 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.6 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.7 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.7 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer610GuestOsMemoryMap.put("SUSE Linux Enterprise Server 9 SP4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer610GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer610GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer610GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP4 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer610GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer610GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 SP1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 SP1 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Windows 7 (32-bit)", new MemoryValues(1024l, 4 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Windows 7 (64-bit)", new MemoryValues(2 * 1024l, 128 * 1024l)); + XenServer610GuestOsMemoryMap.put("CentOS 4.5 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("CentOS 4.6 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("CentOS 4.7 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("CentOS 4.8 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("CentOS 5.0 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("CentOS 5.0 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("CentOS 5.1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("CentOS 5.1 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("CentOS 5.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("CentOS 5.2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("CentOS 5.3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("CentOS 5.3 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("CentOS 5.4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("CentOS 5.4 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("CentOS 5.5 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("CentOS 5.5 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("CentOS 5.6 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("CentOS 5.6 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("CentOS 5.7 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("CentOS 5.7 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("CentOS 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer610GuestOsMemoryMap.put("CentOS 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer610GuestOsMemoryMap.put("CentOS 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer610GuestOsMemoryMap.put("CentOS 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer610GuestOsMemoryMap.put("CentOS 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("CentOS 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer610GuestOsMemoryMap.put("Debian GNU/Linux 6(32-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer610GuestOsMemoryMap.put("Debian GNU/Linux 6(64-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer610GuestOsMemoryMap.put("Debian GNU/Linux 7(32-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer610GuestOsMemoryMap.put("Debian GNU/Linux 7(64-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.0 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.0 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.1 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.1 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.2 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.3 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.3 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.4 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.4 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.5 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.5 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.6 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.6 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.7 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 5.7 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("Oracle Enterprise Linux 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.5 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.5 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.6 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.6 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.7 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.7 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer610GuestOsMemoryMap.put("SUSE Linux Enterprise Server 9 SP4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer610GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer610GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer610GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP4 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer610GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer610GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 SP1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 SP1 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer610GuestOsMemoryMap.put("Windows 7 (32-bit)", new MemoryValues(1024l, 4 * 1024l)); + XenServer610GuestOsMemoryMap.put("Windows 7 (64-bit)", new MemoryValues(2 * 1024l, 128 * 1024l)); //_xenServer610GuestOsMemoryMap.put("Windows 8 (32-bit)", new MemoryValues(512l, 16*1024l)); //? //_xenServer610GuestOsMemoryMap.put("Windows 8 (64-bit)", new MemoryValues(512l, 16*1024l)); //? //_xenServer610GuestOsMemoryMap.put("Windows Server 2003 (32-bit)", new MemoryValues(256l, 64*1024l)); //? @@ -1653,174 +1653,174 @@ public class CitrixHelper { //_xenServer610GuestOsMemoryMap.put("Windows Server 2003 Standard Edition(64-bit)", new MemoryValues(512l, 16*1024l)); //? //_xenServer610GuestOsMemoryMap.put("Windows Server 2008 (32-bit)", new MemoryValues(512l, 16*1024l)); //? //_xenServer610GuestOsMemoryMap.put("Windows Server 2008 (64-bit)", new MemoryValues(512l, 16*1024l)); //? - _xenServer610GuestOsMemoryMap.put("Windows Server 2008 R2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer610GuestOsMemoryMap.put("Windows Server 2008 R2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); //_xenServer610GuestOsMemoryMap.put("Windows Server 2012 (64-bit)", new MemoryValues(512l, 16*1024l)); //? - _xenServer610GuestOsMemoryMap.put("Windows Server 8 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Windows Vista (32-bit)", new MemoryValues(1024l, 4 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Windows XP SP3 (32-bit)", new MemoryValues(256l, 4 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Ubuntu 10.04 (32-bit)", new MemoryValues(128l, 512l)); - _xenServer610GuestOsMemoryMap.put("Ubuntu 10.04 (64-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer610GuestOsMemoryMap.put("Windows Server 8 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer610GuestOsMemoryMap.put("Windows Vista (32-bit)", new MemoryValues(1024l, 4 * 1024l)); + XenServer610GuestOsMemoryMap.put("Windows XP SP3 (32-bit)", new MemoryValues(256l, 4 * 1024l)); + XenServer610GuestOsMemoryMap.put("Ubuntu 10.04 (32-bit)", new MemoryValues(128l, 512l)); + XenServer610GuestOsMemoryMap.put("Ubuntu 10.04 (64-bit)", new MemoryValues(128l, 32 * 1024l)); //_xenServer610GuestOsMemoryMap.put("Ubuntu 10.10 (32-bit)", new MemoryValues(512l, 16*1024l));//? //_xenServer610GuestOsMemoryMap.put("Ubuntu 10.10 (64-bit)", new MemoryValues(512l, 16*1024l)); //? - _xenServer610GuestOsMemoryMap.put("Ubuntu 12.04 (32-bit)", new MemoryValues(128l, 32 * 1024l)); - _xenServer610GuestOsMemoryMap.put("Ubuntu 12.04 (64-bit)", new MemoryValues(128l, 128 * 1024l)); - // _xenServer610GuestOsMemoryMap.put("Other Linux (32-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer610GuestOsMemoryMap.put("Other Linux (64-bit)", new MemoryValues(512l, 16*1024l)); + XenServer610GuestOsMemoryMap.put("Ubuntu 12.04 (32-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer610GuestOsMemoryMap.put("Ubuntu 12.04 (64-bit)", new MemoryValues(128l, 128 * 1024l)); + // XenServer610GuestOsMemoryMap.put("Other Linux (32-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer610GuestOsMemoryMap.put("Other Linux (64-bit)", new MemoryValues(512l, 16*1024l)); //_xenServer610GuestOsMemoryMap.put("Other (32-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer610GuestOsMemoryMap.put("Other (64-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer610GuestOsMemoryMap.put("Other CentOS (32-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer610GuestOsMemoryMap.put("Other CentOS (64-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer610GuestOsMemoryMap.put("Other (64-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer610GuestOsMemoryMap.put("Other CentOS (32-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer610GuestOsMemoryMap.put("Other CentOS (64-bit)", new MemoryValues(512l, 16*1024l)); //_xenServer610GuestOsMemoryMap.put("Other Ubuntu (32-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer610GuestOsMemoryMap.put("Other Ubuntu (64-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer610GuestOsMemoryMap.put("Other SUSE Linux(32-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer610GuestOsMemoryMap.put("Other SUSE Linux(64-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer610GuestOsMemoryMap.put("Other PV (32-bit)", new MemoryValues(512l, 16*1024l)); - // _xenServer610GuestOsMemoryMap.put("Other PV (64-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer610GuestOsMemoryMap.put("Other Ubuntu (64-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer610GuestOsMemoryMap.put("Other SUSE Linux(32-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer610GuestOsMemoryMap.put("Other SUSE Linux(64-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer610GuestOsMemoryMap.put("Other PV (32-bit)", new MemoryValues(512l, 16*1024l)); + // XenServer610GuestOsMemoryMap.put("Other PV (64-bit)", new MemoryValues(512l, 16*1024l)); } static { - _xenServer620GuestOsMemoryMap.put("CentOS 4.5 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 4.6 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 4.7 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 4.8 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 5.0 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 5.0 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 5.1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 5.1 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 5.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 5.2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 5.3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 5.3 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 5.4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 5.4 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 5.5 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 5.5 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 5.6 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 5.6 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 5.7 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 5.7 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 5.8 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 5.8 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 5.9 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 5.9 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 6.3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 6.3 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 6.4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("CentOS 6.4 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Debian GNU/Linux 6(32-bit)", new MemoryValues(128l, 32 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Debian GNU/Linux 6(64-bit)", new MemoryValues(128l, 32 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Debian GNU/Linux 7(32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Debian GNU/Linux 7(64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.0 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.0 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.1 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.1 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.2 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.3 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.3 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.4 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.4 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.5 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.5 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.6 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.6 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.7 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.7 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.8 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.8 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.9 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.9 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 6.3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 6.3 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 6.4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 6.4 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", new MemoryValues(256l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.5 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.5 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.6 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.6 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.7 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.7 (64-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.8 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.8 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.9 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.9 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.3 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.4 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP4 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 SP1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 SP1 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 SP2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); - _xenServer620GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 SP2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 4.5 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 4.6 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 4.7 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 4.8 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 5.0 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 5.0 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 5.1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 5.1 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 5.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 5.2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 5.3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 5.3 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 5.4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 5.4 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 5.5 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 5.5 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 5.6 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 5.6 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 5.7 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 5.7 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 5.8 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 5.8 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 5.9 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 5.9 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 6.3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 6.3 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 6.4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("CentOS 6.4 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("Debian GNU/Linux 6(32-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer620GuestOsMemoryMap.put("Debian GNU/Linux 6(64-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer620GuestOsMemoryMap.put("Debian GNU/Linux 7(32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Debian GNU/Linux 7(64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.0 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.0 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.1 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.1 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.2 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.3 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.3 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.4 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.4 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.5 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.5 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.6 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.6 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.7 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.7 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.8 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.8 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.9 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 5.9 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 6.3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 6.3 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 6.4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Oracle Enterprise Linux 6.4 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", new MemoryValues(256l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.5 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.5 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.6 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.6 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.7 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.7 (64-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.8 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.8 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.9 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 5.9 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.0 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.0 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.1 (32-bit)", new MemoryValues(512l, 8 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.1 (64-bit)", new MemoryValues(512l, 32 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.3 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("Red Hat Enterprise Linux 6.4 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP3 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP4 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("SUSE Linux Enterprise Server 10 SP4 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 SP1 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 SP1 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 SP2 (32-bit)", new MemoryValues(512l, 16 * 1024l)); + XenServer620GuestOsMemoryMap.put("SUSE Linux Enterprise Server 11 SP2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Windows 7 (32-bit)", new MemoryValues(1024l, 4 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Windows 7 (64-bit)", new MemoryValues(2 * 1024l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Windows 7 SP1 (32-bit)", new MemoryValues(1024l, 4 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Windows 7 SP1 (64-bit)", new MemoryValues(2 * 1024l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Windows 8 (32-bit)", new MemoryValues(1024l, 4 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Windows 8 (64-bit)", new MemoryValues(2 * 1024l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Windows Server 2003 SP2 (32-bit)", new MemoryValues(256l, 64 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Windows Server 2003 SP2 (64-bit)", new MemoryValues(256l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Windows Server 2008 SP2 (32-bit)", new MemoryValues(512l, 64 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Windows Server 2008 SP2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Windows Server 2008 R2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Windows Server 2008 R2 SP1 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Windows Server 2012 (64-bit)", new MemoryValues(512l, 128 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Windows Vista SP2 (32-bit)", new MemoryValues(1024l, 4 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Windows XP SP3 (32-bit)", new MemoryValues(256l, 4 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Ubuntu 10.04 (32-bit)", new MemoryValues(128l, 512l)); - _xenServer620GuestOsMemoryMap.put("Ubuntu 10.04 (64-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer620GuestOsMemoryMap.put("Windows 7 (32-bit)", new MemoryValues(1024l, 4 * 1024l)); + XenServer620GuestOsMemoryMap.put("Windows 7 (64-bit)", new MemoryValues(2 * 1024l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("Windows 7 SP1 (32-bit)", new MemoryValues(1024l, 4 * 1024l)); + XenServer620GuestOsMemoryMap.put("Windows 7 SP1 (64-bit)", new MemoryValues(2 * 1024l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("Windows 8 (32-bit)", new MemoryValues(1024l, 4 * 1024l)); + XenServer620GuestOsMemoryMap.put("Windows 8 (64-bit)", new MemoryValues(2 * 1024l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("Windows Server 2003 SP2 (32-bit)", new MemoryValues(256l, 64 * 1024l)); + XenServer620GuestOsMemoryMap.put("Windows Server 2003 SP2 (64-bit)", new MemoryValues(256l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("Windows Server 2008 SP2 (32-bit)", new MemoryValues(512l, 64 * 1024l)); + XenServer620GuestOsMemoryMap.put("Windows Server 2008 SP2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("Windows Server 2008 R2 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("Windows Server 2008 R2 SP1 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("Windows Server 2012 (64-bit)", new MemoryValues(512l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("Windows Vista SP2 (32-bit)", new MemoryValues(1024l, 4 * 1024l)); + XenServer620GuestOsMemoryMap.put("Windows XP SP3 (32-bit)", new MemoryValues(256l, 4 * 1024l)); + XenServer620GuestOsMemoryMap.put("Ubuntu 10.04 (32-bit)", new MemoryValues(128l, 512l)); + XenServer620GuestOsMemoryMap.put("Ubuntu 10.04 (64-bit)", new MemoryValues(128l, 32 * 1024l)); //_xenServer620GuestOsMemoryMap.put("Ubuntu 10.10 (32-bit)", new MemoryValues(512l, 16*1024l));//? //_xenServer620GuestOsMemoryMap.put("Ubuntu 10.10 (64-bit)", new MemoryValues(512l, 16*1024l)); //? - _xenServer620GuestOsMemoryMap.put("Ubuntu 12.04 (32-bit)", new MemoryValues(128l, 32 * 1024l)); - _xenServer620GuestOsMemoryMap.put("Ubuntu 12.04 (64-bit)", new MemoryValues(128l, 128 * 1024l)); + XenServer620GuestOsMemoryMap.put("Ubuntu 12.04 (32-bit)", new MemoryValues(128l, 32 * 1024l)); + XenServer620GuestOsMemoryMap.put("Ubuntu 12.04 (64-bit)", new MemoryValues(128l, 128 * 1024l)); } public static String getXcpGuestOsType(String stdType) { - String guestOS = _xcp100GuestOsMap.get(stdType); + String guestOS = Xcp100GuestOsMap.get(stdType); if (guestOS == null) { s_logger.debug("Can't find the guest os: " + stdType + " mapping into XCP's guestOS type, start it as HVM guest"); guestOS = "Other install media"; @@ -1829,7 +1829,7 @@ public class CitrixHelper { } public static String getXcp160GuestOsType(String stdType) { - String guestOS = _xcp160GuestOsMap.get(stdType); + String guestOS = Xcp160GuestOsMap.get(stdType); if (guestOS == null) { s_logger.debug("Can't find the guest os: " + stdType + " mapping into XCP's guestOS type, start it as HVM guest"); guestOS = "Other install media"; @@ -1838,7 +1838,7 @@ public class CitrixHelper { } public static String getXenServerGuestOsType(String stdType, boolean bootFromCD) { - String guestOS = _xenServerGuestOsMap.get(stdType); + String guestOS = XenServerGuestOsMap.get(stdType); if (guestOS == null) { if (!bootFromCD) { s_logger.debug("Can't find the guest os: " + stdType + " mapping into XenServer 5.6 guestOS type, start it as HVM guest"); @@ -1852,7 +1852,7 @@ public class CitrixHelper { } public static String getXenServer56FP1GuestOsType(String stdType, boolean bootFromCD) { - String guestOS = _xenServer56FP1GuestOsMap.get(stdType); + String guestOS = XenServer56FP1GuestOsMap.get(stdType); if (guestOS == null) { if (!bootFromCD) { s_logger.debug("Can't find the guest os: " + stdType + " mapping into XenServer 5.6 FP1 guestOS type, start it as HVM guest"); @@ -1866,7 +1866,7 @@ public class CitrixHelper { } public static long getXenServer56FP1StaticMax(String stdType, boolean bootFromCD) { - MemoryValues recommendedMaxMinMemory = _xenServer56FP1GuestOsMemoryMap.get(stdType); + MemoryValues recommendedMaxMinMemory = XenServer56FP1GuestOsMemoryMap.get(stdType); if (recommendedMaxMinMemory == null) { return 0l; } @@ -1874,7 +1874,7 @@ public class CitrixHelper { } public static long getXenServer56FP1StaticMin(String stdType, boolean bootFromCD) { - MemoryValues recommendedMaxMinMemory = _xenServer56FP1GuestOsMemoryMap.get(stdType); + MemoryValues recommendedMaxMinMemory = XenServer56FP1GuestOsMemoryMap.get(stdType); if (recommendedMaxMinMemory == null) { return 0l; } @@ -1882,7 +1882,7 @@ public class CitrixHelper { } public static String getXenServer56SP2GuestOsType(String stdType, boolean bootFromCD) { - String guestOS = _xenServer56FP2GuestOsMap.get(stdType); + String guestOS = XenServer56FP2GuestOsMap.get(stdType); if (guestOS == null) { if (!bootFromCD) { s_logger.debug("Can't find the guest os: " + stdType + " mapping into XenServer 5.6 SP2 guestOS type, start it as HVM guest"); @@ -1896,7 +1896,7 @@ public class CitrixHelper { } public static long getXenServer56SP2StaticMax(String stdType, boolean bootFromCD) { - MemoryValues recommendedMaxMinMemory = _xenServer56SP2GuestOsMemoryMap.get(stdType); + MemoryValues recommendedMaxMinMemory = XenServer56SP2GuestOsMemoryMap.get(stdType); if (recommendedMaxMinMemory == null) { return 0l; } @@ -1904,7 +1904,7 @@ public class CitrixHelper { } public static long getXenServer56SP2StaticMin(String stdType, boolean bootFromCD) { - MemoryValues recommendedMaxMinMemory = _xenServer56SP2GuestOsMemoryMap.get(stdType); + MemoryValues recommendedMaxMinMemory = XenServer56SP2GuestOsMemoryMap.get(stdType); if (recommendedMaxMinMemory == null) { return 0l; } @@ -1912,7 +1912,7 @@ public class CitrixHelper { } public static String getXenServer600GuestOsType(String stdType, boolean bootFromCD) { - String guestOS = _xenServer600GuestOsMap.get(stdType); + String guestOS = XenServer600GuestOsMap.get(stdType); if (guestOS == null) { if (!bootFromCD) { s_logger.debug("Can't find the guest os: " + stdType + " mapping into XenServer 6.0.2 guestOS type, start it as HVM guest"); @@ -1927,7 +1927,7 @@ public class CitrixHelper { } public static long getXenServer600StaticMax(String stdType, boolean bootFromCD) { - MemoryValues recommendedMaxMinMemory = _xenServer600GuestOsMemoryMap.get(stdType); + MemoryValues recommendedMaxMinMemory = XenServer600GuestOsMemoryMap.get(stdType); if (recommendedMaxMinMemory == null) { return 0l; } @@ -1935,7 +1935,7 @@ public class CitrixHelper { } public static long getXenServer600StaticMin(String stdType, boolean bootFromCD) { - MemoryValues recommendedMaxMinMemory = _xenServer600GuestOsMemoryMap.get(stdType); + MemoryValues recommendedMaxMinMemory = XenServer600GuestOsMemoryMap.get(stdType); if (recommendedMaxMinMemory == null) { return 0l; } @@ -1943,7 +1943,7 @@ public class CitrixHelper { } public static String getXenServer602GuestOsType(String stdType, boolean bootFromCD) { - String guestOS = _xenServer602GuestOsMap.get(stdType); + String guestOS = XenServer602GuestOsMap.get(stdType); if (guestOS == null) { if (!bootFromCD) { s_logger.debug("Can't find the guest os: " + stdType + " mapping into XenServer 6.0.2 guestOS type, start it as HVM guest"); @@ -1958,7 +1958,7 @@ public class CitrixHelper { } public static long getXenServer602StaticMax(String stdType, boolean bootFromCD) { - MemoryValues recommendedMaxMinMemory = _xenServer602GuestOsMemoryMap.get(stdType); + MemoryValues recommendedMaxMinMemory = XenServer602GuestOsMemoryMap.get(stdType); if (recommendedMaxMinMemory == null) { return 0l; } @@ -1966,7 +1966,7 @@ public class CitrixHelper { } public static long getXenServer602StaticMin(String stdType, boolean bootFromCD) { - MemoryValues recommendedMaxMinMemory = _xenServer602GuestOsMemoryMap.get(stdType); + MemoryValues recommendedMaxMinMemory = XenServer602GuestOsMemoryMap.get(stdType); if (recommendedMaxMinMemory == null) { return 0l; } @@ -1974,7 +1974,7 @@ public class CitrixHelper { } public static String getXenServer610GuestOsType(String stdType, boolean bootFromCD) { - String guestOS = _xenServer610GuestOsMap.get(stdType); + String guestOS = XenServer610GuestOsMap.get(stdType); if (guestOS == null) { if (!bootFromCD) { s_logger.debug("Can't find the guest os: " + stdType + " mapping into XenServer 6.1.0 guestOS type, start it as HVM guest"); @@ -1988,7 +1988,7 @@ public class CitrixHelper { } public static long getXenServer610StaticMax(String stdType, boolean bootFromCD) { - MemoryValues recommendedMaxMinMemory = _xenServer610GuestOsMemoryMap.get(stdType); + MemoryValues recommendedMaxMinMemory = XenServer610GuestOsMemoryMap.get(stdType); if (recommendedMaxMinMemory == null) { return 0l; } @@ -1996,7 +1996,7 @@ public class CitrixHelper { } public static long getXenServer610StaticMin(String stdType, boolean bootFromCD) { - MemoryValues recommendedMaxMinMemory = _xenServer610GuestOsMemoryMap.get(stdType); + MemoryValues recommendedMaxMinMemory = XenServer610GuestOsMemoryMap.get(stdType); if (recommendedMaxMinMemory == null) { return 0l; } @@ -2004,7 +2004,7 @@ public class CitrixHelper { } public static String getXenServer620GuestOsType(String stdType, boolean bootFromCD) { - String guestOS = _xenServer620GuestOsMap.get(stdType); + String guestOS = XenServer620GuestOsMap.get(stdType); if (guestOS == null) { if (!bootFromCD) { s_logger.debug("Can't find the guest os: " + stdType + " mapping into XenServer 6.2.0 guestOS type, start it as HVM guest"); @@ -2018,7 +2018,7 @@ public class CitrixHelper { } public static long getXenServer620StaticMax(String stdType, boolean bootFromCD) { - MemoryValues recommendedMaxMinMemory = _xenServer620GuestOsMemoryMap.get(stdType); + MemoryValues recommendedMaxMinMemory = XenServer620GuestOsMemoryMap.get(stdType); if (recommendedMaxMinMemory == null) { return 0l; } @@ -2026,7 +2026,7 @@ public class CitrixHelper { } public static long getXenServer620StaticMin(String stdType, boolean bootFromCD) { - MemoryValues recommendedMaxMinMemory = _xenServer620GuestOsMemoryMap.get(stdType); + MemoryValues recommendedMaxMinMemory = XenServer620GuestOsMemoryMap.get(stdType); if (recommendedMaxMinMemory == null) { return 0l; } diff --git a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java index 67b119bce7f..200a72ff219 100644 --- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java +++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java @@ -16,9 +16,6 @@ // under the License. package com.cloud.hypervisor.xen.resource; -import static com.cloud.utils.ReflectUtil.flattenProperties; -import static com.google.common.collect.Lists.newArrayList; - import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; @@ -31,7 +28,6 @@ import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; -import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; @@ -49,7 +45,6 @@ import javax.ejb.Local; import javax.naming.ConfigurationException; import javax.xml.parsers.DocumentBuilderFactory; -import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; import org.apache.xmlrpc.XmlRpcException; import org.w3c.dom.Document; @@ -57,7 +52,6 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; -import com.google.gson.Gson; import com.trilead.ssh2.SCPClient; import com.xensource.xenapi.Bond; import com.xensource.xenapi.Connection; @@ -68,20 +62,12 @@ import com.xensource.xenapi.HostMetrics; import com.xensource.xenapi.Network; import com.xensource.xenapi.PBD; import com.xensource.xenapi.PIF; -import com.xensource.xenapi.PIF.Record; import com.xensource.xenapi.Pool; import com.xensource.xenapi.SR; import com.xensource.xenapi.Session; import com.xensource.xenapi.Task; import com.xensource.xenapi.Types; -import com.xensource.xenapi.Types.BadAsyncResult; import com.xensource.xenapi.Types.BadServerResponse; -import com.xensource.xenapi.Types.ConsoleProtocol; -import com.xensource.xenapi.Types.IpConfigurationMode; -import com.xensource.xenapi.Types.OperationNotAllowed; -import com.xensource.xenapi.Types.SrFull; -import com.xensource.xenapi.Types.VbdType; -import com.xensource.xenapi.Types.VmBadPowerState; import com.xensource.xenapi.Types.VmPowerState; import com.xensource.xenapi.Types.XenAPIException; import com.xensource.xenapi.VBD; @@ -102,37 +88,24 @@ import com.cloud.agent.api.Answer; import com.cloud.agent.api.AttachIsoCommand; import com.cloud.agent.api.AttachVolumeAnswer; import com.cloud.agent.api.AttachVolumeCommand; -import com.cloud.agent.api.BackupSnapshotAnswer; -import com.cloud.agent.api.BackupSnapshotCommand; -import com.cloud.agent.api.BumpUpPriorityCommand; import com.cloud.agent.api.CheckHealthAnswer; import com.cloud.agent.api.CheckHealthCommand; import com.cloud.agent.api.CheckNetworkAnswer; import com.cloud.agent.api.CheckNetworkCommand; import com.cloud.agent.api.CheckOnHostAnswer; import com.cloud.agent.api.CheckOnHostCommand; -import com.cloud.agent.api.CheckRouterAnswer; -import com.cloud.agent.api.CheckRouterCommand; -import com.cloud.agent.api.CheckS2SVpnConnectionsAnswer; -import com.cloud.agent.api.CheckS2SVpnConnectionsCommand; import com.cloud.agent.api.CheckVirtualMachineAnswer; import com.cloud.agent.api.CheckVirtualMachineCommand; import com.cloud.agent.api.CleanupNetworkRulesCmd; import com.cloud.agent.api.ClusterSyncAnswer; import com.cloud.agent.api.ClusterSyncCommand; import com.cloud.agent.api.Command; -import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand; -import com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand; import com.cloud.agent.api.CreateStoragePoolCommand; import com.cloud.agent.api.CreateVMSnapshotAnswer; import com.cloud.agent.api.CreateVMSnapshotCommand; -import com.cloud.agent.api.CreateVolumeFromSnapshotAnswer; -import com.cloud.agent.api.CreateVolumeFromSnapshotCommand; import com.cloud.agent.api.DeleteStoragePoolCommand; import com.cloud.agent.api.DeleteVMSnapshotAnswer; import com.cloud.agent.api.DeleteVMSnapshotCommand; -import com.cloud.agent.api.GetDomRVersionAnswer; -import com.cloud.agent.api.GetDomRVersionCmd; import com.cloud.agent.api.GetHostStatsAnswer; import com.cloud.agent.api.GetHostStatsCommand; import com.cloud.agent.api.GetStorageStatsAnswer; @@ -147,8 +120,6 @@ import com.cloud.agent.api.HostStatsEntry; import com.cloud.agent.api.HostVmStateReportEntry; import com.cloud.agent.api.MaintainAnswer; import com.cloud.agent.api.MaintainCommand; -import com.cloud.agent.api.ManageSnapshotAnswer; -import com.cloud.agent.api.ManageSnapshotCommand; import com.cloud.agent.api.MigrateAnswer; import com.cloud.agent.api.MigrateCommand; import com.cloud.agent.api.ModifySshKeysCommand; @@ -156,21 +127,20 @@ import com.cloud.agent.api.ModifyStoragePoolAnswer; import com.cloud.agent.api.ModifyStoragePoolCommand; import com.cloud.agent.api.NetworkRulesSystemVmCommand; import com.cloud.agent.api.NetworkRulesVmSecondaryIpCommand; -import com.cloud.agent.api.OvsCreateGreTunnelCommand; import com.cloud.agent.api.OvsCreateGreTunnelAnswer; -import com.cloud.agent.api.OvsCreateTunnelCommand; -import com.cloud.agent.api.OvsDestroyTunnelCommand; -import com.cloud.agent.api.OvsSetupBridgeCommand; -import com.cloud.agent.api.OvsDestroyBridgeCommand; +import com.cloud.agent.api.OvsCreateGreTunnelCommand; import com.cloud.agent.api.OvsCreateTunnelAnswer; +import com.cloud.agent.api.OvsCreateTunnelCommand; import com.cloud.agent.api.OvsDeleteFlowCommand; -import com.cloud.agent.api.OvsSetTagAndFlowAnswer; +import com.cloud.agent.api.OvsDestroyBridgeCommand; +import com.cloud.agent.api.OvsDestroyTunnelCommand; import com.cloud.agent.api.OvsFetchInterfaceAnswer; -import com.cloud.agent.api.OvsSetTagAndFlowCommand; import com.cloud.agent.api.OvsFetchInterfaceCommand; +import com.cloud.agent.api.OvsSetTagAndFlowAnswer; +import com.cloud.agent.api.OvsSetTagAndFlowCommand; +import com.cloud.agent.api.OvsSetupBridgeCommand; import com.cloud.agent.api.PerformanceMonitorAnswer; import com.cloud.agent.api.PerformanceMonitorCommand; - import com.cloud.agent.api.PingCommand; import com.cloud.agent.api.PingRoutingCommand; import com.cloud.agent.api.PingRoutingWithNwGroupsCommand; @@ -195,7 +165,6 @@ import com.cloud.agent.api.SecurityGroupRuleAnswer; import com.cloud.agent.api.SecurityGroupRulesCmd; import com.cloud.agent.api.SetupAnswer; import com.cloud.agent.api.SetupCommand; -import com.cloud.agent.api.SetupGuestNetworkAnswer; import com.cloud.agent.api.SetupGuestNetworkCommand; import com.cloud.agent.api.StartAnswer; import com.cloud.agent.api.StartCommand; @@ -215,40 +184,13 @@ import com.cloud.agent.api.check.CheckSshCommand; import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand; import com.cloud.agent.api.proxy.ConsoleProxyLoadAnswer; import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand; -import com.cloud.agent.api.routing.CreateIpAliasCommand; -import com.cloud.agent.api.routing.DeleteIpAliasCommand; -import com.cloud.agent.api.routing.DhcpEntryCommand; -import com.cloud.agent.api.routing.DnsMasqConfigCommand; -import com.cloud.agent.api.routing.IpAliasTO; -import com.cloud.agent.api.routing.IpAssocAnswer; import com.cloud.agent.api.routing.IpAssocCommand; import com.cloud.agent.api.routing.IpAssocVpcCommand; -import com.cloud.agent.api.routing.LoadBalancerConfigCommand; import com.cloud.agent.api.routing.NetworkElementCommand; -import com.cloud.agent.api.routing.RemoteAccessVpnCfgCommand; -import com.cloud.agent.api.routing.SavePasswordCommand; -import com.cloud.agent.api.routing.SetFirewallRulesAnswer; -import com.cloud.agent.api.routing.SetFirewallRulesCommand; -import com.cloud.agent.api.routing.SetMonitorServiceCommand; -import com.cloud.agent.api.routing.SetNetworkACLAnswer; import com.cloud.agent.api.routing.SetNetworkACLCommand; -import com.cloud.agent.api.routing.SetPortForwardingRulesAnswer; -import com.cloud.agent.api.routing.SetPortForwardingRulesCommand; -import com.cloud.agent.api.routing.SetPortForwardingRulesVpcCommand; -import com.cloud.agent.api.routing.SetSourceNatAnswer; import com.cloud.agent.api.routing.SetSourceNatCommand; -import com.cloud.agent.api.routing.SetStaticNatRulesAnswer; -import com.cloud.agent.api.routing.SetStaticNatRulesCommand; -import com.cloud.agent.api.routing.SetStaticRouteAnswer; -import com.cloud.agent.api.routing.SetStaticRouteCommand; -import com.cloud.agent.api.routing.Site2SiteVpnCfgCommand; -import com.cloud.agent.api.routing.VmDataCommand; -import com.cloud.agent.api.routing.VpnUsersCfgCommand; -import com.cloud.agent.api.storage.CopyVolumeAnswer; -import com.cloud.agent.api.storage.CopyVolumeCommand; import com.cloud.agent.api.storage.CreateAnswer; import com.cloud.agent.api.storage.CreateCommand; -import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer; import com.cloud.agent.api.storage.DestroyCommand; import com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer; import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand; @@ -256,34 +198,26 @@ import com.cloud.agent.api.storage.ResizeVolumeAnswer; import com.cloud.agent.api.storage.ResizeVolumeCommand; import com.cloud.agent.api.to.DataStoreTO; import com.cloud.agent.api.to.DataTO; -import com.cloud.agent.api.to.DhcpTO; import com.cloud.agent.api.to.DiskTO; -import com.cloud.agent.api.to.FirewallRuleTO; import com.cloud.agent.api.to.IpAddressTO; import com.cloud.agent.api.to.NfsTO; import com.cloud.agent.api.to.NicTO; -import com.cloud.agent.api.to.PortForwardingRuleTO; -import com.cloud.agent.api.to.S3TO; -import com.cloud.agent.api.to.StaticNatRuleTO; import com.cloud.agent.api.to.StorageFilerTO; -import com.cloud.agent.api.to.SwiftTO; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.agent.api.to.VolumeTO; +import com.cloud.agent.resource.virtualnetwork.VirtualRouterDeployer; +import com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource; import com.cloud.exception.InternalErrorException; import com.cloud.host.Host.Type; import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.network.HAProxyConfigurator; -import com.cloud.network.LoadBalancerConfigurator; import com.cloud.network.Networks; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.IsolationType; import com.cloud.network.Networks.TrafficType; import com.cloud.network.PhysicalNetworkSetupInfo; -import com.cloud.network.rules.FirewallRule; import com.cloud.resource.ServerResource; import com.cloud.resource.hypervisor.HypervisorResource; import com.cloud.storage.Storage; -import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.Volume; import com.cloud.storage.VolumeVO; @@ -291,21 +225,20 @@ import com.cloud.storage.resource.StorageSubsystemCommandHandler; import com.cloud.storage.resource.StorageSubsystemCommandHandlerBase; import com.cloud.storage.template.TemplateProp; import com.cloud.template.VirtualMachineTemplate.BootloaderType; +import com.cloud.utils.ExecutionResult; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; -import com.cloud.utils.S3Utils; import com.cloud.utils.StringUtils; import com.cloud.utils.Ternary; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.NetUtils; -import com.cloud.utils.StringUtils; +import com.cloud.utils.ssh.SSHCmdHelper; import com.cloud.vm.DiskProfile; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine.PowerState; import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.snapshot.VMSnapshot; -import com.cloud.utils.ssh.SSHCmdHelper; /** * CitrixResourceBase encapsulates the calls to the XenServer Xapi process @@ -320,9 +253,9 @@ import com.cloud.utils.ssh.SSHCmdHelper; * */ @Local(value = ServerResource.class) -public abstract class CitrixResourceBase implements ServerResource, HypervisorResource { +public abstract class CitrixResourceBase implements ServerResource, HypervisorResource, VirtualRouterDeployer { private static final Logger s_logger = Logger.getLogger(CitrixResourceBase.class); - protected static final XenServerConnectionPool _connPool = XenServerConnectionPool.getInstance(); + protected static final XenServerConnectionPool ConnPool = XenServerConnectionPool.getInstance(); protected String _name; protected String _username; protected Queue _password = new LinkedList(); @@ -341,7 +274,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe protected int _wait; protected int _migratewait; protected String _instance; //instance name (default is usually "VM") - static final Random _rand = new Random(System.currentTimeMillis()); + static final Random Rand = new Random(System.currentTimeMillis()); protected boolean _securityGroupEnabled; protected IAgentControl _agentControl; @@ -355,8 +288,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe protected int _pollingIntervalInSeconds = 60; //Hypervisor specific params with generic value, may need to be overridden for specific versions - long _xs_memory_used = 128 * 1024 * 1024L; // xen hypervisor used 128 M - double _xs_virtualization_factor = 63.0 / 64.0; // 1 - virtualization overhead + long _xsMemoryUsed = 128 * 1024 * 1024L; // xen hypervisor used 128 M + double _xsVirtualizationFactor = 63.0 / 64.0; // 1 - virtualization overhead //static min values for guests on xen private static final long mem_128m = 134217728L; @@ -367,6 +300,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe protected StorageSubsystemCommandHandler storageHandler; protected int _maxNics = 7; + protected VirtualRoutingResource _vrResource; + public enum SRType { NFS, LVM, ISCSI, ISO, LVMOISCSI, LVMOHBA, EXT, FILE; @@ -457,23 +392,12 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } protected boolean pingXenServer() { - Session slaveSession = null; - Connection slaveConn = null; + Connection conn = getConnection(); try { - URL slaveUrl = null; - slaveUrl = _connPool.getURL(_host.ip); - slaveConn = new Connection(slaveUrl, 10); - slaveSession = _connPool.slaveLocalLoginWithPassword(slaveConn, _username, _password); + callHostPlugin(conn, "echo", "main"); return true; } catch (Exception e) { - } finally { - if (slaveSession != null) { - try { - Session.localLogout(slaveConn); - } catch (Exception e) { - } - slaveConn.dispose(); - } + s_logger.debug("cannot ping host " + _host.ip + " due to " + e.toString(), e); } return false; } @@ -487,30 +411,12 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe Class clazz = cmd.getClass(); if (clazz == CreateCommand.class) { return execute((CreateCommand)cmd); - } else if (clazz == SetPortForwardingRulesCommand.class) { - return execute((SetPortForwardingRulesCommand)cmd); - } else if (clazz == SetStaticNatRulesCommand.class) { - return execute((SetStaticNatRulesCommand)cmd); - } else if (clazz == LoadBalancerConfigCommand.class) { - return execute((LoadBalancerConfigCommand)cmd); - } else if (clazz == IpAssocCommand.class) { - return execute((IpAssocCommand)cmd); + } else if (cmd instanceof NetworkElementCommand) { + return _vrResource.executeRequest(cmd); } else if (clazz == CheckConsoleProxyLoadCommand.class) { return execute((CheckConsoleProxyLoadCommand)cmd); } else if (clazz == WatchConsoleProxyLoadCommand.class) { return execute((WatchConsoleProxyLoadCommand)cmd); - } else if (clazz == SavePasswordCommand.class) { - return execute((SavePasswordCommand)cmd); - } else if (clazz == DhcpEntryCommand.class) { - return execute((DhcpEntryCommand)cmd); - } else if (clazz == CreateIpAliasCommand.class) { - return execute((CreateIpAliasCommand)cmd); - } else if (clazz == DnsMasqConfigCommand.class) { - return execute((DnsMasqConfigCommand)cmd); - } else if (clazz == DeleteIpAliasCommand.class) { - return execute((DeleteIpAliasCommand)cmd); - } else if (clazz == VmDataCommand.class) { - return execute((VmDataCommand)cmd); } else if (clazz == ReadyCommand.class) { return execute((ReadyCommand)cmd); } else if (clazz == GetHostStatsCommand.class) { @@ -540,25 +446,13 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } else if (clazz == ModifyStoragePoolCommand.class) { return execute((ModifyStoragePoolCommand)cmd); } else if (clazz == DeleteStoragePoolCommand.class) { - return execute((DeleteStoragePoolCommand)cmd); - } else if (clazz == CopyVolumeCommand.class) { - return execute((CopyVolumeCommand)cmd); - } else if (clazz == ResizeVolumeCommand.class) { - return execute((ResizeVolumeCommand)cmd); + return execute((DeleteStoragePoolCommand) cmd); + }else if (clazz == ResizeVolumeCommand.class) { + return execute((ResizeVolumeCommand) cmd); } else if (clazz == AttachVolumeCommand.class) { return execute((AttachVolumeCommand)cmd); } else if (clazz == AttachIsoCommand.class) { - return execute((AttachIsoCommand)cmd); - } else if (clazz == ManageSnapshotCommand.class) { - return execute((ManageSnapshotCommand)cmd); - } else if (clazz == BackupSnapshotCommand.class) { - return execute((BackupSnapshotCommand)cmd); - } else if (clazz == CreateVolumeFromSnapshotCommand.class) { - return execute((CreateVolumeFromSnapshotCommand)cmd); - } else if (clazz == CreatePrivateTemplateFromVolumeCommand.class) { - return execute((CreatePrivateTemplateFromVolumeCommand)cmd); - } else if (clazz == CreatePrivateTemplateFromSnapshotCommand.class) { - return execute((CreatePrivateTemplateFromSnapshotCommand)cmd); + return execute((AttachIsoCommand) cmd); } else if (clazz == UpgradeSnapshotCommand.class) { return execute((UpgradeSnapshotCommand)cmd); } else if (clazz == GetStorageStatsCommand.class) { @@ -581,10 +475,6 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe return execute((PoolEjectCommand)cmd); } else if (clazz == StartCommand.class) { return execute((StartCommand)cmd); - } else if (clazz == RemoteAccessVpnCfgCommand.class) { - return execute((RemoteAccessVpnCfgCommand)cmd); - } else if (clazz == VpnUsersCfgCommand.class) { - return execute((VpnUsersCfgCommand)cmd); } else if (clazz == CheckSshCommand.class) { return execute((CheckSshCommand)cmd); } else if (clazz == SecurityGroupRulesCmd.class) { @@ -611,135 +501,153 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe return execute((OvsDestroyTunnelCommand)cmd); } else if (clazz == UpdateHostPasswordCommand.class) { return execute((UpdateHostPasswordCommand)cmd); - } else if (cmd instanceof CheckRouterCommand) { - return execute((CheckRouterCommand)cmd); - } else if (cmd instanceof SetFirewallRulesCommand) { - return execute((SetFirewallRulesCommand)cmd); - } else if (cmd instanceof BumpUpPriorityCommand) { - return execute((BumpUpPriorityCommand)cmd); } else if (cmd instanceof ClusterSyncCommand) { return execute((ClusterSyncCommand)cmd); - } else if (cmd instanceof GetDomRVersionCmd) { - return execute((GetDomRVersionCmd)cmd); } else if (clazz == CheckNetworkCommand.class) { return execute((CheckNetworkCommand)cmd); - } else if (clazz == SetupGuestNetworkCommand.class) { - return execute((SetupGuestNetworkCommand)cmd); } else if (clazz == PlugNicCommand.class) { return execute((PlugNicCommand)cmd); } else if (clazz == UnPlugNicCommand.class) { return execute((UnPlugNicCommand)cmd); - } else if (clazz == IpAssocVpcCommand.class) { - return execute((IpAssocVpcCommand)cmd); - } else if (clazz == SetSourceNatCommand.class) { - return execute((SetSourceNatCommand)cmd); - } else if (clazz == SetNetworkACLCommand.class) { - return execute((SetNetworkACLCommand)cmd); - } else if (clazz == SetPortForwardingRulesVpcCommand.class) { - return execute((SetPortForwardingRulesVpcCommand)cmd); - } else if (clazz == SetStaticRouteCommand.class) { - return execute((SetStaticRouteCommand)cmd); - } else if (clazz == Site2SiteVpnCfgCommand.class) { - return execute((Site2SiteVpnCfgCommand)cmd); - } else if (clazz == CheckS2SVpnConnectionsCommand.class) { - return execute((CheckS2SVpnConnectionsCommand)cmd); } else if (cmd instanceof StorageSubSystemCommand) { - return storageHandler.handleStorageCommands((StorageSubSystemCommand)cmd); + return storageHandler.handleStorageCommands((StorageSubSystemCommand) cmd); } else if (clazz == CreateVMSnapshotCommand.class) { - return execute((CreateVMSnapshotCommand)cmd); + return execute((CreateVMSnapshotCommand) cmd); } else if (clazz == DeleteVMSnapshotCommand.class) { - return execute((DeleteVMSnapshotCommand)cmd); + return execute((DeleteVMSnapshotCommand) cmd); } else if (clazz == RevertToVMSnapshotCommand.class) { - return execute((RevertToVMSnapshotCommand)cmd); + return execute((RevertToVMSnapshotCommand) cmd); } else if (clazz == NetworkRulesVmSecondaryIpCommand.class) { - return execute((NetworkRulesVmSecondaryIpCommand)cmd); + return execute((NetworkRulesVmSecondaryIpCommand) cmd); } else if (clazz == ScaleVmCommand.class) { return execute((ScaleVmCommand)cmd); } else if (clazz == PvlanSetupCommand.class) { return execute((PvlanSetupCommand)cmd); - } else if (clazz == SetMonitorServiceCommand.class) { - return execute((SetMonitorServiceCommand)cmd); - } else if (clazz == PerformanceMonitorCommand.class) { - return execute((PerformanceMonitorCommand) cmd); + } else if (clazz == PerformanceMonitorCommand.class) { + return execute((PerformanceMonitorCommand)cmd); } else { return Answer.createUnsupportedCommandAnswer(cmd); } } - private Answer execute(PerformanceMonitorCommand cmd) { - Connection conn = getConnection(); - String perfMon = getPerfMon(conn, cmd.getParams(), cmd.getWait()); - if (perfMon == null) { - return new PerformanceMonitorAnswer(cmd, false, perfMon); - } else - return new PerformanceMonitorAnswer(cmd, true, perfMon); - } + @Override + public ExecutionResult executeInVR(String routerIP, String script, String args) { + Connection conn = getConnection(); + String rc = callHostPlugin(conn, "vmops", "routerProxy", "args", script + " " + routerIP + " " + args); + // Fail case would be start with "fail#" + return new ExecutionResult(rc.startsWith("succ#"), rc.substring(5)); + } - private String getPerfMon(Connection conn, Map params, - int wait) { - String result = null; - try { - result = callHostPluginAsync(conn, "vmopspremium", "asmonitor", 60, - params); - if (result != null) - return result; - } catch (Exception e) { - s_logger.error("Can not get performance monitor for AS due to ", e); - } - return null; - } + @Override + public ExecutionResult createFileInVR(String routerIp, String path, String filename, String content) { + Connection conn = getConnection(); + String rc = callHostPlugin(conn, "vmops", "createFileInDomr", "domrip", routerIp, "filepath", path + filename, "filecontents", content); + // Fail case would be start with "fail#" + return new ExecutionResult(rc.startsWith("succ#"), rc.substring(5)); + } - protected String callHostPluginAsync(Connection conn, String plugin, - String cmd, int wait, Map params) { - int timeout = wait * 1000; - Map args = new HashMap(); - Task task = null; - try { - for (String key : params.keySet()) { - args.put(key, params.get(key)); - } - if (s_logger.isTraceEnabled()) { - s_logger.trace("callHostPlugin executing for command " + cmd - + " with " + getArgsString(args)); - } - Host host = Host.getByUuid(conn, _host.uuid); - task = host.callPluginAsync(conn, plugin, cmd, args); - // poll every 1 seconds - waitForTask(conn, task, 1000, timeout); - checkForSuccess(conn, task); - String result = task.getResult(conn); - if (s_logger.isTraceEnabled()) { - s_logger.trace("callHostPlugin Result: " + result); - } - return result.replace("", "").replace("", "") - .replace("\n", ""); - } catch (Types.HandleInvalid e) { - s_logger.warn("callHostPlugin failed for cmd: " + cmd - + " with args " + getArgsString(args) - + " due to HandleInvalid clazz:" + e.clazz + ", handle:" - + e.handle); - } catch (XenAPIException e) { - s_logger.warn( - "callHostPlugin failed for cmd: " + cmd + " with args " - + getArgsString(args) + " due to " + e.toString(), - e); - } catch (XmlRpcException e) { - s_logger.warn( - "callHostPlugin failed for cmd: " + cmd + " with args " - + getArgsString(args) + " due to " + e.getMessage(), - e); - } finally { - if (task != null) { - try { - task.destroy(conn); - } catch (Exception e1) { - s_logger.warn("unable to destroy task(" + task.toString() - + ") on host(" + _host.uuid + ") due to ", e1); - } - } - } - return null; - } + @Override + public ExecutionResult prepareCommand(NetworkElementCommand cmd) { + //Update IP used to access router + cmd.setRouterAccessIp(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP)); + assert cmd.getRouterAccessIp() != null; + + if (cmd instanceof IpAssocVpcCommand) { + return prepareNetworkElementCommand((IpAssocVpcCommand)cmd); + } else if (cmd instanceof IpAssocCommand) { + return prepareNetworkElementCommand((IpAssocCommand)cmd); + } else if (cmd instanceof SetupGuestNetworkCommand) { + return prepareNetworkElementCommand((SetupGuestNetworkCommand)cmd); + } else if (cmd instanceof SetSourceNatCommand) { + return prepareNetworkElementCommand((SetSourceNatCommand)cmd); + } else if (cmd instanceof SetNetworkACLCommand) { + return prepareNetworkElementCommand((SetNetworkACLCommand)cmd); + } + return new ExecutionResult(true, null); + } + + @Override + public ExecutionResult cleanupCommand(NetworkElementCommand cmd) { + if (cmd instanceof IpAssocCommand && !(cmd instanceof IpAssocVpcCommand)) { + cleanupNetworkElementCommand((IpAssocCommand)cmd); + } + return new ExecutionResult(true, null); + } + + private Answer execute(PerformanceMonitorCommand cmd) { + Connection conn = getConnection(); + String perfMon = getPerfMon(conn, cmd.getParams(), cmd.getWait()); + if (perfMon == null) { + return new PerformanceMonitorAnswer(cmd, false, perfMon); + } else + return new PerformanceMonitorAnswer(cmd, true, perfMon); + } + + private String getPerfMon(Connection conn, Map params, + int wait) { + String result = null; + try { + result = callHostPluginAsync(conn, "vmopspremium", "asmonitor", 60, + params); + if (result != null) + return result; + } catch (Exception e) { + s_logger.error("Can not get performance monitor for AS due to ", e); + } + return null; + } + + protected String callHostPluginAsync(Connection conn, String plugin, + String cmd, int wait, Map params) { + int timeout = wait * 1000; + Map args = new HashMap(); + Task task = null; + try { + for (String key : params.keySet()) { + args.put(key, params.get(key)); + } + if (s_logger.isTraceEnabled()) { + s_logger.trace("callHostPlugin executing for command " + cmd + + " with " + getArgsString(args)); + } + Host host = Host.getByUuid(conn, _host.uuid); + task = host.callPluginAsync(conn, plugin, cmd, args); + // poll every 1 seconds + waitForTask(conn, task, 1000, timeout); + checkForSuccess(conn, task); + String result = task.getResult(conn); + if (s_logger.isTraceEnabled()) { + s_logger.trace("callHostPlugin Result: " + result); + } + return result.replace("", "").replace("", "") + .replace("\n", ""); + } catch (Types.HandleInvalid e) { + s_logger.warn("callHostPlugin failed for cmd: " + cmd + + " with args " + getArgsString(args) + + " due to HandleInvalid clazz:" + e.clazz + ", handle:" + + e.handle); + } catch (XenAPIException e) { + s_logger.warn( + "callHostPlugin failed for cmd: " + cmd + " with args " + + getArgsString(args) + " due to " + e.toString(), + e); + } catch (XmlRpcException e) { + s_logger.warn( + "callHostPlugin failed for cmd: " + cmd + " with args " + + getArgsString(args) + " due to " + e.getMessage(), + e); + } finally { + if (task != null) { + try { + task.destroy(conn); + } catch (Exception e1) { + s_logger.warn("unable to destroy task(" + task.toString() + + ") on host(" + _host.uuid + ") due to ", e1); + } + } + } + return null; + } protected void scaleVM(Connection conn, VM vm, VirtualMachineTO vmSpec, Host host) throws XenAPIException, XmlRpcException { @@ -749,7 +657,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe Long newDynamicMemoryMax = vmSpec.getMaxRam(); if (staticMemoryMin > newDynamicMemoryMin || newDynamicMemoryMax > staticMemoryMax) { throw new CloudRuntimeException("Cannot scale up the vm because of memory constraint violation: " + "0 <= memory-static-min(" + staticMemoryMin + - ") <= memory-dynamic-min(" + newDynamicMemoryMin + ") <= memory-dynamic-max(" + newDynamicMemoryMax + ") <= memory-static-max(" + staticMemoryMax + ")"); + ") <= memory-dynamic-min(" + newDynamicMemoryMin + ") <= memory-dynamic-max(" + newDynamicMemoryMax + ") <= memory-static-max(" + staticMemoryMax + ")"); } vm.setMemoryDynamicRange(conn, newDynamicMemoryMin, newDynamicMemoryMax); @@ -769,7 +677,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe if (vmSpec.getLimitCpuUse()) { long utilization = 0; // max CPU cap, default is unlimited - utilization = (int) ((vmSpec.getMaxSpeed() * 0.99 * vmSpec.getCpus()) / _host.speed * 100); + utilization = (int)((vmSpec.getMaxSpeed() * 0.99 * vmSpec.getCpus()) / _host.speed * 100); //vm.addToVCPUsParamsLive(conn, "cap", Long.toString(utilization)); currently xenserver doesnot support Xapi to add VCPUs params live. callHostPlugin(conn, "vmops", "add_to_VCPUs_params_live", "key", "cap", "value", Long.toString(utilization), "vmname", vmSpec.getName()); } @@ -789,7 +697,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe // If DMC is not enable then don't execute this command. if (!isDmcEnabled(conn, host)) { throw new CloudRuntimeException("Unable to scale the vm: " + vmName + " as DMC - Dynamic memory control is not enabled for the XenServer:" + _host.uuid + - " ,check your license and hypervisor version."); + " ,check your license and hypervisor version."); } // stop vm which is running on this host or is in halted state @@ -799,7 +707,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe VM.Record vmr = vm.getRecord(conn); if ((vmr.powerState == VmPowerState.HALTED) || - (vmr.powerState == VmPowerState.RUNNING && !isRefNull(vmr.residentOn) && !vmr.residentOn.getUuid(conn).equals(_host.uuid))) { + (vmr.powerState == VmPowerState.RUNNING && !isRefNull(vmr.residentOn) && !vmr.residentOn.getUuid(conn).equals(_host.uuid))) { iter.remove(); } } @@ -906,11 +814,11 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } private String revertToSnapshot(Connection conn, VM vmSnapshot, String vmName, String oldVmUuid, Boolean snapshotMemory, String hostUUID) throws XenAPIException, - XmlRpcException { + XmlRpcException { String results = - callHostPluginAsync(conn, "vmopsSnapshot", "revert_memory_snapshot", 10 * 60 * 1000, "snapshotUUID", vmSnapshot.getUuid(conn), "vmName", vmName, "oldVmUuid", - oldVmUuid, "snapshotMemory", snapshotMemory.toString(), "hostUUID", hostUUID); + callHostPluginAsync(conn, "vmopsSnapshot", "revert_memory_snapshot", 10 * 60 * 1000, "snapshotUUID", vmSnapshot.getUuid(conn), "vmName", vmName, "oldVmUuid", + oldVmUuid, "snapshotMemory", snapshotMemory.toString(), "hostUUID", hostUUID); String errMsg = null; if (results == null || results.isEmpty()) { errMsg = "revert_memory_snapshot return null"; @@ -1016,7 +924,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe vswitchNw = networks.iterator().next(); } if (!is_xcp()) - enableXenServerNetwork(conn, vswitchNw, "vswitch", "vswitch network"); + enableXenServerNetwork(conn, vswitchNw, "vswitch", "vswitch network"); _host.vswitchNetwork = vswitchNw; } return _host.vswitchNetwork; @@ -1051,7 +959,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe nw = Network.create(conn, rec); // Plug dom0 vif only when creating network if (!is_xcp()) - enableXenServerNetwork(conn, nw, nwName, "tunnel network for account " + key); + enableXenServerNetwork(conn, nw, nwName, "tunnel network for account " + key); s_logger.debug("### Xen Server network for tunnels created:" + nwName); } else { nw = networks.iterator().next(); @@ -1087,8 +995,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } if (!configured) { // Plug dom0 vif only if not done before for network and host - if (!is_xcp()) - enableXenServerNetwork(conn, nw, nwName, "tunnel network for account " + key); + if (!is_xcp()) + enableXenServerNetwork(conn, nw, nwName, "tunnel network for account " + key); String result = callHostPlugin(conn, "ovstunnel", "setup_ovs_bridge", "bridge", bridge, "key", String.valueOf(key), "xs_nw_uuid", nw.getUuid(conn), @@ -1313,6 +1221,10 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } if (vdi != null) { + if ("detached".equals(vdi.getNameLabel(conn))) { + vdi.setNameLabel(conn, vmName + "-DATA"); + } + Map smConfig = vdi.getSmConfig(conn); for (String key : smConfig.keySet()) { if (key.startsWith("host_")) { @@ -1427,7 +1339,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe if (vmSpec.getLimitCpuUse()) { // CPU cap is per VM, so need to assign cap based on the number of vcpus - utilization = (int) ((vmSpec.getMaxSpeed() * 0.99 * vmSpec.getCpus()) / _host.speed * 100); + utilization = (int)((vmSpec.getMaxSpeed() * 0.99 * vmSpec.getCpus()) / _host.speed * 100); } vcpuParams.put("weight", Integer.toString(cpuWeight)); @@ -1485,12 +1397,13 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe return vm; } + protected void finalizeVmMetaData(VM vm, Connection conn, VirtualMachineTO vmSpec) throws Exception { Map details = vmSpec.getDetails(); - if ( details != null ) { + if (details != null) { String platformstring = details.get("platform"); - if (platformstring != null && !platformstring.isEmpty() ) { + if (platformstring != null && !platformstring.isEmpty()) { Map platform = StringUtils.stringToMap(platformstring); vm.setPlatform(conn, platform); } else { @@ -1508,11 +1421,11 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } String xentoolsversion = details.get("hypervisortoolsversion"); - if ( xentoolsversion == null || !xentoolsversion.equalsIgnoreCase("xenserver61") ) { - Map platform = vm.getPlatform(conn); - platform.remove("device_id"); - vm.setPlatform(conn, platform); - } + if (xentoolsversion == null || !xentoolsversion.equalsIgnoreCase("xenserver61")) { + Map platform = vm.getPlatform(conn); + platform.remove("device_id"); + vm.setPlatform(conn, platform); + } } } @@ -1735,8 +1648,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe String result = null; if (cmd.getType() == PvlanSetupCommand.Type.DHCP) { result = - callHostPlugin(conn, "ovs-pvlan", "setup-pvlan-dhcp", "op", op, "nw-label", nwNameLabel, "primary-pvlan", primaryPvlan, "isolated-pvlan", isolatedPvlan, - "dhcp-name", dhcpName, "dhcp-ip", dhcpIp, "dhcp-mac", dhcpMac); + callHostPlugin(conn, "ovs-pvlan", "setup-pvlan-dhcp", "op", op, "nw-label", nwNameLabel, "primary-pvlan", primaryPvlan, "isolated-pvlan", isolatedPvlan, + "dhcp-name", dhcpName, "dhcp-ip", dhcpIp, "dhcp-mac", dhcpMac); if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) { s_logger.warn("Failed to program pvlan for dhcp server with mac " + dhcpMac); return new Answer(cmd, false, result); @@ -1745,8 +1658,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } } else if (cmd.getType() == PvlanSetupCommand.Type.VM) { result = - callHostPlugin(conn, "ovs-pvlan", "setup-pvlan-vm", "op", op, "nw-label", nwNameLabel, "primary-pvlan", primaryPvlan, "isolated-pvlan", isolatedPvlan, - "vm-mac", vmMac); + callHostPlugin(conn, "ovs-pvlan", "setup-pvlan-vm", "op", op, "nw-label", nwNameLabel, "primary-pvlan", primaryPvlan, "isolated-pvlan", isolatedPvlan, + "vm-mac", vmMac); if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) { s_logger.warn("Failed to program pvlan for vm with mac " + vmMac); return new Answer(cmd, false, result); @@ -1794,35 +1707,15 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe vm = createVmFromTemplate(conn, vmSpec, host); for (DiskTO disk : vmSpec.getDisks()) { - VDI vdi = null; + VDI newVdi = prepareManagedDisk(conn, disk, vmName); - if (disk.getData() instanceof VolumeObjectTO) { - Map details = disk.getDetails(); - boolean isManaged = details != null && Boolean.parseBoolean(details.get(DiskTO.MANAGED)); + if (newVdi != null) { + String path = newVdi.getUuid(conn); - if (isManaged) { - String iScsiName = details.get(DiskTO.IQN); - String storageHost = details.get(DiskTO.STORAGE_HOST); - String chapInitiatorUsername = disk.getDetails().get(DiskTO.CHAP_INITIATOR_USERNAME); - String chapInitiatorSecret = disk.getDetails().get(DiskTO.CHAP_INITIATOR_SECRET); - Long volumeSize = Long.parseLong(details.get(DiskTO.VOLUME_SIZE)); - String vdiNameLabel = vmName + "-DATA"; - - SR sr = getIscsiSR(conn, iScsiName, storageHost, iScsiName, chapInitiatorUsername, chapInitiatorSecret, true); - - vdi = getVDIbyUuid(conn, disk.getPath(), false); - - if (vdi == null) { - vdi = createVdi(sr, vdiNameLabel, volumeSize); - - iqnToPath.put(iScsiName, vdi.getUuid(conn)); - } else { - vdi.setNameLabel(conn, vdiNameLabel); - } - } + iqnToPath.put(disk.getDetails().get(DiskTO.IQN), path); } - createVbd(conn, disk, vmName, vm, vmSpec.getBootloader(), vdi); + createVbd(conn, disk, vmName, vm, vmSpec.getBootloader(), newVdi); } if (vmSpec.getType() != VirtualMachine.Type.User) { @@ -1841,7 +1734,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe if (nic.getBroadcastType() == Networks.BroadcastDomainType.Vswitch) { HashMap args = parseDefaultOvsRuleComamnd(BroadcastDomainType.getValue(nic.getBroadcastUri())); OvsSetTagAndFlowCommand flowCmd = - new OvsSetTagAndFlowCommand(args.get("vmName"), args.get("tag"), args.get("vlans"), args.get("seqno"), Long.parseLong(args.get("vmId"))); + new OvsSetTagAndFlowCommand(args.get("vmName"), args.get("tag"), args.get("vlans"), args.get("seqno"), Long.parseLong(args.get("vmId"))); OvsSetTagAndFlowAnswer r = execute(flowCmd); if (!r.getResult()) { s_logger.warn("Failed to set flow for VM " + r.getVmId()); @@ -1860,7 +1753,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe boolean secGrpEnabled = false; for (NicTO nic : nics) { if (nic.isSecurityGroupEnabled() || - (nic.getIsolationUri() != null && nic.getIsolationUri().getScheme().equalsIgnoreCase(IsolationType.Ec2.toString()))) { + (nic.getIsolationUri() != null && nic.getIsolationUri().getScheme().equalsIgnoreCase(IsolationType.Ec2.toString()))) { secGrpEnabled = true; break; } @@ -1879,7 +1772,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe NicTO[] nics = vmSpec.getNics(); for (NicTO nic : nics) { if (nic.isSecurityGroupEnabled() || nic.getIsolationUri() != null && - nic.getIsolationUri().getScheme().equalsIgnoreCase(IsolationType.Ec2.toString())) { + nic.getIsolationUri().getScheme().equalsIgnoreCase(IsolationType.Ec2.toString())) { List nicSecIps = nic.getNicSecIps(); String secIpsStr; StringBuilder sb = new StringBuilder(); @@ -1892,8 +1785,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe secIpsStr = "0:"; } result = - callHostPlugin(conn, "vmops", "default_network_rules", "vmName", vmName, "vmIP", nic.getIp(), "vmMAC", nic.getMac(), "vmID", - Long.toString(vmSpec.getId()), "secIps", secIpsStr); + callHostPlugin(conn, "vmops", "default_network_rules", "vmName", vmName, "vmIP", nic.getIp(), "vmMAC", nic.getMac(), "vmID", + Long.toString(vmSpec.getId()), "secIps", secIpsStr); if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) { s_logger.warn("Failed to program default network rules for " + vmName + " on nic with ip:" + nic.getIp() + " mac:" + nic.getMac()); @@ -1931,46 +1824,54 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe s_logger.debug("The VM is in stopped state, detected problem during startup : " + vmName); } } - - if (state != State.Running) { - disconnectManagedVolumes(conn, vm); - } } } - private void disconnectManagedVolumes(Connection conn, VM vm) { - try { - Set vbds = vm.getVBDs(conn); + // the idea here is to see if the DiskTO in question is from managed storage and + // does not yet have an SR + // if no SR, create it and create a VDI in it + private VDI prepareManagedDisk(Connection conn, DiskTO disk, String vmName) throws Exception { + Map details = disk.getDetails(); - for (VBD vbd : vbds) { - VDI vdi = vbd.getVDI(conn); - SR sr = null; - - try { - sr = vdi.getSR(conn); - } catch (Exception ex) { - continue; - } - - if (sr.getNameLabel(conn).startsWith("/iqn.")) { - VBD.Record vbdr = vbd.getRecord(conn); - - if (vbdr.currentlyAttached) { - vbd.unplug(conn); - } - - vbd.destroy(conn); - - vdi.setNameLabel(conn, "detached"); - - umount(conn, vdi); - - handleSrAndVdiDetach(sr.getNameLabel(conn)); - } - } - } catch (Exception ex) { - s_logger.debug(ex.getMessage()); + if (details == null) { + return null; } + + boolean isManaged = new Boolean(details.get(DiskTO.MANAGED)).booleanValue(); + + if (!isManaged) { + return null; + } + + String iqn = details.get(DiskTO.IQN); + + Set srNameLabels = SR.getByNameLabel(conn, iqn); + + if (srNameLabels.size() != 0) { + return null; + } + + String vdiNameLabel = vmName + "-DATA"; + + return prepareManagedStorage(conn, details, null, vdiNameLabel); + } + + protected VDI prepareManagedStorage(Connection conn, Map details, String path, String vdiNameLabel) throws Exception { + String iScsiName = details.get(DiskTO.IQN); + String storageHost = details.get(DiskTO.STORAGE_HOST); + String chapInitiatorUsername = details.get(DiskTO.CHAP_INITIATOR_USERNAME); + String chapInitiatorSecret = details.get(DiskTO.CHAP_INITIATOR_SECRET); + Long volumeSize = Long.parseLong(details.get(DiskTO.VOLUME_SIZE)); + + SR sr = getIscsiSR(conn, iScsiName, storageHost, iScsiName, chapInitiatorUsername, chapInitiatorSecret, true); + + VDI vdi = getVDIbyUuid(conn, path, false); + + if (vdi == null) { + vdi = createVdi(sr, vdiNameLabel, volumeSize); + } + + return vdi; } protected Answer execute(ModifySshKeysCommand cmd) { @@ -2016,53 +1917,6 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe return new Answer(cmd); } - private CheckS2SVpnConnectionsAnswer execute(CheckS2SVpnConnectionsCommand cmd) { - Connection conn = getConnection(); - String args = "checkbatchs2svpn.sh " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - for (String ip : cmd.getVpnIps()) { - args += " " + ip; - } - String result = callHostPlugin(conn, "vmops", "routerProxy", "args", args); - if (result == null || result.isEmpty()) { - return new CheckS2SVpnConnectionsAnswer(cmd, false, "CheckS2SVpnConneciontsCommand failed"); - } - return new CheckS2SVpnConnectionsAnswer(cmd, true, result); - } - - private CheckRouterAnswer execute(CheckRouterCommand cmd) { - Connection conn = getConnection(); - String args = "checkrouter.sh " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - String result = callHostPlugin(conn, "vmops", "routerProxy", "args", args); - if (result == null || result.isEmpty()) { - return new CheckRouterAnswer(cmd, "CheckRouterCommand failed"); - } - return new CheckRouterAnswer(cmd, result, true); - } - - private GetDomRVersionAnswer execute(GetDomRVersionCmd cmd) { - Connection conn = getConnection(); - String args = "get_template_version.sh " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - String result = callHostPlugin(conn, "vmops", "routerProxy", "args", args); - if (result == null || result.isEmpty()) { - return new GetDomRVersionAnswer(cmd, "getDomRVersionCmd failed"); - } - String[] lines = result.split("&"); - if (lines.length != 2) { - return new GetDomRVersionAnswer(cmd, result); - } - return new GetDomRVersionAnswer(cmd, result, lines[0], lines[1]); - } - - private Answer execute(BumpUpPriorityCommand cmd) { - Connection conn = getConnection(); - String args = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - String result = callHostPlugin(conn, "vmops", "bumpUpPriority", "args", args); - if (result == null || result.isEmpty()) { - return new Answer(cmd, false, "BumpUpPriorityCommand failed"); - } - return new Answer(cmd, true, result); - } - protected MaintainAnswer execute(MaintainCommand cmd) { Connection conn = getConnection(); try { @@ -2088,598 +1942,87 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } } - protected SetPortForwardingRulesAnswer execute(SetPortForwardingRulesCommand cmd) { - Connection conn = getConnection(); - - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - String[] results = new String[cmd.getRules().length]; - int i = 0; - - boolean endResult = true; - for (PortForwardingRuleTO rule : cmd.getRules()) { - StringBuilder args = new StringBuilder(); - args.append(routerIp); - args.append(rule.revoked() ? " -D " : " -A "); - args.append(" -P ").append(rule.getProtocol().toLowerCase()); - args.append(" -l ").append(rule.getSrcIp()); - args.append(" -p ").append(rule.getStringSrcPortRange()); - args.append(" -r ").append(rule.getDstIp()); - args.append(" -d ").append(rule.getStringDstPortRange()); - - String result = callHostPlugin(conn, "vmops", "setFirewallRule", "args", args.toString()); - - if (result == null || result.isEmpty()) { - results[i++] = "Failed"; - endResult = false; - } else { - results[i++] = null; - } - } - - return new SetPortForwardingRulesAnswer(cmd, results, endResult); - } - - protected SetStaticNatRulesAnswer SetVPCStaticNatRules(SetStaticNatRulesCommand cmd) { - Connection conn = getConnection(); - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - //String args = routerIp; - String[] results = new String[cmd.getRules().length]; - int i = 0; - boolean endResult = true; - for (StaticNatRuleTO rule : cmd.getRules()) { - String args = "vpc_staticnat.sh " + routerIp; - args += rule.revoked() ? " -D" : " -A"; - args += " -l " + rule.getSrcIp(); - args += " -r " + rule.getDstIp(); - String result = callHostPlugin(conn, "vmops", "routerProxy", "args", args.toString()); - - if (result == null || result.isEmpty()) { - results[i++] = "Failed"; - endResult = false; - } else { - results[i++] = null; - } - } - return new SetStaticNatRulesAnswer(cmd, results, endResult); - } - - protected SetStaticNatRulesAnswer execute(SetStaticNatRulesCommand cmd) { - if (cmd.getVpcId() != null) { - return SetVPCStaticNatRules(cmd); - } - Connection conn = getConnection(); - - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - //String args = routerIp; - String[] results = new String[cmd.getRules().length]; - int i = 0; - boolean endResult = true; - for (StaticNatRuleTO rule : cmd.getRules()) { - //1:1 NAT needs instanceip;publicip;domrip;op - StringBuilder args = new StringBuilder(); - args.append(routerIp); - args.append(rule.revoked() ? " -D " : " -A "); - args.append(" -l ").append(rule.getSrcIp()); - args.append(" -r ").append(rule.getDstIp()); - - if (rule.getProtocol() != null) { - args.append(" -P ").append(rule.getProtocol().toLowerCase()); - } - - args.append(" -d ").append(rule.getStringSrcPortRange()); - args.append(" -G "); - - String result = callHostPlugin(conn, "vmops", "setFirewallRule", "args", args.toString()); - - if (result == null || result.isEmpty()) { - results[i++] = "Failed"; - endResult = false; - } else { - results[i++] = null; - } - } - - return new SetStaticNatRulesAnswer(cmd, results, endResult); - } - - protected Answer VPCLoadBalancerConfig(final LoadBalancerConfigCommand cmd) { - Connection conn = getConnection(); - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - - if (routerIp == null) { - return new Answer(cmd); - } - - LoadBalancerConfigurator cfgtr = new HAProxyConfigurator(); - String[] config = cfgtr.generateConfiguration(cmd); - String tmpCfgFileContents = ""; - for (int i = 0; i < config.length; i++) { - tmpCfgFileContents += config[i]; - tmpCfgFileContents += "\n"; - } - String tmpCfgFilePath = "/etc/haproxy/haproxy.cfg.new"; - String result = callHostPlugin(conn, "vmops", "createFileInDomr", "domrip", routerIp, "filepath", tmpCfgFilePath, "filecontents", tmpCfgFileContents); - - if (result == null || result.isEmpty()) { - return new Answer(cmd, false, "LoadBalancerConfigCommand failed to create HA proxy cfg file."); - } - - String[][] rules = cfgtr.generateFwRules(cmd); - - String[] addRules = rules[LoadBalancerConfigurator.ADD]; - String[] removeRules = rules[LoadBalancerConfigurator.REMOVE]; - String[] statRules = rules[LoadBalancerConfigurator.STATS]; - - String args = "vpc_loadbalancer.sh " + routerIp; - String ip = cmd.getNic().getIp(); - args += " -i " + ip; - StringBuilder sb = new StringBuilder(); - if (addRules.length > 0) { - for (int i = 0; i < addRules.length; i++) { - sb.append(addRules[i]).append(','); - } - - args += " -a " + sb.toString(); - } - - sb = new StringBuilder(); - if (removeRules.length > 0) { - for (int i = 0; i < removeRules.length; i++) { - sb.append(removeRules[i]).append(','); - } - - args += " -d " + sb.toString(); - } - - sb = new StringBuilder(); - if (statRules.length > 0) { - for (int i = 0; i < statRules.length; i++) { - sb.append(statRules[i]).append(','); - } - - args += " -s " + sb.toString(); - } - - result = callHostPlugin(conn, "vmops", "routerProxy", "args", args); - - if (result == null || result.isEmpty()) { - return new Answer(cmd, false, "LoadBalancerConfigCommand failed"); - } - return new Answer(cmd); - } - - protected Answer execute(final CreateIpAliasCommand cmd) { - Connection conn = getConnection(); - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - List ipAliasTOs = cmd.getIpAliasList(); - String args = routerIp + " "; - for (IpAliasTO ipaliasto : ipAliasTOs) { - args = args + ipaliasto.getAlias_count() + ":" + ipaliasto.getRouterip() + ":" + ipaliasto.getNetmask() + "-"; - } - String result = callHostPlugin(conn, "vmops", "createipAlias", "args", args); - if (result == null || result.isEmpty()) { - return new Answer(cmd, false, "CreateIPAliasCommand failed\n"); - } - - return new Answer(cmd); - } - - protected Answer execute(final DeleteIpAliasCommand cmd) { - Connection conn = getConnection(); - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - List revokedIpAliasTOs = cmd.getDeleteIpAliasTos(); - String args = routerIp + " "; - for (IpAliasTO ipAliasTO : revokedIpAliasTOs) { - args = args + ipAliasTO.getAlias_count() + ":" + ipAliasTO.getRouterip() + ":" + ipAliasTO.getNetmask() + "-"; - } - //this is to ensure that thre is some argument passed to the deleteipAlias script when there are no revoked rules. - args = args + "- "; - List activeIpAliasTOs = cmd.getCreateIpAliasTos(); - for (IpAliasTO ipAliasTO : activeIpAliasTOs) { - args = args + ipAliasTO.getAlias_count() + ":" + ipAliasTO.getRouterip() + ":" + ipAliasTO.getNetmask() + "-"; - } - String result = callHostPlugin(conn, "vmops", "deleteipAlias", "args", args); - if (result == null || result.isEmpty()) { - return new Answer(cmd, false, "DeleteipAliasCommand failed\n"); - } - - return new Answer(cmd); - } - - protected Answer execute(final DnsMasqConfigCommand cmd) { - Connection conn = getConnection(); - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - List dhcpTos = cmd.getIps(); - String args = ""; - for (DhcpTO dhcpTo : dhcpTos) { - args = args + dhcpTo.getRouterIp() + ":" + dhcpTo.getGateway() + ":" + dhcpTo.getNetmask() + ":" + dhcpTo.getStartIpOfSubnet() + "-"; - } - - String result = callHostPlugin(conn, "vmops", "configdnsmasq", "routerip", routerIp, "args", args); - - if (result == null || result.isEmpty()) { - return new Answer(cmd, false, "DnsMasqconfigCommand failed"); - } - - return new Answer(cmd); - - } - - protected Answer execute(final LoadBalancerConfigCommand cmd) { - if (cmd.getVpcId() != null) { - return VPCLoadBalancerConfig(cmd); - } - Connection conn = getConnection(); - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - - if (routerIp == null) { - return new Answer(cmd); - } - - LoadBalancerConfigurator cfgtr = new HAProxyConfigurator(); - String[] config = cfgtr.generateConfiguration(cmd); - - String[][] rules = cfgtr.generateFwRules(cmd); - String tmpCfgFilePath = "/tmp/" + routerIp.replace('.', '_') + ".cfg"; - String tmpCfgFileContents = ""; - for (int i = 0; i < config.length; i++) { - tmpCfgFileContents += config[i]; - tmpCfgFileContents += "\n"; - } - - String result = callHostPlugin(conn, "vmops", "createFile", "filepath", tmpCfgFilePath, "filecontents", tmpCfgFileContents); - - if (result == null || result.isEmpty()) { - return new Answer(cmd, false, "LoadBalancerConfigCommand failed to create HA proxy cfg file."); - } - - String[] addRules = rules[LoadBalancerConfigurator.ADD]; - String[] removeRules = rules[LoadBalancerConfigurator.REMOVE]; - String[] statRules = rules[LoadBalancerConfigurator.STATS]; - - String args = ""; - args += "-i " + routerIp; - args += " -f " + tmpCfgFilePath; - - StringBuilder sb = new StringBuilder(); - if (addRules.length > 0) { - for (int i = 0; i < addRules.length; i++) { - sb.append(addRules[i]).append(','); - } - - args += " -a " + sb.toString(); - } - - sb = new StringBuilder(); - if (removeRules.length > 0) { - for (int i = 0; i < removeRules.length; i++) { - sb.append(removeRules[i]).append(','); - } - - args += " -d " + sb.toString(); - } - - sb = new StringBuilder(); - if (statRules.length > 0) { - for (int i = 0; i < statRules.length; i++) { - sb.append(statRules[i]).append(','); - } - - args += " -s " + sb.toString(); - } - - result = callHostPlugin(conn, "vmops", "setLoadBalancerRule", "args", args); - - if (result == null || result.isEmpty()) { - return new Answer(cmd, false, "LoadBalancerConfigCommand failed"); - } - - callHostPlugin(conn, "vmops", "deleteFile", "filepath", tmpCfgFilePath); - - return new Answer(cmd); - } - - protected synchronized Answer execute(final DhcpEntryCommand cmd) { - Connection conn = getConnection(); - String args = "-r " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - if (cmd.getVmIpAddress() != null) { - args += " -v " + cmd.getVmIpAddress(); - } - args += " -m " + cmd.getVmMac(); - args += " -n " + cmd.getVmName(); - if (cmd.getDefaultRouter() != null) { - args += " -d " + cmd.getDefaultRouter(); - } - if (cmd.getStaticRoutes() != null) { - args += " -s " + cmd.getStaticRoutes(); - } - - if (cmd.getDefaultDns() != null) { - args += " -N " + cmd.getDefaultDns(); - } - - if (cmd.getVmIp6Address() != null) { - args += " -6 " + cmd.getVmIp6Address(); - args += " -u " + cmd.getDuid(); - } - - if (!cmd.isDefault()) { - args += " -z"; - } - - String result = callHostPlugin(conn, "vmops", "saveDhcpEntry", "args", args); - if (result == null || result.isEmpty()) { - return new Answer(cmd, false, "DhcpEntry failed"); - } - return new Answer(cmd); - } - - protected synchronized Answer execute(final RemoteAccessVpnCfgCommand cmd) { - Connection conn = getConnection(); - String args = "vpn_l2tp.sh " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - if (cmd.isCreate()) { - args += " -r " + cmd.getIpRange(); - args += " -p " + cmd.getPresharedKey(); - args += " -s " + cmd.getVpnServerIp(); - args += " -l " + cmd.getLocalIp(); - args += " -c "; - } else { - args += " -d "; - args += " -s " + cmd.getVpnServerIp(); - } - args += " -C " + cmd.getLocalCidr(); - args += " -i " + cmd.getPublicInterface(); - String result = callHostPlugin(conn, "vmops", "routerProxy", "args", args); - if (result == null || result.isEmpty()) { - return new Answer(cmd, false, "Configure VPN failed"); - } - return new Answer(cmd); - } - - protected synchronized Answer execute(final VpnUsersCfgCommand cmd) { - Connection conn = getConnection(); - for (VpnUsersCfgCommand.UsernamePassword userpwd : cmd.getUserpwds()) { - String args = "vpn_l2tp.sh " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - if (!userpwd.isAdd()) { - args += " -U " + userpwd.getUsername(); - } else { - args += " -u " + userpwd.getUsernamePassword(); - } - String result = callHostPlugin(conn, "vmops", "routerProxy", "args", args); - if (result == null || result.isEmpty()) { - return new Answer(cmd, false, "Configure VPN user failed for user " + userpwd.getUsername()); - } - } - - return new Answer(cmd); - } - - protected Answer execute(final VmDataCommand cmd) { - Connection conn = getConnection(); - String routerPrivateIpAddress = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - Map> data = new HashMap>(); - data.put(cmd.getVmIpAddress(), cmd.getVmData()); - String json = new Gson().toJson(data); - json = Base64.encodeBase64String(json.getBytes()); - - String args = "vmdata.py " + routerPrivateIpAddress + " -d " + json; - - String result = callHostPlugin(conn, "vmops", "routerProxy", "args", args); - - if (result == null || result.isEmpty()) { - return new Answer(cmd, false, "vm_data failed"); - } else { - return new Answer(cmd); - } - - } - - protected Answer execute(final SavePasswordCommand cmd) { - Connection conn = getConnection(); - final String password = cmd.getPassword(); - final String routerPrivateIPAddress = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - final String vmIpAddress = cmd.getVmIpAddress(); - - String args = "savepassword.sh " + routerPrivateIPAddress; - args += " -v " + vmIpAddress; - args += " -p " + password; - String result = callHostPlugin(conn, "vmops", "routerProxy", "args", args); - - if (result == null || result.isEmpty()) { - return new Answer(cmd, false, "savePassword failed"); - } - return new Answer(cmd); - } - - protected void assignPublicIpAddress(Connection conn, String vmName, String privateIpAddress, String publicIpAddress, boolean add, boolean firstIP, - boolean sourceNat, String vlanId, String vlanGateway, String vlanNetmask, String vifMacAddress, Integer networkRate, TrafficType trafficType, String name) - throws InternalErrorException { - - try { - VM router = getVM(conn, vmName); - - NicTO nic = new NicTO(); - nic.setMac(vifMacAddress); - nic.setType(trafficType); - if (vlanId == null) { - nic.setBroadcastType(BroadcastDomainType.Native); - } else { - URI uri = BroadcastDomainType.fromString(vlanId); - nic.setBroadcastType(BroadcastDomainType.getSchemeValue(uri)); - nic.setBroadcastUri(uri); - } - nic.setDeviceId(0); - nic.setNetworkRateMbps(networkRate); - nic.setName(name); - - Network network = getNetwork(conn, nic); - - // Determine the correct VIF on DomR to associate/disassociate the - // IP address with - VIF correctVif = getCorrectVif(conn, router, network); - - // If we are associating an IP address and DomR doesn't have a VIF - // for the specified vlan ID, we need to add a VIF - // If we are disassociating the last IP address in the VLAN, we need - // to remove a VIF - boolean addVif = false; - boolean removeVif = false; - if (add && correctVif == null) { - addVif = true; - } - - if (addVif) { - // Add a new VIF to DomR - String vifDeviceNum = getLowestAvailableVIFDeviceNum(conn, router); - - if (vifDeviceNum == null) { - throw new InternalErrorException("There were no more available slots for a new VIF on router: " + router.getNameLabel(conn)); - } - - nic.setDeviceId(Integer.parseInt(vifDeviceNum)); - - correctVif = createVif(conn, vmName, router, null, nic); - correctVif.plug(conn); - // Add iptables rule for network usage - networkUsage(conn, privateIpAddress, "addVif", "eth" + correctVif.getDevice(conn)); - } - - if (correctVif == null) { - throw new InternalErrorException("Failed to find DomR VIF to associate/disassociate IP with."); - } - - String args = "ipassoc.sh " + privateIpAddress; - - if (add) { - args += " -A "; - } else { - args += " -D "; - } - - if (sourceNat) { - args += " -s"; - } - if (firstIP) { - args += " -f"; - } - - String cidrSize = Long.toString(NetUtils.getCidrSize(vlanNetmask)); - args += " -l "; - args += publicIpAddress + "/" + cidrSize; - - args += " -c "; - args += "eth" + correctVif.getDevice(conn); - - args += " -g "; - args += vlanGateway; - - if (addVif) { - //To indicate this is new interface created - args += " -n"; - } - - String result = callHostPlugin(conn, "vmops", "routerProxy", "args", args); - if (result == null || result.isEmpty()) { - throw new InternalErrorException("Xen plugin \"ipassoc\" failed."); - } - - if (removeVif) { - network = correctVif.getNetwork(conn); - - // Mark this vif to be removed from network usage - networkUsage(conn, privateIpAddress, "deleteVif", "eth" + correctVif.getDevice(conn)); - - // Remove the VIF from DomR - correctVif.unplug(conn); - correctVif.destroy(conn); - - // Disable the VLAN network if necessary - disableVlanNetwork(conn, network); - } - - } catch (XenAPIException e) { - String msg = "Unable to assign public IP address due to " + e.toString(); - s_logger.warn(msg, e); - throw new InternalErrorException(msg); - } catch (final XmlRpcException e) { - String msg = "Unable to assign public IP address due to " + e.getMessage(); - s_logger.warn(msg, e); - throw new InternalErrorException(msg); - } - } - - protected void assignVPCPublicIpAddress(Connection conn, String vmName, String routerIp, IpAddressTO ip) throws Exception { - - try { - VM router = getVM(conn, vmName); - - VIF correctVif = getVifByMac(conn, router, ip.getVifMacAddress()); - if (correctVif == null) { - if (ip.isAdd()) { - throw new InternalErrorException("Failed to find DomR VIF to associate IP with."); - } else { - s_logger.debug("VIF to deassociate IP with does not exist, return success"); - return; - } - } - - String args = "vpc_ipassoc.sh " + routerIp; - String snatArgs = "vpc_privateGateway.sh " + routerIp; - - if (ip.isAdd()) { - args += " -A "; - snatArgs += " -A "; - } else { - args += " -D "; - snatArgs += " -D "; - } - - args += " -l "; - args += ip.getPublicIp(); - - args += " -c "; - args += "eth" + correctVif.getDevice(conn); - - args += " -g "; - args += ip.getVlanGateway(); - - args += " -m "; - args += Long.toString(NetUtils.getCidrSize(ip.getVlanNetmask())); - - args += " -n "; - args += NetUtils.getSubNet(ip.getPublicIp(), ip.getVlanNetmask()); - - String result = callHostPlugin(conn, "vmops", "routerProxy", "args", args); - if (result == null || result.isEmpty()) { - throw new InternalErrorException("Xen plugin \"vpc_ipassoc\" failed."); - } - - if (ip.isSourceNat()) { - snatArgs += " -l " + ip.getPublicIp(); - snatArgs += " -c " + "eth" + correctVif.getDevice(conn); - - result = callHostPlugin(conn, "vmops", "routerProxy", "args", snatArgs); - if (result == null || result.isEmpty()) { - throw new InternalErrorException("Xen plugin \"vpc_privateGateway\" failed."); - } - } - - } catch (Exception e) { - String msg = "Unable to assign public IP address due to " + e.toString(); - s_logger.warn(msg, e); - throw new Exception(msg); - } - } - protected String networkUsage(Connection conn, final String privateIpAddress, final String option, final String vif) { - if (option.equals("get")) { return "0:0"; } return null; } - protected Answer execute(IpAssocCommand cmd) { + protected ExecutionResult prepareNetworkElementCommand(IpAssocCommand cmd) { + Connection conn = getConnection(); + int i = 0; + String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); + String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); + + try { + IpAddressTO[] ips = cmd.getIpAddresses(); + for (IpAddressTO ip : ips) { + + VM router = getVM(conn, routerName); + + NicTO nic = new NicTO(); + nic.setMac(ip.getVifMacAddress()); + nic.setType(ip.getTrafficType()); + if (ip.getBroadcastUri()== null) { + nic.setBroadcastType(BroadcastDomainType.Native); + } else { + URI uri = BroadcastDomainType.fromString(ip.getBroadcastUri()); + nic.setBroadcastType(BroadcastDomainType.getSchemeValue(uri)); + nic.setBroadcastUri(uri); + } + nic.setDeviceId(0); + nic.setNetworkRateMbps(ip.getNetworkRate()); + nic.setName(ip.getNetworkName()); + + Network network = getNetwork(conn, nic); + + // Determine the correct VIF on DomR to associate/disassociate the + // IP address with + VIF correctVif = getCorrectVif(conn, router, network); + + // If we are associating an IP address and DomR doesn't have a VIF + // for the specified vlan ID, we need to add a VIF + // If we are disassociating the last IP address in the VLAN, we need + // to remove a VIF + boolean addVif = false; + if (ip.isAdd() && correctVif == null) { + addVif = true; + } + + if (addVif) { + // Add a new VIF to DomR + String vifDeviceNum = getLowestAvailableVIFDeviceNum(conn, router); + + if (vifDeviceNum == null) { + throw new InternalErrorException("There were no more available slots for a new VIF on router: " + router.getNameLabel(conn)); + } + + nic.setDeviceId(Integer.valueOf(vifDeviceNum)); + + correctVif = createVif(conn, routerName, router, null, nic); + correctVif.plug(conn); + // Add iptables rule for network usage + networkUsage(conn, routerIp, "addVif", "eth" + correctVif.getDevice(conn)); + } + + if (correctVif == null) { + throw new InternalErrorException("Failed to find DomR VIF to associate/disassociate IP with."); + } + + ip.setNicDevId(Integer.valueOf(correctVif.getDevice(conn))); + ip.setNewNic(addVif); + } + } catch (InternalErrorException e) { + s_logger.error("Ip Assoc failure on applying one ip due to exception: ", e); + return new ExecutionResult(false, e.getMessage()); + } catch (Exception e) { + return new ExecutionResult(false, e.getMessage()); + } + return new ExecutionResult(true, null); + } + + protected ExecutionResult cleanupNetworkElementCommand(IpAssocCommand cmd) { Connection conn = getConnection(); String[] results = new String[cmd.getIpAddresses().length]; int i = 0; @@ -2689,16 +2032,57 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe IpAddressTO[] ips = cmd.getIpAddresses(); for (IpAddressTO ip : ips) { - assignPublicIpAddress(conn, routerName, routerIp, ip.getPublicIp(), ip.isAdd(), ip.isFirstIP(), ip.isSourceNat(), ip.getBroadcastUri(), - ip.getVlanGateway(), ip.getVlanNetmask(), ip.getVifMacAddress(), ip.getNetworkRate(), ip.getTrafficType(), ip.getNetworkName()); - results[i++] = ip.getPublicIp() + " - success"; + VM router = getVM(conn, routerName); + + NicTO nic = new NicTO(); + nic.setMac(ip.getVifMacAddress()); + nic.setType(ip.getTrafficType()); + if (ip.getBroadcastUri()== null) { + nic.setBroadcastType(BroadcastDomainType.Native); + } else { + URI uri = BroadcastDomainType.fromString(ip.getBroadcastUri()); + nic.setBroadcastType(BroadcastDomainType.getSchemeValue(uri)); + nic.setBroadcastUri(uri); + } + nic.setDeviceId(0); + nic.setNetworkRateMbps(ip.getNetworkRate()); + nic.setName(ip.getNetworkName()); + + Network network = getNetwork(conn, nic); + + // Determine the correct VIF on DomR to associate/disassociate the + // IP address with + VIF correctVif = getCorrectVif(conn, router, network); + + // If we are disassociating the last IP address in the VLAN, we need + // to remove a VIF + boolean removeVif = false; + + if (correctVif == null) { + throw new InternalErrorException("Failed to find DomR VIF to associate/disassociate IP with."); + } + + if (removeVif) { + network = correctVif.getNetwork(conn); + + // Mark this vif to be removed from network usage + networkUsage(conn, routerIp, "deleteVif", "eth" + correctVif.getDevice(conn)); + + // Remove the VIF from DomR + correctVif.unplug(conn); + correctVif.destroy(conn); + + // Disable the VLAN network if necessary + disableVlanNetwork(conn, network); + } } } catch (InternalErrorException e) { s_logger.error("Ip Assoc failure on applying one ip due to exception: ", e); - results[i++] = IpAssocAnswer.errorResult; + return new ExecutionResult(false, e.getMessage()); + } catch (Exception e) { + return new ExecutionResult(false, e.getMessage()); } - - return new IpAssocAnswer(cmd, results); + return new ExecutionResult(true, null); } protected GetVncPortAnswer execute(GetVncPortCommand cmd) { @@ -3083,7 +2467,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe String startTime = String.valueOf(currentDate.getTime() / 1000 - 1000); return callHostPlugin(conn, "vmops", "gethostvmstats", "collectHostStats", String.valueOf("true"), "consolidationFunction", _consolidationFunction, "interval", - String.valueOf(_pollingIntervalInSeconds), "startTime", startTime); + String.valueOf(_pollingIntervalInSeconds), "startTime", startTime); } protected String getVmStatsRawXML(Connection conn) { @@ -3091,7 +2475,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe String startTime = String.valueOf(currentDate.getTime() / 1000 - 1000); return callHostPlugin(conn, "vmops", "gethostvmstats", "collectHostStats", String.valueOf("false"), "consolidationFunction", _consolidationFunction, "interval", - String.valueOf(_pollingIntervalInSeconds), "startTime", startTime); + String.valueOf(_pollingIntervalInSeconds), "startTime", startTime); } protected State convertToState(Types.VmPowerState ps) { @@ -3305,8 +2689,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe String createTemplateFromSnapshot(Connection conn, String templatePath, String snapshotPath, int wait) { String tmpltLocalDir = UUID.randomUUID().toString(); String results = - callHostPluginAsync(conn, "vmopspremium", "create_privatetemplate_from_snapshot", wait, "templatePath", templatePath, "snapshotPath", snapshotPath, - "tmpltLocalDir", tmpltLocalDir); + callHostPluginAsync(conn, "vmopspremium", "create_privatetemplate_from_snapshot", wait, "templatePath", templatePath, "snapshotPath", snapshotPath, + "tmpltLocalDir", tmpltLocalDir); String errMsg = null; if (results == null || results.isEmpty()) { errMsg = "create_privatetemplate_from_snapshot return null"; @@ -3357,7 +2741,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe String copy_vhd_from_secondarystorage(Connection conn, String mountpoint, String sruuid, int wait) { String nameLabel = "cloud-" + UUID.randomUUID().toString(); String results = - callHostPluginAsync(conn, "vmopspremium", "copy_vhd_from_secondarystorage", wait, "mountpoint", mountpoint, "sruuid", sruuid, "namelabel", nameLabel); + callHostPluginAsync(conn, "vmopspremium", "copy_vhd_from_secondarystorage", wait, "mountpoint", mountpoint, "sruuid", sruuid, "namelabel", nameLabel); String errMsg = null; if (results == null || results.isEmpty()) { errMsg = "copy_vhd_from_secondarystorage return null"; @@ -3542,7 +2926,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe Set vbds = vm.getVBDs(conn); for (VBD vbd : vbds) { VBD.Record vbdRec = vbd.getRecord(conn); - if (vbdRec.type.equals(Types.VbdType.CD.toString()) && !vbdRec.empty) { + if (vbdRec.type.equals(Types.VbdType.CD) && !vbdRec.empty) { vbd.eject(conn); break; } @@ -3610,13 +2994,21 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe throw new CloudRuntimeException("Com'on no control domain? What the crap?!#@!##$@"); } + protected void umountSnapshotDir(Connection conn, Long dcId) { + try { + callHostPlugin(conn, "vmopsSnapshot", "unmountSnapshotsDir", "dcId", dcId.toString()); + } catch (Exception e) { + s_logger.debug("Failed to umount snapshot dir",e); + } + } + protected ReadyAnswer execute(ReadyCommand cmd) { Connection conn = getConnection(); Long dcId = cmd.getDataCenterId(); // Ignore the result of the callHostPlugin. Even if unmounting the // snapshots dir fails, let Ready command // succeed. - callHostPlugin(conn, "vmopsSnapshot", "unmountSnapshotsDir", "dcId", dcId.toString()); + umountSnapshotDir(conn, dcId); setupLinkLocalNetwork(conn); // try to destroy CD-ROM device for all system VMs on this host @@ -3658,7 +3050,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe Iterator i = consoles.iterator(); while (i.hasNext()) { c = i.next(); - if (c.getProtocol(conn) == ConsoleProtocol.RFB) + if (c.getProtocol(conn) == Types.ConsoleProtocol.RFB) return c.getLocation(conn); } } catch (XenAPIException e) { @@ -3802,7 +3194,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe long beginTime = System.currentTimeMillis(); if (s_logger.isTraceEnabled()) { s_logger.trace("Task " + task.getNameLabel(c) + " (" + task.getUuid(c) + ") sent to " + c.getSessionReference() + " is pending completion with a " + timeout + - "ms timeout"); + "ms timeout"); } while (task.getStatus(c) == Types.TaskStatusType.PENDING) { try { @@ -4022,109 +3414,6 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } } - boolean swiftDownload(Connection conn, SwiftTO swift, String container, String rfilename, String dir, String lfilename, Boolean remote) { - String result = null; - try { - result = - callHostPluginAsync(conn, "swiftxen", "swift", 60 * 60, "op", "download", "url", swift.getUrl(), "account", swift.getAccount(), "username", - swift.getUserName(), "key", swift.getKey(), "rfilename", rfilename, "dir", dir, "lfilename", lfilename, "remote", remote.toString()); - if (result != null && result.equals("true")) { - return true; - } - } catch (Exception e) { - s_logger.warn("swift download failed due to ", e); - } - return false; - } - - boolean swiftUpload(Connection conn, SwiftTO swift, String container, String ldir, String lfilename, Boolean isISCSI, int wait) { - String result = null; - try { - result = - callHostPluginAsync(conn, "swiftxen", "swift", wait, "op", "upload", "url", swift.getUrl(), "account", swift.getAccount(), "username", - swift.getUserName(), "key", swift.getKey(), "container", container, "ldir", ldir, "lfilename", lfilename, "isISCSI", isISCSI.toString()); - if (result != null && result.equals("true")) { - return true; - } - } catch (Exception e) { - s_logger.warn("swift upload failed due to " + e.toString(), e); - } - return false; - } - - boolean swiftDelete(Connection conn, SwiftTO swift, String rfilename) { - String result = null; - try { - result = - callHostPlugin(conn, "swiftxen", "swift", "op", "delete", "url", swift.getUrl(), "account", swift.getAccount(), "username", swift.getUserName(), "key", - swift.getKey(), "rfilename", rfilename); - if (result != null && result.equals("true")) { - return true; - } - } catch (Exception e) { - s_logger.warn("swift download failed due to ", e); - } - return false; - } - - public String swiftBackupSnapshot(Connection conn, SwiftTO swift, String srUuid, String snapshotUuid, String container, Boolean isISCSI, int wait) { - String lfilename; - String ldir; - if (isISCSI) { - ldir = "/dev/VG_XenStorage-" + srUuid; - lfilename = "VHD-" + snapshotUuid; - } else { - ldir = "/var/run/sr-mount/" + srUuid; - lfilename = snapshotUuid + ".vhd"; - } - swiftUpload(conn, swift, container, ldir, lfilename, isISCSI, wait); - return lfilename; - } - - protected String backupSnapshot(Connection conn, String primaryStorageSRUuid, Long dcId, Long accountId, Long volumeId, String secondaryStorageMountPath, - String snapshotUuid, String prevBackupUuid, Boolean isISCSI, int wait, Long secHostId) { - String backupSnapshotUuid = null; - - if (prevBackupUuid == null) { - prevBackupUuid = ""; - } - - // Each argument is put in a separate line for readability. - // Using more lines does not harm the environment. - String backupUuid = UUID.randomUUID().toString(); - String results = - callHostPluginAsync(conn, "vmopsSnapshot", "backupSnapshot", wait, "primaryStorageSRUuid", primaryStorageSRUuid, "dcId", dcId.toString(), "accountId", - accountId.toString(), "volumeId", volumeId.toString(), "secondaryStorageMountPath", secondaryStorageMountPath, "snapshotUuid", snapshotUuid, - "prevBackupUuid", prevBackupUuid, "backupUuid", backupUuid, "isISCSI", isISCSI.toString(), "secHostId", secHostId.toString()); - String errMsg = null; - if (results == null || results.isEmpty()) { - errMsg = - "Could not copy backupUuid: " + backupSnapshotUuid + " of volumeId: " + volumeId + " from primary storage " + primaryStorageSRUuid + - " to secondary storage " + secondaryStorageMountPath + " due to null"; - } else { - - String[] tmp = results.split("#"); - String status = tmp[0]; - backupSnapshotUuid = tmp[1]; - // status == "1" if and only if backupSnapshotUuid != null - // So we don't rely on status value but return backupSnapshotUuid as an - // indicator of success. - if (status != null && status.equalsIgnoreCase("1") && backupSnapshotUuid != null) { - s_logger.debug("Successfully copied backupUuid: " + backupSnapshotUuid + " of volumeId: " + volumeId + " to secondary storage"); - return backupSnapshotUuid; - } else { - errMsg = - "Could not copy backupUuid: " + backupSnapshotUuid + " of volumeId: " + volumeId + " from primary storage " + primaryStorageSRUuid + - " to secondary storage " + secondaryStorageMountPath + " due to " + tmp[1]; - } - } - String source = backupUuid + ".vhd"; - killCopyProcess(conn, source); - s_logger.warn(errMsg); - return null; - - } - protected String callHostPluginAsync(Connection conn, String plugin, String cmd, int wait, String... params) { int timeout = wait * 1000; Map args = new HashMap(); @@ -4148,7 +3437,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe return result.replace("", "").replace("", "").replace("\n", ""); } catch (Types.HandleInvalid e) { s_logger.warn("callHostPlugin failed for cmd: " + cmd + " with args " + getArgsString(args) + " due to HandleInvalid clazz:" + e.clazz + ", handle:" + - e.handle); + e.handle); } catch (XenAPIException e) { s_logger.warn("callHostPlugin failed for cmd: " + cmd + " with args " + getArgsString(args) + " due to " + e.toString(), e); } catch (XmlRpcException e) { @@ -4241,8 +3530,6 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe try { if (vm.getPowerState(conn) == VmPowerState.HALTED) { - disconnectManagedVolumes(conn, vm); - Set vifs = vm.getVIFs(conn); List networks = new ArrayList(); for (VIF vif : vifs) { @@ -4263,7 +3550,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe // network might be destroyed by other host } } - return new StopAnswer(cmd, "Stop VM " + vmName + " Succeed", platformstring ,true); + return new StopAnswer(cmd, "Stop VM " + vmName + " Succeed", platformstring, true); } } catch (Exception e) { String msg = "VM destroy failed in Stop " + vmName + " Command due to " + e.getMessage(); @@ -4433,7 +3720,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe if (rec.management) { if (rec.VLAN != null && rec.VLAN != -1) { String msg = - new StringBuilder("Unsupported configuration. Management network is on a VLAN. host=").append(_host.uuid) + new StringBuilder("Unsupported configuration. Management network is on a VLAN. host=").append(_host.uuid) .append("; pif=") .append(rec.uuid) .append("; vlan=") @@ -4458,7 +3745,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe Bond bond = mgmtPifRec.bondSlaveOf; if (!isRefNull(bond)) { String msg = - "Management interface is on slave(" + mgmtPifRec.uuid + ") of bond(" + bond.getUuid(conn) + ") on host(" + _host.uuid + + "Management interface is on slave(" + mgmtPifRec.uuid + ") of bond(" + bond.getUuid(conn) + ") on host(" + _host.uuid + "), please move management interface to bond!"; s_logger.warn(msg); throw new CloudRuntimeException(msg); @@ -4640,7 +3927,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } protected String generateTimeStamp() { - return new StringBuilder("CsCreateTime-").append(System.currentTimeMillis()).append("-").append(_rand.nextInt()).toString(); + return new StringBuilder("CsCreateTime-").append(System.currentTimeMillis()).append("-").append(Rand.nextInt()).toString(); } protected Pair parseTimestamp(String timeStampStr) { @@ -4957,11 +4244,11 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe break; } Host.Record hr = myself.getRecord(conn); - _host.product_version = hr.softwareVersion.get("product_version"); - if (_host.product_version == null) { - _host.product_version = hr.softwareVersion.get("platform_version"); + _host.productVersion = hr.softwareVersion.get("product_version"); + if (_host.productVersion == null) { + _host.productVersion = hr.softwareVersion.get("platform_version"); } else { - _host.product_version = _host.product_version.trim(); + _host.productVersion = _host.productVersion.trim(); } XsLocalNetwork privateNic = getManagementNetwork(conn); @@ -5138,7 +4425,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe return false; } - src.reconfigureIp(conn, IpConfigurationMode.NONE, null, null, null, null); + src.reconfigureIp(conn, Types.IpConfigurationMode.NONE, null, null, null, null); return true; } @@ -5154,7 +4441,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe cmd.setHypervisorType(HypervisorType.XenServer); cmd.setCluster(_cluster); cmd.setPoolSync(false); - cmd.setHostVmStateReport(this.getHostVmStateReport(conn)); + cmd.setHostVmStateReport(getHostVmStateReport(conn)); Pool pool; try { @@ -5225,6 +4512,13 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe if (_securityGroupEnabled) { _canBridgeFirewall = can_bridge_firewall(conn); + if (!_canBridgeFirewall) { + String msg = "Failed to configure brige firewall"; + s_logger.warn(msg); + s_logger.warn("Check host " + _host.ip +" for CSP is installed or not and check network mode for bridge"); + return new SetupAnswer(cmd, msg); + } + } String result = callHostPluginPremium(conn, "heartbeat", "host", _host.uuid, "interval", Integer.toString(_heartbeatInterval)); @@ -5258,7 +4552,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe if (rec.management) { if (rec.VLAN != null && rec.VLAN != -1) { String msg = - new StringBuilder("Unsupported configuration. Management network is on a VLAN. host=").append(_host.uuid) + new StringBuilder("Unsupported configuration. Management network is on a VLAN. host=").append(_host.uuid) .append("; pif=") .append(rec.uuid) .append("; vlan=") @@ -5292,7 +4586,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } if (pr.VLAN != null && pr.VLAN != -1) { String msg = - new StringBuilder("Unsupported configuration. Network cloud-private is on a VLAN. Network=").append(network.uuid) + new StringBuilder("Unsupported configuration. Network cloud-private is on a VLAN. Network=").append(network.uuid) .append(" ; pif=") .append(pr.uuid) .toString(); @@ -5302,7 +4596,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe if (!pr.management && pr.bondMasterOf != null && pr.bondMasterOf.size() > 0) { if (pr.bondMasterOf.size() > 1) { String msg = - new StringBuilder("Unsupported configuration. Network cloud-private has more than one bond. Network=").append(network.uuid) + new StringBuilder("Unsupported configuration. Network cloud-private has more than one bond. Network=").append(network.uuid) .append("; pif=") .append(pr.uuid) .toString(); @@ -5316,8 +4610,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe if (spr.management) { if (!transferManagementNetwork(conn, host, slave, spr, pif)) { String msg = - new StringBuilder("Unable to transfer management network. slave=" + spr.uuid + "; master=" + pr.uuid + "; host=" + - _host.uuid).toString(); + new StringBuilder("Unable to transfer management network. slave=" + spr.uuid + "; master=" + pr.uuid + "; host=" + + _host.uuid).toString(); s_logger.warn(msg); return new SetupAnswer(cmd, msg); } @@ -5475,22 +4769,22 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe for (PhysicalNetworkSetupInfo info : infoList) { if (!isNetworkSetupByName(info.getGuestNetworkName())) { msg = - "For Physical Network id:" + info.getPhysicalNetworkId() + ", Guest Network is not configured on the backend by name " + - info.getGuestNetworkName(); + "For Physical Network id:" + info.getPhysicalNetworkId() + ", Guest Network is not configured on the backend by name " + + info.getGuestNetworkName(); errorout = true; break; } if (!isNetworkSetupByName(info.getPrivateNetworkName())) { msg = - "For Physical Network id:" + info.getPhysicalNetworkId() + ", Private Network is not configured on the backend by name " + - info.getPrivateNetworkName(); + "For Physical Network id:" + info.getPhysicalNetworkId() + ", Private Network is not configured on the backend by name " + + info.getPrivateNetworkName(); errorout = true; break; } if (!isNetworkSetupByName(info.getPublicNetworkName())) { msg = - "For Physical Network id:" + info.getPhysicalNetworkId() + ", Public Network is not configured on the backend by name " + - info.getPublicNetworkName(); + "For Physical Network id:" + info.getPhysicalNetworkId() + ", Public Network is not configured on the backend by name " + + info.getPublicNetworkName(); errorout = true; break; } @@ -5659,8 +4953,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe return new Answer(cmd, true, "success"); } catch (Exception e) { String msg = - "Catch Exception " + e.getClass().getName() + ", create StoragePool failed due to " + e.toString() + " on host:" + _host.uuid + " pool: " + - pool.getHost() + pool.getPath(); + "Catch Exception " + e.getClass().getName() + ", create StoragePool failed due to " + e.toString() + " on host:" + _host.uuid + " pool: " + + pool.getHost() + pool.getPath(); s_logger.warn(msg, e); return new Answer(cmd, false, msg); } @@ -5690,7 +4984,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe return result.replace("\n", ""); } catch (Types.HandleInvalid e) { s_logger.warn("callHostPlugin failed for cmd: " + cmd + " with args " + getArgsString(args) + " due to HandleInvalid clazz:" + e.clazz + ", handle:" + - e.handle); + e.handle); } catch (XenAPIException e) { s_logger.warn("callHostPlugin failed for cmd: " + cmd + " with args " + getArgsString(args) + " due to " + e.toString(), e); } catch (XmlRpcException e) { @@ -5849,8 +5143,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe configureTunnelNetwork(conn, cmd.getNetworkId(), cmd.getFrom(), cmd.getKey()); bridge = nw.getBridge(conn); String result = - callHostPlugin(conn, "ovstunnel", "create_tunnel", "bridge", bridge, "remote_ip", cmd.getRemoteIp(), "key", cmd.getKey().toString(), "from", - cmd.getFrom().toString(), "to", cmd.getTo().toString()); + callHostPlugin(conn, "ovstunnel", "create_tunnel", "bridge", bridge, "remote_ip", cmd.getRemoteIp(), "key", cmd.getKey().toString(), "from", + cmd.getFrom().toString(), "to", cmd.getTo().toString()); String[] res = result.split(":"); if (res.length == 2 && res[0].equalsIgnoreCase("SUCCESS")) { return new OvsCreateTunnelAnswer(cmd, true, result, res[1], bridge); @@ -5923,8 +5217,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe * plugin side */ String result = - callHostPlugin(conn, "ovsgre", "ovs_set_tag_and_flow", "bridge", bridge, "vmName", cmd.getVmName(), "tag", cmd.getTag(), "vlans", cmd.getVlans(), - "seqno", cmd.getSeqNo()); + callHostPlugin(conn, "ovsgre", "ovs_set_tag_and_flow", "bridge", bridge, "vmName", cmd.getVmName(), "tag", cmd.getTag(), "vlans", cmd.getVlans(), + "seqno", cmd.getSeqNo()); s_logger.debug("set flow for " + cmd.getVmName() + " " + result); if (result.equalsIgnoreCase("SUCCESS")) { @@ -5948,7 +5242,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe String label = cmd.getLabel(); //FIXME: this is a tricky to pass the network checking in XCP. I temporary get default label from Host. if (is_xcp()) { - label = getLabel(); + label = getLabel(); } s_logger.debug("Will look for network with name-label:" + label + " on host " + _host.ip); Connection conn = getConnection(); @@ -5956,7 +5250,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe XsLocalNetwork nw = getNetworkByName(conn, label); s_logger.debug("Network object:" + nw.getNetwork().getUuid(conn)); PIF pif = nw.getPif(conn); - Record pifRec = pif.getRecord(conn); + PIF.Record pifRec = pif.getRecord(conn); s_logger.debug("PIF object:" + pifRec.uuid + "(" + pifRec.device + ")"); return new OvsFetchInterfaceAnswer(cmd, true, "Interface " + pifRec.device + " retrieved successfully", pifRec.IP, pifRec.netmask, pifRec.MAC); } catch (BadServerResponse e) { @@ -5981,8 +5275,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe bridge = nw.getBridge(conn); String result = - callHostPlugin(conn, "ovsgre", "ovs_create_gre", "bridge", bridge, "remoteIP", cmd.getRemoteIp(), "greKey", cmd.getKey(), "from", - Long.toString(cmd.getFrom()), "to", Long.toString(cmd.getTo())); + callHostPlugin(conn, "ovsgre", "ovs_create_gre", "bridge", bridge, "remoteIP", cmd.getRemoteIp(), "greKey", cmd.getKey(), "from", + Long.toString(cmd.getFrom()), "to", Long.toString(cmd.getTo())); String[] res = result.split(":"); if (res.length != 2 || (res.length == 2 && res[1].equalsIgnoreCase("[]"))) { return new OvsCreateGreTunnelAnswer(cmd, false, result, _host.ip, bridge); @@ -6009,20 +5303,20 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe if (!_canBridgeFirewall) { s_logger.warn("Host " + _host.ip + " cannot do bridge firewalling"); return new SecurityGroupRuleAnswer(cmd, false, "Host " + _host.ip + " cannot do bridge firewalling", - SecurityGroupRuleAnswer.FailureReason.CANNOT_BRIDGE_FIREWALL); + SecurityGroupRuleAnswer.FailureReason.CANNOT_BRIDGE_FIREWALL); } String result = - callHostPlugin(conn, "vmops", "network_rules", "vmName", cmd.getVmName(), "vmIP", cmd.getGuestIp(), "vmMAC", cmd.getGuestMac(), "vmID", - Long.toString(cmd.getVmId()), "signature", cmd.getSignature(), "seqno", Long.toString(cmd.getSeqNum()), "deflated", "true", "rules", - cmd.compressStringifiedRules(), "secIps", cmd.getSecIpsString()); + callHostPlugin(conn, "vmops", "network_rules", "vmName", cmd.getVmName(), "vmIP", cmd.getGuestIp(), "vmMAC", cmd.getGuestMac(), "vmID", + Long.toString(cmd.getVmId()), "signature", cmd.getSignature(), "seqno", Long.toString(cmd.getSeqNum()), "deflated", "true", "rules", + cmd.compressStringifiedRules(), "secIps", cmd.getSecIpsString()); if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) { s_logger.warn("Failed to program network rules for vm " + cmd.getVmName()); return new SecurityGroupRuleAnswer(cmd, false, "programming network rules failed"); } else { s_logger.info("Programmed network rules for vm " + cmd.getVmName() + " guestIp=" + cmd.getGuestIp() + ", ingress numrules=" + cmd.getIngressRuleSet().length + - ", egress numrules=" + cmd.getEgressRuleSet().length); + ", egress numrules=" + cmd.getEgressRuleSet().length); return new SecurityGroupRuleAnswer(cmd); } } @@ -6044,7 +5338,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } public Connection getConnection() { - return _connPool.connect(_host.uuid, _host.pool, _host.ip, _username, _password, _wait); + return ConnPool.connect(_host.uuid, _host.pool, _host.ip, _username, _password, _wait); } protected void fillHostInfo(Connection conn, StartupRoutingCommand cmd) { @@ -6064,13 +5358,13 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe productBrand = hr.softwareVersion.get("platform_name"); } details.put("product_brand", productBrand); - details.put("product_version", _host.product_version); + details.put("product_version", _host.productVersion); if (hr.softwareVersion.get("product_version_text_short") != null) { details.put("product_version_text_short", hr.softwareVersion.get("product_version_text_short")); cmd.setHypervisorVersion(hr.softwareVersion.get("product_version_text_short")); - cmd.setHypervisorVersion(_host.product_version); + cmd.setHypervisorVersion(_host.productVersion); } if (_privateNetworkName != null) { details.put("private.network.device", _privateNetworkName); @@ -6108,7 +5402,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } } - ram = (long)((ram - dom0Ram - _xs_memory_used) * _xs_virtualization_factor); + ram = (long)((ram - dom0Ram - _xsMemoryUsed) * _xsVirtualizationFactor); cmd.setMemory(ram); cmd.setDom0MinMemory(dom0Ram); @@ -6238,8 +5532,12 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe CheckXenHostInfo(); storageHandler = getStorageHandler(); - return true; + _vrResource = new VirtualRoutingResource(this); + if (!_vrResource.configure(name, params)) { + throw new ConfigurationException("Unable to configure VirtualRoutingResource"); + } + return true; } protected StorageSubsystemCommandHandler getStorageHandler() { @@ -6248,9 +5546,9 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } private void CheckXenHostInfo() throws ConfigurationException { - Connection conn = _connPool.slaveConnect(_host.ip, _username, _password); - if (conn == null) { - throw new ConfigurationException("Can not create slave connection to " + _host.ip); + Connection conn = ConnPool.getConnect(_host.ip, _username, _password); + if( conn == null ) { + throw new ConfigurationException("Can not create connection to " + _host.ip); } try { Host.Record hostRec = null; @@ -6270,20 +5568,12 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } } finally { try { - Session.localLogout(conn); + Session.logout(conn); } catch (Exception e) { } } } - void destroyVDI(Connection conn, VDI vdi) { - try { - vdi.destroy(conn); - } catch (Exception e) { - String msg = "destroy VDI failed due to " + e.toString(); - s_logger.warn(msg); - } - } public CreateAnswer execute(CreateCommand cmd) { Connection conn = getConnection(); @@ -6313,7 +5603,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe s_logger.debug("Succesfully created VDI for " + cmd + ". Uuid = " + vdir.uuid); VolumeTO vol = - new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), vdir.nameLabel, pool.getPath(), vdir.uuid, vdir.virtualSize, null); + new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), vdir.nameLabel, pool.getPath(), vdir.uuid, vdir.virtualSize, null); return new CreateAnswer(cmd, vol); } catch (Exception e) { s_logger.warn("Unable to create volume; Pool=" + pool + "; Disk: " + dskch, e); @@ -6383,8 +5673,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe Host host = Host.getByUuid(conn, _host.uuid); SR sr = - SR.create(conn, host, deviceConfig, new Long(0), name, uri.getHost() + uri.getPath(), SRType.NFS.toString(), "user", shared, - new HashMap()); + SR.create(conn, host, deviceConfig, new Long(0), name, uri.getHost() + uri.getPath(), SRType.NFS.toString(), "user", shared, + new HashMap()); if (!checkSR(conn, sr)) { throw new Exception("no attached PBD"); } @@ -6473,7 +5763,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } protected SR getIscsiSR(Connection conn, String srNameLabel, String target, String path, String chapInitiatorUsername, String chapInitiatorPassword, - boolean ignoreIntroduceException) { + boolean ignoreIntroduceException) { synchronized (srNameLabel.intern()) { Map deviceConfig = new HashMap(); try { @@ -6516,7 +5806,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } if (target.equals(dc.get("target")) && targetiqn.equals(dc.get("targetIQN")) && lunid.equals(dc.get("lunid"))) { throw new CloudRuntimeException("There is a SR using the same configuration target:" + dc.get("target") + ", targetIQN:" + dc.get("targetIQN") + - ", lunid:" + dc.get("lunid") + " for pool " + srNameLabel + "on host:" + _host.uuid); + ", lunid:" + dc.get("lunid") + " for pool " + srNameLabel + "on host:" + _host.uuid); } } deviceConfig.put("target", target); @@ -6647,7 +5937,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe if (server.equals(dc.get("server")) && serverpath.equals(dc.get("serverpath"))) { throw new CloudRuntimeException("There is a SR using the same configuration server:" + dc.get("server") + ", serverpath:" + dc.get("serverpath") + - " for pool " + pool.getUuid() + "on host:" + _host.uuid); + " for pool " + pool.getUuid() + "on host:" + _host.uuid); } } @@ -6655,8 +5945,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe deviceConfig.put("serverpath", serverpath); Host host = Host.getByUuid(conn, _host.uuid); SR sr = - SR.create(conn, host, deviceConfig, new Long(0), pool.getUuid(), Long.toString(pool.getId()), SRType.NFS.toString(), "user", true, - new HashMap()); + SR.create(conn, host, deviceConfig, new Long(0), pool.getUuid(), Long.toString(pool.getId()), SRType.NFS.toString(), "user", true, + new HashMap()); sr.scan(conn); return sr; } catch (XenAPIException e) { @@ -6710,54 +6000,6 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe return new Answer(cmd, true, "Success"); } - public CopyVolumeAnswer execute(final CopyVolumeCommand cmd) { - Connection conn = getConnection(); - String volumeUUID = cmd.getVolumePath(); - StorageFilerTO poolTO = cmd.getPool(); - String secondaryStorageURL = cmd.getSecondaryStorageURL(); - boolean toSecondaryStorage = cmd.toSecondaryStorage(); - int wait = cmd.getWait(); - try { - URI uri = new URI(secondaryStorageURL); - String remoteVolumesMountPath = uri.getHost() + ":" + uri.getPath() + "/volumes/"; - String volumeFolder = String.valueOf(cmd.getVolumeId()) + "/"; - String mountpoint = remoteVolumesMountPath + volumeFolder; - SR primaryStoragePool = getStorageRepository(conn, poolTO.getUuid()); - String srUuid = primaryStoragePool.getUuid(conn); - if (toSecondaryStorage) { - // Create the volume folder - if (!createSecondaryStorageFolder(conn, remoteVolumesMountPath, volumeFolder)) { - throw new InternalErrorException("Failed to create the volume folder."); - } - SR secondaryStorage = null; - try { - // Create a SR for the volume UUID folder - secondaryStorage = createNfsSRbyURI(conn, new URI(secondaryStorageURL + "/volumes/" + volumeFolder), false); - // Look up the volume on the source primary storage pool - VDI srcVolume = getVDIbyUuid(conn, volumeUUID); - // Copy the volume to secondary storage - VDI destVolume = cloudVDIcopy(conn, srcVolume, secondaryStorage, wait); - String destVolumeUUID = destVolume.getUuid(conn); - return new CopyVolumeAnswer(cmd, true, null, null, destVolumeUUID); - } finally { - removeSR(conn, secondaryStorage); - } - } else { - try { - String volumePath = mountpoint + "/" + volumeUUID + ".vhd"; - String uuid = copy_vhd_from_secondarystorage(conn, volumePath, srUuid, wait); - return new CopyVolumeAnswer(cmd, true, null, srUuid, uuid); - } finally { - deleteSecondaryStorageFolder(conn, remoteVolumesMountPath, volumeFolder); - } - } - } catch (Exception e) { - String msg = "Catch Exception " + e.getClass().getName() + " due to " + e.toString(); - s_logger.warn(msg, e); - return new CopyVolumeAnswer(cmd, false, msg, null, null); - } - } - protected VDI createVdi(SR sr, String vdiNameLabel, Long volumeSize) throws Types.XenAPIException, XmlRpcException { VDI vdi = null; @@ -6797,9 +6039,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe return vdi; } - protected void handleSrAndVdiDetach(String iqn) throws Exception { - Connection conn = getConnection(); - + protected void handleSrAndVdiDetach(String iqn, Connection conn) throws Exception { SR sr = getStorageRepository(conn, iqn); removeSR(conn, sr); @@ -6824,7 +6064,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe if (cmd.getAttach() && cmd.isManaged()) { SR sr = - getIscsiSR(conn, cmd.get_iScsiName(), cmd.getStorageHost(), cmd.get_iScsiName(), cmd.getChapInitiatorUsername(), cmd.getChapInitiatorPassword(), true); + getIscsiSR(conn, cmd.get_iScsiName(), cmd.getStorageHost(), cmd.get_iScsiName(), cmd.getChapInitiatorUsername(), cmd.getChapInitiatorPassword(), true); vdi = getVDIbyUuid(conn, cmd.getVolumePath(), false); @@ -6852,7 +6092,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe if (isHVM && !pvDrvInstalled) { s_logger.warn(errorMsg + ": You attempted an operation on a VM which requires PV drivers to be installed but the drivers were not detected"); return new AttachVolumeAnswer(cmd, - "You attempted an operation that requires PV drivers to be installed on the VM. Please install them by inserting xen-pv-drv.iso."); + "You attempted an operation that requires PV drivers to be installed on the VM. Please install them by inserting xen-pv-drv.iso."); } if (attach) { // Figure out the disk number to attach the VM to @@ -6907,7 +6147,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe vdi.setNameLabel(conn, "detached"); if (cmd.isManaged()) { - handleSrAndVdiDetach(cmd.get_iScsiName()); + handleSrAndVdiDetach(cmd.get_iScsiName(), conn); } return new AttachVolumeAnswer(cmd); @@ -7060,9 +6300,9 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe return new CreateVMSnapshotAnswer(cmd, cmd.getTarget(), cmd.getVolumeTOs()); } catch (Exception e) { String msg = ""; - if (e instanceof BadAsyncResult) { + if (e instanceof Types.BadAsyncResult) { String licenseKeyWord = "LICENCE_RESTRICTION"; - BadAsyncResult errorResult = (BadAsyncResult)e; + Types.BadAsyncResult errorResult = (Types.BadAsyncResult)e; if (errorResult.shortDescription != null && errorResult.shortDescription.contains(licenseKeyWord)) { msg = licenseKeyWord; } @@ -7079,7 +6319,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe Set vbds = vmSnapshot.getVBDs(conn); for (VBD vbd : vbds) { VBD.Record vbdr = vbd.getRecord(conn); - if (vbdr.type == VbdType.DISK) { + if (vbdr.type == Types.VbdType.DISK) { VDI vdi = vbdr.VDI; vdi.destroy(conn); } @@ -7098,12 +6338,12 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } } - private VM createWorkingVM(Connection conn, String vmName, String guestOSType, List listVolumeTo) throws BadServerResponse, VmBadPowerState, SrFull, - OperationNotAllowed, XenAPIException, XmlRpcException { + private VM createWorkingVM(Connection conn, String vmName, String guestOSType, List listVolumeTo) throws BadServerResponse, Types.VmBadPowerState, Types.SrFull, + Types.OperationNotAllowed, XenAPIException, XmlRpcException { String guestOsTypeName = getGuestOsType(guestOSType, false); if (guestOsTypeName == null) { String msg = - " Hypervisor " + this.getClass().getName() + " doesn't support guest OS type " + guestOSType + ". you can choose 'Other install media' to run it as HVM"; + " Hypervisor " + this.getClass().getName() + " doesn't support guest OS type " + guestOSType + ". you can choose 'Other install media' to run it as HVM"; s_logger.warn(msg); throw new CloudRuntimeException(msg); } @@ -7154,7 +6394,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe VM snapshot = snapshots.iterator().next(); Set vbds = snapshot.getVBDs(conn); for (VBD vbd : vbds) { - if (vbd.getType(conn) == VbdType.DISK) { + if (vbd.getType(conn) == Types.VbdType.DISK) { VDI vdi = vbd.getVDI(conn); vdiList.add(vdi); } @@ -7279,140 +6519,6 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe return SRType.LVMOHBA.equals(type) || SRType.LVMOISCSI.equals(type) || SRType.LVM.equals(type); } - protected ManageSnapshotAnswer execute(final ManageSnapshotCommand cmd) { - Connection conn = getConnection(); - long snapshotId = cmd.getSnapshotId(); - String snapshotName = cmd.getSnapshotName(); - - // By default assume failure - boolean success = false; - String cmdSwitch = cmd.getCommandSwitch(); - String snapshotOp = "Unsupported snapshot command." + cmdSwitch; - if (cmdSwitch.equals(ManageSnapshotCommand.CREATE_SNAPSHOT)) { - snapshotOp = "create"; - } else if (cmdSwitch.equals(ManageSnapshotCommand.DESTROY_SNAPSHOT)) { - snapshotOp = "destroy"; - } - String details = "ManageSnapshotCommand operation: " + snapshotOp + " Failed for snapshotId: " + snapshotId; - String snapshotUUID = null; - - try { - if (cmdSwitch.equals(ManageSnapshotCommand.CREATE_SNAPSHOT)) { - // Look up the volume - String volumeUUID = cmd.getVolumePath(); - VDI volume = VDI.getByUuid(conn, volumeUUID); - - // Create a snapshot - VDI snapshot = volume.snapshot(conn, new HashMap()); - - if (snapshotName != null) { - snapshot.setNameLabel(conn, snapshotName); - } - // Determine the UUID of the snapshot - - snapshotUUID = snapshot.getUuid(conn); - String preSnapshotUUID = cmd.getSnapshotPath(); - //check if it is a empty snapshot - if (preSnapshotUUID != null) { - SR sr = volume.getSR(conn); - String srUUID = sr.getUuid(conn); - String type = sr.getType(conn); - Boolean isISCSI = IsISCSI(type); - String snapshotParentUUID = getVhdParent(conn, srUUID, snapshotUUID, isISCSI); - - String preSnapshotParentUUID = getVhdParent(conn, srUUID, preSnapshotUUID, isISCSI); - if (snapshotParentUUID != null && snapshotParentUUID.equals(preSnapshotParentUUID)) { - // this is empty snapshot, remove it - snapshot.destroy(conn); - snapshotUUID = preSnapshotUUID; - } - - } - success = true; - details = null; - } else if (cmd.getCommandSwitch().equals(ManageSnapshotCommand.DESTROY_SNAPSHOT)) { - // Look up the snapshot - snapshotUUID = cmd.getSnapshotPath(); - VDI snapshot = getVDIbyUuid(conn, snapshotUUID); - - snapshot.destroy(conn); - snapshotUUID = null; - success = true; - details = null; - } - } catch (XenAPIException e) { - details += ", reason: " + e.toString(); - s_logger.warn(details, e); - } catch (Exception e) { - details += ", reason: " + e.toString(); - s_logger.warn(details, e); - } - return new ManageSnapshotAnswer(cmd, snapshotId, snapshotUUID, success, details); - } - - protected CreatePrivateTemplateAnswer execute(final CreatePrivateTemplateFromVolumeCommand cmd) { - Connection conn = getConnection(); - String secondaryStoragePoolURL = cmd.getSecondaryStorageUrl(); - String volumeUUID = cmd.getVolumePath(); - Long accountId = cmd.getAccountId(); - String userSpecifiedName = cmd.getTemplateName(); - Long templateId = cmd.getTemplateId(); - int wait = cmd.getWait(); - String details = null; - SR tmpltSR = null; - boolean result = false; - String secondaryStorageMountPath = null; - String installPath = null; - try { - URI uri = new URI(secondaryStoragePoolURL); - secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath(); - installPath = "template/tmpl/" + accountId + "/" + templateId; - if (!createSecondaryStorageFolder(conn, secondaryStorageMountPath, installPath)) { - details = " Filed to create folder " + installPath + " in secondary storage"; - s_logger.warn(details); - return new CreatePrivateTemplateAnswer(cmd, false, details); - } - - VDI volume = getVDIbyUuid(conn, volumeUUID); - // create template SR - URI tmpltURI = new URI(secondaryStoragePoolURL + "/" + installPath); - tmpltSR = createNfsSRbyURI(conn, tmpltURI, false); - - // copy volume to template SR - VDI tmpltVDI = cloudVDIcopy(conn, volume, tmpltSR, wait); - // scan makes XenServer pick up VDI physicalSize - tmpltSR.scan(conn); - if (userSpecifiedName != null) { - tmpltVDI.setNameLabel(conn, userSpecifiedName); - } - - String tmpltUUID = tmpltVDI.getUuid(conn); - String tmpltFilename = tmpltUUID + ".vhd"; - long virtualSize = tmpltVDI.getVirtualSize(conn); - long physicalSize = tmpltVDI.getPhysicalUtilisation(conn); - // create the template.properties file - String templatePath = secondaryStorageMountPath + "/" + installPath; - result = postCreatePrivateTemplate(conn, templatePath, tmpltFilename, tmpltUUID, userSpecifiedName, null, physicalSize, virtualSize, templateId); - if (!result) { - throw new CloudRuntimeException("Could not create the template.properties file on secondary storage dir: " + tmpltURI); - } - installPath = installPath + "/" + tmpltFilename; - removeSR(conn, tmpltSR); - tmpltSR = null; - return new CreatePrivateTemplateAnswer(cmd, true, null, installPath, virtualSize, physicalSize, tmpltUUID, ImageFormat.VHD); - } catch (Exception e) { - if (tmpltSR != null) { - removeSR(conn, tmpltSR); - } - if (secondaryStorageMountPath != null) { - deleteSecondaryStorageFolder(conn, secondaryStorageMountPath, installPath); - } - details = "Creating template from volume " + volumeUUID + " failed due to " + e.toString(); - s_logger.error(details, e); - } - return new CreatePrivateTemplateAnswer(cmd, result, details); - } - protected Answer execute(final UpgradeSnapshotCommand cmd) { String secondaryStorageUrl = cmd.getSecondaryStorageUrl(); @@ -7442,60 +6548,6 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe return new Answer(cmd, false, "failure"); } - protected CreatePrivateTemplateAnswer execute(final CreatePrivateTemplateFromSnapshotCommand cmd) { - Connection conn = getConnection(); - Long accountId = cmd.getAccountId(); - Long volumeId = cmd.getVolumeId(); - String secondaryStorageUrl = cmd.getSecondaryStorageUrl(); - String backedUpSnapshotUuid = cmd.getSnapshotUuid(); - Long newTemplateId = cmd.getNewTemplateId(); - String userSpecifiedName = cmd.getTemplateName(); - int wait = cmd.getWait(); - // By default, assume failure - String details = null; - boolean result = false; - String secondaryStorageMountPath = null; - String installPath = null; - try { - URI uri = new URI(secondaryStorageUrl); - secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath(); - installPath = "template/tmpl/" + accountId + "/" + newTemplateId; - if (!createSecondaryStorageFolder(conn, secondaryStorageMountPath, installPath)) { - details = " Filed to create folder " + installPath + " in secondary storage"; - s_logger.warn(details); - return new CreatePrivateTemplateAnswer(cmd, false, details); - } - String templatePath = secondaryStorageMountPath + "/" + installPath; - // create snapshot SR - String filename = backedUpSnapshotUuid; - if (!filename.startsWith("VHD-") && !filename.endsWith(".vhd")) { - filename = backedUpSnapshotUuid + ".vhd"; - } - String snapshotPath = secondaryStorageMountPath + "/snapshots/" + accountId + "/" + volumeId + "/" + filename; - String results = createTemplateFromSnapshot(conn, templatePath, snapshotPath, wait); - String[] tmp = results.split("#"); - String tmpltUuid = tmp[1]; - long physicalSize = Long.parseLong(tmp[2]); - long virtualSize = Long.parseLong(tmp[3]) * 1024 * 1024; - String tmpltFilename = tmpltUuid + ".vhd"; - - // create the template.properties file - result = postCreatePrivateTemplate(conn, templatePath, tmpltFilename, tmpltUuid, userSpecifiedName, null, physicalSize, virtualSize, newTemplateId); - if (!result) { - throw new CloudRuntimeException("Could not create the template.properties file on secondary storage dir: " + templatePath); - } - installPath = installPath + "/" + tmpltFilename; - return new CreatePrivateTemplateAnswer(cmd, true, null, installPath, virtualSize, physicalSize, tmpltUuid, ImageFormat.VHD); - } catch (Exception e) { - if (secondaryStorageMountPath != null) { - deleteSecondaryStorageFolder(conn, secondaryStorageMountPath, installPath); - } - details = "Creating template from snapshot " + backedUpSnapshotUuid + " failed due to " + e.toString(); - s_logger.error(details, e); - } - return new CreatePrivateTemplateAnswer(cmd, result, details); - } - private boolean destroySnapshotOnPrimaryStorageExceptThis(Connection conn, String volumeUuid, String avoidSnapshotUuid) { try { VDI volume = getVDIbyUuid(conn, volumeUuid); @@ -7526,203 +6578,6 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe return false; } - protected BackupSnapshotAnswer execute(final BackupSnapshotCommand cmd) { - Connection conn = getConnection(); - String primaryStorageNameLabel = cmd.getPrimaryStoragePoolNameLabel(); - Long dcId = cmd.getDataCenterId(); - Long accountId = cmd.getAccountId(); - Long volumeId = cmd.getVolumeId(); - String secondaryStorageUrl = cmd.getSecondaryStorageUrl(); - String snapshotUuid = cmd.getSnapshotUuid(); // not null: Precondition. - String prevBackupUuid = cmd.getPrevBackupUuid(); - String prevSnapshotUuid = cmd.getPrevSnapshotUuid(); - int wait = cmd.getWait(); - Long secHostId = cmd.getSecHostId(); - // By default assume failure - String details = null; - boolean success = false; - String snapshotBackupUuid = null; - boolean fullbackup = true; - try { - SR primaryStorageSR = getSRByNameLabelandHost(conn, primaryStorageNameLabel); - if (primaryStorageSR == null) { - throw new InternalErrorException("Could not backup snapshot because the primary Storage SR could not be created from the name label: " + - primaryStorageNameLabel); - } - String psUuid = primaryStorageSR.getUuid(conn); - Boolean isISCSI = IsISCSI(primaryStorageSR.getType(conn)); - URI uri = new URI(secondaryStorageUrl); - String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath(); - VDI snapshotVdi = getVDIbyUuid(conn, snapshotUuid); - String snapshotPaUuid = null; - if (prevBackupUuid != null) { - try { - snapshotPaUuid = getVhdParent(conn, psUuid, snapshotUuid, isISCSI); - if (snapshotPaUuid != null) { - String snashotPaPaPaUuid = getVhdParent(conn, psUuid, snapshotPaUuid, isISCSI); - String prevSnashotPaUuid = getVhdParent(conn, psUuid, prevSnapshotUuid, isISCSI); - if (snashotPaPaPaUuid != null && prevSnashotPaUuid != null && prevSnashotPaUuid.equals(snashotPaPaPaUuid)) { - fullbackup = false; - } - } - } catch (Exception e) { - } - } - - if (fullbackup) { - // the first snapshot is always a full snapshot - String folder = "snapshots/" + accountId + "/" + volumeId; - if (!createSecondaryStorageFolder(conn, secondaryStorageMountPath, folder)) { - details = " Filed to create folder " + folder + " in secondary storage"; - s_logger.warn(details); - return new BackupSnapshotAnswer(cmd, false, details, null, false); - } - String snapshotMountpoint = secondaryStorageUrl + "/" + folder; - SR snapshotSr = null; - try { - snapshotSr = createNfsSRbyURI(conn, new URI(snapshotMountpoint), false); - VDI backedVdi = cloudVDIcopy(conn, snapshotVdi, snapshotSr, wait); - snapshotBackupUuid = backedVdi.getUuid(conn); - if (cmd.getSwift() != null) { - try { - swiftBackupSnapshot(conn, cmd.getSwift(), snapshotSr.getUuid(conn), snapshotBackupUuid, "S-" + volumeId.toString(), false, wait); - snapshotBackupUuid = snapshotBackupUuid + ".vhd"; - } finally { - deleteSnapshotBackup(conn, dcId, accountId, volumeId, secondaryStorageMountPath, snapshotBackupUuid); - } - } else if (cmd.getS3() != null) { - try { - backupSnapshotToS3(conn, cmd.getS3(), snapshotSr.getUuid(conn), snapshotBackupUuid, isISCSI, wait); - snapshotBackupUuid = snapshotBackupUuid + ".vhd"; - } finally { - deleteSnapshotBackup(conn, dcId, accountId, volumeId, secondaryStorageMountPath, snapshotBackupUuid); - } - } - success = true; - } finally { - if (snapshotSr != null) { - removeSR(conn, snapshotSr); - } - } - } else { - String primaryStorageSRUuid = primaryStorageSR.getUuid(conn); - if (cmd.getSwift() != null) { - swiftBackupSnapshot(conn, cmd.getSwift(), primaryStorageSRUuid, snapshotPaUuid, "S-" + volumeId.toString(), isISCSI, wait); - if (isISCSI) { - snapshotBackupUuid = "VHD-" + snapshotPaUuid; - } else { - snapshotBackupUuid = snapshotPaUuid + ".vhd"; - } - success = true; - } else if (cmd.getS3() != null) { - backupSnapshotToS3(conn, cmd.getS3(), primaryStorageSRUuid, snapshotPaUuid, isISCSI, wait); - } else { - snapshotBackupUuid = - backupSnapshot(conn, primaryStorageSRUuid, dcId, accountId, volumeId, secondaryStorageMountPath, snapshotUuid, prevBackupUuid, isISCSI, wait, - secHostId); - success = (snapshotBackupUuid != null); - } - } - String volumeUuid = cmd.getVolumePath(); - destroySnapshotOnPrimaryStorageExceptThis(conn, volumeUuid, snapshotUuid); - if (success) { - details = "Successfully backedUp the snapshotUuid: " + snapshotUuid + " to secondary storage."; - - } - } catch (XenAPIException e) { - details = "BackupSnapshot Failed due to " + e.toString(); - s_logger.warn(details, e); - } catch (Exception e) { - details = "BackupSnapshot Failed due to " + e.getMessage(); - s_logger.warn(details, e); - } - - return new BackupSnapshotAnswer(cmd, success, details, snapshotBackupUuid, fullbackup); - } - - private boolean - backupSnapshotToS3(final Connection connection, final S3TO s3, final String srUuid, final String snapshotUuid, final Boolean iSCSIFlag, final int wait) { - - final String filename = iSCSIFlag ? "VHD-" + snapshotUuid : snapshotUuid + ".vhd"; - final String dir = (iSCSIFlag ? "/dev/VG_XenStorage-" : "/var/run/sr-mount/") + srUuid; - final String key = String.format("/snapshots/%1$s", snapshotUuid); - - try { - - final List parameters = newArrayList(flattenProperties(s3, S3Utils.ClientOptions.class)); - // https workaround for Introspector bug that does not - // recognize Boolean accessor methods ... - parameters.addAll(Arrays.asList("operation", "put", "filename", dir + "/" + filename, "iSCSIFlag", iSCSIFlag.toString(), "bucket", s3.getBucketName(), "key", - key, "https", s3.isHttps() != null ? s3.isHttps().toString() : "null")); - final String result = callHostPluginAsync(connection, "s3xen", "s3", wait, parameters.toArray(new String[parameters.size()])); - - if (result != null && result.equals("true")) { - return true; - } - - } catch (Exception e) { - s_logger.error(String.format("S3 upload failed of snapshot %1$s due to %2$s.", snapshotUuid, e.toString()), e); - } - - return false; - - } - - protected CreateVolumeFromSnapshotAnswer execute(final CreateVolumeFromSnapshotCommand cmd) { - Connection conn = getConnection(); - String primaryStorageNameLabel = cmd.getPrimaryStoragePoolNameLabel(); - Long accountId = cmd.getAccountId(); - Long volumeId = cmd.getVolumeId(); - String secondaryStorageUrl = cmd.getSecondaryStorageUrl(); - String backedUpSnapshotUuid = cmd.getSnapshotUuid(); - int wait = cmd.getWait(); - boolean result = false; - // Generic error message. - String details = null; - String volumeUUID = null; - SR snapshotSR = null; - - if (secondaryStorageUrl == null) { - details += " because the URL passed: " + secondaryStorageUrl + " is invalid."; - return new CreateVolumeFromSnapshotAnswer(cmd, result, details, volumeUUID); - } - try { - SR primaryStorageSR = getSRByNameLabelandHost(conn, primaryStorageNameLabel); - if (primaryStorageSR == null) { - throw new InternalErrorException("Could not create volume from snapshot because the primary Storage SR could not be created from the name label: " + - primaryStorageNameLabel); - } - // Get the absolute path of the snapshot on the secondary storage. - URI snapshotURI = new URI(secondaryStorageUrl + "/snapshots/" + accountId + "/" + volumeId); - String filename = backedUpSnapshotUuid; - if (!filename.startsWith("VHD-") && !filename.endsWith(".vhd")) { - filename = backedUpSnapshotUuid + ".vhd"; - } - String snapshotPath = snapshotURI.getHost() + ":" + snapshotURI.getPath() + "/" + filename; - String srUuid = primaryStorageSR.getUuid(conn); - volumeUUID = copy_vhd_from_secondarystorage(conn, snapshotPath, srUuid, wait); - result = true; - } catch (XenAPIException e) { - details += " due to " + e.toString(); - s_logger.warn(details, e); - } catch (Exception e) { - details += " due to " + e.getMessage(); - s_logger.warn(details, e); - } finally { - // In all cases, if the temporary SR was created, forget it. - if (snapshotSR != null) { - removeSR(conn, snapshotSR); - } - } - if (!result) { - // Is this logged at a higher level? - s_logger.error(details); - } - - // In all cases return something. - return new CreateVolumeFromSnapshotAnswer(cmd, result, details, volumeUUID); - } - protected VM getVM(Connection conn, String vmName) { // Look up VMs with the specified name Set vms; @@ -7879,7 +6734,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } protected boolean postCreatePrivateTemplate(Connection conn, String templatePath, String tmpltFilename, String templateName, String templateDescription, - String checksum, long size, long virtualSize, long templateId) { + String checksum, long size, long virtualSize, long templateId) { if (templateDescription == null) { templateDescription = ""; @@ -7890,9 +6745,9 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } String result = - callHostPlugin(conn, "vmopsSnapshot", "post_create_private_template", "templatePath", templatePath, "templateFilename", tmpltFilename, "templateName", - templateName, "templateDescription", templateDescription, "checksum", checksum, "size", String.valueOf(size), "virtualSize", String.valueOf(virtualSize), - "templateId", String.valueOf(templateId)); + callHostPlugin(conn, "vmopsSnapshot", "post_create_private_template", "templatePath", templatePath, "templateFilename", tmpltFilename, "templateName", + templateName, "templateDescription", templateDescription, "checksum", checksum, "size", String.valueOf(size), "virtualSize", String.valueOf(virtualSize), + "templateId", String.valueOf(templateId)); boolean success = false; if (result != null && !result.isEmpty()) { @@ -7911,8 +6766,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe protected String getVhdParent(Connection conn, String primaryStorageSRUuid, String snapshotUuid, Boolean isISCSI) { String parentUuid = - callHostPlugin(conn, "vmopsSnapshot", "getVhdParent", "primaryStorageSRUuid", primaryStorageSRUuid, "snapshotUuid", snapshotUuid, "isISCSI", - isISCSI.toString()); + callHostPlugin(conn, "vmopsSnapshot", "getVhdParent", "primaryStorageSRUuid", primaryStorageSRUuid, "snapshotUuid", snapshotUuid, "isISCSI", + isISCSI.toString()); if (parentUuid == null || parentUuid.isEmpty() || parentUuid.equalsIgnoreCase("None")) { s_logger.debug("Unable to get parent of VHD " + snapshotUuid + " in SR " + primaryStorageSRUuid); @@ -7922,41 +6777,16 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe return parentUuid; } - protected boolean destroySnapshotOnPrimaryStorage(Connection conn, String snapshotUuid) { - // Precondition snapshotUuid != null - try { - VDI snapshot = getVDIbyUuid(conn, snapshotUuid); - if (snapshot == null) { - throw new InternalErrorException("Could not destroy snapshot " + snapshotUuid + " because the snapshot VDI was null"); - } - snapshot.destroy(conn); - s_logger.debug("Successfully destroyed snapshotUuid: " + snapshotUuid + " on primary storage"); - return true; - } catch (XenAPIException e) { - String msg = "Destroy snapshotUuid: " + snapshotUuid + " on primary storage failed due to " + e.toString(); - s_logger.error(msg, e); - } catch (Exception e) { - String msg = "Destroy snapshotUuid: " + snapshotUuid + " on primary storage failed due to " + e.getMessage(); - s_logger.warn(msg, e); - } - - return false; - } - protected String deleteSnapshotBackup(Connection conn, Long dcId, Long accountId, Long volumeId, String secondaryStorageMountPath, String backupUUID) { // If anybody modifies the formatting below again, I'll skin them String result = - callHostPlugin(conn, "vmopsSnapshot", "deleteSnapshotBackup", "backupUUID", backupUUID, "dcId", dcId.toString(), "accountId", accountId.toString(), - "volumeId", volumeId.toString(), "secondaryStorageMountPath", secondaryStorageMountPath); + callHostPlugin(conn, "vmopsSnapshot", "deleteSnapshotBackup", "backupUUID", backupUUID, "dcId", dcId.toString(), "accountId", accountId.toString(), + "volumeId", volumeId.toString(), "secondaryStorageMountPath", secondaryStorageMountPath); return result; } - protected boolean deleteSnapshotsDir(Connection conn, Long dcId, Long accountId, Long volumeId, String secondaryStorageMountPath) { - return deleteSecondaryStorageFolder(conn, secondaryStorageMountPath, "snapshots" + "/" + accountId.toString() + "/" + volumeId.toString()); - } - @Override public boolean start() { return true; @@ -8007,35 +6837,11 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe Host.Record hostr = poolr.master.getRecord(conn); if (_host.uuid.equals(hostr.uuid)) { - boolean mastermigrated = false; Map hostMap = Host.getAllRecords(conn); - if (hostMap.size() != 1) { - Host newMaster = null; - Host.Record newMasterRecord = null; - for (Map.Entry entry : hostMap.entrySet()) { - if (_host.uuid.equals(entry.getValue().uuid)) { - continue; - } - newMaster = entry.getKey(); - newMasterRecord = entry.getValue(); - s_logger.debug("New master for the XenPool is " + newMasterRecord.uuid + " : " + newMasterRecord.address); - try { - _connPool.switchMaster(_host.ip, _host.pool, conn, newMaster, _username, _password, _wait); - mastermigrated = true; - break; - } catch (Exception e) { - s_logger.warn("Unable to switch the new master to " + newMasterRecord.uuid + ": " + newMasterRecord.address + " due to " + e.toString()); - } - } - } else { - s_logger.debug("This is last host to eject, so don't need to eject: " + hostuuid); - return new Answer(cmd); - } - if (!mastermigrated) { - String msg = "this host is master, and cannot designate a new master"; + if (hostMap.size() > 1) { + String msg = "This host is XS master, please designate a new XS master throught XenCenter before you delete this host from CS"; s_logger.debug(msg); return new Answer(cmd, false, msg); - } } @@ -8160,7 +6966,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe public int speed; public Integer cpuSockets; public int cpus; - public String product_version; + public String productVersion; public String localSRuuid; @Override @@ -8192,8 +6998,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe Connection conn = getConnection(); String result = - callHostPlugin(conn, "vmops", "network_rules_vmSecondaryIp", "vmName", cmd.getVmName(), "vmMac", cmd.getVmMac(), "vmSecIp", cmd.getVmSecIp(), "action", - cmd.getAction()); + callHostPlugin(conn, "vmops", "network_rules_vmSecondaryIp", "vmName", cmd.getVmName(), "vmMac", cmd.getVmMac(), "vmSecIp", cmd.getVmSecIp(), "action", + cmd.getAction()); if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) { success = false; } @@ -8201,76 +7007,6 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe return new Answer(cmd, success, ""); } - private Answer execute(SetMonitorServiceCommand cmd) { - boolean success = true; - - String config = cmd.getConfiguration(); - - Connection conn = getConnection(); - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - - if (routerIp == null) { - return new Answer(cmd); - } - - String args = "monitor_service.sh " + routerIp; - args += " -c " + config; - - String result = callHostPlugin(conn, "vmops", "routerProxy", "args", args); - if (result == null || result.isEmpty()) { - return new Answer(cmd, false, "SetMonitorServiceCommand failed to create cfg file."); - } - - return new Answer(cmd, success, ""); - - } - - protected SetFirewallRulesAnswer execute(SetFirewallRulesCommand cmd) { - String[] results = new String[cmd.getRules().length]; - String callResult; - Connection conn = getConnection(); - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - String egressDefault = cmd.getAccessDetail(NetworkElementCommand.FIREWALL_EGRESS_DEFAULT); - FirewallRuleTO[] allrules = cmd.getRules(); - FirewallRule.TrafficType trafficType = allrules[0].getTrafficType(); - if (routerIp == null) { - return new SetFirewallRulesAnswer(cmd, false, results); - } - - String[][] rules = cmd.generateFwRules(); - String args = ""; - args += routerIp + " -F"; - if (trafficType == FirewallRule.TrafficType.Egress) { - args += " -E"; - if (egressDefault.equals("true")) { - args += " -P 1"; - } else if (egressDefault.equals("System")) { - args += " -P 2"; - } else { - args += " -P 0"; - } - } - StringBuilder sb = new StringBuilder(); - String[] fwRules = rules[0]; - if (fwRules.length > 0) { - for (int i = 0; i < fwRules.length; i++) { - sb.append(fwRules[i]).append(','); - } - args += " -a " + sb.toString(); - } - - callResult = callHostPlugin(conn, "vmops", "setFirewallRule", "args", args); - - if (callResult == null || callResult.isEmpty()) { - //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails - for (int i = 0; i < results.length; i++) { - results[i] = "Failed"; - } - return new SetFirewallRulesAnswer(cmd, false, results); - } - return new SetFirewallRulesAnswer(cmd, true, results); - } - protected Answer execute(final ClusterSyncCommand cmd) { Connection conn = getConnection(); //check if this is master @@ -8342,10 +7078,10 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe State newState = entry.getValue().second(); String host_uuid = entry.getValue().first(); final Ternary oldState = oldStates.remove(vm); - + // check if platform changed - if (platform != null && oldState != null){ - if (!platform.equals(oldState.third()) && newState != State.Stopped && newState != State.Stopping){ + if (platform != null && oldState != null) { + if (!platform.equals(oldState.third()) && newState != State.Stopped && newState != State.Stopping) { s_logger.warn("Detecting a change in platform for " + vm); changes.put(vm, new Ternary(host_uuid, newState, platform)); @@ -8514,28 +7250,14 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe * @param cmd * @return */ - private SetupGuestNetworkAnswer execute(SetupGuestNetworkCommand cmd) { + private ExecutionResult prepareNetworkElementCommand(SetupGuestNetworkCommand cmd) { Connection conn = getConnection(); NicTO nic = cmd.getNic(); - String domrIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - String domrGIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP); String domrName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); - String gw = cmd.getAccessDetail(NetworkElementCommand.GUEST_NETWORK_GATEWAY); - String cidr = Long.toString(NetUtils.getCidrSize(nic.getNetmask())); - String domainName = cmd.getNetworkDomain(); - String dns = cmd.getDefaultDns1(); - if (dns == null || dns.isEmpty()) { - dns = cmd.getDefaultDns2(); - } else { - String dns2 = cmd.getDefaultDns2(); - if (dns2 != null && !dns2.isEmpty()) { - dns += "," + dns2; - } - } try { Set vms = VM.getByNameLabel(conn, domrName); if (vms == null || vms.isEmpty()) { - return new SetupGuestNetworkAnswer(cmd, false, "Can not find VM " + domrName); + return new ExecutionResult(false, "Can not find VM " + domrName); } VM vm = vms.iterator().next(); String mac = nic.getMac(); @@ -8548,255 +7270,81 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } } if (domrVif == null) { - return new SetupGuestNetworkAnswer(cmd, false, "Can not find vif with mac " + mac + " for VM " + domrName); + return new ExecutionResult(false, "Can not find vif with mac " + mac + " for VM " + domrName); } - String args = "vpc_guestnw.sh " + domrIP + (cmd.isAdd() ? " -C" : " -D"); - String dev = "eth" + domrVif.getDevice(conn); - args += " -d " + dev; - args += " -i " + domrGIP; - args += " -g " + gw; - args += " -m " + cidr; - args += " -n " + NetUtils.getSubNet(domrGIP, nic.getNetmask()); - if (dns != null && !dns.isEmpty()) { - args += " -s " + dns; - } - if (domainName != null && !domainName.isEmpty()) { - args += " -e " + domainName; - } - String result = callHostPlugin(conn, "vmops", "routerProxy", "args", args); - if (result == null || result.isEmpty()) { - return new SetupGuestNetworkAnswer(cmd, false, "creating guest network failed due to " + ((result == null) ? "null" : result)); - } - return new SetupGuestNetworkAnswer(cmd, true, "success"); + nic.setDeviceId(Integer.valueOf(domrVif.getDevice(conn))); } catch (Exception e) { String msg = "Creating guest network failed due to " + e.toString(); s_logger.warn(msg, e); - return new SetupGuestNetworkAnswer(cmd, false, msg); + return new ExecutionResult(false, msg); } + return new ExecutionResult(true, null); } - protected IpAssocAnswer execute(IpAssocVpcCommand cmd) { + protected ExecutionResult prepareNetworkElementCommand(IpAssocVpcCommand cmd) { Connection conn = getConnection(); - String[] results = new String[cmd.getIpAddresses().length]; - int i = 0; String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); try { IpAddressTO[] ips = cmd.getIpAddresses(); for (IpAddressTO ip : ips) { - assignVPCPublicIpAddress(conn, routerName, routerIp, ip); - results[i++] = ip.getPublicIp() + " - success"; + VM router = getVM(conn, routerName); + + VIF correctVif = getVifByMac(conn, router, ip.getVifMacAddress()); + if (correctVif == null) { + if (ip.isAdd()) { + throw new InternalErrorException("Failed to find DomR VIF to associate IP with."); + } else { + s_logger.debug("VIF to deassociate IP with does not exist, return success"); + } + } + ip.setNicDevId(Integer.valueOf(correctVif.getDevice(conn))); } } catch (Exception e) { s_logger.error("Ip Assoc failure on applying one ip due to exception: ", e); - results[i++] = IpAssocAnswer.errorResult; + return new ExecutionResult(false, e.getMessage()); } - return new IpAssocAnswer(cmd, results); + return new ExecutionResult(true, null); } - protected Answer execute(Site2SiteVpnCfgCommand cmd) { - Connection conn = getConnection(); - String args = "ipsectunnel.sh " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - if (cmd.isCreate()) { - args += " -A"; - args += " -l "; - args += cmd.getLocalPublicIp(); - args += " -n "; - args += cmd.getLocalGuestCidr(); - args += " -g "; - args += cmd.getLocalPublicGateway(); - args += " -r "; - args += cmd.getPeerGatewayIp(); - args += " -N "; - args += cmd.getPeerGuestCidrList(); - args += " -e "; - args += "\"" + cmd.getEspPolicy() + "\""; - args += " -i "; - args += "\"" + cmd.getIkePolicy() + "\""; - args += " -t "; - args += Long.toString(cmd.getIkeLifetime()); - args += " -T "; - args += Long.toString(cmd.getEspLifetime()); - args += " -s "; - args += "\"" + cmd.getIpsecPsk() + "\""; - args += " -d "; - if (cmd.getDpd()) { - args += "1"; - } else { - args += "0"; - } - if (cmd.isPassive()) { - args += " -p "; - } - } else { - args += " -D"; - args += " -r "; - args += cmd.getPeerGatewayIp(); - args += " -n "; - args += cmd.getLocalGuestCidr(); - args += " -N "; - args += cmd.getPeerGuestCidrList(); - } - String result = callHostPlugin(conn, "vmops", "routerProxy", "args", args); - if (result == null || result.isEmpty()) { - return new Answer(cmd, false, "Configure site to site VPN failed! "); - } - return new Answer(cmd); - } - - protected SetSourceNatAnswer execute(SetSourceNatCommand cmd) { + protected ExecutionResult prepareNetworkElementCommand(SetSourceNatCommand cmd) { Connection conn = getConnection(); String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); IpAddressTO pubIp = cmd.getIpAddress(); try { VM router = getVM(conn, routerName); VIF correctVif = getCorrectVif(conn, router, pubIp); - String args = "vpc_snat.sh " + routerIp; + pubIp.setNicDevId(Integer.valueOf(correctVif.getDevice(conn))); - args += " -A "; - args += " -l "; - args += pubIp.getPublicIp(); - - args += " -c "; - args += "eth" + correctVif.getDevice(conn); - - String result = callHostPlugin(conn, "vmops", "routerProxy", "args", args); - if (result == null || result.isEmpty()) { - throw new InternalErrorException("Xen plugin \"vpc_snat\" failed."); - } - return new SetSourceNatAnswer(cmd, true, "success"); } catch (Exception e) { String msg = "Ip SNAT failure due to " + e.toString(); s_logger.error(msg, e); - return new SetSourceNatAnswer(cmd, false, msg); + return new ExecutionResult(false, msg); } + return new ExecutionResult(true, null); } - private SetNetworkACLAnswer execute(SetNetworkACLCommand cmd) { - String[] results = new String[cmd.getRules().length]; - String callResult; + protected ExecutionResult prepareNetworkElementCommand(SetNetworkACLCommand cmd) { Connection conn = getConnection(); String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - String privateGw = cmd.getAccessDetail(NetworkElementCommand.VPC_PRIVATE_GATEWAY); try { VM router = getVM(conn, routerName); - String[][] rules = cmd.generateFwRules(); - StringBuilder sb = new StringBuilder(); - String[] aclRules = rules[0]; - for (int i = 0; i < aclRules.length; i++) { - sb.append(aclRules[i]).append(','); - } - - if (privateGw != null) { - s_logger.debug("Private gateway configuration is set"); - } NicTO nic = cmd.getNic(); VIF vif = getVifByMac(conn, router, nic.getMac()); - if (privateGw != null) { - s_logger.debug("Private gateway configuration is set"); - String args = "vpc_privategw_acl.sh " + routerIp; - args += " -d " + "eth" + vif.getDevice(conn); - args += " -a " + sb.toString(); - - callResult = callHostPlugin(conn, "vmops", "routerProxy", "args", args); - if (callResult == null || callResult.isEmpty()) { - //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails - for (int i = 0; i < results.length; i++) { - results[i] = "Failed"; - } - return new SetNetworkACLAnswer(cmd, false, results); - } - } else { - String args = "vpc_acl.sh " + routerIp; - args += " -d " + "eth" + vif.getDevice(conn); - args += " -i " + nic.getIp(); - args += " -m " + Long.toString(NetUtils.getCidrSize(nic.getNetmask())); - args += " -a " + sb.toString(); - - callResult = callHostPlugin(conn, "vmops", "routerProxy", "args", args); - if (callResult == null || callResult.isEmpty()) { - //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails - for (int i = 0; i < results.length; i++) { - results[i] = "Failed"; - } - return new SetNetworkACLAnswer(cmd, false, results); - } - } - return new SetNetworkACLAnswer(cmd, true, results); + nic.setDeviceId(Integer.valueOf(vif.getDevice(conn))); } catch (Exception e) { - String msg = "SetNetworkACL failed due to " + e.toString(); + String msg = "Prepare SetNetworkACL failed due to " + e.toString(); s_logger.error(msg, e); - return new SetNetworkACLAnswer(cmd, false, results); - } - } - - protected SetPortForwardingRulesAnswer execute(SetPortForwardingRulesVpcCommand cmd) { - Connection conn = getConnection(); - - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - String[] results = new String[cmd.getRules().length]; - int i = 0; - - boolean endResult = true; - for (PortForwardingRuleTO rule : cmd.getRules()) { - String args = "vpc_portforwarding.sh " + routerIp; - args += rule.revoked() ? " -D" : " -A"; - args += " -P " + rule.getProtocol().toLowerCase(); - args += " -l " + rule.getSrcIp(); - args += " -p " + rule.getStringSrcPortRange(); - args += " -r " + rule.getDstIp(); - args += " -d " + rule.getStringDstPortRange().replace(":", "-"); - - String result = callHostPlugin(conn, "vmops", "routerProxy", "args", args.toString()); - - if (result == null || result.isEmpty()) { - results[i++] = "Failed"; - endResult = false; - } else { - results[i++] = null; - } - } - return new SetPortForwardingRulesAnswer(cmd, results, endResult); - } - - private SetStaticRouteAnswer execute(SetStaticRouteCommand cmd) { - String callResult; - Connection conn = getConnection(); - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - try { - String[] results = new String[cmd.getStaticRoutes().length]; - String[][] rules = cmd.generateSRouteRules(); - StringBuilder sb = new StringBuilder(); - String[] srRules = rules[0]; - for (int i = 0; i < srRules.length; i++) { - sb.append(srRules[i]).append(','); - } - String args = "vpc_staticroute.sh " + routerIp; - args += " -a " + sb.toString(); - callResult = callHostPlugin(conn, "vmops", "routerProxy", "args", args); - if (callResult == null || callResult.isEmpty()) { - //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails - for (int i = 0; i < results.length; i++) { - results[i] = "Failed"; - } - return new SetStaticRouteAnswer(cmd, false, results); - } - return new SetStaticRouteAnswer(cmd, true, results); - } catch (Exception e) { - String msg = "SetStaticRoute failed due to " + e.toString(); - s_logger.error(msg, e); - return new SetStaticRouteAnswer(cmd, false, null); + return new ExecutionResult(false, msg); } + return new ExecutionResult(true, null); } @Override @@ -8821,17 +7369,17 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe public void setRunLevel(int level) { } - private boolean is_xcp() { - Connection conn = getConnection(); - String result = callHostPlugin(conn, "ovstunnel", "is_xcp"); - if (result.equals("XCP")) - return true; - return false; - } + private boolean is_xcp() { + Connection conn = getConnection(); + String result = callHostPlugin(conn, "ovstunnel", "is_xcp"); + if (result.equals("XCP")) + return true; + return false; + } - private String getLabel() { - Connection conn = getConnection(); - String result = callHostPlugin(conn, "ovstunnel", "getLabel"); - return result; - } + private String getLabel() { + Connection conn = getConnection(); + String result = callHostPlugin(conn, "ovstunnel", "getLabel"); + return result; + } } diff --git a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServer56Resource.java b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServer56Resource.java index df43430d481..7e26a5cdb22 100644 --- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServer56Resource.java +++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServer56Resource.java @@ -16,25 +16,6 @@ // under the License. package com.cloud.hypervisor.xen.resource; -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -import javax.ejb.Local; - -import org.apache.log4j.Logger; -import org.apache.xmlrpc.XmlRpcException; - -import com.xensource.xenapi.Connection; -import com.xensource.xenapi.Host; -import com.xensource.xenapi.Network; -import com.xensource.xenapi.PIF; -import com.xensource.xenapi.Types.IpConfigurationMode; -import com.xensource.xenapi.Types.XenAPIException; -import com.xensource.xenapi.VLAN; -import com.xensource.xenapi.VM; - import com.cloud.agent.api.Answer; import com.cloud.agent.api.CheckOnHostAnswer; import com.cloud.agent.api.CheckOnHostCommand; @@ -47,6 +28,22 @@ import com.cloud.agent.api.StartupCommand; import com.cloud.resource.ServerResource; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.script.Script; +import com.xensource.xenapi.Connection; +import com.xensource.xenapi.Host; +import com.xensource.xenapi.Network; +import com.xensource.xenapi.PIF; +import com.xensource.xenapi.Types.IpConfigurationMode; +import com.xensource.xenapi.Types.XenAPIException; +import com.xensource.xenapi.VLAN; +import com.xensource.xenapi.VM; +import org.apache.log4j.Logger; +import org.apache.xmlrpc.XmlRpcException; + +import javax.ejb.Local; +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; @Local(value = ServerResource.class) public class XenServer56Resource extends CitrixResourceBase { @@ -127,7 +124,7 @@ public class XenServer56Resource extends CitrixResourceBase { @Override protected String networkUsage(Connection conn, final String privateIpAddress, final String option, final String vif) { - String args = "netusage.sh " + privateIpAddress + " "; + String args = ""; if (option.equals("get")) { args += "-g"; } else if (option.equals("create")) { @@ -142,7 +139,7 @@ public class XenServer56Resource extends CitrixResourceBase { args += vif; } - return callHostPlugin(conn, "vmops", "routerProxy", "args", args); + return executeInVR(privateIpAddress, "netusage.sh", args).getDetails(); } protected NetworkUsageAnswer VPCNetworkUsage(NetworkUsageCommand cmd) { @@ -151,8 +148,7 @@ public class XenServer56Resource extends CitrixResourceBase { String option = cmd.getOption(); String publicIp = cmd.getGatewayIP(); - String args = "vpc_netusage.sh " + cmd.getPrivateIP(); - args += " -l " + publicIp + " "; + String args = " -l " + publicIp + " "; if (option.equals("get")) { args += "-g"; } else if (option.equals("create")) { @@ -169,7 +165,7 @@ public class XenServer56Resource extends CitrixResourceBase { return new NetworkUsageAnswer(cmd, "success", 0L, 0L); } - String result = callHostPlugin(conn, "vmops", "routerProxy", "args", args); + String result = executeInVR(cmd.getPrivateIP(), "vpc_netusage.sh", args).getDetails(); if (option.equals("get") || option.equals("vpn")) { long[] stats = new long[2]; if (result != null) { diff --git a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServer56SP2Resource.java b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServer56SP2Resource.java index 89adf55a958..9e7d5dd09d0 100644 --- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServer56SP2Resource.java +++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServer56SP2Resource.java @@ -34,8 +34,8 @@ public class XenServer56SP2Resource extends XenServer56FP1Resource { public XenServer56SP2Resource() { super(); - _xs_memory_used = 128 * 1024 * 1024L; - _xs_virtualization_factor = 62.0 / 64.0; + _xsMemoryUsed = 128 * 1024 * 1024L; + _xsVirtualizationFactor = 62.0 / 64.0; } @Override diff --git a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServerConnectionPool.java b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServerConnectionPool.java index 90c6003a7f9..b779085f93c 100644 --- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServerConnectionPool.java +++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServerConnectionPool.java @@ -26,7 +26,6 @@ import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.Queue; -import java.util.Set; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; @@ -43,7 +42,6 @@ import com.xensource.xenapi.Pool; import com.xensource.xenapi.Session; import com.xensource.xenapi.Types; import com.xensource.xenapi.Types.BadServerResponse; -import com.xensource.xenapi.Types.UuidInvalid; import com.xensource.xenapi.Types.XenAPIException; import com.cloud.utils.NumbersUtil; @@ -55,7 +53,6 @@ public class XenServerConnectionPool { protected HashMap _conns = new HashMap(); protected int _retries; protected int _interval; - protected static boolean s_managePool = true; protected static long s_sleepOnError = 10 * 1000; // in ms static { File file = PropertiesUtil.findConfigFile("environment.properties"); @@ -68,15 +65,11 @@ public class XenServerConnectionPool { final Properties props = new Properties(); props.load(finputstream); finputstream.close(); - String search = props.getProperty("manage.xenserver.pool.master"); - if (search != null) { - s_managePool = Boolean.parseBoolean(search); - } - search = props.getProperty("sleep.interval.on.error"); + String search = props.getProperty("sleep.interval.on.error"); if (search != null) { s_sleepOnError = NumbersUtil.parseInterval(search, 10) * 1000; } - s_logger.info("XenServer Connection Pool Configs: manage.xenserver.pool.master=" + s_managePool + "; sleep.interval.on.error=" + s_sleepOnError); + s_logger.info("XenServer Connection Pool Configs: sleep.interval.on.error=" + s_sleepOnError); } catch (FileNotFoundException e) { s_logger.debug("File is not found", e); } catch (IOException e) { @@ -214,288 +207,27 @@ public class XenServerConnectionPool { return false; } - public void switchMaster(String slaveIp, String poolUuid, Connection conn, Host host, String username, Queue password, int wait) throws XmlRpcException, - XenAPIException { - synchronized (poolUuid.intern()) { - String masterIp = host.getAddress(conn); - s_logger.debug("Designating the new master to " + masterIp); - Pool.designateNewMaster(conn, host); - Connection slaveConn = null; - Connection masterConn = null; - int retry = 30; - for (int i = 0; i < retry; i++) { - forceSleep(5); - try { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Logging on as the slave to " + slaveIp); - } - slaveConn = null; - masterConn = null; - Session slaveSession = null; - slaveConn = new Connection(getURL(slaveIp), 10); - slaveSession = slaveLocalLoginWithPassword(slaveConn, username, password); - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Slave logon successful. session= " + slaveSession); - } - - Pool.Record pr = getPoolRecord(slaveConn); - Host master = pr.master; - String ma = master.getAddress(slaveConn); - if (!ma.trim().equals(masterIp.trim())) { - continue; - } - s_logger.debug("Logging on as the master to " + masterIp); - masterConn = new Connection(getURL(masterIp), 10); - loginWithPassword(masterConn, username, password, APIVersion.latest().toString()); - removeConnect(poolUuid); - ensurePoolIntegrity(masterConn, masterIp, username, password, wait); - return; - } catch (Types.HostIsSlave e) { - s_logger.debug("HostIsSlaveException: Still waiting for the conversion to the master"); - } catch (XmlRpcException e) { - s_logger.debug("XmlRpcException: Still waiting for the conversion to the master " + e.getMessage()); - } catch (Exception e) { - s_logger.debug("Exception: Still waiting for the conversion to the master" + e.getMessage()); - } finally { - if (masterConn != null) { - try { - Session.logout(masterConn); - } catch (Exception e) { - s_logger.debug("Unable to log out of session: " + e.getMessage()); - } - masterConn.dispose(); - masterConn = null; - } - localLogout(slaveConn); - slaveConn = null; - } - } - throw new CloudRuntimeException("Unable to logon to the new master after " + retry + " retries"); - } - } - - private void localLogout(Connection conn) { - if (conn == null) - return; + public Connection getConnect(String ip, String username, Queue password) { + Connection conn = new Connection(getURL(ip), 10); try { - if (s_logger.isTraceEnabled()) { - s_logger.trace("Logging out of the session " + conn.getSessionReference()); - } - Session.localLogout(conn); - } catch (Exception e) { - s_logger.debug("localLogout has problem " + e.getMessage()); - } finally { - conn.dispose(); - conn = null; - } - } - - public Connection slaveConnect(String ip, String username, Queue password) { - Connection conn = null; - try { - conn = new Connection(getURL(ip), 10); - slaveLocalLoginWithPassword(conn, username, password); - return conn; - } catch (Exception e) { - s_logger.debug("Failed to slave local login to " + ip); - } - return null; - } - - public Connection masterConnect(String ip, String username, Queue password) { - Connection conn = null; - try { - conn = new Connection(getURL(ip), 10); - s_logger.debug("Logging on as the master to " + ip); loginWithPassword(conn, username, password, APIVersion.latest().toString()); - return conn; - } catch (Exception e) { - s_logger.debug("Failed to slave local login to " + ip); - } - throw new RuntimeException("can not log in to master " + ip); - } - - public String getMasterIp(String ip, String username, Queue password) throws XenAPIException { - Connection slaveConn = null; - try { - slaveConn = new Connection(getURL(ip), 10); - slaveLocalLoginWithPassword(slaveConn, username, password); - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Slave logon to " + ip); - } - String masterIp = null; - Pool.Record pr = getPoolRecord(slaveConn); - Host master = pr.master; - masterIp = master.getAddress(slaveConn); - return masterIp; - } catch (Types.SessionAuthenticationFailed e) { - s_logger.debug("Failed to slave local login to " + ip + " due to " + e.toString()); - throw e; - } catch (Exception e) { - s_logger.debug("Failed to slave local login to " + ip + " due to " + e.toString()); - } finally { - localLogout(slaveConn); - slaveConn = null; - } - throw new RuntimeException("can not get master ip"); - } - - void PoolEmergencyTransitionToMaster(String slaveIp, String username, Queue password) { - if (!s_managePool) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Don't manage pool on error so sleeping for " + s_sleepOnError); - try { - Thread.sleep(s_sleepOnError); - } catch (InterruptedException ie) { - } - } - return; - } - - Connection slaveConn = null; - Connection c = null; - try { - s_logger.debug("Trying to transition master to " + slaveIp); - slaveConn = new Connection(getURL(slaveIp), 10); - slaveLocalLoginWithPassword(slaveConn, username, password); - Pool.emergencyTransitionToMaster(slaveConn); - // restart xapi in 10 sec - forceSleep(10); - // check if the master of this host is set correctly. - c = new Connection(getURL(slaveIp), 10); - for (int i = 0; i < 30; i++) { - try { - loginWithPassword(c, username, password, APIVersion.latest().toString()); - s_logger.debug("Succeeded to transition master to " + slaveIp); - return; - } catch (Types.HostIsSlave e) { - s_logger.debug("HostIsSlave: Still waiting for the conversion to the master " + slaveIp); - } catch (Exception e) { - s_logger.debug("Exception: Still waiting for the conversion to the master"); - } - forceSleep(2); - } - throw new RuntimeException("EmergencyTransitionToMaster failed after retry 30 times"); - } catch (Exception e) { - throw new RuntimeException("EmergencyTransitionToMaster failed due to " + e.getMessage()); - } finally { - localLogout(slaveConn); - slaveConn = null; - if (c != null) { - try { - Session.logout(c); - c.dispose(); - } catch (Exception e) { - } - } - } - - } - - private void PoolEmergencyResetMaster(String slaveIp, String masterIp, String username, Queue password) { - if (!s_managePool) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Don't manage pool on error so sleeping for " + s_sleepOnError); - try { - Thread.sleep(s_sleepOnError); - } catch (InterruptedException ie) { - } - } - return; - } - - Connection slaveConn = null; - try { - s_logger.debug("Trying to reset master of slave " + slaveIp + " to " + masterIp); - slaveConn = new Connection(getURL(slaveIp), 10); - slaveLocalLoginWithPassword(slaveConn, username, password); - Pool.emergencyResetMaster(slaveConn, masterIp); - forceSleep(10); - for (int i = 0; i < 30; i++) { - try { - slaveLocalLoginWithPassword(slaveConn, username, password); - Pool.Record pr = getPoolRecord(slaveConn); - String mIp = pr.master.getAddress(slaveConn); - if (mIp.trim().equals(masterIp.trim())) { - s_logger.debug("Succeeded to reset master of slave " + slaveIp + " to " + masterIp); - return; - } - } catch (Exception e) { - } finally { - localLogout(slaveConn); - slaveConn = null; - } - // wait 2 second - forceSleep(2); - } - throw new CloudRuntimeException("Unable to reset master of slave " + slaveIp + " to " + masterIp + "after 30 retry"); - } catch (Exception e) { - throw new CloudRuntimeException("Unable to reset master of slave " + slaveIp + " to " + masterIp + " due to " + e.toString()); - } finally { - localLogout(slaveConn); - slaveConn = null; - } - } - - protected void ensurePoolIntegrity(Connection conn, String masterIp, String username, Queue password, int wait) { - try { - // try recoverSlave first - Set rcSlaves = Pool.recoverSlaves(conn); - // wait 10 second - forceSleep(10); - for (Host slave : rcSlaves) { - for (int i = 0; i < 30; i++) { - Connection slaveConn = null; - try { - - String slaveIp = slave.getAddress(conn); - s_logger.debug("Logging on as the slave to " + slaveIp); - slaveConn = new Connection(getURL(slaveIp), 10); - slaveLocalLoginWithPassword(slaveConn, username, password); - Pool.Record pr = getPoolRecord(slaveConn); - String mIp = pr.master.getAddress(slaveConn); - if (mIp.trim().equals(masterIp.trim())) { - break; - } - } catch (Exception e) { - } finally { - localLogout(slaveConn); - slaveConn = null; - } - // wait 2 second - forceSleep(2); - } - } - // then try emergency reset master - Set slaves = Host.getAll(conn); - for (Host slave : slaves) { - String slaveIp = slave.getAddress(conn); - Connection slaveConn = null; - try { - s_logger.debug("Logging on as the slave to " + slaveIp); - - slaveConn = new Connection(getURL(slaveIp), 10); - slaveLocalLoginWithPassword(slaveConn, username, password); - Pool.Record slavePoolr = getPoolRecord(slaveConn); - String ip = slavePoolr.master.getAddress(slaveConn); - if (!masterIp.trim().equals(ip.trim())) { - PoolEmergencyResetMaster(slaveIp, masterIp, username, password); - } - } catch (Exception e) { - s_logger.debug("Unable to login to slave " + slaveIp + " error " + e.getMessage()); - } finally { - localLogout(slaveConn); - slaveConn = null; - } + } catch (Types.HostIsSlave e) { + String maddress = e.masterIPAddress; + conn = new Connection(getURL(maddress), 10); + try { + loginWithPassword(conn, username, password, APIVersion.latest().toString()); + } catch (Exception e1) { + String msg = "Unable to create master connection to host(" + maddress +") , due to " + e1.toString(); + s_logger.debug(msg); + throw new CloudRuntimeException(msg, e1); } } catch (Exception e) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Catch " + e.getClass().getName() + " due to " + e.toString()); - } + String msg = "Unable to create master connection to host(" + ip +") , due to " + e.toString(); + s_logger.debug(msg); + throw new CloudRuntimeException(msg, e); } + return conn; } public URL getURL(String ip) { @@ -512,39 +244,17 @@ public class XenServerConnectionPool { public Connection connect(String hostUuid, String poolUuid, String ipAddress, String username, Queue password, int wait) { XenServerConnection mConn = null; - Connection sConn = null; - String masterIp = null; if (hostUuid == null || poolUuid == null || ipAddress == null || username == null || password == null) { String msg = "Connect some parameter are null hostUuid:" + hostUuid + " ,poolUuid:" + poolUuid + " ,ipAddress:" + ipAddress; s_logger.debug(msg); throw new CloudRuntimeException(msg); } - Host host = null; synchronized (poolUuid.intern()) { // Let's see if it is an existing connection. mConn = getConnect(poolUuid); - if (mConn != null) { - try { - host = Host.getByUuid(mConn, hostUuid); - } catch (Types.SessionInvalid e) { - s_logger.debug("Session thgrough ip " + mConn.getIp() + " is invalid for pool(" + poolUuid + ") due to " + e.toString()); - try { - loginWithPassword(mConn, mConn.getUsername(), mConn.getPassword(), APIVersion.latest().toString()); - } catch (Exception e1) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("connect through IP(" + mConn.getIp() + " for pool(" + poolUuid + ") is broken due to " + e.toString()); - } - removeConnect(poolUuid); - mConn = null; - } - } catch (UuidInvalid e) { - String msg = - "Host(" + hostUuid + ") doesn't belong to pool(" + poolUuid + "), please execute 'xe pool-join master-address=" + mConn.getIp() + - " master-username=" + mConn.getUsername(); - if (s_logger.isDebugEnabled()) { - s_logger.debug(msg); - } - throw new CloudRuntimeException(msg, e); + if (mConn != null){ + try{ + Host.getByUuid(mConn, hostUuid); } catch (Exception e) { if (s_logger.isDebugEnabled()) { s_logger.debug("connect through IP(" + mConn.getIp() + " for pool(" + poolUuid + ") is broken due to " + e.toString()); @@ -554,114 +264,30 @@ public class XenServerConnectionPool { } } - if (mConn == null) { + if ( mConn == null ) { + mConn = new XenServerConnection(getURL(ipAddress), ipAddress, username, password, _retries, _interval, wait); try { + loginWithPassword(mConn, username, password, APIVersion.latest().toString()); + } catch (Types.HostIsSlave e) { + String maddress = e.masterIPAddress; + mConn = new XenServerConnection(getURL(maddress), maddress, username, password, _retries, _interval, wait); try { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Logging on as the slave to " + ipAddress); - } - sConn = new Connection(getURL(ipAddress), 5); - slaveLocalLoginWithPassword(sConn, username, password); - } catch (Exception e) { - String msg = "Unable to create slave connection to host(" + hostUuid + ") due to " + e.toString(); - if (s_logger.isDebugEnabled()) { - s_logger.debug(msg); - } - throw new CloudRuntimeException(msg, e); - } - Pool.Record pr = null; - try { - pr = getPoolRecord(sConn); - } catch (Exception e) { - PoolEmergencyTransitionToMaster(ipAddress, username, password); - mConn = new XenServerConnection(getURL(ipAddress), ipAddress, username, password, _retries, _interval, wait); - try { - loginWithPassword(mConn, username, password, APIVersion.latest().toString()); - pr = getPoolRecord(mConn); - } catch (Exception e1) { - String msg = "Unable to create master connection to host(" + hostUuid + ") after transition it to master, due to " + e1.toString(); - if (s_logger.isDebugEnabled()) { - s_logger.debug(msg); - } - throw new CloudRuntimeException(msg, e1); - } - if (!pr.uuid.equals(poolUuid)) { - String msg = "host(" + hostUuid + ") should be in pool(" + poolUuid + "), but it is actually in pool(" + pr.uuid + ")"; - if (s_logger.isDebugEnabled()) { - s_logger.debug(msg); - } - throw new CloudRuntimeException(msg); - } else { - if (s_managePool) { - ensurePoolIntegrity(mConn, ipAddress, username, password, wait); - } - addConnect(poolUuid, mConn); - return mConn; - } - } - if (!pr.uuid.equals(poolUuid)) { - String msg = "host(" + hostUuid + ") should be in pool(" + poolUuid + "), but it is actually in pool(" + pr.uuid + ")"; - if (s_logger.isDebugEnabled()) { - s_logger.debug(msg); - } - throw new CloudRuntimeException(msg); - } - try { - masterIp = pr.master.getAddress(sConn); - mConn = new XenServerConnection(getURL(masterIp), masterIp, username, password, _retries, _interval, wait); loginWithPassword(mConn, username, password, APIVersion.latest().toString()); - addConnect(poolUuid, mConn); - return mConn; - } catch (Exception e) { - String msg = "Unable to logon in " + masterIp + " as master in pool(" + poolUuid + ")"; - if (s_logger.isDebugEnabled()) { - s_logger.debug(msg); - } - throw new CloudRuntimeException(msg); + } catch (Exception e1) { + String msg = "Unable to create master connection to host(" + maddress +") , due to " + e1.toString(); + s_logger.debug(msg); + throw new CloudRuntimeException(msg, e1); + } - } finally { - localLogout(sConn); - sConn = null; + } catch (Exception e) { + String msg = "Unable to create master connection to host(" + ipAddress +") , due to " + e.toString(); + s_logger.debug(msg); + throw new CloudRuntimeException(msg, e); } + addConnect(poolUuid, mConn); } } - if (mConn != null) { - if (s_managePool) { - try { - Map args = new HashMap(); - host.callPlugin(mConn, "echo", "main", args); - } catch (Types.SessionInvalid e) { - if (s_logger.isDebugEnabled()) { - String msg = "Catch Exception: " + e.getClass().getName() + " Can't connect host " + ipAddress + " due to " + e.toString(); - s_logger.debug(msg); - } - PoolEmergencyResetMaster(ipAddress, mConn.getIp(), mConn.getUsername(), mConn.getPassword()); - } catch (Types.CannotContactHost e) { - if (s_logger.isDebugEnabled()) { - String msg = "Catch Exception: " + e.getClass().getName() + " Can't connect host " + ipAddress + " due to " + e.toString(); - s_logger.debug(msg); - } - PoolEmergencyResetMaster(ipAddress, mConn.getIp(), mConn.getUsername(), mConn.getPassword()); - } catch (Types.HostOffline e) { - if (s_logger.isDebugEnabled()) { - String msg = "Catch Exception: " + e.getClass().getName() + " Host is offline " + ipAddress + " due to " + e.toString(); - s_logger.debug(msg); - } - PoolEmergencyResetMaster(ipAddress, mConn.getIp(), mConn.getUsername(), mConn.getPassword()); - } catch (Types.HostNotLive e) { - String msg = "Catch Exception: " + e.getClass().getName() + " Host Not Live " + ipAddress + " due to " + e.toString(); - if (s_logger.isDebugEnabled()) { - s_logger.debug(msg); - } - PoolEmergencyResetMaster(ipAddress, mConn.getIp(), mConn.getUsername(), mConn.getPassword()); - } catch (Exception e) { - String msg = "Echo test failed on host " + hostUuid + " IP " + ipAddress; - s_logger.warn(msg, e); - throw new CloudRuntimeException(msg, e); - } - } - } return mConn; } @@ -840,16 +466,16 @@ public class XenServerConnectionPool { } @Override - protected Map dispatch(String method_call, Object[] method_params) throws XmlRpcException, XenAPIException { - if (method_call.equals("session.local_logout") || method_call.equals("session.slave_local_login_with_password") || method_call.equals("session.logout")) { - return super.dispatch(method_call, method_params); + protected Map dispatch(String methodCall, Object[] methodParams) throws XmlRpcException, XenAPIException { + if (methodCall.equals("session.local_logout") || methodCall.equals("session.slave_local_login_with_password") || methodCall.equals("session.logout")) { + return super.dispatch(methodCall, methodParams); } - if (method_call.equals("session.login_with_password")) { + if (methodCall.equals("session.login_with_password")) { int retries = 0; while (retries++ < _retries) { try { - return super.dispatch(method_call, method_params); + return super.dispatch(methodCall, methodParams); } catch (XmlRpcException e) { Throwable cause = e.getCause(); if (cause == null || !(cause instanceof SocketException)) { @@ -870,21 +496,21 @@ public class XenServerConnectionPool { int retries = 0; while (retries++ < _retries) { try { - return super.dispatch(method_call, method_params); + return super.dispatch(methodCall, methodParams); } catch (Types.SessionInvalid e) { - s_logger.debug("Session is invalid for method: " + method_call + " due to " + e.getMessage() + ". Reconnecting...retry=" + retries); + s_logger.debug("Session is invalid for method: " + methodCall + " due to " + e.getMessage() + ". Reconnecting...retry=" + retries); if (retries >= _retries) { removeConnect(_poolUuid); throw e; } loginWithPassword(this, _username, _password, APIVersion.latest().toString()); - method_params[0] = getSessionReference(); + methodParams[0] = getSessionReference(); } catch (XmlRpcClientException e) { - s_logger.debug("XmlRpcClientException for method: " + method_call + " due to " + e.getMessage()); + s_logger.debug("XmlRpcClientException for method: " + methodCall + " due to " + e.getMessage()); removeConnect(_poolUuid); throw e; } catch (XmlRpcException e) { - s_logger.debug("XmlRpcException for method: " + method_call + " due to " + e.getMessage() + ". Reconnecting...retry=" + retries); + s_logger.debug("XmlRpcException for method: " + methodCall + " due to " + e.getMessage() + ". Reconnecting...retry=" + retries); if (retries >= _retries) { removeConnect(_poolUuid); throw e; @@ -895,7 +521,7 @@ public class XenServerConnectionPool { throw e; } } catch (Types.HostIsSlave e) { - s_logger.debug("HostIsSlave Exception for method: " + method_call + " due to " + e.getMessage() + ". Reconnecting...retry=" + retries); + s_logger.debug("HostIsSlave Exception for method: " + methodCall + " due to " + e.getMessage() + ". Reconnecting...retry=" + retries); removeConnect(_poolUuid); throw e; } diff --git a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServerPoolVms.java b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServerPoolVms.java index 71c0e394dc4..767d77e1b42 100644 --- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServerPoolVms.java +++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServerPoolVms.java @@ -27,14 +27,14 @@ import com.cloud.vm.VirtualMachine.State; public class XenServerPoolVms { private static final Logger s_logger = Logger.getLogger(XenServerPoolVms.class); - private final Map>> _cluster_vms = + private final Map>> _clusterVms = new ConcurrentHashMap>>(); public HashMap> getClusterVmState(String clusterId) { - HashMap> _vms = _cluster_vms.get(clusterId); + HashMap> _vms = _clusterVms.get(clusterId); if (_vms == null) { HashMap> vmStates = new HashMap>(); - _cluster_vms.put(clusterId, vmStates); + _clusterVms.put(clusterId, vmStates); return vmStates; } else return _vms; @@ -51,8 +51,13 @@ public class XenServerPoolVms { return pv == null ? State.Stopped : pv.second(); // if a VM is absent on the cluster, it is effectively in stopped state. } - public void put(String clusterId, String hostUuid, String name, State state, String platform){ - HashMap> vms= getClusterVmState(clusterId); + public Ternary get(String clusterId, String name) { + HashMap> vms = getClusterVmState(clusterId); + return vms.get(name); + } + + public void put(String clusterId, String hostUuid, String name, State state, String platform) { + HashMap> vms = getClusterVmState(clusterId); vms.put(name, new Ternary(hostUuid, state, platform)); } @@ -66,9 +71,9 @@ public class XenServerPoolVms { vms.remove(name); } - public void putAll(String clusterId, HashMap> new_vms) { + public void putAll(String clusterId, HashMap> newVms) { HashMap> vms = getClusterVmState(clusterId); - vms.putAll(new_vms); + vms.putAll(newVms); } public int size(String clusterId) { @@ -79,7 +84,7 @@ public class XenServerPoolVms { @Override public String toString() { StringBuilder sbuf = new StringBuilder("PoolVms="); - for (HashMap> clusterVM : _cluster_vms.values()) { + for (HashMap> clusterVM : _clusterVms.values()) { for (String vmname : clusterVM.keySet()) { sbuf.append(vmname).append("-").append(clusterVM.get(vmname).second()).append(","); } diff --git a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServerStorageProcessor.java b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServerStorageProcessor.java index b1ec074bddf..f2abff74f80 100644 --- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServerStorageProcessor.java +++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServerStorageProcessor.java @@ -30,9 +30,6 @@ import java.util.Map; import java.util.Set; import java.util.UUID; -import org.apache.log4j.Logger; -import org.apache.xmlrpc.XmlRpcException; - import com.xensource.xenapi.Connection; import com.xensource.xenapi.Host; import com.xensource.xenapi.PBD; @@ -40,6 +37,7 @@ import com.xensource.xenapi.Pool; import com.xensource.xenapi.SR; import com.xensource.xenapi.Types; import com.xensource.xenapi.Types.BadServerResponse; +import com.xensource.xenapi.Types.VmPowerState; import com.xensource.xenapi.Types.XenAPIException; import com.xensource.xenapi.VBD; import com.xensource.xenapi.VDI; @@ -64,6 +62,8 @@ import org.apache.cloudstack.storage.datastore.protocol.DataStoreProtocol; import org.apache.cloudstack.storage.to.SnapshotObjectTO; import org.apache.cloudstack.storage.to.TemplateObjectTO; import org.apache.cloudstack.storage.to.VolumeObjectTO; +import org.apache.log4j.Logger; +import org.apache.xmlrpc.XmlRpcException; import com.cloud.agent.api.Answer; import com.cloud.agent.api.CreateStoragePoolCommand; @@ -90,10 +90,10 @@ import com.cloud.utils.storage.encoding.Decoder; public class XenServerStorageProcessor implements StorageProcessor { private static final Logger s_logger = Logger.getLogger(XenServerStorageProcessor.class); protected CitrixResourceBase hypervisorResource; - private String BaseMountPointOnHost = "/var/run/cloud_mount"; + protected String BaseMountPointOnHost = "/var/run/cloud_mount"; public XenServerStorageProcessor(CitrixResourceBase resource) { - this.hypervisorResource = resource; + hypervisorResource = resource; } @Override @@ -117,14 +117,14 @@ public class XenServerStorageProcessor implements StorageProcessor { String vmName = cmd.getVmName(); try { - Connection conn = this.hypervisorResource.getConnection(); + Connection conn = hypervisorResource.getConnection(); VBD isoVBD = null; // Find the VM - VM vm = this.hypervisorResource.getVM(conn, vmName); + VM vm = hypervisorResource.getVM(conn, vmName); // Find the ISO VDI - VDI isoVDI = this.hypervisorResource.getIsoVDIByURL(conn, vmName, isoURL); + VDI isoVDI = hypervisorResource.getIsoVDIByURL(conn, vmName, isoURL); // Find the VM's CD-ROM VBD Set vbds = vm.getVBDs(conn); @@ -163,74 +163,92 @@ public class XenServerStorageProcessor implements StorageProcessor { @Override public AttachAnswer attachVolume(AttachCommand cmd) { - String vmName = cmd.getVmName(); - String vdiNameLabel = vmName + "-DATA"; DiskTO disk = cmd.getDisk(); DataTO data = disk.getData(); try { + String vmName = cmd.getVmName(); + String vdiNameLabel = vmName + "-DATA"; + Connection conn = this.hypervisorResource.getConnection(); + VM vm = null; + + boolean vmNotRunning = true; + + try { + vm = this.hypervisorResource.getVM(conn, vmName); + + VM.Record vmr = vm.getRecord(conn); + + vmNotRunning = vmr.powerState != VmPowerState.RUNNING; + } + catch (CloudRuntimeException ex) { + } + + Map details = disk.getDetails(); + boolean isManaged = Boolean.parseBoolean(details.get(DiskTO.MANAGED)); + + // if the VM is not running and we're not dealing with managed storage, just return success (nothing to do here) + // this should probably never actually happen + if (vmNotRunning && !isManaged) { + return new AttachAnswer(disk); + } VDI vdi = null; - Map details = cmd.getDisk().getDetails(); - boolean isManaged = Boolean.parseBoolean(details.get(DiskTO.MANAGED)); - if (isManaged) { - String iScsiName = details.get(DiskTO.IQN); - String storageHost = details.get(DiskTO.STORAGE_HOST); - String chapInitiatorUsername = disk.getDetails().get(DiskTO.CHAP_INITIATOR_USERNAME); - String chapInitiatorSecret = disk.getDetails().get(DiskTO.CHAP_INITIATOR_SECRET); - Long volumeSize = Long.parseLong(details.get(DiskTO.VOLUME_SIZE)); + vdi = hypervisorResource.prepareManagedStorage(conn, details, data.getPath(), vdiNameLabel); - SR sr = this.hypervisorResource.getIscsiSR(conn, iScsiName, storageHost, iScsiName, chapInitiatorUsername, chapInitiatorSecret, true); + if (vmNotRunning) { + DiskTO newDisk = new DiskTO(disk.getData(), disk.getDiskSeq(), vdi.getUuid(conn), disk.getType()); - vdi = this.hypervisorResource.getVDIbyUuid(conn, data.getPath(), false); - - if (vdi == null) { - vdi = this.hypervisorResource.createVdi(sr, vdiNameLabel, volumeSize); + return new AttachAnswer(newDisk); } - } else { - vdi = this.hypervisorResource.mount(conn, null, null, data.getPath()); + } + else { + vdi = hypervisorResource.mount(conn, null, null, data.getPath()); } - // Look up the VM - VM vm = this.hypervisorResource.getVM(conn, vmName); /* For HVM guest, if no pv driver installed, no attach/detach */ - boolean isHVM; - if (vm.getPVBootloader(conn).equalsIgnoreCase("")) { - isHVM = true; - } else { - isHVM = false; - } + boolean isHVM = vm.getPVBootloader(conn).equalsIgnoreCase(""); + VMGuestMetrics vgm = vm.getGuestMetrics(conn); boolean pvDrvInstalled = false; + if (!this.hypervisorResource.isRefNull(vgm) && vgm.getPVDriversUpToDate(conn)) { pvDrvInstalled = true; } + if (isHVM && !pvDrvInstalled) { s_logger.warn(": You attempted an operation on a VM which requires PV drivers to be installed but the drivers were not detected"); + return new AttachAnswer("You attempted an operation that requires PV drivers to be installed on the VM. Please install them by inserting xen-pv-drv.iso."); } // Figure out the disk number to attach the VM to String diskNumber = null; Long deviceId = disk.getDiskSeq(); + if (deviceId != null) { if (deviceId.longValue() == 3) { String msg = "Device 3 is reserved for CD-ROM, choose other device"; + return new AttachAnswer(msg); } - if (this.hypervisorResource.isDeviceUsed(conn, vm, deviceId)) { + + if (hypervisorResource.isDeviceUsed(conn, vm, deviceId)) { String msg = "Device " + deviceId + " is used in VM " + vmName; + return new AttachAnswer(msg); } + diskNumber = deviceId.toString(); } else { - diskNumber = this.hypervisorResource.getUnusedDeviceNum(conn, vm); + diskNumber = hypervisorResource.getUnusedDeviceNum(conn, vm); } - // Create a new VBD + VBD.Record vbdr = new VBD.Record(); + vbdr.VM = vm; vbdr.VDI = vdi; vbdr.bootable = false; @@ -238,6 +256,7 @@ public class XenServerStorageProcessor implements StorageProcessor { vbdr.mode = Types.VbdMode.RW; vbdr.type = Types.VbdType.DISK; vbdr.unpluggable = true; + VBD vbd = VBD.create(conn, vbdr); // Attach the VBD to the VM @@ -245,9 +264,10 @@ public class XenServerStorageProcessor implements StorageProcessor { // Update the VDI's label to include the VM name vdi.setNameLabel(conn, vdiNameLabel); - DiskTO newDisk = new DiskTO(disk.getData(), Long.parseLong(diskNumber), vdi.getUuid(conn), disk.getType()); - return new AttachAnswer(newDisk); + DiskTO newDisk = new DiskTO(disk.getData(), Long.parseLong(diskNumber), vdi.getUuid(conn), disk.getType()); + + return new AttachAnswer(newDisk); } catch (XenAPIException e) { String msg = "Failed to attach volume" + " for uuid: " + data.getPath() + " due to " + e.toString(); s_logger.warn(msg, e); @@ -279,13 +299,13 @@ public class XenServerStorageProcessor implements StorageProcessor { } try { - Connection conn = this.hypervisorResource.getConnection(); + Connection conn = hypervisorResource.getConnection(); // Find the VM - VM vm = this.hypervisorResource.getVM(conn, cmd.getVmName()); + VM vm = hypervisorResource.getVM(conn, cmd.getVmName()); String vmUUID = vm.getUuid(conn); // Find the ISO VDI - VDI isoVDI = this.hypervisorResource.getIsoVDIByURL(conn, cmd.getVmName(), isoURL); + VDI isoVDI = hypervisorResource.getIsoVDIByURL(conn, cmd.getVmName(), isoURL); SR sr = isoVDI.getSR(conn); @@ -308,7 +328,7 @@ public class XenServerStorageProcessor implements StorageProcessor { } if (!sr.getNameLabel(conn).startsWith("XenServer Tools")) { - this.hypervisorResource.removeSR(conn, sr); + hypervisorResource.removeSR(conn, sr); } return new DettachAnswer(disk); @@ -325,54 +345,73 @@ public class XenServerStorageProcessor implements StorageProcessor { @Override public Answer dettachVolume(DettachCommand cmd) { - String vmName = cmd.getVmName(); DiskTO disk = cmd.getDisk(); DataTO data = disk.getData(); + try { Connection conn = this.hypervisorResource.getConnection(); - // Look up the VDI - VDI vdi = this.hypervisorResource.mount(conn, null, null, data.getPath()); - // Look up the VM - VM vm = this.hypervisorResource.getVM(conn, vmName); - /* For HVM guest, if no pv driver installed, no attach/detach */ - boolean isHVM; - if (vm.getPVBootloader(conn).equalsIgnoreCase("")) { - isHVM = true; - } else { - isHVM = false; + + String vmName = cmd.getVmName(); + VM vm = null; + + boolean vmNotRunning = true; + + try { + vm = this.hypervisorResource.getVM(conn, vmName); + + VM.Record vmr = vm.getRecord(conn); + + vmNotRunning = vmr.powerState != VmPowerState.RUNNING; } - VMGuestMetrics vgm = vm.getGuestMetrics(conn); - boolean pvDrvInstalled = false; - if (!this.hypervisorResource.isRefNull(vgm) && vgm.getPVDriversUpToDate(conn)) { - pvDrvInstalled = true; - } - if (isHVM && !pvDrvInstalled) { - s_logger.warn(": You attempted an operation on a VM which requires PV drivers to be installed but the drivers were not detected"); - return new DettachAnswer( - "You attempted an operation that requires PV drivers to be installed on the VM. Please install them by inserting xen-pv-drv.iso."); + catch (CloudRuntimeException ex) { } - // Look up all VBDs for this VDI - Set vbds = vdi.getVBDs(conn); + // if the VM is not running and we're not dealing with managed storage, just return success (nothing to do here) + // this should probably never actually happen + if (vmNotRunning && !cmd.isManaged()) { + return new DettachAnswer(disk); + } - // Detach each VBD from its VM, and then destroy it - for (VBD vbd : vbds) { - VBD.Record vbdr = vbd.getRecord(conn); + if (!vmNotRunning) { + /* For HVM guest, if no pv driver installed, no attach/detach */ + boolean isHVM = vm.getPVBootloader(conn).equalsIgnoreCase(""); - if (vbdr.currentlyAttached) { - vbd.unplug(conn); + VMGuestMetrics vgm = vm.getGuestMetrics(conn); + boolean pvDrvInstalled = false; + + if (!this.hypervisorResource.isRefNull(vgm) && vgm.getPVDriversUpToDate(conn)) { + pvDrvInstalled = true; } - vbd.destroy(conn); + if (isHVM && !pvDrvInstalled) { + s_logger.warn(": You attempted an operation on a VM which requires PV drivers to be installed but the drivers were not detected"); + return new DettachAnswer("You attempted an operation that requires PV drivers to be installed on the VM. Please install them by inserting xen-pv-drv.iso."); + } + + VDI vdi = this.hypervisorResource.mount(conn, null, null, data.getPath()); + + // Look up all VBDs for this VDI + Set vbds = vdi.getVBDs(conn); + + // Detach each VBD from its VM, and then destroy it + for (VBD vbd : vbds) { + VBD.Record vbdr = vbd.getRecord(conn); + + if (vbdr.currentlyAttached) { + vbd.unplug(conn); + } + + vbd.destroy(conn); + } + + // Update the VDI's label to be "detached" + vdi.setNameLabel(conn, "detached"); + + this.hypervisorResource.umount(conn, vdi); } - // Update the VDI's label to be "detached" - vdi.setNameLabel(conn, "detached"); - - this.hypervisorResource.umount(conn, vdi); - if (cmd.isManaged()) { - this.hypervisorResource.handleSrAndVdiDetach(cmd.get_iScsiName()); + hypervisorResource.handleSrAndVdiDetach(cmd.get_iScsiName(), conn); } return new DettachAnswer(disk); @@ -577,13 +616,13 @@ public class XenServerStorageProcessor implements StorageProcessor { } if (target.equals(dc.get("target")) && targetiqn.equals(dc.get("targetIQN")) && lunid.equals(dc.get("lunid"))) { throw new CloudRuntimeException("There is a SR using the same configuration target:" + dc.get("target") + ", targetIQN:" + dc.get("targetIQN") + - ", lunid:" + dc.get("lunid") + " for pool " + pool.getUuid() + "on host:" + this.hypervisorResource.getHost().uuid); + ", lunid:" + dc.get("lunid") + " for pool " + pool.getUuid() + "on host:" + hypervisorResource.getHost().uuid); } } deviceConfig.put("target", target); deviceConfig.put("targetIQN", targetiqn); - Host host = Host.getByUuid(conn, this.hypervisorResource.getHost().uuid); + Host host = Host.getByUuid(conn, hypervisorResource.getHost().uuid); Map smConfig = new HashMap(); String type = SRType.LVMOISCSI.toString(); String poolId = Long.toString(pool.getId()); @@ -654,7 +693,7 @@ public class XenServerStorageProcessor implements StorageProcessor { } protected Answer execute(CreateStoragePoolCommand cmd) { - Connection conn = this.hypervisorResource.getConnection(); + Connection conn = hypervisorResource.getConnection(); StorageFilerTO pool = cmd.getPool(); try { if (pool.getType() == StoragePoolType.NetworkFilesystem) { @@ -669,7 +708,7 @@ public class XenServerStorageProcessor implements StorageProcessor { } catch (Exception e) { String msg = "Catch Exception " + e.getClass().getName() + ", create StoragePool failed due to " + e.toString() + " on host:" + - this.hypervisorResource.getHost().uuid + " pool: " + pool.getHost() + pool.getPath(); + hypervisorResource.getHost().uuid + " pool: " + pool.getHost() + pool.getPath(); s_logger.warn(msg, e); return new Answer(cmd, false, msg); } @@ -777,7 +816,7 @@ public class XenServerStorageProcessor implements StorageProcessor { } } - private boolean IsISCSI(String type) { + protected boolean IsISCSI(String type) { return SRType.LVMOHBA.equals(type) || SRType.LVMOISCSI.equals(type) || SRType.LVM.equals(type); } @@ -1076,7 +1115,7 @@ public class XenServerStorageProcessor implements StorageProcessor { return lfilename; } - private String backupSnapshotToS3(final Connection connection, final S3TO s3, final String srUuid, final String folder, final String snapshotUuid, + protected String backupSnapshotToS3(final Connection connection, final S3TO s3, final String srUuid, final String folder, final String snapshotUuid, final Boolean iSCSIFlag, final int wait) { final String filename = iSCSIFlag ? "VHD-" + snapshotUuid : snapshotUuid + ".vhd"; @@ -1106,6 +1145,16 @@ public class XenServerStorageProcessor implements StorageProcessor { } + protected Long getSnapshotSize(Connection conn, String primaryStorageSRUuid, String snapshotUuid, Boolean isISCSI, int wait) { + String physicalSize = hypervisorResource.callHostPluginAsync(conn, "vmopsSnapshot", "getSnapshotSize", wait, + "primaryStorageSRUuid", primaryStorageSRUuid, "snapshotUuid", snapshotUuid, "isISCSI", isISCSI.toString()); + if (physicalSize == null || physicalSize.isEmpty()) { + return (long) 0; + } else { + return Long.parseLong(physicalSize); + } + } + protected String backupSnapshot(Connection conn, String primaryStorageSRUuid, String localMountPoint, String path, String secondaryStorageMountPath, String snapshotUuid, String prevBackupUuid, Boolean isISCSI, int wait) { String backupSnapshotUuid = null; @@ -1136,7 +1185,7 @@ public class XenServerStorageProcessor implements StorageProcessor { // indicator of success. if (status != null && status.equalsIgnoreCase("1") && backupSnapshotUuid != null) { s_logger.debug("Successfully copied backupUuid: " + backupSnapshotUuid + " to secondary storage"); - return backupSnapshotUuid; + return results; } else { errMsg = "Could not copy backupUuid: " + backupSnapshotUuid + " from primary storage " + primaryStorageSRUuid + " to secondary storage " + @@ -1149,7 +1198,7 @@ public class XenServerStorageProcessor implements StorageProcessor { throw new CloudRuntimeException(errMsg); } - private boolean destroySnapshotOnPrimaryStorageExceptThis(Connection conn, String volumeUuid, String avoidSnapshotUuid) { + protected boolean destroySnapshotOnPrimaryStorageExceptThis(Connection conn, String volumeUuid, String avoidSnapshotUuid) { try { VDI volume = getVDIbyUuid(conn, volumeUuid); if (volume == null) { @@ -1179,6 +1228,26 @@ public class XenServerStorageProcessor implements StorageProcessor { return false; } + private boolean destroySnapshotOnPrimaryStorage(Connection conn, String lastSnapshotUuid) { + try { + VDI snapshot = getVDIbyUuid(conn, lastSnapshotUuid); + if (snapshot == null) { + // since this is just used to cleanup leftover bad snapshots, no need to throw exception + s_logger.warn("Could not destroy snapshot " + lastSnapshotUuid + " due to can not find it"); + return false; + } + snapshot.destroy(conn); + return true; + } catch (XenAPIException e) { + String msg = "Destroying snapshot: " + lastSnapshotUuid + " failed due to " + e.toString(); + s_logger.error(msg, e); + } catch (Exception e) { + String msg = "Destroying snapshot: " + lastSnapshotUuid + " failed due to " + e.toString(); + s_logger.warn(msg, e); + } + return false; + } + @Override public Answer backupSnapshot(CopyCommand cmd) { Connection conn = hypervisorResource.getConnection(); @@ -1203,6 +1272,7 @@ public class XenServerStorageProcessor implements StorageProcessor { SnapshotObjectTO snapshotTO = (SnapshotObjectTO)srcData; SnapshotObjectTO snapshotOnImage = (SnapshotObjectTO)destData; String snapshotUuid = snapshotTO.getPath(); + String volumeUuid = snapshotTO.getVolume().getPath(); String prevBackupUuid = snapshotOnImage.getParentSnapshotPath(); String prevSnapshotUuid = snapshotTO.getParentSnapshotPath(); @@ -1211,6 +1281,7 @@ public class XenServerStorageProcessor implements StorageProcessor { String details = null; String snapshotBackupUuid = null; boolean fullbackup = true; + Long physicalSize = null; try { SR primaryStorageSR = hypervisorResource.getSRByNameLabelandHost(conn, primaryStorageNameLabel); if (primaryStorageSR == null) { @@ -1257,6 +1328,8 @@ public class XenServerStorageProcessor implements StorageProcessor { snapshotSr = hypervisorResource.createNfsSRbyURI(conn, new URI(snapshotMountpoint), false); VDI backedVdi = hypervisorResource.cloudVDIcopy(conn, snapshotVdi, snapshotSr, wait); snapshotBackupUuid = backedVdi.getUuid(conn); + String primarySRuuid = snapshotSr.getUuid(conn); + physicalSize = getSnapshotSize(conn, primarySRuuid, snapshotBackupUuid, isISCSI, wait); if (destStore instanceof SwiftTO) { try { @@ -1309,17 +1382,21 @@ public class XenServerStorageProcessor implements StorageProcessor { throw new CloudRuntimeException("S3 upload of snapshots " + snapshotPaUuid + " failed"); } } else { - snapshotBackupUuid = + String results = backupSnapshot(conn, primaryStorageSRUuid, localMountPoint, folder, secondaryStorageMountPath, snapshotUuid, prevBackupUuid, isISCSI, wait); + String[] tmp = results.split("#"); + snapshotBackupUuid = tmp[1]; + physicalSize = Long.parseLong(tmp[2]); finalPath = folder + File.separator + snapshotBackupUuid; } } - String volumeUuid = snapshotTO.getVolume().getPath(); + // delete primary snapshots with only the last one left destroySnapshotOnPrimaryStorageExceptThis(conn, volumeUuid, snapshotUuid); SnapshotObjectTO newSnapshot = new SnapshotObjectTO(); newSnapshot.setPath(finalPath); + newSnapshot.setPhysicalSize(physicalSize); if (fullbackup) { newSnapshot.setParentSnapshotPath(null); } else { @@ -1329,9 +1406,13 @@ public class XenServerStorageProcessor implements StorageProcessor { } catch (XenAPIException e) { details = "BackupSnapshot Failed due to " + e.toString(); s_logger.warn(details, e); + // remove last bad primary snapshot when exception happens + destroySnapshotOnPrimaryStorage(conn, snapshotUuid); } catch (Exception e) { details = "BackupSnapshot Failed due to " + e.getMessage(); s_logger.warn(details, e); + // remove last bad primary snapshot when exception happens + destroySnapshotOnPrimaryStorage(conn, snapshotUuid); } return new CopyCmdAnswer(details); @@ -1339,7 +1420,7 @@ public class XenServerStorageProcessor implements StorageProcessor { @Override public Answer createTemplateFromVolume(CopyCommand cmd) { - Connection conn = this.hypervisorResource.getConnection(); + Connection conn = hypervisorResource.getConnection(); VolumeObjectTO volume = (VolumeObjectTO)cmd.getSrcTO(); TemplateObjectTO template = (TemplateObjectTO)cmd.getDestTO(); NfsTO destStore = (NfsTO)cmd.getDestTO().getDataStore(); @@ -1359,7 +1440,7 @@ public class XenServerStorageProcessor implements StorageProcessor { URI uri = new URI(secondaryStoragePoolURL); secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath(); installPath = template.getPath(); - if (!this.hypervisorResource.createSecondaryStorageFolder(conn, secondaryStorageMountPath, installPath)) { + if (!hypervisorResource.createSecondaryStorageFolder(conn, secondaryStorageMountPath, installPath)) { details = " Filed to create folder " + installPath + " in secondary storage"; s_logger.warn(details); return new CopyCmdAnswer(details); @@ -1368,10 +1449,10 @@ public class XenServerStorageProcessor implements StorageProcessor { VDI vol = getVDIbyUuid(conn, volumeUUID); // create template SR URI tmpltURI = new URI(secondaryStoragePoolURL + "/" + installPath); - tmpltSR = this.hypervisorResource.createNfsSRbyURI(conn, tmpltURI, false); + tmpltSR = hypervisorResource.createNfsSRbyURI(conn, tmpltURI, false); // copy volume to template SR - VDI tmpltVDI = this.hypervisorResource.cloudVDIcopy(conn, vol, tmpltSR, wait); + VDI tmpltVDI = hypervisorResource.cloudVDIcopy(conn, vol, tmpltSR, wait); // scan makes XenServer pick up VDI physicalSize tmpltSR.scan(conn); if (userSpecifiedName != null) { @@ -1385,13 +1466,13 @@ public class XenServerStorageProcessor implements StorageProcessor { // create the template.properties file String templatePath = secondaryStorageMountPath + "/" + installPath; result = - this.hypervisorResource.postCreatePrivateTemplate(conn, templatePath, tmpltFilename, tmpltUUID, userSpecifiedName, null, physicalSize, virtualSize, + hypervisorResource.postCreatePrivateTemplate(conn, templatePath, tmpltFilename, tmpltUUID, userSpecifiedName, null, physicalSize, virtualSize, template.getId()); if (!result) { throw new CloudRuntimeException("Could not create the template.properties file on secondary storage dir: " + tmpltURI); } installPath = installPath + "/" + tmpltFilename; - this.hypervisorResource.removeSR(conn, tmpltSR); + hypervisorResource.removeSR(conn, tmpltSR); tmpltSR = null; TemplateObjectTO newTemplate = new TemplateObjectTO(); newTemplate.setPath(installPath); @@ -1403,10 +1484,10 @@ public class XenServerStorageProcessor implements StorageProcessor { return answer; } catch (Exception e) { if (tmpltSR != null) { - this.hypervisorResource.removeSR(conn, tmpltSR); + hypervisorResource.removeSR(conn, tmpltSR); } if (secondaryStorageMountPath != null) { - this.hypervisorResource.deleteSecondaryStorageFolder(conn, secondaryStorageMountPath, installPath); + hypervisorResource.deleteSecondaryStorageFolder(conn, secondaryStorageMountPath, installPath); } details = "Creating template from volume " + volumeUUID + " failed due to " + e.toString(); s_logger.error(details, e); @@ -1421,7 +1502,7 @@ public class XenServerStorageProcessor implements StorageProcessor { @Override public Answer createVolumeFromSnapshot(CopyCommand cmd) { - Connection conn = this.hypervisorResource.getConnection(); + Connection conn = hypervisorResource.getConnection(); DataTO srcData = cmd.getSrcTO(); SnapshotObjectTO snapshot = (SnapshotObjectTO)srcData; DataTO destData = cmd.getDestTO(); @@ -1445,7 +1526,7 @@ public class XenServerStorageProcessor implements StorageProcessor { return new CopyCmdAnswer(details); } try { - SR primaryStorageSR = this.hypervisorResource.getSRByNameLabelandHost(conn, primaryStorageNameLabel); + SR primaryStorageSR = hypervisorResource.getSRByNameLabelandHost(conn, primaryStorageNameLabel); if (primaryStorageSR == null) { throw new InternalErrorException("Could not create volume from snapshot because the primary Storage SR could not be created from the name label: " + primaryStorageNameLabel); @@ -1490,14 +1571,14 @@ public class XenServerStorageProcessor implements StorageProcessor { SnapshotObjectTO snapshot = (SnapshotObjectTO)cmd.getData(); DataStoreTO store = snapshot.getDataStore(); if (store.getRole() == DataStoreRole.Primary) { - Connection conn = this.hypervisorResource.getConnection(); + Connection conn = hypervisorResource.getConnection(); VDI snapshotVdi = getVDIbyUuid(conn, snapshot.getPath()); if (snapshotVdi == null) { return new Answer(null); } String errMsg = null; try { - this.deleteVDI(conn, snapshotVdi); + deleteVDI(conn, snapshotVdi); } catch (BadServerResponse e) { s_logger.debug("delete snapshot failed:" + e.toString()); errMsg = e.toString(); diff --git a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/Xenserver625Resource.java b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/Xenserver625Resource.java new file mode 100644 index 00000000000..7d2a2a13ecb --- /dev/null +++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/Xenserver625Resource.java @@ -0,0 +1,112 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.cloud.hypervisor.xen.resource; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.ejb.Local; + +import org.apache.cloudstack.hypervisor.xenserver.XenServerResourceNewBase; +import org.apache.log4j.Logger; + +import com.cloud.agent.api.StartupRoutingCommand; +import com.cloud.resource.ServerResource; +import com.cloud.storage.resource.StorageSubsystemCommandHandler; +import com.cloud.storage.resource.StorageSubsystemCommandHandlerBase; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.utils.script.Script; +import com.xensource.xenapi.Connection; + +@Local(value=ServerResource.class) +public class Xenserver625Resource extends XenServerResourceNewBase { + private static final Logger s_logger = Logger.getLogger(XenServer620Resource.class); + + public Xenserver625Resource() { + super(); + } + + @Override + protected void fillHostInfo(Connection conn, StartupRoutingCommand cmd) { + super.fillHostInfo(conn, cmd); + Map details = cmd.getHostDetails(); + details.put("Xenserer620HotFix", "Xenserver-Vdi-Copy-HotFix"); + } + + @Override + protected String getGuestOsType(String stdType, boolean bootFromCD) { + return CitrixHelper.getXenServer620GuestOsType(stdType, bootFromCD); + } + + @Override + protected List getPatchFiles() { + List files = new ArrayList(); + String patch = "scripts/vm/hypervisor/xenserver/xenserver62/patch"; + String patchfilePath = Script.findScript("", patch); + if (patchfilePath == null) { + throw new CloudRuntimeException("Unable to find patch file " + patch); + } + File file = new File(patchfilePath); + files.add(file); + return files; + } + + @Override + public long getStaticMax(String os, boolean b, long dynamicMinRam, long dynamicMaxRam){ + long recommendedValue = CitrixHelper.getXenServer620StaticMax(os, b); + if(recommendedValue == 0){ + s_logger.warn("No recommended value found for dynamic max, setting static max and dynamic max equal"); + return dynamicMaxRam; + } + long staticMax = Math.min(recommendedValue, 4l * dynamicMinRam); // XS constraint for stability + if (dynamicMaxRam > staticMax){ // XS contraint that dynamic max <= static max + s_logger.warn("dynamixMax " + dynamicMaxRam + " cant be greater than static max " + staticMax + ", can lead to stability issues. Setting static max as much as dynamic max "); + return dynamicMaxRam; + } + return staticMax; + } + + @Override + public long getStaticMin(String os, boolean b, long dynamicMinRam, long dynamicMaxRam){ + long recommendedValue = CitrixHelper.getXenServer620StaticMin(os, b); + if(recommendedValue == 0){ + s_logger.warn("No recommended value found for dynamic min"); + return dynamicMinRam; + } + + if(dynamicMinRam < recommendedValue){ // XS contraint that dynamic min > static min + s_logger.warn("Vm is set to dynamixMin " + dynamicMinRam + " less than the recommended static min " + recommendedValue + ", could lead to stability issues"); + } + return dynamicMinRam; + } + + @Override + protected StorageSubsystemCommandHandler getStorageHandler() { + XenServerStorageProcessor processor = new Xenserver625StorageProcessor(this); + return new StorageSubsystemCommandHandlerBase(processor); + } + + @Override + protected void umountSnapshotDir(Connection conn, Long dcId) { + + } + +} \ No newline at end of file diff --git a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/Xenserver625StorageProcessor.java b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/Xenserver625StorageProcessor.java new file mode 100644 index 00000000000..dad3d145fae --- /dev/null +++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/Xenserver625StorageProcessor.java @@ -0,0 +1,822 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.cloud.hypervisor.xen.resource; + +import java.io.File; +import java.net.URI; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +import org.apache.cloudstack.storage.command.CopyCmdAnswer; +import org.apache.cloudstack.storage.command.CopyCommand; +import org.apache.cloudstack.storage.to.PrimaryDataStoreTO; +import org.apache.cloudstack.storage.to.SnapshotObjectTO; +import org.apache.cloudstack.storage.to.TemplateObjectTO; +import org.apache.cloudstack.storage.to.VolumeObjectTO; +import org.apache.commons.lang.StringUtils; +import org.apache.log4j.Logger; + +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.to.DataObjectType; +import com.cloud.agent.api.to.DataStoreTO; +import com.cloud.agent.api.to.DataTO; +import com.cloud.agent.api.to.NfsTO; +import com.cloud.agent.api.to.S3TO; +import com.cloud.agent.api.to.SwiftTO; +import com.cloud.exception.InternalErrorException; +import com.cloud.storage.Storage; +import com.cloud.utils.exception.CloudRuntimeException; +import com.xensource.xenapi.Connection; +import com.xensource.xenapi.Host; +import com.xensource.xenapi.PBD; +import com.xensource.xenapi.SR; +import com.xensource.xenapi.Task; +import com.xensource.xenapi.Types; +import com.xensource.xenapi.VDI; + +public class Xenserver625StorageProcessor extends XenServerStorageProcessor { + private static final Logger s_logger = Logger.getLogger(XenServerStorageProcessor.class); + + public Xenserver625StorageProcessor(CitrixResourceBase resource) { + super(resource); + } + protected boolean mountNfs(Connection conn, String remoteDir, String localDir) { + if (localDir == null) { + localDir = "/var/cloud_mount/" + UUID.nameUUIDFromBytes(remoteDir.getBytes()); + } + String results = hypervisorResource.callHostPluginAsync(conn, "cloud-plugin-storage", "mountNfsSecondaryStorage", 100 * 1000, + "localDir", localDir, "remoteDir", remoteDir); + if (results == null || results.isEmpty()) { + String errMsg = "Could not mount secondary storage " + remoteDir + " on host "; + s_logger.warn(errMsg); + throw new CloudRuntimeException(errMsg); + } + return true; + } + + protected boolean makeDirectory(Connection conn, String path) { + String result = hypervisorResource.callHostPlugin(conn, "cloud-plugin-storage", "makeDirectory", "path", path); + if (result == null || result.isEmpty()) { + return false; + } + return true; + } + + protected SR createFileSR(Connection conn, String path) { + SR sr = null; + PBD pbd = null; + try { + Map smConfig = new HashMap(); + Host host = Host.getByUuid(conn, hypervisorResource.getHost().uuid); + String uuid = UUID.randomUUID().toString(); + + sr = SR.introduce(conn,uuid, uuid, uuid, "file", "file", false, smConfig); + PBD.Record record = new PBD.Record(); + record.host = host; + record.SR = sr; + smConfig.put("location", path); + record.deviceConfig = smConfig; + pbd = PBD.create(conn, record); + pbd.plug(conn); + sr.scan(conn); + return sr; + } catch (Exception e) { + try { + if (pbd != null) { + pbd.destroy(conn); + } + } catch (Exception e1) { + s_logger.debug("Failed to destroy pbd", e); + } + try { + if (sr != null) { + sr.forget(conn); + } + } catch (Exception e2) { + s_logger.error("Failed to forget sr", e); + } + String msg = "createFileSR failed! due to " + e.toString(); + s_logger.warn(msg, e); + throw new CloudRuntimeException(msg, e); + } + } + + protected SR createFileSr(Connection conn, String remotePath, String dir) { + String localDir = "/var/cloud_mount/" + UUID.nameUUIDFromBytes(remotePath.getBytes()); + mountNfs(conn, remotePath, localDir); + SR sr = createFileSR(conn, localDir + "/" + dir); + return sr; + } + + @Override + public Answer copyTemplateToPrimaryStorage(CopyCommand cmd) { + DataTO srcData = cmd.getSrcTO(); + DataTO destData = cmd.getDestTO(); + int wait = cmd.getWait(); + DataStoreTO srcStore = srcData.getDataStore(); + Connection conn = hypervisorResource.getConnection(); + SR srcSr = null; + try { + if ((srcStore instanceof NfsTO) && (srcData.getObjectType() == DataObjectType.TEMPLATE)) { + NfsTO srcImageStore = (NfsTO)srcStore; + TemplateObjectTO srcTemplate = (TemplateObjectTO)srcData; + String storeUrl = srcImageStore.getUrl(); + URI uri = new URI(storeUrl); + String volumePath = srcData.getPath(); + volumePath = StringUtils.stripEnd(volumePath, "/"); + String[] splits = volumePath.split("/"); + String volumeDirectory = volumePath; + if (splits.length > 4) { + //"template/tmpl/dcid/templateId/templatename" + int index = volumePath.lastIndexOf("/"); + volumeDirectory = volumePath.substring(0, index); + } + srcSr = createFileSr(conn, uri.getHost() + ":" + uri.getPath(), volumeDirectory); + Set vdis = srcSr.getVDIs(conn); + if (vdis.size() != 1) { + return new CopyCmdAnswer("Can't find template VDI under: " + uri.getHost() + ":" + uri.getPath() + "/" + volumeDirectory); + } + + VDI srcVdi = vdis.iterator().next(); + + PrimaryDataStoreTO destStore = (PrimaryDataStoreTO)destData.getDataStore(); + String poolName = destStore.getUuid(); + + + SR poolsr = null; + Set srs = SR.getByNameLabel(conn, poolName); + if (srs.size() != 1) { + String msg = "There are " + srs.size() + " SRs with same name: " + poolName; + s_logger.warn(msg); + return new CopyCmdAnswer(msg); + } else { + poolsr = srs.iterator().next(); + } + String pUuid = poolsr.getUuid(conn); + boolean isISCSI = IsISCSI(poolsr.getType(conn)); + Task task = srcVdi.copyAsync2(conn, poolsr, null, null); + // poll every 1 seconds , + hypervisorResource.waitForTask(conn, task, 1000, wait * 1000); + hypervisorResource.checkForSuccess(conn, task); + VDI tmpl = Types.toVDI(task, conn); + VDI snapshotvdi = tmpl.snapshot(conn, new HashMap()); + snapshotvdi.setNameLabel(conn, "Template " + srcTemplate.getName()); + tmpl.destroy(conn); + poolsr.scan(conn); + try{ + Thread.sleep(5000); + } catch (Exception e) { + } + + TemplateObjectTO newVol = new TemplateObjectTO(); + newVol.setUuid(snapshotvdi.getUuid(conn)); + newVol.setPath(newVol.getUuid()); + newVol.setFormat(Storage.ImageFormat.VHD); + return new CopyCmdAnswer(newVol); + } + }catch (Exception e) { + String msg = "Catch Exception " + e.getClass().getName() + " for template + " + " due to " + e.toString(); + s_logger.warn(msg, e); + return new CopyCmdAnswer(msg); + } finally { + if (srcSr != null) { + hypervisorResource.removeSR(conn, srcSr); + } + } + return new CopyCmdAnswer("not implemented yet"); + } + + protected String backupSnapshot(Connection conn, String primaryStorageSRUuid, String localMountPoint, String path, String secondaryStorageMountPath, String snapshotUuid, String prevBackupUuid, String prevSnapshotUuid, Boolean isISCSI, int wait) { + String errMsg = null; + boolean mounted = false; + boolean filesrcreated = false; + boolean copied = false; + if (prevBackupUuid == null) { + prevBackupUuid = ""; + } + SR ssSR = null; + + String remoteDir = secondaryStorageMountPath; + + try { + ssSR = createFileSr(conn, remoteDir, path); + filesrcreated = true; + + VDI snapshotvdi = VDI.getByUuid(conn, snapshotUuid); + Task task = null; + if (wait == 0) { + wait = 2 * 60 * 60; + } + VDI dvdi = null; + try { + VDI previousSnapshotVdi = null; + if (prevSnapshotUuid != null) { + previousSnapshotVdi = VDI.getByUuid(conn,prevSnapshotUuid); + } + task = snapshotvdi.copyAsync2(conn, ssSR, previousSnapshotVdi, null); + // poll every 1 seconds , + hypervisorResource.waitForTask(conn, task, 1000, wait * 1000); + hypervisorResource.checkForSuccess(conn, task); + dvdi = Types.toVDI(task, conn); + copied = true; + } finally { + if (task != null) { + try { + task.destroy(conn); + } catch (Exception e1) { + s_logger.warn("unable to destroy task(" + task.toString() + ") on host(" + + ") due to ", e1); + } + } + } + String backupUuid = dvdi.getUuid(conn); + return backupUuid; + } catch (Exception e) { + String msg = "Exception in backupsnapshot stage due to " + e.toString(); + s_logger.debug(msg); + throw new CloudRuntimeException(msg, e); + } finally { + try { + if (filesrcreated && ssSR != null) { + hypervisorResource.removeSR(conn, ssSR); + } + } catch (Exception e) { + s_logger.debug("Exception in backupsnapshot cleanup stage due to " + e.toString()); + } + } + } + + @Override + protected String getVhdParent(Connection conn, String primaryStorageSRUuid, String snapshotUuid, Boolean isISCSI) { + String parentUuid = hypervisorResource.callHostPlugin(conn, "cloud-plugin-storage", "getVhdParent", "primaryStorageSRUuid", primaryStorageSRUuid, + "snapshotUuid", snapshotUuid, "isISCSI", isISCSI.toString()); + + if (parentUuid == null || parentUuid.isEmpty() || parentUuid.equalsIgnoreCase("None")) { + s_logger.debug("Unable to get parent of VHD " + snapshotUuid + " in SR " + primaryStorageSRUuid); + // errString is already logged. + return null; + } + return parentUuid; + } + + @Override + public Answer backupSnapshot(CopyCommand cmd) { + Connection conn = hypervisorResource.getConnection(); + DataTO srcData = cmd.getSrcTO(); + DataTO cacheData = cmd.getCacheTO(); + DataTO destData = cmd.getDestTO(); + int wait = cmd.getWait(); + PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO)srcData.getDataStore(); + String primaryStorageNameLabel = primaryStore.getUuid(); + String secondaryStorageUrl = null; + NfsTO cacheStore = null; + String destPath = null; + if (cacheData != null) { + cacheStore = (NfsTO)cacheData.getDataStore(); + secondaryStorageUrl = cacheStore.getUrl(); + destPath = cacheData.getPath(); + } else { + cacheStore = (NfsTO)destData.getDataStore(); + secondaryStorageUrl = cacheStore.getUrl(); + destPath = destData.getPath(); + } + + SnapshotObjectTO snapshotTO = (SnapshotObjectTO)srcData; + SnapshotObjectTO snapshotOnImage = (SnapshotObjectTO)destData; + String snapshotUuid = snapshotTO.getPath(); + + String prevBackupUuid = snapshotOnImage.getParentSnapshotPath(); + String prevSnapshotUuid = snapshotTO.getParentSnapshotPath(); + Map options = cmd.getOptions(); + // By default assume failure + String details = null; + String snapshotBackupUuid = null; + boolean fullbackup = Boolean.parseBoolean(options.get("fullSnapshot")); + try { + SR primaryStorageSR = hypervisorResource.getSRByNameLabelandHost(conn, primaryStorageNameLabel); + if (primaryStorageSR == null) { + throw new InternalErrorException("Could not backup snapshot because the primary Storage SR could not be created from the name label: " + primaryStorageNameLabel); + } + String psUuid = primaryStorageSR.getUuid(conn); + Boolean isISCSI = IsISCSI(primaryStorageSR.getType(conn)); + + VDI snapshotVdi = getVDIbyUuid(conn, snapshotUuid); + String snapshotPaUuid = null; + + URI uri = new URI(secondaryStorageUrl); + String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath(); + DataStoreTO destStore = destData.getDataStore(); + String folder = destPath; + String finalPath = null; + + String localMountPoint = BaseMountPointOnHost + File.separator + UUID.nameUUIDFromBytes(secondaryStorageUrl.getBytes()).toString(); + if (fullbackup) { + SR snapshotSr = null; + try { + String localDir = "/var/cloud_mount/" + UUID.nameUUIDFromBytes(secondaryStorageMountPath.getBytes()); + mountNfs(conn, secondaryStorageMountPath, localDir); + boolean result = makeDirectory(conn, localDir + "/" + folder); + if (!result) { + details = " Filed to create folder " + folder + " in secondary storage"; + s_logger.warn(details); + return new CopyCmdAnswer(details); + } + + snapshotSr = createFileSr(conn, secondaryStorageMountPath, folder); + + Task task = snapshotVdi.copyAsync2(conn, snapshotSr, null, null); + // poll every 1 seconds , + hypervisorResource.waitForTask(conn, task, 1000, wait * 1000); + hypervisorResource.checkForSuccess(conn, task); + VDI backedVdi = Types.toVDI(task, conn); + snapshotBackupUuid = backedVdi.getUuid(conn); + + if( destStore instanceof SwiftTO) { + try { + String container = "S-" + snapshotTO.getVolume().getVolumeId().toString(); + String destSnapshotName = swiftBackupSnapshot(conn, (SwiftTO)destStore, snapshotSr.getUuid(conn), snapshotBackupUuid, container, false, wait); + String swiftPath = container + File.separator + destSnapshotName; + finalPath = swiftPath; + } finally { + try { + deleteSnapshotBackup(conn, localMountPoint, folder, secondaryStorageMountPath, snapshotBackupUuid); + } catch (Exception e) { + s_logger.debug("Failed to delete snapshot on cache storages" ,e); + } + } + + } else if (destStore instanceof S3TO) { + try { + finalPath = backupSnapshotToS3(conn, (S3TO) destStore, snapshotSr.getUuid(conn), folder, snapshotBackupUuid, isISCSI, wait); + if (finalPath == null) { + throw new CloudRuntimeException("S3 upload of snapshots " + snapshotBackupUuid + " failed"); + } + } finally { + try { + deleteSnapshotBackup(conn, localMountPoint, folder, secondaryStorageMountPath, snapshotBackupUuid); + } catch (Exception e) { + s_logger.debug("Failed to delete snapshot on cache storages" ,e); + } + } + // finalPath = folder + File.separator + snapshotBackupUuid; + } else { + finalPath = folder + File.separator + snapshotBackupUuid; + } + + } finally { + if( snapshotSr != null) { + hypervisorResource.removeSR(conn, snapshotSr); + } + } + } else { + String primaryStorageSRUuid = primaryStorageSR.getUuid(conn); + if( destStore instanceof SwiftTO ) { + String container = "S-" + snapshotTO.getVolume().getVolumeId().toString(); + snapshotBackupUuid = swiftBackupSnapshot(conn, (SwiftTO)destStore, primaryStorageSRUuid, snapshotPaUuid, "S-" + snapshotTO.getVolume().getVolumeId().toString(), isISCSI, wait); + finalPath = container + File.separator + snapshotBackupUuid; + } else if (destStore instanceof S3TO ) { + finalPath = backupSnapshotToS3(conn, (S3TO) destStore, primaryStorageSRUuid, folder, snapshotPaUuid, isISCSI, wait); + if (finalPath == null) { + throw new CloudRuntimeException("S3 upload of snapshots " + snapshotPaUuid + " failed"); + } + } else { + snapshotBackupUuid = backupSnapshot(conn, primaryStorageSRUuid, localMountPoint, folder, + secondaryStorageMountPath, snapshotUuid, prevBackupUuid, prevSnapshotUuid, isISCSI, wait); + + finalPath = folder + File.separator + snapshotBackupUuid; + } + } + String volumeUuid = snapshotTO.getVolume().getPath(); + destroySnapshotOnPrimaryStorageExceptThis(conn, volumeUuid, snapshotUuid); + + SnapshotObjectTO newSnapshot = new SnapshotObjectTO(); + newSnapshot.setPath(finalPath); + if (fullbackup) { + newSnapshot.setParentSnapshotPath(null); + } else { + newSnapshot.setParentSnapshotPath(prevBackupUuid); + } + return new CopyCmdAnswer(newSnapshot); + } catch (Types.XenAPIException e) { + details = "BackupSnapshot Failed due to " + e.toString(); + s_logger.warn(details, e); + } catch (Exception e) { + details = "BackupSnapshot Failed due to " + e.getMessage(); + s_logger.warn(details, e); + } + + return new CopyCmdAnswer(details); + } + + @Override + public Answer createTemplateFromVolume(CopyCommand cmd) { + Connection conn = hypervisorResource.getConnection(); + VolumeObjectTO volume = (VolumeObjectTO)cmd.getSrcTO(); + TemplateObjectTO template = (TemplateObjectTO)cmd.getDestTO(); + NfsTO destStore = (NfsTO)cmd.getDestTO().getDataStore(); + int wait = cmd.getWait(); + + String secondaryStoragePoolURL = destStore.getUrl(); + String volumeUUID = volume.getPath(); + + String userSpecifiedName = template.getName(); + + + String details = null; + SR tmpltSR = null; + boolean result = false; + String secondaryStorageMountPath = null; + String installPath = null; + try { + URI uri = new URI(secondaryStoragePoolURL); + secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath(); + installPath = template.getPath(); + if( !hypervisorResource.createSecondaryStorageFolder(conn, secondaryStorageMountPath, installPath)) { + details = " Filed to create folder " + installPath + " in secondary storage"; + s_logger.warn(details); + return new CopyCmdAnswer(details); + } + + VDI vol = getVDIbyUuid(conn, volumeUUID); + // create template SR + tmpltSR = createFileSr(conn, uri.getHost() + ":" + uri.getPath(), installPath); + + // copy volume to template SR + Task task = vol.copyAsync2(conn, tmpltSR, null, null); + // poll every 1 seconds , + hypervisorResource.waitForTask(conn, task, 1000, wait * 1000); + hypervisorResource.checkForSuccess(conn, task); + VDI tmpltVDI = Types.toVDI(task, conn); + // scan makes XenServer pick up VDI physicalSize + tmpltSR.scan(conn); + if (userSpecifiedName != null) { + tmpltVDI.setNameLabel(conn, userSpecifiedName); + } + + String tmpltUUID = tmpltVDI.getUuid(conn); + String tmpltFilename = tmpltUUID + ".vhd"; + long virtualSize = tmpltVDI.getVirtualSize(conn); + long physicalSize = tmpltVDI.getPhysicalUtilisation(conn); + // create the template.properties file + String templatePath = secondaryStorageMountPath + "/" + installPath; + result = hypervisorResource.postCreatePrivateTemplate(conn, templatePath, tmpltFilename, tmpltUUID, userSpecifiedName, null, physicalSize, virtualSize, template.getId()); + if (!result) { + throw new CloudRuntimeException("Could not create the template.properties file on secondary storage dir"); + } + installPath = installPath + "/" + tmpltFilename; + hypervisorResource.removeSR(conn, tmpltSR); + tmpltSR = null; + TemplateObjectTO newTemplate = new TemplateObjectTO(); + newTemplate.setPath(installPath); + newTemplate.setFormat(Storage.ImageFormat.VHD); + newTemplate.setSize(virtualSize); + newTemplate.setPhysicalSize(physicalSize); + newTemplate.setName(tmpltUUID); + CopyCmdAnswer answer = new CopyCmdAnswer(newTemplate); + return answer; + } catch (Exception e) { + if (tmpltSR != null) { + hypervisorResource.removeSR(conn, tmpltSR); + } + if ( secondaryStorageMountPath != null) { + hypervisorResource.deleteSecondaryStorageFolder(conn, secondaryStorageMountPath, installPath); + } + details = "Creating template from volume " + volumeUUID + " failed due to " + e.toString(); + s_logger.error(details, e); + } + return new CopyCmdAnswer(details); + } + + protected String getSnapshotUuid(String snapshotPath) { + int index = snapshotPath.lastIndexOf(File.separator); + String snapshotUuid = snapshotPath.substring(index + 1); + index = snapshotUuid.lastIndexOf("."); + if (index != -1) { + snapshotUuid = snapshotUuid.substring(0, index); + } + return snapshotUuid; + } + + @Override + public Answer createVolumeFromSnapshot(CopyCommand cmd) { + Connection conn = hypervisorResource.getConnection(); + DataTO srcData = cmd.getSrcTO(); + SnapshotObjectTO snapshot = (SnapshotObjectTO)srcData; + DataTO destData = cmd.getDestTO(); + PrimaryDataStoreTO pool = (PrimaryDataStoreTO)destData.getDataStore(); + VolumeObjectTO volume = (VolumeObjectTO)destData; + DataStoreTO imageStore = srcData.getDataStore(); + + if (!(imageStore instanceof NfsTO)) { + return new CopyCmdAnswer("unsupported protocol"); + } + + NfsTO nfsImageStore = (NfsTO)imageStore; + String primaryStorageNameLabel = pool.getUuid(); + String secondaryStorageUrl = nfsImageStore.getUrl(); + int wait = cmd.getWait(); + boolean result = false; + // Generic error message. + String details = null; + String volumeUUID = null; + + if (secondaryStorageUrl == null) { + details += " because the URL passed: " + secondaryStorageUrl + " is invalid."; + return new CopyCmdAnswer(details); + } + SR srcSr = null; + VDI destVdi = null; + try { + SR primaryStorageSR = hypervisorResource.getSRByNameLabelandHost(conn, primaryStorageNameLabel); + if (primaryStorageSR == null) { + throw new InternalErrorException("Could not create volume from snapshot because the primary Storage SR could not be created from the name label: " + + primaryStorageNameLabel); + } + String nameLabel = "cloud-" + UUID.randomUUID().toString(); + destVdi = createVdi(conn, nameLabel, primaryStorageSR, volume.getSize()); + volumeUUID = destVdi.getUuid(conn); + String snapshotInstallPath = snapshot.getPath(); + int index = snapshotInstallPath.lastIndexOf(File.separator); + String snapshotDirectory = snapshotInstallPath.substring(0, index); + String snapshotUuid = getSnapshotUuid(snapshotInstallPath); + + URI uri = new URI(secondaryStorageUrl); + srcSr = createFileSr(conn, uri.getHost() + ":" + uri.getPath(), snapshotDirectory); + + String[] parents = snapshot.getParents(); + List snapshotChains = new ArrayList(); + if (parents != null) { + for(int i = 0; i < parents.length; i++) { + String snChainPath = parents[i]; + String uuid = getSnapshotUuid(snChainPath); + VDI chain = VDI.getByUuid(conn, uuid); + snapshotChains.add(chain); + } + } + + VDI snapshotVdi = VDI.getByUuid(conn, snapshotUuid); + snapshotChains.add(snapshotVdi); + + for(VDI snapChain : snapshotChains) { + Task task = snapChain.copyAsync2(conn, null, null, destVdi); + // poll every 1 seconds , + hypervisorResource.waitForTask(conn, task, 1000, wait * 1000); + hypervisorResource.checkForSuccess(conn, task); + } + + result = true; + destVdi = VDI.getByUuid(conn, volumeUUID); + VDI.Record vdir = destVdi.getRecord(conn); + VolumeObjectTO newVol = new VolumeObjectTO(); + newVol.setPath(volumeUUID); + newVol.setSize(vdir.virtualSize); + return new CopyCmdAnswer(newVol); + } catch (Types.XenAPIException e) { + details += " due to " + e.toString(); + s_logger.warn(details, e); + } catch (Exception e) { + details += " due to " + e.getMessage(); + s_logger.warn(details, e); + } finally { + if (srcSr != null) { + hypervisorResource.removeSR(conn, srcSr); + } + if (!result && destVdi != null) { + try { + destVdi.destroy(conn); + } catch (Exception e) { + s_logger.debug("destroy dest vdi failed", e); + } + } + } + if (!result) { + // Is this logged at a higher level? + s_logger.error(details); + } + + // In all cases return something. + return new CopyCmdAnswer(details); + } + + @Override + public Answer copyVolumeFromPrimaryToSecondary(CopyCommand cmd) { + Connection conn = hypervisorResource.getConnection(); + VolumeObjectTO srcVolume = (VolumeObjectTO)cmd.getSrcTO(); + VolumeObjectTO destVolume = (VolumeObjectTO)cmd.getDestTO(); + int wait = cmd.getWait(); + DataStoreTO destStore = destVolume.getDataStore(); + + if (destStore instanceof NfsTO) { + SR secondaryStorage = null; + try { + NfsTO nfsStore = (NfsTO)destStore; + URI uri = new URI(nfsStore.getUrl()); + // Create the volume folder + if (!hypervisorResource.createSecondaryStorageFolder(conn, uri.getHost() + ":" + uri.getPath(), destVolume.getPath())) { + throw new InternalErrorException("Failed to create the volume folder."); + } + + // Create a SR for the volume UUID folder + secondaryStorage = createFileSr(conn, uri.getHost() + ":" + uri.getPath(), destVolume.getPath()); + // Look up the volume on the source primary storage pool + VDI srcVdi = getVDIbyUuid(conn, srcVolume.getPath()); + // Copy the volume to secondary storage + Task task = srcVdi.copyAsync2(conn, secondaryStorage, null, null); + // poll every 1 seconds , + hypervisorResource.waitForTask(conn, task, 1000, wait * 1000); + hypervisorResource.checkForSuccess(conn, task); + VDI destVdi = Types.toVDI(task, conn); + String destVolumeUUID = destVdi.getUuid(conn); + + VolumeObjectTO newVol = new VolumeObjectTO(); + newVol.setPath(destVolume.getPath() + File.separator + destVolumeUUID + ".vhd"); + newVol.setSize(srcVolume.getSize()); + return new CopyCmdAnswer(newVol); + } catch (Exception e) { + s_logger.debug("Failed to copy volume to secondary: " + e.toString()); + return new CopyCmdAnswer("Failed to copy volume to secondary: " + e.toString()); + } finally { + hypervisorResource.removeSR(conn, secondaryStorage); + } + } + return new CopyCmdAnswer("unsupported protocol"); + } + + @Override + public Answer copyVolumeFromImageCacheToPrimary(CopyCommand cmd) { + Connection conn = hypervisorResource.getConnection(); + DataTO srcData = cmd.getSrcTO(); + DataTO destData = cmd.getDestTO(); + int wait = cmd.getWait(); + VolumeObjectTO srcVolume = (VolumeObjectTO)srcData; + VolumeObjectTO destVolume = (VolumeObjectTO)destData; + PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO)destVolume.getDataStore(); + DataStoreTO srcStore = srcVolume.getDataStore(); + + if (srcStore instanceof NfsTO) { + NfsTO nfsStore = (NfsTO)srcStore; + String volumePath = srcVolume.getPath(); + int index = volumePath.lastIndexOf("/"); + String volumeDirectory = volumePath.substring(0, index); + String volumeUuid = volumePath.substring(index + 1); + index = volumeUuid.indexOf("."); + if (index != -1) { + volumeUuid = volumeUuid.substring(0, index); + } + URI uri = null; + try { + uri = new URI(nfsStore.getUrl()); + } catch (Exception e) { + return new CopyCmdAnswer(e.toString()); + } + SR srcSr = createFileSr(conn, uri.getHost() + ":" + uri.getPath(), volumeDirectory); + try { + SR primaryStoragePool = hypervisorResource.getStorageRepository(conn, primaryStore.getUuid()); + VDI srcVdi = VDI.getByUuid(conn, volumeUuid); + Task task = srcVdi.copyAsync2(conn, primaryStoragePool, null, null); + // poll every 1 seconds , + hypervisorResource.waitForTask(conn, task, 1000, wait * 1000); + hypervisorResource.checkForSuccess(conn, task); + VDI destVdi = Types.toVDI(task, conn); + VolumeObjectTO newVol = new VolumeObjectTO(); + newVol.setPath(destVdi.getUuid(conn)); + newVol.setSize(srcVolume.getSize()); + + return new CopyCmdAnswer(newVol); + } catch (Exception e) { + String msg = "Catch Exception " + e.getClass().getName() + " due to " + e.toString(); + s_logger.warn(msg, e); + return new CopyCmdAnswer(e.toString()); + } finally { + if (srcSr != null) { + hypervisorResource.removeSR(conn, srcSr); + } + } + } + + s_logger.debug("unsupported protocol"); + return new CopyCmdAnswer("unsupported protocol"); + } + + @Override + public Answer createTemplateFromSnapshot(CopyCommand cmd) { + Connection conn = hypervisorResource.getConnection(); + DataTO srcData = cmd.getSrcTO(); + DataTO destData = cmd.getDestTO(); + int wait = cmd.getWait(); + SnapshotObjectTO srcObj = (SnapshotObjectTO)srcData; + TemplateObjectTO destObj = (TemplateObjectTO)destData; + NfsTO srcStore = (NfsTO)srcObj.getDataStore(); + NfsTO destStore = (NfsTO)destObj.getDataStore(); + + URI srcUri = null; + URI destUri = null; + try { + srcUri = new URI(srcStore.getUrl()); + destUri = new URI(destStore.getUrl()); + } catch (Exception e) { + s_logger.debug("incorrect url", e); + return new CopyCmdAnswer("incorrect url" + e.toString()); + } + + String srcPath = srcObj.getPath(); + int index = srcPath.lastIndexOf("/"); + String srcDir = srcPath.substring(0, index); + String destDir = destObj.getPath(); + SR srcSr = null; + SR destSr = null; + VDI destVdi = null; + boolean result = false; + try { + srcSr = createFileSr(conn, srcUri.getHost() + ":" + srcUri.getPath(), srcDir); + + String destNfsPath = destUri.getHost() + ":" + destUri.getPath(); + String localDir = "/var/cloud_mount/" + UUID.nameUUIDFromBytes(destNfsPath.getBytes()); + mountNfs(conn, destUri.getHost() + ":" + destUri.getPath(), localDir); + makeDirectory(conn, localDir + "/" + destDir); + destSr = createFileSR(conn, localDir + "/" + destDir); + + String nameLabel = "cloud-" + UUID.randomUUID().toString(); + + String[] parents = srcObj.getParents(); + List snapshotChains = new ArrayList(); + if (parents != null) { + for(int i = 0; i < parents.length; i++) { + String snChainPath = parents[i]; + String uuid = getSnapshotUuid(snChainPath); + VDI chain = VDI.getByUuid(conn, uuid); + snapshotChains.add(chain); + } + } + String snapshotUuid = getSnapshotUuid(srcPath); + VDI snapshotVdi = VDI.getByUuid(conn, snapshotUuid); + snapshotChains.add(snapshotVdi); + + long templateVirtualSize = snapshotChains.get(0).getVirtualSize(conn); + destVdi = createVdi(conn, nameLabel, destSr, templateVirtualSize); + String destVdiUuid = destVdi.getUuid(conn); + + for(VDI snapChain : snapshotChains) { + Task task = snapChain.copyAsync2(conn, null, null, destVdi); + // poll every 1 seconds , + hypervisorResource.waitForTask(conn, task, 1000, wait * 1000); + hypervisorResource.checkForSuccess(conn, task); + } + + destVdi = VDI.getByUuid(conn, destVdiUuid); + String templatePath = destDir + "/" + destVdiUuid + ".vhd"; + templatePath = templatePath.replaceAll("//","/"); + TemplateObjectTO newTemplate = new TemplateObjectTO(); + newTemplate.setPath(templatePath); + newTemplate.setFormat(Storage.ImageFormat.VHD); + newTemplate.setSize(destVdi.getVirtualSize(conn)); + newTemplate.setPhysicalSize(destVdi.getPhysicalUtilisation(conn)); + newTemplate.setName(destVdiUuid); + + result = true; + return new CopyCmdAnswer(newTemplate); + } catch (Exception e) { + s_logger.error("Failed create template from snapshot", e); + return new CopyCmdAnswer("Failed create template from snapshot " + e.toString()); + } finally { + if (!result) { + if (destVdi != null) { + try { + destVdi.destroy(conn); + } catch (Exception e) { + s_logger.debug("Clean up left over on dest storage failed: ", e); + } + } + } + + if (destSr != null) { + hypervisorResource.removeSR(conn, destSr); + } + + if (srcSr != null) { + hypervisorResource.removeSR(conn, srcSr); + } + } + } + +} diff --git a/plugins/hypervisors/xen/src/org/apache/cloudstack/hypervisor/xenserver/XenServerResourceNewBase.java b/plugins/hypervisors/xen/src/org/apache/cloudstack/hypervisor/xenserver/XenServerResourceNewBase.java new file mode 100644 index 00000000000..1c9748679bd --- /dev/null +++ b/plugins/hypervisors/xen/src/org/apache/cloudstack/hypervisor/xenserver/XenServerResourceNewBase.java @@ -0,0 +1,320 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.hypervisor.xenserver; + + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.TimeoutException; + +import org.apache.log4j.Logger; +import org.apache.xmlrpc.XmlRpcException; + +import com.xensource.xenapi.Connection; +import com.xensource.xenapi.Event; +import com.xensource.xenapi.Host; +import com.xensource.xenapi.Pool; +import com.xensource.xenapi.Task; +import com.xensource.xenapi.Types; +import com.xensource.xenapi.Types.XenAPIException; +import com.xensource.xenapi.VM; + +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.ClusterSyncAnswer; +import com.cloud.agent.api.ClusterSyncCommand; +import com.cloud.agent.api.StartupCommand; +import com.cloud.hypervisor.xen.resource.XenServer610Resource; +import com.cloud.utils.Ternary; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.VirtualMachineName; + +public class XenServerResourceNewBase extends XenServer610Resource { + private static final Logger s_logger = Logger.getLogger(XenServerResourceNewBase.class); + protected VmEventListener _listener = null; + + @Override + public StartupCommand[] initialize() throws IllegalArgumentException { + StartupCommand[] cmds = super.initialize(); + + Connection conn = getConnection(); + Pool pool; + try { + pool = Pool.getByUuid(conn, _host.pool); + Pool.Record poolr = pool.getRecord(conn); + + Host.Record masterRecord = poolr.master.getRecord(conn); + if (_host.uuid.equals(masterRecord.uuid)) { + _listener = new VmEventListener(true); + _listener.start(); + } else { + _listener = new VmEventListener(false); + } + } catch (XenAPIException e) { + throw new CloudRuntimeException("Unable to determine who is the master", e); + } catch (XmlRpcException e) { + throw new CloudRuntimeException("Unable to determine who is the master", e); + } + return cmds; + } + + protected void waitForTask2(Connection c, Task task, long pollInterval, long timeout) throws XenAPIException, XmlRpcException, TimeoutException { + long beginTime = System.currentTimeMillis(); + if (s_logger.isTraceEnabled()) { + s_logger.trace("Task " + task.getNameLabel(c) + " (" + task.getType(c) + ") sent to " + c.getSessionReference() + " is pending completion with a " + timeout + + "ms timeout"); + } + Set classes = new HashSet(); + classes.add("Task/" + task.toString()); + String token = ""; + Double t = new Double(timeout / 1000); + while (true) { + Map map = Event.properFrom(c, classes, token, t); + token = (String)map.get("token"); + @SuppressWarnings("unchecked") + Set events = (Set)map.get("events"); + if (events.size() == 0) { + String msg = "Async " + timeout / 1000 + " seconds timeout for task " + task.toString(); + s_logger.warn(msg); + task.cancel(c); + throw new TimeoutException(msg); + } + for (Event.Record rec : events) { + if (!(rec.snapshot instanceof Task.Record)) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Skipping over " + rec); + } + continue; + } + + Task.Record taskRecord = (Task.Record)rec.snapshot; + + if (taskRecord.status != Types.TaskStatusType.PENDING) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Task is done " + taskRecord.status); + } + return; + } else { + s_logger.debug("Task is not done " + taskRecord); + } + } + } + } + + @Override + protected Answer execute(final ClusterSyncCommand cmd) { + if (!_listener.isListening()) { + return new Answer(cmd); + } + + HashMap> newStates = _listener.getChanges(); + return new ClusterSyncAnswer(cmd.getClusterId(), newStates); + } + + protected class VmEventListener extends Thread { + boolean _stop = false; + HashMap> _changes = new HashMap>(); + boolean _isMaster; + Set _classes; + String _token = ""; + + public VmEventListener(boolean isMaster) { + _isMaster = isMaster; + _classes = new HashSet(); + _classes.add("VM"); + } + + @Override + public void run() { + setName("XS-Listener-" + _host.ip); + while (!_stop) { + try { + Connection conn = getConnection(); + Map results; + try { + results = Event.properFrom(conn, _classes, _token, new Double(30)); + } catch (Exception e) { + s_logger.error("Retrying the waiting on VM events due to: ", e); + continue; + } + + _token = (String)results.get("token"); + @SuppressWarnings("unchecked") + Set events = (Set)results.get("events"); + for (Event.Record event : events) { + try { + if (!(event.snapshot instanceof VM.Record)) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("The snapshot is not a VM: " + event); + } + continue; + } + VM.Record vm = (VM.Record)event.snapshot; + + String hostUuid = null; + if (vm.residentOn != null && !vm.residentOn.toWireString().contains("OpaqueRef:NULL")) { + hostUuid = vm.residentOn.getUuid(conn); + } + recordChanges(conn, vm, hostUuid); + } catch (Exception e) { + s_logger.error("Skipping over " + event, e); + } + } + } catch (Throwable th) { + s_logger.error("Exception caught in eventlistener thread: ", th); + } + } + } + + protected void recordChanges(Connection conn, VM.Record rec, String hostUuid) { + String vm = rec.nameLabel; + if (!VirtualMachineName.isValidCloudStackVmName(vm, _instance)) { + s_logger.debug("Skipping over VMs that does not conform to CloudStack naming convention: " + vm); + return; + } + + VirtualMachine.State currentState = convertToState(rec.powerState); + if (vm.startsWith("migrating")) { + s_logger.warn("Skipping " + vm + " because it is migrating."); + return; + } + + if (currentState == VirtualMachine.State.Stopped) { + if (s_logger.isTraceEnabled()) { + s_logger.trace("Double check the power state to make sure we got the correct state for " + vm); + } + currentState = getRealPowerState(conn, vm); + } + + boolean updateMap = false; + boolean reportChange = false; + + // NOTE: For now we only record change when the VM is stopped. We don't find out any VMs starting for now. + synchronized (_cluster.intern()) { + Ternary oldState = s_vms.get(_cluster, vm); + if (oldState == null) { + if (s_logger.isTraceEnabled()) { + s_logger.trace("Unable to find " + vm + " from previous map. Assuming it was in Stopped state."); + } + oldState = new Ternary(null, VirtualMachine.State.Stopped, null); + } + + if (s_logger.isTraceEnabled()) { + s_logger.trace(vm + ": current state=" + currentState + ", previous state=" + oldState); + } + + if (oldState.second() == VirtualMachine.State.Starting) { + if (currentState == VirtualMachine.State.Running) { + updateMap = true; + reportChange = false; + } else if (currentState == VirtualMachine.State.Stopped) { + updateMap = false; + reportChange = false; + } + } else if (oldState.second() == VirtualMachine.State.Migrating) { + updateMap = true; + reportChange = false; + } else if (oldState.second() == VirtualMachine.State.Stopping) { + if (currentState == VirtualMachine.State.Stopped) { + updateMap = true; + reportChange = false; + } else if (currentState == VirtualMachine.State.Running) { + updateMap = false; + reportChange = false; + } + } else if (oldState.second() != currentState) { + updateMap = true; + reportChange = true; + } else if (hostUuid != null && !hostUuid.equals(oldState.first())) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Detecting " + vm + " moved from " + oldState.first() + " to " + hostUuid); + } + reportChange = true; + updateMap = true; + } + + if (updateMap) { + s_vms.put(_cluster, hostUuid, vm, currentState); + if (s_logger.isTraceEnabled()) { + s_logger.trace("Updated " + vm + " to [" + hostUuid + ", " + currentState); + } + } + if (reportChange) { + Ternary change = _changes.get(vm); + if (hostUuid == null) { + // This is really strange code. It looks like the sync + // code wants this to be set, which is extremely weird + // for VMs that are dead. Why would I want to set the + // hostUuid if the VM is stopped. + hostUuid = oldState.first(); + if (hostUuid == null) { + hostUuid = _host.uuid; + } + } + if (change == null) { + change = new Ternary(hostUuid, currentState, null); + } else { + change.first(hostUuid); + change.second(currentState); + } + _changes.put(vm, change); + } + } + } + + @Override + public void start() { + if (_isMaster) { + // Throw away the initial set of events because they're history + Connection conn = getConnection(); + Map results; + try { + results = Event.properFrom(conn, _classes, _token, new Double(30)); + } catch (Exception e) { + s_logger.error("Retrying the waiting on VM events due to: ", e); + throw new CloudRuntimeException("Unable to start a listener thread to listen to VM events", e); + } + _token = (String)results.get("token"); + s_logger.debug("Starting the event listener thread for " + _host.uuid); + super.start(); + } + } + + public boolean isListening() { + return _isMaster; + } + + public HashMap> getChanges() { + synchronized (_cluster.intern()) { + if (_changes.size() == 0) { + return null; + } + HashMap> diff = _changes; + _changes = new HashMap>(); + return diff; + } + } + + public void signalStop() { + _stop = true; + interrupt(); + } + } + +} diff --git a/plugins/hypervisors/xen/src/org/apache/cloudstack/storage/motion/XenServerStorageMotionStrategy.java b/plugins/hypervisors/xen/src/org/apache/cloudstack/storage/motion/XenServerStorageMotionStrategy.java index f2bf47262ca..e8217f7216f 100644 --- a/plugins/hypervisors/xen/src/org/apache/cloudstack/storage/motion/XenServerStorageMotionStrategy.java +++ b/plugins/hypervisors/xen/src/org/apache/cloudstack/storage/motion/XenServerStorageMotionStrategy.java @@ -106,7 +106,7 @@ public class XenServerStorageMotionStrategy implements DataMotionStrategy { try { VMInstanceVO instance = instanceDao.findById(vmTo.getId()); if (instance != null) { - if (srcHost.getClusterId() == destHost.getClusterId()) { + if (srcHost.getClusterId().equals(destHost.getClusterId())) { answer = migrateVmWithVolumesWithinCluster(instance, vmTo, srcHost, destHost, volumeMap); } else { answer = migrateVmWithVolumesAcrossCluster(instance, vmTo, srcHost, destHost, volumeMap); @@ -126,7 +126,7 @@ public class XenServerStorageMotionStrategy implements DataMotionStrategy { } private Answer migrateVmWithVolumesAcrossCluster(VMInstanceVO vm, VirtualMachineTO to, Host srcHost, Host destHost, Map volumeToPool) - throws AgentUnavailableException { + throws AgentUnavailableException { // Initiate migration of a virtual machine with it's volumes. try { @@ -153,7 +153,7 @@ public class XenServerStorageMotionStrategy implements DataMotionStrategy { } MigrateWithStorageSendCommand sendCmd = - new MigrateWithStorageSendCommand(to, receiveAnswer.getVolumeToSr(), receiveAnswer.getNicToNetwork(), receiveAnswer.getToken()); + new MigrateWithStorageSendCommand(to, receiveAnswer.getVolumeToSr(), receiveAnswer.getNicToNetwork(), receiveAnswer.getToken()); MigrateWithStorageSendAnswer sendAnswer = (MigrateWithStorageSendAnswer)agentMgr.send(srcHost.getId(), sendCmd); if (sendAnswer == null) { s_logger.error("Migration with storage of vm " + vm + " to host " + destHost + " failed."); @@ -184,7 +184,7 @@ public class XenServerStorageMotionStrategy implements DataMotionStrategy { } private Answer migrateVmWithVolumesWithinCluster(VMInstanceVO vm, VirtualMachineTO to, Host srcHost, Host destHost, Map volumeToPool) - throws AgentUnavailableException { + throws AgentUnavailableException { // Initiate migration of a virtual machine with it's volumes. try { diff --git a/plugins/network-elements/bigswitch-vns/src/com/cloud/network/bigswitch/BigSwitchVnsApi.java b/plugins/network-elements/bigswitch-vns/src/com/cloud/network/bigswitch/BigSwitchVnsApi.java index a2e1b969bb0..44445992858 100644 --- a/plugins/network-elements/bigswitch-vns/src/com/cloud/network/bigswitch/BigSwitchVnsApi.java +++ b/plugins/network-elements/bigswitch-vns/src/com/cloud/network/bigswitch/BigSwitchVnsApi.java @@ -47,8 +47,8 @@ import com.google.gson.reflect.TypeToken; public class BigSwitchVnsApi { private static final Logger s_logger = Logger.getLogger(BigSwitchVnsApi.class); - private final static String _protocol = "http"; - private final static String _nsBaseUri = "/networkService/v1.1"; + private final static String s_protocol = "http"; + private final static String s_nsBaseUri = "/networkService/v1.1"; private final static String CONTENT_TYPE = "Content-Type"; private final static String ACCEPT = "Accept"; private final static String CONTENT_JSON = "application/json"; @@ -70,7 +70,7 @@ public class BigSwitchVnsApi { protected HttpMethod createMethod(String type, String uri, int port) throws BigSwitchVnsApiException { String url; try { - url = new URL(_protocol, _host, port, uri).toString(); + url = new URL(s_protocol, _host, port, uri).toString(); } catch (MalformedURLException e) { s_logger.error("Unable to build BigSwitch API URL", e); throw new BigSwitchVnsApiException("Unable to build v API URL", e); @@ -109,44 +109,44 @@ public class BigSwitchVnsApi { } public void createNetwork(NetworkData network) throws BigSwitchVnsApiException { - String uri = _nsBaseUri + "/tenants/" + network.getNetwork().getTenant_id() + "/networks"; + String uri = s_nsBaseUri + "/tenants/" + network.getNetwork().getTenantId() + "/networks"; executeCreateObject(network, new TypeToken() { }.getType(), uri, Collections. emptyMap()); } public void deleteNetwork(String tenantId, String networkId) throws BigSwitchVnsApiException { - String uri = _nsBaseUri + "/tenants/" + tenantId + "/networks/" + networkId; + String uri = s_nsBaseUri + "/tenants/" + tenantId + "/networks/" + networkId; executeDeleteObject(uri); } public void createPort(String networkUuid, PortData port) throws BigSwitchVnsApiException { - String uri = _nsBaseUri + "/tenants/" + port.getPort().getTenant_id() + "/networks/" + networkUuid + "/ports"; + String uri = s_nsBaseUri + "/tenants/" + port.getPort().getTenantId() + "/networks/" + networkUuid + "/ports"; executeCreateObject(port, new TypeToken() { }.getType(), uri, Collections. emptyMap()); } public void modifyPort(String networkId, PortData port) throws BigSwitchVnsApiException { - String uri = _nsBaseUri + "/tenants/" + port.getPort().getTenant_id() + "/networks/" + networkId + "/ports"; + String uri = s_nsBaseUri + "/tenants/" + port.getPort().getTenantId() + "/networks/" + networkId + "/ports"; executeUpdateObject(port, uri, Collections. emptyMap()); } public void deletePort(String tenantId, String networkId, String portId) throws BigSwitchVnsApiException { - String uri = _nsBaseUri + "/tenants/" + tenantId + "/networks/" + networkId + "/ports/" + portId; + String uri = s_nsBaseUri + "/tenants/" + tenantId + "/networks/" + networkId + "/ports/" + portId; executeDeleteObject(uri); } public void modifyPortAttachment(String tenantId, String networkId, String portId, AttachmentData attachment) throws BigSwitchVnsApiException { - String uri = _nsBaseUri + "/tenants/" + tenantId + "/networks/" + networkId + "/ports/" + portId + "/attachment"; + String uri = s_nsBaseUri + "/tenants/" + tenantId + "/networks/" + networkId + "/ports/" + portId + "/attachment"; executeUpdateObject(attachment, uri, Collections. emptyMap()); } public void deletePortAttachment(String tenantId, String networkId, String portId) throws BigSwitchVnsApiException { - String uri = _nsBaseUri + "/tenants/" + tenantId + "/networks/" + networkId + "/ports/" + portId + "/attachment"; + String uri = s_nsBaseUri + "/tenants/" + tenantId + "/networks/" + networkId + "/ports/" + portId + "/attachment"; executeDeleteObject(uri); } public ControlClusterStatus getControlClusterStatus() throws BigSwitchVnsApiException { - String uri = _nsBaseUri + "/health"; + String uri = s_nsBaseUri + "/health"; ControlClusterStatus ccs = executeRetrieveObject(new TypeToken() { }.getType(), uri, 80, null); ccs.setStatus(true); diff --git a/plugins/network-elements/bigswitch-vns/src/com/cloud/network/bigswitch/NetworkData.java b/plugins/network-elements/bigswitch-vns/src/com/cloud/network/bigswitch/NetworkData.java index d4e97ac5428..e44c0f4f7df 100644 --- a/plugins/network-elements/bigswitch-vns/src/com/cloud/network/bigswitch/NetworkData.java +++ b/plugins/network-elements/bigswitch-vns/src/com/cloud/network/bigswitch/NetworkData.java @@ -17,20 +17,20 @@ package com.cloud.network.bigswitch; public class NetworkData { - private Network network; + private final Network network; public Network getNetwork() { - return this.network; + return network; } public NetworkData() { - this.network = new Network(); + network = new Network(); } public class Network { private String id; private String name; - private String tenant_id; + private String tenantId; private int vlan; private String gateway; private String state; @@ -43,20 +43,20 @@ public class NetworkData { this.id = id; } - public String getDisplay_name() { + public String getDisplayName() { return name; } - public void setDisplay_name(String display_name) { - this.name = display_name; + public void setDisplay_name(String displayName) { + name = displayName; } - public String getTenant_id() { - return tenant_id; + public String getTenantId() { + return tenantId; } - public void setTenant_id(String tenant_id) { - this.tenant_id = tenant_id; + public void setTenantId(String tenantId) { + this.tenantId = tenantId; } public int getVlan() { diff --git a/plugins/network-elements/bigswitch-vns/src/com/cloud/network/bigswitch/PortData.java b/plugins/network-elements/bigswitch-vns/src/com/cloud/network/bigswitch/PortData.java index 3c746c5b8e8..d228d37caac 100644 --- a/plugins/network-elements/bigswitch-vns/src/com/cloud/network/bigswitch/PortData.java +++ b/plugins/network-elements/bigswitch-vns/src/com/cloud/network/bigswitch/PortData.java @@ -30,7 +30,7 @@ public class PortData { public class Port { private String id; private String name; - private String tenant_id; + private String tenantId; private String state; public String getId() { @@ -49,12 +49,12 @@ public class PortData { this.name = name; } - public String getTenant_id() { - return tenant_id; + public String getTenantId() { + return tenantId; } - public void setTenant_id(String tenant_id) { - this.tenant_id = tenant_id; + public void setTenantId(String tenantId) { + this.tenantId = tenantId; } public String getState() { diff --git a/plugins/network-elements/bigswitch-vns/src/com/cloud/network/resource/BigSwitchVnsResource.java b/plugins/network-elements/bigswitch-vns/src/com/cloud/network/resource/BigSwitchVnsResource.java index bee3f00c5f1..223972e2edc 100644 --- a/plugins/network-elements/bigswitch-vns/src/com/cloud/network/resource/BigSwitchVnsResource.java +++ b/plugins/network-elements/bigswitch-vns/src/com/cloud/network/resource/BigSwitchVnsResource.java @@ -187,7 +187,7 @@ public class BigSwitchVnsResource extends ManagerBase implements ServerResource private Answer executeRequest(CreateVnsNetworkCommand cmd, int numRetries) { NetworkData network = new NetworkData(); - network.getNetwork().setTenant_id(cmd.getTenantUuid()); + network.getNetwork().setTenantId(cmd.getTenantUuid()); network.getNetwork().setUuid(cmd.getNetworkUuid()); network.getNetwork().setDisplay_name(truncate("vns-cloudstack-" + cmd.getName(), 64)); network.getNetwork().setVlan(cmd.getVlan()); @@ -222,7 +222,7 @@ public class BigSwitchVnsResource extends ManagerBase implements ServerResource PortData port = new PortData(); port.getPort().setId(cmd.getPortUuid()); port.getPort().setName(cmd.getPortName()); - port.getPort().setTenant_id(cmd.getTenantUuid()); + port.getPort().setTenantId(cmd.getTenantUuid()); try { _bigswitchVnsApi.createPort(cmd.getNetworkUuid(), port); @@ -270,7 +270,7 @@ public class BigSwitchVnsResource extends ManagerBase implements ServerResource PortData port = new PortData(); port.getPort().setId(cmd.getPortUuid()); port.getPort().setName(cmd.getPortName()); - port.getPort().setTenant_id(cmd.getTenantUuid()); + port.getPort().setTenantId(cmd.getTenantUuid()); try { _bigswitchVnsApi.modifyPort(cmd.getNetworkUuid(), port); diff --git a/plugins/network-elements/cisco-vnmc/src/com/cloud/agent/api/ConfigureNexusVsmForAsaCommand.java b/plugins/network-elements/cisco-vnmc/src/com/cloud/agent/api/ConfigureNexusVsmForAsaCommand.java index 2994982534b..fba9942cda9 100755 --- a/plugins/network-elements/cisco-vnmc/src/com/cloud/agent/api/ConfigureNexusVsmForAsaCommand.java +++ b/plugins/network-elements/cisco-vnmc/src/com/cloud/agent/api/ConfigureNexusVsmForAsaCommand.java @@ -51,47 +51,47 @@ public class ConfigureNexusVsmForAsaCommand extends Command { return _vlanId; } - public void setVlanId(long _vlanId) { - this._vlanId = _vlanId; + public void setVlanId(long vlanId) { + this._vlanId = vlanId; } public String getIpAddress() { return _ipAddress; } - public void setIpAddress(String _ipAddress) { - this._ipAddress = _ipAddress; + public void setIpAddress(String ipAddress) { + this._ipAddress = ipAddress; } public String getVsmUsername() { return _vsmUsername; } - public void setVsmUsername(String _vsmUsername) { - this._vsmUsername = _vsmUsername; + public void setVsmUsername(String vsmUsername) { + this._vsmUsername = vsmUsername; } public String getVsmPassword() { return _vsmPassword; } - public void setVsmPassword(String _vsmPassword) { - this._vsmPassword = _vsmPassword; + public void setVsmPassword(String vsmPassword) { + this._vsmPassword = vsmPassword; } public String getVsmIp() { return _vsmIp; } - public void setVsmIp(String _vsmIp) { - this._vsmIp = _vsmIp; + public void setVsmIp(String vsmIp) { + this._vsmIp = vsmIp; } public String getAsaInPortProfile() { return _asaInPortProfile; } - public void setAsaInPortProfile(String _asaInPortProfile) { - this._asaInPortProfile = _asaInPortProfile; + public void setAsaInPortProfile(String asaInPortProfile) { + this._asaInPortProfile = asaInPortProfile; } } diff --git a/plugins/network-elements/cisco-vnmc/src/com/cloud/agent/api/CreateLogicalEdgeFirewallCommand.java b/plugins/network-elements/cisco-vnmc/src/com/cloud/agent/api/CreateLogicalEdgeFirewallCommand.java index 166323d7f60..89e411bddaa 100755 --- a/plugins/network-elements/cisco-vnmc/src/com/cloud/agent/api/CreateLogicalEdgeFirewallCommand.java +++ b/plugins/network-elements/cisco-vnmc/src/com/cloud/agent/api/CreateLogicalEdgeFirewallCommand.java @@ -27,7 +27,7 @@ public class CreateLogicalEdgeFirewallCommand extends Command { private String _publicIp; private String _internalIp; private String _publicSubnet; - private String _internalSubnet; + private String internalSubnet; private List _publicGateways; public CreateLogicalEdgeFirewallCommand(long vlanId, String publicIp, String internalIp, String publicSubnet, String internalSubnet) { @@ -78,11 +78,11 @@ public class CreateLogicalEdgeFirewallCommand extends Command { } public String getInternalSubnet() { - return _internalSubnet; + return internalSubnet; } - public void setInternalSubnet(String _internalSubnet) { - this._internalSubnet = _internalSubnet; + public void setInternalSubnet(String internalSubnet) { + this.internalSubnet = internalSubnet; } public List getPublicGateways() { diff --git a/plugins/network-elements/cisco-vnmc/src/com/cloud/network/cisco/CiscoVnmcConnectionImpl.java b/plugins/network-elements/cisco-vnmc/src/com/cloud/network/cisco/CiscoVnmcConnectionImpl.java index abdf00ea014..cb34b7293dd 100644 --- a/plugins/network-elements/cisco-vnmc/src/com/cloud/network/cisco/CiscoVnmcConnectionImpl.java +++ b/plugins/network-elements/cisco-vnmc/src/com/cloud/network/cisco/CiscoVnmcConnectionImpl.java @@ -41,12 +41,12 @@ import com.cloud.utils.script.Script; public class CiscoVnmcConnectionImpl implements CiscoVnmcConnection { - private String _ip; - private String _username; - private String _password; + private final String _ip; + private final String _username; + private final String _password; private String _cookie; - private final Logger s_logger = Logger.getLogger(CiscoVnmcConnectionImpl.class); + private static final Logger s_logger = Logger.getLogger(CiscoVnmcConnectionImpl.class); private enum VnmcXml { LOGIN("login.xml", "mgmt-controller"), @@ -108,13 +108,12 @@ public class CiscoVnmcConnectionImpl implements CiscoVnmcConnection { ASSIGN_ASA1000V("assoc-asa1000v.xml", "resource-mgr"), UNASSIGN_ASA1000V("disassoc-asa1000v.xml", "resource-mgr"); - private String scriptsDir = "scripts/network/cisco"; + private final String scriptsDir = "scripts/network/cisco"; private String xml; private String service; - private final Logger s_logger = Logger.getLogger(CiscoVnmcConnectionImpl.class); private VnmcXml(String filename, String service) { - this.xml = getXml(filename); + xml = getXml(filename); this.service = service; } @@ -153,9 +152,9 @@ public class CiscoVnmcConnectionImpl implements CiscoVnmcConnection { } public CiscoVnmcConnectionImpl(String hostIp, String userName, String password) { - this._ip = hostIp; - this._username = userName; - this._password = password; + _ip = hostIp; + _username = userName; + _password = password; } diff --git a/plugins/network-elements/cisco-vnmc/src/com/cloud/network/element/CiscoVnmcElement.java b/plugins/network-elements/cisco-vnmc/src/com/cloud/network/element/CiscoVnmcElement.java index e8b6aa213fe..03fac266700 100644 --- a/plugins/network-elements/cisco-vnmc/src/com/cloud/network/element/CiscoVnmcElement.java +++ b/plugins/network-elements/cisco-vnmc/src/com/cloud/network/element/CiscoVnmcElement.java @@ -27,6 +27,7 @@ import java.util.UUID; import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import javax.persistence.EntityExistsException; import org.apache.log4j.Logger; @@ -847,8 +848,12 @@ public class CiscoVnmcElement extends AdapterBase implements SourceNatServicePro throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId); } - ciscoAsa1000vResource = new CiscoAsa1000vDeviceVO(physicalNetworkId, cmd.getManagementIp(), cmd.getInPortProfile(), cmd.getClusterId()); - _ciscoAsa1000vDao.persist((CiscoAsa1000vDeviceVO)ciscoAsa1000vResource); + ciscoAsa1000vResource = new CiscoAsa1000vDeviceVO(physicalNetworkId, cmd.getManagementIp().trim(), cmd.getInPortProfile(), cmd.getClusterId()); + try { + _ciscoAsa1000vDao.persist((CiscoAsa1000vDeviceVO)ciscoAsa1000vResource); + } catch (EntityExistsException e) { + throw new InvalidParameterValueException("An ASA 1000v appliance already exists with same configuration"); + } return ciscoAsa1000vResource; } diff --git a/plugins/network-elements/cisco-vnmc/src/com/cloud/network/element/CiscoVnmcElementService.java b/plugins/network-elements/cisco-vnmc/src/com/cloud/network/element/CiscoVnmcElementService.java index 12f3ea55ad1..8388bb89bb5 100644 --- a/plugins/network-elements/cisco-vnmc/src/com/cloud/network/element/CiscoVnmcElementService.java +++ b/plugins/network-elements/cisco-vnmc/src/com/cloud/network/element/CiscoVnmcElementService.java @@ -32,7 +32,7 @@ public interface CiscoVnmcElementService extends PluggableService { public CiscoVnmcController addCiscoVnmcResource(AddCiscoVnmcResourceCmd cmd); - public CiscoVnmcResourceResponse createCiscoVnmcResourceResponse(CiscoVnmcController CiscoVnmcResourceVO); + public CiscoVnmcResourceResponse createCiscoVnmcResourceResponse(CiscoVnmcController ciscoVnmcResourceVO); boolean deleteCiscoVnmcResource(DeleteCiscoVnmcResourceCmd cmd); diff --git a/plugins/network-elements/cisco-vnmc/src/com/cloud/network/resource/CiscoVnmcResource.java b/plugins/network-elements/cisco-vnmc/src/com/cloud/network/resource/CiscoVnmcResource.java index aad9c90e524..ed75871965a 100644 --- a/plugins/network-elements/cisco-vnmc/src/com/cloud/network/resource/CiscoVnmcResource.java +++ b/plugins/network-elements/cisco-vnmc/src/com/cloud/network/resource/CiscoVnmcResource.java @@ -78,10 +78,10 @@ public class CiscoVnmcResource implements ServerResource { private CiscoVnmcConnectionImpl _connection; public void setConnection(CiscoVnmcConnectionImpl connection) { - this._connection = connection; + _connection = connection; } - private final Logger s_logger = Logger.getLogger(CiscoVnmcResource.class); + private static final Logger s_logger = Logger.getLogger(CiscoVnmcResource.class); @Override public Answer executeRequest(Command cmd) { diff --git a/plugins/network-elements/dns-notifier/resources/components-example.xml b/plugins/network-elements/dns-notifier/resources/components-example.xml index 418835a299f..5977387a28b 100755 --- a/plugins/network-elements/dns-notifier/resources/components-example.xml +++ b/plugins/network-elements/dns-notifier/resources/components-example.xml @@ -185,7 +185,6 @@ under the License. - diff --git a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java index 15333304b1e..6dd0f8a3f93 100644 --- a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java +++ b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java @@ -34,14 +34,14 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; -import org.apache.log4j.Logger; -import org.springframework.stereotype.Component; - import org.apache.cloudstack.api.command.user.loadbalancer.CreateLoadBalancerRuleCmd; +import org.apache.cloudstack.config.ApiServiceConfiguration; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.managed.context.ManagedContextRunnable; +import org.apache.log4j.Logger; +import org.springframework.stereotype.Component; import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; @@ -52,7 +52,6 @@ import com.cloud.agent.api.routing.LoadBalancerConfigCommand; import com.cloud.agent.api.routing.NetworkElementCommand; import com.cloud.agent.api.to.LoadBalancerTO; import com.cloud.agent.manager.Commands; -import com.cloud.cluster.ClusterManager; import com.cloud.configuration.Config; import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter.NetworkType; @@ -205,8 +204,8 @@ public class ElasticLoadBalancerManagerImpl extends ManagerBase implements Elast NicDao _nicDao; String _instance; - static final private String _elbVmNamePrefix = "l"; - static final private String _systemVmType = "elbvm"; + static final private String ElbVmNamePrefix = "l"; + static final private String SystemVmType = "elbvm"; boolean _enabled; TrafficType _frontendTrafficType = TrafficType.Guest; @@ -496,7 +495,7 @@ public class ElasticLoadBalancerManagerImpl extends ManagerBase implements Elast } elbVm = - new DomainRouterVO(id, _elasticLbVmOffering.getId(), vrProvider.getId(), VirtualMachineName.getSystemVmName(id, _instance, _elbVmNamePrefix), + new DomainRouterVO(id, _elasticLbVmOffering.getId(), vrProvider.getId(), VirtualMachineName.getSystemVmName(id, _instance, ElbVmNamePrefix), template.getId(), template.getHypervisorType(), template.getGuestOSId(), owner.getDomainId(), owner.getId(), false, 0, false, RedundantState.UNKNOWN, _elasticLbVmOffering.getOfferHA(), false, VirtualMachine.Type.ElasticLoadBalancerVm, null); elbVm.setRole(Role.LB); @@ -779,7 +778,7 @@ public class ElasticLoadBalancerManagerImpl extends ManagerBase implements Elast DataCenter dc = dest.getDataCenter(); StringBuilder buf = profile.getBootArgsBuilder(); - buf.append(" template=domP type=" + _systemVmType); + buf.append(" template=domP type=" + SystemVmType); buf.append(" name=").append(profile.getHostName()); NicProfile controlNic = null; String defaultDns1 = null; @@ -802,7 +801,7 @@ public class ElasticLoadBalancerManagerImpl extends ManagerBase implements Elast if (s_logger.isInfoEnabled()) { s_logger.info("Check if we need to add management server explicit route to ELB vm. pod cidr: " + dest.getPod().getCidrAddress() + "/" + dest.getPod().getCidrSize() + ", pod gateway: " + dest.getPod().getGateway() + ", management host: " + - ClusterManager.ManagementHostIPAdr.value()); + ApiServiceConfiguration.ManagementHostIPAdr.value()); } if (s_logger.isDebugEnabled()) { diff --git a/plugins/network-elements/f5/pom.xml b/plugins/network-elements/f5/pom.xml index d1a8cda2d17..a2c7b6b46d9 100644 --- a/plugins/network-elements/f5/pom.xml +++ b/plugins/network-elements/f5/pom.xml @@ -36,5 +36,10 @@ org.apache.axis axis + + commons-discovery + commons-discovery + 0.5 + diff --git a/plugins/network-elements/f5/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java b/plugins/network-elements/f5/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java index 1a591e1da57..1cd6851b582 100644 --- a/plugins/network-elements/f5/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java +++ b/plugins/network-elements/f5/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java @@ -322,7 +322,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan String deviceType = NetworkDevice.F5BigIpLoadBalancer.getName(); lbDeviceVO = addExternalLoadBalancer(pNetwork.getId(), cmd.getUrl(), cmd.getUsername(), cmd.getPassword(), - deviceType, new F5BigIpResource(), false, false, null, null); + deviceType, new F5BigIpResource(), false, false, null, null); if (lbDeviceVO != null) { lbHost = _hostDao.findById(lbDeviceVO.getHostId()); @@ -376,7 +376,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan } return addExternalLoadBalancer(cmd.getPhysicalNetworkId(), cmd.getUrl(), cmd.getUsername(), cmd.getPassword(), - deviceName, new F5BigIpResource(), false, false, null, + deviceName, new F5BigIpResource(), false, false, null, null); } diff --git a/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java b/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java index 4ceb810525b..b2030a93f60 100644 --- a/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java +++ b/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java @@ -118,7 +118,7 @@ import com.cloud.vm.dao.NicDao; @Local(value = {InternalLoadBalancerVMManager.class, InternalLoadBalancerVMService.class}) public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements InternalLoadBalancerVMManager, InternalLoadBalancerVMService, VirtualMachineGuru { private static final Logger s_logger = Logger.getLogger(InternalLoadBalancerVMManagerImpl.class); - static final private String _internalLbVmNamePrefix = "b"; + static final private String InternalLbVmNamePrefix = "b"; private String _instance; private String _mgmtHost; @@ -759,7 +759,7 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In } internalLbVm = - new DomainRouterVO(id, routerOffering.getId(), internalLbProviderId, VirtualMachineName.getSystemVmName(id, _instance, _internalLbVmNamePrefix), + new DomainRouterVO(id, routerOffering.getId(), internalLbProviderId, VirtualMachineName.getSystemVmName(id, _instance, InternalLbVmNamePrefix), template.getId(), template.getHypervisorType(), template.getGuestOSId(), owner.getDomainId(), owner.getId(), false, 0, false, RedundantState.UNKNOWN, false, false, VirtualMachine.Type.InternalLoadBalancerVm, vpcId); internalLbVm.setRole(Role.INTERNAL_LB_VM); diff --git a/plugins/network-elements/juniper-contrail/pom.xml b/plugins/network-elements/juniper-contrail/pom.xml index 7b377a0cb59..8c6877dfb90 100644 --- a/plugins/network-elements/juniper-contrail/pom.xml +++ b/plugins/network-elements/juniper-contrail/pom.xml @@ -82,10 +82,15 @@ cloud-framework-events ${project.version} + + org.apache.cloudstack + cloud-framework-spring-lifecycle + ${project.version} + test + com.google.guava guava - ${cs.guava.version} net.juniper.contrail @@ -95,7 +100,6 @@ mysql mysql-connector-java - ${cs.mysql.version} provided diff --git a/plugins/network-elements/juniper-contrail/resources/META-INF/cloudstack/contrail/module.properties b/plugins/network-elements/juniper-contrail/resources/META-INF/cloudstack/contrail/module.properties new file mode 100644 index 00000000000..ced0f3addc7 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/resources/META-INF/cloudstack/contrail/module.properties @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +name=contrail +parent=network \ No newline at end of file diff --git a/plugins/network-elements/juniper-contrail/resources/META-INF/cloudstack/contrail/spring-contrail-context.xml b/plugins/network-elements/juniper-contrail/resources/META-INF/cloudstack/contrail/spring-contrail-context.xml new file mode 100644 index 00000000000..4614af79a4b --- /dev/null +++ b/plugins/network-elements/juniper-contrail/resources/META-INF/cloudstack/contrail/spring-contrail-context.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailElementImpl.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailElementImpl.java index e6a06969ecf..05723b04447 100644 --- a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailElementImpl.java +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailElementImpl.java @@ -26,7 +26,6 @@ import java.util.Set; import javax.ejb.Local; import javax.inject.Inject; -import javax.naming.ConfigurationException; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; @@ -42,6 +41,10 @@ import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.IpAddress; +import com.cloud.network.dao.NetworkDao; +import com.cloud.network.dao.NetworkVO; +import com.cloud.resource.ResourceManager; + import com.cloud.network.Network; import com.cloud.network.Network.Capability; import com.cloud.network.Network.Provider; @@ -51,6 +54,8 @@ import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.network.PublicIpAddress; import com.cloud.network.element.IpDeployer; import com.cloud.network.element.StaticNatServiceProvider; +import com.cloud.network.element.SourceNatServiceProvider; +import com.cloud.network.element.DhcpServiceProvider; import com.cloud.network.rules.StaticNat; import com.cloud.offering.NetworkOffering; import com.cloud.utils.component.AdapterBase; @@ -60,13 +65,22 @@ import com.cloud.vm.ReservationContext; import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachineProfile; import com.cloud.vm.dao.NicDao; +import com.cloud.server.ConfigurationServer; +import com.cloud.server.ConfigurationServerImpl; @Component -@Local(value = {ContrailElement.class, StaticNatServiceProvider.class}) -public class ContrailElementImpl extends AdapterBase implements ContrailElement, IpDeployer, StaticNatServiceProvider { +@Local(value = {ContrailElement.class, StaticNatServiceProvider.class, IpDeployer.class, SourceNatServiceProvider.class}) - private static final Map> _capabilities = InitCapabilities(); +public class ContrailElementImpl extends AdapterBase + implements ContrailElement, StaticNatServiceProvider, IpDeployer, SourceNatServiceProvider, DhcpServiceProvider { + private final Map> _capabilities = InitCapabilities(); + @Inject + ResourceManager _resourceMgr; + @Inject + ConfigurationServer _configServer; + @Inject + NetworkDao _networksDao; @Inject ContrailManager _manager; @Inject @@ -75,12 +89,6 @@ public class ContrailElementImpl extends AdapterBase implements ContrailElement, ServerDBSync _dbSync; private static final Logger s_logger = Logger.getLogger(ContrailElement.class); - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - s_logger.debug("configure"); - return true; - } - // PluggableService @Override public List> getCommands() { @@ -92,7 +100,7 @@ public class ContrailElementImpl extends AdapterBase implements ContrailElement, // NetworkElement API @Override public Provider getProvider() { - return Provider.JuniperContrail; + return Provider.JuniperContrailRouter; } private static Map> InitCapabilities() { @@ -261,8 +269,34 @@ public class ContrailElementImpl extends AdapterBase implements ContrailElement, @Override public boolean isReady(PhysicalNetworkServiceProvider provider) { - return true; - } + Map serviceMap = ((ConfigurationServerImpl)_configServer).getServicesAndProvidersForNetwork( _manager.getRouterOffering().getId()); + List types = new ArrayList(); + types.add(TrafficType.Control); + types.add(TrafficType.Management); + types.add(TrafficType.Storage); + List systemNets = _manager.findSystemNetworks(types); + if (systemNets != null && !systemNets.isEmpty()) { + for (NetworkVO net: systemNets) { + s_logger.debug("update system network service: " + net.getName() + "; service provider: " + serviceMap); + _networksDao.update(net.getId(), net, serviceMap); + } + } else { + s_logger.debug("no system networks created yet"); + } + serviceMap = ((ConfigurationServerImpl)_configServer).getServicesAndProvidersForNetwork( _manager.getPublicRouterOffering().getId()); + types = new ArrayList(); + types.add(TrafficType.Public); + systemNets = _manager.findSystemNetworks(types); + if (systemNets != null && !systemNets.isEmpty()) { + for (NetworkVO net: systemNets) { + s_logger.debug("update system network service: " + net.getName() + "; service provider: " + serviceMap); + _networksDao.update(net.getId(), net, serviceMap); + } + } else { + s_logger.debug("no system networks created yet"); + } + return true; + } @Override public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException, @@ -320,4 +354,28 @@ public class ContrailElementImpl extends AdapterBase implements ContrailElement, } return false; } + + @Override + public boolean addDhcpEntry(Network network, NicProfile nic, + VirtualMachineProfile vm, + DeployDestination dest, ReservationContext context) + throws ConcurrentOperationException, InsufficientCapacityException, + ResourceUnavailableException { + return false; + } + + @Override + public boolean configDhcpSupportForSubnet(Network network, NicProfile nic, + VirtualMachineProfile vm, + DeployDestination dest, ReservationContext context) + throws ConcurrentOperationException, InsufficientCapacityException, + ResourceUnavailableException { + return false; + } + + @Override + public boolean removeDhcpSupportForSubnet(Network network) + throws ResourceUnavailableException { + return false; + } } diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailGuru.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailGuru.java index ea52be9d912..704dedd4a3c 100644 --- a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailGuru.java +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailGuru.java @@ -18,14 +18,15 @@ package org.apache.cloudstack.network.contrail.management; import java.io.IOException; +import java.net.URI; import javax.inject.Inject; +import javax.ejb.Local; import net.juniper.contrail.api.types.MacAddressesType; import net.juniper.contrail.api.types.VirtualMachineInterface; import org.apache.log4j.Logger; -import org.springframework.stereotype.Component; import org.apache.cloudstack.network.contrail.model.InstanceIpModel; import org.apache.cloudstack.network.contrail.model.VMInterfaceModel; @@ -37,6 +38,9 @@ import com.cloud.deploy.DeploymentPlan; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InsufficientVirtualNetworkCapcityException; +import com.cloud.dc.DataCenter; +import com.cloud.dc.DataCenter.NetworkType; +import com.cloud.dc.dao.DataCenterDao; import com.cloud.network.Network; import com.cloud.network.Network.State; import com.cloud.network.NetworkProfile; @@ -47,6 +51,9 @@ import com.cloud.network.Networks.TrafficType; import com.cloud.network.dao.NetworkDao; import com.cloud.network.dao.NetworkVO; import com.cloud.network.guru.NetworkGuru; +import com.cloud.network.PhysicalNetwork; +import com.cloud.network.dao.PhysicalNetworkDao; +import com.cloud.network.dao.PhysicalNetworkVO; import com.cloud.offering.NetworkOffering; import com.cloud.user.Account; import com.cloud.utils.component.AdapterBase; @@ -55,12 +62,15 @@ import com.cloud.utils.net.NetUtils; import com.cloud.vm.Nic.ReservationStrategy; import com.cloud.vm.NicProfile; import com.cloud.vm.NicVO; +import com.cloud.network.dao.IPAddressDao; +import com.cloud.user.AccountManager; +import com.cloud.network.IpAddressManager; import com.cloud.vm.ReservationContext; import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachineProfile; import com.cloud.vm.dao.NicDao; -@Component +@Local(value = {NetworkGuru.class}) public class ContrailGuru extends AdapterBase implements NetworkGuru { @Inject NetworkDao _networkDao; @@ -68,12 +78,29 @@ public class ContrailGuru extends AdapterBase implements NetworkGuru { ContrailManager _manager; @Inject NicDao _nicDao; + @Inject + IPAddressDao _ipAddressDao; + @Inject + AccountManager _accountMgr; + @Inject + IpAddressManager _ipAddrMgr; + @Inject + PhysicalNetworkDao _physicalNetworkDao; + @Inject + DataCenterDao _dcDao; private static final Logger s_logger = Logger.getLogger(ContrailGuru.class); - private static final TrafficType[] _trafficTypes = {TrafficType.Guest}; + private static final TrafficType[] TrafficTypes = {TrafficType.Guest}; - private boolean canHandle(NetworkOffering offering) { - return (offering.getName().equals(ContrailManager.offeringName)); + private boolean canHandle(NetworkOffering offering, NetworkType networkType, PhysicalNetwork physicalNetwork) { + if (networkType == NetworkType.Advanced + && offering.getId() == _manager.getRouterOffering().getId() + && isMyTrafficType(offering.getTrafficType()) + && offering.getGuestType() == Network.GuestType.Isolated + && physicalNetwork.getIsolationMethods().contains("L3VPN")) + return true; + + return false; } @Override @@ -83,7 +110,11 @@ public class ContrailGuru extends AdapterBase implements NetworkGuru { @Override public Network design(NetworkOffering offering, DeploymentPlan plan, Network userSpecified, Account owner) { - if (!canHandle(offering)) { + // Check of the isolation type of the related physical network is L3VPN + PhysicalNetworkVO physnet = _physicalNetworkDao.findById(plan.getPhysicalNetworkId()); + DataCenter dc = _dcDao.findById(plan.getDataCenterId()); + if (!canHandle(offering, dc.getNetworkType(),physnet)) { + s_logger.debug("Refusing to design this network"); return null; } NetworkVO network = @@ -138,6 +169,13 @@ public class ContrailGuru extends AdapterBase implements NetworkGuru { } profile.setStrategy(ReservationStrategy.Start); + URI broadcastUri = null; + try { + broadcastUri = new URI("vlan://untagged"); + } catch (Exception e) { + s_logger.warn("unable to instantiate broadcast URI: " + e); + } + profile.setBroadcastUri(broadcastUri); return profile; } @@ -215,7 +253,9 @@ public class ContrailGuru extends AdapterBase implements NetworkGuru { if (nic.getIp4Address() == null) { s_logger.debug("Allocated IP address " + ipModel.getAddress()); nic.setIp4Address(ipModel.getAddress()); - nic.setNetmask(NetUtils.cidr2Netmask(network.getCidr())); + if (network.getCidr() != null) { + nic.setNetmask(NetUtils.cidr2Netmask(network.getCidr())); + } nic.setGateway(network.getGateway()); nic.setFormat(AddressFormat.Ip4); } @@ -282,6 +322,7 @@ public class ContrailGuru extends AdapterBase implements NetworkGuru { return; } try { + _manager.getDatabase().getVirtualNetworks().remove(vnModel); vnModel.delete(_manager.getModelController()); } catch (IOException e) { s_logger.warn("virtual-network delete", e); @@ -303,12 +344,12 @@ public class ContrailGuru extends AdapterBase implements NetworkGuru { @Override public TrafficType[] getSupportedTrafficType() { - return _trafficTypes; + return TrafficTypes; } @Override public boolean isMyTrafficType(TrafficType type) { - for (TrafficType t : _trafficTypes) { + for (TrafficType t : TrafficTypes) { if (t == type) { return true; } diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailManager.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailManager.java index 98b02b8f96c..6853d1efd55 100644 --- a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailManager.java +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailManager.java @@ -22,6 +22,7 @@ import java.util.List; import net.juniper.contrail.api.ApiConnector; import net.juniper.contrail.api.types.FloatingIp; +import net.juniper.contrail.api.types.NetworkPolicy; import net.juniper.contrail.api.types.VirtualNetwork; import org.apache.cloudstack.network.contrail.model.ModelController; @@ -36,16 +37,20 @@ import com.cloud.network.dao.NetworkVO; import com.cloud.network.dao.PhysicalNetworkVO; import com.cloud.offering.NetworkOffering; import com.cloud.projects.ProjectVO; +import com.cloud.network.vpc.NetworkACLVO; public interface ContrailManager { - public static final String offeringName = "Juniper Contrail offering"; - public static final String offeringDisplayText = "Juniper Contrail network offering"; + public static final String routerOfferingName = "Juniper Contrail Network Offering"; + public static final String routerOfferingDisplayText = "Juniper Contrail Network Offering"; + public static final String routerPublicOfferingName = "Juniper Contrail Public Network Offering"; + public static final String routerPublicOfferingDisplayText = "Juniper Contrail Public Network Offering"; public static final int DB_SYNC_INTERVAL_DEFAULT = 600000; public static final String VNC_ROOT_DOMAIN = "default-domain"; public static final String VNC_DEFAULT_PROJECT = "default-project"; public static final String managementNetworkName = "ip-fabric"; - public NetworkOffering getOffering(); + public NetworkOffering getRouterOffering(); + public NetworkOffering getPublicRouterOffering(); public void syncNetworkDB(short syncMode) throws IOException; @@ -61,7 +66,7 @@ public interface ContrailManager { public void findInfrastructureNetworks(PhysicalNetworkVO phys, List dbList); - public String getPhysicalNetworkName(PhysicalNetworkVO phys_net); + public String getPhysicalNetworkName(PhysicalNetworkVO physNet); public String getCanonicalName(Network net); @@ -81,6 +86,8 @@ public interface ContrailManager { public net.juniper.contrail.api.types.Project getVncProject(long domainId, long accountId) throws IOException; + public net.juniper.contrail.api.types.Project getDefaultVncProject() throws IOException; + public boolean isSystemRootDomain(net.juniper.contrail.api.types.Domain vnc); public boolean isSystemRootDomain(DomainVO domain); @@ -93,9 +100,9 @@ public interface ContrailManager { public boolean isSystemDefaultNetwork(NetworkVO dbNet); - public String getVifNameByVmName(String vm_name, Integer device_id); + public String getVifNameByVmName(String vmName, Integer deviceId); - public String getVifNameByVmUuid(String vm_uuid, Integer device_id); + public String getVifNameByVmUuid(String vmUuid, Integer deviceId); public ApiConnector getApiConnector(); @@ -103,9 +110,13 @@ public interface ContrailManager { public ModelController getModelController(); - public List findJuniperManagedNetworks(List types); + public List findManagedNetworks(List types); - public List findJuniperManagedPublicIps(); + public List findSystemNetworks(List types); + + public List findManagedPublicIps(); + + public List findManagedACLs(); public VirtualNetwork findDefaultVirtualNetwork(TrafficType trafficType) throws IOException; @@ -113,9 +124,9 @@ public interface ContrailManager { public VirtualNetworkModel lookupPublicNetworkModel(); - public void createPublicNetworks(); - public boolean createFloatingIp(PublicIpAddress ip); public boolean deleteFloatingIp(PublicIpAddress ip); + + public boolean isSystemDefaultNetworkPolicy(NetworkPolicy policy); } diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailManagerImpl.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailManagerImpl.java index abf2dd09b24..ef76e4cee49 100644 --- a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailManagerImpl.java +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailManagerImpl.java @@ -21,7 +21,6 @@ import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; @@ -34,6 +33,7 @@ import java.util.TimerTask; import javax.inject.Inject; import javax.naming.ConfigurationException; +import javax.ejb.Local; import net.juniper.contrail.api.ApiConnector; import net.juniper.contrail.api.ApiConnectorFactory; @@ -41,11 +41,11 @@ import net.juniper.contrail.api.ApiPropertyBase; import net.juniper.contrail.api.ObjectReference; import net.juniper.contrail.api.types.FloatingIp; import net.juniper.contrail.api.types.FloatingIpPool; +import net.juniper.contrail.api.types.NetworkPolicy; import net.juniper.contrail.api.types.VirtualNetwork; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; -import org.springframework.stereotype.Component; import com.google.common.collect.ImmutableList; @@ -56,13 +56,13 @@ import org.apache.cloudstack.network.contrail.model.VirtualNetworkModel; import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.ConfigurationService; +import com.cloud.server.ConfigurationServer; import com.cloud.dc.DataCenter; import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.VlanDao; import com.cloud.domain.Domain; import com.cloud.domain.DomainVO; import com.cloud.domain.dao.DomainDao; -import com.cloud.exception.InternalErrorException; import com.cloud.network.Network; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; @@ -75,17 +75,17 @@ import com.cloud.network.dao.NetworkVO; import com.cloud.network.dao.PhysicalNetworkDao; import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; import com.cloud.network.dao.PhysicalNetworkVO; -import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering.Availability; -import com.cloud.offering.NetworkOffering.State; +import com.cloud.offering.NetworkOffering; import com.cloud.offerings.NetworkOfferingVO; import com.cloud.offerings.dao.NetworkOfferingDao; import com.cloud.projects.ProjectVO; +import com.cloud.network.vpc.dao.NetworkACLDao; +import com.cloud.network.vpc.NetworkACLVO; import com.cloud.projects.dao.ProjectDao; import com.cloud.user.Account; import com.cloud.user.dao.AccountDao; import com.cloud.utils.PropertiesUtil; -import com.cloud.utils.component.ComponentLifecycle; import com.cloud.utils.component.ManagerBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; @@ -95,13 +95,14 @@ import com.cloud.vm.dao.NicDao; import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.VMInstanceDao; -@Component +@Local(value = { ContrailManager.class}) public class ContrailManagerImpl extends ManagerBase implements ContrailManager { @Inject public ConfigurationService _configService; @Inject + ConfigurationServer _configServer; + @Inject NetworkOfferingDao _networkOfferingDao; - @Inject DomainDao _domainDao; @Inject @@ -130,12 +131,16 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager VlanDao _vlanDao; @Inject UserVmDao _vmDao; + @Inject + NetworkACLDao _networkAclDao; private static final Logger s_logger = Logger.getLogger(ContrailManager.class); private ApiConnector _api; private NetworkOffering _offering; + private NetworkOffering _routerOffering; + private NetworkOffering _routerPublicOffering; private Timer _dbSyncTimer; private int _dbSyncInterval = DB_SYNC_INTERVAL_DEFAULT; private final String configuration = "contrail.properties"; @@ -143,7 +148,6 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager private ModelController _controller; ContrailManagerImpl() { - setRunLevel(ComponentLifecycle.RUN_LEVEL_COMPONENT); _database = new ModelDatabase(); } @@ -171,20 +175,55 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager return _database; } - private NetworkOffering LocateOffering() { - List offerList = _configService.listNetworkOfferings(TrafficType.Guest, false); - for (NetworkOffering offer : offerList) { + private NetworkOffering LocatePublicNetworkOffering(String offeringName, + String offeringDisplayText, Provider provider) { + List offerList = _configService.listNetworkOfferings(TrafficType.Public, false); + for (NetworkOffering offer: offerList) { if (offer.getName().equals(offeringName)) { - if (offer.getState() != State.Enabled) { + if (offer.getState() != NetworkOffering.State.Enabled) { return EnableNetworkOffering(offer.getId()); } return offer; } } Map> serviceProviderMap = new HashMap>(); - // Map> serviceCapabilityMap = new HashMap>(); Set providerSet = new HashSet(); - providerSet.add(Provider.JuniperContrail); + providerSet.add(provider); + final Service[] services = { + Service.Connectivity, + Service.Dhcp, + Service.NetworkACL, + Service.StaticNat, + Service.SourceNat + }; + for (Service svc: services) { + serviceProviderMap.put(svc, providerSet); + } + ConfigurationManager configMgr = (ConfigurationManager) _configService; + NetworkOfferingVO voffer = configMgr.createNetworkOffering(offeringName, offeringDisplayText, + TrafficType.Public, null, true, Availability.Optional, null, serviceProviderMap, true, + Network.GuestType.Shared, false, null, false, null, true, false, null, true, null, false); + + voffer.setState(NetworkOffering.State.Enabled); + long id = voffer.getId(); + _networkOfferingDao.update(id, voffer); + return _networkOfferingDao.findById(id); + } + + private NetworkOffering LocateNetworkOffering(String offeringName, + String offeringDisplayText, Provider provider) { + List offerList = _configService.listNetworkOfferings(TrafficType.Guest, false); + for (NetworkOffering offer : offerList) { + if (offer.getName().equals(offeringName)) { + if (offer.getState() != NetworkOffering.State.Enabled) { + return EnableNetworkOffering(offer.getId()); + } + return offer; + } + } + Map> serviceProviderMap = new HashMap>(); + Set providerSet = new HashSet(); + providerSet.add(provider); final Service[] services = {Service.Connectivity, Service.Dhcp, Service.NetworkACL, Service.StaticNat, Service.SourceNat}; for (Service svc : services) { serviceProviderMap.put(svc, providerSet); @@ -194,7 +233,7 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager configMgr.createNetworkOffering(offeringName, offeringDisplayText, TrafficType.Guest, null, false, Availability.Optional, null, serviceProviderMap, true, Network.GuestType.Isolated, false, null, false, null, false, true, null, true, null, false); - voffer.setState(State.Enabled); + voffer.setState(NetworkOffering.State.Enabled); long id = voffer.getId(); _networkOfferingDao.update(id, voffer); return _networkOfferingDao.findById(id); @@ -202,7 +241,7 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager private NetworkOffering EnableNetworkOffering(long id) { NetworkOfferingVO offering = _networkOfferingDao.createForUpdate(id); - offering.setState(State.Enabled); + offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(id, offering); return _networkOfferingDao.findById(id); } @@ -211,29 +250,41 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager public boolean configure(String name, Map params) throws ConfigurationException { File configFile = PropertiesUtil.findConfigFile(configuration); - final Properties configProps = new Properties(); try { - configProps.load(new FileInputStream(configFile)); - String value = configProps.getProperty("management.db_sync_interval"); - if (value != null) { - _dbSyncInterval = Integer.valueOf(value); - } - - String hostname = configProps.getProperty("api.hostname"); - String portStr = configProps.getProperty("api.port"); + String hostname = null; int port = 0; - if (portStr != null && portStr.length() > 0) { - port = Integer.parseInt(portStr); + if (configFile == null) { + hostname = "localhost"; + port = 8082; + } else { + final Properties configProps = new Properties(); + configProps.load(new FileInputStream(configFile)); + String value = configProps.getProperty("management.db_sync_interval"); + if (value != null) { + _dbSyncInterval = Integer.valueOf(value); + } + hostname = configProps.getProperty("api.hostname"); + String portStr = configProps.getProperty("api.port"); + if (portStr != null && portStr.length() > 0) { + port = Integer.parseInt(portStr); + } } _api = ApiConnectorFactory.build(hostname, port); } catch (IOException ex) { s_logger.warn("Unable to read " + configuration, ex); throw new ConfigurationException(); + } catch (Exception ex) { + s_logger.debug("Exception in configure: " + ex); + ex.printStackTrace(); + throw new ConfigurationException(); } _controller = new ModelController(this, _api, _vmDao, _networksDao, _nicDao, _vlanDao, _ipAddressDao); - _offering = LocateOffering(); + _routerOffering = LocateNetworkOffering(routerOfferingName, routerOfferingDisplayText, + Provider.JuniperContrailRouter); + _routerPublicOffering = LocatePublicNetworkOffering(routerPublicOfferingName, routerPublicOfferingDisplayText, + Provider.JuniperContrailRouter); _eventHandler.subscribe(); @@ -243,13 +294,18 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager } @Override - public NetworkOffering getOffering() { - return _offering; + public NetworkOffering getPublicRouterOffering() { + return _routerPublicOffering; } @Override - public String getPhysicalNetworkName(PhysicalNetworkVO phys_net) { - String physname = phys_net.getName(); + public NetworkOffering getRouterOffering() { + return _routerOffering; + } + + @Override + public String getPhysicalNetworkName(PhysicalNetworkVO physNet) { + String physname = physNet.getName(); physname = physname.replaceAll("\\s", "").replace("_", ""); return physname; } @@ -340,11 +396,18 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager public net.juniper.contrail.api.types.Project getVncProject(long domainId, long accountId) throws IOException { String projectId = getProjectId(domainId, accountId); if (projectId == null) { - return null; + return getDefaultVncProject(); } return (net.juniper.contrail.api.types.Project)_api.findById(net.juniper.contrail.api.types.Project.class, projectId); } + @Override + public net.juniper.contrail.api.types.Project getDefaultVncProject() throws IOException { + net.juniper.contrail.api.types.Project project = null; + project = (net.juniper.contrail.api.types.Project)_api.findByFQN(net.juniper.contrail.api.types.Project.class, VNC_ROOT_DOMAIN + ":" + VNC_DEFAULT_PROJECT); + return project; + } + @Override public String getFQN(Network net) { // domain, project, name @@ -358,7 +421,7 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager final TrafficType[] ttypes = {TrafficType.Control, // maps to __link_local__ TrafficType.Management, // maps to ip-fabric TrafficType.Public, TrafficType.Storage // maps to ip-fabric - }; + }; for (int i = 0; i < ttypes.length; i++) { List phys_nets; @@ -402,7 +465,7 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager public boolean isManagedPhysicalNetwork(Network network) { List net_list = _physicalNetworkDao.listByZone(network.getDataCenterId()); for (PhysicalNetworkVO phys : net_list) { - if (_physProviderDao.findByServiceProvider(phys.getId(), Network.Provider.JuniperContrail.getName()) != null) { + if (_physProviderDao.findByServiceProvider(phys.getId(), Network.Provider.JuniperContrailRouter.getName()) != null) { return true; } } @@ -427,6 +490,53 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager return _api.findByName(VirtualNetwork.class, fqn); } + @Override + public List findSystemNetworks(List types) { + SearchBuilder searchBuilder = _networksDao.createSearchBuilder(); + searchBuilder.and("trafficType", searchBuilder.entity().getTrafficType(), Op.IN); + SearchCriteria sc = searchBuilder.create(); + if (types == null || types.isEmpty()) { + types = new ArrayList(); + types.add(TrafficType.Control); + types.add(TrafficType.Management); + types.add(TrafficType.Public); + types.add(TrafficType.Storage); + } + sc.setParameters("trafficType", types.toArray()); + List dbNets = _networksDao.search(sc, null); + if (dbNets == null) { + s_logger.debug("no system networks for the given traffic types: " + types.toString()); + dbNets = new ArrayList(); + } + + List phys_list = _physicalNetworkDao.listAll(); + final String provider = Provider.JuniperContrailRouter.getName(); + for (Iterator iter = phys_list.iterator(); iter.hasNext(); ) { + PhysicalNetworkVO phys = iter.next(); + if (_physProviderDao.findByServiceProvider(phys.getId(), provider) != null) { + List infraNets = new ArrayList(); + findInfrastructureNetworks(phys, infraNets); + for (NetworkVO net:infraNets) { + if (types == null || types.isEmpty()) { + if (!dbNets.contains(net)) { + dbNets.add(net); + } + continue; + } + for(TrafficType type:types) { + if (net.getTrafficType() == type) { + if (!dbNets.contains(net)) { + dbNets.add(net); + } + break; + } + } + } + } + } + return dbNets; + } + @Override public VirtualNetwork findDefaultVirtualNetwork(TrafficType trafficType) throws IOException { if (trafficType == TrafficType.Guest || trafficType == TrafficType.Public) { @@ -445,14 +555,17 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager * Returns list of networks managed by Juniper VRouter filtered by traffic types */ @Override - public List findJuniperManagedNetworks(List types) { + public List findManagedNetworks(List types) { SearchBuilder searchBuilder = _networksDao.createSearchBuilder(); searchBuilder.and("trafficType", searchBuilder.entity().getTrafficType(), Op.IN); - searchBuilder.and("networkOfferingId", searchBuilder.entity().getNetworkOfferingId(), Op.EQ); + searchBuilder.and("networkOfferingId", searchBuilder.entity().getNetworkOfferingId(), Op.IN); SearchCriteria sc = searchBuilder.create(); - sc.setParameters("networkOfferingId", getOffering().getId()); + List offerings = new ArrayList(); + offerings.add(getRouterOffering().getId()); + offerings.add(getPublicRouterOffering().getId()); + sc.setParameters("networkOfferingId", offerings.toArray()); if (types == null || types.isEmpty()) { types = new ArrayList(); @@ -471,7 +584,7 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager } List phys_list = _physicalNetworkDao.listAll(); - final String provider = Network.Provider.JuniperContrail.getName(); + final String provider = Network.Provider.JuniperContrailRouter.getName(); for (Iterator iter = phys_list.iterator(); iter.hasNext();) { PhysicalNetworkVO phys = iter.next(); if (_physProviderDao.findByServiceProvider(phys.getId(), provider) != null) { @@ -479,12 +592,16 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager findInfrastructureNetworks(phys, infraNets); for (NetworkVO net : infraNets) { if (types == null || types.isEmpty()) { - dbNets.add(net); + if (!dbNets.contains(net)) { + dbNets.add(net); + } continue; } for (TrafficType type : types) { if (net.getTrafficType() == type) { - dbNets.add(net); + if (!dbNets.contains(net)) { + dbNets.add(net); + } break; } } @@ -494,13 +611,19 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager return dbNets; } + @Override + public List findManagedACLs() { + /* contrail vpc is not yet implemented */ + return null; + } + /* * Returns list of public ip addresses managed by Juniper VRouter */ @Override - public List findJuniperManagedPublicIps() { + public List findManagedPublicIps() { - List dbNets = findJuniperManagedNetworks(null); + List dbNets = findManagedNetworks(null); if (dbNets == null || dbNets.isEmpty()) { s_logger.debug("Juniper managed networks is empty"); @@ -538,7 +661,7 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager types.add(TrafficType.Storage); types.add(TrafficType.Control); - List dbNets = findJuniperManagedNetworks(types); + List dbNets = findManagedNetworks(types); for (NetworkVO net : dbNets) { VirtualNetworkModel vnModel = getDatabase().lookupVirtualNetwork(null, getCanonicalName(net), net.getTrafficType()); @@ -619,16 +742,16 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager } @Override - public String getVifNameByVmName(String vm_name, Integer device_id) { - String vif_name = vm_name + "-" + device_id.toString(); + public String getVifNameByVmName(String vmName, Integer deviceId) { + String vif_name = vmName + "-" + deviceId.toString(); return vif_name; } @Override - public String getVifNameByVmUuid(String vm_uuid, Integer device_id) { - VMInstanceVO vm = _vmInstanceDao.findByUuid(vm_uuid); + public String getVifNameByVmUuid(String vmUuid, Integer deviceId) { + VMInstanceVO vm = _vmInstanceDao.findByUuid(vmUuid); if (vm != null) { - return vm.getInstanceName() + "-" + device_id.toString(); + return vm.getInstanceName() + "-" + deviceId.toString(); } return null; } @@ -647,48 +770,29 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager public VirtualNetworkModel lookupPublicNetworkModel() { List types = new ArrayList(); types.add(TrafficType.Public); - List dbNets = findJuniperManagedNetworks(types); + List dbNets = findManagedNetworks(types); if (dbNets == null) { return null; } NetworkVO net = dbNets.get(0); VirtualNetworkModel vnModel = getDatabase().lookupVirtualNetwork(net.getUuid(), getCanonicalName(net), TrafficType.Public); + if (vnModel == null) { + vnModel = new VirtualNetworkModel(net, net.getUuid(), + getCanonicalName(net), net.getTrafficType()); + vnModel.setProperties(getModelController(), net); + } + try { + if (!vnModel.verify(getModelController())) { + vnModel.update(getModelController()); + } + getDatabase().getVirtualNetworks().add(vnModel); + } catch (Exception ex) { + s_logger.warn("virtual-network update: ", ex); + } return vnModel; } - @Override - public void createPublicNetworks() { - List types = new ArrayList(Arrays.asList(TrafficType.Public)); - List dbNets = findJuniperManagedNetworks(types); - if (dbNets == null) { - return; - } - for (NetworkVO net : dbNets) { - VirtualNetworkModel vnModel = _database.lookupVirtualNetwork(net.getUuid(), getCanonicalName(net), TrafficType.Public); - if (vnModel != null) { - continue; - } - vnModel = new VirtualNetworkModel(net, net.getUuid(), getCanonicalName(net), net.getTrafficType()); - vnModel.build(_controller, net); - try { - vnModel.update(_controller); - } catch (InternalErrorException ex) { - s_logger.warn("virtual-network update", ex); - continue; - } catch (IOException ex) { - s_logger.warn("virtual-network update", ex); - continue; - } - _database.getVirtualNetworks().add(vnModel); - - // Add the Contrail NetworkElement to the Public network. - Map providerMap = new HashMap(); - providerMap.put(Service.Connectivity.getName(), Provider.JuniperContrail.getName()); - _networksDao.update(net.getId(), net, providerMap); - } - } - @Override public boolean createFloatingIp(PublicIpAddress ip) { VirtualNetworkModel vnModel = lookupPublicNetworkModel(); @@ -775,4 +879,12 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager } return null; } + + @Override + public boolean isSystemDefaultNetworkPolicy(NetworkPolicy policy) { + if (policy.getName().equals("default-network-policy")) { + return true; + } + return false; + } } diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/EventUtils.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/EventUtils.java index a06b0b35746..29b58fb7d78 100644 --- a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/EventUtils.java +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/EventUtils.java @@ -33,7 +33,6 @@ import com.cloud.event.ActionEvent; import com.cloud.event.Event; import com.cloud.event.EventCategory; import com.cloud.event.EventTypes; -import com.cloud.server.ManagementServer; import com.cloud.server.ManagementService; import com.cloud.utils.component.ComponentContext; import com.cloud.utils.component.ComponentMethodInterceptor; @@ -42,7 +41,7 @@ import com.cloud.utils.component.ComponentMethodInterceptor; public class EventUtils { private static final Logger s_logger = Logger.getLogger(EventUtils.class); - protected static MessageBus _messageBus = null; + protected static MessageBus s_messageBus = null; public EventUtils() { } @@ -54,7 +53,7 @@ public class EventUtils { } try { - _messageBus = ComponentContext.getComponent(MessageBusBase.class); + s_messageBus = ComponentContext.getComponent(MessageBusBase.class); } catch (NoSuchBeanDefinitionException nbe) { return; // no provider is configured to provide events bus, so just return } @@ -68,7 +67,7 @@ public class EventUtils { eventDescription.put("details", details); event.setDescription(eventDescription); try { - _messageBus.publish(EventTypes.getEntityForEvent(eventType), eventType, null, event); + s_messageBus.publish(EventTypes.getEntityForEvent(eventType), eventType, null, event); } catch (Exception e) { s_logger.warn("Failed to publish action event on the the event bus."); } diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ManagementNetworkGuru.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ManagementNetworkGuru.java index d3d9366ce4b..cfc6fb62a11 100644 --- a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ManagementNetworkGuru.java +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ManagementNetworkGuru.java @@ -48,11 +48,11 @@ import com.cloud.utils.PropertiesUtil; @Component public class ManagementNetworkGuru extends ContrailGuru { private static final Logger s_logger = Logger.getLogger(ManagementNetworkGuru.class); - private static final TrafficType[] _trafficTypes = {TrafficType.Management}; + private static final TrafficType[] TrafficTypes = {TrafficType.Management}; private final String configuration = "contrail.properties"; - private String _mgmt_cidr; - private String _mgmt_gateway; + private String _mgmtCidr; + private String _mgmtGateway; @Override public String getName() { @@ -86,20 +86,20 @@ public class ManagementNetworkGuru extends ContrailGuru { } catch (IOException e) { } } - _mgmt_cidr = configProps.getProperty("management.cidr"); - _mgmt_gateway = configProps.getProperty("management.gateway"); - s_logger.info("Management network " + _mgmt_cidr + " gateway: " + _mgmt_gateway); + _mgmtCidr = configProps.getProperty("management.cidr"); + _mgmtGateway = configProps.getProperty("management.gateway"); + s_logger.info("Management network " + _mgmtCidr + " gateway: " + _mgmtGateway); return true; } @Override public TrafficType[] getSupportedTrafficType() { - return _trafficTypes; + return TrafficTypes; } @Override public boolean isMyTrafficType(TrafficType type) { - for (TrafficType t : _trafficTypes) { + for (TrafficType t : TrafficTypes) { if (t == type) { return true; } @@ -119,11 +119,11 @@ public class ManagementNetworkGuru extends ContrailGuru { return null; } NetworkVO network = - new NetworkVO(offering.getTrafficType(), Mode.Dhcp, BroadcastDomainType.Lswitch, offering.getId(), Network.State.Allocated, plan.getDataCenterId(), - plan.getPhysicalNetworkId()); - if (_mgmt_cidr != null) { - network.setCidr(_mgmt_cidr); - network.setGateway(_mgmt_gateway); + new NetworkVO(offering.getTrafficType(), Mode.Dhcp, BroadcastDomainType.Lswitch, offering.getId(), Network.State.Allocated, plan.getDataCenterId(), + plan.getPhysicalNetworkId()); + if (_mgmtCidr != null) { + network.setCidr(_mgmtCidr); + network.setGateway(_mgmtGateway); } s_logger.debug("Allocated network " + userSpecified.getName() + (network.getCidr() == null ? "" : " subnet: " + network.getCidr())); return network; diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ModelDatabase.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ModelDatabase.java index 7f66a3b8290..66fad7097b8 100644 --- a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ModelDatabase.java +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ModelDatabase.java @@ -20,6 +20,7 @@ package org.apache.cloudstack.network.contrail.management; import java.util.TreeSet; import org.apache.cloudstack.network.contrail.model.ModelObjectBase; +import org.apache.cloudstack.network.contrail.model.NetworkPolicyModel; import org.apache.cloudstack.network.contrail.model.ServiceInstanceModel; import org.apache.cloudstack.network.contrail.model.VirtualMachineModel; import org.apache.cloudstack.network.contrail.model.VirtualNetworkModel; @@ -30,8 +31,9 @@ public class ModelDatabase { TreeSet _serviceInstanceTable; TreeSet _vmTable; TreeSet _vnTable; + TreeSet _policyTable; - ModelDatabase() { + public ModelDatabase() { initDb(); } @@ -39,16 +41,17 @@ public class ModelDatabase { _serviceInstanceTable = new TreeSet(new ModelObjectBase.UuidComparator()); _vmTable = new TreeSet(new ModelObjectBase.UuidComparator()); _vnTable = new TreeSet(new ModelObjectBase.UuidComparator()); + _policyTable = new TreeSet(new ModelObjectBase.UuidComparator()); } public TreeSet getServiceInstances() { return _serviceInstanceTable; } - public ServiceInstanceModel lookupServiceInstance(String uuid) { - ServiceInstanceModel siKey = new ServiceInstanceModel(uuid); + public ServiceInstanceModel lookupServiceInstance(String fqn) { + ServiceInstanceModel siKey = new ServiceInstanceModel(fqn); ServiceInstanceModel current = _serviceInstanceTable.ceiling(siKey); - if (current != null && current.getUuid().equals(uuid)) { + if (current != null && current.getQualifiedName().equals(fqn)) { return current; } return null; @@ -85,4 +88,17 @@ public class ModelDatabase { } return null; } + + public TreeSet getNetworkPolicys() { + return _policyTable; + } + + public NetworkPolicyModel lookupNetworkPolicy(String uuid) { + NetworkPolicyModel vmKey = new NetworkPolicyModel(uuid, null); + NetworkPolicyModel current = _policyTable.ceiling(vmKey); + if (current != null && current.getUuid().equals(uuid)) { + return current; + } + return null; + } } diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java index 22543dd542f..b1f47187ed8 100644 --- a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java @@ -33,6 +33,7 @@ import net.juniper.contrail.api.ApiPropertyBase; import net.juniper.contrail.api.ObjectReference; import net.juniper.contrail.api.types.FloatingIp; import net.juniper.contrail.api.types.FloatingIpPool; +import net.juniper.contrail.api.types.NetworkPolicy; import net.juniper.contrail.api.types.InstanceIp; import net.juniper.contrail.api.types.ServiceInstance; import net.juniper.contrail.api.types.VirtualMachine; @@ -45,6 +46,7 @@ import org.springframework.stereotype.Component; import org.apache.cloudstack.network.contrail.model.FloatingIpModel; import org.apache.cloudstack.network.contrail.model.FloatingIpPoolModel; +import org.apache.cloudstack.network.contrail.model.NetworkPolicyModel; import org.apache.cloudstack.network.contrail.model.ServiceInstanceModel; import org.apache.cloudstack.network.contrail.model.VMInterfaceModel; import org.apache.cloudstack.network.contrail.model.VirtualMachineModel; @@ -62,6 +64,10 @@ import com.cloud.network.dao.NetworkDao; import com.cloud.network.dao.NetworkVO; import com.cloud.network.dao.PhysicalNetworkDao; import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; +import com.cloud.network.vpc.NetworkACLItemDao; +import com.cloud.network.vpc.NetworkACLItemVO; +import com.cloud.network.vpc.NetworkACLVO; +import com.cloud.network.vpc.dao.NetworkACLDao; import com.cloud.projects.ProjectVO; import com.cloud.projects.dao.ProjectDao; import com.cloud.vm.NicVO; @@ -90,16 +96,21 @@ public class ServerDBSyncImpl implements ServerDBSync { PhysicalNetworkServiceProviderDao _physProviderDao; @Inject ContrailManager _manager; + @Inject + NetworkACLItemDao _networkACLItemDao; + @Inject + NetworkACLDao _networkACLDao; + DBSyncGeneric _dbSync; Class[] _vncClasses; // Read-Write (true) or Read-Only mode. - boolean _rw_mode; + boolean _rwMode; private final ReentrantLock _lockSyncMode = new ReentrantLock(); ServerDBSyncImpl() { _vncClasses = - new Class[] {net.juniper.contrail.api.types.Domain.class, net.juniper.contrail.api.types.Project.class, VirtualNetwork.class, VirtualMachine.class, - ServiceInstance.class, FloatingIp.class}; + new Class[] {net.juniper.contrail.api.types.Domain.class, net.juniper.contrail.api.types.Project.class, NetworkPolicy.class, VirtualNetwork.class, + VirtualMachine.class, ServiceInstance.class, FloatingIp.class}; _dbSync = new DBSyncGeneric(this); } @@ -122,7 +133,7 @@ public class ServerDBSyncImpl implements ServerDBSync { /* lock the sync mode*/ _lockSyncMode.lock(); - _rw_mode = syncMode == DBSyncGeneric.SYNC_MODE_UPDATE; + _rwMode = syncMode == DBSyncGeneric.SYNC_MODE_UPDATE; _dbSync.setSyncMode(syncMode); if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { @@ -440,7 +451,7 @@ public class ServerDBSyncImpl implements ServerDBSync { List types = new ArrayList(); types.add(TrafficType.Public); types.add(TrafficType.Guest); - List dbNets = _manager.findJuniperManagedNetworks(types); + List dbNets = _manager.findManagedNetworks(types); List vList = (List)api.list(VirtualNetwork.class, null); List vncList = new ArrayList(); @@ -499,9 +510,19 @@ public class ServerDBSyncImpl implements ServerDBSync { } VirtualNetworkModel vnModel = new VirtualNetworkModel(dbNet, dbNet.getUuid(), _manager.getCanonicalName(dbNet), dbNet.getTrafficType()); + if (dbNet.getTrafficType() == TrafficType.Guest && dbNet.getNetworkACLId() != null) { + NetworkACLVO acl = _networkACLDao.findById(dbNet.getNetworkACLId()); + NetworkPolicyModel policyModel = _manager.getDatabase().lookupNetworkPolicy(acl.getUuid()); + if (policyModel == null) { + s_logger.error("Network(" + dbNet.getName() + ") has ACL but policy model not created: " + + acl.getUuid() + ", name: " + acl.getName()); + } else { + vnModel.addToNetworkPolicy(policyModel); + } + } vnModel.build(_manager.getModelController(), dbNet); - if (_rw_mode) { + if (_rwMode) { try { if (!vnModel.verify(_manager.getModelController())) { vnModel.update(_manager.getModelController()); @@ -569,9 +590,19 @@ public class ServerDBSyncImpl implements ServerDBSync { VirtualNetworkModel current = _manager.getDatabase().lookupVirtualNetwork(vnet.getUuid(), _manager.getCanonicalName(dbn), dbn.getTrafficType()); VirtualNetworkModel vnModel = new VirtualNetworkModel(dbn, vnet.getUuid(), _manager.getCanonicalName(dbn), dbn.getTrafficType()); + if (dbn.getTrafficType() == TrafficType.Guest && dbn.getNetworkACLId() != null) { + NetworkACLVO acl = _networkACLDao.findById(dbn.getNetworkACLId()); + NetworkPolicyModel policyModel = _manager.getDatabase().lookupNetworkPolicy(acl.getUuid()); + if (policyModel == null) { + s_logger.error("Network(" + dbn.getName() + ") has ACL but policy model not created: " + + acl.getUuid() + ", name: " + acl.getName()); + } else { + vnModel.addToNetworkPolicy(policyModel); + } + } vnModel.build(_manager.getModelController(), dbn); - if (_rw_mode) { + if (_rwMode) { if (current != null) { FloatingIpPoolModel fipPoolModel = current.getFipPoolModel(); if (fipPoolModel != null) { @@ -589,6 +620,23 @@ public class ServerDBSyncImpl implements ServerDBSync { } catch (Exception ex) { s_logger.warn("update virtual-network", ex); } + if (current != null) { + NetworkPolicyModel oldPolicyModel = current.getNetworkPolicyModel(); + if (oldPolicyModel != vnModel.getNetworkPolicyModel()) { + /* + * if no other VNs are associated with the old policy, + * we could delete it from the Contrail VNC + */ + if (oldPolicyModel != null && !oldPolicyModel.hasDescendents()) { + try { + oldPolicyModel.delete(_manager.getModelController()); + _manager.getDatabase().getNetworkPolicys().remove(oldPolicyModel); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } } else { //compare if (current != null && current.compare(_manager.getModelController(), vnModel) == false) { @@ -643,7 +691,7 @@ public class ServerDBSyncImpl implements ServerDBSync { vmModel.build(_manager.getModelController(), dbVm); buildNicResources(vmModel, dbVm, syncLogMesg); - if (_rw_mode) { + if (_rwMode) { try { vmModel.update(_manager.getModelController()); } catch (InternalErrorException ex) { @@ -695,7 +743,7 @@ public class ServerDBSyncImpl implements ServerDBSync { public void deleteVirtualMachine(VirtualMachine vncVm, StringBuffer syncLogMesg) { final ApiConnector api = _manager.getApiConnector(); syncLogMesg.append("VM# DB:none; VNC: " + vncVm.getName() + "/" + vncVm.getUuid() + "; action: delete\n"); - if (!_rw_mode) { + if (!_rwMode) { return; } try { @@ -758,7 +806,7 @@ public class ServerDBSyncImpl implements ServerDBSync { } VirtualMachineModel current = _manager.getDatabase().lookupVirtualMachine(vncVm.getUuid()); - if (_rw_mode) { + if (_rwMode) { if (current != null) { _manager.getDatabase().getVirtualMachines().remove(current); } @@ -780,7 +828,7 @@ public class ServerDBSyncImpl implements ServerDBSync { public boolean syncFloatingIp() throws Exception { - List ipList = _manager.findJuniperManagedPublicIps(); + List ipList = _manager.findManagedPublicIps(); List vncList = _manager.getFloatingIps(); if (ipList == null) { ipList = new ArrayList(); @@ -884,6 +932,164 @@ public class ServerDBSyncImpl implements ServerDBSync { return true; } + /* + * Network Policy Synchronization methods + */ + @SuppressWarnings({ "unchecked" }) + public boolean syncNetworkPolicy() throws Exception { + final ApiConnector api = _manager.getApiConnector(); + try { + + List dbAcls = _manager.findManagedACLs(); + if (dbAcls == null) { + dbAcls = new ArrayList(); + } + + List pList = (List) api.list(NetworkPolicy.class, null); + List vncList = new ArrayList(); + + for (NetworkPolicy policy:pList) { + if (!_manager.isSystemDefaultNetworkPolicy(policy)) { + vncList.add(policy); + } + } + s_logger.debug("sync Network Policy - DB size: " + dbAcls.size() + " VNC Size: " + vncList.size()); + return _dbSync.syncGeneric(NetworkPolicy.class, dbAcls, vncList); + } catch (Exception ex) { + s_logger.warn("sync network-policys", ex); + throw ex; + } + } + + public Comparator dbComparatorNetworkPolicy() { + Comparator comparator = new Comparator() { + public int compare(NetworkACLVO u1, NetworkACLVO u2) { + return u1.getUuid().compareTo(u2.getUuid()); + } + }; + return comparator; + } + + public Comparator vncComparatorNetworkPolicy() { + Comparator comparator = new Comparator() { + public int compare(NetworkPolicy u1, NetworkPolicy u2) { + return u1.getUuid().compareTo(u2.getUuid()); + } + }; + return comparator; + } + + public void createNetworkPolicy(NetworkACLVO db, StringBuffer syncLogMesg) throws IOException { + syncLogMesg.append("Policy# DB: " + db.getName() + + "(" + db.getUuid() + "); VNC: none; action: create\n"); + + if (_manager.getDatabase().lookupNetworkPolicy(db.getUuid()) != null) { + s_logger.warn("Policy model object is already present in DB: " + + db.getUuid() + ", name: " + db.getName()); + } + NetworkPolicyModel policyModel = new NetworkPolicyModel(db.getUuid(), db.getName()); + net.juniper.contrail.api.types.Project project = null; + try { + project = _manager.getDefaultVncProject(); + } catch (IOException ex) { + s_logger.warn("read project", ex); + throw ex; + } + policyModel.setProject(project); + List rules = _networkACLItemDao.listByACL(db.getId()); + try { + policyModel.build(_manager.getModelController(), rules); + } catch (Exception e) { + e.printStackTrace(); + } + + if (_rwMode) { + try { + if (!policyModel.verify(_manager.getModelController())) { + policyModel.update(_manager.getModelController()); + } + } catch (Exception ex) { + s_logger.warn("create network-policy", ex); + syncLogMesg.append("Error: Policy# VNC : Unable to create network policy " + + db.getName() + "\n"); + return; + } + s_logger.debug("add model " + policyModel.getName()); + _manager.getDatabase().getNetworkPolicys().add(policyModel); + syncLogMesg.append("Policy# VNC: " + db.getUuid() + ", " + policyModel.getName() + " created\n"); + } else { + syncLogMesg.append("Policy# VNC: " + policyModel.getName() + " created \n"); + } + } + + public void deleteNetworkPolicy(NetworkPolicy policy, StringBuffer syncLogMesg) throws IOException { + final ApiConnector api = _manager.getApiConnector(); + if (_manager.isSystemDefaultNetworkPolicy(policy)) { + syncLogMesg.append("Policy# System default Network Policy# VNC: " + policy.getName() + " can not be deleted\n"); + return; + } + syncLogMesg.append("Policy# DB: none; VNC: " + policy.getName() + "(" + policy.getUuid() + "); action: delete\n"); + api.delete(policy); + syncLogMesg.append("Policy# VNC: " + policy.getName() + " deleted\n"); + } + + public Integer compareNetworkPolicy(NetworkACLVO dbn, NetworkPolicy policy, StringBuffer syncLogMesg) { + if (_manager.isSystemDefaultNetworkPolicy(policy)) { + return 1; + } + return dbn.getUuid().compareTo(policy.getUuid()); + } + + public Boolean filterNetworkPolicy(NetworkPolicy policy, StringBuffer syncLogMesg) { + if (_manager.isSystemDefaultNetworkPolicy(policy)) { + syncLogMesg.append("Policy# VNC: " + policy.getName() + " filtered; action: don't delete\n"); + return true; + } + return false; + } + + public Boolean equalNetworkPolicy(NetworkACLVO db, NetworkPolicy policy, StringBuffer syncLogMesg) { + syncLogMesg.append("Policy# DB: " + db.getName() + + "; VNC: " + policy.getName() + "; action: equal\n"); + NetworkPolicyModel current = _manager.getDatabase().lookupNetworkPolicy(policy.getUuid()); + NetworkPolicyModel policyModel = new NetworkPolicyModel(db.getUuid(), db.getName()); + net.juniper.contrail.api.types.Project project = null; + try { + project = _manager.getDefaultVncProject(); + } catch (IOException ex) { + s_logger.warn("read project", ex); + } + policyModel.setProject(project); + List rules = _networkACLItemDao.listByACL(db.getId()); + try { + policyModel.build(_manager.getModelController(), rules); + } catch (Exception e) { + e.printStackTrace(); + } + if (_rwMode) { + if (current != null) { + _manager.getDatabase().getNetworkPolicys().remove(current); + } + s_logger.debug("add policy model " + policyModel.getName()); + _manager.getDatabase().getNetworkPolicys().add(policyModel); + try { + if (!policyModel.verify(_manager.getModelController())) { + policyModel.update(_manager.getModelController()); + } + } catch (Exception ex) { + s_logger.warn("update network-policy", ex); + } + } else { + //compare + if (current != null && current.compare(_manager.getModelController(), policyModel) == false) { + syncLogMesg.append("Policy# DB: " + db.getName() + + "; VNC: " + policy.getName() + "; attributes differ\n"); + return false; + } + } + return true; + } + public Integer compareServiceInstance(ServiceInstanceModel siModel, ServiceInstance siObj, StringBuffer logMsg) { String fqn = StringUtils.join(siObj.getQualifiedName(), ':'); return siModel.getQualifiedName().compareTo(fqn); @@ -903,7 +1109,7 @@ public class ServerDBSyncImpl implements ServerDBSync { public void deleteServiceInstance(ServiceInstance siObj, StringBuffer logMsg) { final ApiConnector api = _manager.getApiConnector(); s_logger.debug("delete " + siObj.getQualifiedName()); - if (!_rw_mode) { + if (!_rwMode) { return; } try { @@ -946,7 +1152,7 @@ public class ServerDBSyncImpl implements ServerDBSync { List siList = (List)api.list(ServiceInstance.class, null); java.util.Collections.sort(siList, new ServiceInstanceComparator()); DBSyncGeneric.SyncStats stats = new DBSyncGeneric.SyncStats(); - _dbSync.syncCollections(ServiceInstance.class, _manager.getDatabase().getServiceInstances(), siList, _rw_mode, stats); + _dbSync.syncCollections(ServiceInstance.class, _manager.getDatabase().getServiceInstances(), siList, _rwMode, stats); inSync = stats.create == 0 && stats.delete == 0; } catch (Exception ex) { s_logger.warn("synchronize service-instances", ex); diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServerEventHandlerImpl.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServerEventHandlerImpl.java index 5030bb71d09..05dcdce1a92 100644 --- a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServerEventHandlerImpl.java +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServerEventHandlerImpl.java @@ -87,14 +87,6 @@ public class ServerEventHandlerImpl implements ServerEventHandler { public void defaultMessageHandler(String subject, String topic, Object args) { s_logger.info("DB Event Received - topic: " + topic + "; subject: " + subject); - if (subject.equals("VLAN.IP.RANGE.CREATE")) { - _manager.createPublicNetworks(); - return; - } else if (subject.equals("VLAN.IP.RANGE.DELETE")) { - // TODO - return; - } - org.apache.cloudstack.framework.events.Event event = (org.apache.cloudstack.framework.events.Event)args; /* Method name should be on for example: onDomainCreate */ @@ -244,7 +236,5 @@ public class ServerEventHandlerImpl implements ServerEventHandler { _messageBus.subscribe(EventTypes.EVENT_PROJECT_DELETE, MessageDispatcher.getDispatcher(this)); _messageBus.subscribe(EventTypes.EVENT_DOMAIN_CREATE, MessageDispatcher.getDispatcher(this)); _messageBus.subscribe(EventTypes.EVENT_DOMAIN_DELETE, MessageDispatcher.getDispatcher(this)); - _messageBus.subscribe(EventTypes.EVENT_VLAN_IP_RANGE_CREATE, MessageDispatcher.getDispatcher(this)); - _messageBus.subscribe(EventTypes.EVENT_VLAN_IP_RANGE_DELETE, MessageDispatcher.getDispatcher(this)); } } diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServiceManagerImpl.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServiceManagerImpl.java index e15e2ce8ff6..9860faf7f09 100644 --- a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServiceManagerImpl.java +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServiceManagerImpl.java @@ -27,12 +27,13 @@ import javax.inject.Inject; import net.juniper.contrail.api.ApiConnector; import net.juniper.contrail.api.types.ServiceInstance; -import net.juniper.contrail.api.types.VirtualNetwork; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.network.contrail.api.response.ServiceInstanceResponse; import org.apache.cloudstack.network.contrail.model.ServiceInstanceModel; import org.apache.cloudstack.network.contrail.model.VirtualMachineModel; +import org.apache.cloudstack.network.contrail.model.VirtualNetworkModel; + import org.apache.log4j.Logger; import com.cloud.api.ApiDBUtils; @@ -96,7 +97,7 @@ public class ServiceManagerImpl implements ServiceManager { */ @ActionEvent(eventType = EventTypes.EVENT_VM_CREATE, eventDescription = "createServiceInstance", create = true) private ServiceVirtualMachine createServiceVM(DataCenter zone, Account owner, VirtualMachineTemplate template, ServiceOffering serviceOffering, String name, - ServiceInstance siObj, Network left, Network right) { + ServiceInstance siObj, Network left, Network right) { long id = _vmDao.getNextInSequence(Long.class, "id"); DataCenterDeployment plan = new DataCenterDeployment(zone.getId()); @@ -109,8 +110,8 @@ public class ServiceManagerImpl implements ServiceManager { String instanceName = VirtualMachineName.getVmName(id, owner.getId(), "SRV"); ServiceVirtualMachine svm = - new ServiceVirtualMachine(id, instanceName, name, template.getId(), serviceOffering.getId(), template.getHypervisorType(), template.getGuestOSId(), - zone.getId(), owner.getDomainId(), owner.getAccountId(), false); + new ServiceVirtualMachine(id, instanceName, name, template.getId(), serviceOffering.getId(), template.getHypervisorType(), template.getGuestOSId(), + zone.getId(), owner.getDomainId(), owner.getAccountId(), false); // database synchronization code must be able to distinguish service instance VMs. Map kvmap = new HashMap(); @@ -130,7 +131,7 @@ public class ServiceManagerImpl implements ServiceManager { @Override public ServiceVirtualMachine createServiceInstance(DataCenter zone, Account owner, VirtualMachineTemplate template, ServiceOffering serviceOffering, String name, - Network left, Network right) { + Network left, Network right) { s_logger.debug("createServiceInstance by " + owner.getAccountName()); // TODO: permission model. // service instances need to be able to access the public network. @@ -142,17 +143,15 @@ public class ServiceManagerImpl implements ServiceManager { } final ApiConnector api = _manager.getApiConnector(); - final VirtualNetwork netLeft; - try { - netLeft = (VirtualNetwork)api.findById(VirtualNetwork.class, left.getUuid()); - } catch (IOException ex) { - throw new CloudRuntimeException("Unable to read virtual-network object", ex); + VirtualNetworkModel leftModel = _manager.getDatabase().lookupVirtualNetwork(left.getUuid(), + _manager.getCanonicalName(left), left.getTrafficType()); + if (leftModel == null) { + throw new CloudRuntimeException("Unable to read virtual-network object"); } - final VirtualNetwork netRight; - try { - netRight = (VirtualNetwork)api.findById(VirtualNetwork.class, right.getUuid()); - } catch (IOException ex) { - throw new CloudRuntimeException("Unable to read virtual-network object", ex); + VirtualNetworkModel rightModel = _manager.getDatabase().lookupVirtualNetwork(right.getUuid(), + _manager.getCanonicalName(right), right.getTrafficType()); + if (rightModel == null) { + throw new CloudRuntimeException("Unable to read virtual-network object"); } net.juniper.contrail.api.types.Project project; @@ -174,7 +173,8 @@ public class ServiceManagerImpl implements ServiceManager { } // 1. Create service-instance. - ServiceInstanceModel serviceModel = new ServiceInstanceModel(project, name, template, serviceOffering, netLeft, netRight); + ServiceInstanceModel serviceModel = new ServiceInstanceModel(project, name, template, serviceOffering, + leftModel, rightModel); try { serviceModel.update(_manager.getModelController()); diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/NetworkPolicyModel.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/NetworkPolicyModel.java new file mode 100644 index 00000000000..8ec2ff7187a --- /dev/null +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/NetworkPolicyModel.java @@ -0,0 +1,305 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package org.apache.cloudstack.network.contrail.model; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang.StringUtils; +import org.apache.log4j.Logger; + +import com.cloud.network.Networks; + +import net.juniper.contrail.api.types.NetworkPolicy; +import net.juniper.contrail.api.types.PolicyEntriesType; +import net.juniper.contrail.api.types.PolicyEntriesType.PolicyRuleType; +import net.juniper.contrail.api.types.Project; +import net.juniper.contrail.api.ApiConnector; +import org.apache.cloudstack.network.contrail.management.ContrailManager; + +import com.cloud.exception.InternalErrorException; +import com.cloud.network.dao.NetworkVO; +import com.cloud.network.vpc.NetworkACLItem; +import com.cloud.network.vpc.NetworkACLItem.Action; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.SearchCriteria.Op; +import com.cloud.utils.exception.CloudRuntimeException; + +public class NetworkPolicyModel extends ModelObjectBase { + private static final Logger s_logger = Logger.getLogger(NetworkPolicyModel.class); + + private String _uuid; + private String _fqName; + private String _name; + private Project _project; + private NetworkPolicy _policy; + PolicyEntriesType _policyMap; + + public NetworkPolicyModel(String uuid, String name) { + _uuid = uuid; + _name = name; + } + + public String getQualifiedName() { + return _fqName; + } + + public String getName() { + return _name; + } + + public NetworkVO cidrToNetwork(ModelController controller, String cidr) { + SearchBuilder searchBuilder = controller.getNetworkDao().createSearchBuilder(); + searchBuilder.and("trafficType", searchBuilder.entity().getTrafficType(), Op.EQ); + searchBuilder.and("cidr", searchBuilder.entity().getCidr(), Op.EQ); + searchBuilder.and("networkOfferingId", searchBuilder.entity().getNetworkOfferingId(), Op.EQ); + + SearchCriteria sc = searchBuilder.create(); + + sc.setParameters("networkOfferingId", controller.getManager().getRouterOffering().getId()); + sc.setParameters("cidr", cidr); + sc.setParameters("trafficType", Networks.TrafficType.Guest); + + List dbNets = controller.getNetworkDao().search(sc, null); + if (dbNets == null || dbNets.size() == 0) { + return null; + } + if (dbNets.size() > 1) { + s_logger.warn("more than one network found with cidr: " + cidr); + } + return dbNets.get(0); + } + + public void build(ModelController controller, List rules) throws Exception { + String projectName = null; + if (_project != null) { + _fqName = StringUtils.join(_project.getQualifiedName(), ':') + ":" + _name; + projectName = StringUtils.join(_project.getQualifiedName(), ':'); + } else { + _fqName = ContrailManager.VNC_ROOT_DOMAIN + ":" + ContrailManager.VNC_DEFAULT_PROJECT + ":" + _name; + projectName = ContrailManager.VNC_ROOT_DOMAIN + ":" + ContrailManager.VNC_DEFAULT_PROJECT; + } + + PolicyEntriesType policyMap = new PolicyEntriesType(); + + for (NetworkACLItem rule:rules) { + if (rule.getState() != NetworkACLItem.State.Active && + rule.getState() != NetworkACLItem.State.Add) { + continue; + } + + String action = null; + if (rule.getAction() == Action.Allow) { + action = "pass"; + } else if (rule.getAction() == Action.Deny) { + action = "deny"; + } + List cidrList = rule.getSourceCidrList(); + String protocol = rule.getProtocol(); + if (protocol == null || protocol.equalsIgnoreCase("ALL") || protocol.isEmpty()) { + protocol = "any"; + } else { + protocol = protocol.toLowerCase(); + } + + Integer portStart = rule.getSourcePortStart(); + Integer portEnd = rule.getSourcePortEnd(); + if (portStart == null) { + portStart = 0; + } + if (portEnd == null) { + portEnd = 65535; + } + + List srcList = new ArrayList(); + List dstList = new ArrayList(); + + List srcPorts = new ArrayList(); + List dstPorts = new ArrayList(); + + if (rule.getTrafficType() == NetworkACLItem.TrafficType.Egress){ + for (String cidr: cidrList) { + NetworkVO net = cidrToNetwork(controller, cidr); + /*String[] maskInfo = StringUtils.splitByWholeSeparator(cidr, "/"); + SubnetType subnet = new SubnetType(); + subnet.setIpPrefix(maskInfo[0]); + subnet.setIpPrefixLen(Integer.parseInt(maskInfo[1])); + */ + String netName = projectName + ":" + controller.getManager().getCanonicalName(net); + dstList.add(new PolicyRuleType.AddressType(null, netName, null)); + } + dstPorts.add(new PolicyRuleType.PortType(portStart, portEnd)); + srcList.add(new PolicyRuleType.AddressType(null, "local", null)); + srcPorts.add(new PolicyRuleType.PortType(0, 65535)); + } else { + for (String cidr: cidrList) { + NetworkVO net = cidrToNetwork(controller, cidr); + String netName = projectName + ":" + controller.getManager().getCanonicalName(net); + dstList.add(new PolicyRuleType.AddressType(null, netName, null)); + } + dstPorts.add(new PolicyRuleType.PortType(portStart, portEnd)); + + srcList.add(new PolicyRuleType.AddressType(null, "any", null)); + srcPorts.add(new PolicyRuleType.PortType(0, 65535)); + } + + PolicyRuleType vnRule = new PolicyRuleType( + new PolicyRuleType.SequenceType(1, 0), rule.getUuid(), "<>", protocol, + srcList, srcPorts, null, dstList, dstPorts, + new PolicyRuleType.ActionListType(action, null, null, null)); + policyMap.addPolicyRule(vnRule); + } + _policyMap = policyMap; + } + + /* for service instance policy */ + public void build(ModelController modelController, String leftVn, String rightVn, String gatewayName, + List siList, String action) { + if (_project != null) { + _fqName = StringUtils.join(_project.getQualifiedName(), ':') + ":" + _name; + } else { + _fqName = ContrailManager.VNC_ROOT_DOMAIN + ":" + ContrailManager.VNC_DEFAULT_PROJECT + ":" + _name; + } + + PolicyEntriesType policyMap = new PolicyEntriesType(); + List srcList = new ArrayList(); + srcList.add(new PolicyRuleType.AddressType(null, leftVn, null)); + List dstList = new ArrayList(); + dstList.add(new PolicyRuleType.AddressType(null, rightVn, null)); + + List portAny = new ArrayList(); + portAny.add(new PolicyRuleType.PortType(0, 65535)); + + PolicyRuleType rule = new PolicyRuleType( + new PolicyRuleType.SequenceType(1, 0), null, "<>", "any", + srcList, portAny, null, dstList, portAny, + new PolicyRuleType.ActionListType(action, gatewayName, siList, null)); + policyMap.addPolicyRule(rule); + _policyMap = policyMap; + } + + public boolean hasPolicyRules() { + if (_policyMap != null && _policyMap.getPolicyRule() != null && _policyMap.getPolicyRule().size() > 0) { + return true; + } + return false; + } + + @Override + public int compareTo(ModelObject o) { + NetworkPolicyModel other; + try { + other = (NetworkPolicyModel) o; + } catch (ClassCastException ex) { + String clsname = o.getClass().getName(); + return NetworkPolicyModel.class.getName().compareTo(clsname); + } + return _uuid.compareTo(other._uuid); + } + + @Override + public void delete(ModelController controller) throws IOException { + ApiConnector api = controller.getApiAccessor(); + if (_policy != null) { + api.delete(_policy); + _policy = null; + } + } + + @Override + public void destroy(ModelController controller) throws IOException { + } + + public String getUuid() { + return _uuid; + } + + @Override + public void update(ModelController controller) throws InternalErrorException, IOException { + ApiConnector api = controller.getApiAccessor(); + if (_project == null) { + s_logger.debug("Project is null for the policy: " + _name); + throw new IOException("Project is null for the policy: " + _name); + } + + NetworkPolicy policy = _policy; + + if (policy == null) { + try { + String policyId = api.findByName(NetworkPolicy.class, _project, _name); + if (policyId != null) { + policy = _policy = (NetworkPolicy) api.findById(NetworkPolicy.class, policyId); + } + if (policy == null) { + policy = new NetworkPolicy(); + policy.setUuid(_uuid); + policy.setName(_name); + policy.setParent(_project); + } + } catch (IOException ex) { + s_logger.warn("network-policy read", ex); + return; + } + } + + policy.setEntries(_policyMap); + if (_policy == null) { + try { + api.create(policy); + } catch (Exception ex) { + s_logger.debug("network policy create", ex); + throw new CloudRuntimeException("Failed to create network policy", ex); + } + _policy = policy; + } else { + try { + api.update(policy); + } catch (IOException ex) { + s_logger.warn("network policy update", ex); + throw new CloudRuntimeException("Unable to update network policy", ex); + } + } + for (ModelObject successor: successors()) { + successor.update(controller); + } + } + + @Override + public boolean verify(ModelController controller) { + return false; + } + + @Override + public boolean compare(ModelController controller, ModelObject current) { + return true; + } + + public void setProperties(ModelController controller, List rules) { + + } + + public void setProject(Project project) { + _project = project; + } + + public NetworkPolicy getPolicy() { + return _policy; + } +} diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/ServiceInstanceModel.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/ServiceInstanceModel.java index d0664238a79..0ce22adc421 100644 --- a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/ServiceInstanceModel.java +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/ServiceInstanceModel.java @@ -20,19 +20,15 @@ package org.apache.cloudstack.network.contrail.model; import java.io.IOException; import java.util.ArrayList; import java.util.List; +import java.util.UUID; import net.juniper.contrail.api.ApiConnector; import net.juniper.contrail.api.ObjectReference; -import net.juniper.contrail.api.types.NetworkPolicy; -import net.juniper.contrail.api.types.PolicyEntriesType; -import net.juniper.contrail.api.types.PolicyEntriesType.PolicyRuleType; import net.juniper.contrail.api.types.Project; import net.juniper.contrail.api.types.ServiceInstance; import net.juniper.contrail.api.types.ServiceInstanceType; import net.juniper.contrail.api.types.ServiceTemplate; import net.juniper.contrail.api.types.ServiceTemplateType; -import net.juniper.contrail.api.types.VirtualNetwork; -import net.juniper.contrail.api.types.VirtualNetworkPolicyType; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; @@ -47,7 +43,7 @@ public class ServiceInstanceModel extends ModelObjectBase { private static final Logger s_logger = Logger.getLogger(ServiceInstanceModel.class); private String _uuid; - private String _fq_name; + private String _fqName; private String _projectId; private String _mgmtName; private String _leftName; @@ -56,11 +52,11 @@ public class ServiceInstanceModel extends ModelObjectBase { private String _templateName; private String _templateId; private String _templateUrl; - private VirtualNetwork _left; - private VirtualNetwork _right; + private VirtualNetworkModel _left; + private VirtualNetworkModel _right; private ServiceTemplate _tmpl; private ServiceInstance _serviceInstance; - private NetworkPolicy _policy; + private NetworkPolicyModel _policy; /** * Create a ServiceInstance as result of an API call. @@ -72,20 +68,20 @@ public class ServiceInstanceModel extends ModelObjectBase { * @param left * @param right */ - public ServiceInstanceModel(Project project, String name, VirtualMachineTemplate template, ServiceOffering serviceOffering, VirtualNetwork left, VirtualNetwork right) { + public ServiceInstanceModel(Project project, String name, VirtualMachineTemplate template, ServiceOffering serviceOffering, VirtualNetworkModel left, VirtualNetworkModel right) { String parent_name; if (project != null) { parent_name = StringUtils.join(project.getQualifiedName(), ':'); } else { parent_name = ContrailManager.VNC_ROOT_DOMAIN + ":" + ContrailManager.VNC_DEFAULT_PROJECT; } - _fq_name = parent_name + ":" + name; + _fqName = parent_name + ":" + name; _mgmtName = ContrailManager.VNC_ROOT_DOMAIN + ":" + ContrailManager.VNC_DEFAULT_PROJECT + ":" + ContrailManager.managementNetworkName; _left = left; _right = right; - _leftName = StringUtils.join(left.getQualifiedName(), ":"); - _rightName = StringUtils.join(right.getQualifiedName(), ":"); + _leftName = StringUtils.join(left.getVirtualNetwork().getQualifiedName(), ":"); + _rightName = StringUtils.join(right.getVirtualNetwork().getQualifiedName(), ":"); _templateName = template.getName(); _templateId = template.getUuid(); @@ -103,33 +99,11 @@ public class ServiceInstanceModel extends ModelObjectBase { } public String getQualifiedName() { - return _fq_name; + return _fqName; } public String getName() { - return _fq_name.substring(_fq_name.lastIndexOf(':') + 1); - } - - private void applyNetworkPolicy(ModelController controller, NetworkPolicy policy, VirtualNetwork left, VirtualNetwork right) { - left.setNetworkPolicy(policy, new VirtualNetworkPolicyType(new VirtualNetworkPolicyType.SequenceType(1, 0), null)); - // TODO: network_ipam_refs attr is missing - left.clearNetworkIpam(); - try { - ApiConnector api = controller.getApiAccessor(); - api.update(left); - } catch (IOException ex) { - throw new CloudRuntimeException("Unable to update virtual-network", ex); - } - - right.setNetworkPolicy(policy, new VirtualNetworkPolicyType(new VirtualNetworkPolicyType.SequenceType(1, 0), null)); - // TODO: network_ipam_refs attr is missing - right.clearNetworkIpam(); - try { - ApiConnector api = controller.getApiAccessor(); - api.update(right); - } catch (IOException ex) { - throw new CloudRuntimeException("Unable to update virtual-network", ex); - } + return _fqName.substring(_fqName.lastIndexOf(':') + 1); } /** @@ -139,7 +113,7 @@ public class ServiceInstanceModel extends ModelObjectBase { public void build(ModelController controller, ServiceInstance siObj) { ApiConnector api = controller.getApiAccessor(); _serviceInstance = siObj; - _fq_name = StringUtils.join(siObj.getQualifiedName(), ':'); + _fqName = StringUtils.join(siObj.getQualifiedName(), ':'); ServiceInstanceType props = siObj.getProperties(); // TODO: read management network names and cache network objects. ObjectReference ref = siObj.getServiceTemplate().get(0); @@ -151,18 +125,6 @@ public class ServiceInstanceModel extends ModelObjectBase { s_logger.warn("service-template read", ex); } } - try { - Project project = (Project)api.findById(Project.class, siObj.getParentUuid()); - if (project != null) { - _projectId = project.getUuid(); - } - String policyId = api.findByName(NetworkPolicy.class, project, siObj.getName()); - if (policyId != null) { - _policy = (NetworkPolicy)api.findById(NetworkPolicy.class, policyId); - } - } catch (IOException ex) { - s_logger.warn("network-policy read", ex); - } } @Override @@ -174,7 +136,7 @@ public class ServiceInstanceModel extends ModelObjectBase { String clsname = o.getClass().getName(); return ServiceInstanceModel.class.getName().compareTo(clsname); } - return _fq_name.compareTo(other._fq_name); + return _fqName.compareTo(other._fqName); } private ServiceInstance createServiceInstance(ModelController controller) { @@ -207,40 +169,52 @@ public class ServiceInstanceModel extends ModelObjectBase { return si_obj; } - private NetworkPolicy createServicePolicy(ModelController controller) { - NetworkPolicy policy = new NetworkPolicy(); - policy.setParent(_serviceInstance.getParent()); - policy.setName(_serviceInstance.getName()); - PolicyEntriesType policy_map = new PolicyEntriesType(); - List srcList = new ArrayList(); - srcList.add(new PolicyRuleType.AddressType(null, _leftName, null)); - List dstList = new ArrayList(); - dstList.add(new PolicyRuleType.AddressType(null, _rightName, null)); + private void clearServicePolicy(ModelController controller) { + _left.addToNetworkPolicy(null); + _right.addToNetworkPolicy(null); + try { + controller.getManager().getDatabase().getNetworkPolicys().remove(_policy); + _policy.delete(controller.getManager().getModelController()); + _policy = null; + } catch (Exception e) { + s_logger.error(e); + } + try { + _left.update(controller.getManager().getModelController()); + _right.update(controller.getManager().getModelController()); + } catch (Exception ex) { + s_logger.error("virtual-network update for policy delete: ", ex); + } + } + + private NetworkPolicyModel setServicePolicy(ModelController controller) { + NetworkPolicyModel policyModel = new NetworkPolicyModel(UUID.randomUUID().toString(), _serviceInstance.getName()); + policyModel.setProject((Project)_serviceInstance.getParent()); + _left.addToNetworkPolicy(policyModel); + _right.addToNetworkPolicy(policyModel); List siList = new ArrayList(); siList.add(StringUtils.join(_serviceInstance.getQualifiedName(), ':')); - List portAny = new ArrayList(); - portAny.add(new PolicyRuleType.PortType(0, 65535)); - - PolicyRuleType rule = - new PolicyRuleType(new PolicyRuleType.SequenceType(1, 0), /* uuid */null, "<>", "any", srcList, portAny, /* application */null, dstList, portAny, - new PolicyRuleType.ActionListType("pass", "in-network", siList, null)); - policy_map.addPolicyRule(rule); - policy.setEntries(policy_map); - - try { - ApiConnector api = controller.getApiAccessor(); - if (!api.create(policy)) { - throw new CloudRuntimeException("Unable to create network-policy"); - } - } catch (IOException ex) { - throw new CloudRuntimeException("Unable to create network-policy", ex); + try { + policyModel.build(controller.getManager().getModelController(), _leftName, _rightName, "in-network", siList, "pass"); + } catch (Exception e) { + s_logger.error(e); + return null; } - return policy; + try { + if (!policyModel.verify(controller.getManager().getModelController())) { + policyModel.update(controller.getManager().getModelController()); + } + controller.getManager().getDatabase().getNetworkPolicys().add(policyModel); + } catch (Exception ex) { + s_logger.error("network-policy update: ", ex); + } + return policyModel; } @Override public void delete(ModelController controller) throws IOException { ApiConnector api = controller.getApiAccessor(); + clearServicePolicy(controller); if (_serviceInstance != null) { api.delete(_serviceInstance); } @@ -291,9 +265,7 @@ public class ServiceInstanceModel extends ModelObjectBase { } _uuid = _serviceInstance.getUuid(); if (_policy == null) { - _policy = createServicePolicy(controller); - // TODO: update the network model objects and call update - applyNetworkPolicy(controller, _policy, _left, _right); + _policy = setServicePolicy(controller); } } diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/VirtualMachineModel.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/VirtualMachineModel.java index 96cea95250d..4d0218c8b4a 100644 --- a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/VirtualMachineModel.java +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/VirtualMachineModel.java @@ -29,6 +29,7 @@ import net.juniper.contrail.api.types.VirtualMachine; import org.apache.cloudstack.network.contrail.management.ContrailManager; import org.apache.log4j.Logger; +import org.apache.commons.lang.StringUtils; import com.cloud.exception.InternalErrorException; import com.cloud.network.dao.NetworkDao; @@ -101,22 +102,27 @@ public class VirtualMachineModel extends ModelObjectBase { ApiConnector api = controller.getApiAccessor(); _serviceUuid = serviceUuid; - ServiceInstanceModel siModel = manager.getDatabase().lookupServiceInstance(serviceUuid); - if (siModel == null) { - ServiceInstance siObj; - try { - siObj = (ServiceInstance)api.findById(ServiceInstance.class, serviceUuid); - } catch (IOException ex) { - s_logger.warn("service-instance read", ex); - throw new CloudRuntimeException("Unable to read service-instance object", ex); - } - if (siObj == null) { - //If the ServiceInstance object is null, do not call build. It will break in many places. Instead, call update passing the controller as parameter. - //It will then create a new ServiceInstance is that's null. - siModel = new ServiceInstanceModel(serviceUuid); - siModel.update(controller); - - siObj = siModel.getServiceInstance(); + ServiceInstance siObj; + try { + siObj = (ServiceInstance) api.findById(ServiceInstance.class, serviceUuid); + } catch (IOException ex) { + s_logger.warn("service-instance read", ex); + throw new CloudRuntimeException("Unable to read service-instance object", ex); + } + ServiceInstanceModel siModel; + if (siObj == null) { + siModel = new ServiceInstanceModel(serviceUuid); + siModel.build(controller, siObj); + manager.getDatabase().getServiceInstances().add(siModel); + } else { + String fqn = StringUtils.join(siObj.getQualifiedName(), ':'); + siModel = manager.getDatabase().lookupServiceInstance(fqn); + if (siModel == null) { + if (siObj == null) { + siModel = new ServiceInstanceModel(serviceUuid); + siModel.build(controller, siObj); + manager.getDatabase().getServiceInstances().add(siModel); + } } } _serviceModel = siModel; @@ -199,21 +205,21 @@ public class VirtualMachineModel extends ModelObjectBase { boolean isActiveInstance(VMInstanceVO instance) { switch (instance.getState()) { - case Migrating: - case Starting: - case Running: - case Shutdowned: - case Stopped: - case Stopping: - return true; + case Migrating: + case Starting: + case Running: + case Shutdowned: + case Stopped: + case Stopping: + return true; - case Destroyed: - case Error: - case Expunging: - return false; + case Destroyed: + case Error: + case Expunging: + return false; - default: - s_logger.warn("Unknown VMInstance state " + instance.getState().getDescription()); + default: + s_logger.warn("Unknown VMInstance state " + instance.getState().getDescription()); } return true; } @@ -257,17 +263,17 @@ public class VirtualMachineModel extends ModelObjectBase { String tag; switch (nic.getDeviceId()) { - case 0: - tag = "management"; - break; - case 1: - tag = "left"; - break; - case 2: - tag = "right"; - break; - default: - tag = null; + case 0: + tag = "management"; + break; + case 1: + tag = "left"; + break; + case 2: + tag = "right"; + break; + default: + tag = null; } VMInterfaceModel vmiModel = getVMInterface(nic.getUuid()); @@ -337,8 +343,27 @@ public class VirtualMachineModel extends ModelObjectBase { @Override public boolean verify(ModelController controller) { - // TODO Auto-generated method stub - return false; + assert _initialized : "initialized is false"; + assert _uuid != null : "uuid is not set"; + + ApiConnector api = controller.getApiAccessor(); + + try { + _vm = (VirtualMachine) api.findById(VirtualMachine.class, _uuid); + } catch (IOException e) { + s_logger.error("virtual-machine verify", e); + } + + if (_vm == null) { + return false; + } + + for (ModelObject successor: successors()) { + if (!successor.verify(controller)) { + return false; + } + } + return true; } @Override diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/VirtualNetworkModel.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/VirtualNetworkModel.java index 547d4bd8b04..b0505b17db7 100644 --- a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/VirtualNetworkModel.java +++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/VirtualNetworkModel.java @@ -29,6 +29,7 @@ import net.juniper.contrail.api.types.NetworkIpam; import net.juniper.contrail.api.types.Project; import net.juniper.contrail.api.types.SubnetType; import net.juniper.contrail.api.types.VirtualNetwork; +import net.juniper.contrail.api.types.VirtualNetworkPolicyType; import net.juniper.contrail.api.types.VnSubnetsType; import org.apache.log4j.Logger; @@ -66,6 +67,7 @@ public class VirtualNetworkModel extends ModelObjectBase { private NetworkIpam _ipam; private FloatingIpPoolModel _fipPoolModel; + private NetworkPolicyModel _policyModel; public VirtualNetworkModel(Network network, String uuid, String name, TrafficType trafficType) { _uuid = uuid; @@ -133,6 +135,10 @@ public class VirtualNetworkModel extends ModelObjectBase { successor.delete(controller); } + if (_policyModel != null) { + _policyModel.removeSuccessor(this); + } + try { api.delete(VirtualNetwork.class, _uuid); } catch (IOException ex) { @@ -181,6 +187,8 @@ public class VirtualNetworkModel extends ModelObjectBase { } } + _id = network.getId(); + try { _projectId = manager.getProjectId(network.getDomainId(), network.getAccountId()); } catch (IOException ex) { @@ -226,6 +234,16 @@ public class VirtualNetworkModel extends ModelObjectBase { } } + if (_policyModel == null) { + vn.clearNetworkPolicy(); + } else if (!_policyModel.hasPolicyRules()) { + vn.clearNetworkPolicy(); + _policyModel.removeSuccessor(this); + } else { + vn.setNetworkPolicy(_policyModel.getPolicy(), new VirtualNetworkPolicyType( + new VirtualNetworkPolicyType.SequenceType(1, 0), null)); + } + if (_ipam == null) { NetworkIpam ipam = null; try { @@ -402,6 +420,22 @@ public class VirtualNetworkModel extends ModelObjectBase { return false; } + List> policyRefs = _vn.getNetworkPolicy(); + if ((policyRefs == null || policyRefs.isEmpty()) && _policyModel != null) { + return false; + } + + if ((policyRefs != null && !policyRefs.isEmpty()) && _policyModel == null) { + return false; + } + + if (policyRefs != null && !policyRefs.isEmpty() && _policyModel != null) { + ObjectReference ref = policyRefs.get(0); + if (!ref.getUuid().equals(_policyModel.getUuid())) { + return false; + } + } + for (ModelObject successor : successors()) { if (!successor.verify(controller)) { return false; @@ -413,8 +447,6 @@ public class VirtualNetworkModel extends ModelObjectBase { @Override public boolean compare(ModelController controller, ModelObject o) { VirtualNetworkModel latest; - ApiConnector api = controller.getApiAccessor(); - assert this._vn != null : "vnc virtual network current is not initialized"; try { @@ -475,6 +507,40 @@ public class VirtualNetworkModel extends ModelObjectBase { return false; } + List> currentPolicyRefs = this._vn.getNetworkPolicy(); + List> latestPolicyRefs = latest._vn.getNetworkPolicy(); + + if (currentPolicyRefs == null && latestPolicyRefs == null) { + return true; + } + + if ((currentPolicyRefs == null && latestPolicyRefs != null) || + (currentPolicyRefs != null && latestPolicyRefs == null) || + (currentPolicyRefs.size() != latestPolicyRefs.size())) { + return false; + } + + if (currentPolicyRefs.isEmpty() && latestPolicyRefs.isEmpty()) { + return true; + } + + //both must be non empty lists + ObjectReference ref1 = currentPolicyRefs.get(0); + ObjectReference ref2 = latestPolicyRefs.get(0); + + if ((ref1 != null && ref2 == null) || (ref1 == null && ref2 != null)) { + return false; + } + + if ((ref1.getUuid() != null && ref2.getUuid() == null) || (ref1.getUuid() == null && ref2.getUuid() != null)) { + return false; + } + if (ref1.getUuid() == null && ref2.getUuid() == null) { + return true; + } + if (!ref1.getUuid().equals(ref2.getUuid())) { + return false; + } return true; } @@ -485,4 +551,18 @@ public class VirtualNetworkModel extends ModelObjectBase { public void setFipPoolModel(FloatingIpPoolModel fipPoolModel) { _fipPoolModel = fipPoolModel; } + + public NetworkPolicyModel getNetworkPolicyModel() { + return _policyModel; + } + + public void addToNetworkPolicy(NetworkPolicyModel policyModel) { + if (_policyModel != null) { + _policyModel.removeSuccessor(this); + } + _policyModel = policyModel; + if (_policyModel != null) { + _policyModel.addSuccessor(this); + } + } } diff --git a/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/IntegrationTestConfiguration.java b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/IntegrationTestConfiguration.java index 8b14a42219f..1a53c173d9f 100644 --- a/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/IntegrationTestConfiguration.java +++ b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/IntegrationTestConfiguration.java @@ -21,6 +21,7 @@ import java.io.IOException; import javax.inject.Inject; +import org.eclipse.jetty.security.IdentityService; import org.mockito.Matchers; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; @@ -42,17 +43,19 @@ import org.apache.cloudstack.affinity.dao.AffinityGroupDao; import org.apache.cloudstack.affinity.dao.AffinityGroupDaoImpl; import org.apache.cloudstack.affinity.dao.AffinityGroupDomainMapDaoImpl; import org.apache.cloudstack.affinity.dao.AffinityGroupVMMapDaoImpl; -import org.apache.cloudstack.api.IdentityService; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.engine.datacenter.entity.api.db.dao.DcDetailsDaoImpl; +import org.apache.cloudstack.engine.orchestration.NetworkOrchestrator; import org.apache.cloudstack.engine.orchestration.service.VolumeOrchestrationService; import org.apache.cloudstack.engine.service.api.OrchestrationService; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; +import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProvider; import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector; import org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator; import org.apache.cloudstack.engine.subsystem.api.storage.TemplateDataFactory; import org.apache.cloudstack.engine.subsystem.api.storage.TemplateService; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory; +import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService; import org.apache.cloudstack.framework.config.ConfigDepot; import org.apache.cloudstack.framework.config.ConfigDepotAdmin; import org.apache.cloudstack.framework.config.dao.ConfigurationDaoImpl; @@ -65,6 +68,7 @@ import org.apache.cloudstack.framework.jobs.impl.AsyncJobManagerImpl; import org.apache.cloudstack.framework.jobs.impl.AsyncJobMonitor; import org.apache.cloudstack.framework.jobs.impl.SyncQueueManager; import org.apache.cloudstack.lb.dao.ApplicationLoadBalancerRuleDaoImpl; +import org.apache.cloudstack.network.element.InternalLoadBalancerElement; import org.apache.cloudstack.network.lb.ApplicationLoadBalancerService; import org.apache.cloudstack.network.lb.InternalLoadBalancerVMManager; import org.apache.cloudstack.network.lb.InternalLoadBalancerVMService; @@ -73,6 +77,9 @@ import org.apache.cloudstack.region.PortableIpDaoImpl; import org.apache.cloudstack.region.PortableIpRangeDaoImpl; import org.apache.cloudstack.region.RegionManager; import org.apache.cloudstack.region.dao.RegionDaoImpl; +import org.apache.cloudstack.spring.lifecycle.registry.ExtensionRegistry; +import org.apache.cloudstack.storage.datastore.PrimaryDataStoreProviderManager; +import org.apache.cloudstack.storage.image.datastore.ImageStoreProviderManager; import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDaoImpl; import org.apache.cloudstack.storage.image.db.ImageStoreDaoImpl; import org.apache.cloudstack.storage.image.db.TemplateDataStoreDaoImpl; @@ -120,6 +127,7 @@ import com.cloud.dc.dao.AccountVlanMapDaoImpl; import com.cloud.dc.dao.ClusterDaoImpl; import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.DataCenterDaoImpl; +import com.cloud.dc.dao.DataCenterDetailsDaoImpl; import com.cloud.dc.dao.DataCenterIpAddressDaoImpl; import com.cloud.dc.dao.DataCenterLinkLocalIpAddressDaoImpl; import com.cloud.dc.dao.DataCenterVnetDaoImpl; @@ -141,11 +149,11 @@ import com.cloud.host.dao.HostDetailsDaoImpl; import com.cloud.host.dao.HostTagsDaoImpl; import com.cloud.hypervisor.HypervisorGuruManagerImpl; import com.cloud.hypervisor.dao.HypervisorCapabilitiesDaoImpl; +import com.cloud.hypervisor.XenServerGuru; import com.cloud.network.ExternalDeviceUsageManager; import com.cloud.network.IpAddress; import com.cloud.network.IpAddressManagerImpl; import com.cloud.network.Ipv6AddressManagerImpl; -import com.cloud.network.NetworkModelImpl; import com.cloud.network.NetworkServiceImpl; import com.cloud.network.NetworkUsageService; import com.cloud.network.StorageNetworkManager; @@ -161,6 +169,7 @@ import com.cloud.network.as.dao.CounterDaoImpl; import com.cloud.network.dao.AccountGuestVlanMapDaoImpl; import com.cloud.network.dao.FirewallRulesCidrsDaoImpl; import com.cloud.network.dao.FirewallRulesDaoImpl; +import com.cloud.network.dao.IPAddressDaoImpl; import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.LBHealthCheckPolicyDaoImpl; import com.cloud.network.dao.LBStickinessPolicyDaoImpl; @@ -183,7 +192,11 @@ import com.cloud.network.dao.Site2SiteVpnGatewayDaoImpl; import com.cloud.network.dao.UserIpv6AddressDaoImpl; import com.cloud.network.dao.VirtualRouterProviderDaoImpl; import com.cloud.network.dao.VpnUserDaoImpl; +import com.cloud.network.element.FirewallServiceProvider; +import com.cloud.network.element.NetworkACLServiceProvider; +import com.cloud.network.element.PortForwardingServiceProvider; import com.cloud.network.element.Site2SiteVpnServiceProvider; +import com.cloud.network.element.VpcProvider; import com.cloud.network.firewall.FirewallManagerImpl; import com.cloud.network.lb.LoadBalancingRulesManagerImpl; import com.cloud.network.router.VpcVirtualNetworkApplianceManagerImpl; @@ -234,7 +247,7 @@ import com.cloud.storage.VolumeApiService; import com.cloud.storage.dao.DiskOfferingDaoImpl; import com.cloud.storage.dao.GuestOSCategoryDaoImpl; import com.cloud.storage.dao.GuestOSDaoImpl; -import com.cloud.storage.dao.LaunchPermissionDao; +import com.cloud.storage.dao.LaunchPermissionDaoImpl; import com.cloud.storage.dao.SnapshotDaoImpl; import com.cloud.storage.dao.SnapshotPolicyDaoImpl; import com.cloud.storage.dao.StoragePoolDetailsDaoImpl; @@ -255,11 +268,9 @@ import com.cloud.template.TemplateApiService; import com.cloud.template.TemplateManager; import com.cloud.user.Account; import com.cloud.user.AccountDetailsDaoImpl; -import com.cloud.user.AccountVO; import com.cloud.user.DomainManagerImpl; import com.cloud.user.ResourceLimitService; import com.cloud.user.User; -import com.cloud.user.UserVO; import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.AccountDaoImpl; import com.cloud.user.dao.SSHKeyPairDaoImpl; @@ -272,12 +283,14 @@ import com.cloud.utils.db.EntityManager; import com.cloud.utils.db.Transaction; import com.cloud.utils.db.TransactionCallbackNoReturn; import com.cloud.utils.db.TransactionStatus; -import com.cloud.uuididentity.dao.IdentityDaoImpl; import com.cloud.vm.ItWorkDaoImpl; +import com.cloud.vm.UserVmManagerImpl; +import com.cloud.vm.VirtualMachineManagerImpl; import com.cloud.vm.dao.ConsoleProxyDaoImpl; import com.cloud.vm.dao.DomainRouterDaoImpl; import com.cloud.vm.dao.InstanceGroupDaoImpl; import com.cloud.vm.dao.InstanceGroupVMMapDaoImpl; +import com.cloud.vm.dao.NicDaoImpl; import com.cloud.vm.dao.NicIpAliasDaoImpl; import com.cloud.vm.dao.NicSecondaryIpDaoImpl; import com.cloud.vm.dao.SecondaryStorageVmDaoImpl; @@ -294,19 +307,19 @@ import com.cloud.vm.snapshot.dao.VMSnapshotDaoImpl; AsyncJobJournalDaoImpl.class, AsyncJobManagerImpl.class, AutoScalePolicyConditionMapDaoImpl.class, AutoScalePolicyDaoImpl.class, AutoScaleVmGroupDaoImpl.class, AutoScaleVmGroupPolicyMapDaoImpl.class, AutoScaleVmProfileDaoImpl.class, CapacityDaoImpl.class, ClusterDaoImpl.class, ClusterDetailsDaoImpl.class, ConditionDaoImpl.class, ConfigurationDaoImpl.class, ConfigurationManagerImpl.class, ConfigurationServerImpl.class, ConsoleProxyDaoImpl.class, - ContrailElementImpl.class, ContrailGuru.class, ContrailManagerImpl.class, CounterDaoImpl.class, DataCenterDaoImpl.class, DataCenterIpAddressDaoImpl.class, + ContrailElementImpl.class, ContrailGuru.class, ContrailManagerImpl.class, CounterDaoImpl.class, DataCenterDaoImpl.class, DataCenterDetailsDaoImpl.class, DataCenterIpAddressDaoImpl.class, DataCenterJoinDaoImpl.class, DataCenterLinkLocalIpAddressDaoImpl.class, DataCenterVnetDaoImpl.class, DcDetailsDaoImpl.class, DedicatedResourceDaoImpl.class, DiskOfferingDaoImpl.class, DiskOfferingJoinDaoImpl.class, DomainDaoImpl.class, DomainManagerImpl.class, DomainRouterDaoImpl.class, DomainRouterJoinDaoImpl.class, - EventDaoImpl.class, EventJoinDaoImpl.class, EventUtils.class, EventUtils.class, FirewallManagerImpl.class, FirewallRulesCidrsDaoImpl.class, + EventDaoImpl.class, EventJoinDaoImpl.class, EventUtils.class, ExtensionRegistry.class, FirewallManagerImpl.class, FirewallRulesCidrsDaoImpl.class, FirewallRulesDaoImpl.class, GuestOSCategoryDaoImpl.class, GuestOSDaoImpl.class, HostDaoImpl.class, HostDetailsDaoImpl.class, HostJoinDaoImpl.class, HostPodDaoImpl.class, HostTagsDaoImpl.class, HostTransferMapDaoImpl.class, HypervisorCapabilitiesDaoImpl.class, HypervisorGuruManagerImpl.class, - IdentityDaoImpl.class, ImageStoreDaoImpl.class, ImageStoreJoinDaoImpl.class, InstanceGroupDaoImpl.class, InstanceGroupJoinDaoImpl.class, - InstanceGroupVMMapDaoImpl.class, IpAddressManagerImpl.class, Ipv6AddressManagerImpl.class, ItWorkDaoImpl.class, LBHealthCheckPolicyDaoImpl.class, - LBStickinessPolicyDaoImpl.class, LaunchPermissionDao.class, LoadBalancerDaoImpl.class, LoadBalancerVMMapDaoImpl.class, LoadBalancingRulesManagerImpl.class, + ImageStoreDaoImpl.class, ImageStoreJoinDaoImpl.class, InstanceGroupDaoImpl.class, InstanceGroupJoinDaoImpl.class, + InstanceGroupVMMapDaoImpl.class, InternalLoadBalancerElement.class, IPAddressDaoImpl.class, IpAddressManagerImpl.class, Ipv6AddressManagerImpl.class, ItWorkDaoImpl.class, LBHealthCheckPolicyDaoImpl.class, + LBStickinessPolicyDaoImpl.class, LaunchPermissionDaoImpl.class, LoadBalancerDaoImpl.class, LoadBalancerVMMapDaoImpl.class, LoadBalancingRulesManagerImpl.class, ManagementServerHostDaoImpl.class, MockAccountManager.class, NetworkACLDaoImpl.class, NetworkACLItemDaoImpl.class, NetworkACLManagerImpl.class, - NetworkAccountDaoImpl.class, NetworkDaoImpl.class, NetworkDomainDaoImpl.class, NetworkModelImpl.class, NetworkOfferingDaoImpl.class, - NetworkOfferingDetailsDaoImpl.class, NetworkOfferingServiceMapDaoImpl.class, NetworkOpDaoImpl.class, NetworkRuleConfigDaoImpl.class, NetworkServiceImpl.class, - NetworkServiceMapDaoImpl.class, NicIpAliasDaoImpl.class, NicSecondaryIpDaoImpl.class, PhysicalNetworkDaoImpl.class, PhysicalNetworkServiceProviderDaoImpl.class, + NetworkAccountDaoImpl.class, NetworkDaoImpl.class, NetworkDomainDaoImpl.class, NetworkOfferingDaoImpl.class, + NetworkOfferingDetailsDaoImpl.class, NetworkOfferingServiceMapDaoImpl.class, NetworkOpDaoImpl.class, NetworkOrchestrator.class, NetworkRuleConfigDaoImpl.class, NetworkServiceImpl.class, + NetworkServiceMapDaoImpl.class, NicDaoImpl.class, NicIpAliasDaoImpl.class, NicSecondaryIpDaoImpl.class, PhysicalNetworkDaoImpl.class, PhysicalNetworkServiceProviderDaoImpl.class, PhysicalNetworkTrafficTypeDaoImpl.class, PlannerHostReservationDaoImpl.class, PodVlanDaoImpl.class, PodVlanMapDaoImpl.class, PortForwardingRulesDaoImpl.class, PortableIpDaoImpl.class, PortableIpRangeDaoImpl.class, PrimaryDataStoreDaoImpl.class, PrivateIpDaoImpl.class, ProjectAccountDaoImpl.class, ProjectAccountJoinDaoImpl.class, ProjectInvitationDaoImpl.class, ProjectDaoImpl.class, ProjectInvitationJoinDaoImpl.class, ProjectJoinDaoImpl.class, @@ -318,11 +331,11 @@ import com.cloud.vm.snapshot.dao.VMSnapshotDaoImpl; SnapshotDaoImpl.class, SnapshotPolicyDaoImpl.class, StaticRouteDaoImpl.class, StatsCollector.class, StoragePoolDetailsDaoImpl.class, StoragePoolHostDaoImpl.class, StoragePoolJoinDaoImpl.class, SyncQueueItemDaoImpl.class, TemplateDataStoreDaoImpl.class, TemplateJoinDaoImpl.class, UploadDaoImpl.class, UsageEventDaoImpl.class, UserAccountJoinDaoImpl.class, UserDaoImpl.class, UserIpv6AddressDaoImpl.class, UserStatisticsDaoImpl.class, UserStatsLogDaoImpl.class, - UserVmCloneSettingDaoImpl.class, UserVmDaoImpl.class, UserVmDetailsDaoImpl.class, UserVmJoinDaoImpl.class, VMInstanceDaoImpl.class, VMSnapshotDaoImpl.class, - VMTemplateDaoImpl.class, VMTemplateDetailsDaoImpl.class, VMTemplateHostDaoImpl.class, VMTemplateZoneDaoImpl.class, VirtualRouterProviderDaoImpl.class, + UserVmCloneSettingDaoImpl.class, UserVmDaoImpl.class, UserVmDetailsDaoImpl.class, UserVmJoinDaoImpl.class, UserVmManagerImpl.class, VMInstanceDaoImpl.class, VMSnapshotDaoImpl.class, + VMTemplateDaoImpl.class, VMTemplateDetailsDaoImpl.class, VMTemplateHostDaoImpl.class, VMTemplateZoneDaoImpl.class, VirtualMachineManagerImpl.class, VirtualRouterProviderDaoImpl.class, VlanDaoImpl.class, VmDiskStatisticsDaoImpl.class, VmRulesetLogDaoImpl.class, VolumeDaoImpl.class, VolumeHostDaoImpl.class, VolumeJoinDaoImpl.class, VpcDaoImpl.class, VpcGatewayDaoImpl.class, VpcManagerImpl.class, VpcOfferingDaoImpl.class, VpcOfferingServiceMapDaoImpl.class, VpcServiceMapDaoImpl.class, - VpcVirtualNetworkApplianceManagerImpl.class, VpnUserDaoImpl.class}, includeFilters = {@Filter(value = IntegrationTestConfiguration.ComponentFilter.class, + VpcVirtualNetworkApplianceManagerImpl.class, VpnUserDaoImpl.class, XenServerGuru.class}, includeFilters = {@Filter(value = IntegrationTestConfiguration.ComponentFilter.class, type = FilterType.CUSTOM)}, useDefaultFilters = false) @Configuration public class IntegrationTestConfiguration { @@ -714,5 +727,36 @@ public class IntegrationTestConfiguration { public VolumeOrchestrationService volumeOrchestrationService() { return Mockito.mock(VolumeOrchestrationService.class); } - + @Bean + public FirewallServiceProvider firewallServiceProvider() { + return Mockito.mock(FirewallServiceProvider.class); + } + @Bean + public PortForwardingServiceProvider portForwardingServiceProvider() { + return Mockito.mock(PortForwardingServiceProvider.class); + } + @Bean + public NetworkACLServiceProvider networkACLServiceProvider() { + return Mockito.mock(NetworkACLServiceProvider.class); + } + @Bean + public VpcProvider vpcProvier() { + return Mockito.mock(VpcProvider.class); + } + @Bean + public VolumeService volumeService() { + return Mockito.mock(VolumeService.class); + } + @Bean + public PrimaryDataStoreProviderManager privateDataStoreProviderManager() { + return Mockito.mock(PrimaryDataStoreProviderManager.class); + } + @Bean + public ImageStoreProviderManager imageStoreProviderManager() { + return Mockito.mock(ImageStoreProviderManager.class); + } + @Bean + public DataStoreProvider dataStoreProvider() { + return Mockito.mock(DataStoreProvider.class); + } } diff --git a/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/ManagementServerMock.java b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/ManagementServerMock.java index c449b8a6c0a..50419ea1b36 100644 --- a/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/ManagementServerMock.java +++ b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/ManagementServerMock.java @@ -116,10 +116,10 @@ public class ManagementServerMock { private DataCenterVO _zone; private PhysicalNetwork _znet; - private long _host_id = -1L; + private long _hostId = -1L; // TODO: Use the name parameter to retrieve the @Parameter annotation. - static void setParameter(BaseCmd cmd, String name, BaseCmd.CommandType field_type, Object value) { + static void setParameter(BaseCmd cmd, String name, BaseCmd.CommandType fieldType, Object value) { Class cls = cmd.getClass(); Field field; try { @@ -129,7 +129,7 @@ public class ManagementServerMock { return; } field.setAccessible(true); - switch (field_type) { + switch (fieldType) { case STRING: try { field.set(cmd, value); @@ -169,11 +169,11 @@ public class ManagementServerMock { private void createHost() { HostVO host = - new HostVO(_host_id, "aa01", Type.BaremetalDhcp, "192.168.1.1", "255.255.255.0", null, null, null, null, null, null, null, null, null, null, + new HostVO(_hostId, "aa01", Type.BaremetalDhcp, "192.168.1.1", "255.255.255.0", null, null, null, null, null, null, null, null, null, null, UUID.randomUUID().toString(), Status.Up, "1.0", null, null, _zone.getId(), null, 0, 0, "aa", 0, StoragePoolType.NetworkFilesystem); host.setResourceState(ResourceState.Enabled); _hostDao.persist(host); - _host_id = host.getId(); + _hostId = host.getId(); } private void createPublicVlanIpRange() { @@ -241,7 +241,7 @@ public class ManagementServerMock { new UserVmVO(id, name, name, tmpl.getId(), HypervisorType.XenServer, tmpl.getGuestOSId(), false, false, _zone.getDomainId(), Account.ACCOUNT_ID_SYSTEM, small.getId(), null, name, null); vm.setState(com.cloud.vm.VirtualMachine.State.Running); - vm.setHostId(_host_id); + vm.setHostId(_hostId); vm.setDataCenterId(network.getDataCenterId()); _userVmDao.persist(vm); @@ -256,7 +256,7 @@ public class ManagementServerMock { } private void deleteHost() { - _hostDao.remove(_host_id); + _hostDao.remove(_hostId); } @@ -327,17 +327,17 @@ public class ManagementServerMock { _znet = _networkService.getPhysicalNetwork(id); List nets = _physicalNetworkDao.listByZoneAndTrafficType(_zone.getId(), TrafficType.Public); if (nets == null || nets.isEmpty()) { - _networkService.addTrafficTypeToPhysicalNetwork(_znet.getId(), TrafficType.Public.toString(), null, null, null, null, null, null); + _networkService.addTrafficTypeToPhysicalNetwork(_znet.getId(), TrafficType.Public.toString(), "vlan", null, null, null, null, null, null); } } catch (InvalidParameterValueException e) { List isolationMethods = new ArrayList(); - isolationMethods.add("GRE"); + isolationMethods.add("L3VPN"); _znet = _networkService.createPhysicalNetwork(_zone.getId(), null, null, isolationMethods, BroadcastDomainRange.ZONE.toString(), _zone.getDomainId(), null, "znet"); List nets = _physicalNetworkDao.listByZoneAndTrafficType(_zone.getId(), TrafficType.Public); if (nets == null || nets.isEmpty()) { - _networkService.addTrafficTypeToPhysicalNetwork(_znet.getId(), TrafficType.Public.toString(), null, null, null, null, null, null); + _networkService.addTrafficTypeToPhysicalNetwork(_znet.getId(), TrafficType.Public.toString(), "vlan", null, null, null, null, null, null); } } if (_znet.getState() != PhysicalNetwork.State.Enabled) { @@ -353,14 +353,14 @@ public class ManagementServerMock { } } if (!found) { - _networkService.addTrafficTypeToPhysicalNetwork(_znet.getId(), TrafficType.Guest.toString(), null, null, null, null, null, null); + _networkService.addTrafficTypeToPhysicalNetwork(_znet.getId(), TrafficType.Guest.toString(), "vlan", null, null, null, null, null, null); } Pair, Integer> providers = - _networkService.listNetworkServiceProviders(_znet.getId(), Provider.JuniperContrail.getName(), null, null, null); + _networkService.listNetworkServiceProviders(_znet.getId(), Provider.JuniperContrailRouter.getName(), null, null, null); if (providers.second() == 0) { - s_logger.debug("Add " + Provider.JuniperContrail.getName() + " to network " + _znet.getName()); - PhysicalNetworkServiceProvider provider = _networkService.addProviderToPhysicalNetwork(_znet.getId(), Provider.JuniperContrail.getName(), null, null); + s_logger.debug("Add " + Provider.JuniperContrailRouter.getName() + " to network " + _znet.getName()); + PhysicalNetworkServiceProvider provider = _networkService.addProviderToPhysicalNetwork(_znet.getId(), Provider.JuniperContrailRouter.getName(), null, null); _networkService.updateNetworkServiceProvider(provider.getId(), PhysicalNetworkServiceProvider.State.Enabled.toString(), null); } else { PhysicalNetworkServiceProvider provider = providers.first().get(0); @@ -372,7 +372,7 @@ public class ManagementServerMock { providers = _networkService.listNetworkServiceProviders(_znet.getId(), null, PhysicalNetworkServiceProvider.State.Enabled.toString(), null, null); s_logger.debug(_znet.getName() + " has " + providers.second().toString() + " Enabled providers"); for (PhysicalNetworkServiceProvider provider : providers.first()) { - if (provider.getProviderName().equals(Provider.JuniperContrail.getName())) { + if (provider.getProviderName().equals(Provider.JuniperContrailRouter.getName())) { continue; } s_logger.debug("Disabling " + provider.getProviderName()); diff --git a/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/MockAccountManager.java b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/MockAccountManager.java index 2f81688c0f8..fa7be5827c5 100644 --- a/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/MockAccountManager.java +++ b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/MockAccountManager.java @@ -34,7 +34,6 @@ import org.apache.cloudstack.api.command.admin.user.RegisterCmd; import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd; import org.apache.cloudstack.context.CallContext; -import com.cloud.api.query.dao.AccountJoinDao; import com.cloud.api.query.vo.ControlledViewEntity; import com.cloud.configuration.ResourceLimit; import com.cloud.configuration.dao.ResourceCountDao; @@ -68,8 +67,6 @@ public class MockAccountManager extends ManagerBase implements AccountManager { @Inject ResourceCountDao _resourceCountDao; - @Inject - AccountJoinDao _accountJoinDao; @Inject UserDao _userDao; diff --git a/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/NetworkProviderTest.java b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/NetworkProviderTest.java index 7c5e3c0aec7..95204900f72 100644 --- a/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/NetworkProviderTest.java +++ b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/NetworkProviderTest.java @@ -115,27 +115,27 @@ public class NetworkProviderTest extends TestCase { private ManagementServerMock _server; private ApiConnector _api; - private static int _mysql_server_port; - private static long _msId; - private static Merovingian2 _lockMaster; - public static boolean _initDone = false; + private static int s_mysqlSrverPort; + private static long s_msId; + private static Merovingian2 s_lockMaster; + public static boolean s_initDone = false; @BeforeClass public static void globalSetUp() throws Exception { ApiConnectorFactory.setImplementation(ApiConnectorMock.class); s_logger.info("mysql server is getting launched "); - _mysql_server_port = TestDbSetup.init(null); - s_logger.info("mysql server launched on port " + _mysql_server_port); + s_mysqlSrverPort = TestDbSetup.init(null); + s_logger.info("mysql server launched on port " + s_mysqlSrverPort); - _msId = ManagementServerNode.getManagementServerId(); - _lockMaster = Merovingian2.createLockMaster(_msId); + s_msId = ManagementServerNode.getManagementServerId(); + s_lockMaster = Merovingian2.createLockMaster(s_msId); } @AfterClass public static void globalTearDown() throws Exception { - _lockMaster.cleanupForServer(_msId); + s_lockMaster.cleanupForServer(s_msId); JmxUtil.unregisterMBean("Locks", "Locks"); - _lockMaster = null; + s_lockMaster = null; AbstractApplicationContext ctx = (AbstractApplicationContext)ComponentContext.getApplicationContext(); Map lifecycleComponents = ctx.getBeansOfType(ComponentLifecycle.class); @@ -144,8 +144,8 @@ public class NetworkProviderTest extends TestCase { } ctx.close(); - s_logger.info("destroying mysql server instance running at port <" + _mysql_server_port + ">"); - TestDbSetup.destroy(_mysql_server_port, null); + s_logger.info("destroying mysql server instance running at port <" + s_mysqlSrverPort + ">"); + TestDbSetup.destroy(s_mysqlSrverPort, null); } @Override @@ -162,8 +162,8 @@ public class NetworkProviderTest extends TestCase { CallContext.register(user, system); _server = ComponentContext.inject(new ManagementServerMock()); - _server.initialize(!_initDone); - _initDone = false; + _server.initialize(!s_initDone); + s_initDone = false; _api = _contrailMgr.getApiConnector(); } @@ -179,7 +179,7 @@ public class NetworkProviderTest extends TestCase { List list = _networkService.getIsolatedNetworksOwnedByAccountInZone(zone.getId(), system); for (Network net : list) { s_logger.debug("Delete network " + net.getName()); - _networkService.deleteNetwork(net.getId()); + _networkService.deleteNetwork(net.getId(), false); } } @@ -204,7 +204,7 @@ public class NetworkProviderTest extends TestCase { ManagementServerMock.setParameter(cmd, "accountName", BaseCmd.CommandType.STRING, system.getAccountName()); ManagementServerMock.setParameter(cmd, ApiConstants.NAME, BaseCmd.CommandType.STRING, name); ManagementServerMock.setParameter(cmd, "displayText", BaseCmd.CommandType.STRING, "test network"); - ManagementServerMock.setParameter(cmd, "networkOfferingId", BaseCmd.CommandType.LONG, _contrailMgr.getOffering().getId()); + ManagementServerMock.setParameter(cmd, "networkOfferingId", BaseCmd.CommandType.LONG, _contrailMgr.getRouterOffering().getId()); ManagementServerMock.setParameter(cmd, "zoneId", BaseCmd.CommandType.LONG, zone.getId()); ManagementServerMock.setParameter(cmd, ApiConstants.GATEWAY, BaseCmd.CommandType.STRING, "10.0.1.254"); ManagementServerMock.setParameter(cmd, ApiConstants.NETMASK, BaseCmd.CommandType.STRING, "255.255.255.0"); diff --git a/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/PublicNetworkTest.java b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/PublicNetworkTest.java index 9901241c6f5..c85bc659e31 100644 --- a/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/PublicNetworkTest.java +++ b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/PublicNetworkTest.java @@ -67,10 +67,10 @@ public class PublicNetworkTest extends TestCase { @Inject public NetworkDao _networksDao; - private static boolean _initDone = false; - private static int _mysql_server_port; - private static long _msId; - private static Merovingian2 _lockMaster; + private static boolean s_initDone = false; + private static int s_mysqlServerPort; + private static long s_msId; + private static Merovingian2 s_lockMaster; private ManagementServerMock _server; private ApiConnector _spy; @@ -78,17 +78,17 @@ public class PublicNetworkTest extends TestCase { public static void globalSetUp() throws Exception { ApiConnectorFactory.setImplementation(ApiConnectorMockito.class); s_logger.info("mysql server is getting launched "); - _mysql_server_port = TestDbSetup.init(null); - s_logger.info("mysql server launched on port " + _mysql_server_port); - _msId = ManagementServerNode.getManagementServerId(); - _lockMaster = Merovingian2.createLockMaster(_msId); + s_mysqlServerPort = TestDbSetup.init(null); + s_logger.info("mysql server launched on port " + s_mysqlServerPort); + s_msId = ManagementServerNode.getManagementServerId(); + s_lockMaster = Merovingian2.createLockMaster(s_msId); } @AfterClass public static void globalTearDown() throws Exception { - _lockMaster.cleanupForServer(_msId); + s_lockMaster.cleanupForServer(s_msId); JmxUtil.unregisterMBean("Locks", "Locks"); - _lockMaster = null; + s_lockMaster = null; AbstractApplicationContext ctx = (AbstractApplicationContext)ComponentContext.getApplicationContext(); Map lifecycleComponents = ctx.getBeansOfType(ComponentLifecycle.class); @@ -97,8 +97,8 @@ public class PublicNetworkTest extends TestCase { } ctx.close(); - s_logger.info("destroying mysql server instance running at port <" + _mysql_server_port + ">"); - TestDbSetup.destroy(_mysql_server_port, null); + s_logger.info("destroying mysql server instance running at port <" + s_mysqlServerPort + ">"); + TestDbSetup.destroy(s_mysqlServerPort, null); } @Override @@ -112,8 +112,8 @@ public class PublicNetworkTest extends TestCase { } _server = ComponentContext.inject(new ManagementServerMock()); - _server.initialize(!_initDone); - _initDone = false; + _server.initialize(!s_initDone); + s_initDone = false; _spy = ((ApiConnectorMockito)_contrailMgr.getApiConnector()).getSpy(); } diff --git a/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/model/VirtualMachineModelTest.java b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/model/VirtualMachineModelTest.java new file mode 100644 index 00000000000..f85beb62fe6 --- /dev/null +++ b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/model/VirtualMachineModelTest.java @@ -0,0 +1,124 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package org.apache.cloudstack.network.contrail.model; + +import static org.mockito.Matchers.anyLong; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.util.UUID; + +import junit.framework.TestCase; +import net.juniper.contrail.api.ApiConnector; +import net.juniper.contrail.api.ApiConnectorMock; + +import org.apache.log4j.Logger; +import org.junit.Test; + +import org.apache.cloudstack.network.contrail.management.ContrailManagerImpl; +import org.apache.cloudstack.network.contrail.management.ModelDatabase; + +import com.cloud.network.Network; +import com.cloud.network.dao.NetworkVO; +import com.cloud.vm.VMInstanceVO; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.dao.UserVmDao; + +public class VirtualMachineModelTest extends TestCase { + private static final Logger s_logger = + Logger.getLogger(VirtualMachineModelTest.class); + + @Test + public void testVirtualMachineDBLookup() { + ModelDatabase db = new ModelDatabase(); + VMInstanceVO vm = mock(VMInstanceVO.class); + + // Create 3 dummy Virtual Machine model objects + // Add these models to database. + // Each VM is identified by unique UUId. + VirtualMachineModel vm0 = new VirtualMachineModel(vm, "fbc1f8fa-4b78-45ee-bba0-b551dbf72353"); + db.getVirtualMachines().add(vm0); + + VirtualMachineModel vm1 = new VirtualMachineModel(vm, "fbc1f8fa-4b78-45ee-bba0-b551dbf83464"); + db.getVirtualMachines().add(vm1); + + VirtualMachineModel vm2 = new VirtualMachineModel(vm, "fbc1f8fa-4b78-45ee-bba0-b551dbf94575"); + db.getVirtualMachines().add(vm2); + + s_logger.debug("No of Vitual Machines added to database : " + db.getVirtualMachines().size()); + + assertEquals(3, db.getVirtualMachines().size()); + + assertSame(vm0, db.lookupVirtualMachine("fbc1f8fa-4b78-45ee-bba0-b551dbf72353")); + assertSame(vm1, db.lookupVirtualMachine("fbc1f8fa-4b78-45ee-bba0-b551dbf83464")); + assertSame(vm2, db.lookupVirtualMachine("fbc1f8fa-4b78-45ee-bba0-b551dbf94575")); + } + + @Test + public void testCreateVirtualMachine() throws IOException { + + String uuid = UUID.randomUUID().toString(); + ContrailManagerImpl contrailMgr = mock(ContrailManagerImpl.class); + ModelController controller = mock(ModelController.class); + ApiConnector api = new ApiConnectorMock(null, 0); + when(controller.getManager()).thenReturn(contrailMgr); + when(controller.getApiAccessor()).thenReturn(api); + + // Create Virtual-Network (VN) + NetworkVO network = mock(NetworkVO.class); + when(network.getName()).thenReturn("testnetwork"); + when(network.getState()).thenReturn(Network.State.Allocated); + when(network.getGateway()).thenReturn("10.1.1.1"); + when(network.getCidr()).thenReturn("10.1.1.0/24"); + when(network.getPhysicalNetworkId()).thenReturn(42L); + when(network.getDomainId()).thenReturn(10L); + when(network.getAccountId()).thenReturn(42L); + + when(contrailMgr.getCanonicalName(network)).thenReturn("testnetwork"); + when(contrailMgr.getProjectId(network.getDomainId(), network.getAccountId())).thenReturn("testProjectId"); + + // Create Virtual-Machine (VM) + VMInstanceVO vm = mock(VMInstanceVO.class); + when(vm.getInstanceName()).thenReturn("testVM1"); + when(vm.getState()).thenReturn(VirtualMachine.State.Starting); + when(vm.getDomainId()).thenReturn(10L); + when(vm.getAccountId()).thenReturn(42L); + + UserVmDao VmDao = mock(UserVmDao.class); + when(VmDao.findById(anyLong())).thenReturn(null); + when(controller.getVmDao()).thenReturn(VmDao); + + VirtualMachineModel vmModel = new VirtualMachineModel(vm, uuid); + + assertEquals(vmModel.getInstanceName(), "testVM1"); + assertEquals(vmModel.getUuid(), uuid); + + vmModel.build(controller, vm); + try { + vmModel.update(controller); + } catch (Exception ex) { + fail("virtual-network update failed "); + } + + //verify + assertTrue(vmModel.verify(controller)); + + } + +} diff --git a/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/VirtualNetworkModelTest.java b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/model/VirtualNetworkModelTest.java similarity index 52% rename from plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/VirtualNetworkModelTest.java rename to plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/model/VirtualNetworkModelTest.java index 09385417440..b1b5ae1ebff 100644 --- a/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/VirtualNetworkModelTest.java +++ b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/model/VirtualNetworkModelTest.java @@ -15,18 +15,26 @@ // specific language governing permissions and limitations // under the License. -package org.apache.cloudstack.network.contrail.management; +package org.apache.cloudstack.network.contrail.model; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.IOException; import java.util.UUID; import junit.framework.TestCase; +import net.juniper.contrail.api.ApiConnector; +import net.juniper.contrail.api.ApiConnectorMock; import org.apache.log4j.Logger; import org.junit.Test; -import org.mockito.Mockito; -import org.apache.cloudstack.network.contrail.model.VirtualNetworkModel; +import org.apache.cloudstack.network.contrail.management.ContrailManager; +import org.apache.cloudstack.network.contrail.management.ContrailManagerImpl; +import org.apache.cloudstack.network.contrail.management.ModelDatabase; +import com.cloud.network.Network.State; import com.cloud.network.Networks.TrafficType; import com.cloud.network.dao.NetworkVO; @@ -36,7 +44,7 @@ public class VirtualNetworkModelTest extends TestCase { @Test public void testDBLookup() { ModelDatabase db = new ModelDatabase(); - NetworkVO network = Mockito.mock(NetworkVO.class); + NetworkVO network = mock(NetworkVO.class); VirtualNetworkModel storageModel = new VirtualNetworkModel(network, null, ContrailManager.managementNetworkName, TrafficType.Storage); db.getVirtualNetworks().add(storageModel); VirtualNetworkModel mgmtModel = new VirtualNetworkModel(network, null, ContrailManager.managementNetworkName, TrafficType.Management); @@ -46,6 +54,7 @@ public class VirtualNetworkModelTest extends TestCase { VirtualNetworkModel guestModel2 = new VirtualNetworkModel(network, UUID.randomUUID().toString(), "test", TrafficType.Guest); db.getVirtualNetworks().add(guestModel2); s_logger.debug("networks: " + db.getVirtualNetworks().size()); + s_logger.debug("No of Vitual Networks added to database : " + db.getVirtualNetworks().size()); assertEquals(4, db.getVirtualNetworks().size()); assertSame(storageModel, db.lookupVirtualNetwork(null, storageModel.getName(), TrafficType.Storage)); assertSame(mgmtModel, db.lookupVirtualNetwork(null, mgmtModel.getName(), TrafficType.Management)); @@ -53,4 +62,41 @@ public class VirtualNetworkModelTest extends TestCase { assertSame(guestModel2, db.lookupVirtualNetwork(guestModel2.getUuid(), null, TrafficType.Guest)); } + @Test + public void testCreateVirtualNetwork() throws IOException { + + String uuid = UUID.randomUUID().toString(); + ContrailManagerImpl contrailMgr = mock(ContrailManagerImpl.class); + ModelController controller = mock(ModelController.class); + ApiConnector api = new ApiConnectorMock(null, 0); + when(controller.getManager()).thenReturn(contrailMgr); + when(controller.getApiAccessor()).thenReturn(api); + + // Create Virtual-Network (VN) + NetworkVO network = mock(NetworkVO.class); + when(network.getName()).thenReturn("testnetwork"); + when(network.getState()).thenReturn(State.Allocated); + when(network.getGateway()).thenReturn("10.1.1.1"); + when(network.getCidr()).thenReturn("10.1.1.0/24"); + when(network.getPhysicalNetworkId()).thenReturn(42L); + when(network.getDomainId()).thenReturn(10L); + when(network.getAccountId()).thenReturn(42L); + + when(contrailMgr.getCanonicalName(network)).thenReturn("testnetwork"); + when(contrailMgr.getProjectId(network.getDomainId(), network.getAccountId())).thenReturn("testProjectId"); + + VirtualNetworkModel vnModel = new VirtualNetworkModel(network, uuid, "testnetwork", TrafficType.Guest); + + assertEquals(vnModel.getName(), "testnetwork"); + assertEquals(vnModel.getUuid(), uuid); + + vnModel.build(controller, network); + try { + vnModel.update(controller); + } catch (Exception ex) { + fail("virtual-network update failed "); + } + assertTrue(vnModel.verify(controller)); + } + } diff --git a/plugins/network-elements/juniper-contrail/test/resources/commonContext.xml b/plugins/network-elements/juniper-contrail/test/resources/commonContext.xml index c57751328f9..6f46f6dde4e 100644 --- a/plugins/network-elements/juniper-contrail/test/resources/commonContext.xml +++ b/plugins/network-elements/juniper-contrail/test/resources/commonContext.xml @@ -1,16 +1,15 @@ - + - - + + - - - + + + + - + - + - - - + + + + + - + + - - - - - - - - - + + - + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java b/plugins/network-elements/juniper-srx/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java index 82f701b4a06..cb31ea440a1 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java @@ -218,14 +218,13 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan return false; } - if (rules != null && rules.size() == 1 ) { + if (rules != null && rules.size() == 1) { // for SRX no need to add default egress rule to DENY traffic if (rules.get(0).getTrafficType() == FirewallRule.TrafficType.Egress && rules.get(0).getType() == FirewallRule.FirewallRuleType.System && - ! _networkManager.getNetworkEgressDefaultPolicy(config.getId())) + !_networkManager.getNetworkEgressDefaultPolicy(config.getId())) return true; } - return applyFirewallRules(config, rules); } diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/network/resource/JuniperSrxResource.java b/plugins/network-elements/juniper-srx/src/com/cloud/network/resource/JuniperSrxResource.java index b828ab66db6..ed6011b9a7a 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/network/resource/JuniperSrxResource.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/network/resource/JuniperSrxResource.java @@ -104,7 +104,7 @@ public class JuniperSrxResource implements ServerResource { private UsageFilter _usageFilterVlanOutput; private UsageFilter _usageFilterIPInput; private UsageFilter _usageFilterIPOutput; - private final Logger s_logger = Logger.getLogger(JuniperSrxResource.class); + private static final Logger s_logger = Logger.getLogger(JuniperSrxResource.class); private enum SrxXml { LOGIN("login.xml"), @@ -173,7 +173,7 @@ public class JuniperSrxResource implements ServerResource { private final String scriptsDir = "scripts/network/juniper"; private final String xml; - private final Logger s_logger = Logger.getLogger(JuniperSrxResource.class); + private static final Logger s_logger = Logger.getLogger(JuniperSrxResource.class); private SrxXml(String filename) { xml = getXml(filename); @@ -854,9 +854,9 @@ public class JuniperSrxResource implements ServerResource { addEgressSecurityPolicyAndApplications(SecurityPolicyType.SECURITYPOLICY_EGRESS, guestVlan, extractApplications(activeRulesForGuestNw), extractCidrs(activeRulesForGuestNw), defaultEgressPolicy); - /* Adding default policy rules are required because the order of rules is important. - * Depending on the rules order the traffic accept/drop is performed - */ + /* Adding default policy rules are required because the order of rules is important. + * Depending on the rules order the traffic accept/drop is performed + */ removeEgressSecurityPolicyAndApplications(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT, guestVlan, cidrs, defaultEgressPolicy); addEgressSecurityPolicyAndApplications(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT, guestVlan, applications, cidrs, defaultEgressPolicy); } @@ -2809,7 +2809,7 @@ public class JuniperSrxResource implements ServerResource { if (type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS) || type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT)) { xml = replaceXmlValue(xml, "from-zone", _privateZone); xml = replaceXmlValue(xml, "to-zone", _publicZone); - if (cidrs == null) { + if (cidrs == null || cidrs.size() == 0) { srcAddrs = "any"; } else { for (String cidr : cidrs) { diff --git a/plugins/network-elements/netscaler/src/com/cloud/api/commands/AddNetscalerLoadBalancerCmd.java b/plugins/network-elements/netscaler/src/com/cloud/api/commands/AddNetscalerLoadBalancerCmd.java index 1237e7f7104..b744fffdcb1 100644 --- a/plugins/network-elements/netscaler/src/com/cloud/api/commands/AddNetscalerLoadBalancerCmd.java +++ b/plugins/network-elements/netscaler/src/com/cloud/api/commands/AddNetscalerLoadBalancerCmd.java @@ -86,9 +86,9 @@ public class AddNetscalerLoadBalancerCmd extends BaseAsyncCmd { private String gslbSitePrivateIp; @Parameter(name = ApiConstants.EXCLUSIVE_GSLB_PROVIDER, - type = CommandType.BOOLEAN, - required = false, - description = "true if NetScaler device being added is for providing GSLB service exclusively and can not be used for LB") + type = CommandType.BOOLEAN, + required = false, + description = "true if NetScaler device being added is for providing GSLB service exclusively and can not be used for LB") private Boolean isExclusiveGslbProvider; ///////////////////////////////////////////////////// diff --git a/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java b/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java index a2bda9042d9..5199f602eb3 100644 --- a/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java +++ b/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java @@ -383,7 +383,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl if (cmd.isExclusiveGslbProvider() && !cmd.isGslbProvider()) { throw new InvalidParameterValueException("NetScaler can be provisioned to be exclusive GSLB service provider" + - " only if its being configured as GSLB service provider also."); + " only if its being configured as GSLB service provider also."); } ExternalLoadBalancerDeviceVO lbDeviceVO = diff --git a/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetscalerResource.java b/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetscalerResource.java index e8272986c99..54e5d50f2ba 100644 --- a/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetscalerResource.java +++ b/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetscalerResource.java @@ -16,7 +16,6 @@ // under the License. package com.cloud.network.resource; -import java.io.PrintWriter; import java.io.StringWriter; import java.security.cert.Certificate; import java.util.ArrayList; @@ -28,16 +27,9 @@ import java.util.Map; import javax.naming.ConfigurationException; -import com.citrix.netscaler.nitro.resource.config.ssl.sslcertkey; -import com.citrix.netscaler.nitro.resource.config.ssl.sslcertkey_sslvserver_binding; -import com.citrix.netscaler.nitro.resource.config.ssl.sslcertlink; -import com.citrix.netscaler.nitro.resource.config.ssl.sslvserver_sslcertkey_binding; -import com.cloud.network.lb.LoadBalancingRule.LbSslCert; -import com.cloud.utils.security.CertificateHelper; -import com.cloud.utils.ssh.SshHelper; -import com.google.common.collect.Lists; import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.log4j.Logger; +import org.bouncycastle.openssl.PEMWriter; import com.citrix.netscaler.nitro.exception.nitro_exception; import com.citrix.netscaler.nitro.resource.base.base_response; @@ -73,6 +65,10 @@ import com.citrix.netscaler.nitro.resource.config.ns.nshardware; import com.citrix.netscaler.nitro.resource.config.ns.nsip; import com.citrix.netscaler.nitro.resource.config.ns.nstimer; import com.citrix.netscaler.nitro.resource.config.ns.nstimer_autoscalepolicy_binding; +import com.citrix.netscaler.nitro.resource.config.ssl.sslcertkey; +import com.citrix.netscaler.nitro.resource.config.ssl.sslcertkey_sslvserver_binding; +import com.citrix.netscaler.nitro.resource.config.ssl.sslcertlink; +import com.citrix.netscaler.nitro.resource.config.ssl.sslvserver_sslcertkey_binding; import com.citrix.netscaler.nitro.resource.stat.lb.lbvserver_stats; import com.citrix.netscaler.nitro.service.nitro_service; import com.citrix.netscaler.nitro.util.filtervalue; @@ -80,6 +76,7 @@ import com.citrix.sdx.nitro.resource.config.device_profile; import com.citrix.sdx.nitro.resource.config.mps; import com.citrix.sdx.nitro.resource.config.ns; import com.citrix.sdx.nitro.resource.config.xen_vpx_image; +import com.google.common.collect.Lists; import com.google.gson.Gson; import org.apache.cloudstack.api.ApiConstants; @@ -121,6 +118,7 @@ import com.cloud.agent.api.to.LoadBalancerTO.StickinessPolicyTO; import com.cloud.agent.api.to.StaticNatRuleTO; import com.cloud.host.Host; import com.cloud.host.Host.Type; +import com.cloud.network.lb.LoadBalancingRule.LbSslCert; import com.cloud.network.rules.LbStickinessMethod.StickinessMethodType; import com.cloud.resource.ServerResource; import com.cloud.serializer.GsonHelper; @@ -128,7 +126,8 @@ import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.exception.ExecutionException; import com.cloud.utils.net.NetUtils; -import org.bouncycastle.openssl.PEMWriter; +import com.cloud.utils.security.CertificateHelper; +import com.cloud.utils.ssh.SshHelper; class NitroError { static final int NS_RESOURCE_EXISTS = 273; @@ -683,17 +682,17 @@ public class NetscalerResource implements ServerResource { String previousCertKeyName = null; - if ( sslCert.getChain() != null ) { + if (sslCert.getChain() != null) { List chainList = CertificateHelper.parseChain(sslCert.getChain()); // go from ROOT to intermediate CAs - for ( Certificate intermediateCert : Lists.reverse(chainList)){ + for (Certificate intermediateCert : Lists.reverse(chainList)) { - String fingerPrint=CertificateHelper.generateFingerPrint(intermediateCert); + String fingerPrint = CertificateHelper.generateFingerPrint(intermediateCert); String intermediateCertKeyName = generateSslCertKeyName(fingerPrint); String intermediateCertFileName = intermediateCertKeyName + ".pem"; - if (! SSL.isSslCertKeyPresent(_netscalerService, intermediateCertKeyName)) { - byte[] certData= intermediateCert.getEncoded(); + if (!SSL.isSslCertKeyPresent(_netscalerService, intermediateCertKeyName)) { + byte[] certData = intermediateCert.getEncoded(); StringWriter textWriter = new StringWriter(); PEMWriter pemWriter = new PEMWriter(textWriter); pemWriter.writeObject(intermediateCert); @@ -703,7 +702,7 @@ public class NetscalerResource implements ServerResource { SSL.createSslCertKey(_netscalerService, intermediateCertFileName, null, intermediateCertKeyName, null); } - if ( previousCertKeyName != null && ! SSL.certLinkExists(_netscalerService, intermediateCertKeyName, previousCertKeyName)){ + if (previousCertKeyName != null && !SSL.certLinkExists(_netscalerService, intermediateCertKeyName, previousCertKeyName)) { SSL.linkCerts(_netscalerService, intermediateCertKeyName, previousCertKeyName); } @@ -715,17 +714,17 @@ public class NetscalerResource implements ServerResource { String keyFilename = generateSslKeyName(sslCert.getFingerprint()) + ".pem"; //netscaler uses ".pem" format for "bundle" files String certKeyName = generateSslCertKeyName(sslCert.getFingerprint()); - ByteArrayOutputStream certDataStream = new ByteArrayOutputStream( ); + ByteArrayOutputStream certDataStream = new ByteArrayOutputStream(); certDataStream.write(sslCert.getCert().getBytes()); - if (! SSL.isSslCertKeyPresent(_netscalerService, certKeyName)) { + if (!SSL.isSslCertKeyPresent(_netscalerService, certKeyName)) { SSL.uploadCert(_ip, _username, _password, certFilename, certDataStream.toByteArray()); SSL.uploadKey(_ip, _username, _password, keyFilename, sslCert.getKey().getBytes()); SSL.createSslCertKey(_netscalerService, certFilename, keyFilename, certKeyName, sslCert.getPassword()); } - if (previousCertKeyName != null && ! SSL.certLinkExists(_netscalerService, certKeyName, previousCertKeyName)){ + if (previousCertKeyName != null && !SSL.certLinkExists(_netscalerService, certKeyName, previousCertKeyName)) { SSL.linkCerts(_netscalerService, certKeyName, previousCertKeyName); } @@ -831,8 +830,8 @@ public class NetscalerResource implements ServerResource { // unbind before deleting if (nsVirtualServerExists(nsVirtualServerName) && - SSL.isSslCertKeyPresent(_netscalerService, certKeyName) && - SSL.isBoundToVserver(_netscalerService, certKeyName, nsVirtualServerName)) { + SSL.isSslCertKeyPresent(_netscalerService, certKeyName) && + SSL.isBoundToVserver(_netscalerService, certKeyName, nsVirtualServerName)) { SSL.unbindCertKeyFromVserver(_netscalerService, certKeyName, nsVirtualServerName); } @@ -843,27 +842,26 @@ public class NetscalerResource implements ServerResource { SSL.deleteKeyFile(_ip, _username, _password, keyFilename); } - /* * Check and delete intermediate certs: * we can delete an intermediate cert if no other * cert references it as the athority */ - if ( sslCert.getChain() != null ) { + if (sslCert.getChain() != null) { List chainList = CertificateHelper.parseChain(sslCert.getChain()); //go from intermediate CAs to ROOT - for ( Certificate intermediateCert : chainList){ + for (Certificate intermediateCert : chainList) { - String fingerPrint=CertificateHelper.generateFingerPrint(intermediateCert); + String fingerPrint = CertificateHelper.generateFingerPrint(intermediateCert); String intermediateCertKeyName = generateSslCertKeyName(fingerPrint); String intermediateCertFileName = intermediateCertKeyName + ".pem"; if (SSL.isSslCertKeyPresent(_netscalerService, intermediateCertKeyName) && - ! SSL.isCaforCerts(_netscalerService, intermediateCertKeyName)) { + !SSL.isCaforCerts(_netscalerService, intermediateCertKeyName)) { SSL.deleteSslCertKey(_netscalerService, intermediateCertKeyName); SSL.deleteCertFile(_ip, _username, _password, intermediateCertFileName); - }else { + } else { break;// if this cert has another certificate as a child then stop at this point because we need the whole chain } @@ -1797,7 +1795,7 @@ public class NetscalerResource implements ServerResource { return false; } - private static void deleteSslCertKey(nitro_service ns, String certKeyName) throws ExecutionException { + private static void deleteSslCertKey(nitro_service ns, String certKeyName) throws ExecutionException { try { sslcertkey certkey = new sslcertkey(); @@ -1813,7 +1811,7 @@ public class NetscalerResource implements ServerResource { } private static void deleteCertFile(String nsIp, String username, String password, String certFilename) throws Exception { - SshHelper.sshExecute(nsIp,SSH_PORT,username,null,password,"shell rm " + SSL_CERT_PATH + certFilename); + SshHelper.sshExecute(nsIp, SSH_PORT, username, null, password, "shell rm " + SSL_CERT_PATH + certFilename); } private static void deleteKeyFile(String nsIp, String username, String password, String keyFilename) throws Exception { @@ -1827,7 +1825,7 @@ public class NetscalerResource implements ServerResource { certkey.set_certkey(certKeyName); certkey.set_cert(SSL_CERT_PATH + certFilename); - if ( keyFilename != null ) + if (keyFilename != null) certkey.set_key(SSL_CERT_PATH + keyFilename); if (password != null) { @@ -1896,8 +1894,8 @@ public class NetscalerResource implements ServerResource { private static void uploadCert(String nsIp, String user, String password, String certFilename, byte[] certData) throws ExecutionException { try { - SshHelper.scpTo(nsIp,SSH_PORT,user,null,password, SSL_CERT_PATH, certData, certFilename, null); - } catch (Exception e){ + SshHelper.scpTo(nsIp, SSH_PORT, user, null, password, SSL_CERT_PATH, certData, certFilename, null); + } catch (Exception e) { throw new ExecutionException("Failed to copy private key to device " + e.getMessage()); } } @@ -1912,7 +1910,7 @@ public class NetscalerResource implements ServerResource { private static void enableSslFeature(nitro_service ns) throws ExecutionException { try { - base_response result = ns.enable_features(new String[]{"SSL"}); + base_response result = ns.enable_features(new String[] {"SSL"}); if (result.errorcode != 0) throw new ExecutionException("Unable to enable SSL on LB"); } catch (nitro_exception e) { @@ -1944,7 +1942,7 @@ public class NetscalerResource implements ServerResource { try { // check if there is a link from userCertName to caCertName - sslcertkey userCert = sslcertkey.get(ns,userCertName); + sslcertkey userCert = sslcertkey.get(ns, userCertName); String nsCaCert = userCert.get_linkcertkeyname(); if (nsCaCert != null && nsCaCert.equals(caCertName)) @@ -1984,8 +1982,8 @@ public class NetscalerResource implements ServerResource { public static boolean isCaforCerts(nitro_service ns, String caCertName) throws ExecutionException { // check if this certificate serves as a CA for other certificates try { - sslcertlink[] childLinks = sslcertlink.get_filtered(ns,"linkcertkeyname:" + caCertName); - if(childLinks != null && childLinks.length > 0){ + sslcertlink[] childLinks = sslcertlink.get_filtered(ns, "linkcertkeyname:" + caCertName); + if (childLinks != null && childLinks.length > 0) { return true; } @@ -2002,7 +2000,7 @@ public class NetscalerResource implements ServerResource { try { sslcertkey_sslvserver_binding[] cert_vs_binding = sslcertkey_sslvserver_binding.get_filtered(ns, certKeyName, "vservername:" + nsVirtualServerName); - if(cert_vs_binding != null && cert_vs_binding.length > 0){ + if (cert_vs_binding != null && cert_vs_binding.length > 0) { return true; } @@ -2016,73 +2014,73 @@ public class NetscalerResource implements ServerResource { } } - private void enableVPXInterfaces(String publicIf, String privateIf, ns ns_obj) { + private void enableVPXInterfaces(String publicIf, String privateIf, ns nsObj) { // enable VPX to use 10 gigabit Ethernet interfaces if public/private interface // on SDX is a 10Gig interface if (publicIf.equals("10/1") || privateIf.equals("10/1")) { - ns_obj.set_if_10_1(new Boolean(true)); + nsObj.set_if_10_1(new Boolean(true)); } if (publicIf.equals("10/2") || privateIf.equals("10/2")) { - ns_obj.set_if_10_2(new Boolean(true)); + nsObj.set_if_10_2(new Boolean(true)); } if (publicIf.equals("10/3") || privateIf.equals("10/3")) { - ns_obj.set_if_10_3(new Boolean(true)); + nsObj.set_if_10_3(new Boolean(true)); } if (publicIf.equals("10/4") || privateIf.equals("10/4")) { - ns_obj.set_if_10_4(new Boolean(true)); + nsObj.set_if_10_4(new Boolean(true)); } if (publicIf.equals("10/5") || privateIf.equals("10/5")) { - ns_obj.set_if_10_5(new Boolean(true)); + nsObj.set_if_10_5(new Boolean(true)); } if (publicIf.equals("10/6") || privateIf.equals("10/6")) { - ns_obj.set_if_10_6(new Boolean(true)); + nsObj.set_if_10_6(new Boolean(true)); } if (publicIf.equals("10/7") || privateIf.equals("10/7")) { - ns_obj.set_if_10_7(new Boolean(true)); + nsObj.set_if_10_7(new Boolean(true)); } if (publicIf.equals("10/8") || privateIf.equals("10/8")) { - ns_obj.set_if_10_8(new Boolean(true)); + nsObj.set_if_10_8(new Boolean(true)); } // enable VPX to use 1 gigabit Ethernet interfaces if public/private interface // on SDX is a 1Gig interface if (publicIf.equals("1/1") || privateIf.equals("1/1")) { - ns_obj.set_if_1_1(new Boolean(true)); + nsObj.set_if_1_1(new Boolean(true)); } if (publicIf.equals("1/2") || privateIf.equals("1/2")) { - ns_obj.set_if_1_2(new Boolean(true)); + nsObj.set_if_1_2(new Boolean(true)); } if (publicIf.equals("1/3") || privateIf.equals("1/3")) { - ns_obj.set_if_1_3(new Boolean(true)); + nsObj.set_if_1_3(new Boolean(true)); } if (publicIf.equals("1/4") || privateIf.equals("1/4")) { - ns_obj.set_if_1_4(new Boolean(true)); + nsObj.set_if_1_4(new Boolean(true)); } if (publicIf.equals("1/5") || privateIf.equals("1/5")) { - ns_obj.set_if_1_5(new Boolean(true)); + nsObj.set_if_1_5(new Boolean(true)); } if (publicIf.equals("1/6") || privateIf.equals("1/6")) { - ns_obj.set_if_1_6(new Boolean(true)); + nsObj.set_if_1_6(new Boolean(true)); } if (publicIf.equals("1/7") || privateIf.equals("1/7")) { - ns_obj.set_if_1_7(new Boolean(true)); + nsObj.set_if_1_7(new Boolean(true)); } if (publicIf.equals("1/8") || privateIf.equals("1/8")) { - ns_obj.set_if_1_8(new Boolean(true)); + nsObj.set_if_1_8(new Boolean(true)); } } @@ -3746,18 +3744,18 @@ public class NetscalerResource implements ServerResource { private String generateSslCertName(String fingerPrint) { // maximum length supported by NS is 31 // the first 20 characters of the SHA-1 checksum are the unique id - String uniqueId = fingerPrint.replace(":","").substring(0,20); + String uniqueId = fingerPrint.replace(":", "").substring(0, 20); return genObjectName("Cloud-Cert", uniqueId); } private String generateSslKeyName(String fingerPrint) { - String uniqueId = fingerPrint.replace(":","").substring(0,20); + String uniqueId = fingerPrint.replace(":", "").substring(0, 20); return genObjectName("Cloud-Key", uniqueId); } - private String generateSslCertKeyName(String fingerPrint){ - String uniqueId = fingerPrint.replace(":","").substring(0,20); + private String generateSslCertKeyName(String fingerPrint) { + String uniqueId = fingerPrint.replace(":", "").substring(0, 20); return genObjectName("Cloud-Cert", uniqueId); } diff --git a/plugins/network-elements/nicira-nvp/pom.xml b/plugins/network-elements/nicira-nvp/pom.xml index 1315e9ba841..6fc43ec4cfe 100644 --- a/plugins/network-elements/nicira-nvp/pom.xml +++ b/plugins/network-elements/nicira-nvp/pom.xml @@ -1,20 +1,22 @@ 4.0.0 @@ -28,37 +30,49 @@ + + + test/resources + true + + - org.apache.maven.plugins - maven-checkstyle-plugin - ${cs.checkstyle.version} - - - org.apache.cloudstack - checkstyle - ${project.version} - - + com.mycila + license-maven-plugin + cloudstack-checklicence process-classes check - - true - tooling/checkstyle.xml - true - true - ${project.basedir} - **\/*.java,**\/*.xml,**\/*.ini,**\/*.sh,**\/*.bat - **\/target\/,**\/bin\/ - + + + integration + + + + org.apache.maven.plugins + maven-failsafe-plugin + + + + integration-test + verify + + + + + + + + + diff --git a/plugins/network-elements/nicira-nvp/resources/META-INF/cloudstack/nvp/module.properties b/plugins/network-elements/nicira-nvp/resources/META-INF/cloudstack/nvp/module.properties index 92f92a4b4b0..5085fcec0c7 100644 --- a/plugins/network-elements/nicira-nvp/resources/META-INF/cloudstack/nvp/module.properties +++ b/plugins/network-elements/nicira-nvp/resources/META-INF/cloudstack/nvp/module.properties @@ -1,3 +1,4 @@ +# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information @@ -14,5 +15,7 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. +# + name=nvp parent=network \ No newline at end of file diff --git a/plugins/network-elements/nicira-nvp/resources/META-INF/cloudstack/nvp/spring-nvp-context.xml b/plugins/network-elements/nicira-nvp/resources/META-INF/cloudstack/nvp/spring-nvp-context.xml index 8d9813a020e..cd8a2c9846f 100644 --- a/plugins/network-elements/nicira-nvp/resources/META-INF/cloudstack/nvp/spring-nvp-context.xml +++ b/plugins/network-elements/nicira-nvp/resources/META-INF/cloudstack/nvp/spring-nvp-context.xml @@ -1,20 +1,22 @@ networkList = networkDao.listByPhysicalNetwork(physicalNetworkId); - - // Networks with broadcast type lswitch are ours - for (NetworkVO network : networkList) { - if (network.getBroadcastDomainType() == Networks.BroadcastDomainType.Lswitch) { - if ((network.getState() != Network.State.Shutdown) && (network.getState() != Network.State.Destroy)) { - throw new CloudRuntimeException("This Nicira Nvp device can not be deleted as there are one or more logical networks provisioned by cloudstack."); + if (networkList != null) { + // Networks with broadcast type lswitch are ours + for (NetworkVO network : networkList) { + if (network.getBroadcastDomainType() == Networks.BroadcastDomainType.Lswitch) { + if ((network.getState() != Network.State.Shutdown) && (network.getState() != Network.State.Destroy)) { + throw new CloudRuntimeException("This Nicira Nvp device can not be deleted as there are one or more logical networks provisioned by cloudstack."); + } } } } @@ -651,6 +672,9 @@ public class NiciraNvpElement extends AdapterBase implements ConnectivityProvide // Find the nicira networks on this physical network List networkList = networkDao.listByPhysicalNetwork(physicalNetworkId); + if (networkList == null) { + return Collections.emptyList(); + } // Networks with broadcast type lswitch are ours List responseList = new ArrayList(); @@ -733,7 +757,7 @@ public class NiciraNvpElement extends AdapterBase implements ConnectivityProvide cidrs.add(ip.getAddress().addr() + "/" + NetUtils.getCidrSize(ip.getNetmask())); } ConfigurePublicIpsOnLogicalRouterCommand cmd = - new ConfigurePublicIpsOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), niciraNvpHost.getDetail("l3gatewayserviceuuid"), cidrs); + new ConfigurePublicIpsOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), niciraNvpHost.getDetail("l3gatewayserviceuuid"), cidrs); ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd); //FIXME answer can be null if the host is down return answer.getResult(); @@ -774,7 +798,7 @@ public class NiciraNvpElement extends AdapterBase implements ConnectivityProvide // we only need the source and destination ip. Unfortunately no mention if a rule // is new. StaticNatRuleTO ruleTO = - new StaticNatRuleTO(1, sourceIp.getAddress().addr(), MIN_PORT, MAX_PORT, rule.getDestIpAddress(), MIN_PORT, MAX_PORT, "any", rule.isForRevoke(), false); + new StaticNatRuleTO(1, sourceIp.getAddress().addr(), MIN_PORT, MAX_PORT, rule.getDestIpAddress(), MIN_PORT, MAX_PORT, "any", rule.isForRevoke(), false); staticNatRules.add(ruleTO); } @@ -816,7 +840,7 @@ public class NiciraNvpElement extends AdapterBase implements ConnectivityProvide } ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = - new ConfigurePortForwardingRulesOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), portForwardingRules); + new ConfigurePortForwardingRulesOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), portForwardingRules); ConfigurePortForwardingRulesOnLogicalRouterAnswer answer = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd); return answer.getResult(); diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElementService.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElementService.java index fd3ffdb72d7..dae1a0f2803 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElementService.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElementService.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,6 +15,8 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +// + package com.cloud.network.element; import java.util.List; diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java index 211bd6c7aac..4866d406421 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,6 +15,8 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +// + package com.cloud.network.guru; import java.net.URI; diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/AccessConfiguration.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/AccessConfiguration.java new file mode 100644 index 00000000000..487f14b3b8d --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/AccessConfiguration.java @@ -0,0 +1,132 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.network.nicira; + +import java.io.Serializable; +import java.util.List; + +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.apache.commons.lang.builder.ReflectionToStringBuilder; +import org.apache.commons.lang.builder.ToStringStyle; + +@SuppressWarnings("serial") +public abstract class AccessConfiguration implements Serializable { + + protected String displayName; + protected List logicalPortEgressRules; + protected List logicalPortIngressRules; + protected List tags; + protected String uuid; + protected String href; + protected String schema; + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(final String displayName) { + this.displayName = displayName; + } + + public List getLogicalPortEgressRules() { + return logicalPortEgressRules; + } + + public void setLogicalPortEgressRules(final List logicalPortEgressRules) { + this.logicalPortEgressRules = logicalPortEgressRules; + } + + public List getLogicalPortIngressRules() { + return logicalPortIngressRules; + } + + public void setLogicalPortIngressRules(final List logicalPortIngressRules) { + this.logicalPortIngressRules = logicalPortIngressRules; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(final String uuid) { + this.uuid = uuid; + } + + public String getHref() { + return href; + } + + public void setHref(final String href) { + this.href = href; + } + + public String getSchema() { + return schema; + } + + public void setSchema(final String schema) { + this.schema = schema; + } + + public List getTags() { + return tags; + } + + public void setTags(final List tags) { + this.tags = tags; + } + + @Override + public String toString() { + return ReflectionToStringBuilder.reflectionToString(this, ToStringStyle.DEFAULT_STYLE, false); + } + + @Override + public int hashCode() { + return new HashCodeBuilder(17, 31) + .append(displayName).append(logicalPortEgressRules) + .append(logicalPortIngressRules).append(tags) + .append(uuid).append(href).append(schema) + .toHashCode(); + } + + @Override + @SuppressWarnings("unchecked") + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (obj == this) { + return true; + } + if (!(this.getClass().isInstance(obj))) { + return false; + } + final AccessConfiguration another = + (AccessConfiguration) obj; + return new EqualsBuilder() + .append(displayName, another.displayName) + .append(uuid, another.uuid) + .append(href, another.href) + .append(schema, another.schema) + .isEquals(); + } +} diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/AccessRule.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/AccessRule.java new file mode 100644 index 00000000000..e614db6e43a --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/AccessRule.java @@ -0,0 +1,58 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.network.nicira; + +import java.io.Serializable; + +import org.apache.commons.lang.builder.ReflectionToStringBuilder; +import org.apache.commons.lang.builder.ToStringStyle; + +@SuppressWarnings("serial") +public abstract class AccessRule implements Serializable { + + public static final String ETHERTYPE_IPV4 = "IPv4"; + public static final String ETHERTYPE_IPV6 = "IPv6"; + + protected String ethertype = ETHERTYPE_IPV4; + + protected int protocol; + + + public String getEthertype() { + return ethertype; + } + + public void setEthertype(String ethertype) { + this.ethertype = ethertype; + } + + public int getProtocol() { + return protocol; + } + + public void setProtocol(int protocol) { + this.protocol = protocol; + } + + @Override + public String toString() { + return ReflectionToStringBuilder.reflectionToString(this, ToStringStyle.DEFAULT_STYLE, false); + } +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/HandshakeEnd.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Acl.java similarity index 83% rename from services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/HandshakeEnd.java rename to plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Acl.java index 3a8b4b6d1c2..976177fdff8 100644 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/HandshakeEnd.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Acl.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,14 +15,10 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package rdpclient; +// -import streamer.BaseElement; - -public class HandshakeEnd extends BaseElement { - - public HandshakeEnd(String id) { - super(id); - } +package com.cloud.network.nicira; +@SuppressWarnings("serial") +public class Acl extends AccessConfiguration { } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/AclRule.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/AclRule.java new file mode 100644 index 00000000000..8a4c05332cf --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/AclRule.java @@ -0,0 +1,209 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.network.nicira; + +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; + +@SuppressWarnings("serial") +public class AclRule extends AccessRule { + + public static final String ETHERTYPE_ARP = "ARP"; + + /** + * @TODO Convert this String into Enum and check the JSON communication still works + */ + protected String action; + + protected String sourceIpPrefix; + + protected String destinationIpPrefix; + + protected String sourceMacAddress; + + protected String destinationMacAddress; + + protected Integer sourcePortRangeMin; + + protected Integer destinationPortRangeMin; + + protected Integer sourcePortRangeMax; + + protected Integer destinationPortRangeMax; + + protected Integer icmpProtocolCode; + + protected Integer icmpProtocolType; + + protected int order; + + + /** + * Default constructor + */ + public AclRule() { + } + + /** + * Fully parameterized constructor + */ + public AclRule(String ethertype, int protocol, String action, String sourceMacAddress, + String destinationMacAddress, String sourceIpPrefix, String destinationIpPrefix, + Integer sourcePortRangeMin, Integer sourcePortRangeMax, + Integer destinationPortRangeMin, Integer destinationPortRangeMax, + int order, Integer icmpProtocolCode, Integer icmpProtocolType) { + this.ethertype = ethertype; + this.protocol = protocol; + this.action = action; + this.sourceMacAddress = sourceMacAddress; + this.destinationMacAddress = destinationMacAddress; + this.sourceIpPrefix = sourceIpPrefix; + this.destinationIpPrefix = destinationIpPrefix; + this.sourcePortRangeMin = sourcePortRangeMin; + this.sourcePortRangeMax = sourcePortRangeMax; + this.destinationPortRangeMin = destinationPortRangeMin; + this.destinationPortRangeMax = destinationPortRangeMax; + this.order = order; + this.icmpProtocolCode = icmpProtocolCode; + this.icmpProtocolType = icmpProtocolType; + } + + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getSourceIpPrefix() { + return sourceIpPrefix; + } + + public void setSourceIpPrefix(String sourceIpPrefix) { + this.sourceIpPrefix = sourceIpPrefix; + } + + public String getDestinationIpPrefix() { + return destinationIpPrefix; + } + + public void setDestinationIpPrefix(String destinationIpPrefix) { + this.destinationIpPrefix = destinationIpPrefix; + } + + public String getSourceMacAddress() { + return sourceMacAddress; + } + + public void setSourceMacAddress(String sourceMacAddress) { + this.sourceMacAddress = sourceMacAddress; + } + + public String getDestinationMacAddress() { + return destinationMacAddress; + } + + public void setDestinationMacAddress(String destinationMacAddress) { + this.destinationMacAddress = destinationMacAddress; + } + + public Integer getSourcePortRangeMin() { + return sourcePortRangeMin; + } + + public void setSourcePortRangeMin(Integer sourcePortRangeMin) { + this.sourcePortRangeMin = sourcePortRangeMin; + } + + public Integer getDestinationPortRangeMin() { + return destinationPortRangeMin; + } + + public void setDestinationPortRangeMin(Integer destinationPortRangeMin) { + this.destinationPortRangeMin = destinationPortRangeMin; + } + + public Integer getSourcePortRangeMax() { + return sourcePortRangeMax; + } + + public void setSourcePortRangeMax(Integer sourcePortRangeMax) { + this.sourcePortRangeMax = sourcePortRangeMax; + } + + public Integer getDestinationPortRangeMax() { + return destinationPortRangeMax; + } + + public void setDestinationPortRangeMax(Integer destinationPortRangeMax) { + this.destinationPortRangeMax = destinationPortRangeMax; + } + + public Integer getIcmpProtocolCode() { + return icmpProtocolCode; + } + + public void setIcmpProtocolCode(Integer icmpProtocolCode) { + this.icmpProtocolCode = icmpProtocolCode; + } + + public Integer getIcmpProtocolType() { + return icmpProtocolType; + } + + public void setIcmpProtocolType(Integer icmpProtocolType) { + this.icmpProtocolType = icmpProtocolType; + } + + public int getOrder() { + return order; + } + + public void setOrder(int order) { + this.order = order; + } + + @Override + public int hashCode() { + return new HashCodeBuilder(17, 31) + .append(ethertype).append(protocol) + .toHashCode(); + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (obj == this) { + return true; + } + if (!(obj instanceof AclRule)) { + return false; + } + AclRule another = (AclRule) obj; + return new EqualsBuilder() + .append(ethertype, another.ethertype) + .append(protocol, another.protocol) + .isEquals(); + } +} diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Attachment.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Attachment.java index b1b1ebc3545..90ff131ff88 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Attachment.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Attachment.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,6 +15,8 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +// + package com.cloud.network.nicira; public abstract class Attachment { diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/ControlClusterStatus.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/ControlClusterStatus.java index daee5c2e5c9..8d6399e9125 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/ControlClusterStatus.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/ControlClusterStatus.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,6 +15,8 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +// + package com.cloud.network.nicira; public class ControlClusterStatus { diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/DestinationNatRule.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/DestinationNatRule.java index 24670de5767..a0d5afcaa84 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/DestinationNatRule.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/DestinationNatRule.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,6 +15,8 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +// + package com.cloud.network.nicira; public class DestinationNatRule extends NatRule { diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/L3GatewayAttachment.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/L3GatewayAttachment.java index 515a75197b4..a1d5ce4a990 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/L3GatewayAttachment.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/L3GatewayAttachment.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,6 +15,8 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +// + package com.cloud.network.nicira; /** diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterConfig.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterConfig.java index 5c99e158eac..b6eaa8f277a 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterConfig.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterConfig.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,6 +15,8 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +// + package com.cloud.network.nicira; import java.util.List; diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterPort.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterPort.java index ed1b8da7ddf..8ffe0546875 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterPort.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterPort.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,6 +15,8 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +// + package com.cloud.network.nicira; import java.util.List; diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitch.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitch.java index c2d75a72c1d..23793549912 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitch.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitch.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,6 +15,8 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +// + package com.cloud.network.nicira; import java.util.List; diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitchPort.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitchPort.java index da58c78bde4..3565fbe8dbe 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitchPort.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitchPort.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,6 +15,8 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +// + package com.cloud.network.nicira; import java.util.List; diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Match.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Match.java index 2e31df8eccf..ae3a86c42ee 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Match.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Match.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,6 +15,8 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +// + package com.cloud.network.nicira; /** diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NatRule.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NatRule.java index fca295d231d..912e352e273 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NatRule.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NatRule.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,6 +15,8 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +// + package com.cloud.network.nicira; import java.util.UUID; diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpApi.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpApi.java index 6f695ade9bd..83d00752665 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpApi.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpApi.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,6 +15,8 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +// + package com.cloud.network.nicira; import java.io.IOException; @@ -71,11 +74,18 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.reflect.TypeToken; +@SuppressWarnings("rawtypes") public class NiciraNvpApi { + protected static final String GET_METHOD_TYPE = "get"; + protected static final String DELETE_METHOD_TYPE = "delete"; + protected static final String PUT_METHOD_TYPE = "put"; + protected static final String POST_METHOD_TYPE = "post"; private static final String TEXT_HTML_CONTENT_TYPE = "text/html"; private static final String JSON_CONTENT_TYPE = "application/json"; private static final String CONTENT_TYPE = "Content-Type"; private static final int BODY_RESP_MAX_LEN = 1024; + protected static final String SEC_PROFILE_URI_PREFIX = "/ws.v1/security-profile"; + protected static final String ACL_URI_PREFIX = "/ws.v1/acl"; private static final String SWITCH_URI_PREFIX = "/ws.v1/lswitch"; private static final String ROUTER_URI_PREFIX = "/ws.v1/lrouter"; private static final int HTTPS_PORT = 443; @@ -83,7 +93,6 @@ public class NiciraNvpApi { private final static String protocol = "https"; private final static MultiThreadedHttpConnectionManager s_httpClientManager = new MultiThreadedHttpConnectionManager(); - private String name; private String host; private String adminuser; private String adminpass; @@ -93,6 +102,27 @@ public class NiciraNvpApi { private final Gson gson; + protected final static Map prefixMap; + + protected final static Map listTypeMap; + + protected final static Map defaultListParams; + + static { + prefixMap = new HashMap(); + prefixMap.put(SecurityProfile.class, SEC_PROFILE_URI_PREFIX); + prefixMap.put(Acl.class, ACL_URI_PREFIX); + + listTypeMap = new HashMap(); + listTypeMap.put(SecurityProfile.class, new TypeToken>() { + }.getType()); + listTypeMap.put(Acl.class, new TypeToken>() { + }.getType()); + + defaultListParams = new HashMap(); + defaultListParams.put("fields", "*"); + } + /* This factory method is protected so we can extend this * in the unittests. */ @@ -104,18 +134,18 @@ public class NiciraNvpApi { String url; try { url = new URL(protocol, host, uri).toString(); - } catch (MalformedURLException e) { + } catch (final MalformedURLException e) { s_logger.error("Unable to build Nicira API URL", e); throw new NiciraNvpApiException("Unable to build Nicira API URL", e); } - if ("post".equalsIgnoreCase(type)) { + if (POST_METHOD_TYPE.equalsIgnoreCase(type)) { return new PostMethod(url); - } else if ("get".equalsIgnoreCase(type)) { + } else if (GET_METHOD_TYPE.equalsIgnoreCase(type)) { return new GetMethod(url); - } else if ("delete".equalsIgnoreCase(type)) { + } else if (DELETE_METHOD_TYPE.equalsIgnoreCase(type)) { return new DeleteMethod(url); - } else if ("put".equalsIgnoreCase(type)) { + } else if (PUT_METHOD_TYPE.equalsIgnoreCase(type)) { return new PutMethod(url); } else { throw new NiciraNvpApiException("Requesting unknown method type"); @@ -129,7 +159,7 @@ public class NiciraNvpApi { try { // Cast to ProtocolSocketFactory to avoid the deprecated constructor with the SecureProtocolSocketFactory parameter Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory)new TrustingProtocolSocketFactory(), HTTPS_PORT)); - } catch (IOException e) { + } catch (final IOException e) { s_logger.warn("Failed to register the TrustingProtocolSocketFactory, falling back to default SSLSocketFactory", e); } @@ -160,20 +190,20 @@ public class NiciraNvpApi { try { url = new URL(protocol, host, "/ws.v1/login").toString(); - } catch (MalformedURLException e) { + } catch (final MalformedURLException e) { s_logger.error("Unable to build Nicira API URL", e); throw new NiciraNvpApiException("Unable to build Nicira API URL", e); } - PostMethod pm = new PostMethod(url); + final PostMethod pm = new PostMethod(url); pm.addParameter("username", adminuser); pm.addParameter("password", adminpass); try { client.executeMethod(pm); - } catch (HttpException e) { + } catch (final HttpException e) { throw new NiciraNvpApiException("Nicira NVP API login failed ", e); - } catch (IOException e) { + } catch (final IOException e) { throw new NiciraNvpApiException("Nicira NVP API login failed ", e); } finally { pm.releaseConnection(); @@ -193,69 +223,263 @@ public class NiciraNvpApi { // Success; the cookie required for login is kept in _client } + /** + * POST {@link SecurityProfile} + * + * @param securityProfile + * @return + * @throws NiciraNvpApiException + */ + public SecurityProfile createSecurityProfile(final SecurityProfile securityProfile) throws NiciraNvpApiException { + return create(securityProfile); + } + + /** + * GET list of {@link SecurityProfile} + * + * @return + * @throws NiciraNvpApiException + */ + public NiciraNvpList findSecurityProfile() throws NiciraNvpApiException { + return findSecurityProfile(null); + } + + /** + * GET list of {@link SecurityProfile} filtered by UUID + * + * We could have invoked the service: + * SEC_PROFILE_URI_PREFIX + "/" + securityProfileUuid + * but it is not working currently + * + * @param uuid + * @return + * @throws NiciraNvpApiException + */ + public NiciraNvpList findSecurityProfile(final String uuid) throws NiciraNvpApiException { + return find(uuid, SecurityProfile.class); + } + + /** + * PUT {@link SecurityProfile} given a UUID as key and a {@link SecurityProfile} + * with the new data + * + * @param securityProfile + * @param securityProfileUuid + * @throws NiciraNvpApiException + */ + public void updateSecurityProfile(final SecurityProfile securityProfile, + final String securityProfileUuid) + throws NiciraNvpApiException { + update(securityProfile, securityProfileUuid); + } + + /** + * DELETE Security Profile given a UUID as key + * + * @param securityProfileUuid + * @throws NiciraNvpApiException + */ + public void deleteSecurityProfile(final String securityProfileUuid) + throws NiciraNvpApiException { + delete(securityProfileUuid, SecurityProfile.class); + } + + + /** + * POST {@link Acl} + * + * @param acl + * @return + * @throws NiciraNvpApiException + */ + public Acl createAcl(final Acl acl) throws NiciraNvpApiException { + return create(acl); + } + + /** + * GET list of {@link Acl} + * + * @return + * @throws NiciraNvpApiException + */ + public NiciraNvpList findAcl() throws NiciraNvpApiException { + return findAcl(null); + } + + /** + * GET list of {@link Acl} filtered by UUID + * + * @param uuid + * @return + * @throws NiciraNvpApiException + */ + public NiciraNvpList findAcl(final String uuid) throws NiciraNvpApiException { + return find(uuid, Acl.class); + } + + /** + * PUT {@link Acl} given a UUID as key and a {@link Acl} + * with the new data + * + * @param acl + * @param aclUuid + * @throws NiciraNvpApiException + */ + public void updateAcl(final Acl acl, + final String aclUuid) + throws NiciraNvpApiException { + update(acl, aclUuid); + } + + /** + * DELETE Acl given a UUID as key + * + * @param acl + * @throws NiciraNvpApiException + */ + public void deleteAcl(final String aclUuid) throws NiciraNvpApiException { + delete(aclUuid, Acl.class); + } + + /** + * POST + * + * @param entity + * @return + * @throws NiciraNvpApiException + */ + protected T create(final T entity) throws NiciraNvpApiException { + final String uri = prefixMap.get(entity.getClass()); + final T createdEntity = executeCreateObject(entity, new TypeToken() { + }.getType(), uri, Collections. emptyMap()); + + return createdEntity; + } + + /** + * GET list of items + * + * @return + * @throws NiciraNvpApiException + */ + protected NiciraNvpList find(final Class clazz) throws NiciraNvpApiException { + return find(null, clazz); + } + + /** + * GET list of items + * + * @param uuid + * @return + * @throws NiciraNvpApiException + */ + public NiciraNvpList find(final String uuid, final Class clazz) throws NiciraNvpApiException { + final String uri = prefixMap.get(clazz); + Map params = defaultListParams; + if (uuid != null) { + params = new HashMap(defaultListParams); + params.put("uuid", uuid); + } + + final NiciraNvpList entities = executeRetrieveObject(listTypeMap.get(clazz), uri, params); + + if (entities == null) { + throw new NiciraNvpApiException("Unexpected response from API"); + } + + return entities; + } + + /** + * PUT item given a UUID as key and an item object + * with the new data + * + * @param item + * @param uuid + * @throws NiciraNvpApiException + */ + public void update(final T item, + final String uuid) + throws NiciraNvpApiException { + final String uri = prefixMap.get(item.getClass()) + "/" + uuid; + executeUpdateObject(item, uri, Collections. emptyMap()); + } + + /** + * DELETE Security Profile given a UUID as key + * + * @param securityProfileUuid + * @throws NiciraNvpApiException + */ + public void delete(final String uuid, final Class clazz) + throws NiciraNvpApiException { + final String uri = prefixMap.get(clazz) + "/" + uuid; + executeDeleteObject(uri); + } + public LogicalSwitch createLogicalSwitch(final LogicalSwitch logicalSwitch) throws NiciraNvpApiException { - String uri = SWITCH_URI_PREFIX; - LogicalSwitch createdLogicalSwitch = executeCreateObject(logicalSwitch, new TypeToken() { + final String uri = SWITCH_URI_PREFIX; + final LogicalSwitch createdLogicalSwitch = executeCreateObject(logicalSwitch, new TypeToken() { }.getType(), uri, Collections. emptyMap()); return createdLogicalSwitch; } public void deleteLogicalSwitch(final String uuid) throws NiciraNvpApiException { - String uri = SWITCH_URI_PREFIX + uuid; + final String uri = SWITCH_URI_PREFIX + "/" + uuid; executeDeleteObject(uri); } public LogicalSwitchPort createLogicalSwitchPort(final String logicalSwitchUuid, final LogicalSwitchPort logicalSwitchPort) throws NiciraNvpApiException { - String uri = SWITCH_URI_PREFIX + logicalSwitchUuid + "/lport"; - LogicalSwitchPort createdLogicalSwitchPort = executeCreateObject(logicalSwitchPort, new TypeToken() { + final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport"; + final LogicalSwitchPort createdLogicalSwitchPort = executeCreateObject(logicalSwitchPort, new TypeToken() { }.getType(), uri, Collections. emptyMap()); return createdLogicalSwitchPort; } - public void modifyLogicalSwitchPortAttachment(final String logicalSwitchUuid, final String logicalSwitchPortUuid, Attachment attachment) throws NiciraNvpApiException { - String uri = SWITCH_URI_PREFIX + logicalSwitchUuid + "/lport/" + logicalSwitchPortUuid + "/attachment"; + public void modifyLogicalSwitchPortAttachment(final String logicalSwitchUuid, final String logicalSwitchPortUuid, final Attachment attachment) throws NiciraNvpApiException { + final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport/" + logicalSwitchPortUuid + "/attachment"; executeUpdateObject(attachment, uri, Collections. emptyMap()); } public void deleteLogicalSwitchPort(final String logicalSwitchUuid, final String logicalSwitchPortUuid) throws NiciraNvpApiException { - String uri = SWITCH_URI_PREFIX + logicalSwitchUuid + "/lport/" + logicalSwitchPortUuid; + final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport/" + logicalSwitchPortUuid; executeDeleteObject(uri); } public String findLogicalSwitchPortUuidByVifAttachmentUuid(final String logicalSwitchUuid, final String vifAttachmentUuid) throws NiciraNvpApiException { - String uri = SWITCH_URI_PREFIX + logicalSwitchUuid + "/lport"; - Map params = new HashMap(); + final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport"; + final Map params = new HashMap(); params.put("attachment_vif_uuid", vifAttachmentUuid); params.put("fields", "uuid"); - NiciraNvpList lspl = executeRetrieveObject(new TypeToken>() { + final NiciraNvpList lspl = executeRetrieveObject(new TypeToken>() { }.getType(), uri, params); if (lspl == null || lspl.getResultCount() != 1) { throw new NiciraNvpApiException("Unexpected response from API"); } - LogicalSwitchPort lsp = lspl.getResults().get(0); + final LogicalSwitchPort lsp = lspl.getResults().get(0); return lsp.getUuid(); } public ControlClusterStatus getControlClusterStatus() throws NiciraNvpApiException { - String uri = "/ws.v1/control-cluster/status"; - ControlClusterStatus ccs = executeRetrieveObject(new TypeToken() { + final String uri = "/ws.v1/control-cluster/status"; + final ControlClusterStatus ccs = executeRetrieveObject(new TypeToken() { }.getType(), uri, null); return ccs; } public NiciraNvpList findLogicalSwitchPortsByUuid(final String logicalSwitchUuid, final String logicalSwitchPortUuid) throws NiciraNvpApiException { - String uri = SWITCH_URI_PREFIX + logicalSwitchUuid + "/lport"; - Map params = new HashMap(); + final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport"; + final Map params = new HashMap(); params.put("uuid", logicalSwitchPortUuid); params.put("fields", "uuid"); - NiciraNvpList lspl = executeRetrieveObject(new TypeToken>() { + final NiciraNvpList lspl = executeRetrieveObject(new TypeToken>() { }.getType(), uri, params); if (lspl == null) { @@ -266,69 +490,69 @@ public class NiciraNvpApi { } public LogicalRouterConfig createLogicalRouter(final LogicalRouterConfig logicalRouterConfig) throws NiciraNvpApiException { - String uri = ROUTER_URI_PREFIX; + final String uri = ROUTER_URI_PREFIX; - LogicalRouterConfig lrc = executeCreateObject(logicalRouterConfig, new TypeToken() { + final LogicalRouterConfig lrc = executeCreateObject(logicalRouterConfig, new TypeToken() { }.getType(), uri, Collections. emptyMap()); return lrc; } public void deleteLogicalRouter(final String logicalRouterUuid) throws NiciraNvpApiException { - String uri = ROUTER_URI_PREFIX + logicalRouterUuid; + final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid; executeDeleteObject(uri); } public LogicalRouterPort createLogicalRouterPort(final String logicalRouterUuid, final LogicalRouterPort logicalRouterPort) throws NiciraNvpApiException { - String uri = ROUTER_URI_PREFIX + logicalRouterUuid + "/lport"; + final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport"; - LogicalRouterPort lrp = executeCreateObject(logicalRouterPort, new TypeToken() { + final LogicalRouterPort lrp = executeCreateObject(logicalRouterPort, new TypeToken() { }.getType(), uri, Collections. emptyMap()); return lrp; } public void deleteLogicalRouterPort(final String logicalRouterUuid, final String logicalRouterPortUuid) throws NiciraNvpApiException { - String uri = ROUTER_URI_PREFIX + logicalRouterUuid + "/lport/" + logicalRouterPortUuid; + final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport/" + logicalRouterPortUuid; executeDeleteObject(uri); } public void modifyLogicalRouterPort(final String logicalRouterUuid, final LogicalRouterPort logicalRouterPort) throws NiciraNvpApiException { - String uri = ROUTER_URI_PREFIX + logicalRouterUuid + "/lport/" + logicalRouterPort.getUuid(); + final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport/" + logicalRouterPort.getUuid(); executeUpdateObject(logicalRouterPort, uri, Collections. emptyMap()); } public void modifyLogicalRouterPortAttachment(final String logicalRouterUuid, final String logicalRouterPortUuid, final Attachment attachment) - throws NiciraNvpApiException { - String uri = ROUTER_URI_PREFIX + logicalRouterUuid + "/lport/" + logicalRouterPortUuid + "/attachment"; + throws NiciraNvpApiException { + final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport/" + logicalRouterPortUuid + "/attachment"; executeUpdateObject(attachment, uri, Collections. emptyMap()); } public NatRule createLogicalRouterNatRule(final String logicalRouterUuid, final NatRule natRule) throws NiciraNvpApiException { - String uri = ROUTER_URI_PREFIX + logicalRouterUuid + "/nat"; + final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/nat"; return executeCreateObject(natRule, new TypeToken() { }.getType(), uri, Collections. emptyMap()); } public void modifyLogicalRouterNatRule(final String logicalRouterUuid, final NatRule natRule) throws NiciraNvpApiException { - String uri = ROUTER_URI_PREFIX + logicalRouterUuid + "/nat/" + natRule.getUuid(); + final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/nat/" + natRule.getUuid(); executeUpdateObject(natRule, uri, Collections. emptyMap()); } public void deleteLogicalRouterNatRule(final String logicalRouterUuid, final UUID natRuleUuid) throws NiciraNvpApiException { - String uri = ROUTER_URI_PREFIX + logicalRouterUuid + "/nat/" + natRuleUuid.toString(); + final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/nat/" + natRuleUuid.toString(); executeDeleteObject(uri); } public NiciraNvpList findLogicalRouterPortByGatewayServiceAndVlanId(final String logicalRouterUuid, final String gatewayServiceUuid, - final long vlanId) throws NiciraNvpApiException { - String uri = ROUTER_URI_PREFIX + logicalRouterUuid + "/lport"; - Map params = new HashMap(); + final long vlanId) throws NiciraNvpApiException { + final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport"; + final Map params = new HashMap(); params.put("attachment_gwsvc_uuid", gatewayServiceUuid); params.put("attachment_vlan", "0"); params.put("fields", "*"); @@ -338,21 +562,21 @@ public class NiciraNvpApi { } public LogicalRouterConfig findOneLogicalRouterByUuid(final String logicalRouterUuid) throws NiciraNvpApiException { - String uri = ROUTER_URI_PREFIX + logicalRouterUuid; + final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid; return executeRetrieveObject(new TypeToken() { }.getType(), uri, Collections. emptyMap()); } public void updateLogicalRouterPortConfig(final String logicalRouterUuid, final LogicalRouterPort logicalRouterPort) throws NiciraNvpApiException { - String uri = ROUTER_URI_PREFIX + logicalRouterUuid + "/lport" + logicalRouterPort.getUuid(); + final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport" + logicalRouterPort.getUuid(); executeUpdateObject(logicalRouterPort, uri, Collections. emptyMap()); } public NiciraNvpList findNatRulesByLogicalRouterUuid(final String logicalRouterUuid) throws NiciraNvpApiException { - String uri = ROUTER_URI_PREFIX + logicalRouterUuid + "/nat"; - Map params = new HashMap(); + final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/nat"; + final Map params = new HashMap(); params.put("fields", "*"); return executeRetrieveObject(new TypeToken>() { @@ -360,9 +584,9 @@ public class NiciraNvpApi { } public NiciraNvpList findLogicalRouterPortByGatewayServiceUuid(final String logicalRouterUuid, final String l3GatewayServiceUuid) - throws NiciraNvpApiException { - String uri = ROUTER_URI_PREFIX + logicalRouterUuid + "/lport"; - Map params = new HashMap(); + throws NiciraNvpApiException { + final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport"; + final Map params = new HashMap(); params.put("fields", "*"); params.put("attachment_gwsvc_uuid", l3GatewayServiceUuid); @@ -375,18 +599,18 @@ public class NiciraNvpApi { throw new NiciraNvpApiException("Hostname/credentials are null or empty"); } - PutMethod pm = (PutMethod)createMethod("put", uri); + final PutMethod pm = (PutMethod)createMethod(PUT_METHOD_TYPE, uri); pm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE); try { pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), JSON_CONTENT_TYPE, null)); - } catch (UnsupportedEncodingException e) { + } catch (final UnsupportedEncodingException e) { throw new NiciraNvpApiException("Failed to encode json request body", e); } executeMethod(pm); if (pm.getStatusCode() != HttpStatus.SC_OK) { - String errorMessage = responseToErrorMessage(pm); + final String errorMessage = responseToErrorMessage(pm); pm.releaseConnection(); s_logger.error("Failed to update object : " + errorMessage); throw new NiciraNvpApiException("Failed to update object : " + errorMessage); @@ -394,24 +618,25 @@ public class NiciraNvpApi { pm.releaseConnection(); } + @SuppressWarnings("unchecked") protected T executeCreateObject(final T newObject, final Type returnObjectType, final String uri, final Map parameters) - throws NiciraNvpApiException { + throws NiciraNvpApiException { if (host == null || host.isEmpty() || adminuser == null || adminuser.isEmpty() || adminpass == null || adminpass.isEmpty()) { throw new NiciraNvpApiException("Hostname/credentials are null or empty"); } - PostMethod pm = (PostMethod)createMethod("post", uri); + final PostMethod pm = (PostMethod)createMethod(POST_METHOD_TYPE, uri); pm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE); try { pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), JSON_CONTENT_TYPE, null)); - } catch (UnsupportedEncodingException e) { + } catch (final UnsupportedEncodingException e) { throw new NiciraNvpApiException("Failed to encode json request body", e); } executeMethod(pm); if (pm.getStatusCode() != HttpStatus.SC_CREATED) { - String errorMessage = responseToErrorMessage(pm); + final String errorMessage = responseToErrorMessage(pm); pm.releaseConnection(); s_logger.error("Failed to create object : " + errorMessage); throw new NiciraNvpApiException("Failed to create object : " + errorMessage); @@ -420,7 +645,7 @@ public class NiciraNvpApi { T result; try { result = (T)gson.fromJson(pm.getResponseBodyAsString(), TypeToken.get(newObject.getClass()).getType()); - } catch (IOException e) { + } catch (final IOException e) { throw new NiciraNvpApiException("Failed to decode json response body", e); } finally { pm.releaseConnection(); @@ -434,13 +659,13 @@ public class NiciraNvpApi { throw new NiciraNvpApiException("Hostname/credentials are null or empty"); } - DeleteMethod dm = (DeleteMethod)createMethod("delete", uri); + final DeleteMethod dm = (DeleteMethod)createMethod(DELETE_METHOD_TYPE, uri); dm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE); executeMethod(dm); if (dm.getStatusCode() != HttpStatus.SC_NO_CONTENT) { - String errorMessage = responseToErrorMessage(dm); + final String errorMessage = responseToErrorMessage(dm); dm.releaseConnection(); s_logger.error("Failed to delete object : " + errorMessage); throw new NiciraNvpApiException("Failed to delete object : " + errorMessage); @@ -448,16 +673,17 @@ public class NiciraNvpApi { dm.releaseConnection(); } + @SuppressWarnings("unchecked") protected T executeRetrieveObject(final Type returnObjectType, final String uri, final Map parameters) throws NiciraNvpApiException { if (host == null || host.isEmpty() || adminuser == null || adminuser.isEmpty() || adminpass == null || adminpass.isEmpty()) { throw new NiciraNvpApiException("Hostname/credentials are null or empty"); } - GetMethod gm = (GetMethod)createMethod("get", uri); + final GetMethod gm = (GetMethod)createMethod(GET_METHOD_TYPE, uri); gm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE); if (parameters != null && !parameters.isEmpty()) { - List nameValuePairs = new ArrayList(parameters.size()); - for (Entry e : parameters.entrySet()) { + final List nameValuePairs = new ArrayList(parameters.size()); + for (final Entry e : parameters.entrySet()) { nameValuePairs.add(new NameValuePair(e.getKey(), e.getValue())); } gm.setQueryString(nameValuePairs.toArray(new NameValuePair[0])); @@ -466,7 +692,7 @@ public class NiciraNvpApi { executeMethod(gm); if (gm.getStatusCode() != HttpStatus.SC_OK) { - String errorMessage = responseToErrorMessage(gm); + final String errorMessage = responseToErrorMessage(gm); gm.releaseConnection(); s_logger.error("Failed to retrieve object : " + errorMessage); throw new NiciraNvpApiException("Failed to retrieve object : " + errorMessage); @@ -475,7 +701,7 @@ public class NiciraNvpApi { T returnValue; try { returnValue = (T)gson.fromJson(gm.getResponseBodyAsString(), returnObjectType); - } catch (IOException e) { + } catch (final IOException e) { s_logger.error("IOException while retrieving response body", e); throw new NiciraNvpApiException(e); } finally { @@ -493,11 +719,11 @@ public class NiciraNvpApi { login(); client.executeMethod(method); } - } catch (HttpException e) { + } catch (final HttpException e) { s_logger.error("HttpException caught while trying to connect to the Nicira NVP Controller", e); method.releaseConnection(); throw new NiciraNvpApiException("API call to Nicira NVP Controller Failed", e); - } catch (IOException e) { + } catch (final IOException e) { s_logger.error("IOException caught while trying to connect to the Nicira NVP Controller", e); method.releaseConnection(); throw new NiciraNvpApiException("API call to Nicira NVP Controller Failed", e); @@ -513,7 +739,7 @@ public class NiciraNvpApi { // and will clutter the logs try { return method.getResponseBodyAsString(BODY_RESP_MAX_LEN); - } catch (IOException e) { + } catch (final IOException e) { s_logger.debug("Error while loading response body", e); } } @@ -533,7 +759,7 @@ public class NiciraNvpApi { public TrustingProtocolSocketFactory() throws IOException { // Create a trust manager that does not validate certificate chains - TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() { + final TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; @@ -552,12 +778,12 @@ public class NiciraNvpApi { try { // Install the all-trusting trust manager - SSLContext sc = SSLContext.getInstance("SSL"); + final SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); ssf = sc.getSocketFactory(); - } catch (KeyManagementException e) { + } catch (final KeyManagementException e) { throw new IOException(e); - } catch (NoSuchAlgorithmException e) { + } catch (final NoSuchAlgorithmException e) { throw new IOException(e); } } @@ -579,12 +805,12 @@ public class NiciraNvpApi { @Override public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params) - throws IOException, UnknownHostException, ConnectTimeoutException { - int timeout = params.getConnectionTimeout(); + throws IOException, UnknownHostException, ConnectTimeoutException { + final int timeout = params.getConnectionTimeout(); if (timeout == 0) { return createSocket(host, port, localAddress, localPort); } else { - Socket s = ssf.createSocket(); + final Socket s = ssf.createSocket(); s.bind(new InetSocketAddress(localAddress, localPort)); s.connect(new InetSocketAddress(host, port), timeout); return s; @@ -596,13 +822,13 @@ public class NiciraNvpApi { @Override public NatRule deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context) throws JsonParseException { - JsonObject jsonObject = jsonElement.getAsJsonObject(); + final JsonObject jsonObject = jsonElement.getAsJsonObject(); if (!jsonObject.has("type")) { throw new JsonParseException("Deserializing as a NatRule, but no type present in the json object"); } - String natRuleType = jsonObject.get("type").getAsString(); + final String natRuleType = jsonObject.get("type").getAsString(); if ("SourceNatRule".equals(natRuleType)) { return context.deserialize(jsonElement, SourceNatRule.class); } else if ("DestinationNatRule".equals(natRuleType)) { diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpApiException.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpApiException.java index facc5ab59e3..0d2782007f5 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpApiException.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpApiException.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,6 +15,8 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +// + package com.cloud.network.nicira; public class NiciraNvpApiException extends Exception { diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpList.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpList.java index ba6ff974790..34b5e19c8c1 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpList.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpList.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,6 +15,8 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +// + package com.cloud.network.nicira; import java.util.List; diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpTag.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpTag.java index 7185bc71b62..625e49c21a5 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpTag.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpTag.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,6 +15,8 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +// + package com.cloud.network.nicira; import org.apache.log4j.Logger; diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/PatchAttachment.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/PatchAttachment.java index 3e2a8c3166a..26fa0486113 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/PatchAttachment.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/PatchAttachment.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,6 +15,8 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +// + package com.cloud.network.nicira; /** diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RouterNextHop.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RouterNextHop.java index 7622c68c287..8dd884072be 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RouterNextHop.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RouterNextHop.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,6 +15,8 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +// + package com.cloud.network.nicira; /** diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RoutingConfig.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RoutingConfig.java index c5eca5b9bc4..5eaef0a699d 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RoutingConfig.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RoutingConfig.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,6 +15,8 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +// + package com.cloud.network.nicira; public class RoutingConfig { diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SecurityProfile.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SecurityProfile.java new file mode 100644 index 00000000000..d83ce49db12 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SecurityProfile.java @@ -0,0 +1,24 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.network.nicira; + +@SuppressWarnings("serial") +public class SecurityProfile extends AccessConfiguration { +} diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SecurityRule.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SecurityRule.java new file mode 100644 index 00000000000..e23593cb3d6 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SecurityRule.java @@ -0,0 +1,138 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.network.nicira; + +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; + +@SuppressWarnings("serial") +public class SecurityRule extends AccessRule { + + protected String ipPrefix; + + protected int portRangeMin; + + protected int portRangeMax; + + protected String profileUuid; + + + /** + * Default constructor + */ + public SecurityRule() { + } + + /** + * Fully parameterized constructor + */ + public SecurityRule(final String ethertype, final String ipPrefix, final String profileUuid, + final int portRangeMin, final int portRangeMax, final int protocol) { + this.ethertype = ethertype; + this.ipPrefix = ipPrefix; + this.portRangeMin = portRangeMin; + this.portRangeMax = portRangeMax; + this.profileUuid = profileUuid; + this.protocol = protocol; + } + + @Override + public String getEthertype() { + return ethertype; + } + + @Override + public void setEthertype(final String ethertype) { + this.ethertype = ethertype; + } + + public String getIpPrefix() { + return ipPrefix; + } + + public void setIpPrefix(final String ipPrefix) { + this.ipPrefix = ipPrefix; + } + + public int getPortRangeMin() { + return portRangeMin; + } + + public void setPortRangeMin(final int portRangeMin) { + this.portRangeMin = portRangeMin; + } + + public int getPortRangeMax() { + return portRangeMax; + } + + public void setPortRangeMax(final int portRangeMax) { + this.portRangeMax = portRangeMax; + } + + public String getProfileUuid() { + return profileUuid; + } + + public void setProfileUuid(final String profileUuid) { + this.profileUuid = profileUuid; + } + + @Override + public int getProtocol() { + return protocol; + } + + @Override + public void setProtocol(final int protocol) { + this.protocol = protocol; + } + + @Override + public int hashCode() { + return new HashCodeBuilder(17, 31) + .append(ethertype).append(ipPrefix) + .append(portRangeMin).append(portRangeMax) + .append(profileUuid).append(protocol) + .toHashCode(); + } + + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (obj == this) { + return true; + } + if (!(obj instanceof SecurityRule)) { + return false; + } + final SecurityRule another = (SecurityRule) obj; + return new EqualsBuilder() + .append(ethertype, another.ethertype) + .append(ipPrefix, another.ipPrefix) + .append(portRangeMin, another.portRangeMin) + .append(portRangeMax, another.portRangeMax) + .append(profileUuid, another.profileUuid) + .append(protocol, another.protocol) + .isEquals(); + } +} diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SingleDefaultRouteImplictRoutingConfig.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SingleDefaultRouteImplictRoutingConfig.java index bbe1cb56ea2..05335791b95 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SingleDefaultRouteImplictRoutingConfig.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SingleDefaultRouteImplictRoutingConfig.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,6 +15,8 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +// + package com.cloud.network.nicira; /** @@ -21,7 +24,7 @@ package com.cloud.network.nicira; */ public class SingleDefaultRouteImplictRoutingConfig extends RoutingConfig { public RouterNextHop defaultRouteNextHop; - public String type = "SingleDefaultRouteImplicitRoutingConfig"; + public final String type = "SingleDefaultRouteImplicitRoutingConfig"; public SingleDefaultRouteImplictRoutingConfig(RouterNextHop routerNextHop) { defaultRouteNextHop = routerNextHop; diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SourceNatRule.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SourceNatRule.java index ee467a710a9..b95cb9aeb5d 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SourceNatRule.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SourceNatRule.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,6 +15,8 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +// + package com.cloud.network.nicira; public class SourceNatRule extends NatRule { diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/TransportZoneBinding.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/TransportZoneBinding.java index fd0fbb1c370..c643876d93c 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/TransportZoneBinding.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/TransportZoneBinding.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,6 +15,8 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +// + package com.cloud.network.nicira; public class TransportZoneBinding { diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/VifAttachment.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/VifAttachment.java index 7b37ac151f1..87765be12a2 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/VifAttachment.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/VifAttachment.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,6 +15,8 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +// + package com.cloud.network.nicira; public class VifAttachment extends Attachment { diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java index 8c99a819a4f..c228b08d5ee 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,6 +15,8 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +// + package com.cloud.network.resource; import java.util.ArrayList; diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/element/NiciraNvpElementTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/element/NiciraNvpElementTest.java index 436c86c2743..822c8c7ee93 100644 --- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/element/NiciraNvpElementTest.java +++ b/plugins/network-elements/nicira-nvp/test/com/cloud/network/element/NiciraNvpElementTest.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,6 +15,8 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +// + package com.cloud.network.element; import static org.junit.Assert.assertFalse; diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java index 3e303b8aae4..db8637ccfb6 100644 --- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java +++ b/plugins/network-elements/nicira-nvp/test/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,6 +15,8 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +// + package com.cloud.network.guru; import static org.junit.Assert.assertFalse; diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NatRuleTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NatRuleTest.java index 1a635278d37..84b28fb8da8 100644 --- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NatRuleTest.java +++ b/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NatRuleTest.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,6 +15,8 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +// + package com.cloud.network.nicira; import static org.junit.Assert.assertTrue; diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraNvpApiIT.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraNvpApiIT.java new file mode 100644 index 00000000000..7f8f471595a --- /dev/null +++ b/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraNvpApiIT.java @@ -0,0 +1,166 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.network.nicira; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.cloud.utils.PropertiesUtil; + +public class NiciraNvpApiIT { + + protected NiciraNvpApi api; + + protected long timestamp = System.currentTimeMillis(); + + @Before + public void setup() throws IOException { + final Properties properties = new Properties(); + PropertiesUtil.loadFromFile(properties, PropertiesUtil.findConfigFile("config.properties")); + api = new NiciraNvpApi(); + api.setControllerAddress(properties.getProperty("nvp.host")); + api.setAdminCredentials(properties.getProperty("nvp.admin.user"), + properties.getProperty("nvp.admin.pwd")); + } + + @Test + public void testCRUDSecurityProfile() throws NiciraNvpApiException { + SecurityProfile sProfile = new SecurityProfile(); + sProfile.setDisplayName("SecProfile"+timestamp); + + final List egressRules = new ArrayList(); + sProfile.setLogicalPortEgressRules(egressRules); + egressRules.add(new SecurityRule(SecurityRule.ETHERTYPE_IPV4, "1.10.10.0", null, 80, 88, 6)); + egressRules.add(new SecurityRule(SecurityRule.ETHERTYPE_IPV6, "2a80:34ac::1", null, 90, 98, 6)); + + final List ingressRules = new ArrayList(); + sProfile.setLogicalPortIngressRules(ingressRules); + ingressRules.add(new SecurityRule(SecurityRule.ETHERTYPE_IPV4, "1.10.10.0", null, 50, 58, 6)); + ingressRules.add(new SecurityRule(SecurityRule.ETHERTYPE_IPV6, "280a:3ac4::1", null, 60, 68, 6)); + + final List tags = new ArrayList(); + sProfile.setTags(tags); + tags.add(new NiciraNvpTag("nvp", "MyTag1")); + tags.add(new NiciraNvpTag("nicira", "MyTag2")); + // In the creation we don't get to specify UUID, href or schema: they don't exist yet + + try { + sProfile = api.createSecurityProfile(sProfile); + + // We can now update the new entity + sProfile.setDisplayName("UpdatedSecProfile"+timestamp); + api.updateSecurityProfile(sProfile, sProfile.getUuid()); + + // Read them all + NiciraNvpList profiles = api.findSecurityProfile(); + SecurityProfile scInList = null; + for(final SecurityProfile iProfile : profiles.getResults()) { + if (iProfile.getUuid().equalsIgnoreCase(sProfile.getUuid())) { + scInList = iProfile; + } + } + Assert.assertEquals("Read a Security Profile different from the one just created and updated", + sProfile, scInList); + + // Read them filtered by uuid (get one) + profiles = api.findSecurityProfile(sProfile.getUuid()); + Assert.assertEquals("Read a Security Profile different from the one just created and updated", + sProfile, + profiles.getResults().get(0)); + Assert.assertEquals("Read a Security Profile filtered by unique id (UUID) with more than one item", + 1, profiles.getResults().size()); + + // We can now delete the new entity + api.deleteSecurityProfile(sProfile.getUuid()); + } catch (final NiciraNvpApiException e) { + e.printStackTrace(); + assertTrue("Errors creating Security Profile", false); + } + } + + @Test + public void testCRUDAcl() throws NiciraNvpApiException { + Acl acl = new Acl(); + acl.setDisplayName("Acl"+timestamp); + + // Note that if the protocol is 6 (TCP) then you cannot put ICMP code and type + // Note that if the protocol is 1 (ICMP) then you cannot put ports + final List egressRules = new ArrayList(); + acl.setLogicalPortEgressRules(egressRules); + egressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 1, "allow", null, null, + "1.10.10.0", "1.10.10.1", null, null, null, null, 0, 0, 5)); + egressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 6, "allow", null, null, + "1.10.10.6", "1.10.10.7", 80, 80, 80, 80, 1, null, null)); + + final List ingressRules = new ArrayList(); + acl.setLogicalPortIngressRules(ingressRules); + ingressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 1, "allow", null, null, + "1.10.10.0", "1.10.10.1", null, null, null, null, 0, 0, 5)); + ingressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 6, "allow", null, null, + "1.10.10.6", "1.10.10.7", 80, 80, 80, 80, 1, null, null)); + + final List tags = new ArrayList(); + acl.setTags(tags); + tags.add(new NiciraNvpTag("nvp", "MyTag1")); + tags.add(new NiciraNvpTag("nicira", "MyTag2")); + // In the creation we don't get to specify UUID, href or schema: they don't exist yet + + try { + acl = api.createAcl(acl); + + // We can now update the new entity + acl.setDisplayName("UpdatedAcl"+timestamp); + api.updateAcl(acl, acl.getUuid()); + + // Read them all + NiciraNvpList acls = api.findAcl(); + Acl scInList = null; + for(final Acl iAcl : acls.getResults()) { + if (iAcl.getUuid().equalsIgnoreCase(acl.getUuid())) { + scInList = iAcl; + } + } + Assert.assertEquals("Read a ACL different from the one just created and updated", + acl, scInList); + + // Read them filtered by uuid (get one) + acls = api.findAcl(acl.getUuid()); + Assert.assertEquals("Read a ACL different from the one just created and updated", + acl, + acls.getResults().get(0)); + Assert.assertEquals("Read a ACL filtered by unique id (UUID) with more than one item", + 1, acls.getResults().size()); + + // We can now delete the new entity + api.deleteAcl(acl.getUuid()); + } catch (final NiciraNvpApiException e) { + e.printStackTrace(); + assertTrue("Errors creating ACL", false); + } + } +} diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraNvpApiTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraNvpApiTest.java index 26517b5fb88..13d970c1cbc 100644 --- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraNvpApiTest.java +++ b/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraNvpApiTest.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,9 +15,12 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +// + package com.cloud.network.nicira; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -35,18 +39,46 @@ import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.PutMethod; import org.apache.commons.httpclient.params.HttpClientParams; +import org.apache.commons.httpclient.NameValuePair; import org.apache.http.HttpStatus; import org.junit.Before; import org.junit.Test; public class NiciraNvpApiTest { + protected static final String UUID = "aaaa"; + protected static final String UUID2 = "bbbb"; + protected static final String UUID_SEC_PROFILE_URI = NiciraNvpApi.SEC_PROFILE_URI_PREFIX + "/aaaa"; + protected static final String SCHEMA = "myTestSchema"; + protected static final String SCHEMA2 = "myTestSchema2"; + protected static final String HREF = "myTestHref"; + protected static final String HREF2 = "myTestHref2"; + protected static final String DISPLAY_NAME = "myTestName"; + protected static final String UUID_JSON_RESPONSE = "{\"uuid\" : \"aaaa\"}"; + protected static final String SEC_PROFILE_JSON_RESPONSE = + "{\"uuid\" : \"aaaa\"," + + "\"display_name\" : \"myTestName\"," + + "\"href\" : \"myTestHref\"," + + "\"schema\" : \"myTestSchema\"}"; + + protected static final String SEC_PROFILE_LIST_JSON_RESPONSE = "{\"results\" : [{\"uuid\" : \"aaaa\"," + + "\"display_name\" : \"myTestName\"," + + "\"href\" : \"myTestHref\"," + + "\"schema\" : \"myTestSchema\"}," + + "{ \"uuid\" : \"bbbb\"," + + "\"display_name\" : \"myTestName2\"," + + "\"href\" : \"myTestHref2\"," + + "\"schema\" : \"myTestSchema2\"}]," + + "\"result_count\": 2}"; + NiciraNvpApi api; HttpClient client = mock(HttpClient.class); HttpMethod method; + String type; + String uri; @Before public void setUp() { - HttpClientParams hmp = mock(HttpClientParams.class); + final HttpClientParams hmp = mock(HttpClientParams.class); when(client.getParams()).thenReturn(hmp); api = new NiciraNvpApi() { @Override @@ -55,7 +87,9 @@ public class NiciraNvpApiTest { } @Override - protected HttpMethod createMethod(String type, String uri) { + protected HttpMethod createMethod(final String newType, final String newUri) { + type = newType; + uri = newUri; return method; } }; @@ -125,7 +159,7 @@ public class NiciraNvpApiTest { @Test public void executeMethodTest() throws NiciraNvpApiException { - GetMethod gm = mock(GetMethod.class); + final GetMethod gm = mock(GetMethod.class); when(gm.getStatusCode()).thenReturn(HttpStatus.SC_OK); api.executeMethod(gm); @@ -137,7 +171,7 @@ public class NiciraNvpApiTest { */ @Test(expected = NiciraNvpApiException.class) public void executeMethodTestWithLogin() throws NiciraNvpApiException, HttpException, IOException { - GetMethod gm = mock(GetMethod.class); + final GetMethod gm = mock(GetMethod.class); when(client.executeMethod((HttpMethod)any())).thenThrow(new HttpException()); when(gm.getStatusCode()).thenReturn(HttpStatus.SC_UNAUTHORIZED).thenReturn(HttpStatus.SC_UNAUTHORIZED); api.executeMethod(gm); @@ -149,9 +183,9 @@ public class NiciraNvpApiTest { LogicalSwitch ls = new LogicalSwitch(); method = mock(PostMethod.class); when(method.getStatusCode()).thenReturn(HttpStatus.SC_CREATED); - when(method.getResponseBodyAsString()).thenReturn("{ \"uuid\" : \"aaaa\" }"); + when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE); ls = api.executeCreateObject(ls, LogicalSwitch.class, "/", Collections. emptyMap()); - assertTrue("aaaa".equals(ls.getUuid())); + assertTrue(UUID.equals(ls.getUuid())); verify(method, times(1)).releaseConnection(); } @@ -161,7 +195,7 @@ public class NiciraNvpApiTest { LogicalSwitch ls = new LogicalSwitch(); method = mock(PostMethod.class); when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); - Header header = mock(Header.class); + final Header header = mock(Header.class); when(header.getValue()).thenReturn("text/html"); when(method.getResponseHeader("Content-Type")).thenReturn(header); when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later."); @@ -179,7 +213,7 @@ public class NiciraNvpApiTest { when(client.executeMethod((HttpMethod)any())).thenThrow(new HttpException()); method = mock(PostMethod.class); when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); - Header header = mock(Header.class); + final Header header = mock(Header.class); when(header.getValue()).thenReturn("text/html"); when(method.getResponseHeader("Content-Type")).thenReturn(header); when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later."); @@ -192,7 +226,7 @@ public class NiciraNvpApiTest { @Test public void testExecuteUpdateObject() throws NiciraNvpApiException, IOException { - LogicalSwitch ls = new LogicalSwitch(); + final LogicalSwitch ls = new LogicalSwitch(); method = mock(PutMethod.class); when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK); api.executeUpdateObject(ls, "/", Collections. emptyMap()); @@ -202,10 +236,10 @@ public class NiciraNvpApiTest { @Test(expected = NiciraNvpApiException.class) public void testExecuteUpdateObjectFailure() throws NiciraNvpApiException, IOException { - LogicalSwitch ls = new LogicalSwitch(); + final LogicalSwitch ls = new LogicalSwitch(); method = mock(PutMethod.class); when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); - Header header = mock(Header.class); + final Header header = mock(Header.class); when(header.getValue()).thenReturn("text/html"); when(method.getResponseHeader("Content-Type")).thenReturn(header); when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later."); @@ -219,7 +253,7 @@ public class NiciraNvpApiTest { @Test(expected = NiciraNvpApiException.class) public void testExecuteUpdateObjectException() throws NiciraNvpApiException, IOException { - LogicalSwitch ls = new LogicalSwitch(); + final LogicalSwitch ls = new LogicalSwitch(); method = mock(PutMethod.class); when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK); when(client.executeMethod((HttpMethod)any())).thenThrow(new IOException()); @@ -243,7 +277,7 @@ public class NiciraNvpApiTest { public void testExecuteDeleteObjectFailure() throws NiciraNvpApiException, IOException { method = mock(DeleteMethod.class); when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); - Header header = mock(Header.class); + final Header header = mock(Header.class); when(header.getValue()).thenReturn("text/html"); when(method.getResponseHeader("Content-Type")).thenReturn(header); when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later."); @@ -271,7 +305,7 @@ public class NiciraNvpApiTest { public void testExecuteRetrieveObject() throws NiciraNvpApiException, IOException { method = mock(GetMethod.class); when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK); - when(method.getResponseBodyAsString()).thenReturn("{ \"uuid\" : \"aaaa\" }"); + when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE); api.executeRetrieveObject(LogicalSwitch.class, "/", Collections. emptyMap()); verify(method, times(1)).releaseConnection(); verify(client, times(1)).executeMethod(method); @@ -281,8 +315,8 @@ public class NiciraNvpApiTest { public void testExecuteRetrieveObjectFailure() throws NiciraNvpApiException, IOException { method = mock(GetMethod.class); when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); - when(method.getResponseBodyAsString()).thenReturn("{ \"uuid\" : \"aaaa\" }"); - Header header = mock(Header.class); + when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE); + final Header header = mock(Header.class); when(header.getValue()).thenReturn("text/html"); when(method.getResponseHeader("Content-Type")).thenReturn(header); when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later."); @@ -298,7 +332,7 @@ public class NiciraNvpApiTest { public void testExecuteRetrieveObjectException() throws NiciraNvpApiException, IOException { method = mock(GetMethod.class); when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK); - when(method.getResponseBodyAsString()).thenReturn("{ \"uuid\" : \"aaaa\" }"); + when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE); when(client.executeMethod((HttpMethod)any())).thenThrow(new HttpException()); try { api.executeRetrieveObject(LogicalSwitch.class, "/", Collections. emptyMap()); @@ -307,4 +341,135 @@ public class NiciraNvpApiTest { } } + @Test + public void testFindSecurityProfile() throws NiciraNvpApiException, IOException { + // Prepare + method = mock(GetMethod.class); + when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK); + when(method.getResponseBodyAsString()).thenReturn(SEC_PROFILE_LIST_JSON_RESPONSE); + final NameValuePair[] queryString = new NameValuePair[]{ + new NameValuePair("fields","*")}; + + // Execute + final NiciraNvpList actualProfiles = api.findSecurityProfile(); + + // Assert + verify(method, times(1)).releaseConnection(); + verify(method, times(1)).setQueryString(queryString); + assertEquals("Wrong Uuid in the newly created SecurityProfile", + UUID, actualProfiles.getResults().get(0).getUuid()); + assertEquals("Wrong Uuid in the newly created SecurityProfile", + HREF, actualProfiles.getResults().get(0).getHref()); + assertEquals("Wrong Schema in the newly created SecurityProfile", + SCHEMA, actualProfiles.getResults().get(0).getSchema()); + assertEquals("Wrong Uuid in the newly created SecurityProfile", + UUID2, actualProfiles.getResults().get(1).getUuid()); + assertEquals("Wrong Uuid in the newly created SecurityProfile", + HREF2, actualProfiles.getResults().get(1).getHref()); + assertEquals("Wrong Schema in the newly created SecurityProfile", + SCHEMA2, actualProfiles.getResults().get(1).getSchema()); + assertEquals("Wrong Schema in the newly created SecurityProfile", + 2, actualProfiles.getResultCount()); + assertEquals("Wrong URI for SecurityProfile creation REST service", + NiciraNvpApi.SEC_PROFILE_URI_PREFIX, uri); + assertEquals("Wrong URI for SecurityProfile creation REST service", + NiciraNvpApi.GET_METHOD_TYPE, type); + } + + @Test + public void testFindSecurityProfileByUuid() throws NiciraNvpApiException, IOException { + // Prepare + method = mock(GetMethod.class); + when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK); + when(method.getResponseBodyAsString()).thenReturn(SEC_PROFILE_LIST_JSON_RESPONSE); + final NameValuePair[] queryString = new NameValuePair[]{ + new NameValuePair("uuid", UUID), + new NameValuePair("fields","*") + }; + + // Execute + final NiciraNvpList actualProfiles = api.findSecurityProfile(UUID); + + // Assert + verify(method, times(1)).releaseConnection(); + verify(method, times(1)).setQueryString(queryString); + assertEquals("Wrong Uuid in the newly created SecurityProfile", + UUID, actualProfiles.getResults().get(0).getUuid()); + assertEquals("Wrong Uuid in the newly created SecurityProfile", + HREF, actualProfiles.getResults().get(0).getHref()); + assertEquals("Wrong Schema in the newly created SecurityProfile", + SCHEMA, actualProfiles.getResults().get(0).getSchema()); + assertEquals("Wrong Uuid in the newly created SecurityProfile", + UUID2, actualProfiles.getResults().get(1).getUuid()); + assertEquals("Wrong Uuid in the newly created SecurityProfile", + HREF2, actualProfiles.getResults().get(1).getHref()); + assertEquals("Wrong Schema in the newly created SecurityProfile", + SCHEMA2, actualProfiles.getResults().get(1).getSchema()); + assertEquals("Wrong Schema in the newly created SecurityProfile", + 2, actualProfiles.getResultCount()); + assertEquals("Wrong URI for SecurityProfile creation REST service", + NiciraNvpApi.SEC_PROFILE_URI_PREFIX, uri); + assertEquals("Wrong HTTP method for SecurityProfile creation REST service", + NiciraNvpApi.GET_METHOD_TYPE, type); + } + + @Test + public void testCreateSecurityProfile() throws NiciraNvpApiException, IOException { + // Prepare + final SecurityProfile inputSecProfile = new SecurityProfile(); + method = mock(PostMethod.class); + when(method.getStatusCode()).thenReturn(HttpStatus.SC_CREATED); + when(method.getResponseBodyAsString()).thenReturn(SEC_PROFILE_JSON_RESPONSE); + + // Execute + final SecurityProfile actualSecProfile = api.createSecurityProfile(inputSecProfile); + + // Assert + verify(method, times(1)).releaseConnection(); + assertEquals("Wrong Uuid in the newly created SecurityProfile", + UUID, actualSecProfile.getUuid()); + assertEquals("Wrong Uuid in the newly created SecurityProfile", + HREF, actualSecProfile.getHref()); + assertEquals("Wrong Schema in the newly created SecurityProfile", + SCHEMA, actualSecProfile.getSchema()); + assertEquals("Wrong URI for SecurityProfile creation REST service", + NiciraNvpApi.SEC_PROFILE_URI_PREFIX, uri); + assertEquals("Wrong HTTP method for SecurityProfile creation REST service", + NiciraNvpApi.POST_METHOD_TYPE, type); + } + + @Test + public void testUpdateSecurityProfile() throws NiciraNvpApiException, IOException { + // Prepare + final SecurityProfile inputSecProfile = new SecurityProfile(); + method = mock(PutMethod.class); + when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK); + + // Execute + api.updateSecurityProfile(inputSecProfile, UUID); + + // Assert + verify(method, times(1)).releaseConnection(); + assertEquals("Wrong URI for SecurityProfile creation REST service", + UUID_SEC_PROFILE_URI, uri); + assertEquals("Wrong HTTP method for SecurityProfile creation REST service", + NiciraNvpApi.PUT_METHOD_TYPE, type); + } + + @Test + public void testDeleteSecurityProfile() throws NiciraNvpApiException, IOException { + // Prepare + method = mock(DeleteMethod.class); + when(method.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT); + + // Execute + api.deleteSecurityProfile(UUID); + + // Assert + verify(method, times(1)).releaseConnection(); + assertEquals("Wrong URI for SecurityProfile deletion REST service", + UUID_SEC_PROFILE_URI, uri); + assertEquals("Wrong HTTP method for SecurityProfile deletion REST service", + NiciraNvpApi.DELETE_METHOD_TYPE, type); + } } diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraTagTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraTagTest.java index 751280356d9..58dcedc6a89 100644 --- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraTagTest.java +++ b/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraTagTest.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,6 +15,8 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +// + package com.cloud.network.nicira; import static org.junit.Assert.assertEquals; diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java index ad01218909e..2717c3125d8 100644 --- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java +++ b/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,6 +15,8 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +// + package com.cloud.network.resource; import static org.junit.Assert.assertFalse; diff --git a/scripts/network/domr/s2s_vpn.sh b/plugins/network-elements/nicira-nvp/test/resources/config.properties old mode 100755 new mode 100644 similarity index 80% rename from scripts/network/domr/s2s_vpn.sh rename to plugins/network-elements/nicira-nvp/test/resources/config.properties index 3ec3e260636..4006e38d64e --- a/scripts/network/domr/s2s_vpn.sh +++ b/plugins/network-elements/nicira-nvp/test/resources/config.properties @@ -1,4 +1,4 @@ -#!/bin/bash +# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information @@ -15,15 +15,9 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. +# - - -# @VERSION@ - -cert="/root/.ssh/id_rsa.cloud" -domr=$1 -shift -ssh -p 3922 -o StrictHostKeyChecking=no -i $cert root@$domr "/opt/cloud/bin/ipsectunnel.sh $*" >/dev/null - -exit $? +nvp.host=${nvp-host} +nvp.admin.user=${nvp-admin-user} +nvp.admin.pwd=${nvp-admin-pwd} diff --git a/plugins/network-elements/opendaylight/pom.xml b/plugins/network-elements/opendaylight/pom.xml new file mode 100644 index 00000000000..decfd676cd4 --- /dev/null +++ b/plugins/network-elements/opendaylight/pom.xml @@ -0,0 +1,86 @@ + + + 4.0.0 + cloud-plugin-network-opendaylight + Apache CloudStack Plugin - Network Opendaylight + + org.apache.cloudstack + cloudstack-plugins + 4.4.0-SNAPSHOT + ../../pom.xml + + + + + ${basedir}/src/main/java + ${basedir}/src/main/scripts + ${basedir}/src/test/java + ${basedir}/target/classes + ${basedir}/target/test-classes + + + ${basedir}/src/main/resources + + + + + ${basedir}/src/test/resources + + + + + com.mycila + license-maven-plugin + + + cloudstack-checklicence + process-classes + + check + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-failsafe-plugin + + + + integration-test + verify + + + + + + + + + diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/OpendaylightElement.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/OpendaylightElement.java new file mode 100644 index 00000000000..05bc8317090 --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/OpendaylightElement.java @@ -0,0 +1,174 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.ejb.Local; +import javax.inject.Inject; +import javax.naming.ConfigurationException; + +import org.apache.log4j.Logger; +import org.springframework.stereotype.Component; + +import org.apache.cloudstack.network.opendaylight.agent.commands.StartupOpenDaylightControllerCommand; + +import com.cloud.agent.api.StartupCommand; +import com.cloud.deploy.DeployDestination; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.host.Host; +import com.cloud.host.HostVO; +import com.cloud.network.Network; +import com.cloud.network.Network.Capability; +import com.cloud.network.Network.Provider; +import com.cloud.network.Network.Service; +import com.cloud.network.PhysicalNetworkServiceProvider; +import com.cloud.network.element.ConnectivityProvider; +import com.cloud.network.element.NetworkElement; +import com.cloud.offering.NetworkOffering; +import com.cloud.resource.ResourceManager; +import com.cloud.resource.ResourceStateAdapter; +import com.cloud.resource.ServerResource; +import com.cloud.resource.UnableDeleteHostException; +import com.cloud.utils.component.AdapterBase; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.vm.NicProfile; +import com.cloud.vm.ReservationContext; +import com.cloud.vm.VirtualMachineProfile; + +@Component +@Local(value = {NetworkElement.class, ConnectivityProvider.class}) +public class OpendaylightElement extends AdapterBase implements ConnectivityProvider, ResourceStateAdapter { + + private static final Logger s_logger = Logger.getLogger(OpendaylightElement.class); + private static final Map> s_capabilities = setCapabilities(); + + @Inject + ResourceManager resourceManager; + + @Override + public Map> getCapabilities() { + return s_capabilities; + } + + @Override + public Provider getProvider() { + return Provider.Opendaylight; + } + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + boolean configured = super.configure(name, params); + if (configured) + resourceManager.registerResourceStateAdapter(name, this); + return configured; + } + + @Override + public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, + ResourceUnavailableException, InsufficientCapacityException { + // TODO Auto-generated method stub + return true; + } + + @Override + public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, + ResourceUnavailableException, InsufficientCapacityException { + // TODO Auto-generated method stub + return true; + } + + @Override + public boolean release(Network network, NicProfile nic, VirtualMachineProfile vm, ReservationContext context) throws ConcurrentOperationException, + ResourceUnavailableException { + // TODO Auto-generated method stub + return true; + } + + @Override + public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException { + return true; + } + + @Override + public boolean destroy(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { + return true; + } + + @Override + public boolean isReady(PhysicalNetworkServiceProvider provider) { + return true; + } + + @Override + public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException, + ResourceUnavailableException { + return true; + } + + @Override + public boolean canEnableIndividualServices() { + return false; + } + + @Override + public boolean verifyServicesCombination(Set services) { + if (services.contains(Service.Connectivity) && services.size() == 1) + return true; + return false; + } + + @Override + public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] startup) { + if (!(startup[0] instanceof StartupOpenDaylightControllerCommand)) { + return null; + } + throw new CloudRuntimeException("createHostVOForConnectedAgent is not implemented for OpendaylightElement"); + } + + @Override + public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map details, List hostTags) { + if (!(startup[0] instanceof StartupOpenDaylightControllerCommand)) { + return null; + } + host.setType(Host.Type.L2Networking); + return host; + } + + @Override + public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { + return new DeleteHostAnswer(true); + } + + private static Map> setCapabilities() { + Map> capabilities = new HashMap>(); + + // L2 Support : SDN provisioning + capabilities.put(Service.Connectivity, null); + + return capabilities; + } + +} diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/OpendaylightGuestNetworkGuru.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/OpendaylightGuestNetworkGuru.java new file mode 100644 index 00000000000..a6089558775 --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/OpendaylightGuestNetworkGuru.java @@ -0,0 +1,276 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight; + +import java.util.List; +import java.util.UUID; + +import javax.inject.Inject; + +import org.apache.log4j.Logger; + +import org.apache.cloudstack.network.opendaylight.agent.commands.AddHypervisorCommand; +import org.apache.cloudstack.network.opendaylight.agent.commands.ConfigureNetworkCommand; +import org.apache.cloudstack.network.opendaylight.agent.commands.ConfigurePortCommand; +import org.apache.cloudstack.network.opendaylight.agent.commands.DestroyNetworkCommand; +import org.apache.cloudstack.network.opendaylight.agent.commands.DestroyPortCommand; +import org.apache.cloudstack.network.opendaylight.agent.responses.AddHypervisorAnswer; +import org.apache.cloudstack.network.opendaylight.agent.responses.ConfigureNetworkAnswer; +import org.apache.cloudstack.network.opendaylight.agent.responses.ConfigurePortAnswer; +import org.apache.cloudstack.network.opendaylight.agent.responses.DestroyNetworkAnswer; +import org.apache.cloudstack.network.opendaylight.agent.responses.DestroyPortAnswer; +import org.apache.cloudstack.network.opendaylight.dao.OpenDaylightControllerMappingDao; +import org.apache.cloudstack.network.opendaylight.dao.OpenDaylightControllerVO; + +import com.cloud.agent.AgentManager; +import com.cloud.dc.DataCenter; +import com.cloud.dc.DataCenter.NetworkType; +import com.cloud.deploy.DeployDestination; +import com.cloud.deploy.DeploymentPlan; +import com.cloud.exception.InsufficientAddressCapacityException; +import com.cloud.exception.InsufficientVirtualNetworkCapcityException; +import com.cloud.network.Network; +import com.cloud.network.Network.GuestType; +import com.cloud.network.Network.Provider; +import com.cloud.network.Network.Service; +import com.cloud.network.Network.State; +import com.cloud.network.NetworkModel; +import com.cloud.network.NetworkProfile; +import com.cloud.network.Networks.BroadcastDomainType; +import com.cloud.network.PhysicalNetwork; +import com.cloud.network.PhysicalNetwork.IsolationMethod; +import com.cloud.network.dao.NetworkDao; +import com.cloud.network.dao.NetworkVO; +import com.cloud.network.dao.PhysicalNetworkDao; +import com.cloud.network.dao.PhysicalNetworkVO; +import com.cloud.network.guru.GuestNetworkGuru; +import com.cloud.offering.NetworkOffering; +import com.cloud.offerings.dao.NetworkOfferingServiceMapDao; +import com.cloud.user.Account; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.vm.NicProfile; +import com.cloud.vm.ReservationContext; +import com.cloud.vm.VirtualMachineProfile; + +public class OpendaylightGuestNetworkGuru extends GuestNetworkGuru { + private static final Logger s_logger = Logger.getLogger(OpendaylightGuestNetworkGuru.class); + + @Inject + protected NetworkOfferingServiceMapDao ntwkOfferingSrvcDao; + @Inject + PhysicalNetworkDao physicalNetworkDao; + @Inject + OpenDaylightControllerMappingDao openDaylightControllerMappingDao; + @Inject + NetworkModel networkModel; + @Inject + AgentManager agentManager; + @Inject + NetworkDao networkDao; + + public OpendaylightGuestNetworkGuru() { + _isolationMethods = new IsolationMethod[] {IsolationMethod.ODL}; + } + + @Override + protected boolean canHandle(NetworkOffering offering, NetworkType networkType, PhysicalNetwork physicalNetwork) { + if (networkType == NetworkType.Advanced && isMyTrafficType(offering.getTrafficType()) && offering.getGuestType() == Network.GuestType.Isolated && + isMyIsolationMethod(physicalNetwork) && ntwkOfferingSrvcDao.areServicesSupportedByNetworkOffering(offering.getId(), Service.Connectivity) + && ntwkOfferingSrvcDao.isProviderForNetworkOffering(offering.getId(), Provider.Opendaylight)) { + return true; + } else { + s_logger.trace("We only take care of Guest networks of type " + GuestType.Isolated + " in zone of type " + NetworkType.Advanced); + return false; + } + } + + @Override + public Network design(NetworkOffering offering, DeploymentPlan plan, Network userSpecified, Account owner) { + PhysicalNetworkVO physnet = physicalNetworkDao.findById(plan.getPhysicalNetworkId()); + DataCenter dc = _dcDao.findById(plan.getDataCenterId()); + if (!canHandle(offering, dc.getNetworkType(), physnet)) { + s_logger.debug("Refusing to design this network"); + return null; + } + + List devices = openDaylightControllerMappingDao.listByPhysicalNetwork(physnet.getId()); + if (devices.isEmpty()) { + s_logger.error("No Controller on physical network " + physnet.getName()); + return null; + } + s_logger.debug("Controller " + devices.get(0).getUuid() + " found on physical network " + physnet.getId()); + s_logger.debug("Physical isolation type is ODL, asking GuestNetworkGuru to design this network"); + + NetworkVO networkObject = (NetworkVO)super.design(offering, plan, userSpecified, owner); + if (networkObject == null) { + return null; + } + // Override the broadcast domain type + networkObject.setBroadcastDomainType(BroadcastDomainType.OpenDaylight); + + return networkObject; + } + + @Override + public Network implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws InsufficientVirtualNetworkCapcityException { + assert (network.getState() == State.Implementing) : "Why are we implementing " + network; + + long dcId = dest.getDataCenter().getId(); + + //get physical network id + Long physicalNetworkId = network.getPhysicalNetworkId(); + + // physical network id can be null in Guest Network in Basic zone, so locate the physical network + if (physicalNetworkId == null) { + physicalNetworkId = networkModel.findPhysicalNetworkId(dcId, offering.getTags(), offering.getTrafficType()); + } + + NetworkVO implemented = new NetworkVO(network.getTrafficType(), network.getMode(), network.getBroadcastDomainType(), network.getNetworkOfferingId(), State.Allocated, + network.getDataCenterId(), physicalNetworkId); + + if (network.getGateway() != null) { + implemented.setGateway(network.getGateway()); + } + + if (network.getCidr() != null) { + implemented.setCidr(network.getCidr()); + } + + // Name is either the given name or the uuid + String name = network.getName(); + if (name == null || name.isEmpty()) { + name = ((NetworkVO)network).getUuid(); + } + + List devices = openDaylightControllerMappingDao.listByPhysicalNetwork(physicalNetworkId); + if (devices.isEmpty()) { + s_logger.error("No Controller on physical network " + physicalNetworkId); + return null; + } + OpenDaylightControllerVO controller = devices.get(0); + + ConfigureNetworkCommand cmd = new ConfigureNetworkCommand(name, context.getAccount().getAccountName()); + ConfigureNetworkAnswer answer = (ConfigureNetworkAnswer)agentManager.easySend(controller.getHostId(), cmd); + + if (answer == null || !answer.getResult()) { + s_logger.error("ConfigureNetworkCommand failed"); + return null; + } + + implemented.setBroadcastUri(BroadcastDomainType.OpenDaylight.toUri(answer.getNetworkUuid())); + implemented.setBroadcastDomainType(BroadcastDomainType.OpenDaylight); + s_logger.info("Implemented OK, network linked to = " + implemented.getBroadcastUri().toString()); + + return implemented; + } + + @Override + public void reserve(NicProfile nic, Network network, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) + throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException { + super.reserve(nic, network, vm, dest, context); + + //get physical network id + Long physicalNetworkId = network.getPhysicalNetworkId(); + + List devices = openDaylightControllerMappingDao.listByPhysicalNetwork(physicalNetworkId); + if (devices.isEmpty()) { + s_logger.error("No Controller on physical network " + physicalNetworkId); + throw new InsufficientVirtualNetworkCapcityException("No OpenDaylight Controller configured for this network", dest.getPod().getId()); + } + OpenDaylightControllerVO controller = devices.get(0); + + AddHypervisorCommand addCmd = new AddHypervisorCommand(dest.getHost().getUuid(), dest.getHost().getPrivateIpAddress()); + AddHypervisorAnswer addAnswer = (AddHypervisorAnswer)agentManager.easySend(controller.getHostId(), addCmd); + if (addAnswer == null || !addAnswer.getResult()) { + s_logger.error("Failed to add " + dest.getHost().getName() + " as a node to the controller"); + throw new InsufficientVirtualNetworkCapcityException("Failed to add destination hypervisor to the OpenDaylight Controller", dest.getPod().getId()); + } + + ConfigurePortCommand cmd = new ConfigurePortCommand(UUID.fromString(nic.getUuid()), UUID.fromString(BroadcastDomainType.getValue(network.getBroadcastUri())), context + .getAccount().getAccountName(), nic.getMacAddress()); + ConfigurePortAnswer answer = (ConfigurePortAnswer)agentManager.easySend(controller.getHostId(), cmd); + + if (answer == null || !answer.getResult()) { + s_logger.error("ConfigureNetworkCommand failed"); + throw new InsufficientVirtualNetworkCapcityException("Failed to configure the port on the OpenDaylight Controller", dest.getPod().getId()); + } + + } + + @Override + public boolean release(NicProfile nic, VirtualMachineProfile vm, String reservationId) { + boolean success = super.release(nic, vm, reservationId); + + if (success) { + //get physical network id + NetworkVO network = _networkDao.findById(nic.getNetworkId()); + Long physicalNetworkId = network.getPhysicalNetworkId(); + + List devices = openDaylightControllerMappingDao.listByPhysicalNetwork(physicalNetworkId); + if (devices.isEmpty()) { + s_logger.error("No Controller on physical network " + physicalNetworkId); + throw new CloudRuntimeException("No OpenDaylight controller on this physical network"); + } + OpenDaylightControllerVO controller = devices.get(0); + + DestroyPortCommand cmd = new DestroyPortCommand(UUID.fromString(nic.getUuid())); + DestroyPortAnswer answer = (DestroyPortAnswer)agentManager.easySend(controller.getHostId(), cmd); + + if (answer == null || !answer.getResult()) { + s_logger.error("DestroyPortCommand failed"); + success = false; + } + } + + return success; + } + + @Override + public void shutdown(NetworkProfile profile, NetworkOffering offering) { + NetworkVO networkObject = networkDao.findById(profile.getId()); + if (networkObject.getBroadcastDomainType() != BroadcastDomainType.OpenDaylight || networkObject.getBroadcastUri() == null) { + s_logger.warn("BroadcastUri is empty or incorrect for guestnetwork " + networkObject.getDisplayText()); + return; + } + + List devices = openDaylightControllerMappingDao.listByPhysicalNetwork(networkObject.getPhysicalNetworkId()); + if (devices.isEmpty()) { + s_logger.error("No Controller on physical network " + networkObject.getPhysicalNetworkId()); + return; + } + OpenDaylightControllerVO controller = devices.get(0); + + DestroyNetworkCommand cmd = new DestroyNetworkCommand(BroadcastDomainType.getValue(networkObject.getBroadcastUri())); + DestroyNetworkAnswer answer = (DestroyNetworkAnswer)agentManager.easySend(controller.getHostId(), cmd); + + if (answer == null || !answer.getResult()) { + s_logger.error("DestroyNetworkCommand failed"); + } + + super.shutdown(profile, offering); + } + + @Override + public boolean trash(Network network, NetworkOffering offering) { + // TODO Auto-generated method stub + return super.trash(network, offering); + } + +} diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/OpenDaylightControllerResource.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/OpenDaylightControllerResource.java new file mode 100644 index 00000000000..5473858531d --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/OpenDaylightControllerResource.java @@ -0,0 +1,344 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.agent; + +import java.net.MalformedURLException; +import java.net.URL; +import java.security.InvalidParameterException; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Random; +import java.util.UUID; + +import javax.naming.ConfigurationException; + +import org.apache.log4j.Logger; + +import org.apache.cloudstack.network.opendaylight.agent.commands.AddHypervisorCommand; +import org.apache.cloudstack.network.opendaylight.agent.commands.ConfigureNetworkCommand; +import org.apache.cloudstack.network.opendaylight.agent.commands.ConfigurePortCommand; +import org.apache.cloudstack.network.opendaylight.agent.commands.DestroyNetworkCommand; +import org.apache.cloudstack.network.opendaylight.agent.commands.DestroyPortCommand; +import org.apache.cloudstack.network.opendaylight.agent.commands.StartupOpenDaylightControllerCommand; +import org.apache.cloudstack.network.opendaylight.agent.responses.AddHypervisorAnswer; +import org.apache.cloudstack.network.opendaylight.agent.responses.ConfigureNetworkAnswer; +import org.apache.cloudstack.network.opendaylight.agent.responses.ConfigurePortAnswer; +import org.apache.cloudstack.network.opendaylight.agent.responses.DestroyNetworkAnswer; +import org.apache.cloudstack.network.opendaylight.agent.responses.DestroyPortAnswer; +import org.apache.cloudstack.network.opendaylight.api.NeutronRestApiException; +import org.apache.cloudstack.network.opendaylight.api.model.NeutronNetwork; +import org.apache.cloudstack.network.opendaylight.api.model.NeutronNetworkWrapper; +import org.apache.cloudstack.network.opendaylight.api.model.NeutronNetworksList; +import org.apache.cloudstack.network.opendaylight.api.model.NeutronNode; +import org.apache.cloudstack.network.opendaylight.api.model.NeutronNodeWrapper; +import org.apache.cloudstack.network.opendaylight.api.model.NeutronNodesList; +import org.apache.cloudstack.network.opendaylight.api.model.NeutronPort; +import org.apache.cloudstack.network.opendaylight.api.model.NeutronPortWrapper; +import org.apache.cloudstack.network.opendaylight.api.resources.NeutronNetworksNorthboundAction; +import org.apache.cloudstack.network.opendaylight.api.resources.NeutronNodesNorthboundAction; +import org.apache.cloudstack.network.opendaylight.api.resources.NeutronPortsNorthboundAction; + +import com.cloud.agent.IAgentControl; +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.Command; +import com.cloud.agent.api.MaintainAnswer; +import com.cloud.agent.api.MaintainCommand; +import com.cloud.agent.api.PingCommand; +import com.cloud.agent.api.ReadyAnswer; +import com.cloud.agent.api.ReadyCommand; +import com.cloud.agent.api.StartupCommand; +import com.cloud.host.Host; +import com.cloud.host.Host.Type; +import com.cloud.resource.ServerResource; + +public class OpenDaylightControllerResource implements ServerResource { + private static final Logger s_logger = Logger.getLogger(OpenDaylightControllerResource.class); + private Map configuration = new HashMap(); + + private URL controllerUrl; + private String controllerUsername; + private String controllerPassword; + + private int runLevel; + + @Override + public String getName() { + if (configuration.containsKey("name")) + return (String)configuration.get("name"); + else + return null; + } + + @Override + public void setName(String name) { + configuration.put("name", name); + } + + @Override + public void setConfigParams(Map params) { + for (Entry entry : params.entrySet()) { + configuration.put(entry.getKey(), entry.getValue()); + } + updateConfiguration(); + } + + @Override + public Map getConfigParams() { + return Collections.unmodifiableMap(configuration); + } + + @Override + public int getRunLevel() { + return runLevel; + } + + @Override + public void setRunLevel(int level) { + runLevel = level; + } + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + for (Entry entry : params.entrySet()) { + configuration.put(entry.getKey(), entry.getValue()); + } + updateConfiguration(); + return true; + } + + @Override + public boolean start() { + return true; + } + + @Override + public boolean stop() { + return true; + } + + @Override + public Type getType() { + return Type.L2Networking; + } + + @Override + public StartupCommand[] initialize() { + StartupOpenDaylightControllerCommand sc = new StartupOpenDaylightControllerCommand(); + sc.setGuid((String)configuration.get("guid")); + sc.setName(getName()); + sc.setDataCenter((String)configuration.get("zoneId")); + sc.setPod(""); + sc.setPrivateIpAddress(""); + sc.setStorageIpAddress(""); + sc.setVersion(OpenDaylightControllerResource.class.getPackage().getImplementationVersion()); + return new StartupCommand[] {sc}; + + } + + @Override + public PingCommand getCurrentStatus(long id) { + return new PingCommand(Host.Type.L2Networking, id); + } + + @Override + public Answer executeRequest(Command cmd) { + if (cmd instanceof ConfigureNetworkCommand) { + return executeRequest((ConfigureNetworkCommand)cmd); + } else if (cmd instanceof DestroyNetworkCommand) { + return executeRequest((DestroyNetworkCommand)cmd); + } else if (cmd instanceof ConfigurePortCommand) { + return executeRequest((ConfigurePortCommand)cmd); + } else if (cmd instanceof DestroyPortCommand) { + return executeRequest((DestroyPortCommand)cmd); + } else if (cmd instanceof AddHypervisorCommand) { + return executeRequest((AddHypervisorCommand)cmd); + } else if (cmd instanceof ReadyCommand) { + return executeRequest((ReadyCommand)cmd); + } else if (cmd instanceof MaintainCommand) { + return executeRequest((MaintainCommand)cmd); + } else { + return Answer.createUnsupportedCommandAnswer(cmd); + } + } + + @Override + public void disconnected() { + s_logger.warn("OpenDaylightControllerResource is disconnected from the controller at " + controllerUrl); + + } + + @Override + public IAgentControl getAgentControl() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setAgentControl(IAgentControl agentControl) { + // TODO Auto-generated method stub + + } + + private Answer executeRequest(final ReadyCommand cmd) { + return new ReadyAnswer(cmd); + } + + private Answer executeRequest(final MaintainCommand cmd) { + return new MaintainAnswer(cmd); + } + + private Answer executeRequest(ConfigureNetworkCommand cmd) { + NeutronNetworksNorthboundAction configureNetwork = new NeutronNetworksNorthboundAction(controllerUrl, controllerUsername, controllerPassword); + + // Find free gre key + int gre_key = -1; + Random keyGenerator = new Random(System.currentTimeMillis()); + try { + NeutronNetworksList networks = configureNetwork.listAllNetworks(); + while (true) { + int i = keyGenerator.nextInt(); + for (NeutronNetwork network : networks.getNetworks()) { + if (network.getSegmentationId() == i) { + continue; + } + } + gre_key = i; + break; + } + } catch (NeutronRestApiException e) { + s_logger.error("Failed to list existing networks on the ODL Controller", e); + return new ConfigureNetworkAnswer(cmd, e); + } + + NeutronNetwork newNetwork = new NeutronNetwork(); + + // Configuration from the command + newNetwork.setName(cmd.getName()); + newNetwork.setTenantId(cmd.getTenantId()); + + // Static configuation + newNetwork.setNetworkType("gre"); + newNetwork.setShared(false); + newNetwork.setSegmentationId(gre_key); + newNetwork.setId(UUID.randomUUID()); + + NeutronNetworkWrapper wrapper = new NeutronNetworkWrapper(); + wrapper.setNetwork(newNetwork); + try { + wrapper = configureNetwork.createNeutronNetwork(wrapper); + } catch (NeutronRestApiException e) { + s_logger.error("createNeutronNetwork failed", e); + return new ConfigureNetworkAnswer(cmd, e); + } + + return new ConfigureNetworkAnswer(cmd, true, null, wrapper.getNetwork().getId().toString()); + } + + private Answer executeRequest(DestroyNetworkCommand cmd) { + NeutronNetworksNorthboundAction configureNetwork = new NeutronNetworksNorthboundAction(controllerUrl, controllerUsername, controllerPassword); + try { + configureNetwork.deleteNeutronNetwork(cmd.getNetworkUuid()); + } catch (NeutronRestApiException e) { + s_logger.error("deleteNeutronNetwork failed", e); + return new DestroyNetworkAnswer(cmd, e); + } + + return new DestroyNetworkAnswer(cmd, true, "Network " + cmd.getNetworkUuid() + " deleted"); + } + + private Answer executeRequest(ConfigurePortCommand cmd) { + NeutronPortsNorthboundAction configurePort = new NeutronPortsNorthboundAction(controllerUrl, controllerUsername, controllerPassword); + NeutronPort newPort = new NeutronPort(); + + // Configuration from the command + newPort.setId(cmd.getPortId()); + newPort.setTenantId(cmd.getTennantId()); + newPort.setAdminStateUp(true); + newPort.setName(cmd.getPortId().toString()); + newPort.setNetworkId(cmd.getNetworkId()); + newPort.setMacAddress(cmd.getMacAddress()); + newPort.setDeviceId(UUID.randomUUID()); + + // Static valus + newPort.setStatus("ACTIVE"); + newPort.setFixedIps(Collections. emptyList()); + + NeutronPortWrapper portWrapper = new NeutronPortWrapper(); + portWrapper.setPort(newPort); + try { + portWrapper = configurePort.createNeutronPort(portWrapper); + } catch (NeutronRestApiException e) { + s_logger.error("createPortCommand failed", e); + return new ConfigurePortAnswer(cmd, e); + } + + return new ConfigurePortAnswer(cmd, true, "Port " + portWrapper.getPort().getId().toString() + " created"); + + } + + private Answer executeRequest(DestroyPortCommand cmd) { + NeutronPortsNorthboundAction configurePort = new NeutronPortsNorthboundAction(controllerUrl, controllerUsername, controllerPassword); + try { + configurePort.deleteNeutronPort(cmd.getPortId().toString()); + } catch (NeutronRestApiException e) { + s_logger.error("deleteNeutronPort failed", e); + return new DestroyPortAnswer(cmd, e); + } + + return new DestroyPortAnswer(cmd, true, "Port " + cmd.getPortId().toString() + " deleted"); + } + + private Answer executeRequest(AddHypervisorCommand cmd) { + NeutronNodesNorthboundAction nodeActions = new NeutronNodesNorthboundAction(controllerUrl, controllerUsername, controllerPassword); + try { + NeutronNodesList nodes = nodeActions.listAllNodes(); + if (nodes.getNodes() != null) { + for (NeutronNodeWrapper nodeWrapper : nodes.getNodes()) { + NeutronNode node = nodeWrapper.getNode(); + if (node.getId().equals(cmd.getHostId())) { + return new AddHypervisorAnswer(cmd, true, "Hypervisor already connected"); + } + } + } + + // Not found in the existing node list, add it + nodeActions.updateNeutronNodeV2("OVS", cmd.getHostId(), cmd.getIpAddress(), 6640); + } catch (NeutronRestApiException e) { + s_logger.error("Call to OpenDaylight failed", e); + return new AddHypervisorAnswer(cmd, e); + } + return new AddHypervisorAnswer(cmd, true, "Hypervisor " + cmd.getHostId() + " added"); + } + + private void updateConfiguration() { + if (!configuration.containsKey("url") || !configuration.containsKey("username") || !configuration.containsKey("password")) + throw new InvalidParameterException("OpenDaylightControllerResource needs a url, username and password."); + try { + controllerUrl = new URL((String)configuration.get("url")); + } catch (MalformedURLException e) { + throw new InvalidParameterException("OpenDaylightControllerResource found an invalid controller url"); + } + controllerUsername = (String)configuration.get("username"); + controllerPassword = (String)configuration.get("password"); + } + +} diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/OpenDaylightControllerResourceManager.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/OpenDaylightControllerResourceManager.java new file mode 100644 index 00000000000..db1ea37ebbf --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/OpenDaylightControllerResourceManager.java @@ -0,0 +1,42 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.agent; + +import java.util.List; + +import org.apache.cloudstack.network.opendaylight.api.commands.AddOpenDaylightControllerCmd; +import org.apache.cloudstack.network.opendaylight.api.commands.DeleteOpenDaylightControllerCmd; +import org.apache.cloudstack.network.opendaylight.api.commands.ListOpenDaylightControllersCmd; +import org.apache.cloudstack.network.opendaylight.api.responses.OpenDaylightControllerResponse; +import org.apache.cloudstack.network.opendaylight.dao.OpenDaylightControllerVO; + +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.utils.component.PluggableService; + +public interface OpenDaylightControllerResourceManager extends PluggableService { + + public OpenDaylightControllerVO addController(AddOpenDaylightControllerCmd cmd); + + public void deleteController(DeleteOpenDaylightControllerCmd cmd) throws InvalidParameterValueException; + + public List listControllers(ListOpenDaylightControllersCmd cmd); + + public OpenDaylightControllerResponse createResponseFromVO(OpenDaylightControllerVO controller); +} diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/OpenDaylightControllerResourceManagerImpl.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/OpenDaylightControllerResourceManagerImpl.java new file mode 100644 index 00000000000..013c3028071 --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/OpenDaylightControllerResourceManagerImpl.java @@ -0,0 +1,219 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.agent; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.inject.Inject; +import javax.naming.ConfigurationException; + +import org.apache.log4j.Logger; + +import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice; +import org.apache.cloudstack.network.opendaylight.api.commands.AddOpenDaylightControllerCmd; +import org.apache.cloudstack.network.opendaylight.api.commands.DeleteOpenDaylightControllerCmd; +import org.apache.cloudstack.network.opendaylight.api.commands.ListOpenDaylightControllersCmd; +import org.apache.cloudstack.network.opendaylight.api.responses.OpenDaylightControllerResponse; +import org.apache.cloudstack.network.opendaylight.dao.OpenDaylightControllerMappingDao; +import org.apache.cloudstack.network.opendaylight.dao.OpenDaylightControllerVO; + +import com.cloud.api.ApiDBUtils; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.host.Host; +import com.cloud.host.HostVO; +import com.cloud.host.dao.HostDao; +import com.cloud.network.Network; +import com.cloud.network.Networks; +import com.cloud.network.PhysicalNetwork; +import com.cloud.network.PhysicalNetworkServiceProvider; +import com.cloud.network.dao.NetworkDao; +import com.cloud.network.dao.NetworkVO; +import com.cloud.network.dao.PhysicalNetworkDao; +import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; +import com.cloud.network.dao.PhysicalNetworkServiceProviderVO; +import com.cloud.network.dao.PhysicalNetworkVO; +import com.cloud.resource.ResourceManager; +import com.cloud.resource.ResourceState; +import com.cloud.resource.ServerResource; +import com.cloud.utils.db.Transaction; +import com.cloud.utils.db.TransactionCallback; +import com.cloud.utils.db.TransactionStatus; +import com.cloud.utils.exception.CloudRuntimeException; + +public class OpenDaylightControllerResourceManagerImpl implements OpenDaylightControllerResourceManager { + private final static Logger s_logger = Logger.getLogger(OpenDaylightControllerResourceManagerImpl.class); + + @Inject + HostDao hostDao; + @Inject + ResourceManager resourceManager; + @Inject + PhysicalNetworkDao physicalNetworkDao; + @Inject + PhysicalNetworkServiceProviderDao physicalNetworkServiceProviderDao; + @Inject + OpenDaylightControllerMappingDao openDaylightControllerMappingDao; + @Inject + NetworkDao networkDao; + + @Override + public List> getCommands() { + List> commands = new ArrayList>(); + commands.add(AddOpenDaylightControllerCmd.class); + commands.add(DeleteOpenDaylightControllerCmd.class); + commands.add(ListOpenDaylightControllersCmd.class); + return commands; + } + + @Override + public OpenDaylightControllerVO addController(AddOpenDaylightControllerCmd cmd) { + ServerResource odlController = new OpenDaylightControllerResource(); + + final String deviceName = NetworkDevice.OpenDaylightController.getName(); + NetworkDevice networkDevice = NetworkDevice.getNetworkDevice(deviceName); + if (networkDevice == null) { + throw new CloudRuntimeException("No network device found for name " + deviceName); + } + final Long physicalNetworkId = cmd.getPhysicalNetworkId(); + PhysicalNetworkVO physicalNetwork = physicalNetworkDao.findById(physicalNetworkId); + if (physicalNetwork == null) { + throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId); + } + long zoneId = physicalNetwork.getDataCenterId(); + + final PhysicalNetworkServiceProviderVO ntwkSvcProvider = physicalNetworkServiceProviderDao.findByServiceProvider(physicalNetwork.getId(), + networkDevice.getNetworkServiceProvder()); + if (ntwkSvcProvider == null) { + throw new CloudRuntimeException("Network Service Provider: " + networkDevice.getNetworkServiceProvder() + " is not enabled in the physical network: " + + physicalNetworkId + "to add this device"); + } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) { + throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() + " is in shutdown state in the physical network: " + + physicalNetworkId + "to add this device"); + } + + final Map hostParams = new HashMap(); + hostParams.put("guid", UUID.randomUUID().toString()); + hostParams.put("zoneId", String.valueOf(physicalNetwork.getDataCenterId())); + hostParams.put("physicalNetworkId", String.valueOf(physicalNetwork.getId())); + hostParams.put("name", "ODL Controller - " + hostParams.get("guid")); + hostParams.put("url", cmd.getUrl()); + hostParams.put("username", cmd.getUsername()); + hostParams.put("password", cmd.getPassword()); + + Map hostdetails = new HashMap(); + hostdetails.putAll(hostParams); + + try { + odlController.configure(hostParams.get("name"), hostdetails); + final Host host = resourceManager.addHost(zoneId, odlController, Host.Type.L2Networking, hostParams); + if (host != null) { + return Transaction.execute(new TransactionCallback() { + @Override + public OpenDaylightControllerVO doInTransaction(TransactionStatus status) { + OpenDaylightControllerVO controller = new OpenDaylightControllerVO(host.getId(), physicalNetworkId, ntwkSvcProvider.getProviderName(), hostParams + .get("name")); + openDaylightControllerMappingDao.persist(controller); + return controller; + } + }); + } else { + throw new CloudRuntimeException("Failed to create host object for ODL Controller"); + } + } catch (ConfigurationException e) { + throw new CloudRuntimeException("Failed to add ODL Controller as a resource", e); + } + } + + @Override + public void deleteController(DeleteOpenDaylightControllerCmd cmd) throws InvalidParameterValueException { + OpenDaylightControllerVO controller = openDaylightControllerMappingDao.findById(cmd.getId()); + if (controller == null) { + throw new InvalidParameterValueException("No ODL Controller with id " + cmd.getId()); + } + + // Find the physical network we work for + Long physicalNetworkId = controller.getPhysicalNetworkId(); + PhysicalNetworkVO physicalNetwork = physicalNetworkDao.findById(physicalNetworkId); + if (physicalNetwork != null) { + // Lets see if there are networks that use us + List networkList = networkDao.listByPhysicalNetwork(physicalNetworkId); + + if (networkList != null) { + // Networks with broadcast type lswitch are ours + for (NetworkVO network : networkList) { + if (network.getBroadcastDomainType() == Networks.BroadcastDomainType.OpenDaylight) { + if ((network.getState() != Network.State.Shutdown) && (network.getState() != Network.State.Destroy)) { + throw new CloudRuntimeException("This Controller can not be deleted as there are one or more logical networks provisioned by cloudstack."); + } + } + } + } + } + + HostVO host = hostDao.findById(controller.getHostId()); + Long hostId = host.getId(); + + host.setResourceState(ResourceState.Maintenance); + hostDao.update(hostId, host); + resourceManager.deleteHost(hostId, false, false); + + openDaylightControllerMappingDao.remove(cmd.getId()); + } + + @Override + public List listControllers(ListOpenDaylightControllersCmd cmd) { + if (cmd.getId() != null) { + List foundControllers = new ArrayList(); + OpenDaylightControllerVO controller = openDaylightControllerMappingDao.findById(cmd.getId()); + if (controller != null) { + foundControllers.add(controller); + } + return foundControllers; + } else if (cmd.getPhysicalNetworkId() != null) { + return openDaylightControllerMappingDao.listByPhysicalNetwork(cmd.getPhysicalNetworkId()); + } + return openDaylightControllerMappingDao.listAll(); + } + + @Override + public OpenDaylightControllerResponse createResponseFromVO(OpenDaylightControllerVO controller) { + OpenDaylightControllerResponse response = new OpenDaylightControllerResponse(); + HostVO controllerHost = hostDao.findById(controller.getHostId()); + hostDao.loadDetails(controllerHost); + + PhysicalNetwork pnw = ApiDBUtils.findPhysicalNetworkById(controller.getPhysicalNetworkId()); + if (pnw != null) { + response.setPhysicalNetworkId(pnw.getUuid()); + } + + response.setObjectName("opendaylightcontroller"); + response.setId(controller.getUuid()); + response.setUrl(controllerHost.getDetail("url")); + response.setName(controllerHost.getDetail("name")); + response.setUsername(controllerHost.getDetail("username")); + + return response; + } + +} diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/commands/AddHypervisorCommand.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/commands/AddHypervisorCommand.java new file mode 100644 index 00000000000..8094271a9ca --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/commands/AddHypervisorCommand.java @@ -0,0 +1,58 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.agent.commands; + +import com.cloud.agent.api.Command; + +public class AddHypervisorCommand extends Command { + private String hostId; + private String ipAddress; + + public AddHypervisorCommand() { + } + + public AddHypervisorCommand(String hostId, String ipAddress) { + this.hostId = hostId; + this.ipAddress = ipAddress; + } + + public String getHostId() { + return hostId; + } + + public void setHostId(String hostId) { + this.hostId = hostId; + } + + public String getIpAddress() { + return ipAddress; + } + + public void setIpAddress(String ipAddress) { + this.ipAddress = ipAddress; + } + + @Override + public boolean executeInSequence() { + // TODO Auto-generated method stub + return false; + } + +} diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/commands/ConfigureNetworkCommand.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/commands/ConfigureNetworkCommand.java new file mode 100644 index 00000000000..a5a2bf134d1 --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/commands/ConfigureNetworkCommand.java @@ -0,0 +1,54 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.agent.commands; + +import com.cloud.agent.api.Command; + +public class ConfigureNetworkCommand extends Command { + private String name; + private String tenantId; + + public ConfigureNetworkCommand(String name, String tenantId) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getTenantId() { + return tenantId; + } + + public void setTenantId(String tennantId) { + tenantId = tennantId; + } + + @Override + public boolean executeInSequence() { + // TODO Auto-generated method stub + return false; + } + +} diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/commands/ConfigurePortCommand.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/commands/ConfigurePortCommand.java new file mode 100644 index 00000000000..b36746893f4 --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/commands/ConfigurePortCommand.java @@ -0,0 +1,80 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.agent.commands; + +import java.util.UUID; + +import com.cloud.agent.api.Command; + +public class ConfigurePortCommand extends Command { + private UUID networkId; + private String tennantId; + private String macAddress; + private UUID portId; + + public ConfigurePortCommand() { + } + + public ConfigurePortCommand(UUID portId, UUID networkId, String tennantId, String macAddress) { + this.portId = portId; + this.networkId = networkId; + this.tennantId = tennantId; + this.macAddress = macAddress; + } + + public UUID getNetworkId() { + return networkId; + } + + public void setNetworkId(UUID networkId) { + this.networkId = networkId; + } + + public String getTennantId() { + return tennantId; + } + + public void setTennantId(String tennantId) { + this.tennantId = tennantId; + } + + public String getMacAddress() { + return macAddress; + } + + public void setMacAddress(String macAddress) { + this.macAddress = macAddress; + } + + public UUID getPortId() { + return portId; + } + + public void setPortId(UUID portId) { + this.portId = portId; + } + + @Override + public boolean executeInSequence() { + // TODO Auto-generated method stub + return false; + } + +} diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/commands/DestroyNetworkCommand.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/commands/DestroyNetworkCommand.java new file mode 100644 index 00000000000..971a882e98e --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/commands/DestroyNetworkCommand.java @@ -0,0 +1,45 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.agent.commands; + +import com.cloud.agent.api.Command; + +public class DestroyNetworkCommand extends Command { + private String networkUuid; + + public DestroyNetworkCommand(String networkUuid) { + this.networkUuid = networkUuid; + } + + public String getNetworkUuid() { + return networkUuid; + } + + public void setNetworkUuid(String networkUuid) { + this.networkUuid = networkUuid; + } + + @Override + public boolean executeInSequence() { + // TODO Auto-generated method stub + return false; + } + +} diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/commands/DestroyPortCommand.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/commands/DestroyPortCommand.java new file mode 100644 index 00000000000..9cd3dd72b8c --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/commands/DestroyPortCommand.java @@ -0,0 +1,50 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.agent.commands; + +import java.util.UUID; + +import com.cloud.agent.api.Command; + +public class DestroyPortCommand extends Command { + private UUID portId; + + public DestroyPortCommand() { + } + + public DestroyPortCommand(UUID portId) { + this.portId = portId; + } + + public UUID getPortId() { + return portId; + } + + public void setPortId(UUID portId) { + this.portId = portId; + } + + @Override + public boolean executeInSequence() { + // TODO Auto-generated method stub + return false; + } + +} diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/commands/StartupOpenDaylightControllerCommand.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/commands/StartupOpenDaylightControllerCommand.java new file mode 100644 index 00000000000..77206b1012a --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/commands/StartupOpenDaylightControllerCommand.java @@ -0,0 +1,29 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.agent.commands; + +import com.cloud.agent.api.StartupCommand; +import com.cloud.host.Host; + +public class StartupOpenDaylightControllerCommand extends StartupCommand { + public StartupOpenDaylightControllerCommand() { + super(Host.Type.L2Networking); + } +} diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/responses/AddHypervisorAnswer.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/responses/AddHypervisorAnswer.java new file mode 100644 index 00000000000..4dffaf2ee43 --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/responses/AddHypervisorAnswer.java @@ -0,0 +1,35 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.agent.responses; + +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.Command; + +public class AddHypervisorAnswer extends Answer { + + public AddHypervisorAnswer(Command command, boolean success, String details) { + super(command, success, details); + } + + public AddHypervisorAnswer(Command command, Exception e) { + super(command, e); + } + +} diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/responses/ConfigureNetworkAnswer.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/responses/ConfigureNetworkAnswer.java new file mode 100644 index 00000000000..7b5af5081e4 --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/responses/ConfigureNetworkAnswer.java @@ -0,0 +1,43 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.agent.responses; + +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.Command; + +public class ConfigureNetworkAnswer extends Answer { + private String networkUuid; + + public ConfigureNetworkAnswer(Command command, boolean success, String details, String networkUuid) { + this.networkUuid = networkUuid; + } + + public ConfigureNetworkAnswer(Command command, boolean success, String details) { + super(command, success, details); + } + + public ConfigureNetworkAnswer(Command command, Exception e) { + super(command, e); + } + + public String getNetworkUuid() { + return networkUuid; + } +} diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/responses/ConfigurePortAnswer.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/responses/ConfigurePortAnswer.java new file mode 100644 index 00000000000..178fdcdcc2a --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/responses/ConfigurePortAnswer.java @@ -0,0 +1,35 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.agent.responses; + +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.Command; + +public class ConfigurePortAnswer extends Answer { + + public ConfigurePortAnswer(Command command, boolean success, String details) { + super(command, success, details); + } + + public ConfigurePortAnswer(Command command, Exception e) { + super(command, e); + } + +} diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/responses/DestroyNetworkAnswer.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/responses/DestroyNetworkAnswer.java new file mode 100644 index 00000000000..16c3b7ca5e6 --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/responses/DestroyNetworkAnswer.java @@ -0,0 +1,35 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.agent.responses; + +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.Command; + +public class DestroyNetworkAnswer extends Answer { + + public DestroyNetworkAnswer(Command command, boolean success, String details) { + super(command, success, details); + } + + public DestroyNetworkAnswer(Command command, Exception e) { + super(command, e); + } + +} diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/responses/DestroyPortAnswer.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/responses/DestroyPortAnswer.java new file mode 100644 index 00000000000..ca239d6ebd4 --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/agent/responses/DestroyPortAnswer.java @@ -0,0 +1,35 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.agent.responses; + +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.Command; + +public class DestroyPortAnswer extends Answer { + + public DestroyPortAnswer(Command command, boolean success, String details) { + super(command, success, details); + } + + public DestroyPortAnswer(Command command, Exception e) { + super(command, e); + } + +} diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/NeutronInvalidCredentialsException.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/NeutronInvalidCredentialsException.java new file mode 100644 index 00000000000..6c1c00975c5 --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/NeutronInvalidCredentialsException.java @@ -0,0 +1,38 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.api; + +public class NeutronInvalidCredentialsException extends Exception { + + public NeutronInvalidCredentialsException() { + } + + public NeutronInvalidCredentialsException(final String message) { + super(message); + } + + public NeutronInvalidCredentialsException(final Throwable cause) { + super(cause); + } + + public NeutronInvalidCredentialsException(final String message, final Throwable cause) { + super(message, cause); + } +} \ No newline at end of file diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/NeutronRestApi.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/NeutronRestApi.java new file mode 100644 index 00000000000..8c67a98d08e --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/NeutronRestApi.java @@ -0,0 +1,217 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.api; + +import java.io.IOException; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.MalformedURLException; +import java.net.Socket; +import java.net.URL; +import java.net.UnknownHostException; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.X509Certificate; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +import org.apache.commons.httpclient.ConnectTimeoutException; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpException; +import org.apache.commons.httpclient.HttpMethodBase; +import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; +import org.apache.commons.httpclient.cookie.CookiePolicy; +import org.apache.commons.httpclient.params.HttpConnectionParams; +import org.apache.commons.httpclient.protocol.Protocol; +import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; +import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory; +import org.apache.log4j.Logger; + +public class NeutronRestApi { + + private static final Logger s_logger = Logger.getLogger(NeutronRestApi.class); + private static final MultiThreadedHttpConnectionManager s_httpClientManager = new MultiThreadedHttpConnectionManager(); + + private static final String PROTOCOL = "https"; + private static final int HTTPS_PORT = 443; + + private final HttpClient client; + + private Class httpClazz; + + protected NeutronRestApi(final Class httpClazz) { + this(httpClazz, PROTOCOL, HTTPS_PORT); + } + + protected NeutronRestApi(final Class httpClazz, final String protocol, final int port) { + client = createHttpClient(); + client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); + this.httpClazz = httpClazz; + + try { + // Cast to ProtocolSocketFactory to avoid the deprecated constructor + // with the SecureProtocolSocketFactory parameter + Protocol.registerProtocol(protocol, new Protocol(protocol, (ProtocolSocketFactory) new TrustingProtocolSocketFactory(), HTTPS_PORT)); + } catch (IOException e) { + s_logger.warn("Failed to register the TrustingProtocolSocketFactory, falling back to default SSLSocketFactory", e); + } + } + + public Class getHttpClazz() { + return httpClazz; + } + + public HttpMethodBase createMethod(final URL neutronUrl, final String uri) throws NeutronRestApiException { + String url; + try { + String formattedUrl = neutronUrl.toString() + uri; + url = new URL(formattedUrl).toString(); + + Constructor httpMethodConstructor = httpClazz.getConstructor(String.class); + HttpMethodBase httpMethod = httpMethodConstructor.newInstance(url); + + return httpMethod; + } catch (MalformedURLException e) { + String error = "Unable to build Neutron API URL"; + s_logger.error(error, e); + throw new NeutronRestApiException(error, e); + } catch (NoSuchMethodException e) { + String error = "Unable to build Neutron API URL due to reflection error"; + s_logger.error(error, e); + throw new NeutronRestApiException(error, e); + } catch (SecurityException e) { + String error = "Unable to build Neutron API URL due to security violation"; + s_logger.error(error, e); + throw new NeutronRestApiException(error, e); + } catch (InstantiationException e) { + String error = "Unable to build Neutron API due to instantiation error"; + s_logger.error(error, e); + throw new NeutronRestApiException(error, e); + } catch (IllegalAccessException e) { + String error = "Unable to build Neutron API URL due to absence of access modifier"; + s_logger.error(error, e); + throw new NeutronRestApiException(error, e); + } catch (IllegalArgumentException e) { + String error = "Unable to build Neutron API URL due to wrong argument in constructor"; + s_logger.error(error, e); + throw new NeutronRestApiException(error, e); + } catch (InvocationTargetException e) { + String error = "Unable to build Neutron API URL due to target error"; + s_logger.error(error, e); + throw new NeutronRestApiException(error, e); + } + } + + public void executeMethod(final HttpMethodBase method) throws NeutronRestApiException { + try { + client.executeMethod(method); + } catch (HttpException e) { + s_logger.error("HttpException caught while trying to connect to the Neutron Controller", e); + method.releaseConnection(); + throw new NeutronRestApiException("API call to Neutron Controller Failed", e); + } catch (IOException e) { + s_logger.error("IOException caught while trying to connect to the Neutron Controller", e); + method.releaseConnection(); + throw new NeutronRestApiException("API call to Neutron Controller Failed", e); + } + } + + /* + * This factory method is protected so we can extend this in the unit tests. + */ + protected HttpClient createHttpClient() { + return new HttpClient(s_httpClientManager); + } + + /* + * It uses a self-signed certificate. The TrustingProtocolSocketFactory will + * accept any provided certificate when making an SSL connection to the SDN + * Manager + */ + private class TrustingProtocolSocketFactory implements SecureProtocolSocketFactory { + + private SSLSocketFactory ssf; + + public TrustingProtocolSocketFactory() throws IOException { + // Create a trust manager that does not validate certificate chains + TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { + @Override + public X509Certificate[] getAcceptedIssuers() { + return null; + } + + @Override + public void checkClientTrusted(final X509Certificate[] certs, final String authType) { + // Trust always + } + + @Override + public void checkServerTrusted(final X509Certificate[] certs, final String authType) { + // Trust always + } + } }; + + try { + // Install the all-trusting trust manager + SSLContext sc = SSLContext.getInstance("SSL"); + sc.init(null, trustAllCerts, new java.security.SecureRandom()); + ssf = sc.getSocketFactory(); + } catch (KeyManagementException e) { + throw new IOException(e); + } catch (NoSuchAlgorithmException e) { + throw new IOException(e); + } + } + + @Override + public Socket createSocket(final String host, final int port) throws IOException { + return ssf.createSocket(host, port); + } + + @Override + public Socket createSocket(final String address, final int port, final InetAddress localAddress, final int localPort) throws IOException, UnknownHostException { + return ssf.createSocket(address, port, localAddress, localPort); + } + + @Override + public Socket createSocket(final Socket socket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException { + return ssf.createSocket(socket, host, port, autoClose); + } + + @Override + public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params) throws IOException, + UnknownHostException, ConnectTimeoutException { + int timeout = params.getConnectionTimeout(); + if (timeout == 0) { + return createSocket(host, port, localAddress, localPort); + } else { + Socket s = ssf.createSocket(); + s.bind(new InetSocketAddress(localAddress, localPort)); + s.connect(new InetSocketAddress(host, port), timeout); + return s; + } + } + } +} \ No newline at end of file diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/NeutronRestApiException.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/NeutronRestApiException.java new file mode 100644 index 00000000000..77efcee694e --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/NeutronRestApiException.java @@ -0,0 +1,38 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.api; + +public class NeutronRestApiException extends Exception { + + public NeutronRestApiException() { + } + + public NeutronRestApiException(final String message) { + super(message); + } + + public NeutronRestApiException(final Throwable cause) { + super(cause); + } + + public NeutronRestApiException(final String message, final Throwable cause) { + super(message, cause); + } +} \ No newline at end of file diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/NeutronRestFactory.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/NeutronRestFactory.java new file mode 100644 index 00000000000..d99677ee3a2 --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/NeutronRestFactory.java @@ -0,0 +1,55 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.api; + +import java.util.Hashtable; +import java.util.Map; + +import org.apache.commons.httpclient.HttpMethodBase; + +public class NeutronRestFactory { + + private Map flyweight = new Hashtable(); + + private static NeutronRestFactory instance; + + static { + instance = new NeutronRestFactory(); + } + + private NeutronRestFactory() { + } + + public static NeutronRestFactory getInstance() { + return instance; + } + + public NeutronRestApi getNeutronApi(final Class clazz) { + if (!flyweight.containsKey(clazz.getName())) { + NeutronRestApi api = new NeutronRestApi(clazz); + addNeutronApi(api); + } + return flyweight.get(clazz.getName()); + } + + public void addNeutronApi(final NeutronRestApi api) { + flyweight.put(api.getHttpClazz().getName(), api); + } +} \ No newline at end of file diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/commands/AddOpenDaylightControllerCmd.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/commands/AddOpenDaylightControllerCmd.java new file mode 100644 index 00000000000..80130c0e4b8 --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/commands/AddOpenDaylightControllerCmd.java @@ -0,0 +1,114 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.api.commands; + +import javax.inject.Inject; + +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.context.CallContext; +import org.apache.cloudstack.network.opendaylight.agent.OpenDaylightControllerResourceManager; +import org.apache.cloudstack.network.opendaylight.api.responses.OpenDaylightControllerResponse; + +import com.cloud.event.EventTypes; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.NetworkRuleConflictException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; + +@APICommand(name = "addOpenDaylightController", responseObject = OpenDaylightControllerResponse.class, description = "Adds an OpenDyalight controler") +public class AddOpenDaylightControllerCmd extends BaseAsyncCmd { + + @Inject + private OpenDaylightControllerResourceManager resourceManager; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.PHYSICAL_NETWORK_ID, type = CommandType.UUID, entityType = PhysicalNetworkResponse.class, required = true, + description = "the Physical Network ID") + private Long physicalNetworkId; + + @Parameter(name = ApiConstants.URL, type = CommandType.STRING, required = true, description = "Api URL of the OpenDaylight Controller.") + private String url; + + @Parameter(name = ApiConstants.USERNAME, type = CommandType.STRING, required = true, description = "Username to access the OpenDaylight API") + private String username; + + @Parameter(name = ApiConstants.PASSWORD, type = CommandType.STRING, required = true, description = "Credential to access the OpenDaylight API") + private String password; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return "addOpenDaylightController"; + } + + @Override + public long getEntityOwnerId() { + return CallContext.current().getCallingAccount().getId(); + } + + @Override + public String getEventType() { + return EventTypes.EVENT_EXTERNAL_OPENDAYLIGHT_ADD_CONTROLLER; + } + + @Override + public String getEventDescription() { + return "Adding OpenDaylight controller"; + } + + public Long getPhysicalNetworkId() { + return physicalNetworkId; + } + + public String getUrl() { + return url; + } + + public String getUsername() { + return username; + } + + public String getPassword() { + return password; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, + NetworkRuleConflictException { + resourceManager.addController(this); + } + +} diff --git a/api/src/org/apache/cloudstack/api/command/admin/storage/PrepareSecondaryStorageForMigrationCmd.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/commands/DeleteOpenDaylightControllerCmd.java similarity index 55% rename from api/src/org/apache/cloudstack/api/command/admin/storage/PrepareSecondaryStorageForMigrationCmd.java rename to plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/commands/DeleteOpenDaylightControllerCmd.java index a57f2dfeffc..b5565041444 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/storage/PrepareSecondaryStorageForMigrationCmd.java +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/commands/DeleteOpenDaylightControllerCmd.java @@ -1,3 +1,4 @@ +// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information @@ -14,38 +15,41 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package org.apache.cloudstack.api.command.admin.storage; +// -import org.apache.log4j.Logger; +package org.apache.cloudstack.network.opendaylight.api.commands; + +import javax.inject.Inject; import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiCommandJobType; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.ImageStoreResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import org.apache.cloudstack.context.CallContext; +import org.apache.cloudstack.network.opendaylight.agent.OpenDaylightControllerResourceManager; +import org.apache.cloudstack.network.opendaylight.api.responses.OpenDaylightControllerResponse; import com.cloud.event.EventTypes; +import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.exception.NetworkRuleConflictException; +import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; -import com.cloud.storage.ImageStore; -import com.cloud.user.Account; -@APICommand(name = "prepareSecondaryStorageForMigration", - description = "Prepare a NFS secondary storage to migrate to use object store like S3", - responseObject = ImageStoreResponse.class) -public class PrepareSecondaryStorageForMigrationCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(PrepareSecondaryStorageForMigrationCmd.class.getName()); - private static final String s_name = "preparesecondarystorageformigrationresponse"; +@APICommand(name = "deleteOpenDaylightController", responseObject = OpenDaylightControllerResponse.class, description = "Removes an OpenDyalight controler") +public class DeleteOpenDaylightControllerCmd extends BaseAsyncCmd { + @Inject + private OpenDaylightControllerResourceManager resourceManager; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = ImageStoreResponse.class, required = true, description = "Secondary image store ID") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = OpenDaylightControllerResponse.class, required = true, description = "OpenDaylight Controller ID") private Long id; ///////////////////////////////////////////////////// @@ -56,55 +60,40 @@ public class PrepareSecondaryStorageForMigrationCmd extends BaseAsyncCmd { return id; } - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public String getCommandName() { - return s_name; - } - - @Override - public ApiCommandJobType getInstanceType() { - return ApiCommandJobType.ImageStore; - } - - @Override - public Long getInstanceId() { - return getId(); - } - - @Override - public long getEntityOwnerId() { - Account account = CallContext.current().getCallingAccount(); - if (account != null) { - return account.getId(); - } - - return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked - } - @Override public String getEventType() { - return EventTypes.EVENT_MIGRATE_PREPARE_SECONDARY_STORAGE; + return EventTypes.EVENT_EXTERNAL_OPENDAYLIGHT_DELETE_CONTROLLER; } @Override public String getEventDescription() { - return "preparing secondary storage: " + getId() + " for object store migration"; + return "Deleted OpenDaylight Controller"; } @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException { - ImageStore result = _storageService.prepareSecondaryStorageForObjectStoreMigration(getId()); - if (result != null) { - ImageStoreResponse response = _responseGenerator.createImageStoreResponse(result); + public String getCommandName() { + return "deleteOpenDaylightController"; + } + + @Override + public long getEntityOwnerId() { + return CallContext.current().getCallingAccount().getId(); + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, + NetworkRuleConflictException { + try { + resourceManager.deleteController(this); + SuccessResponse response = new SuccessResponse(getCommandName()); response.setResponseName(getCommandName()); - response.setResponseName("secondarystorage"); - setResponseObject(response); - } else { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to prepare secondary storage for object store migration"); + setResponseObject(response); //FIXME + } catch (InvalidParameterValueException e) { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete OpenDaylight controller."); } } + } diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/commands/ListOpenDaylightControllersCmd.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/commands/ListOpenDaylightControllersCmd.java new file mode 100644 index 00000000000..f3e2e39f4cc --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/commands/ListOpenDaylightControllersCmd.java @@ -0,0 +1,104 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.api.commands; + +import java.util.ArrayList; +import java.util.List; + +import javax.inject.Inject; + +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.context.CallContext; +import org.apache.cloudstack.network.opendaylight.agent.OpenDaylightControllerResourceManager; +import org.apache.cloudstack.network.opendaylight.api.responses.OpenDaylightControllerResponse; +import org.apache.cloudstack.network.opendaylight.dao.OpenDaylightControllerVO; + +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.NetworkRuleConflictException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; + +@APICommand(name = "listOpenDaylightControllers", responseObject = OpenDaylightControllerResponse.class, description = "Lists OpenDyalight controllers") +public class ListOpenDaylightControllersCmd extends BaseCmd { + @Inject + private OpenDaylightControllerResourceManager resourceManager; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.PHYSICAL_NETWORK_ID, type = CommandType.UUID, entityType = PhysicalNetworkResponse.class, required = false, + description = "the Physical Network ID") + private Long physicalNetworkId; + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = OpenDaylightControllerResponse.class, required = false, + description = "the ID of a OpenDaylight Controller") + private Long Id; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return "listOpenDaylightControllers"; + } + + @Override + public long getEntityOwnerId() { + return CallContext.current().getCallingAccount().getId(); + } + + public Long getPhysicalNetworkId() { + return physicalNetworkId; + } + + public Long getId() { + return Id; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, + NetworkRuleConflictException { + List controllers = resourceManager.listControllers(this); + + List controllerList = new ArrayList(); + for (OpenDaylightControllerVO controller: controllers) { + OpenDaylightControllerResponse responseObject = resourceManager.createResponseFromVO(controller); + controllerList.add(responseObject); + } + ListResponse responseList = new ListResponse(); + responseList.setResponseName(getCommandName()); + responseList.setResponses(controllerList); + setResponseObject(responseList); + } + +} diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/enums/NeutronNorthboundEnum.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/enums/NeutronNorthboundEnum.java new file mode 100644 index 00000000000..3ee5d19d5fe --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/enums/NeutronNorthboundEnum.java @@ -0,0 +1,44 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.api.enums; + +public enum NeutronNorthboundEnum { + + NETWORKS_URI("/controller/nb/v2/neutron/networks"), + NETWORK_PARAM_URI("/controller/nb/v2/neutron/networks/{0}"), + + PORTS_URI("/controller/nb/v2/neutron/ports"), + PORTS_PARAM_URI("/controller/nb/v2/neutron/ports/{0}"), + + NODES_URI("/controller/nb/v2/connectionmanager/nodes"), + NODE_PARAM_URI("/controller/nb/v2/connectionmanager/node/{0}/{1}"), + NODE_PORT_PER_NODE_URI("/controller/nb/v2/connectionmanager/node/{0}/address/{1}/port/{2}"), + NODE_PORT_PER_TYPE_URI("/controller/nb/v2/connectionmanager/node/{0}/{1}/address/{2}/port/{3}"); + + private String uri; + + private NeutronNorthboundEnum(String uri) { + this.uri = uri; + } + + public String getUri() { + return uri; + } +} \ No newline at end of file diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/model/NeutronNetwork.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/model/NeutronNetwork.java new file mode 100644 index 00000000000..b61025f7f44 --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/model/NeutronNetwork.java @@ -0,0 +1,213 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.api.model; + +import java.util.UUID; + +import com.google.gson.annotations.SerializedName; + +public class NeutronNetwork { + + private UUID id; + private String name; + private boolean shared; + private String tenantId; + @SerializedName("provider:network_type") + private String networkType; + @SerializedName("provider:segmentation_id") + private Integer segmentationId; + + public NeutronNetwork() { + } + + public NeutronNetwork(final UUID id, final String name, final boolean shared, final String tenantId, final String networkType, final Integer segmentationId) { + this.id = id; + this.name = name; + this.shared = shared; + this.tenantId = tenantId; + this.networkType = networkType; + this.segmentationId = segmentationId; + } + + public UUID getId() { + return id; + } + + public void setId(final UUID uuid) { + id = uuid; + } + + public String getNetworkType() { + return networkType; + } + + public void setNetworkType(final String networkType) { + this.networkType = networkType; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public boolean isShared() { + return shared; + } + + public void setShared(final boolean shared) { + this.shared = shared; + } + + public Integer getSegmentationId() { + return segmentationId; + } + + public void setSegmentationId(final Integer segmentationId) { + this.segmentationId = segmentationId; + } + + public String getTenantId() { + return tenantId; + } + + public void setTenantId(final String tenantId) { + this.tenantId = tenantId; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (name == null ? 0 : name.hashCode()); + result = prime * result + (networkType == null ? 0 : networkType.hashCode()); + result = prime * result + (segmentationId == null ? 0 : segmentationId.hashCode()); + result = prime * result + (shared ? 1231 : 1237); + result = prime * result + (tenantId == null ? 0 : tenantId.hashCode()); + result = prime * result + (id == null ? 0 : id.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + NeutronNetwork other = (NeutronNetwork) obj; + if (name == null) { + if (other.name != null) { + return false; + } + } else if (!name.equals(other.name)) { + return false; + } + if (networkType == null) { + if (other.networkType != null) { + return false; + } + } else if (!networkType.equals(other.networkType)) { + return false; + } + if (segmentationId == null) { + if (other.segmentationId != null) { + return false; + } + } else if (!segmentationId.equals(other.segmentationId)) { + return false; + } + if (shared != other.shared) { + return false; + } + if (tenantId == null) { + if (other.tenantId != null) { + return false; + } + } else if (!tenantId.equals(other.tenantId)) { + return false; + } + if (id == null) { + if (other.id != null) { + return false; + } + } else if (!id.equals(other.id)) { + return false; + } + return true; + } + + public boolean equalsIgnoreUuid(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + NeutronNetwork other = (NeutronNetwork) obj; + if (name == null) { + if (other.name != null) { + return false; + } + } else if (!name.equals(other.name)) { + return false; + } + if (networkType == null) { + if (other.networkType != null) { + return false; + } + } else if (!networkType.equals(other.networkType)) { + return false; + } + if (segmentationId == null) { + if (other.segmentationId != null) { + return false; + } + } else if (!segmentationId.equals(other.segmentationId)) { + return false; + } + if (shared != other.shared) { + return false; + } + if (tenantId == null) { + if (other.tenantId != null) { + return false; + } + } else if (!tenantId.equals(other.tenantId)) { + return false; + } + return true; + } + + @Override + public String toString() { + return "NeutronNetwork [uuid=" + id + ", networkType=" + networkType + ", name=" + name + ", shared=" + shared + ", segmentationId=" + segmentationId + ", tenantId=" + + tenantId + "]"; + } +} \ No newline at end of file diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/model/NeutronNetworkWrapper.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/model/NeutronNetworkWrapper.java new file mode 100644 index 00000000000..37087f6a5ce --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/model/NeutronNetworkWrapper.java @@ -0,0 +1,70 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.api.model; + +public class NeutronNetworkWrapper { + + private NeutronNetwork network; + + public NeutronNetworkWrapper() { + } + + public NeutronNetworkWrapper(final NeutronNetwork network) { + this.network = network; + } + + public NeutronNetwork getNetwork() { + return network; + } + + public void setNetwork(final NeutronNetwork network) { + this.network = network; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (network == null ? 0 : network.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + NeutronNetworkWrapper other = (NeutronNetworkWrapper) obj; + if (network == null) { + if (other.network != null) { + return false; + } + } else if (!network.equals(other.network)) { + return false; + } + return true; + } +} \ No newline at end of file diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/model/NeutronNetworksList.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/model/NeutronNetworksList.java new file mode 100644 index 00000000000..22d6d4e4d84 --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/model/NeutronNetworksList.java @@ -0,0 +1,42 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.api.model; + +import java.util.List; + +public class NeutronNetworksList { + + private List networks; + + public NeutronNetworksList() { + } + + public NeutronNetworksList(final List networks) { + this.networks = networks; + } + + public List getNetworks() { + return networks; + } + + public void setNetworks(final List networks) { + this.networks = networks; + } +} \ No newline at end of file diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/model/NeutronNode.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/model/NeutronNode.java new file mode 100644 index 00000000000..1672cfefc81 --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/model/NeutronNode.java @@ -0,0 +1,98 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.api.model; + + +public class NeutronNode { + + private String id; + private String type; + + public NeutronNode() { + } + + public NeutronNode(final String id, final String type) { + this.id = id; + this.type = type; + } + + public String getId() { + return id; + } + + public void setId(final String id) { + this.id = id; + } + + public String getType() { + return type; + } + + public void setType(final String type) { + this.type = type; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (id == null ? 0 : id.hashCode()); + result = prime * result + (type == null ? 0 : type.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + NeutronNode other = (NeutronNode) obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (type == null) { + if (other.type != null) + return false; + } else if (!type.equals(other.type)) + return false; + return true; + } + + public boolean equalsIgnoreUuid(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + NeutronNode other = (NeutronNode) obj; + if (type == null) { + if (other.type != null) + return false; + } else if (!type.equals(other.type)) + return false; + return true; + } +} \ No newline at end of file diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/model/NeutronNodeWrapper.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/model/NeutronNodeWrapper.java new file mode 100644 index 00000000000..6065d912a49 --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/model/NeutronNodeWrapper.java @@ -0,0 +1,65 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.api.model; + +public class NeutronNodeWrapper { + + private NeutronNode node; + + public NeutronNodeWrapper() { + } + + public NeutronNodeWrapper(final NeutronNode node) { + this.node = node; + } + + public NeutronNode getNode() { + return node; + } + + public void setNode(final NeutronNode node) { + this.node = node; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (node == null ? 0 : node.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + NeutronNodeWrapper other = (NeutronNodeWrapper) obj; + if (node == null) { + if (other.node != null) + return false; + } else if (!node.equals(other.node)) + return false; + return true; + } +} \ No newline at end of file diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/model/NeutronNodesList.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/model/NeutronNodesList.java new file mode 100644 index 00000000000..a419b66ea59 --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/model/NeutronNodesList.java @@ -0,0 +1,42 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.api.model; + +import java.util.List; + +public class NeutronNodesList { + + private List nodes; + + public NeutronNodesList() { + } + + public NeutronNodesList(final List nodes) { + this.nodes = nodes; + } + + public List getNodes() { + return nodes; + } + + public void setNodes(final List nodes) { + this.nodes = nodes; + } +} \ No newline at end of file diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/model/NeutronPort.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/model/NeutronPort.java new file mode 100644 index 00000000000..764dcd1e507 --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/model/NeutronPort.java @@ -0,0 +1,265 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.api.model; + +import java.util.List; +import java.util.UUID; + +public class NeutronPort { + + private UUID id; + private String name; + private String tenantId; + private UUID networkId; + private String macAddress; + private UUID deviceId; + private boolean adminStateUp; + private String status; + private List fixedIps; + + public NeutronPort() { + } + + public NeutronPort(final UUID id, final String name, final String tenantId, final UUID networkId, final String macAddress, final UUID deviceId, final boolean adminStateUp, + final String status, final List fixedIps) { + this.id = id; + this.name = name; + this.tenantId = tenantId; + this.networkId = networkId; + this.macAddress = macAddress; + this.deviceId = deviceId; + this.adminStateUp = adminStateUp; + this.status = status; + this.fixedIps = fixedIps; + } + + public UUID getId() { + return id; + } + + public void setId(final UUID uuid) { + id = uuid; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public String getTenantId() { + return tenantId; + } + + public void setTenantId(final String tenantId) { + this.tenantId = tenantId; + } + + public UUID getNetworkId() { + return networkId; + } + + public void setNetworkId(final UUID networkId) { + this.networkId = networkId; + } + + public String getMacAddress() { + return macAddress; + } + + public void setMacAddress(final String macAddress) { + this.macAddress = macAddress; + } + + public UUID getDeviceId() { + return deviceId; + } + + public void setDeviceId(final UUID deviceId) { + this.deviceId = deviceId; + } + + public boolean isAdminStateUp() { + return adminStateUp; + } + + public void setAdminStateUp(final boolean adminStateUp) { + this.adminStateUp = adminStateUp; + } + + public String getStatus() { + return status; + } + + public void setStatus(final String status) { + this.status = status; + } + + public List getFixedIps() { + return fixedIps; + } + + public void setFixedIps(final List fixedIps) { + this.fixedIps = fixedIps; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (adminStateUp ? 1231 : 1237); + result = prime * result + (deviceId == null ? 0 : deviceId.hashCode()); + result = prime * result + (macAddress == null ? 0 : macAddress.hashCode()); + result = prime * result + (name == null ? 0 : name.hashCode()); + result = prime * result + (networkId == null ? 0 : networkId.hashCode()); + result = prime * result + (status == null ? 0 : status.hashCode()); + result = prime * result + (tenantId == null ? 0 : tenantId.hashCode()); + result = prime * result + (id == null ? 0 : id.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + NeutronPort other = (NeutronPort) obj; + if (adminStateUp != other.adminStateUp) { + return false; + } + if (deviceId == null) { + if (other.deviceId != null) { + return false; + } + } else if (!deviceId.equals(other.deviceId)) { + return false; + } + if (macAddress == null) { + if (other.macAddress != null) { + return false; + } + } else if (!macAddress.equals(other.macAddress)) { + return false; + } + if (name == null) { + if (other.name != null) { + return false; + } + } else if (!name.equals(other.name)) { + return false; + } + if (networkId == null) { + if (other.networkId != null) { + return false; + } + } else if (!networkId.equals(other.networkId)) { + return false; + } + if (status == null) { + if (other.status != null) { + return false; + } + } else if (!status.equals(other.status)) { + return false; + } + if (tenantId == null) { + if (other.tenantId != null) { + return false; + } + } else if (!tenantId.equals(other.tenantId)) { + return false; + } + if (id == null) { + if (other.id != null) { + return false; + } + } else if (!id.equals(other.id)) { + return false; + } + return true; + } + + public boolean equalsIgnoreUuid(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + NeutronPort other = (NeutronPort) obj; + if (adminStateUp != other.adminStateUp) { + return false; + } + if (deviceId == null) { + if (other.deviceId != null) { + return false; + } + } else if (!deviceId.equals(other.deviceId)) { + return false; + } + if (macAddress == null) { + if (other.macAddress != null) { + return false; + } + } else if (!macAddress.equals(other.macAddress)) { + return false; + } + if (name == null) { + if (other.name != null) { + return false; + } + } else if (!name.equals(other.name)) { + return false; + } + if (networkId == null) { + if (other.networkId != null) { + return false; + } + } else if (!networkId.equals(other.networkId)) { + return false; + } + if (status == null) { + if (other.status != null) { + return false; + } + } else if (!status.equals(other.status)) { + return false; + } + if (tenantId == null) { + if (other.tenantId != null) { + return false; + } + } else if (!tenantId.equals(other.tenantId)) { + return false; + } + return true; + } +} \ No newline at end of file diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/model/NeutronPortWrapper.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/model/NeutronPortWrapper.java new file mode 100644 index 00000000000..0fe00d598a9 --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/model/NeutronPortWrapper.java @@ -0,0 +1,70 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.api.model; + +public class NeutronPortWrapper { + + private NeutronPort port; + + public NeutronPortWrapper() { + } + + public NeutronPortWrapper(final NeutronPort port) { + this.port = port; + } + + public NeutronPort getPort() { + return port; + } + + public void setPort(final NeutronPort port) { + this.port = port; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (port == null ? 0 : port.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + NeutronPortWrapper other = (NeutronPortWrapper) obj; + if (port == null) { + if (other.port != null) { + return false; + } + } else if (!port.equals(other.port)) { + return false; + } + return true; + } +} \ No newline at end of file diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/model/NeutronPortsList.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/model/NeutronPortsList.java new file mode 100644 index 00000000000..680e9a05f6a --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/model/NeutronPortsList.java @@ -0,0 +1,42 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.api.model; + +import java.util.List; + +public class NeutronPortsList { + + private List ports; + + public NeutronPortsList() { + } + + public NeutronPortsList(final List ports) { + this.ports = ports; + } + + public List getPorts() { + return ports; + } + + public void setPorts(final List ports) { + this.ports = ports; + } +} \ No newline at end of file diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/resources/Action.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/resources/Action.java new file mode 100644 index 00000000000..2711fef7449 --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/resources/Action.java @@ -0,0 +1,289 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.api.resources; + +import java.io.IOException; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.cloudstack.network.opendaylight.api.NeutronInvalidCredentialsException; +import org.apache.cloudstack.network.opendaylight.api.NeutronRestApi; +import org.apache.cloudstack.network.opendaylight.api.NeutronRestApiException; +import org.apache.cloudstack.network.opendaylight.api.NeutronRestFactory; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.httpclient.Header; +import org.apache.commons.httpclient.HttpMethodBase; +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.httpclient.NameValuePair; +import org.apache.commons.httpclient.methods.DeleteMethod; +import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.commons.httpclient.methods.PostMethod; +import org.apache.commons.httpclient.methods.PutMethod; +import org.apache.commons.httpclient.methods.StringRequestEntity; +import org.apache.log4j.Logger; + +public abstract class Action { + + private static final Logger s_logger = Logger.getLogger(Action.class); + private static final int BODY_RESP_MAX_LEN = 1024; + + // private static final String DEFAULT + + protected static final String TEXT_HTML_CONTENT_TYPE = "text/html"; + protected static final String JSON_CONTENT_TYPE = "application/json"; + protected static final String CONTENT_TYPE = "Content-Type"; + + private final URL url; + private final String username; + private final String password; + + public Action(final URL url, final String username, final String password) { + + this.url = url; + this.username = username; + this.password = password; + } + + public String executeGet(final String uri, final Map parameters) throws NeutronRestApiException { + try { + validateCredentials(); + } catch (NeutronInvalidCredentialsException e) { + throw new NeutronRestApiException("Invalid credentials!", e); + } + + NeutronRestFactory factory = NeutronRestFactory.getInstance(); + + NeutronRestApi neutronRestApi = factory.getNeutronApi(GetMethod.class); + GetMethod getMethod = (GetMethod) neutronRestApi.createMethod(url, uri); + + try { + getMethod.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE); + + String encodedCredentials = encodeCredentials(); + getMethod.setRequestHeader("Authorization", "Basic " + encodedCredentials); + + if (parameters != null && !parameters.isEmpty()) { + List nameValuePairs = new ArrayList(parameters.size()); + for (Entry e : parameters.entrySet()) { + nameValuePairs.add(new NameValuePair(e.getKey(), e.getValue())); + } + getMethod.setQueryString(nameValuePairs.toArray(new NameValuePair[0])); + } + + neutronRestApi.executeMethod(getMethod); + + if (getMethod.getStatusCode() != HttpStatus.SC_OK) { + String errorMessage = responseToErrorMessage(getMethod); + getMethod.releaseConnection(); + s_logger.error("Failed to retrieve object : " + errorMessage); + throw new NeutronRestApiException("Failed to retrieve object : " + errorMessage); + } + + return getMethod.getResponseBodyAsString(); + + } catch (NeutronRestApiException e) { + s_logger.error("NeutronRestApiException caught while trying to execute HTTP Method on the Neutron Controller", e); + throw new NeutronRestApiException("API call to Neutron Controller Failed", e); + } catch (IOException e) { + throw new NeutronRestApiException(e); + } finally { + getMethod.releaseConnection(); + } + } + + protected String executePost(final String uri, final StringRequestEntity entity) throws NeutronRestApiException { + try { + validateCredentials(); + } catch (NeutronInvalidCredentialsException e) { + throw new NeutronRestApiException("Invalid credentials!", e); + } + + NeutronRestFactory factory = NeutronRestFactory.getInstance(); + + NeutronRestApi neutronRestApi = factory.getNeutronApi(PostMethod.class); + PostMethod postMethod = (PostMethod) neutronRestApi.createMethod(url, uri); + + try { + postMethod.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE); + postMethod.setRequestEntity(entity); + + String encodedCredentials = encodeCredentials(); + postMethod.setRequestHeader("Authorization", "Basic " + encodedCredentials); + + neutronRestApi.executeMethod(postMethod); + + if (postMethod.getStatusCode() != HttpStatus.SC_CREATED) { + String errorMessage = responseToErrorMessage(postMethod); + postMethod.releaseConnection(); + s_logger.error("Failed to create object : " + errorMessage); + throw new NeutronRestApiException("Failed to create object : " + errorMessage); + } + + return postMethod.getResponseBodyAsString(); + } catch (NeutronRestApiException e) { + s_logger.error("NeutronRestApiException caught while trying to execute HTTP Method on the Neutron Controller", e); + throw new NeutronRestApiException("API call to Neutron Controller Failed", e); + } catch (IOException e) { + throw new NeutronRestApiException("Failed to load json response body", e); + } finally { + postMethod.releaseConnection(); + } + } + + protected void executePut(final String uri, final StringRequestEntity entity) throws NeutronRestApiException { + try { + validateCredentials(); + } catch (NeutronInvalidCredentialsException e) { + throw new NeutronRestApiException("Invalid credentials!", e); + } + + NeutronRestFactory factory = NeutronRestFactory.getInstance(); + + NeutronRestApi neutronRestApi = factory.getNeutronApi(PutMethod.class); + PutMethod putMethod = (PutMethod) neutronRestApi.createMethod(url, uri); + + try { + putMethod.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE); + putMethod.setRequestEntity(entity); + + String encodedCredentials = encodeCredentials(); + putMethod.setRequestHeader("Authorization", "Basic " + encodedCredentials); + + neutronRestApi.executeMethod(putMethod); + + if (putMethod.getStatusCode() != HttpStatus.SC_OK) { + String errorMessage = responseToErrorMessage(putMethod); + putMethod.releaseConnection(); + s_logger.error("Failed to update object : " + errorMessage); + throw new NeutronRestApiException("Failed to create object : " + errorMessage); + } + } catch (NeutronRestApiException e) { + s_logger.error("NeutronRestApiException caught while trying to execute HTTP Method on the Neutron Controller", e); + throw new NeutronRestApiException("API call to Neutron Controller Failed", e); + } finally { + putMethod.releaseConnection(); + } + } + + protected String executePut(final String uri) throws NeutronRestApiException { + try { + validateCredentials(); + } catch (NeutronInvalidCredentialsException e) { + throw new NeutronRestApiException("Invalid credentials!", e); + } + + NeutronRestFactory factory = NeutronRestFactory.getInstance(); + + NeutronRestApi neutronRestApi = factory.getNeutronApi(PutMethod.class); + PutMethod putMethod = (PutMethod) neutronRestApi.createMethod(url, uri); + + try { + String encodedCredentials = encodeCredentials(); + putMethod.setRequestHeader("Authorization", "Basic " + encodedCredentials); + + neutronRestApi.executeMethod(putMethod); + + if (putMethod.getStatusCode() != HttpStatus.SC_OK) { + String errorMessage = responseToErrorMessage(putMethod); + putMethod.releaseConnection(); + s_logger.error("Failed to update object : " + errorMessage); + throw new NeutronRestApiException("Failed to create object : " + errorMessage); + } + + return putMethod.getResponseBodyAsString(); + } catch (NeutronRestApiException e) { + s_logger.error("NeutronRestApiException caught while trying to execute HTTP Method on the Neutron Controller", e); + throw new NeutronRestApiException("API call to Neutron Controller Failed", e); + } catch (IOException e) { + throw new NeutronRestApiException("Failed to load json response body", e); + } finally { + putMethod.releaseConnection(); + } + } + + protected void executeDelete(final String uri) throws NeutronRestApiException { + try { + validateCredentials(); + } catch (NeutronInvalidCredentialsException e) { + throw new NeutronRestApiException("Invalid credentials!", e); + } + + NeutronRestFactory factory = NeutronRestFactory.getInstance(); + + NeutronRestApi neutronRestApi = factory.getNeutronApi(DeleteMethod.class); + DeleteMethod deleteMethod = (DeleteMethod) neutronRestApi.createMethod(url, uri); + + try { + deleteMethod.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE); + + String encodedCredentials = encodeCredentials(); + deleteMethod.setRequestHeader("Authorization", "Basic " + encodedCredentials); + + neutronRestApi.executeMethod(deleteMethod); + + if (deleteMethod.getStatusCode() != HttpStatus.SC_NO_CONTENT) { + String errorMessage = responseToErrorMessage(deleteMethod); + deleteMethod.releaseConnection(); + s_logger.error("Failed to update object : " + errorMessage); + throw new NeutronRestApiException("Failed to create object : " + errorMessage); + } + } catch (NeutronRestApiException e) { + s_logger.error("NeutronRestApiException caught while trying to execute HTTP Method on the Neutron Controller", e); + throw new NeutronRestApiException("API call to Neutron Controller Failed", e); + } finally { + deleteMethod.releaseConnection(); + } + } + + private void validateCredentials() throws NeutronInvalidCredentialsException { + if (username == null || username.isEmpty() || password == null || password.isEmpty()) { + throw new NeutronInvalidCredentialsException("Credentials are null or empty"); + } + } + + private String encodeCredentials() { + String authString = username + ":" + password; + byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); + String authStringEnc = new String(authEncBytes); + return authStringEnc; + } + + private String responseToErrorMessage(final HttpMethodBase method) { + assert method.isRequestSent() : "no use getting an error message unless the request is sent"; + + final Header contentTypeHeader = method.getResponseHeader(CONTENT_TYPE); + if (contentTypeHeader != null && TEXT_HTML_CONTENT_TYPE.equals(contentTypeHeader.getValue())) { + // The error message is the response content + // Safety margin of 1024 characters, anything longer is probably + // useless and will clutter the logs + try { + return method.getResponseBodyAsString(BODY_RESP_MAX_LEN); + } catch (IOException e) { + s_logger.debug("Error while loading response body", e); + } + } + + // The default + return method.getStatusText(); + } +} \ No newline at end of file diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/resources/NeutronNetworksNorthboundAction.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/resources/NeutronNetworksNorthboundAction.java new file mode 100644 index 00000000000..ce33da0e9a4 --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/resources/NeutronNetworksNorthboundAction.java @@ -0,0 +1,113 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.api.resources; + +import java.io.UnsupportedEncodingException; +import java.lang.reflect.Type; +import java.net.URL; +import java.text.MessageFormat; +import java.util.Collections; + +import org.apache.commons.httpclient.methods.StringRequestEntity; + +import com.google.gson.FieldNamingPolicy; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; + +import org.apache.cloudstack.network.opendaylight.api.NeutronRestApiException; +import org.apache.cloudstack.network.opendaylight.api.enums.NeutronNorthboundEnum; +import org.apache.cloudstack.network.opendaylight.api.model.NeutronNetwork; +import org.apache.cloudstack.network.opendaylight.api.model.NeutronNetworkWrapper; +import org.apache.cloudstack.network.opendaylight.api.model.NeutronNetworksList; + +public class NeutronNetworksNorthboundAction extends Action { + + private final Gson gsonNeutronNetwork; + + public NeutronNetworksNorthboundAction(final URL url, final String username, final String password) { + super(url, username, password); + gsonNeutronNetwork = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); + } + + @SuppressWarnings("unchecked") + public T listAllNetworks() throws NeutronRestApiException { + String uri = NeutronNorthboundEnum.NETWORKS_URI.getUri(); + String bodystring = executeGet(uri, Collections. emptyMap()); + + Type returnType = new TypeToken>() { + }.getType(); + + T returnValue = (T) gsonNeutronNetwork.fromJson(bodystring, returnType); + + return returnValue; + } + + @SuppressWarnings("unchecked") + public T findNetworkById(final String networkId) throws NeutronRestApiException { + String uri = NeutronNorthboundEnum.NETWORK_PARAM_URI.getUri(); + uri = MessageFormat.format(uri, networkId); + + String bodystring = executeGet(uri, Collections. emptyMap()); + + Type returnType = new TypeToken() { + }.getType(); + + T returnValue = (T) gsonNeutronNetwork.fromJson(bodystring, returnType); + + return returnValue; + } + + @SuppressWarnings("unchecked") + public T createNeutronNetwork(final NeutronNetworkWrapper newNetworkWrapper) throws NeutronRestApiException { + try { + String uri = NeutronNorthboundEnum.NETWORKS_URI.getUri(); + StringRequestEntity entity = new StringRequestEntity(gsonNeutronNetwork.toJson(newNetworkWrapper), JSON_CONTENT_TYPE, null); + + String bodystring = executePost(uri, entity); + + T result = (T) gsonNeutronNetwork.fromJson(bodystring, TypeToken.get(NeutronNetworkWrapper.class).getType()); + + return result; + } catch (UnsupportedEncodingException e) { + throw new NeutronRestApiException("Failed to encode json request body", e); + } + } + + public void updateNeutronNetwork(final String networkId, final NeutronNetworkWrapper newNetworkWrapper) throws NeutronRestApiException { + try { + String uri = NeutronNorthboundEnum.NETWORK_PARAM_URI.getUri(); + uri = MessageFormat.format(uri, networkId); + + StringRequestEntity entity = new StringRequestEntity(gsonNeutronNetwork.toJson(newNetworkWrapper), JSON_CONTENT_TYPE, null); + + executePut(uri, entity); + } catch (UnsupportedEncodingException e) { + throw new NeutronRestApiException("Failed to encode json request body", e); + } + } + + public void deleteNeutronNetwork(final String networkId) throws NeutronRestApiException { + String uri = NeutronNorthboundEnum.NETWORK_PARAM_URI.getUri(); + uri = MessageFormat.format(uri, networkId); + + executeDelete(uri); + } +} \ No newline at end of file diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/resources/NeutronNodesNorthboundAction.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/resources/NeutronNodesNorthboundAction.java new file mode 100644 index 00000000000..03bf02ea4ed --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/resources/NeutronNodesNorthboundAction.java @@ -0,0 +1,89 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.api.resources; + +import java.lang.reflect.Type; +import java.net.URL; +import java.text.MessageFormat; +import java.util.Collections; + +import org.apache.cloudstack.network.opendaylight.api.NeutronRestApiException; +import org.apache.cloudstack.network.opendaylight.api.enums.NeutronNorthboundEnum; +import org.apache.cloudstack.network.opendaylight.api.model.NeutronNodeWrapper; +import org.apache.cloudstack.network.opendaylight.api.model.NeutronNodesList; + +import com.google.gson.FieldNamingPolicy; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; + +public class NeutronNodesNorthboundAction extends Action { + + private final Gson gsonNeutronNode; + + public NeutronNodesNorthboundAction(final URL url, final String username, final String password) { + super(url, username, password); + gsonNeutronNode = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); + } + + @SuppressWarnings("unchecked") + public T listAllNodes() throws NeutronRestApiException { + String uri = NeutronNorthboundEnum.PORTS_URI.getUri(); + String bodystring = executeGet(uri, Collections. emptyMap()); + + Type returnType = new TypeToken>() { + }.getType(); + + T returnValue = (T) gsonNeutronNode.fromJson(bodystring, returnType); + + return returnValue; + } + + public void deleteNode(final String nodeType, final String nodeId) throws NeutronRestApiException { + String uri = NeutronNorthboundEnum.NETWORK_PARAM_URI.getUri(); + uri = MessageFormat.format(uri, nodeType, nodeId); + + executeDelete(uri); + } + + @SuppressWarnings("unchecked") + public T updateNeutronNodeV1(final String nodeId, final String ipAddress, final int port) throws NeutronRestApiException { + String uri = NeutronNorthboundEnum.NODE_PORT_PER_NODE_URI.getUri(); + uri = MessageFormat.format(uri, nodeId, ipAddress, String.valueOf(port)); + + String bodystring = executePut(uri); + + T result = (T) gsonNeutronNode.fromJson(bodystring, TypeToken.get(NeutronNodeWrapper.class).getType()); + + return result; + } + + @SuppressWarnings("unchecked") + public T updateNeutronNodeV2(final String nodeType, final String nodeId, final String ipAddress, final int port) throws NeutronRestApiException { + String uri = NeutronNorthboundEnum.NODE_PORT_PER_TYPE_URI.getUri(); + uri = MessageFormat.format(uri, nodeType, nodeId, ipAddress, String.valueOf(port)); + + String bodystring = executePut(uri); + + T result = (T) gsonNeutronNode.fromJson(bodystring, TypeToken.get(NeutronNodeWrapper.class).getType()); + + return result; + } +} \ No newline at end of file diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/resources/NeutronPortsNorthboundAction.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/resources/NeutronPortsNorthboundAction.java new file mode 100644 index 00000000000..78287d97251 --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/resources/NeutronPortsNorthboundAction.java @@ -0,0 +1,111 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.api.resources; + +import java.io.UnsupportedEncodingException; +import java.lang.reflect.Type; +import java.net.URL; +import java.text.MessageFormat; +import java.util.Collections; + +import org.apache.cloudstack.network.opendaylight.api.NeutronRestApiException; +import org.apache.cloudstack.network.opendaylight.api.enums.NeutronNorthboundEnum; +import org.apache.cloudstack.network.opendaylight.api.model.NeutronPortWrapper; +import org.apache.cloudstack.network.opendaylight.api.model.NeutronPortsList; +import org.apache.commons.httpclient.methods.StringRequestEntity; + +import com.google.gson.FieldNamingPolicy; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; + +public class NeutronPortsNorthboundAction extends Action { + + private final Gson gsonNeutronPort; + + public NeutronPortsNorthboundAction(final URL url, final String username, final String password) { + super(url, username, password); + gsonNeutronPort = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); + } + + @SuppressWarnings("unchecked") + public T listAllPorts() throws NeutronRestApiException { + String uri = NeutronNorthboundEnum.PORTS_URI.getUri(); + String bodystring = executeGet(uri, Collections. emptyMap()); + + Type returnType = new TypeToken>() { + }.getType(); + + T returnValue = (T) gsonNeutronPort.fromJson(bodystring, returnType); + + return returnValue; + } + + @SuppressWarnings("unchecked") + public T findPortById(final String portId) throws NeutronRestApiException { + String uri = NeutronNorthboundEnum.PORTS_PARAM_URI.getUri(); + uri = MessageFormat.format(uri, portId); + + String bodystring = executeGet(uri, Collections. emptyMap()); + + Type returnType = new TypeToken() { + }.getType(); + + T returnValue = (T) gsonNeutronPort.fromJson(bodystring, returnType); + + return returnValue; + } + + @SuppressWarnings("unchecked") + public T createNeutronPort(final NeutronPortWrapper newPortWrapper) throws NeutronRestApiException { + try { + String uri = NeutronNorthboundEnum.PORTS_URI.getUri(); + StringRequestEntity entity = new StringRequestEntity(gsonNeutronPort.toJson(newPortWrapper), JSON_CONTENT_TYPE, null); + + String bodystring = executePost(uri, entity); + + T result = (T) gsonNeutronPort.fromJson(bodystring, TypeToken.get(NeutronPortWrapper.class).getType()); + + return result; + } catch (UnsupportedEncodingException e) { + throw new NeutronRestApiException("Failed to encode json request body", e); + } + } + + public void updateNeutronPort(final String portId, final NeutronPortWrapper newPortWrapper) throws NeutronRestApiException { + try { + String uri = NeutronNorthboundEnum.PORTS_PARAM_URI.getUri(); + uri = MessageFormat.format(uri, portId); + + StringRequestEntity entity = new StringRequestEntity(gsonNeutronPort.toJson(newPortWrapper), JSON_CONTENT_TYPE, null); + + executePut(uri, entity); + } catch (UnsupportedEncodingException e) { + throw new NeutronRestApiException("Failed to encode json request body", e); + } + } + + public void deleteNeutronPort(final String portId) throws NeutronRestApiException { + String uri = NeutronNorthboundEnum.PORTS_PARAM_URI.getUri(); + uri = MessageFormat.format(uri, portId); + + executeDelete(uri); + } +} \ No newline at end of file diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/responses/OpenDaylightControllerResponse.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/responses/OpenDaylightControllerResponse.java new file mode 100644 index 00000000000..c11a6ca12ce --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/api/responses/OpenDaylightControllerResponse.java @@ -0,0 +1,73 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.api.responses; + +import com.google.gson.annotations.SerializedName; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +import org.apache.cloudstack.network.opendaylight.dao.OpenDaylightControllerVO; + +import com.cloud.serializer.Param; + +@EntityReference(value = OpenDaylightControllerVO.class) +public class OpenDaylightControllerResponse extends BaseResponse { + @SerializedName(ApiConstants.ID) + @Param(description = "device id of the controller") + private String id; + + @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) + @Param(description = "the physical network to which this controller belongs to") + private String physicalNetworkId; + + @SerializedName(ApiConstants.NAME) + @Param(description = "the name assigned to the controller") + private String name; + + @SerializedName(ApiConstants.URL) + @Param(description = "the url of the controller api") + private String url; + + @SerializedName(ApiConstants.USERNAME) + @Param(description = "the username to authenticate to the controller") + private String username; + + public void setId(String id) { + this.id = id; + } + + public void setPhysicalNetworkId(String physicalNetworkId) { + this.physicalNetworkId = physicalNetworkId; + } + + public void setName(String name) { + this.name = name; + } + + public void setUrl(String url) { + this.url = url; + } + + public void setUsername(String username) { + this.username = username; + } + +} diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/dao/OpenDaylightControllerMappingDao.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/dao/OpenDaylightControllerMappingDao.java new file mode 100644 index 00000000000..f13a3dd8688 --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/dao/OpenDaylightControllerMappingDao.java @@ -0,0 +1,28 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.dao; + +import java.util.List; + +import com.cloud.utils.db.GenericDao; + +public interface OpenDaylightControllerMappingDao extends GenericDao { + List listByPhysicalNetwork(long physicalNetworkId); +} diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/dao/OpenDaylightControllerMappingDaoImpl.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/dao/OpenDaylightControllerMappingDaoImpl.java new file mode 100644 index 00000000000..8cec3c63554 --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/dao/OpenDaylightControllerMappingDaoImpl.java @@ -0,0 +1,45 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.dao; + +import java.util.List; + +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.SearchCriteria.Op; + +public class OpenDaylightControllerMappingDaoImpl extends GenericDaoBase implements OpenDaylightControllerMappingDao { + private SearchBuilder physicalNetworkIdSearch; + + public OpenDaylightControllerMappingDaoImpl() { + physicalNetworkIdSearch = createSearchBuilder(); + physicalNetworkIdSearch.and("physicalNetworkId", physicalNetworkIdSearch.entity().getPhysicalNetworkId(), Op.EQ); + physicalNetworkIdSearch.done(); + } + + @Override + public List listByPhysicalNetwork(long physicalNetworkId) { + SearchCriteria sc = physicalNetworkIdSearch.create(); + sc.setParameters("physicalNetworkId", physicalNetworkId); + return search(sc, null); + } + +} diff --git a/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/dao/OpenDaylightControllerVO.java b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/dao/OpenDaylightControllerVO.java new file mode 100644 index 00000000000..6af058fc91f --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/java/org/apache/cloudstack/network/opendaylight/dao/OpenDaylightControllerVO.java @@ -0,0 +1,100 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.dao; + +import java.util.UUID; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import org.apache.cloudstack.api.InternalIdentity; + +@Entity +@Table(name = "external_opendaylight_controllers") +public class OpenDaylightControllerVO implements InternalIdentity { + private static final long serialVersionUID = -575928081553194369L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "uuid") + private String uuid; + + @Column(name = "host_id") + private long hostId; + + @Column(name = "physical_network_id") + private long physicalNetworkId; + + @Column(name = "provider_name") + private String providerName; + + @Column(name = "device_name") + private String deviceName; + + public OpenDaylightControllerVO() { + uuid = UUID.randomUUID().toString(); + } + + public OpenDaylightControllerVO(final long hostId, final long physicalNetworkId, final String providerName, final String deviceName) { + super(); + this.hostId = hostId; + this.physicalNetworkId = physicalNetworkId; + this.providerName = providerName; + this.deviceName = deviceName; + uuid = UUID.randomUUID().toString(); + } + + @Override + public long getId() { + return id; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public long getPhysicalNetworkId() { + return physicalNetworkId; + } + + public long getHostId() { + return hostId; + } + + public String getProviderName() { + return providerName; + } + + public String getDeviceName() { + return deviceName; + } + +} diff --git a/scripts/network/domr/call_dnsmasq.sh b/plugins/network-elements/opendaylight/src/main/resources/META-INF/cloudstack/opendaylight/module.properties old mode 100755 new mode 100644 similarity index 75% rename from scripts/network/domr/call_dnsmasq.sh rename to plugins/network-elements/opendaylight/src/main/resources/META-INF/cloudstack/opendaylight/module.properties index 81c218d0e7b..6cc5e4e694d --- a/scripts/network/domr/call_dnsmasq.sh +++ b/plugins/network-elements/opendaylight/src/main/resources/META-INF/cloudstack/opendaylight/module.properties @@ -1,4 +1,4 @@ -#!/usr/bin/env bash +# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information @@ -15,13 +15,7 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. +# -usage() { - printf "Usage: %s: \n" $(basename $0) >&2 -} - -cert="/root/.ssh/id_rsa.cloud" - -ssh -p 3922 -q -o StrictHostKeyChecking=no -i $cert root@$1 "/root/dnsmasq.sh $2" -exit $? - +name=opendaylight +parent=network diff --git a/plugins/network-elements/opendaylight/src/main/resources/META-INF/cloudstack/opendaylight/spring-opendaylight-context.xml b/plugins/network-elements/opendaylight/src/main/resources/META-INF/cloudstack/opendaylight/spring-opendaylight-context.xml new file mode 100644 index 00000000000..7f1e84f3818 --- /dev/null +++ b/plugins/network-elements/opendaylight/src/main/resources/META-INF/cloudstack/opendaylight/spring-opendaylight-context.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + diff --git a/plugins/network-elements/opendaylight/src/test/java/org/apache/cloudstack/network/opendaylight/api/test/NeutronEnumsTest.java b/plugins/network-elements/opendaylight/src/test/java/org/apache/cloudstack/network/opendaylight/api/test/NeutronEnumsTest.java new file mode 100644 index 00000000000..453e9e4628a --- /dev/null +++ b/plugins/network-elements/opendaylight/src/test/java/org/apache/cloudstack/network/opendaylight/api/test/NeutronEnumsTest.java @@ -0,0 +1,85 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.api.test; + +import java.text.MessageFormat; + +import junit.framework.Assert; + +import org.apache.cloudstack.network.opendaylight.api.NeutronRestApiException; +import org.apache.cloudstack.network.opendaylight.api.enums.NeutronNorthboundEnum; +import org.junit.Test; + +public class NeutronEnumsTest { + + @Test + public void enumsUrlFormatTest1() throws NeutronRestApiException { + String netUrl = NeutronNorthboundEnum.NETWORK_PARAM_URI.getUri(); + netUrl = MessageFormat.format(netUrl, netId); + + Assert.assertEquals(NETWORK_PARAM_URI, netUrl); + } + + @Test + public void enumsUrlFormatTest2() throws NeutronRestApiException { + String portUrl = NeutronNorthboundEnum.PORTS_PARAM_URI.getUri(); + portUrl = MessageFormat.format(portUrl, portId); + + Assert.assertEquals(PORTS_PARAM_URI, portUrl); + } + + @Test + public void enumsUrlFormatTest3() throws NeutronRestApiException { + String nodedelUrl = NeutronNorthboundEnum.NODE_PARAM_URI.getUri(); + nodedelUrl = MessageFormat.format(nodedelUrl, "test", nodeId); + + Assert.assertEquals(NODE_PARAM_URI, nodedelUrl); + } + + @Test + public void enumsUrlFormatTest4() throws NeutronRestApiException { + String nodeV1Url = NeutronNorthboundEnum.NODE_PORT_PER_NODE_URI.getUri(); + nodeV1Url = MessageFormat.format(nodeV1Url, nodeId, ip, String.valueOf(port)); + + Assert.assertEquals(NODE_PORT_PER_NODE_URI, nodeV1Url); + } + + @Test + public void enumsUrlFormatTest5() throws NeutronRestApiException { + String nodeV2Url = NeutronNorthboundEnum.NODE_PORT_PER_TYPE_URI.getUri(); + nodeV2Url = MessageFormat.format(nodeV2Url, "test", nodeId, ip, String.valueOf(port)); + + Assert.assertEquals(NODE_PORT_PER_TYPE_URI, nodeV2Url); + } + + static String NETWORK_PARAM_URI = "/controller/nb/v2/neutron/networks/0AACEED5-A688-429A-92FC-E1C9E4EEEE98"; + + static String PORTS_PARAM_URI = "/controller/nb/v2/neutron/ports/F4267875-0C85-4829-8434-901A08691C6E"; + + static String NODE_PARAM_URI = "/controller/nb/v2/connectionmanager/node/test/ca31aa7f-84c7-416d-bc00-1f84927367e0"; + static String NODE_PORT_PER_NODE_URI = "/controller/nb/v2/connectionmanager/node/ca31aa7f-84c7-416d-bc00-1f84927367e0/address/1.1.1.1/port/6400"; + static String NODE_PORT_PER_TYPE_URI = "/controller/nb/v2/connectionmanager/node/test/ca31aa7f-84c7-416d-bc00-1f84927367e0/address/1.1.1.1/port/6400"; + + static String netId = "0AACEED5-A688-429A-92FC-E1C9E4EEEE98"; + static String portId = "F4267875-0C85-4829-8434-901A08691C6E"; + static String nodeId = "ca31aa7f-84c7-416d-bc00-1f84927367e0"; + static String ip = "1.1.1.1"; + static int port = 6400; +} \ No newline at end of file diff --git a/plugins/network-elements/opendaylight/src/test/java/org/apache/cloudstack/network/opendaylight/api/test/NeutronNetworkAdapterTest.java b/plugins/network-elements/opendaylight/src/test/java/org/apache/cloudstack/network/opendaylight/api/test/NeutronNetworkAdapterTest.java new file mode 100644 index 00000000000..463646aa97d --- /dev/null +++ b/plugins/network-elements/opendaylight/src/test/java/org/apache/cloudstack/network/opendaylight/api/test/NeutronNetworkAdapterTest.java @@ -0,0 +1,88 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.api.test; + +import java.io.UnsupportedEncodingException; +import java.util.UUID; + +import junit.framework.Assert; + +import org.apache.commons.httpclient.methods.StringRequestEntity; +import org.junit.Test; + +import com.google.gson.FieldNamingPolicy; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; + +import org.apache.cloudstack.network.opendaylight.api.NeutronRestApiException; +import org.apache.cloudstack.network.opendaylight.api.model.NeutronNetwork; +import org.apache.cloudstack.network.opendaylight.api.model.NeutronNetworkWrapper; + +public class NeutronNetworkAdapterTest { + + private final Gson gsonNeutronNetwork = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); + + @Test + public void gsonNeutronNetworkMarshalingTest() throws NeutronRestApiException { + NeutronNetwork network = new NeutronNetwork(); + network.setId(UUID.fromString("ca31aa7f-84c7-416d-bc00-1f84927367e0")); + network.setName("test_gre"); + network.setNetworkType("test"); + network.setSegmentationId(1001); + network.setShared(true); + network.setTenantId("wilder"); + + NeutronNetworkWrapper networkWrapper = new NeutronNetworkWrapper(); + networkWrapper.setNetwork(network); + + StringRequestEntity entity; + try { + entity = new StringRequestEntity(gsonNeutronNetwork.toJson(networkWrapper), "application/json", null); + + String actual = entity.getContent(); + Assert.assertEquals(jsonString, actual); + } catch (UnsupportedEncodingException e) { + Assert.fail(e.getMessage()); + } + } + + @Test + public void gsonNeutronNetworkUnmarshalingTest() throws NeutronRestApiException { + NeutronNetwork network = new NeutronNetwork(); + network.setId(UUID.fromString("ca31aa7f-84c7-416d-bc00-1f84927367e0")); + network.setName("test_gre"); + network.setNetworkType("test"); + network.setSegmentationId(1001); + network.setShared(true); + network.setTenantId("wilder"); + + NeutronNetworkWrapper networkWrapper = new NeutronNetworkWrapper(); + networkWrapper.setNetwork(network); + + NeutronNetworkWrapper returnValue = (NeutronNetworkWrapper) gsonNeutronNetwork.fromJson(jsonString, TypeToken.get(networkWrapper.getClass()).getType()); + + Assert.assertNotNull(returnValue); + Assert.assertEquals("test_gre", returnValue.getNetwork().getName()); + } + + static String jsonString = "{\"network\":{\"id\":\"ca31aa7f-84c7-416d-bc00-1f84927367e0\",\"name\":" + + "\"test_gre\",\"shared\":true,\"tenant_id\":\"wilder\",\"provider:network_type\":\"test\",\"provider:segmentation_id\":1001}}"; +} \ No newline at end of file diff --git a/plugins/network-elements/opendaylight/src/test/java/org/apache/cloudstack/network/opendaylight/api/test/NeutronNodeAdapterTest.java b/plugins/network-elements/opendaylight/src/test/java/org/apache/cloudstack/network/opendaylight/api/test/NeutronNodeAdapterTest.java new file mode 100644 index 00000000000..632b570bd6b --- /dev/null +++ b/plugins/network-elements/opendaylight/src/test/java/org/apache/cloudstack/network/opendaylight/api/test/NeutronNodeAdapterTest.java @@ -0,0 +1,74 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.api.test; + +import java.io.UnsupportedEncodingException; + +import junit.framework.Assert; + +import org.apache.cloudstack.network.opendaylight.api.NeutronRestApiException; +import org.apache.cloudstack.network.opendaylight.api.model.NeutronNode; +import org.apache.cloudstack.network.opendaylight.api.model.NeutronNodeWrapper; +import org.apache.commons.httpclient.methods.StringRequestEntity; +import org.junit.Test; + +import com.google.gson.FieldNamingPolicy; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; + +public class NeutronNodeAdapterTest { + + private final Gson gsonNeutronNode = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); + + @Test + public void gsonNeutronPortMarshalingTest() throws NeutronRestApiException { + NeutronNode node = new NeutronNode("node-test", "test"); + NeutronNodeWrapper nodeWrapper = new NeutronNodeWrapper(node); + + StringRequestEntity entity; + try { + entity = new StringRequestEntity(gsonNeutronNode.toJson(nodeWrapper), "application/json", null); + + String actual = entity.getContent(); + Assert.assertEquals(jsonString, actual); + } catch (UnsupportedEncodingException e) { + Assert.fail(e.getMessage()); + } + } + + @Test + public void gsonNeutronPortUnmarshalingTest() throws NeutronRestApiException { + NeutronNodeWrapper returnValue = (NeutronNodeWrapper) gsonNeutronNode.fromJson(jsonString, TypeToken.get(NeutronNodeWrapper.class).getType()); + + Assert.assertNotNull(returnValue); + Assert.assertEquals("node-test", returnValue.getNode().getId().toString()); + } + + @Test + public void gsonNeutronPortUnmarshalingNullTest() throws NeutronRestApiException { + String json = null; + NeutronNodeWrapper returnValue = (NeutronNodeWrapper) gsonNeutronNode.fromJson(json, TypeToken.get(NeutronNodeWrapper.class).getType()); + + Assert.assertNull(returnValue); + } + + static String jsonString = "{\"node\":{\"id\":\"node-test\",\"type\":\"test\"}}"; +} \ No newline at end of file diff --git a/plugins/network-elements/opendaylight/src/test/java/org/apache/cloudstack/network/opendaylight/api/test/NeutronPortAdapterTest.java b/plugins/network-elements/opendaylight/src/test/java/org/apache/cloudstack/network/opendaylight/api/test/NeutronPortAdapterTest.java new file mode 100644 index 00000000000..d888e9d13f1 --- /dev/null +++ b/plugins/network-elements/opendaylight/src/test/java/org/apache/cloudstack/network/opendaylight/api/test/NeutronPortAdapterTest.java @@ -0,0 +1,95 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.api.test; + +import java.io.UnsupportedEncodingException; +import java.util.UUID; + +import junit.framework.Assert; + +import org.apache.cloudstack.network.opendaylight.api.NeutronRestApiException; +import org.apache.cloudstack.network.opendaylight.api.model.NeutronPort; +import org.apache.cloudstack.network.opendaylight.api.model.NeutronPortWrapper; +import org.apache.commons.httpclient.methods.StringRequestEntity; +import org.junit.Test; + +import com.google.gson.FieldNamingPolicy; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; + +public class NeutronPortAdapterTest { + + private final Gson gsonNeutronPort = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); + + @Test + public void gsonNeutronPortMarshalingTest() throws NeutronRestApiException { + NeutronPort port = new NeutronPort(); + + port.setId(UUID.fromString("ca31aa7f-84c7-416d-bc00-1f84927367e0")); + port.setName("test_gre"); + port.setAdminStateUp(true); + port.setDeviceId(UUID.fromString("ca31aa7f-84c7-416d-bc00-1f84927367e0")); + port.setMacAddress("ca31aa7f-84c7-416d-bc00-1f84927367e0"); + port.setNetworkId(UUID.fromString("ca31aa7f-84c7-416d-bc00-1f84927367e0")); + port.setStatus("ACTIVE"); + port.setTenantId("wilder"); + + NeutronPortWrapper portWrapper = new NeutronPortWrapper(); + portWrapper.setPort(port); + + StringRequestEntity entity; + try { + entity = new StringRequestEntity(gsonNeutronPort.toJson(portWrapper), "application/json", null); + + String actual = entity.getContent(); + + Assert.assertEquals(jsonString, actual); + } catch (UnsupportedEncodingException e) { + Assert.fail(e.getMessage()); + } + } + + @Test + public void gsonNeutronPortUnmarshalingTest() throws NeutronRestApiException { + NeutronPort port = new NeutronPort(); + + port.setId(UUID.fromString("ca31aa7f-84c7-416d-bc00-1f84927367e0")); + port.setName("test_gre"); + port.setAdminStateUp(true); + port.setDeviceId(UUID.fromString("ca31aa7f-84c7-416d-bc00-1f84927367e0")); + port.setMacAddress("ca31aa7f-84c7-416d-bc00-1f84927367e0"); + port.setNetworkId(UUID.fromString("ca31aa7f-84c7-416d-bc00-1f84927367e0")); + port.setStatus("ACTIVE"); + port.setTenantId("wilder"); + + NeutronPortWrapper portWrapper = new NeutronPortWrapper(); + portWrapper.setPort(port); + + NeutronPortWrapper returnValue = (NeutronPortWrapper) gsonNeutronPort.fromJson(jsonString, TypeToken.get(portWrapper.getClass()).getType()); + + Assert.assertNotNull(returnValue); + Assert.assertEquals("ca31aa7f-84c7-416d-bc00-1f84927367e0", returnValue.getPort().getMacAddress()); + } + + static String jsonString = "{\"port\":{\"id\":\"ca31aa7f-84c7-416d-bc00-1f84927367e0\",\"name\":\"test_gre\",\"tenant_id\":\"wilder\",\"network_id\":" + + "\"ca31aa7f-84c7-416d-bc00-1f84927367e0\",\"mac_address\":\"ca31aa7f-84c7-416d-bc00-1f84927367e0\",\"device_id\":\"ca31aa7f-84c7-416d-bc00-1f84927367e0\"," + + "\"admin_state_up\":true,\"status\":\"ACTIVE\"}}"; +} \ No newline at end of file diff --git a/plugins/network-elements/opendaylight/src/test/java/org/apache/cloudstack/network/opendaylight/api/test/NeutronRestApiIT.java b/plugins/network-elements/opendaylight/src/test/java/org/apache/cloudstack/network/opendaylight/api/test/NeutronRestApiIT.java new file mode 100644 index 00000000000..98ceb215aae --- /dev/null +++ b/plugins/network-elements/opendaylight/src/test/java/org/apache/cloudstack/network/opendaylight/api/test/NeutronRestApiIT.java @@ -0,0 +1,95 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.api.test; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.List; + +import junit.framework.Assert; + +import org.apache.cloudstack.network.opendaylight.api.NeutronRestApiException; +import org.apache.cloudstack.network.opendaylight.api.model.NeutronNetworkWrapper; +import org.apache.cloudstack.network.opendaylight.api.model.NeutronNetworksList; +import org.apache.cloudstack.network.opendaylight.api.model.NeutronNodeWrapper; +import org.apache.cloudstack.network.opendaylight.api.model.NeutronNodesList; +import org.apache.cloudstack.network.opendaylight.api.model.NeutronPortWrapper; +import org.apache.cloudstack.network.opendaylight.api.model.NeutronPortsList; +import org.apache.cloudstack.network.opendaylight.api.resources.NeutronNetworksNorthboundAction; +import org.apache.cloudstack.network.opendaylight.api.resources.NeutronNodesNorthboundAction; +import org.apache.cloudstack.network.opendaylight.api.resources.NeutronPortsNorthboundAction; +import org.junit.Test; + +public class NeutronRestApiIT { + + @Test + public void neutronListAllNodes() throws NeutronRestApiException { + URL url; + try { + url = new URL("http://178.237.34.233:8080"); + + NeutronNodesNorthboundAction neutron = new NeutronNodesNorthboundAction(url, "admin", "admin"); + NeutronNodesList results = neutron.listAllNodes(); + + Assert.assertNotNull(results); + + } catch (MalformedURLException e) { + Assert.fail("Should not fail here."); + } + } + + @Test + public void neutronListAllNetworks() throws NeutronRestApiException { + URL url; + try { + url = new URL("http://178.237.34.233:8080"); + + NeutronNetworksNorthboundAction neutron = new NeutronNetworksNorthboundAction(url, "admin", "admin"); + NeutronNetworksList results = neutron.listAllNetworks(); + + Assert.assertNotNull(results); + + List networks = results.getNetworks(); + Assert.assertNotNull(networks); + + } catch (MalformedURLException e) { + Assert.fail("Should not fail here."); + } + } + + @Test + public void neutronListAllPorts() throws NeutronRestApiException { + URL url; + try { + url = new URL("http://178.237.34.233:8080"); + + NeutronPortsNorthboundAction neutron = new NeutronPortsNorthboundAction(url, "admin", "admin"); + NeutronPortsList results = neutron.listAllPorts(); + + Assert.assertNotNull(results); + + List networks = results.getPorts(); + Assert.assertNotNull(networks); + + } catch (MalformedURLException e) { + Assert.fail("Should not fail here."); + } + } +} \ No newline at end of file diff --git a/plugins/network-elements/opendaylight/src/test/java/org/apache/cloudstack/network/opendaylight/api/test/NeutronRestApiTest.java b/plugins/network-elements/opendaylight/src/test/java/org/apache/cloudstack/network/opendaylight/api/test/NeutronRestApiTest.java new file mode 100644 index 00000000000..d340e7daec8 --- /dev/null +++ b/plugins/network-elements/opendaylight/src/test/java/org/apache/cloudstack/network/opendaylight/api/test/NeutronRestApiTest.java @@ -0,0 +1,254 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.cloudstack.network.opendaylight.api.test; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.UUID; + +import junit.framework.Assert; + +import org.apache.cloudstack.network.opendaylight.api.NeutronRestApi; +import org.apache.cloudstack.network.opendaylight.api.NeutronRestApiException; +import org.apache.cloudstack.network.opendaylight.api.NeutronRestFactory; +import org.apache.cloudstack.network.opendaylight.api.model.NeutronNetwork; +import org.apache.cloudstack.network.opendaylight.api.model.NeutronNetworkWrapper; +import org.apache.cloudstack.network.opendaylight.api.resources.NeutronNetworksNorthboundAction; +import org.apache.cloudstack.network.opendaylight.api.resources.NeutronNodesNorthboundAction; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpException; +import org.apache.commons.httpclient.HttpMethodBase; +import org.apache.commons.httpclient.methods.DeleteMethod; +import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.commons.httpclient.methods.PostMethod; +import org.apache.commons.httpclient.methods.PutMethod; +import org.junit.Test; + +public class NeutronRestApiTest { + + NeutronRestFactory factory = NeutronRestFactory.getInstance(); + + NeutronRestApi httpGet = factory.getNeutronApi(GetMethod.class); + NeutronRestApi httpPost = factory.getNeutronApi(PostMethod.class); + NeutronRestApi httpPut = factory.getNeutronApi(PutMethod.class); + NeutronRestApi httpDelete = factory.getNeutronApi(DeleteMethod.class); + + @Test + public void resourceHttpGetInstances() throws NeutronRestApiException { + NeutronRestApi newHttpGet = factory.getNeutronApi(GetMethod.class); + assertTrue(httpGet == newHttpGet); + } + + @Test + public void resourceHttpPostInstances() throws NeutronRestApiException { + NeutronRestApi newHttpPost = factory.getNeutronApi(PostMethod.class); + assertTrue(httpPost == newHttpPost); + } + + @Test + public void resourceHttpPutInstances() throws NeutronRestApiException { + NeutronRestApi newHttpPut = factory.getNeutronApi(PutMethod.class); + assertTrue(httpPut == newHttpPut); + } + + @Test + public void resourceHttpDeleteInstances() throws NeutronRestApiException { + NeutronRestApi newHttpDelete = factory.getNeutronApi(DeleteMethod.class); + assertTrue(httpDelete == newHttpDelete); + } + + @Test(expected = NeutronRestApiException.class) + public void neutronNetworksFail() throws NeutronRestApiException { + URL url; + try { + url = new URL("http://localhost:8080"); + + NeutronNetworksNorthboundAction neutron = new NeutronNetworksNorthboundAction(url, "admin", "admin"); + neutron.listAllNetworks(); + } catch (MalformedURLException e) { + Assert.fail("Should not fail here."); + } + } + + @Test(expected = NeutronRestApiException.class) + public void neutronFindNetworkByIdFail() throws NeutronRestApiException { + URL url; + try { + url = new URL("http://localhost:8080"); + + NeutronNetworksNorthboundAction neutron = new NeutronNetworksNorthboundAction(url, "admin", "admin"); + neutron.findNetworkById("0AACEED5-A688-429A-92FC-E1C9E4EEEE98"); + } catch (MalformedURLException e) { + Assert.fail("Should not fail here."); + } + } + + @Test(expected = NeutronRestApiException.class) + public void neutronNodesFail() throws NeutronRestApiException { + URL url; + try { + url = new URL("http://localhost:8080"); + + NeutronNodesNorthboundAction neutron = new NeutronNodesNorthboundAction(url, "admin", "admin"); + neutron.listAllNodes(); + } catch (MalformedURLException e) { + Assert.fail("Should not fail here."); + } + } + + /* + * Test fails because there is no controller. It's used only to test that + * the HTTP methods are correct. + */ + @Test(expected = NeutronRestApiException.class) + public void neutronHTTPDeleteMethod() throws NeutronRestApiException { + URL url; + try { + url = new URL("http://127.0.0.1:8080"); + + NeutronNetworksNorthboundAction neutron = new NeutronNetworksNorthboundAction(url, "admin", "admin"); + neutron.deleteNeutronNetwork("0AACEED5-A688-429A-92FC-E1C9E4EEEE98"); + } catch (MalformedURLException e) { + Assert.fail("Should not fail here."); + } + } + + /* + * Test fails because there is no controller. It's used only to test that + * the HTTP methods are correct. + */ + @Test(expected = NeutronRestApiException.class) + public void neutronHTTPGetMethod() throws NeutronRestApiException { + URL url; + try { + url = new URL("http://localhost:8080"); + + NeutronNetworksNorthboundAction neutron = new NeutronNetworksNorthboundAction(url, "admin", "admin"); + neutron.listAllNetworks(); + } catch (MalformedURLException e) { + Assert.fail("Should not fail here."); + } + } + + /* + * Test fails because there is no controller. It's used only to test that + * the HTTP methods are correct. + */ + @Test(expected = NeutronRestApiException.class) + public void neutronHTTPPostMethod() throws NeutronRestApiException { + URL url; + try { + url = new URL("http://localhost:8080"); + + NeutronNetwork network = new NeutronNetwork(); + network.setId(UUID.fromString("ca31aa7f-84c7-416d-bc00-1f84927367e0")); + network.setName("test_gre"); + network.setNetworkType("test"); + network.setSegmentationId(1001); + network.setShared(true); + network.setTenantId("wilder"); + + NeutronNetworkWrapper networkWrapper = new NeutronNetworkWrapper(); + networkWrapper.setNetwork(network); + + NeutronNetworksNorthboundAction neutron = new NeutronNetworksNorthboundAction(url, "admin", "admin"); + neutron.createNeutronNetwork(networkWrapper); + + } catch (MalformedURLException e) { + Assert.fail("Should not fail here."); + } + } + + /* + * Test fails because there is no controller. It's used only to test that + * the HTTP methods are correct. + */ + @Test(expected = NeutronRestApiException.class) + public void neutronHTTPPutMethod() throws NeutronRestApiException { + URL url; + try { + url = new URL("http://localhost:8080"); + + NeutronNetwork network = new NeutronNetwork(); + network.setId(UUID.fromString("ca31aa7f-84c7-416d-bc00-1f84927367e0")); + network.setName("test_gre"); + network.setNetworkType("test"); + network.setSegmentationId(1001); + network.setShared(true); + network.setTenantId("wilder"); + + NeutronNetworkWrapper networkWrapper = new NeutronNetworkWrapper(); + networkWrapper.setNetwork(network); + + NeutronNetworksNorthboundAction neutron = new NeutronNetworksNorthboundAction(url, "admin", "admin"); + neutron.updateNeutronNetwork("ca31aa7f-84c7-416d-bc00-1f84927367e0", networkWrapper); + + } catch (MalformedURLException e) { + Assert.fail("Should not fail here."); + } + } + + /* + * Test fails because there is no controller. It's used only to test that + * the HTTP methods are correct. + */ + @Test(expected = NeutronRestApiException.class) + public void neutronHTTPPutUriMethod() throws NeutronRestApiException { + URL url; + try { + url = new URL("http://localhost:8080"); + + NeutronNodesNorthboundAction neutron = new NeutronNodesNorthboundAction(url, "admin", "admin"); + neutron.updateNeutronNodeV1("ca31aa7f-84c7-416d-bc00-1f84927367e0", "1.1.1.1.", 6400); + + } catch (MalformedURLException e) { + Assert.fail("Should not fail here."); + } + } + + static String networkJSON = "{" + "\"networks\": [" + "{" + "\"network\": {" + "\"segmentation_id\": 100," + "\"shared\": false," + "\"name\": \"net_test\"," + + "\"network_type\": \"test\"," + "\"tenant_id\": \"t\"," + "\"id\": \"0AACEED5-A688-429A-92FC-E1C9E4EEEE98\"," + "\"status\": \"ACTIVE\"" + "}" + "}" + "]" + "}"; +} + +class NeutronRestApiMock extends NeutronRestApi { + + HttpClient client = mock(HttpClient.class); + + NeutronRestApiMock(final Class httpClazz) { + super(httpClazz); + } + + @Override + public void executeMethod(final HttpMethodBase method) throws NeutronRestApiException { + try { + client.executeMethod(method); + } catch (HttpException e) { + method.releaseConnection(); + throw new NeutronRestApiException("API call to Neutron NVP Controller Failed", e); + } catch (IOException e) { + method.releaseConnection(); + throw new NeutronRestApiException("API call to Neutron NVP Controller Failed", e); + } + } +} \ No newline at end of file diff --git a/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsCreateGreTunnelAnswer.java b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsCreateGreTunnelAnswer.java index 7913cc845de..e9e34557c70 100644 --- a/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsCreateGreTunnelAnswer.java +++ b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsCreateGreTunnelAnswer.java @@ -16,66 +16,64 @@ // under the License. package com.cloud.agent.api; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.Command; public class OvsCreateGreTunnelAnswer extends Answer { - String hostIp; - String remoteIp; - String bridge; - String key; - long from; - long to; - int port; + String hostIp; + String remoteIp; + String bridge; + String key; + long from; + long to; + int port; - public OvsCreateGreTunnelAnswer(Command cmd, boolean success, String details) { - super(cmd, success, details); - } + public OvsCreateGreTunnelAnswer(Command cmd, boolean success, String details) { + super(cmd, success, details); + } - public OvsCreateGreTunnelAnswer(Command cmd, boolean success, - String details, String hostIp, String bridge) { - super(cmd, success, details); - OvsCreateGreTunnelCommand c = (OvsCreateGreTunnelCommand) cmd; - this.hostIp = hostIp; - this.bridge = bridge; - this.remoteIp = c.getRemoteIp(); - this.key = c.getKey(); - this.port = -1; - this.from = c.getFrom(); - this.to = c.getTo(); - } + public OvsCreateGreTunnelAnswer(Command cmd, boolean success, + String details, String hostIp, String bridge) { + super(cmd, success, details); + OvsCreateGreTunnelCommand c = (OvsCreateGreTunnelCommand)cmd; + this.hostIp = hostIp; + this.bridge = bridge; + this.remoteIp = c.getRemoteIp(); + this.key = c.getKey(); + this.port = -1; + this.from = c.getFrom(); + this.to = c.getTo(); + } - public OvsCreateGreTunnelAnswer(Command cmd, boolean success, - String details, String hostIp, String bridge, int port) { - this(cmd, success, details, hostIp, bridge); - this.port = port; - } + public OvsCreateGreTunnelAnswer(Command cmd, boolean success, + String details, String hostIp, String bridge, int port) { + this(cmd, success, details, hostIp, bridge); + this.port = port; + } - public String getHostIp() { - return hostIp; - } + public String getHostIp() { + return hostIp; + } - public String getRemoteIp() { - return remoteIp; - } + public String getRemoteIp() { + return remoteIp; + } - public String getBridge() { - return bridge; - } + public String getBridge() { + return bridge; + } - public String getKey() { - return key; - } + public String getKey() { + return key; + } - public long getFrom() { - return from; - } + public long getFrom() { + return from; + } - public long getTo() { - return to; - } + public long getTo() { + return to; + } - public int getPort() { - return port; - } + public int getPort() { + return port; + } } diff --git a/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsCreateGreTunnelCommand.java b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsCreateGreTunnelCommand.java index 588ff519006..9a3d4172151 100644 --- a/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsCreateGreTunnelCommand.java +++ b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsCreateGreTunnelCommand.java @@ -16,40 +16,39 @@ // under the License. package com.cloud.agent.api; -import com.cloud.agent.api.Command; public class OvsCreateGreTunnelCommand extends Command { - String remoteIp; - String key; - long from; - long to; + String remoteIp; + String key; + long from; + long to; - @Override - public boolean executeInSequence() { - return true; - } + @Override + public boolean executeInSequence() { + return true; + } - public OvsCreateGreTunnelCommand(String remoteIp, String key, long from, - long to) { - this.remoteIp = remoteIp; - this.key = key; - this.from = from; - this.to = to; - } + public OvsCreateGreTunnelCommand(String remoteIp, String key, long from, + long to) { + this.remoteIp = remoteIp; + this.key = key; + this.from = from; + this.to = to; + } - public String getRemoteIp() { - return remoteIp; - } + public String getRemoteIp() { + return remoteIp; + } - public String getKey() { - return key; - } + public String getKey() { + return key; + } - public long getFrom() { - return from; - } + public long getFrom() { + return from; + } - public long getTo() { - return to; - } + public long getTo() { + return to; + } } diff --git a/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsCreateTunnelAnswer.java b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsCreateTunnelAnswer.java index f921042ca62..96acab7435c 100644 --- a/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsCreateTunnelAnswer.java +++ b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsCreateTunnelAnswer.java @@ -16,70 +16,68 @@ // under the License. package com.cloud.agent.api; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.Command; public class OvsCreateTunnelAnswer extends Answer { - Long from; - Long to; - long networkId; - String inPortName; + Long from; + Long to; + long networkId; + String inPortName; - // for debug info - String fromIp; - String toIp; - int key; - String bridge; + // for debug info + String fromIp; + String toIp; + int key; + String bridge; - public OvsCreateTunnelAnswer(Command cmd, boolean success, String details, - String bridge) { - super(cmd, success, details); - OvsCreateTunnelCommand c = (OvsCreateTunnelCommand) cmd; - from = c.getFrom(); - to = c.getTo(); - networkId = c.getNetworkId(); - inPortName = "[]"; - fromIp = c.getFromIp(); - toIp = c.getRemoteIp(); - key = c.getKey(); - this.bridge = bridge; - } + public OvsCreateTunnelAnswer(Command cmd, boolean success, String details, + String bridge) { + super(cmd, success, details); + OvsCreateTunnelCommand c = (OvsCreateTunnelCommand)cmd; + from = c.getFrom(); + to = c.getTo(); + networkId = c.getNetworkId(); + inPortName = "[]"; + fromIp = c.getFromIp(); + toIp = c.getRemoteIp(); + key = c.getKey(); + this.bridge = bridge; + } - public OvsCreateTunnelAnswer(Command cmd, boolean success, String details, - String inPortName, String bridge) { - this(cmd, success, details, bridge); - this.inPortName = inPortName; - } + public OvsCreateTunnelAnswer(Command cmd, boolean success, String details, + String inPortName, String bridge) { + this(cmd, success, details, bridge); + this.inPortName = inPortName; + } - public Long getFrom() { - return from; - } + public Long getFrom() { + return from; + } - public Long getTo() { - return to; - } + public Long getTo() { + return to; + } - public long getNetworkId() { - return networkId; - } + public long getNetworkId() { + return networkId; + } - public String getInPortName() { - return inPortName; - } + public String getInPortName() { + return inPortName; + } - public String getFromIp() { - return fromIp; - } + public String getFromIp() { + return fromIp; + } - public String getToIp() { - return toIp; - } + public String getToIp() { + return toIp; + } - public int getKey() { - return key; - } + public int getKey() { + return key; + } - public String getBridge() { - return bridge; - } + public String getBridge() { + return bridge; + } } diff --git a/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsCreateTunnelCommand.java b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsCreateTunnelCommand.java index 1dc4d8296d3..7f151fbb680 100644 --- a/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsCreateTunnelCommand.java +++ b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsCreateTunnelCommand.java @@ -16,55 +16,54 @@ // under the License. package com.cloud.agent.api; -import com.cloud.agent.api.Command; public class OvsCreateTunnelCommand extends Command { - Integer key; - String remoteIp; - Long from; - Long to; - long networkId; + Integer key; + String remoteIp; + Long from; + Long to; + long networkId; - // for debug info - String fromIp; + // for debug info + String fromIp; - @Override - public boolean executeInSequence() { - return true; - } + @Override + public boolean executeInSequence() { + return true; + } - public OvsCreateTunnelCommand(String remoteIp, Integer key, Long from, - Long to, long networkId, String fromIp) { - this.remoteIp = remoteIp; - this.key = key; - this.from = from; - this.to = to; - this.networkId = networkId; - this.fromIp = fromIp; - } + public OvsCreateTunnelCommand(String remoteIp, Integer key, Long from, + Long to, long networkId, String fromIp) { + this.remoteIp = remoteIp; + this.key = key; + this.from = from; + this.to = to; + this.networkId = networkId; + this.fromIp = fromIp; + } - public Integer getKey() { - return key; - } + public Integer getKey() { + return key; + } - public String getRemoteIp() { - return remoteIp; - } + public String getRemoteIp() { + return remoteIp; + } - public Long getFrom() { - return from; - } + public Long getFrom() { + return from; + } - public Long getTo() { - return to; - } + public Long getTo() { + return to; + } - public long getNetworkId() { - return networkId; - } + public long getNetworkId() { + return networkId; + } - public String getFromIp() { - return fromIp; - } + public String getFromIp() { + return fromIp; + } } diff --git a/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsDeleteFlowCommand.java b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsDeleteFlowCommand.java index 3b5e1c23370..4d2df9ff171 100644 --- a/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsDeleteFlowCommand.java +++ b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsDeleteFlowCommand.java @@ -16,21 +16,20 @@ // under the License. package com.cloud.agent.api; -import com.cloud.agent.api.Command; public class OvsDeleteFlowCommand extends Command { - String vmName; + String vmName; - @Override - public boolean executeInSequence() { - return true; - } + @Override + public boolean executeInSequence() { + return true; + } - public String getVmName() { - return vmName; - } + public String getVmName() { + return vmName; + } - public OvsDeleteFlowCommand(String vmName) { - this.vmName = vmName; - } + public OvsDeleteFlowCommand(String vmName) { + this.vmName = vmName; + } } diff --git a/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsDestroyBridgeCommand.java b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsDestroyBridgeCommand.java index 21b89af2043..59b50beb9a7 100644 --- a/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsDestroyBridgeCommand.java +++ b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsDestroyBridgeCommand.java @@ -17,28 +17,27 @@ package com.cloud.agent.api; -import com.cloud.agent.api.Command; public class OvsDestroyBridgeCommand extends Command { - Long networkId; - Integer key; + Long networkId; + Integer key; - public OvsDestroyBridgeCommand(Long networkId, Integer key) { - this.networkId = networkId; - this.key = key; - } + public OvsDestroyBridgeCommand(Long networkId, Integer key) { + this.networkId = networkId; + this.key = key; + } - public Long getNetworkId() { - return networkId; - } + public Long getNetworkId() { + return networkId; + } - public Integer getKey() { - return key; - } + public Integer getKey() { + return key; + } - @Override - public boolean executeInSequence() { - return true; - } + @Override + public boolean executeInSequence() { + return true; + } } diff --git a/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsDestroyTunnelCommand.java b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsDestroyTunnelCommand.java index d06acf52df4..4776a07eddd 100644 --- a/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsDestroyTunnelCommand.java +++ b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsDestroyTunnelCommand.java @@ -16,35 +16,34 @@ // under the License. package com.cloud.agent.api; -import com.cloud.agent.api.Command; public class OvsDestroyTunnelCommand extends Command { - Long networkId; - Integer key; - String inPortName; + Long networkId; + Integer key; + String inPortName; - public OvsDestroyTunnelCommand(Long networkId, Integer key, - String inPortName) { - this.networkId = networkId; - this.inPortName = inPortName; - this.key = key; - } + public OvsDestroyTunnelCommand(Long networkId, Integer key, + String inPortName) { + this.networkId = networkId; + this.inPortName = inPortName; + this.key = key; + } - public Long getNetworkId() { - return networkId; - } + public Long getNetworkId() { + return networkId; + } - public String getInPortName() { - return inPortName; - } + public String getInPortName() { + return inPortName; + } - public Integer getKey() { - return key; - } + public Integer getKey() { + return key; + } - @Override - public boolean executeInSequence() { - return true; - } + @Override + public boolean executeInSequence() { + return true; + } } diff --git a/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsFetchInterfaceAnswer.java b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsFetchInterfaceAnswer.java index 6c7deaaf957..237d21a010f 100644 --- a/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsFetchInterfaceAnswer.java +++ b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsFetchInterfaceAnswer.java @@ -17,42 +17,40 @@ package com.cloud.agent.api; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.Command; public class OvsFetchInterfaceAnswer extends Answer { - String ip; - String netmask; - String mac; - String label; + String ip; + String netmask; + String mac; + String label; - public OvsFetchInterfaceAnswer(Command cmd, boolean success, String details) { - super(cmd, success, details); - this.label = ((OvsFetchInterfaceCommand) cmd).getLabel(); - } + public OvsFetchInterfaceAnswer(Command cmd, boolean success, String details) { + super(cmd, success, details); + this.label = ((OvsFetchInterfaceCommand)cmd).getLabel(); + } - public OvsFetchInterfaceAnswer(Command cmd, boolean success, - String details, String ip, String netmask, String mac) { - super(cmd, success, details); - this.ip = ip; - this.netmask = netmask; - this.mac = mac; - this.label = ((OvsFetchInterfaceCommand) cmd).getLabel(); - } + public OvsFetchInterfaceAnswer(Command cmd, boolean success, + String details, String ip, String netmask, String mac) { + super(cmd, success, details); + this.ip = ip; + this.netmask = netmask; + this.mac = mac; + this.label = ((OvsFetchInterfaceCommand)cmd).getLabel(); + } - public String getIp() { - return ip; - } + public String getIp() { + return ip; + } - public String getNetmask() { - return netmask; - } + public String getNetmask() { + return netmask; + } - public String getMac() { - return mac; - } + public String getMac() { + return mac; + } - public String getLabel() { - return label; - } + public String getLabel() { + return label; + } } diff --git a/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsFetchInterfaceCommand.java b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsFetchInterfaceCommand.java index a305d5bb587..79a7e5c2074 100644 --- a/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsFetchInterfaceCommand.java +++ b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsFetchInterfaceCommand.java @@ -17,22 +17,21 @@ package com.cloud.agent.api; -import com.cloud.agent.api.Command; public class OvsFetchInterfaceCommand extends Command { - String label; + String label; - @Override - public boolean executeInSequence() { - return true; - } + @Override + public boolean executeInSequence() { + return true; + } - public OvsFetchInterfaceCommand(String label) { - this.label = label; - } + public OvsFetchInterfaceCommand(String label) { + this.label = label; + } - public String getLabel() { - return label; - } + public String getLabel() { + return label; + } } diff --git a/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsSetTagAndFlowAnswer.java b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsSetTagAndFlowAnswer.java index ee1fe42e6ae..be5be450166 100644 --- a/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsSetTagAndFlowAnswer.java +++ b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsSetTagAndFlowAnswer.java @@ -16,25 +16,23 @@ // under the License. package com.cloud.agent.api; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.Command; public class OvsSetTagAndFlowAnswer extends Answer { - Long vmId; - Long seqno; + Long vmId; + Long seqno; - public OvsSetTagAndFlowAnswer(Command cmd, boolean success, String details) { - super(cmd, success, details); - OvsSetTagAndFlowCommand c = (OvsSetTagAndFlowCommand) cmd; - this.vmId = c.getVmId(); - this.seqno = Long.parseLong(c.getSeqNo()); - } + public OvsSetTagAndFlowAnswer(Command cmd, boolean success, String details) { + super(cmd, success, details); + OvsSetTagAndFlowCommand c = (OvsSetTagAndFlowCommand)cmd; + this.vmId = c.getVmId(); + this.seqno = Long.parseLong(c.getSeqNo()); + } - public Long getVmId() { - return vmId; - } + public Long getVmId() { + return vmId; + } - public Long getSeqNo() { - return seqno; - } + public Long getSeqNo() { + return seqno; + } } diff --git a/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsSetTagAndFlowCommand.java b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsSetTagAndFlowCommand.java index 28a936a3e06..078528b37ce 100644 --- a/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsSetTagAndFlowCommand.java +++ b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsSetTagAndFlowCommand.java @@ -16,46 +16,45 @@ // under the License. package com.cloud.agent.api; -import com.cloud.agent.api.Command; public class OvsSetTagAndFlowCommand extends Command { - String vlans; - String vmName; - String seqno; - String tag; - Long vmId; + String vlans; + String vmName; + String seqno; + String tag; + Long vmId; - @Override - public boolean executeInSequence() { - return true; - } + @Override + public boolean executeInSequence() { + return true; + } - public String getSeqNo() { - return seqno; - } + public String getSeqNo() { + return seqno; + } - public String getVlans() { - return vlans; - } + public String getVlans() { + return vlans; + } - public String getVmName() { - return vmName; - } + public String getVmName() { + return vmName; + } - public Long getVmId() { - return vmId; - } + public Long getVmId() { + return vmId; + } - public String getTag() { - return tag; - } + public String getTag() { + return tag; + } - public OvsSetTagAndFlowCommand(String vmName, String tag, String vlans, - String seqno, Long vmId) { - this.vmName = vmName; - this.tag = tag; - this.vlans = vlans; - this.seqno = seqno; - this.vmId = vmId; - } + public OvsSetTagAndFlowCommand(String vmName, String tag, String vlans, + String seqno, Long vmId) { + this.vmName = vmName; + this.tag = tag; + this.vlans = vlans; + this.seqno = seqno; + this.vmId = vmId; + } } diff --git a/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsSetupBridgeCommand.java b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsSetupBridgeCommand.java index 6968a4c890f..e3390f3c6f7 100644 --- a/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsSetupBridgeCommand.java +++ b/plugins/network-elements/ovs/src/com/cloud/agent/api/OvsSetupBridgeCommand.java @@ -17,33 +17,32 @@ package com.cloud.agent.api; -import com.cloud.agent.api.Command; public class OvsSetupBridgeCommand extends Command { - Integer key; - Long hostId; - Long networkId; + Integer key; + Long hostId; + Long networkId; - @Override - public boolean executeInSequence() { - return true; - } + @Override + public boolean executeInSequence() { + return true; + } - public OvsSetupBridgeCommand(Integer key, Long hostId, Long networkId) { - this.key = key; - this.hostId = hostId; - this.networkId = networkId; - } + public OvsSetupBridgeCommand(Integer key, Long hostId, Long networkId) { + this.key = key; + this.hostId = hostId; + this.networkId = networkId; + } - public Integer getKey() { - return key; - } + public Integer getKey() { + return key; + } - public Long getHostId() { - return hostId; - } + public Long getHostId() { + return hostId; + } - public Long getNetworkId() { - return networkId; - } + public Long getNetworkId() { + return networkId; + } } diff --git a/plugins/network-elements/ovs/src/com/cloud/agent/api/StartupOvsCommand.java b/plugins/network-elements/ovs/src/com/cloud/agent/api/StartupOvsCommand.java index 766aec28e58..17204029970 100644 --- a/plugins/network-elements/ovs/src/com/cloud/agent/api/StartupOvsCommand.java +++ b/plugins/network-elements/ovs/src/com/cloud/agent/api/StartupOvsCommand.java @@ -16,12 +16,11 @@ // under the License. package com.cloud.agent.api; -import com.cloud.agent.api.StartupCommand; import com.cloud.host.Host; public class StartupOvsCommand extends StartupCommand { - public StartupOvsCommand() { - super(Host.Type.L2Networking); - } + public StartupOvsCommand() { + super(Host.Type.L2Networking); + } } diff --git a/plugins/network-elements/ovs/src/com/cloud/network/element/OvsElement.java b/plugins/network-elements/ovs/src/com/cloud/network/element/OvsElement.java index 2641d5488e9..ea46f93b1e2 100644 --- a/plugins/network-elements/ovs/src/com/cloud/network/element/OvsElement.java +++ b/plugins/network-elements/ovs/src/com/cloud/network/element/OvsElement.java @@ -28,6 +28,8 @@ import javax.naming.ConfigurationException; import org.apache.log4j.Logger; +import com.google.gson.Gson; + import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupOvsCommand; import com.cloud.agent.api.to.LoadBalancerTO; @@ -71,189 +73,188 @@ import com.cloud.vm.NicProfile; import com.cloud.vm.ReservationContext; import com.cloud.vm.VirtualMachineProfile; import com.cloud.vm.dao.DomainRouterDao; -import com.google.gson.Gson; -@Local(value = { NetworkElement.class, ConnectivityProvider.class, - SourceNatServiceProvider.class, StaticNatServiceProvider.class, - PortForwardingServiceProvider.class, IpDeployer.class }) +@Local(value = {NetworkElement.class, ConnectivityProvider.class, + SourceNatServiceProvider.class, StaticNatServiceProvider.class, + PortForwardingServiceProvider.class, IpDeployer.class}) public class OvsElement extends AdapterBase implements NetworkElement, - OvsElementService, ConnectivityProvider, ResourceStateAdapter, - PortForwardingServiceProvider, LoadBalancingServiceProvider, - StaticNatServiceProvider, IpDeployer { - @Inject - OvsTunnelManager _ovsTunnelMgr; - @Inject - NetworkModel _networkModel; - @Inject - NetworkServiceMapDao _ntwkSrvcDao; - @Inject - ResourceManager _resourceMgr; - @Inject - DomainRouterDao _routerDao; - @Inject - VpcVirtualNetworkApplianceManager _routerMgr; + OvsElementService, ConnectivityProvider, ResourceStateAdapter, + PortForwardingServiceProvider, LoadBalancingServiceProvider, + StaticNatServiceProvider, IpDeployer { + @Inject + OvsTunnelManager _ovsTunnelMgr; + @Inject + NetworkModel _networkModel; + @Inject + NetworkServiceMapDao _ntwkSrvcDao; + @Inject + ResourceManager _resourceMgr; + @Inject + DomainRouterDao _routerDao; + @Inject + VpcVirtualNetworkApplianceManager _routerMgr; - private static final Logger s_logger = Logger.getLogger(OvsElement.class); - private static final Map> capabilities = setCapabilities(); + private static final Logger s_logger = Logger.getLogger(OvsElement.class); + private static final Map> capabilities = setCapabilities(); - @Override - public Map> getCapabilities() { - return capabilities; - } + @Override + public Map> getCapabilities() { + return capabilities; + } - @Override - public Provider getProvider() { - return Provider.Ovs; - } + @Override + public Provider getProvider() { + return Provider.Ovs; + } - protected boolean canHandle(Network network, Service service) { - s_logger.debug("Checking if OvsElement can handle service " - + service.getName() + " on network " + network.getDisplayText()); - if (network.getBroadcastDomainType() != BroadcastDomainType.Vswitch) { - return false; - } + protected boolean canHandle(Network network, Service service) { + s_logger.debug("Checking if OvsElement can handle service " + + service.getName() + " on network " + network.getDisplayText()); + if (network.getBroadcastDomainType() != BroadcastDomainType.Vswitch) { + return false; + } - if (!_networkModel.isProviderForNetwork(getProvider(), network.getId())) { - s_logger.debug("OvsElement is not a provider for network " - + network.getDisplayText()); - return false; - } + if (!_networkModel.isProviderForNetwork(getProvider(), network.getId())) { + s_logger.debug("OvsElement is not a provider for network " + + network.getDisplayText()); + return false; + } - if (!_ntwkSrvcDao.canProviderSupportServiceInNetwork(network.getId(), - service, Network.Provider.Ovs)) { - s_logger.debug("OvsElement can't provide the " + service.getName() - + " service on network " + network.getDisplayText()); - return false; - } + if (!_ntwkSrvcDao.canProviderSupportServiceInNetwork(network.getId(), + service, Network.Provider.Ovs)) { + s_logger.debug("OvsElement can't provide the " + service.getName() + + " service on network " + network.getDisplayText()); + return false; + } - return true; - } + return true; + } - @Override - public boolean configure(String name, Map params) - throws ConfigurationException { - super.configure(name, params); - _resourceMgr.registerResourceStateAdapter(name, this); - return true; - } + @Override + public boolean configure(String name, Map params) + throws ConfigurationException { + super.configure(name, params); + _resourceMgr.registerResourceStateAdapter(name, this); + return true; + } - @Override - public boolean implement(Network network, NetworkOffering offering, - DeployDestination dest, ReservationContext context) - throws ConcurrentOperationException, ResourceUnavailableException, - InsufficientCapacityException { - s_logger.debug("entering OvsElement implement function for network " - + network.getDisplayText() + " (state " + network.getState() - + ")"); + @Override + public boolean implement(Network network, NetworkOffering offering, + DeployDestination dest, ReservationContext context) + throws ConcurrentOperationException, ResourceUnavailableException, + InsufficientCapacityException { + s_logger.debug("entering OvsElement implement function for network " + + network.getDisplayText() + " (state " + network.getState() + + ")"); - if (!canHandle(network, Service.Connectivity)) { - return false; - } - return true; - } + if (!canHandle(network, Service.Connectivity)) { + return false; + } + return true; + } - @Override - public boolean prepare(Network network, NicProfile nic, - VirtualMachineProfile vm, - DeployDestination dest, ReservationContext context) - throws ConcurrentOperationException, ResourceUnavailableException, - InsufficientCapacityException { - if (!canHandle(network, Service.Connectivity)) { - return false; - } + @Override + public boolean prepare(Network network, NicProfile nic, + VirtualMachineProfile vm, + DeployDestination dest, ReservationContext context) + throws ConcurrentOperationException, ResourceUnavailableException, + InsufficientCapacityException { + if (!canHandle(network, Service.Connectivity)) { + return false; + } - if (nic.getBroadcastType() != Networks.BroadcastDomainType.Vswitch) { - return false; - } + if (nic.getBroadcastType() != Networks.BroadcastDomainType.Vswitch) { + return false; + } - if (nic.getTrafficType() != Networks.TrafficType.Guest) { - return false; - } + if (nic.getTrafficType() != Networks.TrafficType.Guest) { + return false; + } - _ovsTunnelMgr.VmCheckAndCreateTunnel(vm, network, dest); + _ovsTunnelMgr.VmCheckAndCreateTunnel(vm, network, dest); - return true; - } + return true; + } - @Override - public boolean release(Network network, NicProfile nic, - VirtualMachineProfile vm, - ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException { - if (!canHandle(network, Service.Connectivity)) { - return false; - } - if (nic.getBroadcastType() != Networks.BroadcastDomainType.Vswitch) { - return false; - } + @Override + public boolean release(Network network, NicProfile nic, + VirtualMachineProfile vm, + ReservationContext context) throws ConcurrentOperationException, + ResourceUnavailableException { + if (!canHandle(network, Service.Connectivity)) { + return false; + } + if (nic.getBroadcastType() != Networks.BroadcastDomainType.Vswitch) { + return false; + } - if (nic.getTrafficType() != Networks.TrafficType.Guest) { - return false; - } + if (nic.getTrafficType() != Networks.TrafficType.Guest) { + return false; + } - _ovsTunnelMgr.CheckAndDestroyTunnel(vm.getVirtualMachine(), network); - return true; - } + _ovsTunnelMgr.CheckAndDestroyTunnel(vm.getVirtualMachine(), network); + return true; + } - @Override - public boolean shutdown(Network network, ReservationContext context, - boolean cleanup) throws ConcurrentOperationException, - ResourceUnavailableException { - if (!canHandle(network, Service.Connectivity)) { - return false; - } - return true; - } + @Override + public boolean shutdown(Network network, ReservationContext context, + boolean cleanup) throws ConcurrentOperationException, + ResourceUnavailableException { + if (!canHandle(network, Service.Connectivity)) { + return false; + } + return true; + } - @Override - public boolean destroy(Network network, ReservationContext context) - throws ConcurrentOperationException, ResourceUnavailableException { - if (!canHandle(network, Service.Connectivity)) { - return false; - } - return true; - } + @Override + public boolean destroy(Network network, ReservationContext context) + throws ConcurrentOperationException, ResourceUnavailableException { + if (!canHandle(network, Service.Connectivity)) { + return false; + } + return true; + } - @Override - public boolean isReady(PhysicalNetworkServiceProvider provider) { - return true; - } + @Override + public boolean isReady(PhysicalNetworkServiceProvider provider) { + return true; + } - @Override - public boolean shutdownProviderInstances( - PhysicalNetworkServiceProvider provider, ReservationContext context) - throws ConcurrentOperationException, ResourceUnavailableException { - return true; - } + @Override + public boolean shutdownProviderInstances( + PhysicalNetworkServiceProvider provider, ReservationContext context) + throws ConcurrentOperationException, ResourceUnavailableException { + return true; + } - @Override - public boolean canEnableIndividualServices() { - return true; - } + @Override + public boolean canEnableIndividualServices() { + return true; + } - @Override - public boolean verifyServicesCombination(Set services) { - if (!services.contains(Service.Connectivity)) { - s_logger.warn("Unable to provide services without Connectivity service enabled for this element"); - return false; - } + @Override + public boolean verifyServicesCombination(Set services) { + if (!services.contains(Service.Connectivity)) { + s_logger.warn("Unable to provide services without Connectivity service enabled for this element"); + return false; + } - return true; - } + return true; + } - private static Map> setCapabilities() { - Map> capabilities = new HashMap>(); + private static Map> setCapabilities() { + Map> capabilities = new HashMap>(); - // L2 Support : SDN provisioning - capabilities.put(Service.Connectivity, null); + // L2 Support : SDN provisioning + capabilities.put(Service.Connectivity, null); - // L3 Support : Port Forwarding - capabilities.put(Service.PortForwarding, null); + // L3 Support : Port Forwarding + capabilities.put(Service.PortForwarding, null); - // L3 support : StaticNat - capabilities.put(Service.StaticNat, null); + // L3 support : StaticNat + capabilities.put(Service.StaticNat, null); - // L3 support : Load Balancer + // L3 support : Load Balancer // Set capabilities for LB service Map lbCapabilities = new HashMap(); lbCapabilities.put(Capability.SupportedLBAlgorithms, "roundrobin,leastconn,source"); @@ -264,9 +265,9 @@ public class OvsElement extends AdapterBase implements NetworkElement, capabilities.put(Service.Lb, lbCapabilities); - return capabilities; - } - + return capabilities; + } + public static String getHAProxyStickinessCapability() { LbStickinessMethod method; List methodList = new ArrayList(1); @@ -274,89 +275,90 @@ public class OvsElement extends AdapterBase implements NetworkElement, method = new LbStickinessMethod(StickinessMethodType.LBCookieBased, "This is loadbalancer cookie based stickiness method."); method.addParam("cookie-name", false, "Cookie name passed in http header by the LB to the client.", false); method.addParam("mode", false, - "Valid values: insert, rewrite, prefix. Default value: insert. In the insert mode cookie will be created" + + "Valid values: insert, rewrite, prefix. Default value: insert. In the insert mode cookie will be created" + " by the LB. In other modes, cookie will be created by the server and LB modifies it.", false); method.addParam( - "nocache", - false, - "This option is recommended in conjunction with the insert mode when there is a cache between the client" + + "nocache", + false, + "This option is recommended in conjunction with the insert mode when there is a cache between the client" + " and HAProxy, as it ensures that a cacheable response will be tagged non-cacheable if a cookie needs " + "to be inserted. This is important because if all persistence cookies are added on a cacheable home page" + " for instance, then all customers will then fetch the page from an outer cache and will all share the " + "same persistence cookie, leading to one server receiving much more traffic than others. See also the " + "insert and postonly options. ", - true); + true); method.addParam( - "indirect", - false, - "When this option is specified in insert mode, cookies will only be added when the server was not reached" + + "indirect", + false, + "When this option is specified in insert mode, cookies will only be added when the server was not reached" + " after a direct access, which means that only when a server is elected after applying a load-balancing algorithm," + " or after a redispatch, then the cookie will be inserted. If the client has all the required information" + " to connect to the same server next time, no further cookie will be inserted. In all cases, when the " + "indirect option is used in insert mode, the cookie is always removed from the requests transmitted to " + "the server. The persistence mechanism then becomes totally transparent from the application point of view.", - true); + true); method.addParam( - "postonly", - false, - "This option ensures that cookie insertion will only be performed on responses to POST requests. It is an" + + "postonly", + false, + "This option ensures that cookie insertion will only be performed on responses to POST requests. It is an" + " alternative to the nocache option, because POST responses are not cacheable, so this ensures that the " + "persistence cookie will never get cached.Since most sites do not need any sort of persistence before the" + " first POST which generally is a login request, this is a very efficient method to optimize caching " + "without risking to find a persistence cookie in the cache. See also the insert and nocache options.", - true); + true); method.addParam( - "domain", - false, - "This option allows to specify the domain at which a cookie is inserted. It requires exactly one parameter:" + + "domain", + false, + "This option allows to specify the domain at which a cookie is inserted. It requires exactly one parameter:" + " a valid domain name. If the domain begins with a dot, the browser is allowed to use it for any host " + "ending with that name. It is also possible to specify several domain names by invoking this option multiple" + " times. Some browsers might have small limits on the number of domains, so be careful when doing that. " + "For the record, sending 10 domains to MSIE 6 or Firefox 2 works as expected.", - false); + false); methodList.add(method); method = new LbStickinessMethod(StickinessMethodType.AppCookieBased, - "This is App session based sticky method. Define session stickiness on an existing application cookie. " + + "This is App session based sticky method. Define session stickiness on an existing application cookie. " + "It can be used only for a specific http traffic"); method.addParam("cookie-name", false, "This is the name of the cookie used by the application and which LB will " + - "have to learn for each new session. Default value: Auto geneared based on ip", false); + "have to learn for each new session. Default value: Auto geneared based on ip", false); method.addParam("length", false, "This is the max number of characters that will be memorized and checked in " + - "each cookie value. Default value:52", false); + "each cookie value. Default value:52", false); method.addParam( - "holdtime", - false, - "This is the time after which the cookie will be removed from memory if unused. The value should be in " + + "holdtime", + false, + "This is the time after which the cookie will be removed from memory if unused. The value should be in " + "the format Example : 20s or 30m or 4h or 5d . only seconds(s), minutes(m) hours(h) and days(d) are valid," + " cannot use th combinations like 20h30m. Default value:3h ", - false); + false); method.addParam( - "request-learn", - false, - "If this option is specified, then haproxy will be able to learn the cookie found in the request in case the server does not specify any in response. This is typically what happens with PHPSESSID cookies, or when haproxy's session expires before the application's session and the correct server is selected. It is recommended to specify this option to improve reliability", - true); + "request-learn", + false, + "If this option is specified, then haproxy will be able to learn the cookie found in the request in case the server does not specify any in response. This is typically what happens with PHPSESSID cookies, or when haproxy's session expires before the application's session and the correct server is selected. It is recommended to specify this option to improve reliability", + true); method.addParam( - "prefix", - false, - "When this option is specified, haproxy will match on the cookie prefix (or URL parameter prefix). " + + "prefix", + false, + "When this option is specified, haproxy will match on the cookie prefix (or URL parameter prefix). " + + "The appsession value is the data following this prefix. Example : appsession ASPSESSIONID len 64 timeout 3h prefix This will match the cookie ASPSESSIONIDXXXX=XXXXX, the appsession value will be XXXX=XXXXX.", - true); + true); method.addParam( - "mode", - false, - "This option allows to change the URL parser mode. 2 modes are currently supported : - path-parameters " + + "mode", + false, + "This option allows to change the URL parser mode. 2 modes are currently supported : - path-parameters " + ": The parser looks for the appsession in the path parameters part (each parameter is separated by a semi-colon), " + "which is convenient for JSESSIONID for example.This is the default mode if the option is not set. - query-string :" + " In this mode, the parser will look for the appsession in the query string.", - false); + false); methodList.add(method); method = new LbStickinessMethod(StickinessMethodType.SourceBased, "This is source based Stickiness method, " + - "it can be used for any type of protocol."); + "it can be used for any type of protocol."); method.addParam("tablesize", false, "Size of table to store source ip addresses. example: tablesize=200k or 300m" + - " or 400g. Default value:200k", false); + " or 400g. Default value:200k", false); method.addParam("expire", false, "Entry in source ip table will expire after expire duration. units can be s,m,h,d ." + - " example: expire=30m 20s 50h 4d. Default value:3h", false); + " example: expire=30m 20s 50h 4d. Default value:3h", false); methodList.add(method); Gson gson = new Gson(); @@ -364,287 +366,287 @@ public class OvsElement extends AdapterBase implements NetworkElement, return capability; } - @Override - public List> getCommands() { - List> cmdList = new ArrayList>(); - return cmdList; - } + @Override + public List> getCommands() { + List> cmdList = new ArrayList>(); + return cmdList; + } - @Override - public HostVO createHostVOForConnectedAgent(HostVO host, - StartupCommand[] cmd) { - return null; - } + @Override + public HostVO createHostVOForConnectedAgent(HostVO host, + StartupCommand[] cmd) { + return null; + } - @Override - public HostVO createHostVOForDirectConnectAgent(HostVO host, - StartupCommand[] startup, ServerResource resource, - Map details, List hostTags) { - if (!(startup[0] instanceof StartupOvsCommand)) { - return null; - } - host.setType(Host.Type.L2Networking); - return host; - } + @Override + public HostVO createHostVOForDirectConnectAgent(HostVO host, + StartupCommand[] startup, ServerResource resource, + Map details, List hostTags) { + if (!(startup[0] instanceof StartupOvsCommand)) { + return null; + } + host.setType(Host.Type.L2Networking); + return host; + } - @Override - public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, - boolean isForceDeleteStorage) throws UnableDeleteHostException { - if (!(host.getType() == Host.Type.L2Networking)) { - return null; - } - return new DeleteHostAnswer(true); - } + @Override + public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, + boolean isForceDeleteStorage) throws UnableDeleteHostException { + if (!(host.getType() == Host.Type.L2Networking)) { + return null; + } + return new DeleteHostAnswer(true); + } - @Override - public IpDeployer getIpDeployer(Network network) { - return this; - } + @Override + public IpDeployer getIpDeployer(Network network) { + return this; + } - @Override - public boolean applyIps(Network network, - List ipAddress, Set services) - throws ResourceUnavailableException { - boolean canHandle = true; - for (Service service : services) { - // check if Ovs can handle services except SourceNat & Firewall - if (!canHandle(network, service) && service != Service.SourceNat && service != Service.Firewall) { - canHandle = false; - break; - } - } - if (canHandle) { - List routers = _routerDao.listByNetworkAndRole( - network.getId(), Role.VIRTUAL_ROUTER); - if (routers == null || routers.isEmpty()) { - s_logger.debug("Virtual router element doesn't need to associate ip addresses on the backend; virtual " - + "router doesn't exist in the network " - + network.getId()); - return true; - } + @Override + public boolean applyIps(Network network, + List ipAddress, Set services) + throws ResourceUnavailableException { + boolean canHandle = true; + for (Service service : services) { + // check if Ovs can handle services except SourceNat & Firewall + if (!canHandle(network, service) && service != Service.SourceNat && service != Service.Firewall) { + canHandle = false; + break; + } + } + if (canHandle) { + List routers = _routerDao.listByNetworkAndRole( + network.getId(), Role.VIRTUAL_ROUTER); + if (routers == null || routers.isEmpty()) { + s_logger.debug("Virtual router element doesn't need to associate ip addresses on the backend; virtual " + + "router doesn't exist in the network " + + network.getId()); + return true; + } - return _routerMgr.associatePublicIP(network, ipAddress, routers); - } else { - return false; - } - } + return _routerMgr.associatePublicIP(network, ipAddress, routers); + } else { + return false; + } + } - @Override - public boolean applyStaticNats(Network network, List rules) - throws ResourceUnavailableException { - if (!canHandle(network, Service.StaticNat)) { - return false; - } - List routers = _routerDao.listByNetworkAndRole( - network.getId(), Role.VIRTUAL_ROUTER); - if (routers == null || routers.isEmpty()) { - s_logger.debug("Ovs element doesn't need to apply static nat on the backend; virtual " - + "router doesn't exist in the network " + network.getId()); - return true; - } + @Override + public boolean applyStaticNats(Network network, List rules) + throws ResourceUnavailableException { + if (!canHandle(network, Service.StaticNat)) { + return false; + } + List routers = _routerDao.listByNetworkAndRole( + network.getId(), Role.VIRTUAL_ROUTER); + if (routers == null || routers.isEmpty()) { + s_logger.debug("Ovs element doesn't need to apply static nat on the backend; virtual " + + "router doesn't exist in the network " + network.getId()); + return true; + } - return _routerMgr.applyStaticNats(network, rules, routers); - } + return _routerMgr.applyStaticNats(network, rules, routers); + } - @Override - public boolean applyPFRules(Network network, List rules) - throws ResourceUnavailableException { - if (!canHandle(network, Service.PortForwarding)) { - return false; - } - List routers = _routerDao.listByNetworkAndRole( - network.getId(), Role.VIRTUAL_ROUTER); - if (routers == null || routers.isEmpty()) { - s_logger.debug("Ovs element doesn't need to apply firewall rules on the backend; virtual " - + "router doesn't exist in the network " + network.getId()); - return true; - } + @Override + public boolean applyPFRules(Network network, List rules) + throws ResourceUnavailableException { + if (!canHandle(network, Service.PortForwarding)) { + return false; + } + List routers = _routerDao.listByNetworkAndRole( + network.getId(), Role.VIRTUAL_ROUTER); + if (routers == null || routers.isEmpty()) { + s_logger.debug("Ovs element doesn't need to apply firewall rules on the backend; virtual " + + "router doesn't exist in the network " + network.getId()); + return true; + } - return _routerMgr.applyFirewallRules(network, rules, routers); - } + return _routerMgr.applyFirewallRules(network, rules, routers); + } - @Override - public boolean applyLBRules(Network network, List rules) - throws ResourceUnavailableException { - if (canHandle(network, Service.Lb)) { - if (!canHandleLbRules(rules)) { - return false; - } + @Override + public boolean applyLBRules(Network network, List rules) + throws ResourceUnavailableException { + if (canHandle(network, Service.Lb)) { + if (!canHandleLbRules(rules)) { + return false; + } - List routers = _routerDao.listByNetworkAndRole( - network.getId(), Role.VIRTUAL_ROUTER); - if (routers == null || routers.isEmpty()) { - s_logger.debug("Virtual router elemnt doesn't need to apply firewall rules on the backend; virtual " - + "router doesn't exist in the network " - + network.getId()); - return true; - } + List routers = _routerDao.listByNetworkAndRole( + network.getId(), Role.VIRTUAL_ROUTER); + if (routers == null || routers.isEmpty()) { + s_logger.debug("Virtual router elemnt doesn't need to apply firewall rules on the backend; virtual " + + "router doesn't exist in the network " + + network.getId()); + return true; + } - if (!_routerMgr.applyLoadBalancingRules(network, rules, routers)) { - throw new CloudRuntimeException( - "Failed to apply load balancing rules in network " - + network.getId()); - } else { - return true; - } - } else { - return false; - } - } + if (!_routerMgr.applyLoadBalancingRules(network, rules, routers)) { + throw new CloudRuntimeException( + "Failed to apply load balancing rules in network " + + network.getId()); + } else { + return true; + } + } else { + return false; + } + } - @Override - public boolean validateLBRule(Network network, LoadBalancingRule rule) { - List rules = new ArrayList(); - rules.add(rule); - if (canHandle(network, Service.Lb) && canHandleLbRules(rules)) { - List routers = _routerDao.listByNetworkAndRole( - network.getId(), Role.VIRTUAL_ROUTER); - if (routers == null || routers.isEmpty()) { - return true; - } - return validateHAProxyLBRule(rule); - } - return true; - } + @Override + public boolean validateLBRule(Network network, LoadBalancingRule rule) { + List rules = new ArrayList(); + rules.add(rule); + if (canHandle(network, Service.Lb) && canHandleLbRules(rules)) { + List routers = _routerDao.listByNetworkAndRole( + network.getId(), Role.VIRTUAL_ROUTER); + if (routers == null || routers.isEmpty()) { + return true; + } + return validateHAProxyLBRule(rule); + } + return true; + } - @Override - public List updateHealthChecks(Network network, - List lbrules) { - // TODO Auto-generated method stub - return null; - } + @Override + public List updateHealthChecks(Network network, + List lbrules) { + // TODO Auto-generated method stub + return null; + } - private boolean canHandleLbRules(List rules) { - Map lbCaps = this.getCapabilities().get(Service.Lb); - if (!lbCaps.isEmpty()) { - String schemeCaps = lbCaps.get(Capability.LbSchemes); - if (schemeCaps != null) { - for (LoadBalancingRule rule : rules) { - if (!schemeCaps.contains(rule.getScheme().toString())) { - s_logger.debug("Scheme " + rules.get(0).getScheme() - + " is not supported by the provider " - + this.getName()); - return false; - } - } - } - } - return true; - } + private boolean canHandleLbRules(List rules) { + Map lbCaps = this.getCapabilities().get(Service.Lb); + if (!lbCaps.isEmpty()) { + String schemeCaps = lbCaps.get(Capability.LbSchemes); + if (schemeCaps != null) { + for (LoadBalancingRule rule : rules) { + if (!schemeCaps.contains(rule.getScheme().toString())) { + s_logger.debug("Scheme " + rules.get(0).getScheme() + + " is not supported by the provider " + + this.getName()); + return false; + } + } + } + } + return true; + } - public static boolean validateHAProxyLBRule(LoadBalancingRule rule) { - String timeEndChar = "dhms"; + public static boolean validateHAProxyLBRule(LoadBalancingRule rule) { + String timeEndChar = "dhms"; - for (LbStickinessPolicy stickinessPolicy : rule.getStickinessPolicies()) { - List> paramsList = stickinessPolicy - .getParams(); + for (LbStickinessPolicy stickinessPolicy : rule.getStickinessPolicies()) { + List> paramsList = stickinessPolicy + .getParams(); - if (StickinessMethodType.LBCookieBased.getName().equalsIgnoreCase( - stickinessPolicy.getMethodName())) { + if (StickinessMethodType.LBCookieBased.getName().equalsIgnoreCase( + stickinessPolicy.getMethodName())) { - } else if (StickinessMethodType.SourceBased.getName() - .equalsIgnoreCase(stickinessPolicy.getMethodName())) { - String tablesize = "200k"; // optional - String expire = "30m"; // optional + } else if (StickinessMethodType.SourceBased.getName() + .equalsIgnoreCase(stickinessPolicy.getMethodName())) { + String tablesize = "200k"; // optional + String expire = "30m"; // optional - /* overwrite default values with the stick parameters */ - for (Pair paramKV : paramsList) { - String key = paramKV.first(); - String value = paramKV.second(); - if ("tablesize".equalsIgnoreCase(key)) - tablesize = value; - if ("expire".equalsIgnoreCase(key)) - expire = value; - } - if ((expire != null) - && !containsOnlyNumbers(expire, timeEndChar)) { - throw new InvalidParameterValueException( - "Failed LB in validation rule id: " + rule.getId() - + " Cause: expire is not in timeformat: " - + expire); - } - if ((tablesize != null) - && !containsOnlyNumbers(tablesize, "kmg")) { - throw new InvalidParameterValueException( - "Failed LB in validation rule id: " - + rule.getId() - + " Cause: tablesize is not in size format: " - + tablesize); + /* overwrite default values with the stick parameters */ + for (Pair paramKV : paramsList) { + String key = paramKV.first(); + String value = paramKV.second(); + if ("tablesize".equalsIgnoreCase(key)) + tablesize = value; + if ("expire".equalsIgnoreCase(key)) + expire = value; + } + if ((expire != null) + && !containsOnlyNumbers(expire, timeEndChar)) { + throw new InvalidParameterValueException( + "Failed LB in validation rule id: " + rule.getId() + + " Cause: expire is not in timeformat: " + + expire); + } + if ((tablesize != null) + && !containsOnlyNumbers(tablesize, "kmg")) { + throw new InvalidParameterValueException( + "Failed LB in validation rule id: " + + rule.getId() + + " Cause: tablesize is not in size format: " + + tablesize); - } - } else if (StickinessMethodType.AppCookieBased.getName() - .equalsIgnoreCase(stickinessPolicy.getMethodName())) { - /* - * FORMAT : appsession len timeout - * [request-learn] [prefix] [mode - * ] - */ - /* example: appsession JSESSIONID len 52 timeout 3h */ - String cookieName = null; // optional - String length = null; // optional - String holdTime = null; // optional + } + } else if (StickinessMethodType.AppCookieBased.getName() + .equalsIgnoreCase(stickinessPolicy.getMethodName())) { + /* + * FORMAT : appsession len timeout + * [request-learn] [prefix] [mode + * ] + */ + /* example: appsession JSESSIONID len 52 timeout 3h */ + String cookieName = null; // optional + String length = null; // optional + String holdTime = null; // optional - for (Pair paramKV : paramsList) { - String key = paramKV.first(); - String value = paramKV.second(); - if ("cookie-name".equalsIgnoreCase(key)) - cookieName = value; - if ("length".equalsIgnoreCase(key)) - length = value; - if ("holdtime".equalsIgnoreCase(key)) - holdTime = value; - } + for (Pair paramKV : paramsList) { + String key = paramKV.first(); + String value = paramKV.second(); + if ("cookie-name".equalsIgnoreCase(key)) + cookieName = value; + if ("length".equalsIgnoreCase(key)) + length = value; + if ("holdtime".equalsIgnoreCase(key)) + holdTime = value; + } - if ((length != null) && (!containsOnlyNumbers(length, null))) { - throw new InvalidParameterValueException( - "Failed LB in validation rule id: " + rule.getId() - + " Cause: length is not a number: " - + length); - } - if ((holdTime != null) - && (!containsOnlyNumbers(holdTime, timeEndChar) && !containsOnlyNumbers( - holdTime, null))) { - throw new InvalidParameterValueException( - "Failed LB in validation rule id: " + rule.getId() - + " Cause: holdtime is not in timeformat: " - + holdTime); - } - } - } - return true; - } + if ((length != null) && (!containsOnlyNumbers(length, null))) { + throw new InvalidParameterValueException( + "Failed LB in validation rule id: " + rule.getId() + + " Cause: length is not a number: " + + length); + } + if ((holdTime != null) + && (!containsOnlyNumbers(holdTime, timeEndChar) && !containsOnlyNumbers( + holdTime, null))) { + throw new InvalidParameterValueException( + "Failed LB in validation rule id: " + rule.getId() + + " Cause: holdtime is not in timeformat: " + + holdTime); + } + } + } + return true; + } - /* - * This function detects numbers like 12 ,32h ,42m .. etc,. 1) plain number - * like 12 2) time or tablesize like 12h, 34m, 45k, 54m , here last - * character is non-digit but from known characters . - */ - private static boolean containsOnlyNumbers(String str, String endChar) { - if (str == null) - return false; + /* + * This function detects numbers like 12 ,32h ,42m .. etc,. 1) plain number + * like 12 2) time or tablesize like 12h, 34m, 45k, 54m , here last + * character is non-digit but from known characters . + */ + private static boolean containsOnlyNumbers(String str, String endChar) { + if (str == null) + return false; - String number = str; - if (endChar != null) { - boolean matchedEndChar = false; - if (str.length() < 2) - return false; // atleast one numeric and one char. example: - // 3h - char strEnd = str.toCharArray()[str.length() - 1]; - for (char c : endChar.toCharArray()) { - if (strEnd == c) { - number = str.substring(0, str.length() - 1); - matchedEndChar = true; - break; - } - } - if (!matchedEndChar) - return false; - } - try { - int i = Integer.parseInt(number); - } catch (NumberFormatException e) { - return false; - } - return true; - } + String number = str; + if (endChar != null) { + boolean matchedEndChar = false; + if (str.length() < 2) + return false; // atleast one numeric and one char. example: + // 3h + char strEnd = str.toCharArray()[str.length() - 1]; + for (char c : endChar.toCharArray()) { + if (strEnd == c) { + number = str.substring(0, str.length() - 1); + matchedEndChar = true; + break; + } + } + if (!matchedEndChar) + return false; + } + try { + int i = Integer.parseInt(number); + } catch (NumberFormatException e) { + return false; + } + return true; + } } diff --git a/plugins/network-elements/ovs/src/com/cloud/network/guru/OvsGuestNetworkGuru.java b/plugins/network-elements/ovs/src/com/cloud/network/guru/OvsGuestNetworkGuru.java index 7a671a0359f..6aacbb21c62 100644 --- a/plugins/network-elements/ovs/src/com/cloud/network/guru/OvsGuestNetworkGuru.java +++ b/plugins/network-elements/ovs/src/com/cloud/network/guru/OvsGuestNetworkGuru.java @@ -20,9 +20,10 @@ import javax.ejb.Local; import javax.inject.Inject; import org.apache.log4j.Logger; -import org.apache.cloudstack.context.CallContext; import org.springframework.stereotype.Component; +import org.apache.cloudstack.context.CallContext; + import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter.NetworkType; import com.cloud.deploy.DeployDestination; @@ -48,175 +49,174 @@ import com.cloud.offerings.dao.NetworkOfferingServiceMapDao; import com.cloud.user.Account; import com.cloud.vm.NicProfile; import com.cloud.vm.ReservationContext; -import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; @Component @Local(value = NetworkGuru.class) public class OvsGuestNetworkGuru extends GuestNetworkGuru { - private static final Logger s_logger = Logger - .getLogger(OvsGuestNetworkGuru.class); + private static final Logger s_logger = Logger + .getLogger(OvsGuestNetworkGuru.class); - @Inject - OvsTunnelManager _ovsTunnelMgr; - @Inject - NetworkOfferingServiceMapDao _ntwkOfferingSrvcDao; + @Inject + OvsTunnelManager _ovsTunnelMgr; + @Inject + NetworkOfferingServiceMapDao _ntwkOfferingSrvcDao; - OvsGuestNetworkGuru() { - super(); - _isolationMethods = new IsolationMethod[] { IsolationMethod.GRE, - IsolationMethod.L3, IsolationMethod.VLAN }; - } + OvsGuestNetworkGuru() { + super(); + _isolationMethods = new IsolationMethod[] {IsolationMethod.GRE, + IsolationMethod.L3, IsolationMethod.VLAN}; + } - @Override - protected boolean canHandle(NetworkOffering offering, - final NetworkType networkType, final PhysicalNetwork physicalNetwork) { - // This guru handles only Guest Isolated network that supports Source - // nat service - if (networkType == NetworkType.Advanced - && isMyTrafficType(offering.getTrafficType()) - && offering.getGuestType() == Network.GuestType.Isolated - && isMyIsolationMethod(physicalNetwork) - && _ntwkOfferingSrvcDao.areServicesSupportedByNetworkOffering( - offering.getId(), Service.Connectivity)) { - return true; - } else { - s_logger.trace("We only take care of Guest networks of type " - + GuestType.Isolated + " in zone of type " - + NetworkType.Advanced); - return false; - } - } + @Override + protected boolean canHandle(NetworkOffering offering, + final NetworkType networkType, final PhysicalNetwork physicalNetwork) { + // This guru handles only Guest Isolated network that supports Source + // nat service + if (networkType == NetworkType.Advanced + && isMyTrafficType(offering.getTrafficType()) + && offering.getGuestType() == Network.GuestType.Isolated + && isMyIsolationMethod(physicalNetwork) + && _ntwkOfferingSrvcDao.areServicesSupportedByNetworkOffering( + offering.getId(), Service.Connectivity)) { + return true; + } else { + s_logger.trace("We only take care of Guest networks of type " + + GuestType.Isolated + " in zone of type " + + NetworkType.Advanced); + return false; + } + } - @Override - public Network design(NetworkOffering offering, DeploymentPlan plan, - Network userSpecified, Account owner) { + @Override + public Network design(NetworkOffering offering, DeploymentPlan plan, + Network userSpecified, Account owner) { - PhysicalNetworkVO physnet = _physicalNetworkDao.findById(plan - .getPhysicalNetworkId()); - DataCenter dc = _dcDao.findById(plan.getDataCenterId()); - if (!canHandle(offering, dc.getNetworkType(), physnet)) { - s_logger.debug("Refusing to design this network"); - return null; - } - NetworkVO config = (NetworkVO) super.design(offering, plan, - userSpecified, owner); - if (config == null) { - return null; - } + PhysicalNetworkVO physnet = _physicalNetworkDao.findById(plan + .getPhysicalNetworkId()); + DataCenter dc = _dcDao.findById(plan.getDataCenterId()); + if (!canHandle(offering, dc.getNetworkType(), physnet)) { + s_logger.debug("Refusing to design this network"); + return null; + } + NetworkVO config = (NetworkVO)super.design(offering, plan, + userSpecified, owner); + if (config == null) { + return null; + } - config.setBroadcastDomainType(BroadcastDomainType.Vswitch); + config.setBroadcastDomainType(BroadcastDomainType.Vswitch); - return config; - } + return config; + } - @Override - public Network implement(Network network, NetworkOffering offering, - DeployDestination dest, ReservationContext context) - throws InsufficientVirtualNetworkCapcityException { - assert (network.getState() == State.Implementing) : "Why are we implementing " - + network; + @Override + public Network implement(Network network, NetworkOffering offering, + DeployDestination dest, ReservationContext context) + throws InsufficientVirtualNetworkCapcityException { + assert (network.getState() == State.Implementing) : "Why are we implementing " + + network; - long dcId = dest.getDataCenter().getId(); - NetworkType nwType = dest.getDataCenter().getNetworkType(); - // get physical network id - Long physicalNetworkId = network.getPhysicalNetworkId(); - // physical network id can be null in Guest Network in Basic zone, so - // locate the physical network - if (physicalNetworkId == null) { - physicalNetworkId = _networkModel.findPhysicalNetworkId(dcId, - offering.getTags(), offering.getTrafficType()); - } - PhysicalNetworkVO physnet = _physicalNetworkDao - .findById(physicalNetworkId); + long dcId = dest.getDataCenter().getId(); + NetworkType nwType = dest.getDataCenter().getNetworkType(); + // get physical network id + Long physicalNetworkId = network.getPhysicalNetworkId(); + // physical network id can be null in Guest Network in Basic zone, so + // locate the physical network + if (physicalNetworkId == null) { + physicalNetworkId = _networkModel.findPhysicalNetworkId(dcId, + offering.getTags(), offering.getTrafficType()); + } + PhysicalNetworkVO physnet = _physicalNetworkDao + .findById(physicalNetworkId); - if (!canHandle(offering, nwType, physnet)) { - s_logger.debug("Refusing to design this network"); - return null; - } - NetworkVO implemented = (NetworkVO) super.implement(network, offering, - dest, context); + if (!canHandle(offering, nwType, physnet)) { + s_logger.debug("Refusing to design this network"); + return null; + } + NetworkVO implemented = (NetworkVO)super.implement(network, offering, + dest, context); - if (network.getGateway() != null) { - implemented.setGateway(network.getGateway()); - } + if (network.getGateway() != null) { + implemented.setGateway(network.getGateway()); + } - if (network.getCidr() != null) { - implemented.setCidr(network.getCidr()); - } - String name = network.getName(); - if (name == null || name.isEmpty()) { - name = ((NetworkVO) network).getUuid(); - } + if (network.getCidr() != null) { + implemented.setCidr(network.getCidr()); + } + String name = network.getName(); + if (name == null || name.isEmpty()) { + name = ((NetworkVO)network).getUuid(); + } - // do we need to create switch right now? + // do we need to create switch right now? - implemented.setBroadcastDomainType(BroadcastDomainType.Vswitch); + implemented.setBroadcastDomainType(BroadcastDomainType.Vswitch); - return implemented; - } + return implemented; + } - @Override - public void reserve(NicProfile nic, Network network, - VirtualMachineProfile vm, - DeployDestination dest, ReservationContext context) - throws InsufficientVirtualNetworkCapcityException, - InsufficientAddressCapacityException { - // TODO Auto-generated method stub - super.reserve(nic, network, vm, dest, context); - } + @Override + public void reserve(NicProfile nic, Network network, + VirtualMachineProfile vm, + DeployDestination dest, ReservationContext context) + throws InsufficientVirtualNetworkCapcityException, + InsufficientAddressCapacityException { + // TODO Auto-generated method stub + super.reserve(nic, network, vm, dest, context); + } - @Override - public boolean release(NicProfile nic, - VirtualMachineProfile vm, - String reservationId) { - // TODO Auto-generated method stub - return super.release(nic, vm, reservationId); - } + @Override + public boolean release(NicProfile nic, + VirtualMachineProfile vm, + String reservationId) { + // TODO Auto-generated method stub + return super.release(nic, vm, reservationId); + } - @Override - public void shutdown(NetworkProfile profile, NetworkOffering offering) { - NetworkVO networkObject = _networkDao.findById(profile.getId()); - if (networkObject.getBroadcastDomainType() != BroadcastDomainType.Vswitch - || networkObject.getBroadcastUri() == null) { - s_logger.warn("BroadcastUri is empty or incorrect for guestnetwork " - + networkObject.getDisplayText()); - return; - } + @Override + public void shutdown(NetworkProfile profile, NetworkOffering offering) { + NetworkVO networkObject = _networkDao.findById(profile.getId()); + if (networkObject.getBroadcastDomainType() != BroadcastDomainType.Vswitch + || networkObject.getBroadcastUri() == null) { + s_logger.warn("BroadcastUri is empty or incorrect for guestnetwork " + + networkObject.getDisplayText()); + return; + } - super.shutdown(profile, offering); - } + super.shutdown(profile, offering); + } - @Override - public boolean trash(Network network, NetworkOffering offering) { - return super.trash(network, offering); - } + @Override + public boolean trash(Network network, NetworkOffering offering) { + return super.trash(network, offering); + } - @Override - protected void allocateVnet(Network network, NetworkVO implemented, - long dcId, long physicalNetworkId, String reservationId) - throws InsufficientVirtualNetworkCapcityException { - if (network.getBroadcastUri() == null) { - String vnet = _dcDao.allocateVnet(dcId, physicalNetworkId, - network.getAccountId(), reservationId, - UseSystemGuestVlans.valueIn(network.getAccountId())); - if (vnet == null) { - throw new InsufficientVirtualNetworkCapcityException( - "Unable to allocate vnet as a part of network " - + network + " implement ", DataCenter.class, - dcId); - } - implemented - .setBroadcastUri(BroadcastDomainType.Vswitch.toUri(vnet)); - ActionEventUtils.onCompletedActionEvent( - CallContext.current().getCallingUserId(), - network.getAccountId(), - EventVO.LEVEL_INFO, - EventTypes.EVENT_ZONE_VLAN_ASSIGN, - "Assigned Zone Vlan: " + vnet + " Network Id: " - + network.getId(), 0); - } else { - implemented.setBroadcastUri(network.getBroadcastUri()); - } - } + @Override + protected void allocateVnet(Network network, NetworkVO implemented, + long dcId, long physicalNetworkId, String reservationId) + throws InsufficientVirtualNetworkCapcityException { + if (network.getBroadcastUri() == null) { + String vnet = _dcDao.allocateVnet(dcId, physicalNetworkId, + network.getAccountId(), reservationId, + UseSystemGuestVlans.valueIn(network.getAccountId())); + if (vnet == null) { + throw new InsufficientVirtualNetworkCapcityException( + "Unable to allocate vnet as a part of network " + + network + " implement ", DataCenter.class, + dcId); + } + implemented + .setBroadcastUri(BroadcastDomainType.Vswitch.toUri(vnet)); + ActionEventUtils.onCompletedActionEvent( + CallContext.current().getCallingUserId(), + network.getAccountId(), + EventVO.LEVEL_INFO, + EventTypes.EVENT_ZONE_VLAN_ASSIGN, + "Assigned Zone Vlan: " + vnet + " Network Id: " + + network.getId(), 0); + } else { + implemented.setBroadcastUri(network.getBroadcastUri()); + } + } } diff --git a/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsTunnelManagerImpl.java b/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsTunnelManagerImpl.java index 553d645bd0d..aa0f42e617e 100644 --- a/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsTunnelManagerImpl.java +++ b/plugins/network-elements/ovs/src/com/cloud/network/ovs/OvsTunnelManagerImpl.java @@ -29,6 +29,7 @@ import javax.persistence.EntityExistsException; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; + import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import com.cloud.agent.AgentManager; @@ -78,74 +79,74 @@ import com.cloud.vm.dao.UserVmDao; public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManager { public static final Logger s_logger = Logger.getLogger(OvsTunnelManagerImpl.class.getName()); - // boolean _isEnabled; - ScheduledExecutorService _executorPool; - ScheduledExecutorService _cleanupExecutor; + // boolean _isEnabled; + ScheduledExecutorService _executorPool; + ScheduledExecutorService _cleanupExecutor; - @Inject - ConfigurationDao _configDao; - @Inject - NicDao _nicDao; - @Inject - HostDao _hostDao; - @Inject - PhysicalNetworkTrafficTypeDao _physNetTTDao; - @Inject - UserVmDao _userVmDao; - @Inject - DomainRouterDao _routerDao; - @Inject - OvsTunnelNetworkDao _tunnelNetworkDao; - @Inject - OvsTunnelInterfaceDao _tunnelInterfaceDao; - @Inject - AgentManager _agentMgr; + @Inject + ConfigurationDao _configDao; + @Inject + NicDao _nicDao; + @Inject + HostDao _hostDao; + @Inject + PhysicalNetworkTrafficTypeDao _physNetTTDao; + @Inject + UserVmDao _userVmDao; + @Inject + DomainRouterDao _routerDao; + @Inject + OvsTunnelNetworkDao _tunnelNetworkDao; + @Inject + OvsTunnelInterfaceDao _tunnelInterfaceDao; + @Inject + AgentManager _agentMgr; - @Override - public boolean configure(String name, Map params) - throws ConfigurationException { + @Override + public boolean configure(String name, Map params) + throws ConfigurationException { _executorPool = Executors.newScheduledThreadPool(10, new NamedThreadFactory("OVS")); _cleanupExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("OVS-Cleanup")); return true; } - @DB - protected OvsTunnelInterfaceVO createInterfaceRecord(String ip, - String netmask, String mac, long hostId, String label) { - OvsTunnelInterfaceVO ti = null; - try { - ti = new OvsTunnelInterfaceVO(ip, netmask, mac, hostId, label); - // TODO: Is locking really necessary here? - OvsTunnelInterfaceVO lock = _tunnelInterfaceDao - .acquireInLockTable(Long.valueOf(1)); - if (lock == null) { - s_logger.warn("Cannot lock table ovs_tunnel_account"); - return null; - } - _tunnelInterfaceDao.persist(ti); - _tunnelInterfaceDao.releaseFromLockTable(lock.getId()); - } catch (EntityExistsException e) { - s_logger.debug("A record for the interface for network " + label - + " on host id " + hostId + " already exists"); - } - return ti; - } + @DB + protected OvsTunnelInterfaceVO createInterfaceRecord(String ip, + String netmask, String mac, long hostId, String label) { + OvsTunnelInterfaceVO ti = null; + try { + ti = new OvsTunnelInterfaceVO(ip, netmask, mac, hostId, label); + // TODO: Is locking really necessary here? + OvsTunnelInterfaceVO lock = _tunnelInterfaceDao + .acquireInLockTable(Long.valueOf(1)); + if (lock == null) { + s_logger.warn("Cannot lock table ovs_tunnel_account"); + return null; + } + _tunnelInterfaceDao.persist(ti); + _tunnelInterfaceDao.releaseFromLockTable(lock.getId()); + } catch (EntityExistsException e) { + s_logger.debug("A record for the interface for network " + label + + " on host id " + hostId + " already exists"); + } + return ti; + } - private String handleFetchInterfaceAnswer(Answer[] answers, Long hostId) { - OvsFetchInterfaceAnswer ans = (OvsFetchInterfaceAnswer) answers[0]; - if (ans.getResult()) { - if (ans.getIp() != null && !("".equals(ans.getIp()))) { - OvsTunnelInterfaceVO ti = createInterfaceRecord(ans.getIp(), - ans.getNetmask(), ans.getMac(), hostId, ans.getLabel()); - return ti.getIp(); - } - } - // Fetch interface failed! - s_logger.warn("Unable to fetch the IP address for the GRE tunnel endpoint" - + ans.getDetails()); - return null; - } + private String handleFetchInterfaceAnswer(Answer[] answers, Long hostId) { + OvsFetchInterfaceAnswer ans = (OvsFetchInterfaceAnswer)answers[0]; + if (ans.getResult()) { + if (ans.getIp() != null && !("".equals(ans.getIp()))) { + OvsTunnelInterfaceVO ti = createInterfaceRecord(ans.getIp(), + ans.getNetmask(), ans.getMac(), hostId, ans.getLabel()); + return ti.getIp(); + } + } + // Fetch interface failed! + s_logger.warn("Unable to fetch the IP address for the GRE tunnel endpoint" + + ans.getDetails()); + return null; + } @DB protected OvsTunnelNetworkVO createTunnelRecord(long from, long to, long networkId, int key) { @@ -165,7 +166,6 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage return ta; } - private void handleCreateTunnelAnswer(Answer[] answers) { OvsCreateTunnelAnswer r = (OvsCreateTunnelAnswer)answers[0]; String s = @@ -177,66 +177,66 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage OvsTunnelNetworkVO tunnel = _tunnelNetworkDao.getByFromToNetwork(from, to, networkId); if (tunnel == null) { throw new CloudRuntimeException( - String.format("Unable find tunnelNetwork record" + - "(from=%1$s,to=%2$s, account=%3$s", - from, to, networkId)); - } - if (!r.getResult()) { - tunnel.setState("FAILED"); - s_logger.warn("Create GRE tunnel failed due to " + r.getDetails() - + s); - } else { - tunnel.setState("SUCCESS"); - tunnel.setPortName(r.getInPortName()); - s_logger.warn("Create GRE tunnel " + r.getDetails() + s); - } - _tunnelNetworkDao.update(tunnel.getId(), tunnel); - } + String.format("Unable find tunnelNetwork record" + + "(from=%1$s,to=%2$s, account=%3$s", + from, to, networkId)); + } + if (!r.getResult()) { + tunnel.setState("FAILED"); + s_logger.warn("Create GRE tunnel failed due to " + r.getDetails() + + s); + } else { + tunnel.setState("SUCCESS"); + tunnel.setPortName(r.getInPortName()); + s_logger.warn("Create GRE tunnel " + r.getDetails() + s); + } + _tunnelNetworkDao.update(tunnel.getId(), tunnel); + } - private String getGreEndpointIP(Host host, Network nw) - throws AgentUnavailableException, OperationTimedoutException { - String endpointIp = null; - // Fetch fefault name for network label from configuration - String physNetLabel = _configDao.getValue(Config.OvsTunnelNetworkDefaultLabel.key()); + private String getGreEndpointIP(Host host, Network nw) + throws AgentUnavailableException, OperationTimedoutException { + String endpointIp = null; + // Fetch fefault name for network label from configuration + String physNetLabel = _configDao.getValue(Config.OvsTunnelNetworkDefaultLabel.key()); Long physNetId = nw.getPhysicalNetworkId(); PhysicalNetworkTrafficType physNetTT = - _physNetTTDao.findBy(physNetId, TrafficType.Guest); + _physNetTTDao.findBy(physNetId, TrafficType.Guest); HypervisorType hvType = host.getHypervisorType(); String label = null; switch (hvType) { - case XenServer: - label = physNetTT.getXenNetworkLabel(); - if ((label!=null) && (!label.equals(""))) { - physNetLabel = label; - } - break; - case KVM: - label = physNetTT.getKvmNetworkLabel(); - if ((label != null) && (!label.equals(""))) { - physNetLabel = label; - } - break; - default: - throw new CloudRuntimeException("Hypervisor " + - hvType.toString() + - " unsupported by OVS Tunnel Manager"); + case XenServer: + label = physNetTT.getXenNetworkLabel(); + if ((label != null) && (!label.equals(""))) { + physNetLabel = label; + } + break; + case KVM: + label = physNetTT.getKvmNetworkLabel(); + if ((label != null) && (!label.equals(""))) { + physNetLabel = label; + } + break; + default: + throw new CloudRuntimeException("Hypervisor " + + hvType.toString() + + " unsupported by OVS Tunnel Manager"); } // Try to fetch GRE endpoint IP address for cloud db // If not found, then find it on the hypervisor OvsTunnelInterfaceVO tunnelIface = - _tunnelInterfaceDao.getByHostAndLabel(host.getId(), - physNetLabel); + _tunnelInterfaceDao.getByHostAndLabel(host.getId(), + physNetLabel); if (tunnelIface == null) { //Now find and fetch configuration for physical interface - //for network with label on target host - Commands fetchIfaceCmds = - new Commands(new OvsFetchInterfaceCommand(physNetLabel)); - s_logger.debug("Ask host " + host.getId() + - " to retrieve interface for phy net with label:" + - physNetLabel); - Answer[] fetchIfaceAnswers = _agentMgr.send(host.getId(), fetchIfaceCmds); + //for network with label on target host + Commands fetchIfaceCmds = + new Commands(new OvsFetchInterfaceCommand(physNetLabel)); + s_logger.debug("Ask host " + host.getId() + + " to retrieve interface for phy net with label:" + + physNetLabel); + Answer[] fetchIfaceAnswers = _agentMgr.send(host.getId(), fetchIfaceCmds); //And finally save it for future use endpointIp = handleFetchInterfaceAnswer(fetchIfaceAnswers, host.getId()); } else { @@ -245,56 +245,56 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage return endpointIp; } - private int getGreKey(Network network) { - int key = 0; - try { - //The GRE key is actually in the host part of the URI + private int getGreKey(Network network) { + int key = 0; + try { + //The GRE key is actually in the host part of the URI // this is not true for lswitch/NiciraNvp! String keyStr = BroadcastDomainType.getValue(network.getBroadcastUri()); // The key is most certainly and int if network is a vlan. // !! not in the case of lswitch/pvlan/(possibly)vswitch // So we now feel quite safe in converting it into a string // by calling the appropriate BroadcastDomainType method - key = Integer.valueOf(keyStr); - return key; - } catch (NumberFormatException e) { - s_logger.debug("Well well, how did '" + key - + "' end up in the broadcast URI for the network?"); - throw new CloudRuntimeException(String.format( - "Invalid GRE key parsed from" - + "network broadcast URI (%s)", network - .getBroadcastUri().toString())); - } - } + key = Integer.valueOf(keyStr); + return key; + } catch (NumberFormatException e) { + s_logger.debug("Well well, how did '" + key + + "' end up in the broadcast URI for the network?"); + throw new CloudRuntimeException(String.format( + "Invalid GRE key parsed from" + + "network broadcast URI (%s)", network + .getBroadcastUri().toString())); + } + } - @DB + @DB protected void CheckAndCreateTunnel(VirtualMachine instance, Network nw, DeployDestination dest) { - s_logger.debug("Creating tunnels with OVS tunnel manager"); - if (instance.getType() != VirtualMachine.Type.User - && instance.getType() != VirtualMachine.Type.DomainRouter) { - s_logger.debug("Will not work if you're not" - + "an instance or a virtual router"); - return; - } + s_logger.debug("Creating tunnels with OVS tunnel manager"); + if (instance.getType() != VirtualMachine.Type.User + && instance.getType() != VirtualMachine.Type.DomainRouter) { + s_logger.debug("Will not work if you're not" + + "an instance or a virtual router"); + return; + } - long hostId = dest.getHost().getId(); - int key = getGreKey(nw); - // Find active VMs with a NIC on the target network - List vms = _userVmDao.listByNetworkIdAndStates(nw.getId(), - State.Running, State.Starting, State.Stopping, State.Unknown, - State.Migrating); - // Find routers for the network - List routers = _routerDao.findByNetwork(nw.getId()); - List ins = new ArrayList(); - if (vms != null) { - ins.addAll(vms); - } - if (routers.size() != 0) { - ins.addAll(routers); - } - List toHostIds = new ArrayList(); - List fromHostIds = new ArrayList(); + long hostId = dest.getHost().getId(); + int key = getGreKey(nw); + // Find active VMs with a NIC on the target network + List vms = _userVmDao.listByNetworkIdAndStates(nw.getId(), + State.Running, State.Starting, State.Stopping, State.Unknown, + State.Migrating); + // Find routers for the network + List routers = _routerDao.findByNetwork(nw.getId()); + List ins = new ArrayList(); + if (vms != null) { + ins.addAll(vms); + } + if (routers.size() != 0) { + ins.addAll(routers); + } + List toHostIds = new ArrayList(); + List fromHostIds = new ArrayList(); for (VMInstanceVO v : ins) { Long rh = v.getHostId(); if (rh == null || rh.longValue() == hostId) { @@ -305,7 +305,7 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage if (ta == null || ta.getState().equals("FAILED")) { s_logger.debug("Attempting to create tunnel from:" + hostId + " to:" + rh.longValue()); if (ta == null) { - this.createTunnelRecord(hostId, rh.longValue(), nw.getId(), key); + createTunnelRecord(hostId, rh.longValue(), nw.getId(), key); } if (!toHostIds.contains(rh)) { toHostIds.add(rh); @@ -313,15 +313,15 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage } ta = _tunnelNetworkDao.getByFromToNetwork(rh.longValue(), - hostId, nw.getId()); + hostId, nw.getId()); // Try and create the tunnel even if a previous attempt failed if (ta == null || ta.getState().equals("FAILED")) { - s_logger.debug("Attempting to create tunnel from:" + - rh.longValue() + " to:" + hostId); - if (ta == null) { - this.createTunnelRecord(rh.longValue(), hostId, - nw.getId(), key); - } + s_logger.debug("Attempting to create tunnel from:" + + rh.longValue() + " to:" + hostId); + if (ta == null) { + createTunnelRecord(rh.longValue(), hostId, + nw.getId(), key); + } if (!fromHostIds.contains(rh)) { fromHostIds.add(rh); } @@ -333,89 +333,88 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage if (myIp == null) throw new GreTunnelException("Unable to retrieve the source " + "endpoint for the GRE tunnel." + "Failure is on host:" + dest.getHost().getId()); boolean noHost = true; - for (Long i : toHostIds) { - HostVO rHost = _hostDao.findById(i); - String otherIp = getGreEndpointIP(rHost, nw); - if (otherIp == null) - throw new GreTunnelException( - "Unable to retrieve the remote " - + "endpoint for the GRE tunnel." - + "Failure is on host:" + rHost.getId()); - Commands cmds = new Commands( - new OvsCreateTunnelCommand(otherIp, key, - Long.valueOf(hostId), i, nw.getId(), myIp)); - s_logger.debug("Ask host " + hostId - + " to create gre tunnel to " + i); - Answer[] answers = _agentMgr.send(hostId, cmds); - handleCreateTunnelAnswer(answers); - noHost = false; - } + for (Long i : toHostIds) { + HostVO rHost = _hostDao.findById(i); + String otherIp = getGreEndpointIP(rHost, nw); + if (otherIp == null) + throw new GreTunnelException( + "Unable to retrieve the remote " + + "endpoint for the GRE tunnel." + + "Failure is on host:" + rHost.getId()); + Commands cmds = new Commands( + new OvsCreateTunnelCommand(otherIp, key, + Long.valueOf(hostId), i, nw.getId(), myIp)); + s_logger.debug("Ask host " + hostId + + " to create gre tunnel to " + i); + Answer[] answers = _agentMgr.send(hostId, cmds); + handleCreateTunnelAnswer(answers); + noHost = false; + } - for (Long i : fromHostIds) { - HostVO rHost = _hostDao.findById(i); - String otherIp = getGreEndpointIP(rHost, nw); - Commands cmds = new Commands(new OvsCreateTunnelCommand(myIp, - key, i, Long.valueOf(hostId), nw.getId(), otherIp)); - s_logger.debug("Ask host " + i + " to create gre tunnel to " - + hostId); - Answer[] answers = _agentMgr.send(i, cmds); - handleCreateTunnelAnswer(answers); - noHost = false; - } - // If no tunnels have been configured, perform the bridge setup - // anyway - // This will ensure VIF rules will be triggered - if (noHost) { - Commands cmds = new Commands(new OvsSetupBridgeCommand(key, - hostId, nw.getId())); - s_logger.debug("Ask host " + hostId - + " to configure bridge for network:" + nw.getId()); - Answer[] answers = _agentMgr.send(hostId, cmds); - handleSetupBridgeAnswer(answers); - } - } catch (Exception e) { - // I really thing we should do a better handling of these exceptions - s_logger.warn("Ovs Tunnel network created tunnel failed", e); - } - } + for (Long i : fromHostIds) { + HostVO rHost = _hostDao.findById(i); + String otherIp = getGreEndpointIP(rHost, nw); + Commands cmds = new Commands(new OvsCreateTunnelCommand(myIp, + key, i, Long.valueOf(hostId), nw.getId(), otherIp)); + s_logger.debug("Ask host " + i + " to create gre tunnel to " + + hostId); + Answer[] answers = _agentMgr.send(i, cmds); + handleCreateTunnelAnswer(answers); + noHost = false; + } + // If no tunnels have been configured, perform the bridge setup + // anyway + // This will ensure VIF rules will be triggered + if (noHost) { + Commands cmds = new Commands(new OvsSetupBridgeCommand(key, + hostId, nw.getId())); + s_logger.debug("Ask host " + hostId + + " to configure bridge for network:" + nw.getId()); + Answer[] answers = _agentMgr.send(hostId, cmds); + handleSetupBridgeAnswer(answers); + } + } catch (Exception e) { + // I really thing we should do a better handling of these exceptions + s_logger.warn("Ovs Tunnel network created tunnel failed", e); + } + } - @Override - public boolean isOvsTunnelEnabled() { - return true; - } + @Override + public boolean isOvsTunnelEnabled() { + return true; + } @Override public void VmCheckAndCreateTunnel(VirtualMachineProfile vm, - Network nw, DeployDestination dest) { + Network nw, DeployDestination dest) { CheckAndCreateTunnel(vm.getVirtualMachine(), nw, dest); } @DB - private void handleDestroyTunnelAnswer(Answer ans, long from, long to, long network_id) { + private void handleDestroyTunnelAnswer(Answer ans, long from, long to, long networkId) { if (ans.getResult()) { OvsTunnelNetworkVO lock = _tunnelNetworkDao.acquireInLockTable(Long.valueOf(1)); if (lock == null) { s_logger.warn(String.format("failed to lock" + - "ovs_tunnel_account, remove record of " + - "tunnel(from=%1$s, to=%2$s account=%3$s) failed", - from, to, network_id)); + "ovs_tunnel_account, remove record of " + + "tunnel(from=%1$s, to=%2$s account=%3$s) failed", + from, to, networkId)); return; } - _tunnelNetworkDao.removeByFromToNetwork(from, to, network_id); + _tunnelNetworkDao.removeByFromToNetwork(from, to, networkId); _tunnelNetworkDao.releaseFromLockTable(lock.getId()); s_logger.debug(String.format("Destroy tunnel(account:%1$s," + - "from:%2$s, to:%3$s) successful", - network_id, from, to)); + "from:%2$s, to:%3$s) successful", + networkId, from, to)); } else { - s_logger.debug(String.format("Destroy tunnel(account:%1$s," + "from:%2$s, to:%3$s) failed", network_id, from, to)); + s_logger.debug(String.format("Destroy tunnel(account:%1$s," + "from:%2$s, to:%3$s) failed", networkId, from, to)); } } @DB - private void handleDestroyBridgeAnswer(Answer ans, - long host_id, long network_id) { + private void handleDestroyBridgeAnswer(Answer ans, long hostId, long networkId) { if (ans.getResult()) { OvsTunnelNetworkVO lock = _tunnelNetworkDao.acquireInLockTable(Long.valueOf(1)); @@ -424,14 +423,14 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage return; } - _tunnelNetworkDao.removeByFromNetwork(host_id, network_id); + _tunnelNetworkDao.removeByFromNetwork(hostId, networkId); _tunnelNetworkDao.releaseFromLockTable(lock.getId()); s_logger.debug(String.format("Destroy bridge for" + - "network %1$s successful", network_id)); + "network %1$s successful", networkId)); } else { - s_logger.debug(String.format("Destroy bridge for" + - "network %1$s failed", network_id)); + s_logger.debug(String.format("Destroy bridge for" + + "network %1$s failed", networkId)); } } @@ -442,9 +441,9 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage @Override public void CheckAndDestroyTunnel(VirtualMachine vm, Network nw) { - // if (!_isEnabled) { - // return; - // } + // if (!_isEnabled) { + // return; + // } List userVms = _userVmDao.listByAccountIdAndHostId(vm.getAccountId(), vm.getHostId()); if (vm.getType() == VirtualMachine.Type.User) { @@ -472,19 +471,19 @@ public class OvsTunnelManagerImpl extends ManagerBase implements OvsTunnelManage /* Then ask hosts have peer tunnel with me to destroy them */ List peers = - _tunnelNetworkDao.listByToNetwork(vm.getHostId(), - nw.getId()); + _tunnelNetworkDao.listByToNetwork(vm.getHostId(), + nw.getId()); for (OvsTunnelNetworkVO p : peers) { - // If the tunnel was not successfully created don't bother to remove it - if (p.getState().equals("SUCCESS")) { - cmd = new OvsDestroyTunnelCommand(p.getNetworkId(), key, - p.getPortName()); - s_logger.debug("Destroying tunnel to " + vm.getHostId() + - " from " + p.getFrom()); - ans = _agentMgr.send(p.getFrom(), cmd); - handleDestroyTunnelAnswer(ans, p.getFrom(), - p.getTo(), p.getNetworkId()); - } + // If the tunnel was not successfully created don't bother to remove it + if (p.getState().equals("SUCCESS")) { + cmd = new OvsDestroyTunnelCommand(p.getNetworkId(), key, + p.getPortName()); + s_logger.debug("Destroying tunnel to " + vm.getHostId() + + " from " + p.getFrom()); + ans = _agentMgr.send(p.getFrom(), cmd); + handleDestroyTunnelAnswer(ans, p.getFrom(), + p.getTo(), p.getNetworkId()); + } } } catch (Exception e) { s_logger.warn(String.format("Destroy tunnel(account:%1$s," + "hostId:%2$s) failed", vm.getAccountId(), vm.getHostId()), e); diff --git a/plugins/network-elements/palo-alto/src/com/cloud/network/element/PaloAltoExternalFirewallElement.java b/plugins/network-elements/palo-alto/src/com/cloud/network/element/PaloAltoExternalFirewallElement.java index be9a0b880fe..cfb64b8bde4 100644 --- a/plugins/network-elements/palo-alto/src/com/cloud/network/element/PaloAltoExternalFirewallElement.java +++ b/plugins/network-elements/palo-alto/src/com/cloud/network/element/PaloAltoExternalFirewallElement.java @@ -27,7 +27,6 @@ import javax.inject.Inject; import org.apache.log4j.Logger; -import org.apache.cloudstack.api.response.ExternalFirewallResponse; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice; @@ -42,7 +41,6 @@ import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationManager; import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter.NetworkType; -import com.cloud.dc.DataCenterVO; import com.cloud.dc.dao.DataCenterDao; import com.cloud.deploy.DeployDestination; import com.cloud.exception.ConcurrentOperationException; @@ -51,7 +49,6 @@ import com.cloud.exception.InsufficientNetworkCapacityException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.host.Host; -import com.cloud.host.HostVO; import com.cloud.host.dao.HostDao; import com.cloud.host.dao.HostDetailsDao; import com.cloud.network.ExternalFirewallDeviceManagerImpl; diff --git a/plugins/network-elements/palo-alto/src/com/cloud/network/element/PaloAltoFirewallElementService.java b/plugins/network-elements/palo-alto/src/com/cloud/network/element/PaloAltoFirewallElementService.java index 12f04077215..d30baca4804 100644 --- a/plugins/network-elements/palo-alto/src/com/cloud/network/element/PaloAltoFirewallElementService.java +++ b/plugins/network-elements/palo-alto/src/com/cloud/network/element/PaloAltoFirewallElementService.java @@ -18,15 +18,12 @@ package com.cloud.network.element; import java.util.List; -import org.apache.cloudstack.api.response.ExternalFirewallResponse; - import com.cloud.api.commands.AddPaloAltoFirewallCmd; import com.cloud.api.commands.ConfigurePaloAltoFirewallCmd; import com.cloud.api.commands.DeletePaloAltoFirewallCmd; import com.cloud.api.commands.ListPaloAltoFirewallNetworksCmd; import com.cloud.api.commands.ListPaloAltoFirewallsCmd; import com.cloud.api.response.PaloAltoFirewallResponse; -import com.cloud.host.Host; import com.cloud.network.Network; import com.cloud.network.dao.ExternalFirewallDeviceVO; import com.cloud.utils.component.PluggableService; diff --git a/plugins/network-elements/palo-alto/src/com/cloud/network/resource/PaloAltoResource.java b/plugins/network-elements/palo-alto/src/com/cloud/network/resource/PaloAltoResource.java index 1b05a116f33..2952b931d42 100644 --- a/plugins/network-elements/palo-alto/src/com/cloud/network/resource/PaloAltoResource.java +++ b/plugins/network-elements/palo-alto/src/com/cloud/network/resource/PaloAltoResource.java @@ -29,11 +29,11 @@ import java.util.Map; import javax.naming.ConfigurationException; import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.transform.dom.DOMSource; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; // for prettyFormat() import javax.xml.transform.stream.StreamSource; @@ -111,10 +111,10 @@ public class PaloAltoResource implements ServerResource { private String _threatProfile; private String _logProfile; private String _pingManagementProfile; - private final Logger s_logger = Logger.getLogger(PaloAltoResource.class); + private static final Logger s_logger = Logger.getLogger(PaloAltoResource.class); - private static String _apiUri = "/api"; - private static HttpClient _httpclient; + private static String s_apiUri = "/api"; + private static HttpClient s_httpclient; protected enum PaloAltoMethod { GET, POST; @@ -127,7 +127,7 @@ public class PaloAltoResource implements ServerResource { private enum InterfaceType { AGGREGATE("aggregate-ethernet"), ETHERNET("ethernet"); - private String type; + private final String type; private InterfaceType(String type) { this.type = type; @@ -142,7 +142,7 @@ public class PaloAltoResource implements ServerResource { private enum Protocol { TCP("tcp"), UDP("udp"), ICMP("icmp"), ALL("all"); - private String protocol; + private final String protocol; private Protocol(String protocol) { this.protocol = protocol; @@ -365,14 +365,14 @@ public class PaloAltoResource implements ServerResource { * Login */ private void openHttpConnection() { - _httpclient = new DefaultHttpClient(); + s_httpclient = new DefaultHttpClient(); // Allows you to connect via SSL using unverified certs - _httpclient = HttpClientWrapper.wrapClient(_httpclient); + s_httpclient = HttpClientWrapper.wrapClient(s_httpclient); } private boolean refreshPaloAltoConnection() { - if (_httpclient == null) { + if (s_httpclient == null) { openHttpConnection(); } @@ -1191,8 +1191,9 @@ public class PaloAltoResource implements ServerResource { private String genFirewallRuleName(long id) { // ingress return "policy_" + Long.toString(id); } + private String genFirewallRuleName(long id, String vlan) { // egress - return "policy_"+Long.toString(id)+"_"+vlan; + return "policy_" + Long.toString(id) + "_" + vlan; } public boolean manageFirewallRule(ArrayList cmdList, PaloAltoPrimative prim, FirewallRuleTO rule) throws ExecutionException { @@ -1311,7 +1312,7 @@ public class PaloAltoResource implements ServerResource { xml += "" + dstAddressXML + ""; xml += "" + appXML + ""; xml += "" + serviceXML + ""; - xml += ""+action+""; + xml += "" + action + ""; xml += "no"; xml += "no"; if (_threatProfile != null && action.equals("allow")) { // add the threat profile if it exists @@ -1328,34 +1329,35 @@ public class PaloAltoResource implements ServerResource { Map e_params = new HashMap(); e_params.put("type", "config"); e_params.put("action", "get"); - e_params.put("xpath", "/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='policy_0_"+rule.getSrcVlanTag()+"']"); + e_params.put("xpath", "/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='policy_0_" + rule.getSrcVlanTag() + "']"); String e_response = request(PaloAltoMethod.GET, e_params); has_default = (validResponse(e_response) && responseNotEmpty(e_response)); - + // there is an existing default rule, so we need to remove it and add it back after the new rule is added. if (has_default) { - s_logger.debug("Moving the default egress rule after the new rule: "+ruleName); + s_logger.debug("Moving the default egress rule after the new rule: " + ruleName); NodeList response_body; Document doc = getDocument(e_response); XPath xpath = XPathFactory.newInstance().newXPath(); try { XPathExpression expr = xpath.compile("/response[@status='success']/result/entry/node()"); - response_body = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); + response_body = (NodeList)expr.evaluate(doc, XPathConstants.NODESET); } catch (XPathExpressionException e) { throw new ExecutionException(e.getCause().getMessage()); } - for (int i=0; i dd_params = new HashMap(); dd_params.put("type", "config"); dd_params.put("action", "delete"); - dd_params.put("xpath", "/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='policy_0_"+rule.getSrcVlanTag()+"']"); + dd_params.put("xpath", "/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='policy_0_" + rule.getSrcVlanTag() + + "']"); cmdList.add(new DefaultPaloAltoCommand(PaloAltoMethod.POST, dd_params)); } } - + // add the new rule... Map a_params = new HashMap(); a_params.put("type", "config"); @@ -1369,10 +1371,10 @@ public class PaloAltoResource implements ServerResource { Map da_params = new HashMap(); da_params.put("type", "config"); da_params.put("action", "set"); - da_params.put("xpath", "/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='policy_0_"+rule.getSrcVlanTag()+"']"); + da_params.put("xpath", "/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='policy_0_" + rule.getSrcVlanTag() + "']"); da_params.put("element", defaultEgressRule); cmdList.add(new DefaultPaloAltoCommand(PaloAltoMethod.POST, da_params)); - s_logger.debug("Completed move of the default egress rule after rule: "+ruleName); + s_logger.debug("Completed move of the default egress rule after rule: " + ruleName); } return true; @@ -1401,7 +1403,8 @@ public class PaloAltoResource implements ServerResource { Map params = new HashMap(); params.put("type", "config"); params.put("action", "get"); - params.put("xpath", "/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[contains(@name, 'policy') and contains(@name, '"+Long.toString(vlan)+"')]"); + params.put("xpath", + "/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[contains(@name, 'policy') and contains(@name, '" + Long.toString(vlan) + "')]"); String response = request(PaloAltoMethod.GET, params); boolean has_orphans = (validResponse(response) && responseNotEmpty(response)); @@ -1409,12 +1412,13 @@ public class PaloAltoResource implements ServerResource { Map d_params = new HashMap(); d_params.put("type", "config"); d_params.put("action", "delete"); - d_params.put("xpath", "/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[contains(@name, 'policy') and contains(@name, '"+Long.toString(vlan)+"')]"); + d_params.put("xpath", + "/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[contains(@name, 'policy') and contains(@name, '" + Long.toString(vlan) + + "')]"); cmdList.add(new DefaultPaloAltoCommand(PaloAltoMethod.POST, d_params)); } } - /* * Usage */ @@ -1664,15 +1668,15 @@ public class PaloAltoResource implements ServerResource { } try { - debug_msg = debug_msg + "GET request: https://" + _ip + _apiUri + URLDecoder.decode(queryString, "UTF-8") + "\n"; + debug_msg = debug_msg + "GET request: https://" + _ip + s_apiUri + URLDecoder.decode(queryString, "UTF-8") + "\n"; } catch (UnsupportedEncodingException e) { - debug_msg = debug_msg + "GET request: https://" + _ip + _apiUri + queryString + "\n"; + debug_msg = debug_msg + "GET request: https://" + _ip + s_apiUri + queryString + "\n"; } - HttpGet get_request = new HttpGet("https://" + _ip + _apiUri + queryString); + HttpGet get_request = new HttpGet("https://" + _ip + s_apiUri + queryString); ResponseHandler responseHandler = new BasicResponseHandler(); try { - responseBody = _httpclient.execute(get_request, responseHandler); + responseBody = s_httpclient.execute(get_request, responseHandler); } catch (IOException e) { throw new ExecutionException(e.getMessage()); } @@ -1688,12 +1692,12 @@ public class PaloAltoResource implements ServerResource { nvps.add(new BasicNameValuePair("key", _key)); } - debug_msg = debug_msg + "POST request: https://" + _ip + _apiUri + "\n"; + debug_msg = debug_msg + "POST request: https://" + _ip + s_apiUri + "\n"; for (NameValuePair nvp : nvps) { debug_msg = debug_msg + "param: " + nvp.getName() + ", " + nvp.getValue() + "\n"; } - HttpPost post_request = new HttpPost("https://" + _ip + _apiUri); + HttpPost post_request = new HttpPost("https://" + _ip + s_apiUri); try { post_request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); } catch (UnsupportedEncodingException e) { @@ -1701,7 +1705,7 @@ public class PaloAltoResource implements ServerResource { } ResponseHandler responseHandler = new BasicResponseHandler(); try { - responseBody = _httpclient.execute(post_request, responseHandler); + responseBody = s_httpclient.execute(post_request, responseHandler); } catch (IOException e) { throw new ExecutionException(e.getMessage()); } @@ -1965,13 +1969,13 @@ public class PaloAltoResource implements ServerResource { } /* Get the type of interface from the PA device. */ - private String getInterfaceType(String interface_name) throws ExecutionException { + private String getInterfaceType(String interfaceName) throws ExecutionException { String[] types = {InterfaceType.ETHERNET.toString(), InterfaceType.AGGREGATE.toString()}; for (String type : types) { Map params = new HashMap(); params.put("type", "config"); params.put("action", "get"); - params.put("xpath", "/config/devices/entry/network/interface/" + type + "/entry[@name='" + interface_name + "']"); + params.put("xpath", "/config/devices/entry/network/interface/" + type + "/entry[@name='" + interfaceName + "']"); String ethernet_response = request(PaloAltoMethod.GET, params); if (validResponse(ethernet_response) && responseNotEmpty(ethernet_response)) { return type; @@ -2081,7 +2085,7 @@ public class PaloAltoResource implements ServerResource { t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); t.transform(new DOMSource(node), new StreamResult(sw)); } catch (Throwable t) { - throw new ExecutionException("XML convert error when modifying PA config: "+t.getMessage()); + throw new ExecutionException("XML convert error when modifying PA config: " + t.getMessage()); } return sw.toString(); } diff --git a/plugins/network-elements/palo-alto/test/com/cloud/network/resource/MockablePaloAltoResource.java b/plugins/network-elements/palo-alto/test/com/cloud/network/resource/MockablePaloAltoResource.java index 44cc65bfcd8..6657ee3170d 100755 --- a/plugins/network-elements/palo-alto/test/com/cloud/network/resource/MockablePaloAltoResource.java +++ b/plugins/network-elements/palo-alto/test/com/cloud/network/resource/MockablePaloAltoResource.java @@ -54,7 +54,31 @@ public class MockablePaloAltoResource extends PaloAltoResource { if (context.containsKey("public_using_ethernet") && context.get("public_using_ethernet").equals("true")) { context.put("public_interface_type", "ethernet"); response = - "no20060064unspecifiedunspecified1800nononounspecifiedno3011noEUI-64nono20060064unspecifiedunspecified1800nononounspecifiedno3011noEUI-64no3033autoautoauto"; + "no" + + + "20060064unspecified" + + + "unspecified1800no" + + + "nonounspecified" + + + "no3011"+ + "noEUI-64no" + + + "" + + + "no200600" + + + "64unspecifiedunspecified" + + + "1800nonono" + + "unspecifiedno30" + + "11noEUI-64" + + "no" + + "3033autoautoauto" + + ""; } else { response = ""; } @@ -164,7 +188,7 @@ public class MockablePaloAltoResource extends PaloAltoResource { // get egress firewall rule | has_egress_fw_rule | policy_0_3954 if (params.get("xpath").equals("/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='policy_0_3954']")) { if (context.containsKey("has_egress_fw_rule") && context.get("has_egress_fw_rule").equals("true")) { - response = + response = "" + "" + "trustuntrust10.3.96.1/20" @@ -191,7 +215,8 @@ public class MockablePaloAltoResource extends PaloAltoResource { } // get default egress rule | policy_0_3954 - if (params.get("xpath").equals("/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[contains(@name, 'policy') and contains(@name, '3954')]")) { + if (params.get("xpath").equals( + "/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[contains(@name, 'policy') and contains(@name, '3954')]")) { response = ""; } diff --git a/plugins/network-elements/palo-alto/test/com/cloud/network/resource/PaloAltoResourceTest.java b/plugins/network-elements/palo-alto/test/com/cloud/network/resource/PaloAltoResourceTest.java index 4ef8ecc338d..931e6ccaed0 100755 --- a/plugins/network-elements/palo-alto/test/com/cloud/network/resource/PaloAltoResourceTest.java +++ b/plugins/network-elements/palo-alto/test/com/cloud/network/resource/PaloAltoResourceTest.java @@ -52,48 +52,48 @@ import com.cloud.utils.exception.ExecutionException; public class PaloAltoResourceTest { // configuration data - private String _test_name = "PaloAltoTestDevice"; - private String _test_zoneId = "TestZone"; - private String _test_ip = "192.168.80.2"; - private String _test_username = "admin"; - private String _test_password = "admin"; - private String _test_publicInterface = "ethernet1/1"; - private String _test_privateInterface = "ethernet1/2"; - private String _test_publicZone = "untrust"; - private String _test_privateZone = "trust"; - private String _test_virtualRouter = "default"; + private String _testName = "PaloAltoTestDevice"; + private String _testZoneId = "TestZone"; + private String _testIp = "192.168.80.2"; + private String _testUsername = "admin"; + private String _testPassword = "admin"; + private String _testPublicInterface = "ethernet1/1"; + private String _testPrivateInterface = "ethernet1/2"; + private String _testPublicZone = "untrust"; + private String _testPrivateZone = "trust"; + private String _testVirtualRouter = "default"; MockablePaloAltoResource _resource; - Map _resource_params; + Map _resourceParams; HashMap _context; @Before public void setUp() { _resource = new MockablePaloAltoResource(); - _resource_params = new HashMap(); // params to be passed to configure() - _resource_params.put("name", _test_name); - _resource_params.put("zoneId", _test_zoneId); - _resource_params.put("ip", _test_ip); - _resource_params.put("username", _test_username); - _resource_params.put("password", _test_password); - _resource_params.put("publicinterface", _test_publicInterface); - _resource_params.put("privateinterface", _test_privateInterface); - _resource_params.put("publicnetwork", _test_publicZone); - _resource_params.put("privatenetwork", _test_privateZone); - _resource_params.put("pavr", _test_virtualRouter); - _resource_params.put("guid", "aaaaa-bbbbb-ccccc"); + _resourceParams = new HashMap(); // params to be passed to configure() + _resourceParams.put("name", _testName); + _resourceParams.put("zoneId", _testZoneId); + _resourceParams.put("ip", _testIp); + _resourceParams.put("username", _testUsername); + _resourceParams.put("password", _testPassword); + _resourceParams.put("publicinterface", _testPublicInterface); + _resourceParams.put("privateinterface", _testPrivateInterface); + _resourceParams.put("publicnetwork", _testPublicZone); + _resourceParams.put("privatenetwork", _testPrivateZone); + _resourceParams.put("pavr", _testVirtualRouter); + _resourceParams.put("guid", "aaaaa-bbbbb-ccccc"); _context = new HashMap(); // global context - _context.put("name", _test_name); - _context.put("zone_id", _test_zoneId); - _context.put("ip", _test_ip); - _context.put("username", _test_username); - _context.put("password", _test_password); - _context.put("public_interface", _test_publicInterface); - _context.put("private_interface", _test_privateInterface); - _context.put("public_zone", _test_publicZone); - _context.put("private_zone", _test_privateZone); - _context.put("pa_vr", _test_virtualRouter); + _context.put("name", _testName); + _context.put("zone_id", _testZoneId); + _context.put("ip", _testIp); + _context.put("username", _testUsername); + _context.put("password", _testPassword); + _context.put("public_interface", _testPublicInterface); + _context.put("private_interface", _testPrivateInterface); + _context.put("public_zone", _testPublicZone); + _context.put("private_zone", _testPrivateZone); + _context.put("pa_vr", _testVirtualRouter); // -- _context.put("public_using_ethernet", "true"); _context.put("private_using_ethernet", "true"); @@ -115,7 +115,7 @@ public class PaloAltoResourceTest { } _context.remove("has_management_profile"); _resource.setMockContext(_context); - _resource.configure("PaloAltoResource", _resource_params); + _resource.configure("PaloAltoResource", _resourceParams); } @Test @@ -124,7 +124,7 @@ public class PaloAltoResourceTest { System.out.println("\nTEST: resourceConfigureWithManagementProfile"); System.out.println("---------------------------------------------------"); } - _resource.configure("PaloAltoResource", _resource_params); + _resource.configure("PaloAltoResource", _resourceParams); } @Test(expected = ConfigurationException.class) @@ -136,7 +136,7 @@ public class PaloAltoResourceTest { _context.put("firewall_has_pending_changes", "true"); _context.remove("has_management_profile"); _resource.setMockContext(_context); - _resource.configure("PaloAltoResource", _resource_params); + _resource.configure("PaloAltoResource", _resourceParams); } @Test(expected = ConfigurationException.class) @@ -148,7 +148,7 @@ public class PaloAltoResourceTest { _context.put("simulate_commit_failure", "true"); _context.remove("has_management_profile"); _resource.setMockContext(_context); - _resource.configure("PaloAltoResource", _resource_params); + _resource.configure("PaloAltoResource", _resourceParams); } @Test @@ -157,7 +157,7 @@ public class PaloAltoResourceTest { System.out.println("\nTEST: testInitialization"); System.out.println("---------------------------------------------------"); } - _resource.configure("PaloAltoResource", _resource_params); + _resource.configure("PaloAltoResource", _resourceParams); StartupCommand[] sc = _resource.initialize(); assertTrue(sc.length == 1); @@ -174,7 +174,7 @@ public class PaloAltoResourceTest { System.out.println("\nTEST: implementGuestNetwork"); System.out.println("---------------------------------------------------"); } - _resource.configure("PaloAltoResource", _resource_params); + _resource.configure("PaloAltoResource", _resourceParams); IpAddressTO ip = new IpAddressTO(Long.valueOf("1"), "192.168.80.102", true, false, true, "untagged", null, null, null, 100, false); IpAddressTO[] ips = new IpAddressTO[1]; @@ -201,7 +201,7 @@ public class PaloAltoResourceTest { _context.put("has_src_nat_rule", "true"); _context.put("has_isolation_fw_rule", "true"); _resource.setMockContext(_context); - _resource.configure("PaloAltoResource", _resource_params); + _resource.configure("PaloAltoResource", _resourceParams); IpAddressTO ip = new IpAddressTO(Long.valueOf("1"), "192.168.80.102", false, false, true, "untagged", null, null, null, 100, false); IpAddressTO[] ips = new IpAddressTO[1]; @@ -227,7 +227,7 @@ public class PaloAltoResourceTest { _context.put("has_isolation_fw_rule", "true"); _context.put("has_service_tcp_80", "true"); _resource.setMockContext(_context); - _resource.configure("PaloAltoResource", _resource_params); + _resource.configure("PaloAltoResource", _resourceParams); long vlanId = 3954; List rules = new ArrayList(); @@ -257,7 +257,7 @@ public class PaloAltoResourceTest { _context.put("has_service_tcp_80", "true"); _context.put("has_ingress_fw_rule", "true"); _resource.setMockContext(_context); - _resource.configure("PaloAltoResource", _resource_params); + _resource.configure("PaloAltoResource", _resourceParams); long vlanId = 3954; List rules = new ArrayList(); @@ -284,7 +284,7 @@ public class PaloAltoResourceTest { _context.put("has_isolation_fw_rule", "true"); _context.put("has_service_tcp_80", "true"); _resource.setMockContext(_context); - _resource.configure("PaloAltoResource", _resource_params); + _resource.configure("PaloAltoResource", _resourceParams); long vlanId = 3954; List rules = new ArrayList(); @@ -315,7 +315,7 @@ public class PaloAltoResourceTest { _context.put("has_service_tcp_80", "true"); _context.put("has_egress_fw_rule", "true"); _resource.setMockContext(_context); - _resource.configure("PaloAltoResource", _resource_params); + _resource.configure("PaloAltoResource", _resourceParams); long vlanId = 3954; List rules = new ArrayList(); @@ -344,7 +344,7 @@ public class PaloAltoResourceTest { _context.put("has_isolation_fw_rule", "true"); _context.put("has_service_tcp_80", "true"); _resource.setMockContext(_context); - _resource.configure("PaloAltoResource", _resource_params); + _resource.configure("PaloAltoResource", _resourceParams); long vlanId = 3954; List rules = new ArrayList(); @@ -372,7 +372,7 @@ public class PaloAltoResourceTest { _context.put("has_service_tcp_80", "true"); _context.put("has_stc_nat_rule", "true"); _resource.setMockContext(_context); - _resource.configure("PaloAltoResource", _resource_params); + _resource.configure("PaloAltoResource", _resourceParams); long vlanId = 3954; List rules = new ArrayList(); @@ -399,7 +399,7 @@ public class PaloAltoResourceTest { _context.put("has_isolation_fw_rule", "true"); _context.put("has_service_tcp_80", "true"); _resource.setMockContext(_context); - _resource.configure("PaloAltoResource", _resource_params); + _resource.configure("PaloAltoResource", _resourceParams); long vlanId = 3954; List rules = new ArrayList(); @@ -427,7 +427,7 @@ public class PaloAltoResourceTest { _context.put("has_service_tcp_80", "true"); _context.put("has_dst_nat_rule", "true"); _resource.setMockContext(_context); - _resource.configure("PaloAltoResource", _resource_params); + _resource.configure("PaloAltoResource", _resourceParams); long vlanId = 3954; List rules = new ArrayList(); diff --git a/plugins/network-elements/stratosphere-ssp/pom.xml b/plugins/network-elements/stratosphere-ssp/pom.xml index 41d0803618c..b04f1f557a4 100644 --- a/plugins/network-elements/stratosphere-ssp/pom.xml +++ b/plugins/network-elements/stratosphere-ssp/pom.xml @@ -20,7 +20,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 cloud-plugin-network-ssp - Apache Cloudstack Plugin - Stratosphere SSP + Apache CloudStack Plugin - Stratosphere SSP http://www.stratosphere.co.jp/ org.apache.cloudstack diff --git a/plugins/network-elements/stratosphere-ssp/resources/META-INF/cloudstack/ssp/spring-ssp-context.xml b/plugins/network-elements/stratosphere-ssp/resources/META-INF/cloudstack/ssp/spring-ssp-context.xml index 528f3e3e38c..7e8fe6c3e6f 100644 --- a/plugins/network-elements/stratosphere-ssp/resources/META-INF/cloudstack/ssp/spring-ssp-context.xml +++ b/plugins/network-elements/stratosphere-ssp/resources/META-INF/cloudstack/ssp/spring-ssp-context.xml @@ -38,5 +38,4 @@ - diff --git a/plugins/network-elements/stratosphere-ssp/src/org/apache/cloudstack/network/element/SspElement.java b/plugins/network-elements/stratosphere-ssp/src/org/apache/cloudstack/network/element/SspElement.java index 50bacf30005..173d6f0de9e 100644 --- a/plugins/network-elements/stratosphere-ssp/src/org/apache/cloudstack/network/element/SspElement.java +++ b/plugins/network-elements/stratosphere-ssp/src/org/apache/cloudstack/network/element/SspElement.java @@ -145,12 +145,12 @@ public class SspElement extends AdapterBase implements ConnectivityProvider, Ssp return provider; } - private List fetchSspClients(Long physicalNetworkId, Long dataCenterId, boolean enabled_only) { + private List fetchSspClients(Long physicalNetworkId, Long dataCenterId, boolean enabledOnly) { ArrayList clients = new ArrayList(); boolean provider_found = false; PhysicalNetworkServiceProviderVO provider = _physicalNetworkServiceProviderDao.findByServiceProvider(physicalNetworkId, s_SSP_NAME); - if (enabled_only) { + if (enabledOnly) { if (provider != null && provider.getState() == State.Enabled) { provider_found = true; } diff --git a/plugins/pom.xml b/plugins/pom.xml index 17dd8af6765..37382de61bf 100755 --- a/plugins/pom.xml +++ b/plugins/pom.xml @@ -32,12 +32,14 @@ deployment-planners/user-concentrated-pod deployment-planners/user-dispersing deployment-planners/implicit-dedication + ha-planners/skip-heurestics host-allocators/random dedicated-resources hypervisors/ovm hypervisors/xen hypervisors/kvm event-bus/rabbitmq + event-bus/inmemory hypervisors/baremetal hypervisors/ucs hypervisors/hyperv @@ -49,6 +51,7 @@ network-elements/bigswitch-vns network-elements/midonet network-elements/stratosphere-ssp + network-elements/opendaylight storage-allocators/random user-authenticators/ldap user-authenticators/md5 @@ -59,6 +62,7 @@ storage/image/swift storage/image/default storage/image/sample + storage/volume/nexenta storage/volume/solidfire storage/volume/default storage/volume/sample diff --git a/plugins/storage/image/default/src/org/apache/cloudstack/storage/datastore/driver/CloudStackImageStoreDriverImpl.java b/plugins/storage/image/default/src/org/apache/cloudstack/storage/datastore/driver/CloudStackImageStoreDriverImpl.java index 1db10e2eb32..d6e1a01b49c 100644 --- a/plugins/storage/image/default/src/org/apache/cloudstack/storage/datastore/driver/CloudStackImageStoreDriverImpl.java +++ b/plugins/storage/image/default/src/org/apache/cloudstack/storage/datastore/driver/CloudStackImageStoreDriverImpl.java @@ -95,7 +95,7 @@ public class CloudStackImageStoreDriverImpl extends BaseImageStoreDriverImpl { } if (_sslCopy) { hostname = ipAddress.replace(".", "-"); - if(_ssvmUrlDomain != null && _ssvmUrlDomain.length() > 0){ + if (_ssvmUrlDomain != null && _ssvmUrlDomain.length() > 0) { hostname = hostname + "." + _ssvmUrlDomain; } else { hostname = hostname + ".realhostip.com"; diff --git a/plugins/storage/image/default/src/org/apache/cloudstack/storage/datastore/lifecycle/CloudStackImageStoreLifeCycleImpl.java b/plugins/storage/image/default/src/org/apache/cloudstack/storage/datastore/lifecycle/CloudStackImageStoreLifeCycleImpl.java index 95c90349a03..7675e946d52 100644 --- a/plugins/storage/image/default/src/org/apache/cloudstack/storage/datastore/lifecycle/CloudStackImageStoreLifeCycleImpl.java +++ b/plugins/storage/image/default/src/org/apache/cloudstack/storage/datastore/lifecycle/CloudStackImageStoreLifeCycleImpl.java @@ -18,6 +18,8 @@ package org.apache.cloudstack.storage.datastore.lifecycle; import java.net.URI; import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -26,7 +28,7 @@ import javax.inject.Inject; import org.apache.log4j.Logger; -import com.ibm.wsdl.util.StringUtils; +import com.cloud.utils.StringUtils; import org.apache.cloudstack.engine.subsystem.api.storage.ClusterScope; import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; @@ -65,8 +67,8 @@ public class CloudStackImageStoreLifeCycleImpl implements ImageStoreLifeCycle { return _discoverers; } - public void setDiscoverers(List _discoverers) { - this._discoverers = _discoverers; + public void setDiscoverers(List discoverers) { + this._discoverers = discoverers; } public CloudStackImageStoreLifeCycleImpl() { @@ -86,7 +88,13 @@ public class CloudStackImageStoreLifeCycleImpl implements ImageStoreLifeCycle { DataStoreRole role = (DataStoreRole)dsInfos.get("role"); Map details = (Map)dsInfos.get("details"); - s_logger.info("Trying to add a new data store at " + StringUtils.cleanString(url) + " to data center " + dcId); + String logString = ""; + if(url.contains("cifs")) { + logString = cleanPassword(url); + } else { + logString = StringUtils.cleanString(url); + } + s_logger.info("Trying to add a new data store at " + logString + " to data center " + dcId); URI uri = null; try { @@ -167,4 +175,22 @@ public class CloudStackImageStoreLifeCycleImpl implements ImageStoreLifeCycle { return imageStoreHelper.convertToStagingStore(store); } + public static String cleanPassword(String logString) { + String cleanLogString = null; + if (logString != null) { + cleanLogString = logString; + String[] temp = logString.split(","); + int i = 0; + if (temp != null) { + while (i < temp.length) { + temp[i] = StringUtils.cleanString(temp[i]); + i++; + } + List stringList = new ArrayList(); + Collections.addAll(stringList, temp); + cleanLogString = StringUtils.join(stringList, ","); + } + } + return cleanLogString; + } } diff --git a/plugins/storage/image/s3/src/org/apache/cloudstack/storage/datastore/lifecycle/S3ImageStoreLifeCycleImpl.java b/plugins/storage/image/s3/src/org/apache/cloudstack/storage/datastore/lifecycle/S3ImageStoreLifeCycleImpl.java index ff0930642a5..718c591b7fb 100644 --- a/plugins/storage/image/s3/src/org/apache/cloudstack/storage/datastore/lifecycle/S3ImageStoreLifeCycleImpl.java +++ b/plugins/storage/image/s3/src/org/apache/cloudstack/storage/datastore/lifecycle/S3ImageStoreLifeCycleImpl.java @@ -60,8 +60,8 @@ public class S3ImageStoreLifeCycleImpl implements ImageStoreLifeCycle { return _discoverers; } - public void setDiscoverers(List _discoverers) { - this._discoverers = _discoverers; + public void setDiscoverers(List discoverers) { + this._discoverers = discoverers; } public S3ImageStoreLifeCycleImpl() { diff --git a/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/driver/CloudStackPrimaryDataStoreDriverImpl.java b/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/driver/CloudStackPrimaryDataStoreDriverImpl.java index e41b437689f..ae217b63595 100644 --- a/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/driver/CloudStackPrimaryDataStoreDriverImpl.java +++ b/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/driver/CloudStackPrimaryDataStoreDriverImpl.java @@ -24,8 +24,6 @@ import java.util.UUID; import javax.inject.Inject; -import org.apache.log4j.Logger; - import org.apache.cloudstack.engine.orchestration.service.VolumeOrchestrationService; import org.apache.cloudstack.engine.subsystem.api.storage.ChapInfo; import org.apache.cloudstack.engine.subsystem.api.storage.CopyCommandResult; @@ -37,6 +35,7 @@ import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint; import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector; import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; +import org.apache.cloudstack.engine.subsystem.api.storage.StorageAction; import org.apache.cloudstack.engine.subsystem.api.storage.TemplateDataFactory; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; import org.apache.cloudstack.framework.async.AsyncCompletionCallback; @@ -51,6 +50,7 @@ import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; import org.apache.cloudstack.storage.to.SnapshotObjectTO; import org.apache.cloudstack.storage.to.TemplateObjectTO; import org.apache.cloudstack.storage.volume.VolumeObject; +import org.apache.log4j.Logger; import com.cloud.agent.api.Answer; import com.cloud.agent.api.storage.ResizeVolumeAnswer; @@ -61,6 +61,7 @@ import com.cloud.agent.api.to.DataTO; import com.cloud.agent.api.to.StorageFilerTO; import com.cloud.configuration.Config; import com.cloud.exception.StorageUnavailableException; +import com.cloud.host.Host; import com.cloud.host.dao.HostDao; import com.cloud.storage.CreateSnapshotPayload; import com.cloud.storage.DataStoreRole; @@ -68,6 +69,7 @@ import com.cloud.storage.ResizeVolumePayload; import com.cloud.storage.Storage; import com.cloud.storage.StorageManager; import com.cloud.storage.StoragePool; +import com.cloud.storage.Volume; import com.cloud.storage.dao.DiskOfferingDao; import com.cloud.storage.dao.SnapshotDao; import com.cloud.storage.dao.VMTemplateDao; @@ -148,6 +150,17 @@ public class CloudStackPrimaryDataStoreDriverImpl implements PrimaryDataStoreDri return null; } + @Override + public boolean connectVolumeToHost(VolumeInfo volumeInfo, Host host, DataStore dataStore) { return false; } + + @Override + public void disconnectVolumeFromHost(VolumeInfo volumeInfo, Host host, DataStore dataStore) {} + + @Override + public long getVolumeSizeIncludingHypervisorSnapshotReserve(Volume volume, StoragePool pool) { + return volume.getSize(); + } + @Override public void createAsync(DataStore dataStore, DataObject data, AsyncCompletionCallback callback) { String errMsg = null; @@ -269,10 +282,11 @@ public class CloudStackPrimaryDataStoreDriverImpl implements PrimaryDataStoreDri } CreateObjectCommand cmd = new CreateObjectCommand(snapshotTO); - EndPoint ep = epSelector.select(snapshot); + EndPoint ep = this.epSelector.select(snapshot, StorageAction.TAKESNAPSHOT); Answer answer = null; - if (ep == null) { - String errMsg = "No remote endpoint to send DeleteCommand, check if host or ssvm is down?"; + + if ( ep == null ){ + String errMsg = "No remote endpoint to send createObjectCommand, check if host or ssvm is down?"; s_logger.error(errMsg); answer = new Answer(cmd, false, errMsg); } else { diff --git a/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/lifecycle/CloudStackPrimaryDataStoreLifeCycleImpl.java b/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/lifecycle/CloudStackPrimaryDataStoreLifeCycleImpl.java index a8108bddd37..7da36b0cf56 100644 --- a/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/lifecycle/CloudStackPrimaryDataStoreLifeCycleImpl.java +++ b/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/lifecycle/CloudStackPrimaryDataStoreLifeCycleImpl.java @@ -464,8 +464,6 @@ public class CloudStackPrimaryDataStoreLifeCycleImpl implements PrimaryDataStore HypervisorType hType = null; if (hostPoolRecords.size() > 0) { hType = getHypervisorType(hostPoolRecords.get(0).getHostId()); - } else { - return false; } // Remove the SR associated with the Xenserver @@ -486,7 +484,7 @@ public class CloudStackPrimaryDataStoreLifeCycleImpl implements PrimaryDataStore } } - if (!deleteFlag) { + if (!hostPoolRecords.isEmpty() && !deleteFlag) { throw new CloudRuntimeException("Failed to delete storage pool on host"); } diff --git a/plugins/storage/volume/nexenta/pom.xml b/plugins/storage/volume/nexenta/pom.xml new file mode 100644 index 00000000000..4db205f35ab --- /dev/null +++ b/plugins/storage/volume/nexenta/pom.xml @@ -0,0 +1,47 @@ + + + 4.0.0 + cloud-plugin-storage-volume-nexenta + Apache CloudStack Plugin - Storage Volume Nexenta Provider + + org.apache.cloudstack + cloudstack-plugins + 4.4.0-SNAPSHOT + ../../../pom.xml + + + + org.apache.cloudstack + cloud-engine-storage-volume + ${project.version} + + + + + + maven-surefire-plugin + + true + + + + integration-test + + test + + + + + + + \ No newline at end of file diff --git a/plugins/storage/volume/nexenta/resources/META-INF.cloudstack.storage-volume-solidfire/module.properties b/plugins/storage/volume/nexenta/resources/META-INF.cloudstack.storage-volume-solidfire/module.properties new file mode 100644 index 00000000000..c2036006f1f --- /dev/null +++ b/plugins/storage/volume/nexenta/resources/META-INF.cloudstack.storage-volume-solidfire/module.properties @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +name=storage-volume-nexenta +parent=storage \ No newline at end of file diff --git a/plugins/storage/volume/nexenta/resources/META-INF.cloudstack.storage-volume-solidfire/spring-storage-volume-nexenta-context.xml b/plugins/storage/volume/nexenta/resources/META-INF.cloudstack.storage-volume-solidfire/spring-storage-volume-nexenta-context.xml new file mode 100644 index 00000000000..6c83c1ac47f --- /dev/null +++ b/plugins/storage/volume/nexenta/resources/META-INF.cloudstack.storage-volume-solidfire/spring-storage-volume-nexenta-context.xml @@ -0,0 +1,32 @@ + + + + + + \ No newline at end of file diff --git a/plugins/storage/volume/nexenta/src/org/apache/cloudstack/storage/datastore/driver/NexentaPrimaryDataStoreDriver.java b/plugins/storage/volume/nexenta/src/org/apache/cloudstack/storage/datastore/driver/NexentaPrimaryDataStoreDriver.java new file mode 100644 index 00000000000..70f4a4f140c --- /dev/null +++ b/plugins/storage/volume/nexenta/src/org/apache/cloudstack/storage/datastore/driver/NexentaPrimaryDataStoreDriver.java @@ -0,0 +1,194 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.cloudstack.storage.datastore.driver; + +import static org.apache.cloudstack.storage.datastore.util.NexentaUtil.NexentaPluginParameters; + +import java.util.Map; + +import javax.inject.Inject; + +import org.apache.cloudstack.engine.subsystem.api.storage.ChapInfo; +import org.apache.cloudstack.engine.subsystem.api.storage.CopyCommandResult; +import org.apache.cloudstack.engine.subsystem.api.storage.CreateCmdResult; +import org.apache.cloudstack.engine.subsystem.api.storage.DataObject; +import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; +import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver; +import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; +import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; +import org.apache.cloudstack.framework.async.AsyncCompletionCallback; +import org.apache.cloudstack.storage.command.CommandResult; +import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; +import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao; +import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; +import org.apache.cloudstack.storage.datastore.util.NexentaStorAppliance; +import org.apache.cloudstack.storage.datastore.util.NexentaStorAppliance.NexentaStorZvol; +import org.apache.cloudstack.storage.datastore.util.NexentaUtil; +import org.apache.log4j.Logger; + +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.to.DataObjectType; +import com.cloud.agent.api.to.DataStoreTO; +import com.cloud.agent.api.to.DataTO; +import com.cloud.host.Host; +import com.cloud.storage.Storage; +import com.cloud.storage.StoragePool; +import com.cloud.storage.Volume; +import com.cloud.storage.VolumeVO; +import com.cloud.storage.dao.VolumeDao; +import com.cloud.user.dao.AccountDao; + +public class NexentaPrimaryDataStoreDriver implements PrimaryDataStoreDriver { + private static final Logger logger = Logger.getLogger(NexentaPrimaryDataStoreDriver.class); + + @Override + public boolean connectVolumeToHost(VolumeInfo volumeInfo, Host host, DataStore dataStore) { + return false; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void disconnectVolumeFromHost(VolumeInfo volumeInfo, Host host, DataStore dataStore) { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public long getVolumeSizeIncludingHypervisorSnapshotReserve(Volume volume, StoragePool pool) { + return 0; //To change body of implemented methods use File | Settings | File Templates. + } + + @Inject + private VolumeDao _volumeDao; + @Inject + PrimaryDataStoreDao _storagePoolDao; + @Inject + private StoragePoolDetailsDao _storagePoolDetailsDao; + @Inject + private AccountDao _accountDao; + + @Override + public Map getCapabilities() { + return null; + } + + @Override + public ChapInfo getChapInfo(VolumeInfo volumeInfo) { + return null; + } + + @Override + public DataTO getTO(DataObject data) { + return null; + } + + @Override + public DataStoreTO getStoreTO(DataStore store) { + return null; + } + + private NexentaStorAppliance getNexentaStorAppliance(long storagePoolId) { + NexentaPluginParameters parameters = new NexentaPluginParameters(); + + parameters.setNmsUrl(_storagePoolDetailsDao.findDetail(storagePoolId, NexentaUtil.NMS_URL).getValue()); + parameters.setVolume(_storagePoolDetailsDao.findDetail(storagePoolId, NexentaUtil.VOLUME).getValue()); + parameters.setStorageType(_storagePoolDetailsDao.findDetail(storagePoolId, NexentaUtil.STORAGE_TYPE).getValue()); + parameters.setStorageHost(_storagePoolDetailsDao.findDetail(storagePoolId, NexentaUtil.STORAGE_HOST).getValue()); + parameters.setStoragePort(_storagePoolDetailsDao.findDetail(storagePoolId, NexentaUtil.STORAGE_PORT).getValue()); + parameters.setStoragePath(_storagePoolDetailsDao.findDetail(storagePoolId, NexentaUtil.STORAGE_PATH).getValue()); + parameters.setSparseVolumes(_storagePoolDetailsDao.findDetail(storagePoolId, NexentaUtil.SPARSE_VOLUMES).getValue()); + parameters.setVolumeBlockSize(_storagePoolDetailsDao.findDetail(storagePoolId, NexentaUtil.VOLUME_BLOCK_SIZE).getValue()); + + return new NexentaStorAppliance(parameters); + } + + @Override + public void takeSnapshot(SnapshotInfo snapshot, AsyncCompletionCallback callback) {} + + @Override + public void revertSnapshot(SnapshotInfo snapshot, AsyncCompletionCallback callback) {} + + @Override + public void createAsync(DataStore dataStore, DataObject dataObject, AsyncCompletionCallback callback) { + String iqn = null; + String errorMessage = null; + + if (dataObject.getType() != DataObjectType.VOLUME) { + errorMessage = "Invalid DataObjectType (" + dataObject.getType() + ") passed to createAsync"; + } else { + VolumeInfo volumeInfo = (VolumeInfo) dataObject; + + long storagePoolId = dataStore.getId(); + NexentaStorAppliance appliance = getNexentaStorAppliance(storagePoolId); + + // TODO: maybe we should use md5(volume name) as volume name + NexentaStorZvol zvol = (NexentaStorZvol) appliance.createVolume(volumeInfo.getName(), volumeInfo.getSize()); + iqn = zvol.getIqn(); + + VolumeVO volume = this._volumeDao.findById(volumeInfo.getId()); + volume.set_iScsiName(iqn); + volume.setFolder(zvol.getName()); + volume.setPoolType(Storage.StoragePoolType.IscsiLUN); + volume.setPoolId(storagePoolId); + _volumeDao.update(volume.getId(), volume); + + StoragePoolVO storagePool = _storagePoolDao.findById(storagePoolId); + long capacityBytes = storagePool.getCapacityBytes(); + long usedBytes = storagePool.getUsedBytes(); + usedBytes += volumeInfo.getSize(); + storagePool.setUsedBytes(usedBytes > capacityBytes ? capacityBytes : usedBytes); + _storagePoolDao.update(storagePoolId, storagePool); + } + + CreateCmdResult result = new CreateCmdResult(iqn, new Answer(null, errorMessage == null, errorMessage)); + result.setResult(errorMessage); + callback.complete(result); + } + + @Override + public void deleteAsync(DataStore store, DataObject data, AsyncCompletionCallback callback) { + String errorMessage = null; + if (data.getType() == DataObjectType.VOLUME) { + VolumeInfo volumeInfo = (VolumeInfo) data; + long storagePoolId = store.getId(); + NexentaStorAppliance appliance = getNexentaStorAppliance(storagePoolId); + StoragePoolVO storagePool = _storagePoolDao.findById(storagePoolId); + + + +// _storagePoolDao.update(stoagePoolId); + } else { + errorMessage = String.format( + "Invalid DataObjectType(%s) passed to deleteAsync", + data.getType()); + } + CommandResult result = new CommandResult(); + result.setResult(errorMessage); + callback.complete(result); + } + + @Override + public void copyAsync(DataObject srcdata, DataObject destData, AsyncCompletionCallback callback) {} + + @Override + public boolean canCopy(DataObject srcData, DataObject destData) { + return false; + } + + @Override + public void resize(DataObject data, AsyncCompletionCallback callback) {} +} diff --git a/plugins/storage/volume/nexenta/src/org/apache/cloudstack/storage/datastore/lifecylce/NexentaPrimaryDataStoreLifeCycle.java b/plugins/storage/volume/nexenta/src/org/apache/cloudstack/storage/datastore/lifecylce/NexentaPrimaryDataStoreLifeCycle.java new file mode 100644 index 00000000000..c7ce33ab054 --- /dev/null +++ b/plugins/storage/volume/nexenta/src/org/apache/cloudstack/storage/datastore/lifecylce/NexentaPrimaryDataStoreLifeCycle.java @@ -0,0 +1,176 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.cloudstack.storage.datastore.lifecylce; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.inject.Inject; + +import org.apache.cloudstack.engine.subsystem.api.storage.ClusterScope; +import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; +import org.apache.cloudstack.engine.subsystem.api.storage.HostScope; +import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreLifeCycle; +import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreParameters; +import org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope; +import org.apache.cloudstack.storage.datastore.util.NexentaUtil; +import org.apache.cloudstack.storage.volume.datastore.PrimaryDataStoreHelper; +import org.apache.log4j.Logger; + +import com.cloud.agent.api.StoragePoolInfo; +import com.cloud.dc.DataCenterVO; +import com.cloud.dc.dao.DataCenterDao; +import com.cloud.host.HostVO; +import com.cloud.hypervisor.Hypervisor; +import com.cloud.resource.ResourceManager; +import com.cloud.storage.StorageManager; +import com.cloud.storage.StoragePoolAutomation; + +public class NexentaPrimaryDataStoreLifeCycle + implements PrimaryDataStoreLifeCycle { + private static final Logger logger = + Logger.getLogger(NexentaPrimaryDataStoreLifeCycle.class); + + @Inject + private DataCenterDao zoneDao; + @Inject + private PrimaryDataStoreHelper dataStoreHelper; + @Inject + private ResourceManager _resourceMgr; + @Inject + StorageManager _storageMgr; + @Inject + private StoragePoolAutomation storagePoolAutomation; + + @Override + public DataStore initialize(Map dsInfos) { + String url = (String) dsInfos.get("url"); + Long zoneId = (Long) dsInfos.get("zoneId"); + String storagePoolName = (String) dsInfos.get("name"); + String providerName = (String) dsInfos.get("providerName"); + Long capacityBytes = (Long)dsInfos.get("capacityBytes"); + Long capacityIops = (Long)dsInfos.get("capacityIops"); + String tags = (String)dsInfos.get("tags"); + Map details = (Map) dsInfos.get("details"); + NexentaUtil.NexentaPluginParameters params = NexentaUtil.parseNexentaPluginUrl(url); + DataCenterVO zone = zoneDao.findById(zoneId); + String uuid = String.format("%s_%s_%s", NexentaUtil.PROVIDER_NAME, zone.getUuid(), params.getNmsUrl().getHost()); + + if (capacityBytes == null || capacityBytes <= 0) { + throw new IllegalArgumentException("'capacityBytes' must be present and greater than 0."); + } + + if (capacityIops == null || capacityIops <= 0) { + throw new IllegalArgumentException("'capacityIops' must be present and greater than 0."); + } + + PrimaryDataStoreParameters parameters = new PrimaryDataStoreParameters(); + + parameters.setHost(params.getStorageHost()); + parameters.setPort(params.getStoragePort()); + parameters.setPath(params.getStoragePath()); + parameters.setType(params.getStorageType()); + parameters.setUuid(uuid); + parameters.setZoneId(zoneId); + parameters.setName(storagePoolName); + parameters.setProviderName(providerName); + parameters.setManaged(true); + parameters.setCapacityBytes(capacityBytes); + parameters.setUsedBytes(0); + parameters.setCapacityIops(capacityIops); + parameters.setHypervisorType(Hypervisor.HypervisorType.Any); + parameters.setTags(tags); + + details.put(NexentaUtil.NMS_URL, params.getNmsUrl().toString()); + + details.put(NexentaUtil.VOLUME, params.getVolume()); + details.put(NexentaUtil.SPARSE_VOLUMES, params.getSparseVolumes().toString()); + + details.put(NexentaUtil.STORAGE_TYPE, params.getStorageType().toString()); + details.put(NexentaUtil.STORAGE_HOST, params.getStorageHost()); + details.put(NexentaUtil.STORAGE_PORT, params.getStoragePort().toString()); + details.put(NexentaUtil.STORAGE_PATH, params.getStoragePath()); + + parameters.setDetails(details); + + // this adds a row in the cloud.storage_pool table for this SolidFire cluster + return dataStoreHelper.createPrimaryDataStore(parameters); + } + + @Override + public boolean attachCluster(DataStore store, ClusterScope scope) { + return true; + } + + @Override + public boolean attachHost(DataStore store, HostScope scope, StoragePoolInfo existingInfo) { + return true; + } + + @Override + public boolean attachZone(DataStore dataStore, ZoneScope scope, Hypervisor.HypervisorType hypervisorType) { + dataStoreHelper.attachZone(dataStore); + + List xenServerHosts = _resourceMgr.listAllUpAndEnabledHostsInOneZoneByHypervisor(Hypervisor.HypervisorType.XenServer, scope.getScopeId()); + List vmWareServerHosts = _resourceMgr.listAllUpAndEnabledHostsInOneZoneByHypervisor(Hypervisor.HypervisorType.VMware, scope.getScopeId()); + List kvmHosts = _resourceMgr.listAllUpAndEnabledHostsInOneZoneByHypervisor(Hypervisor.HypervisorType.KVM, scope.getScopeId()); + List hosts = new ArrayList(); + + hosts.addAll(xenServerHosts); + hosts.addAll(vmWareServerHosts); + hosts.addAll(kvmHosts); + + for (HostVO host : hosts) { + try { + _storageMgr.connectHostToSharedPool(host.getId(), dataStore.getId()); + } catch (Exception e) { + logger.warn("Unable to establish a connection between " + host + " and " + dataStore, e); + } + } + + return true; + } + + @Override + public boolean maintain(DataStore store) { + storagePoolAutomation.maintain(store); + dataStoreHelper.maintain(store); + + return true; + } + + @Override + public boolean cancelMaintain(DataStore store) { + dataStoreHelper.cancelMaintain(store); + storagePoolAutomation.cancelMaintain(store); + + return true; + } + + @Override + public boolean deleteDataStore(DataStore store) { + return dataStoreHelper.deletePrimaryDataStore(store); + } + + @Override + public boolean migrateToObjectStore(DataStore store) { + return false; + } +} diff --git a/plugins/storage/volume/nexenta/src/org/apache/cloudstack/storage/datastore/provider/NexentaHostListener.java b/plugins/storage/volume/nexenta/src/org/apache/cloudstack/storage/datastore/provider/NexentaHostListener.java new file mode 100644 index 00000000000..950325288f3 --- /dev/null +++ b/plugins/storage/volume/nexenta/src/org/apache/cloudstack/storage/datastore/provider/NexentaHostListener.java @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.cloudstack.storage.datastore.provider; + +import org.apache.log4j.Logger; + +import org.apache.cloudstack.engine.subsystem.api.storage.HypervisorHostListener; + +public class NexentaHostListener implements HypervisorHostListener { + private static final Logger logger = Logger.getLogger(NexentaHostListener.class); + + public boolean hostConnect(long hostId, long poolId) { + return true; + } + + public boolean hostDisconnected(long hostId, long poolId) { + return true; + } +} diff --git a/plugins/storage/volume/nexenta/src/org/apache/cloudstack/storage/datastore/provider/NexentaPrimaryDataStoreProvider.java b/plugins/storage/volume/nexenta/src/org/apache/cloudstack/storage/datastore/provider/NexentaPrimaryDataStoreProvider.java new file mode 100644 index 00000000000..afd7e35c257 --- /dev/null +++ b/plugins/storage/volume/nexenta/src/org/apache/cloudstack/storage/datastore/provider/NexentaPrimaryDataStoreProvider.java @@ -0,0 +1,81 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.cloudstack.storage.datastore.provider; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.springframework.stereotype.Component; + +import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreProvider; +import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreLifeCycle; +import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver; +import org.apache.cloudstack.engine.subsystem.api.storage.HypervisorHostListener; +import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreDriver; +import org.apache.cloudstack.storage.datastore.driver.NexentaPrimaryDataStoreDriver; +import org.apache.cloudstack.storage.datastore.lifecylce.NexentaPrimaryDataStoreLifeCycle; +import org.apache.cloudstack.storage.datastore.util.NexentaUtil; + +import com.cloud.utils.component.ComponentContext; + +@Component +public class NexentaPrimaryDataStoreProvider implements PrimaryDataStoreProvider { + private DataStoreLifeCycle lifeCycle; + private PrimaryDataStoreDriver driver; + private HypervisorHostListener listener; + + @Override + public DataStoreLifeCycle getDataStoreLifeCycle() { + return lifeCycle; + } + + @Override + public DataStoreDriver getDataStoreDriver() { + return driver; + } + + @Override + public HypervisorHostListener getHostListener() { + return listener; + } + + @Override + public String getName() { + return NexentaUtil.PROVIDER_NAME; + } + + @Override + public boolean configure(Map params) { + lifeCycle = ComponentContext.inject(NexentaPrimaryDataStoreLifeCycle.class); + driver = ComponentContext.inject(NexentaPrimaryDataStoreDriver.class); + listener = ComponentContext.inject(NexentaHostListener.class); + + return true; + } + + @Override + public Set getTypes() { + Set types = new HashSet(); + + types.add(DataStoreProviderType.PRIMARY); + + return types; + } +} diff --git a/plugins/storage/volume/nexenta/src/org/apache/cloudstack/storage/datastore/util/NexentaNmsClient.java b/plugins/storage/volume/nexenta/src/org/apache/cloudstack/storage/datastore/util/NexentaNmsClient.java new file mode 100644 index 00000000000..70565fcea32 --- /dev/null +++ b/plugins/storage/volume/nexenta/src/org/apache/cloudstack/storage/datastore/util/NexentaNmsClient.java @@ -0,0 +1,229 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.cloudstack.storage.datastore.util; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +import org.apache.http.HttpResponse; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.conn.BasicClientConnectionManager; +import org.apache.log4j.Logger; + +import com.cloud.utils.exception.CloudRuntimeException; +import com.google.gson.Gson; +import com.google.gson.annotations.SerializedName; + +public class NexentaNmsClient { + private static final Logger logger = Logger.getLogger(NexentaNmsClient.class); + + protected NexentaNmsUrl nmsUrl = null; + protected DefaultHttpClient httpClient = null; + + NexentaNmsClient(NexentaNmsUrl nmsUrl) { + this.nmsUrl = nmsUrl; + } + + private static boolean isSuccess(int iCode) { + return iCode >= 200 && iCode < 300; + } + + protected DefaultHttpClient getClient() { + if (httpClient == null) { + if (nmsUrl.getSchema().equalsIgnoreCase("http")) { + httpClient = getHttpClient(); + } else { + httpClient = getHttpsClient(); + } + AuthScope authScope = new AuthScope(nmsUrl.getHost(), nmsUrl.getPort(), AuthScope.ANY_SCHEME, "basic"); + UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(nmsUrl.getUsername(), nmsUrl.getPassword()); + httpClient.getCredentialsProvider().setCredentials(authScope, credentials); + } + return httpClient; + } + + protected DefaultHttpClient getHttpsClient() { + try { + SSLContext sslContext = SSLContext.getInstance("SSL"); + X509TrustManager tm = new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { + } + + @Override + public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return null; + } + }; + + sslContext.init(null, new TrustManager[] {tm}, new SecureRandom()); + + SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + SchemeRegistry registry = new SchemeRegistry(); + + registry.register(new Scheme("https", nmsUrl.getPort(), socketFactory)); + + BasicClientConnectionManager mgr = new BasicClientConnectionManager(registry); + + return new DefaultHttpClient(mgr); + } catch (NoSuchAlgorithmException ex) { + throw new CloudRuntimeException(ex.getMessage()); + } catch (KeyManagementException ex) { + throw new CloudRuntimeException(ex.getMessage()); + } + } + + protected DefaultHttpClient getHttpClient() { + return new DefaultHttpClient(); + } + + @SuppressWarnings("unused") + static class NmsRequest { + private String method; + private String object; + private Object[] params; + + NmsRequest(String object, String method) { + this(method, object, null); + } + + NmsRequest(String object, String method, Object... params) { + this.method = method; + this.object = object; + this.params = params; + } + + public String toString() { + StringBuffer b = new StringBuffer(); + b.append("Request to ").append(object).append(" method ").append(method); + if (params != null) { + b.append(" params:"); + for (Object param:params) { + b.append(" ").append(param).append(","); + } + } + return b.toString(); + } + } + + @SuppressWarnings("unused") + static class NmsError { + private String message; + + public String getMesssage() { + return message; + } + } + + @SuppressWarnings("unused") + static class NmsResponse { + @SerializedName("tg_flash") protected String tgFlash; + + protected NmsError error; + + NmsResponse() {} + + NmsResponse(String tgFlash, NmsError error) { + this.tgFlash = tgFlash; + this.error = error; + } + + public String getTgFlash() { + return tgFlash; + } + + public NmsError getError() { + return error; + } + } + + public NmsResponse execute(Class responseClass, String object, String method, Object... params) { + StringBuilder sb = new StringBuilder(); + NmsRequest nmsRequest = new NmsRequest(object, method, params); + if (logger.isDebugEnabled()) { + logger.debug(nmsRequest); + } + final Gson gson = new Gson(); + String jsonRequest = gson.toJson(nmsRequest); + StringEntity input = new StringEntity(jsonRequest, ContentType.APPLICATION_JSON); + HttpPost postRequest = new HttpPost(nmsUrl.toString()); + postRequest.setEntity(input); + + DefaultHttpClient httpClient = getClient(); + try { + HttpResponse response = httpClient.execute(postRequest); + final int status = response.getStatusLine().getStatusCode(); + if (!isSuccess(status)) { + throw new CloudRuntimeException("Failed on JSON-RPC API call. HTTP error code = " + status); + } + BufferedReader buffer = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); + String tmp; + while ((tmp = buffer.readLine()) != null) { + sb.append(tmp); + } + } catch (ClientProtocolException ex) { + throw new CloudRuntimeException(ex.getMessage()); + } catch (IOException ex) { + throw new CloudRuntimeException(ex.getMessage()); + } finally { + if (httpClient != null) { + try { + httpClient.getConnectionManager().shutdown(); + } catch (Exception t) { + logger.debug(t.getMessage()); + } + } + } + + String responseString = sb.toString(); + if (logger.isDebugEnabled()) { + logger.debug("NexentaStor Appliance response: " + responseString); + } + + NmsResponse nmsResponse = (NmsResponse) gson.fromJson(responseString, responseClass); + if (nmsResponse.getError() != null) { + throw new CloudRuntimeException(nmsResponse.getError().getMesssage()); + } + + return nmsResponse; + } +} diff --git a/plugins/storage/volume/nexenta/src/org/apache/cloudstack/storage/datastore/util/NexentaNmsUrl.java b/plugins/storage/volume/nexenta/src/org/apache/cloudstack/storage/datastore/util/NexentaNmsUrl.java new file mode 100644 index 00000000000..684b8dc1d0c --- /dev/null +++ b/plugins/storage/volume/nexenta/src/org/apache/cloudstack/storage/datastore/util/NexentaNmsUrl.java @@ -0,0 +1,85 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.cloudstack.storage.datastore.util; + +public class NexentaNmsUrl { + protected final boolean isAuto; + protected String schema; + protected final String username; + protected final String password; + protected final String host; + protected int port; + + public NexentaNmsUrl(boolean isAuto, String schema, String username, String password, String host, int port) { + this.isAuto = isAuto; + this.schema = schema; + this.username = username; + this.password = password; + this.host = host; + this.port = port; + } + + public boolean isAuto() { + return this.isAuto; + } + + public void setSchema(String schema) { + this.schema = schema; + } + + public String getSchema() { + return this.schema; + } + + public String getUsername() { + return this.username; + } + + public String getPassword() { + return this.password; + } + + public String getHost() { + return this.host; + } + + public int getPort() { + return this.port; + } + + public String getPath() { + return "/rest/nms"; + } + + public String toString() { + StringBuilder b = new StringBuilder(); + if (isAuto) { + b.append("auto://"); + } else { + b.append(schema).append("://"); + } + if (username != null && password != null) { + b.append(username).append(":").append(password).append("@"); + } else if (username != null) { + b.append(username).append("@"); + } + b.append(host).append(":").append(port).append("/rest/nms/"); + return b.toString(); + } +} diff --git a/plugins/storage/volume/nexenta/src/org/apache/cloudstack/storage/datastore/util/NexentaStorAppliance.java b/plugins/storage/volume/nexenta/src/org/apache/cloudstack/storage/datastore/util/NexentaStorAppliance.java new file mode 100644 index 00000000000..c1efc75e124 --- /dev/null +++ b/plugins/storage/volume/nexenta/src/org/apache/cloudstack/storage/datastore/util/NexentaStorAppliance.java @@ -0,0 +1,418 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.cloudstack.storage.datastore.util; + +import java.util.HashMap; +import java.util.LinkedList; + +import org.apache.cloudstack.storage.datastore.util.NexentaNmsClient.NmsResponse; +import org.apache.log4j.LogManager; +import org.apache.log4j.Logger; + +import com.cloud.utils.exception.CloudRuntimeException; +import com.google.gson.annotations.SerializedName; + +public class NexentaStorAppliance { + private static final Logger logger = LogManager.getLogger(NexentaStorAppliance.class); + + protected NexentaNmsClient client; + protected NexentaUtil.NexentaPluginParameters parameters; + + public NexentaStorAppliance(NexentaUtil.NexentaPluginParameters parameters) { + client = new NexentaNmsClient(parameters.getNmsUrl()); + this.parameters = parameters; + } + + NexentaStorAppliance(NexentaNmsClient client, NexentaUtil.NexentaPluginParameters parameters) { + this.client = client; + this.parameters = parameters; + } + + String getVolumeName(String volumeName) { + if (volumeName.startsWith("/")) { + return String.format("%s%s", parameters.getVolume(), volumeName); + } + return String.format("%s/%s", parameters.getVolume(), volumeName); + } + + static String getTargetName(String volumeName) { + return NexentaUtil.ISCSI_TARGET_NAME_PREFIX + volumeName; + } + + static String getTargetGroupName(String volumeName) { + return NexentaUtil.ISCSI_TARGET_GROUP_PREFIX + volumeName; + } + + @SuppressWarnings("unused") + static final class IntegerNmsResponse extends NmsResponse { + Integer result; + + IntegerNmsResponse(int result) { + this.result = Integer.valueOf(result); + } + + public Integer getResult() { + return result; + } + } + + @SuppressWarnings("unused") + static final class IscsiTarget { + protected String status; + protected String protocol; + protected String name; + protected String sessions; + protected String alias; + protected String provider; + + IscsiTarget(String status, String protocol, String name, String sessions, String alias, String provider) { + this.status = status; + this.protocol = protocol; + this.name = name; + this.sessions = sessions; + this.alias = alias; + this.provider = provider; + } + } + + @SuppressWarnings("unused") + static final class ListOfIscsiTargetsNmsResponse extends NmsResponse { + protected HashMap result; + + ListOfIscsiTargetsNmsResponse() {} + + ListOfIscsiTargetsNmsResponse(HashMap result) { + this.result = result; + } + + public HashMap getResult() { + return result; + } + } + + /** + * Checks if iSCSI target exists. + * @param targetName iSCSI target name + * @return true if iSCSI target exists, else false + */ + boolean isIscsiTargetExists(String targetName) { + ListOfIscsiTargetsNmsResponse response = (ListOfIscsiTargetsNmsResponse) client.execute(ListOfIscsiTargetsNmsResponse.class, "stmf", "list_targets"); + if (response == null) { + return false; + } + HashMap result = response.getResult(); + return result != null && result.keySet().contains(targetName); + } + + @SuppressWarnings("unused") + static final class CreateIscsiTargetRequestParams { + @SerializedName("target_name") String targetName; + + CreateIscsiTargetRequestParams(String targetName) { + this.targetName = targetName; + } + + @Override + public boolean equals(Object other) { + return other instanceof CreateIscsiTargetRequestParams && targetName.equals(((CreateIscsiTargetRequestParams) other).targetName); + } + } + + /** + * Creates iSCSI target on NexentaStor Appliance. + * @param targetName iSCSI target name + */ + void createIscsiTarget(String targetName) { + try { + client.execute(NmsResponse.class, "iscsitarget", "create_target", new CreateIscsiTargetRequestParams(targetName)); + } catch (CloudRuntimeException ex) { + if (!ex.getMessage().contains("already configured")) { + throw ex; + } + logger.debug("Ignored target creation error: " + ex); + } + } + + @SuppressWarnings("unused") + static final class ListOfStringsNmsResponse extends NmsResponse { + LinkedList result; + + ListOfStringsNmsResponse() {} + + ListOfStringsNmsResponse(LinkedList result) { + this.result = result; + } + + public LinkedList getResult() { + return result; + } + } + + /** + * Checks if iSCSI target group already exists on NexentaStor Appliance. + * @param targetGroupName iSCSI target group name + * @return true if iSCSI target group already exists, else false + */ + boolean isIscsiTargetGroupExists(String targetGroupName) { + ListOfStringsNmsResponse response = (ListOfStringsNmsResponse) client.execute(ListOfStringsNmsResponse.class, "stmf", "list_targetgroups"); + if (response == null) { + return false; + } + LinkedList result = response.getResult(); + return result != null && result.contains(targetGroupName); + } + + /** + * Creates iSCSI target group on NexentaStor Appliance. + * @param targetGroupName iSCSI target group name + */ + void createIscsiTargetGroup(String targetGroupName) { + try { + client.execute(NmsResponse.class, "stmf", "create_targetgroup", targetGroupName); + } catch (CloudRuntimeException ex) { + if (!ex.getMessage().contains("already exists") && !ex.getMessage().contains("target must be offline")) { + throw ex; + } + logger.info("Ignored target group creation error: " + ex); + } + } + + /** + * Checks if iSCSI target is member of target group. + * @param targetGroupName iSCSI target group name + * @param targetName iSCSI target name + * @return true if target is member of iSCSI target group, else false + */ + boolean isTargetMemberOfTargetGroup(String targetGroupName, String targetName) { + ListOfStringsNmsResponse response = (ListOfStringsNmsResponse) client.execute(ListOfStringsNmsResponse.class, "stmf", "list_targetgroup_members", targetGroupName); + if (response == null) { + return false; + } + LinkedList result = response.getResult(); + return result != null && result.contains(targetName); + } + + /** + * Adds iSCSI target to target group. + * @param targetGroupName iSCSI target group name + * @param targetName iSCSI target name + */ + void addTargetGroupMember(String targetGroupName, String targetName) { + try { + client.execute(NmsResponse.class, "stmf", "add_targetgroup_member", targetGroupName, targetName); + } catch (CloudRuntimeException ex) { + if (!ex.getMessage().contains("already exists") && !ex.getMessage().contains("target must be offline")) { + throw ex; + } + logger.debug("Ignored target group member addition error: " + ex); + } + } + + /** + * Checks if LU already exists on NexentaStor appliance. + * @param luName LU name + * @return true if LU already exists, else false + */ + boolean isLuExists(String luName) { + IntegerNmsResponse response; + try { + response = (IntegerNmsResponse) client.execute(IntegerNmsResponse.class, "scsidisk", "lu_exists", luName); + } catch (CloudRuntimeException ex) { + if (ex.getMessage().contains("does not exist")) { + return false; + } + throw ex; + } + return response!= null && response.getResult() > 0; + } + + @SuppressWarnings("unused") + static final class LuParams { + @Override + public boolean equals(Object other) { + return other instanceof LuParams; + } + } + + /** + * Creates LU for volume. + * @param volumeName volume name + */ + void createLu(String volumeName) { + try { + client.execute(NmsResponse.class, "scsidisk", "create_lu", volumeName, new LuParams()); + } catch (CloudRuntimeException ex) { + if (!ex.getMessage().contains("in use")) { + throw ex; + } + logger.info("Ignored LU creation error: " + ex); + } + } + + /** + * Checks if LU shared on NexentaStor appliance. + * @param luName LU name + * @return true if LU was already shared, else false + */ + boolean isLuShared(String luName) { + IntegerNmsResponse response; + try { + response = (IntegerNmsResponse) client.execute(IntegerNmsResponse.class, "scsidisk", "lu_shared", luName); + } catch (CloudRuntimeException ex) { + if (ex.getMessage().contains("does not exist")) { + return false; + } + throw ex; + } + return response != null && response.getResult() > 0; + } + + @SuppressWarnings("unused") + static final class MappingEntry { + @SerializedName("target_group") String targetGroup; + String lun; + String zvol; + @SerializedName("host_group") String hostGroup; + @SerializedName("entry_number") String entryNumber; + + MappingEntry(String targetGroup, String lun) { + this.targetGroup = targetGroup; + this.lun = lun; + } + + static boolean isEquals(Object a, Object b) { + return (a == null && b == null) || (a != null && a.equals(b)); + } + + @Override + public boolean equals(Object other) { + if (other instanceof MappingEntry) { + MappingEntry o = (MappingEntry) other; + return isEquals(targetGroup, o.targetGroup) && isEquals(lun, o.lun) && isEquals(zvol, o.zvol) && + isEquals(hostGroup, o.hostGroup) && isEquals(entryNumber, o.entryNumber); + } + return false; + } + } + + @SuppressWarnings("unused") + static final class AddMappingEntryNmsResponse extends NmsResponse { + MappingEntry result; + } + + /** + * Adds LU mapping entry to iSCSI target group. + * @param luName LU name + * @param targetGroupName iSCSI target group name + */ + void addLuMappingEntry(String luName, String targetGroupName) { + MappingEntry mappingEntry = new MappingEntry(targetGroupName, "0"); + try { + client.execute(AddMappingEntryNmsResponse.class, "scsidisk", "add_lun_mapping_entry", luName, mappingEntry); + } catch (CloudRuntimeException ex) { + if (!ex.getMessage().contains("view already exists")) { + throw ex; + } + logger.debug("Ignored LU mapping entry addition error " + ex); + } + } + + NexentaStorZvol createIscsiVolume(String volumeName, Long volumeSize) { + final String zvolName = getVolumeName(volumeName); + String volumeSizeString = String.format("%dB", volumeSize); + + client.execute(NmsResponse.class, "zvol", "create", zvolName, volumeSizeString, parameters.getVolumeBlockSize(), parameters.getSparseVolumes()); + + final String targetName = getTargetName(volumeName); + final String targetGroupName = getTargetGroupName(volumeName); + + if (!isIscsiTargetExists(targetName)) { + createIscsiTarget(targetName); + } + + if (!isIscsiTargetGroupExists(targetGroupName)) { + createIscsiTargetGroup(targetGroupName); + } + + if (!isTargetMemberOfTargetGroup(targetGroupName, targetName)) { + addTargetGroupMember(targetGroupName, targetName); + } + + if (!isLuExists(zvolName)) { + createLu(zvolName); + } + + if (!isLuShared(zvolName)) { + addLuMappingEntry(zvolName, targetGroupName); + } + + return new NexentaStorZvol(zvolName, targetName); + } + + static abstract class NexentaStorVolume { + protected String name; + + NexentaStorVolume(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + @Override + public String toString() { + return name; + } + } + + public static final class NexentaStorZvol extends NexentaStorVolume { + protected String iqn; + + public NexentaStorZvol(String name, String iqn) { + super(name); + this.iqn = iqn; + } + + public String getIqn() { + return iqn; + } + } + + public void deleteIscsiVolume(String volumeName) { + try { + NmsResponse response = client.execute(NmsResponse.class, "zvol", "destroy", volumeName, ""); + } catch (CloudRuntimeException ex) { + if (!ex.getMessage().contains("does not exist")) { + throw ex; + } + logger.debug(String.format( + "Volume %s does not exist, it seems it was already " + + "deleted.", volumeName)); + } + } + + public NexentaStorVolume createVolume(String volumeName, Long volumeSize) { + return createIscsiVolume(volumeName, volumeSize); + } + + public void deleteVolume(String volumeName) { + deleteIscsiVolume(volumeName); + } +} diff --git a/plugins/storage/volume/nexenta/src/org/apache/cloudstack/storage/datastore/util/NexentaUtil.java b/plugins/storage/volume/nexenta/src/org/apache/cloudstack/storage/datastore/util/NexentaUtil.java new file mode 100644 index 00000000000..ee6a78ff49c --- /dev/null +++ b/plugins/storage/volume/nexenta/src/org/apache/cloudstack/storage/datastore/util/NexentaUtil.java @@ -0,0 +1,242 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.cloudstack.storage.datastore.util; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.StringTokenizer; + +import com.cloud.storage.Storage; + +public class NexentaUtil { + public static final String PROVIDER_NAME = "Nexenta"; + + public static final String NMS_URL = "nmsUrl"; + public static final String VOLUME = "volume"; + + public static final String STORAGE_HOST = "storageHost"; + public static final String STORAGE_PORT = "storagePort"; + public static final String STORAGE_TYPE = "storageType"; + public static final String STORAGE_PATH = "storagePath"; + + public static final String DEFAULT_NMS_USER = "admin"; + public static final String DEFAULT_NMS_PASSWORD = "nexenta"; + + public static final String SPARSE_VOLUMES = "sparseVolumes"; + public static final String VOLUME_BLOCK_SIZE = "volumeBlockSize"; + + public static final int DEFAULT_NMS_PORT = 2000; + public static final int DEFAULT_ISCSI_TARGET_PORTAL_PORT = 3260; + public static final int DEFAULT_NFS_PORT = 2049; + + public static final String ISCSI_TARGET_NAME_PREFIX = "iqn.1986-03.com.sun:02:cloudstack-"; + public static final String ISCSI_TARGET_GROUP_PREFIX = "cloudstack/"; + + /** + * Parse NMS url into normalized parts like scheme, user, host and others. + * + * Example NMS URL: + * auto://admin:nexenta@192.168.1.1:2000/ + * + * NMS URL parts: + * auto true if url starts with auto://, protocol will be automatically switched to https if http not supported; + * scheme (auto) connection protocol (http or https); + * user (admin) NMS user; + * password (nexenta) NMS password; + * host (192.168.1.1) NMS host; + * port (2000) NMS port. + * + * @param nmsUrl url string to parse + * @return instance of NexentaConnection class + */ + public static NexentaNmsUrl parseNmsUrl(String nmsUrl) { + URI uri; + + try { + uri = new URI(nmsUrl); + } catch (URISyntaxException e) { + throw new IllegalArgumentException("Invalid URI: " + nmsUrl); + } + + boolean isAuto = false; + String schema = uri.getScheme(); + if (schema == null || schema.isEmpty() || "auto".equalsIgnoreCase(schema)) { + schema = "http"; + isAuto = true; + } + + String username, password, userInfo = uri.getUserInfo(); + if (userInfo == null) { + username = DEFAULT_NMS_USER; + password = DEFAULT_NMS_PASSWORD; + } else { + if (userInfo.indexOf(':') < 0) { + username = userInfo; + password = DEFAULT_NMS_PASSWORD; + } else { + String[] parts = userInfo.split(":", 2); + username = parts[0]; + password = parts[1]; + } + } + + String host = uri.getHost(); + if (host == null) { + throw new IllegalArgumentException(String.format("NMS host required: %s.", nmsUrl)); + } + + int port = uri.getPort(); + if (port == -1) { + port = DEFAULT_NMS_PORT; + } + + return new NexentaNmsUrl(isAuto, schema, username, password, host, port); + } + + public static Storage.StoragePoolType getStorageType(String v) { + if ("iSCSI".equalsIgnoreCase(v)) { + return Storage.StoragePoolType.Iscsi; + } else if ("NFS".equalsIgnoreCase(v)) { + return Storage.StoragePoolType.NetworkFilesystem; + } + return Storage.StoragePoolType.Iscsi; + } + + public static class NexentaPluginParameters { + protected NexentaNmsUrl nmsUrl; + protected String volume; + protected Storage.StoragePoolType storageType = Storage.StoragePoolType.Iscsi; + protected String storageHost; + protected Integer storagePort; + protected String storagePath; + protected Boolean sparseVolumes = false; + protected String volumeBlockSize = "8K"; + + public void setNmsUrl(String url) { + this.nmsUrl = NexentaUtil.parseNmsUrl(url); + } + + public NexentaNmsUrl getNmsUrl() { + return nmsUrl; + } + + public void setVolume(String volume) { + if (volume.endsWith("/")) { + this.volume = volume.substring(0, volume.length() - 1); + } else { + this.volume = volume; + } + } + + public String getVolume() { + return volume; + } + + public void setStorageType(String storageType) { + this.storageType = NexentaUtil.getStorageType(storageType); + } + + public Storage.StoragePoolType getStorageType() { + return storageType; + } + + public void setStorageHost(String host) { + this.storageHost = host; + } + + public String getStorageHost() { + if (storageHost == null && nmsUrl != null) { + return nmsUrl.getHost(); + } + return storageHost; + } + + public void setStoragePort(String port) { + this.storagePort = Integer.parseInt(port); + } + + public Integer getStoragePort() { + if (storagePort == null && storageType != null) { + if (storageType == Storage.StoragePoolType.Iscsi) { + return DEFAULT_ISCSI_TARGET_PORTAL_PORT; + } else { + return DEFAULT_NFS_PORT; + } + } + return storagePort; + } + + public void setStoragePath(String path) { + this.storagePath = path; + } + + public String getStoragePath() { + return storagePath; + } + + public void setSparseVolumes(String sparseVolumes) { + this.sparseVolumes = Boolean.TRUE.toString().equalsIgnoreCase(sparseVolumes); + } + + public Boolean getSparseVolumes() { + return sparseVolumes; + } + + public void setVolumeBlockSize(String volumeBlockSize) { + this.volumeBlockSize = volumeBlockSize; + } + + public String getVolumeBlockSize() { + return volumeBlockSize; + } + } + + public static NexentaPluginParameters parseNexentaPluginUrl(String url) { + final String delimiter1 = ";"; + final String delimiter2 = "="; + StringTokenizer st = new StringTokenizer(url, delimiter1); + NexentaPluginParameters params = new NexentaPluginParameters(); + while (st.hasMoreElements()) { + String token = st.nextElement().toString(); + int idx = token.indexOf(delimiter2); + if (idx == -1) { + throw new RuntimeException("Invalid URL format"); + } + String[] urlKeyAndValue = token.split(delimiter2, 2); + if (NMS_URL.equalsIgnoreCase(urlKeyAndValue[0])) { + params.setNmsUrl(urlKeyAndValue[1]); + } else if (VOLUME.equalsIgnoreCase(urlKeyAndValue[0])) { + params.setVolume(urlKeyAndValue[1]); + } else if (STORAGE_TYPE.equalsIgnoreCase(urlKeyAndValue[0])) { + params.setStorageType(urlKeyAndValue[1]); + } else if (STORAGE_HOST.equalsIgnoreCase(urlKeyAndValue[0])) { + params.setStorageHost(urlKeyAndValue[1]); + } else if (STORAGE_PORT.equalsIgnoreCase(urlKeyAndValue[0])) { + params.setStoragePort(urlKeyAndValue[1]); + } else if (STORAGE_PATH.equalsIgnoreCase(urlKeyAndValue[0])) { + params.setStoragePath(urlKeyAndValue[1]); + } else if (SPARSE_VOLUMES.equalsIgnoreCase(urlKeyAndValue[0])) { + params.setSparseVolumes(urlKeyAndValue[1]); + } else if (VOLUME_BLOCK_SIZE.equalsIgnoreCase(urlKeyAndValue[0])) { + params.setVolumeBlockSize(urlKeyAndValue[1]); + } + } + return params; + } +} diff --git a/plugins/storage/volume/nexenta/test/org/apache/cloudstack/storage/datastore/util/NexentaStorApplianceTest.java b/plugins/storage/volume/nexenta/test/org/apache/cloudstack/storage/datastore/util/NexentaStorApplianceTest.java new file mode 100644 index 00000000000..6dc59ebd0af --- /dev/null +++ b/plugins/storage/volume/nexenta/test/org/apache/cloudstack/storage/datastore/util/NexentaStorApplianceTest.java @@ -0,0 +1,337 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.cloudstack.storage.datastore.util; + +import static org.apache.cloudstack.storage.datastore.util.NexentaStorAppliance.IscsiTarget; +import static org.apache.cloudstack.storage.datastore.util.NexentaStorAppliance.ListOfIscsiTargetsNmsResponse; +import static org.apache.cloudstack.storage.datastore.util.NexentaStorAppliance.CreateIscsiTargetRequestParams; +import static org.apache.cloudstack.storage.datastore.util.NexentaStorAppliance.ListOfStringsNmsResponse; +import static org.apache.cloudstack.storage.datastore.util.NexentaStorAppliance.IntegerNmsResponse; +import static org.apache.cloudstack.storage.datastore.util.NexentaStorAppliance.LuParams; +import static org.apache.cloudstack.storage.datastore.util.NexentaStorAppliance.MappingEntry; +import static org.apache.cloudstack.storage.datastore.util.NexentaStorAppliance.AddMappingEntryNmsResponse; +import static org.apache.cloudstack.storage.datastore.util.NexentaNmsClient.NmsResponse; + + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.HashMap; +import java.util.LinkedList; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.runners.MockitoJUnitRunner; + +import com.cloud.utils.exception.CloudRuntimeException; + +@RunWith(MockitoJUnitRunner.class) +public class NexentaStorApplianceTest { + private NexentaNmsClient client; + + private NexentaStorAppliance appliance; + + @Rule + public ExpectedException exception = ExpectedException.none(); + + @Before + public void init() { + final String url = "nmsUrl=https://admin:nexenta@10.1.3.182:8457;volume=cloudstack;storageType=iscsi"; + NexentaUtil.NexentaPluginParameters parameters = NexentaUtil.parseNexentaPluginUrl(url); + //client = new NexentaNmsClient(parameters.getNmsUrl()); + client = mock(NexentaNmsClient.class); + appliance = new NexentaStorAppliance(client, parameters); + } + + @Test + public void testIsIscsiTargetExists() { + final String targetName = NexentaStorAppliance.getTargetName("volume1"); + + when(client.execute(ListOfIscsiTargetsNmsResponse.class, "stmf", "list_targets")).thenReturn(null); + assertFalse(appliance.isIscsiTargetExists(targetName)); + + when(client.execute(ListOfIscsiTargetsNmsResponse.class, "stmf", "list_targets")).thenReturn(new ListOfIscsiTargetsNmsResponse()); + assertFalse(appliance.isIscsiTargetExists(targetName)); + + final HashMap result = new HashMap(); + + result.put("any", new IscsiTarget("Online", "iSCSI", "any", "0", "-", "iscsit")); + when(client.execute(ListOfIscsiTargetsNmsResponse.class, "stmf", "list_targets")).thenReturn(new ListOfIscsiTargetsNmsResponse(result)); + assertFalse(appliance.isIscsiTargetExists(targetName)); + + result.put(targetName, new IscsiTarget("Online", "iSCSI", targetName, "0", "-", "iscsit")); + when(client.execute(ListOfIscsiTargetsNmsResponse.class, "stmf", "list_targets")).thenReturn(new ListOfIscsiTargetsNmsResponse(result)); + assertTrue(appliance.isIscsiTargetExists(targetName)); + } + + final static String ISCSI_TARGET_ALREADY_CONFIGURED_ERROR = "Unable to create iscsi target\\n iSCSI target %s already configured\\n itadm create-target failed with error " + + "17\\n"; + + @Test + public void testCreateIscsiTarget() { + final String targetName = NexentaStorAppliance.getTargetName("volume1"); + final CreateIscsiTargetRequestParams p = new CreateIscsiTargetRequestParams(targetName); + + appliance.createIscsiTarget(targetName); + verify(client).execute(NmsResponse.class, "iscsitarget", "create_target", p); + + final String error = String.format(ISCSI_TARGET_ALREADY_CONFIGURED_ERROR, targetName); + when(client.execute(NmsResponse.class, "iscsitarget", "create_target", p)).thenThrow(new CloudRuntimeException(error)); + appliance.createIscsiTarget(targetName); + } + + @Test + public void testCreateIscsiTargetFails() { + final String targetName = NexentaStorAppliance.getTargetName("volume1"); + final CreateIscsiTargetRequestParams p = new CreateIscsiTargetRequestParams(targetName); + exception.expect(CloudRuntimeException.class); + exception.expectMessage("any exception"); + when(client.execute(NmsResponse.class, "iscsitarget", "create_target", p)).thenThrow(new CloudRuntimeException("any exception")); + appliance.createIscsiTarget(targetName); + } + + @Test + public void testIsIscsiTargetGroupExists() { + final String targetGroup = NexentaStorAppliance.getTargetGroupName("volume1"); + + when(client.execute(ListOfStringsNmsResponse.class, "stmf", "list_targetgroups")).thenReturn(null); + assertFalse(appliance.isIscsiTargetGroupExists(targetGroup)); + + when(client.execute(ListOfIscsiTargetsNmsResponse.class, "stmf", "list_targetgroups")).thenReturn(new ListOfIscsiTargetsNmsResponse()); + assertFalse(appliance.isIscsiTargetGroupExists(targetGroup)); + + LinkedList result = new LinkedList(); + + result.add("any"); + when(client.execute(ListOfStringsNmsResponse.class, "stmf", "list_targetgroups")).thenReturn(new ListOfStringsNmsResponse(result)); + assertFalse(appliance.isIscsiTargetGroupExists(targetGroup)); + + result.add(targetGroup); + when(client.execute(ListOfStringsNmsResponse.class, "stmf", "list_targetgroups")).thenReturn(new ListOfStringsNmsResponse(result)); + assertTrue(appliance.isIscsiTargetGroupExists(targetGroup)); + } + + final static String ISCSI_TARGET_GROUP_EXISTS_ERROR = "Unable to create targetgroup: stmfadm: %s: already exists\\n"; + + @Test + public void testCreateIscsiTargetGroup() { + final String targetGroupName = NexentaStorAppliance.getTargetGroupName("volume1"); + + appliance.createIscsiTargetGroup(targetGroupName); + verify(client).execute(NmsResponse.class, "stmf", "create_targetgroup", targetGroupName); + + final String error = String.format(ISCSI_TARGET_GROUP_EXISTS_ERROR, targetGroupName); + when(client.execute(NmsResponse.class, "stmf", "create_targetgroup", targetGroupName)).thenThrow(new CloudRuntimeException(error)); + appliance.createIscsiTargetGroup(targetGroupName); + } + + @Test + public void testCreateIscsiTargetGroupFails() { + final String targetGroupName = NexentaStorAppliance.getTargetGroupName("volume1"); + when(client.execute(NmsResponse.class, "stmf", "create_targetgroup", targetGroupName)).thenThrow(new CloudRuntimeException("any exception")); + exception.expect(CloudRuntimeException.class); + exception.expectMessage("any exception"); + appliance.createIscsiTargetGroup(targetGroupName); + } + + @Test + public void testIsMemberOfTargetGroup() { + final String targetName = NexentaStorAppliance.getTargetName("volume1"); + final String targetGroupName = NexentaStorAppliance.getTargetGroupName("volume1"); + + when(client.execute(ListOfStringsNmsResponse.class, "stmf", "list_targetgroup_members", targetGroupName)).thenReturn(null); + assertFalse(appliance.isTargetMemberOfTargetGroup(targetGroupName, targetName)); + + when(client.execute(ListOfStringsNmsResponse.class, "stmf", "list_targetgroup_members", targetGroupName)).thenReturn(new ListOfStringsNmsResponse()); + assertFalse(appliance.isTargetMemberOfTargetGroup(targetGroupName, targetName)); + + LinkedList result = new LinkedList(); + + result.add("any"); + when(client.execute(ListOfStringsNmsResponse.class, "stmf", "list_targetgroup_members", targetGroupName)).thenReturn(new ListOfStringsNmsResponse(result)); + assertFalse(appliance.isTargetMemberOfTargetGroup(targetGroupName, targetName)); + + result.add(targetName); + when(client.execute(ListOfStringsNmsResponse.class, "stmf", "list_targetgroup_members", targetGroupName)).thenReturn(new ListOfStringsNmsResponse(result)); + assertTrue(appliance.isTargetMemberOfTargetGroup(targetGroupName, targetName)); + } + + @Test + public void testAddTargetGroupMember() { + final String targetName = NexentaStorAppliance.getTargetName("volume1"); + final String targetGroupName = NexentaStorAppliance.getTargetGroupName("volume1"); + + appliance.addTargetGroupMember(targetGroupName, targetName); + verify(client).execute(NmsResponse.class, "stmf", "add_targetgroup_member", targetGroupName, targetName); + + String error = String.format(ISCSI_TARGET_ALREADY_EXISTS_IN_TARGET_GROUP_ERROR, targetName); + when(client.execute(NmsResponse.class, "stmf", "add_targetgroup_member", targetGroupName, targetName)).thenThrow(new CloudRuntimeException(error)); + appliance.addTargetGroupMember(targetGroupName, targetName); + } + + final static String ISCSI_TARGET_ALREADY_EXISTS_IN_TARGET_GROUP_ERROR = "Unable to add member to targetgroup: stmfadm: %s: already exists\\n"; + + @Test + public void testAddTargetGroupMemberFails() { + final String targetName = NexentaStorAppliance.getTargetName("volume1"); + final String targetGroupName = NexentaStorAppliance.getTargetGroupName("volume1"); + + when(client.execute(NmsResponse.class, "stmf", "add_targetgroup_member", targetGroupName, targetName)).thenThrow(new CloudRuntimeException("any exception")); + exception.expect(CloudRuntimeException.class); + exception.expectMessage("any exception"); + appliance.addTargetGroupMember(targetGroupName, targetName); + } + + @Test + public void testIsLuExists() { + final String volumeName = appliance.getVolumeName("volume1"); + when(client.execute(IntegerNmsResponse.class, "scsidisk", "lu_exists", volumeName)).thenReturn(null); + assertFalse(appliance.isLuExists(volumeName)); + + when(client.execute(IntegerNmsResponse.class, "scsidisk", "lu_exists", volumeName)).thenReturn(new IntegerNmsResponse(0)); + assertFalse(appliance.isLuExists(volumeName)); + + when(client.execute(IntegerNmsResponse.class, "scsidisk", "lu_exists", volumeName)).thenReturn(new IntegerNmsResponse(1)); + assertTrue(appliance.isLuExists(volumeName)); + + when(client.execute(IntegerNmsResponse.class, "scsidisk", "lu_exists", volumeName)).thenThrow(new CloudRuntimeException("does not exist")); + assertFalse(appliance.isLuExists(volumeName)); + } + + @Test + public void testIsLuExistsFails() { + final String volumeName = appliance.getVolumeName("volume1"); + exception.expect(CloudRuntimeException.class); + exception.expectMessage("any exception"); + when(client.execute(IntegerNmsResponse.class, "scsidisk", "lu_exists", volumeName)).thenThrow(new CloudRuntimeException("any exception")); + assertTrue(appliance.isLuExists(volumeName)); + } + + final static String CREATE_LU_IN_USE_ERROR = "Unable to create lu with " + + "zvol '%s':\\n stmfadm: filename /dev/zvol/rdsk/%s: in use\\n"; + + @Test + public void testCreateLu() { + final String luName = appliance.getVolumeName("volume1"); + final LuParams p = new LuParams(); + + appliance.createLu(luName); + verify(client).execute(NmsResponse.class, "scsidisk", "create_lu", luName, p); + + String error = String.format(CREATE_LU_IN_USE_ERROR, luName, luName); + when(client.execute(NmsResponse.class, "scsidisk", "create_lu", luName, p)).thenThrow(new CloudRuntimeException(error)); + appliance.createLu(luName); + } + + @Test + public void testCreateLuFails() { + final String luName = appliance.getVolumeName("volume1"); + when(client.execute(NmsResponse.class, "scsidisk", "create_lu", luName, new LuParams())).thenThrow(new CloudRuntimeException("any exception")); + exception.expect(CloudRuntimeException.class); + exception.expectMessage("any exception"); + appliance.createLu(luName); + } + + final static String ZVOL_DOES_NOT_EXISTS_ERROR = "Zvol '%s' does not exist"; + + @Test + public void testIsLuShared() { + final String luName = appliance.getVolumeName("volume1"); + when(client.execute(IntegerNmsResponse.class, "scsidisk", "lu_shared", luName)).thenReturn(null); + assertFalse(appliance.isLuShared(luName)); + + when(client.execute(IntegerNmsResponse.class, "scsidisk", "lu_shared", luName)).thenReturn(new IntegerNmsResponse(0)); + assertFalse(appliance.isLuShared(luName)); + + when(client.execute(IntegerNmsResponse.class, "scsidisk", "lu_shared", luName)).thenReturn(new IntegerNmsResponse(1)); + assertTrue(appliance.isLuShared(luName)); + + final String error = String.format(ZVOL_DOES_NOT_EXISTS_ERROR, luName); + when(client.execute(IntegerNmsResponse.class, "scsidisk", "lu_shared", luName)).thenThrow(new CloudRuntimeException(error)); + assertFalse(appliance.isLuShared(luName)); + } + + @Test + public void testIsLuSharedFails() { + final String luName = appliance.getVolumeName("volume1"); + when(client.execute(IntegerNmsResponse.class, "scsidisk", "lu_shared", luName)).thenThrow(new CloudRuntimeException("any exception")); + exception.expect(CloudRuntimeException.class); + exception.expectMessage("any exception"); + appliance.isLuShared(luName); + } + + final static String ADD_LUN_MAPPING_ENTRY_ERROR = "(rc: 256) Unable to " + + "add view to zvol '%s':\\n add-view: view already exists\\n"; + + @Test + public void testAddLuMappingEntry() { + final String luName = appliance.getVolumeName("volume1"); + final String targetGroupName = NexentaStorAppliance.getTargetGroupName("volume1"); + final MappingEntry mappingEntry = new MappingEntry(targetGroupName, "0"); + appliance.addLuMappingEntry(luName, targetGroupName); + verify(client).execute(AddMappingEntryNmsResponse.class, "scsidisk", "add_lun_mapping_entry", luName, mappingEntry); + + String error = String.format(ADD_LUN_MAPPING_ENTRY_ERROR, luName); + when(client.execute(AddMappingEntryNmsResponse.class, "scsidisk", "add_lun_mapping_entry", luName, mappingEntry)).thenThrow(new CloudRuntimeException(error)); + appliance.addLuMappingEntry(luName, targetGroupName); + } + + @Test + public void testAddLuMappingEntryTest() { + final String luName = appliance.getVolumeName("volume1"); + final String targetGroupName = NexentaStorAppliance.getTargetGroupName("volume1"); + final MappingEntry mappingEntry = new MappingEntry(targetGroupName, "0"); + when(client.execute(AddMappingEntryNmsResponse.class, "scsidisk", "add_lun_mapping_entry", luName, mappingEntry)).thenThrow(new CloudRuntimeException("any exception")); + exception.expect(CloudRuntimeException.class); + exception.expectMessage("any exception"); + appliance.addLuMappingEntry(luName, targetGroupName); + } + + @Test + public void testCreateIscsiVolume() { + final String volumeName = "volume1"; + final Long volumeSize = Long.valueOf(1); + appliance.createIscsiVolume(volumeName, volumeSize); + } + + @Test + public void testDeleteIscsiVolume() { + final String volumeName = appliance.getVolumeName("volume1"); + appliance.deleteIscsiVolume(volumeName); + verify(client).execute(NmsResponse.class, "zvol", "destroy", volumeName, ""); + + when(client.execute(NmsResponse.class, "zvol", "destroy", volumeName, "")).thenThrow(new CloudRuntimeException(String.format("Zvol '%s' does not exist", volumeName))); + appliance.deleteIscsiVolume(volumeName); + } + + @Test + public void testDeleteIscsiVolumeFails() { + final String volumeName = appliance.getVolumeName("volume1"); + exception.expect(CloudRuntimeException.class); + exception.expectMessage("any exception"); + when(client.execute(NmsResponse.class, "zvol", "destroy", volumeName, "")).thenThrow(new CloudRuntimeException("any exception")); + appliance.deleteIscsiVolume(volumeName); + } +} diff --git a/plugins/storage/volume/nexenta/test/org/apache/cloudstack/storage/datastore/util/NexentaUtilTest.java b/plugins/storage/volume/nexenta/test/org/apache/cloudstack/storage/datastore/util/NexentaUtilTest.java new file mode 100644 index 00000000000..8f4498557c1 --- /dev/null +++ b/plugins/storage/volume/nexenta/test/org/apache/cloudstack/storage/datastore/util/NexentaUtilTest.java @@ -0,0 +1,135 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.cloudstack.storage.datastore.util; + +import static junit.framework.Assert.assertNull; +import static org.junit.Assert.assertEquals; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import com.cloud.storage.Storage; + +@RunWith(JUnit4.class) +public class NexentaUtilTest { + @Rule + public ExpectedException exception = ExpectedException.none(); + + @Test + public void testParseNmsUrl() { + NexentaNmsUrl c; + + c = NexentaUtil.parseNmsUrl("auto://192.168.1.1/"); + assertEquals(c.toString(), "auto://admin:nexenta@192.168.1.1:2000/rest/nms/"); + assertEquals(c.getSchema(), "http"); + + c = NexentaUtil.parseNmsUrl("http://192.168.1.1/"); + assertEquals(c.toString(), "http://admin:nexenta@192.168.1.1:2000/rest/nms/"); + + c = NexentaUtil.parseNmsUrl("http://192.168.1.1:8080"); + assertEquals(c.toString(), "http://admin:nexenta@192.168.1.1:8080/rest/nms/"); + + c = NexentaUtil.parseNmsUrl("https://root@192.168.1.1:8080"); + assertEquals(c.toString(), "https://root:nexenta@192.168.1.1:8080/rest/nms/"); + + c = NexentaUtil.parseNmsUrl("https://root:password@192.168.1.1:8080"); + assertEquals(c.toString(), "https://root:password@192.168.1.1:8080/rest/nms/"); + } + + @Test + public void testGetStorageType() { + assertEquals(NexentaUtil.getStorageType("iscsi"), Storage.StoragePoolType.Iscsi); + assertEquals(NexentaUtil.getStorageType("nfs"), Storage.StoragePoolType.NetworkFilesystem); + assertEquals(NexentaUtil.getStorageType("any"), Storage.StoragePoolType.Iscsi); + } + + @Test + public void testParseNexentaPluginUrl() { + String url = "nmsUrl=http://admin:nexenta@192.168.1.1:2000;"; + + NexentaUtil.NexentaPluginParameters parameters; + parameters = NexentaUtil.parseNexentaPluginUrl(url); + assertEquals(parameters.getNmsUrl().toString(), "http://admin:nexenta@192.168.1.1:2000/rest/nms/"); + assertNull(parameters.getVolume()); + assertEquals(parameters.getStorageType(), Storage.StoragePoolType.Iscsi); + assertEquals(parameters.getStorageHost(), "192.168.1.1"); + assertEquals((int) parameters.getStoragePort(), NexentaUtil.DEFAULT_ISCSI_TARGET_PORTAL_PORT); + assertNull(parameters.getStoragePath()); + assertEquals((boolean) parameters.getSparseVolumes(), false); + assertEquals(parameters.getVolumeBlockSize(), "8K"); + + url += "volume=cloudstack"; + parameters = NexentaUtil.parseNexentaPluginUrl(url); + assertEquals(parameters.getNmsUrl().toString(), "http://admin:nexenta@192.168.1.1:2000/rest/nms/"); + assertEquals(parameters.getVolume(), "cloudstack"); + + url += "/;"; + parameters = NexentaUtil.parseNexentaPluginUrl(url); + assertEquals(parameters.getVolume(), "cloudstack"); + + url += "storageType="; + parameters = NexentaUtil.parseNexentaPluginUrl(url + "nfs"); + assertEquals(parameters.getStorageType(), Storage.StoragePoolType.NetworkFilesystem); + assertEquals((int) parameters.getStoragePort(), NexentaUtil.DEFAULT_NFS_PORT); + + parameters = NexentaUtil.parseNexentaPluginUrl(url + "iscsi"); + assertEquals(parameters.getStorageType(), Storage.StoragePoolType.Iscsi); + assertEquals((int) parameters.getStoragePort(), NexentaUtil.DEFAULT_ISCSI_TARGET_PORTAL_PORT); + + url += "nfs;storageHost=192.168.1.2;"; + parameters = NexentaUtil.parseNexentaPluginUrl(url); + assertEquals(parameters.getStorageHost(), "192.168.1.2"); + + url += "storagePort=3000;"; + parameters = NexentaUtil.parseNexentaPluginUrl(url); + assertEquals((int) parameters.getStoragePort(), 3000); + + url += "storagePath=/volumes/cloudstack;"; + parameters = NexentaUtil.parseNexentaPluginUrl(url); + assertEquals(parameters.getStoragePath(), "/volumes/cloudstack"); + + url += "sparseVolumes=true;"; + parameters = NexentaUtil.parseNexentaPluginUrl(url); + assertEquals(parameters.getSparseVolumes(), Boolean.TRUE); + + url += "volumeBlockSize=128K;"; + parameters = NexentaUtil.parseNexentaPluginUrl(url); + assertEquals(parameters.getVolumeBlockSize(), "128K"); + + url += "unknownParameter=value;"; // NOTE: exception should not be raised + parameters = NexentaUtil.parseNexentaPluginUrl(url); + + assertEquals(parameters.getNmsUrl().toString(), "http://admin:nexenta@192.168.1.1:2000/rest/nms/"); + assertEquals(parameters.getVolume(), "cloudstack"); + assertEquals(parameters.getStorageType(), Storage.StoragePoolType.NetworkFilesystem); + assertEquals(parameters.getStorageHost(), "192.168.1.2"); + assertEquals((int) parameters.getStoragePort(), 3000); + assertEquals(parameters.getStoragePath(), "/volumes/cloudstack"); + assertEquals(parameters.getSparseVolumes(), Boolean.TRUE); + assertEquals(parameters.getVolumeBlockSize(), "128K"); + + exception.expect(RuntimeException.class); + exception.expectMessage("Invalid URL format"); + + NexentaUtil.parseNexentaPluginUrl(url + "invalidParameter"); + } +} diff --git a/plugins/storage/volume/sample/src/org/apache/cloudstack/storage/datastore/driver/SamplePrimaryDataStoreDriverImpl.java b/plugins/storage/volume/sample/src/org/apache/cloudstack/storage/datastore/driver/SamplePrimaryDataStoreDriverImpl.java index 5e5a9340486..1f9a128727e 100644 --- a/plugins/storage/volume/sample/src/org/apache/cloudstack/storage/datastore/driver/SamplePrimaryDataStoreDriverImpl.java +++ b/plugins/storage/volume/sample/src/org/apache/cloudstack/storage/datastore/driver/SamplePrimaryDataStoreDriverImpl.java @@ -42,6 +42,9 @@ import org.apache.cloudstack.storage.datastore.DataObjectManager; import com.cloud.agent.api.Answer; import com.cloud.agent.api.to.DataStoreTO; import com.cloud.agent.api.to.DataTO; +import com.cloud.host.Host; +import com.cloud.storage.StoragePool; +import com.cloud.storage.Volume; import com.cloud.storage.dao.StoragePoolHostDao; import com.cloud.utils.exception.CloudRuntimeException; @@ -78,6 +81,17 @@ public class SamplePrimaryDataStoreDriverImpl implements PrimaryDataStoreDriver return null; } + @Override + public boolean connectVolumeToHost(VolumeInfo volumeInfo, Host host, DataStore dataStore) { return false; } + + @Override + public void disconnectVolumeFromHost(VolumeInfo volumeInfo, Host host, DataStore dataStore) {} + + @Override + public long getVolumeSizeIncludingHypervisorSnapshotReserve(Volume volume, StoragePool pool) { + return volume.getSize(); + } + private class CreateVolumeContext extends AsyncRpcContext { private final DataObject volume; diff --git a/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/driver/SolidfirePrimaryDataStoreDriver.java b/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/driver/SolidfirePrimaryDataStoreDriver.java index d85ed0da820..014413d3452 100644 --- a/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/driver/SolidfirePrimaryDataStoreDriver.java +++ b/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/driver/SolidfirePrimaryDataStoreDriver.java @@ -17,8 +17,10 @@ package org.apache.cloudstack.storage.datastore.driver; import java.text.NumberFormat; +import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.UUID; import javax.inject.Inject; @@ -44,8 +46,15 @@ import com.cloud.agent.api.Answer; import com.cloud.agent.api.to.DataObjectType; import com.cloud.agent.api.to.DataStoreTO; import com.cloud.agent.api.to.DataTO; +import com.cloud.dc.ClusterDetailsVO; +import com.cloud.dc.ClusterDetailsDao; import com.cloud.dc.dao.DataCenterDao; +import com.cloud.host.Host; +import com.cloud.host.HostVO; +import com.cloud.host.dao.HostDao; import com.cloud.storage.Storage.StoragePoolType; +import com.cloud.storage.StoragePool; +import com.cloud.storage.Volume; import com.cloud.storage.VolumeVO; import com.cloud.storage.dao.VolumeDao; import com.cloud.storage.dao.VolumeDetailsDao; @@ -53,22 +62,18 @@ import com.cloud.user.AccountDetailVO; import com.cloud.user.AccountDetailsDao; import com.cloud.user.AccountVO; import com.cloud.user.dao.AccountDao; +import com.cloud.utils.exception.CloudRuntimeException; public class SolidfirePrimaryDataStoreDriver implements PrimaryDataStoreDriver { - @Inject - private PrimaryDataStoreDao _storagePoolDao; - @Inject - private StoragePoolDetailsDao _storagePoolDetailsDao; - @Inject - private VolumeDao _volumeDao; - @Inject - private VolumeDetailsDao _volumeDetailsDao; - @Inject - private DataCenterDao _zoneDao; - @Inject - private AccountDao _accountDao; - @Inject - private AccountDetailsDao _accountDetailsDao; + @Inject private PrimaryDataStoreDao _storagePoolDao; + @Inject private StoragePoolDetailsDao _storagePoolDetailsDao; + @Inject private VolumeDao _volumeDao; + @Inject private VolumeDetailsDao _volumeDetailsDao; + @Inject private DataCenterDao _zoneDao; + @Inject private AccountDao _accountDao; + @Inject private AccountDetailsDao _accountDetailsDao; + @Inject private ClusterDetailsDao _clusterDetailsDao; + @Inject private HostDao _hostDao; @Override public Map getCapabilities() { @@ -147,25 +152,35 @@ public class SolidfirePrimaryDataStoreDriver implements PrimaryDataStoreDriver { } private void updateCsDbWithAccountInfo(long csAccountId, SolidFireUtil.SolidFireAccount sfAccount) { - AccountDetailVO accountDetails = new AccountDetailVO(csAccountId, SolidFireUtil.ACCOUNT_ID, String.valueOf(sfAccount.getId())); + AccountDetailVO accountDetail = new AccountDetailVO(csAccountId, + SolidFireUtil.ACCOUNT_ID, + String.valueOf(sfAccount.getId())); - _accountDetailsDao.persist(accountDetails); + _accountDetailsDao.persist(accountDetail); - accountDetails = new AccountDetailVO(csAccountId, SolidFireUtil.CHAP_INITIATOR_USERNAME, String.valueOf(sfAccount.getName())); + accountDetail = new AccountDetailVO(csAccountId, + SolidFireUtil.CHAP_INITIATOR_USERNAME, + String.valueOf(sfAccount.getName())); - _accountDetailsDao.persist(accountDetails); + _accountDetailsDao.persist(accountDetail); - accountDetails = new AccountDetailVO(csAccountId, SolidFireUtil.CHAP_INITIATOR_SECRET, String.valueOf(sfAccount.getInitiatorSecret())); + accountDetail = new AccountDetailVO(csAccountId, + SolidFireUtil.CHAP_INITIATOR_SECRET, + String.valueOf(sfAccount.getInitiatorSecret())); - _accountDetailsDao.persist(accountDetails); + _accountDetailsDao.persist(accountDetail); - accountDetails = new AccountDetailVO(csAccountId, SolidFireUtil.CHAP_TARGET_USERNAME, sfAccount.getName()); + accountDetail = new AccountDetailVO(csAccountId, + SolidFireUtil.CHAP_TARGET_USERNAME, + sfAccount.getName()); - _accountDetailsDao.persist(accountDetails); + _accountDetailsDao.persist(accountDetail); - accountDetails = new AccountDetailVO(csAccountId, SolidFireUtil.CHAP_TARGET_SECRET, sfAccount.getTargetSecret()); + accountDetail = new AccountDetailVO(csAccountId, + SolidFireUtil.CHAP_TARGET_SECRET, + sfAccount.getTargetSecret()); - _accountDetailsDao.persist(accountDetails); + _accountDetailsDao.persist(accountDetail); } private class ChapInfoImpl implements ChapInfo { @@ -202,6 +217,12 @@ public class SolidfirePrimaryDataStoreDriver implements PrimaryDataStoreDriver { } } + @Override + public ChapInfo getChapInfo(VolumeInfo volumeInfo) { + return null; + } + + /* @Override public ChapInfo getChapInfo(VolumeInfo volumeInfo) { long accountId = volumeInfo.getAccountId(); @@ -214,25 +235,276 @@ public class SolidfirePrimaryDataStoreDriver implements PrimaryDataStoreDriver { String chapInitiatorSecret = accountDetail.getValue(); - StoragePoolDetailVO storagePoolDetail = _storagePoolDetailsDao.findDetail(volumeInfo.getPoolId(), SolidFireUtil.USE_MUTUAL_CHAP_FOR_VMWARE); + accountDetail = _accountDetailsDao.findDetail(accountId, SolidFireUtil.CHAP_TARGET_USERNAME); - boolean useMutualChapForVMware = new Boolean(storagePoolDetail.getValue()); + String chapTargetUsername = accountDetail.getValue(); - String chapTargetUsername = null; - String chapTargetSecret = null; + accountDetail = _accountDetailsDao.findDetail(accountId, SolidFireUtil.CHAP_TARGET_SECRET); - if (useMutualChapForVMware) { - accountDetail = _accountDetailsDao.findDetail(accountId, SolidFireUtil.CHAP_TARGET_USERNAME); - - chapTargetUsername = accountDetail.getValue(); - - accountDetail = _accountDetailsDao.findDetail(accountId, SolidFireUtil.CHAP_TARGET_SECRET); - - chapTargetSecret = accountDetail.getValue(); - } + String chapTargetSecret = accountDetail.getValue(); return new ChapInfoImpl(chapInitiatorUsername, chapInitiatorSecret, chapTargetUsername, chapTargetSecret); } + */ + + // get the VAG associated with volumeInfo's cluster, if any (ListVolumeAccessGroups) + // if the VAG exists + // update the VAG to contain all IQNs of the hosts (ModifyVolumeAccessGroup) + // if the ID of volumeInfo in not in the VAG, add it (ModifyVolumeAccessGroup) + // if the VAG doesn't exist, create it with the IQNs of the hosts and the ID of volumeInfo (CreateVolumeAccessGroup) + @Override + public boolean connectVolumeToHost(VolumeInfo volumeInfo, Host host, DataStore dataStore) + { + if (volumeInfo == null || host == null || dataStore == null) { + return false; + } + + long sfVolumeId = Long.parseLong(volumeInfo.getFolder()); + long clusterId = host.getClusterId(); + long storagePoolId = dataStore.getId(); + + ClusterDetailsVO clusterDetail = _clusterDetailsDao.findDetail(clusterId, getVagKey(storagePoolId)); + + String vagId = clusterDetail != null ? clusterDetail.getValue() : null; + + List hosts = _hostDao.findByClusterId(clusterId); + + if (!hostsSupport_iScsi(hosts)) { + return false; + } + + SolidFireConnection sfConnection = getSolidFireConnection(storagePoolId); + + if (vagId != null) { + SolidFireUtil.SolidFireVag sfVag = SolidFireUtil.getSolidFireVag(sfConnection.getManagementVip(), sfConnection.getManagementPort(), + sfConnection.getClusterAdminUsername(), sfConnection.getClusterAdminPassword(), Long.parseLong(vagId)); + + String[] hostIqns = getNewHostIqns(sfVag.getInitiators(), getIqnsFromHosts(hosts)); + long[] volumeIds = getNewVolumeIds(sfVag.getVolumeIds(), sfVolumeId, true); + + SolidFireUtil.modifySolidFireVag(sfConnection.getManagementVip(), sfConnection.getManagementPort(), + sfConnection.getClusterAdminUsername(), sfConnection.getClusterAdminPassword(), sfVag.getId(), + hostIqns, volumeIds); + } + else { + long lVagId; + + try { + lVagId = SolidFireUtil.createSolidFireVag(sfConnection.getManagementVip(), sfConnection.getManagementPort(), + sfConnection.getClusterAdminUsername(), sfConnection.getClusterAdminPassword(), "CloudStack-" + UUID.randomUUID().toString(), + getIqnsFromHosts(hosts), new long[] { sfVolumeId }); + } + catch (Exception ex) { + String iqnInVagAlready = "Exceeded maximum number of Volume Access Groups per initiator"; + + if (!ex.getMessage().contains(iqnInVagAlready)) { + throw new CloudRuntimeException(ex.getMessage()); + } + + // getCompatibleVag throws an exception if an existing VAG can't be located + SolidFireUtil.SolidFireVag sfVag = getCompatibleVag(hosts, sfConnection); + + long[] volumeIds = getNewVolumeIds(sfVag.getVolumeIds(), sfVolumeId, true); + + SolidFireUtil.modifySolidFireVag(sfConnection.getManagementVip(), sfConnection.getManagementPort(), + sfConnection.getClusterAdminUsername(), sfConnection.getClusterAdminPassword(), sfVag.getId(), + sfVag.getInitiators(), volumeIds); + + lVagId = sfVag.getId(); + } + + clusterDetail = new ClusterDetailsVO(clusterId, getVagKey(storagePoolId), String.valueOf(lVagId)); + + _clusterDetailsDao.persist(clusterDetail); + } + + return true; + } + + // this method takes in a collection of hosts and tries to find an existing VAG that has all three of them in it + // if successful, the VAG is returned; else, a CloudRuntimeException is thrown and this issue should be corrected by an admin + private SolidFireUtil.SolidFireVag getCompatibleVag(List hosts, SolidFireConnection sfConnection) { + List sfVags = SolidFireUtil.getAllSolidFireVags(sfConnection.getManagementVip(), sfConnection.getManagementPort(), + sfConnection.getClusterAdminUsername(), sfConnection.getClusterAdminPassword()); + + if (sfVags != null) { + List hostIqns = new ArrayList(); + + // where the method we're in is called, hosts should not be null + for (HostVO host : hosts) { + // where the method we're in is called, host.getStorageUrl() should not be null (it actually should start with "iqn") + hostIqns.add(host.getStorageUrl().toLowerCase()); + } + + for (SolidFireUtil.SolidFireVag sfVag : sfVags) { + List lstInitiators = getStringArrayAsLowerCaseStringList(sfVag.getInitiators()); + + // lstInitiators should not be returned from getStringArrayAsLowerCaseStringList as null + if (lstInitiators.containsAll(hostIqns)) { + return sfVag; + } + } + } + + throw new CloudRuntimeException("Unable to locate the appropriate SolidFire Volume Access Group"); + } + + private List getStringArrayAsLowerCaseStringList(String[] aString) { + List lstLowerCaseString = new ArrayList(); + + if (aString != null) { + for (String str : aString) { + if (str != null) { + lstLowerCaseString.add(str.toLowerCase()); + } + } + } + + return lstLowerCaseString; + } + + // get the VAG associated with volumeInfo's cluster, if any (ListVolumeAccessGroups) // might not exist if using CHAP + // if the VAG exists + // remove the ID of volumeInfo from the VAG (ModifyVolumeAccessGroup) + @Override + public void disconnectVolumeFromHost(VolumeInfo volumeInfo, Host host, DataStore dataStore) + { + if (volumeInfo == null || host == null || dataStore == null) { + return; + } + + long sfVolumeId = Long.parseLong(volumeInfo.getFolder()); + long clusterId = host.getClusterId(); + long storagePoolId = dataStore.getId(); + + ClusterDetailsVO clusterDetail = _clusterDetailsDao.findDetail(clusterId, getVagKey(storagePoolId)); + + String vagId = clusterDetail != null ? clusterDetail.getValue() : null; + + if (vagId != null) { + List hosts = _hostDao.findByClusterId(clusterId); + + SolidFireConnection sfConnection = getSolidFireConnection(storagePoolId); + + SolidFireUtil.SolidFireVag sfVag = SolidFireUtil.getSolidFireVag(sfConnection.getManagementVip(), sfConnection.getManagementPort(), + sfConnection.getClusterAdminUsername(), sfConnection.getClusterAdminPassword(), Long.parseLong(vagId)); + + String[] hostIqns = getNewHostIqns(sfVag.getInitiators(), getIqnsFromHosts(hosts)); + long[] volumeIds = getNewVolumeIds(sfVag.getVolumeIds(), sfVolumeId, false); + + SolidFireUtil.modifySolidFireVag(sfConnection.getManagementVip(), sfConnection.getManagementPort(), + sfConnection.getClusterAdminUsername(), sfConnection.getClusterAdminPassword(), sfVag.getId(), + hostIqns, volumeIds); + } + } + + private boolean hostsSupport_iScsi(List hosts) { + if (hosts == null || hosts.size() == 0) { + return false; + } + + for (Host host : hosts) { + if (host == null || host.getStorageUrl() == null || host.getStorageUrl().trim().length() == 0 || !host.getStorageUrl().startsWith("iqn")) { + return false; + } + } + + return true; + } + + private String[] getNewHostIqns(String[] currentIqns, String[] newIqns) { + List lstIqns = new ArrayList(); + + if (currentIqns != null) { + for (String currentIqn : currentIqns) { + lstIqns.add(currentIqn); + } + } + + if (newIqns != null) { + for (String newIqn : newIqns) { + if (!lstIqns.contains(newIqn)) { + lstIqns.add(newIqn); + } + } + } + + return lstIqns.toArray(new String[0]); + } + + private long[] getNewVolumeIds(long[] volumeIds, long volumeIdToAddOrRemove, boolean add) { + if (add) { + return getNewVolumeIdsAdd(volumeIds, volumeIdToAddOrRemove); + } + + return getNewVolumeIdsRemove(volumeIds, volumeIdToAddOrRemove); + } + + private long[] getNewVolumeIdsAdd(long[] volumeIds, long volumeIdToAdd) { + List lstVolumeIds = new ArrayList(); + + if (volumeIds != null) { + for (long volumeId : volumeIds) { + lstVolumeIds.add(volumeId); + } + } + + if (lstVolumeIds.contains(volumeIdToAdd)) { + return volumeIds; + } + + lstVolumeIds.add(volumeIdToAdd); + + return convertArray(lstVolumeIds); + } + + private long[] getNewVolumeIdsRemove(long[] volumeIds, long volumeIdToRemove) { + List lstVolumeIds = new ArrayList(); + + if (volumeIds != null) { + for (long volumeId : volumeIds) { + lstVolumeIds.add(volumeId); + } + } + + lstVolumeIds.remove(volumeIdToRemove); + + return convertArray(lstVolumeIds); + } + + private long[] convertArray(List items) { + if (items == null) { + return new long[0]; + } + + long[] outArray = new long[items.size()]; + + for (int i = 0; i < items.size(); i++) { + Long value = items.get(i); + + outArray[i] = value; + } + + return outArray; + } + + private String getVagKey(long storagePoolId) { + return "sfVolumeAccessGroup_" + storagePoolId; + } + + private String[] getIqnsFromHosts(List hosts) { + if (hosts == null || hosts.size() == 0) { + throw new CloudRuntimeException("There do not appear to be any hosts in this cluster."); + } + + List lstIqns = new ArrayList(); + + for (Host host : hosts) { + lstIqns.add(host.getStorageUrl()); + } + + return lstIqns.toArray(new String[0]); + } private long getDefaultMinIops(long storagePoolId) { StoragePoolDetailVO storagePoolDetail = _storagePoolDetailsDao.findDetail(storagePoolId, SolidFireUtil.CLUSTER_DEFAULT_MIN_IOPS); @@ -284,8 +556,20 @@ public class SolidfirePrimaryDataStoreDriver implements PrimaryDataStoreDriver { iops = new Iops(volumeInfo.getMinIops(), volumeInfo.getMaxIops(), getDefaultBurstIops(storagePoolId, volumeInfo.getMaxIops())); } - long volumeSize = volumeInfo.getSize(); - Integer hypervisorSnapshotReserve = volumeInfo.getHypervisorSnapshotReserve(); + long volumeSize = getVolumeSizeIncludingHypervisorSnapshotReserve(volumeInfo, _storagePoolDao.findById(storagePoolId)); + + long sfVolumeId = SolidFireUtil.createSolidFireVolume(mVip, mPort, clusterAdminUsername, clusterAdminPassword, + getSolidFireVolumeName(volumeInfo.getName()), sfAccountId, volumeSize, true, + NumberFormat.getInstance().format(volumeInfo.getSize()), + iops.getMinIops(), iops.getMaxIops(), iops.getBurstIops()); + + return SolidFireUtil.getSolidFireVolume(mVip, mPort, clusterAdminUsername, clusterAdminPassword, sfVolumeId); + } + + @Override + public long getVolumeSizeIncludingHypervisorSnapshotReserve(Volume volume, StoragePool pool) { + long volumeSize = volume.getSize(); + Integer hypervisorSnapshotReserve = volume.getHypervisorSnapshotReserve(); if (hypervisorSnapshotReserve != null) { if (hypervisorSnapshotReserve < 25) { @@ -295,11 +579,7 @@ public class SolidfirePrimaryDataStoreDriver implements PrimaryDataStoreDriver { volumeSize += volumeSize * (hypervisorSnapshotReserve / 100f); } - long sfVolumeId = - SolidFireUtil.createSolidFireVolume(mVip, mPort, clusterAdminUsername, clusterAdminPassword, getSolidFireVolumeName(volumeInfo.getName()), sfAccountId, - volumeSize, true, NumberFormat.getNumberInstance().format(volumeInfo.getSize().toString()), iops.getMinIops(), iops.getMaxIops(), iops.getBurstIops()); - - return SolidFireUtil.getSolidFireVolume(mVip, mPort, clusterAdminUsername, clusterAdminPassword, sfVolumeId); + return volumeSize; } private String getSolidFireVolumeName(String strCloudStackVolumeName) { @@ -356,11 +636,12 @@ public class SolidfirePrimaryDataStoreDriver implements PrimaryDataStoreDriver { } } - private void deleteSolidFireVolume(VolumeInfo volumeInfo, SolidFireConnection sfConnection) { + private SolidFireUtil.SolidFireVolume deleteSolidFireVolume(VolumeInfo volumeInfo, SolidFireConnection sfConnection) + { Long storagePoolId = volumeInfo.getPoolId(); if (storagePoolId == null) { - return; // this volume was never assigned to a storage pool, so no SAN volume should exist for it + return null; // this volume was never assigned to a storage pool, so no SAN volume should exist for it } String mVip = sfConnection.getManagementVip(); @@ -370,7 +651,7 @@ public class SolidfirePrimaryDataStoreDriver implements PrimaryDataStoreDriver { long sfVolumeId = Long.parseLong(volumeInfo.getFolder()); - SolidFireUtil.deleteSolidFireVolume(mVip, mPort, clusterAdminUsername, clusterAdminPassword, sfVolumeId); + return SolidFireUtil.deleteSolidFireVolume(mVip, mPort, clusterAdminUsername, clusterAdminPassword, sfVolumeId); } private String getSfAccountName(String csAccountUuid, long csAccountId) { @@ -429,7 +710,7 @@ public class SolidfirePrimaryDataStoreDriver implements PrimaryDataStoreDriver { long capacityBytes = storagePool.getCapacityBytes(); long usedBytes = storagePool.getUsedBytes(); - usedBytes += volumeInfo.getSize(); + usedBytes += sfVolume.getTotalSize(); storagePool.setUsedBytes(usedBytes > capacityBytes ? capacityBytes : usedBytes); @@ -447,6 +728,7 @@ public class SolidfirePrimaryDataStoreDriver implements PrimaryDataStoreDriver { callback.complete(result); } + /* private void deleteSolidFireAccount(long sfAccountId, SolidFireConnection sfConnection) { String mVip = sfConnection.getManagementVip(); int mPort = sfConnection.getManagementPort(); @@ -486,6 +768,7 @@ public class SolidfirePrimaryDataStoreDriver implements PrimaryDataStoreDriver { return false; } + */ @Override public void deleteAsync(DataStore dataStore, DataObject dataObject, AsyncCompletionCallback callback) { @@ -493,31 +776,31 @@ public class SolidfirePrimaryDataStoreDriver implements PrimaryDataStoreDriver { if (dataObject.getType() == DataObjectType.VOLUME) { VolumeInfo volumeInfo = (VolumeInfo)dataObject; - AccountVO account = _accountDao.findById(volumeInfo.getAccountId()); - AccountDetailVO accountDetails = _accountDetailsDao.findDetail(account.getAccountId(), SolidFireUtil.ACCOUNT_ID); - long sfAccountId = Long.parseLong(accountDetails.getValue()); + // AccountVO account = _accountDao.findById(volumeInfo.getAccountId()); + // AccountDetailVO accountDetails = _accountDetailsDao.findDetail(account.getAccountId(), SolidFireUtil.ACCOUNT_ID); + // long sfAccountId = Long.parseLong(accountDetails.getValue()); long storagePoolId = dataStore.getId(); SolidFireConnection sfConnection = getSolidFireConnection(storagePoolId); - deleteSolidFireVolume(volumeInfo, sfConnection); + SolidFireUtil.SolidFireVolume sfVolume = deleteSolidFireVolume(volumeInfo, sfConnection); _volumeDao.deleteVolumesByInstance(volumeInfo.getId()); - // if (!sfAccountHasVolume(sfAccountId, sfConnection)) { - // // delete the account from the SolidFire SAN - // deleteSolidFireAccount(sfAccountId, sfConnection); + // if (!sfAccountHasVolume(sfAccountId, sfConnection)) { + // // delete the account from the SolidFire SAN + // deleteSolidFireAccount(sfAccountId, sfConnection); // - // // delete the info in the account_details table - // // that's related to the SolidFire account - // _accountDetailsDao.deleteDetails(account.getAccountId()); - // } + // // delete the info in the account_details table + // // that's related to the SolidFire account + // _accountDetailsDao.deleteDetails(account.getAccountId()); + // } StoragePoolVO storagePool = _storagePoolDao.findById(storagePoolId); long usedBytes = storagePool.getUsedBytes(); - usedBytes -= volumeInfo.getSize(); + usedBytes -= sfVolume != null ? sfVolume.getTotalSize() : 0; storagePool.setUsedBytes(usedBytes < 0 ? 0 : usedBytes); diff --git a/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/lifecycle/SolidFirePrimaryDataStoreLifeCycle.java b/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/lifecycle/SolidFirePrimaryDataStoreLifeCycle.java index d085ddc00a0..af6a77aef24 100644 --- a/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/lifecycle/SolidFirePrimaryDataStoreLifeCycle.java +++ b/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/lifecycle/SolidFirePrimaryDataStoreLifeCycle.java @@ -171,16 +171,6 @@ public class SolidFirePrimaryDataStoreLifeCycle implements PrimaryDataStoreLifeC details.put(SolidFireUtil.CLUSTER_DEFAULT_MAX_IOPS, String.valueOf(lClusterDefaultMaxIops)); details.put(SolidFireUtil.CLUSTER_DEFAULT_BURST_IOPS_PERCENT_OF_MAX_IOPS, String.valueOf(fClusterDefaultBurstIopsPercentOfMaxIops)); - String useMutualChapForVMware = getValue(SolidFireUtil.USE_MUTUAL_CHAP_FOR_VMWARE, url); - - if (useMutualChapForVMware == null || new Boolean(useMutualChapForVMware)) { - useMutualChapForVMware = Boolean.TRUE.toString(); - } else { - useMutualChapForVMware = Boolean.FALSE.toString(); - } - - details.put(SolidFireUtil.USE_MUTUAL_CHAP_FOR_VMWARE, useMutualChapForVMware); - // this adds a row in the cloud.storage_pool table for this SolidFire cluster return dataStoreHelper.createPrimaryDataStore(parameters); } diff --git a/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/util/SolidFireUtil.java b/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/util/SolidFireUtil.java index 5f26c97b97c..3c457ba8067 100644 --- a/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/util/SolidFireUtil.java +++ b/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/util/SolidFireUtil.java @@ -75,10 +75,10 @@ public class SolidFireUtil { public static final String CHAP_TARGET_USERNAME = "chapTargetUsername"; public static final String CHAP_TARGET_SECRET = "chapTargetSecret"; - public static final String USE_MUTUAL_CHAP_FOR_VMWARE = "useMutualChapForVMware"; - - public static long createSolidFireVolume(String strSfMvip, int iSfPort, String strSfAdmin, String strSfPassword, String strSfVolumeName, long lSfAccountId, - long lTotalSize, boolean bEnable512e, final String strCloudStackVolumeSize, long lMinIops, long lMaxIops, long lBurstIops) { + public static long createSolidFireVolume(String strSfMvip, int iSfPort, String strSfAdmin, String strSfPassword, + String strSfVolumeName, long lSfAccountId, long lTotalSize, boolean bEnable512e, final String strCloudStackVolumeSize, + long lMinIops, long lMaxIops, long lBurstIops) + { final Gson gson = new GsonBuilder().create(); VolumeToCreate volumeToCreate = @@ -95,27 +95,8 @@ public class SolidFireUtil { return volumeCreateResult.result.volumeID; } - public static void deleteSolidFireVolume(String strSfMvip, int iSfPort, String strSfAdmin, String strSfPassword, long lVolumeId) { - final Gson gson = new GsonBuilder().create(); - - VolumeToDelete volumeToDelete = new VolumeToDelete(lVolumeId); - - String strVolumeToDeleteJson = gson.toJson(volumeToDelete); - - executeJsonRpc(strVolumeToDeleteJson, strSfMvip, iSfPort, strSfAdmin, strSfPassword); - } - - public static void purgeSolidFireVolume(String strSfMvip, int iSfPort, String strSfAdmin, String strSfPassword, long lVolumeId) { - final Gson gson = new GsonBuilder().create(); - - VolumeToPurge volumeToPurge = new VolumeToPurge(lVolumeId); - - String strVolumeToPurgeJson = gson.toJson(volumeToPurge); - - executeJsonRpc(strVolumeToPurgeJson, strSfMvip, iSfPort, strSfAdmin, strSfPassword); - } - - public static SolidFireVolume getSolidFireVolume(String strSfMvip, int iSfPort, String strSfAdmin, String strSfPassword, long lVolumeId) { + public static SolidFireVolume getSolidFireVolume(String strSfMvip, int iSfPort, String strSfAdmin, String strSfPassword, long lVolumeId) + { final Gson gson = new GsonBuilder().create(); VolumeToGet volumeToGet = new VolumeToGet(lVolumeId); @@ -132,8 +113,9 @@ public class SolidFireUtil { String strVolumeIqn = getVolumeIqn(volumeGetResult, lVolumeId); long lAccountId = getVolumeAccountId(volumeGetResult, lVolumeId); String strVolumeStatus = getVolumeStatus(volumeGetResult, lVolumeId); + long lTotalSize = getVolumeTotalSize(volumeGetResult, lVolumeId); - return new SolidFireVolume(lVolumeId, strVolumeName, strVolumeIqn, lAccountId, strVolumeStatus); + return new SolidFireVolume(lVolumeId, strVolumeName, strVolumeIqn, lAccountId, strVolumeStatus, lTotalSize); } public static List getSolidFireVolumesForAccountId(String strSfMvip, int iSfPort, String strSfAdmin, String strSfPassword, long lAccountId) { @@ -152,12 +134,62 @@ public class SolidFireUtil { List sfVolumes = new ArrayList(); for (VolumeGetResult.Result.Volume volume : volumeGetResult.result.volumes) { - sfVolumes.add(new SolidFireVolume(volume.volumeID, volume.name, volume.iqn, volume.accountID, volume.status)); + sfVolumes.add(new SolidFireVolume(volume.volumeID, volume.name, volume.iqn, volume.accountID, volume.status, volume.totalSize)); } return sfVolumes; } + public static List getDeletedVolumes(String strSfMvip, int iSfPort, String strSfAdmin, String strSfPassword) + { + final Gson gson = new GsonBuilder().create(); + + ListDeletedVolumes listDeletedVolumes = new ListDeletedVolumes(); + + String strListDeletedVolumesJson = gson.toJson(listDeletedVolumes); + + String strListDeletedVolumesResultJson = executeJsonRpc(strListDeletedVolumesJson, strSfMvip, iSfPort, + strSfAdmin, strSfPassword); + + VolumeGetResult volumeGetResult = gson.fromJson(strListDeletedVolumesResultJson, VolumeGetResult.class); + + verifyResult(volumeGetResult.result, strListDeletedVolumesResultJson, gson); + + List deletedVolumes = new ArrayList (); + + for (VolumeGetResult.Result.Volume volume : volumeGetResult.result.volumes) { + deletedVolumes.add(new SolidFireVolume(volume.volumeID, volume.name, volume.iqn, volume.accountID, volume.status, volume.totalSize)); + } + + return deletedVolumes; + } + + public static SolidFireVolume deleteSolidFireVolume(String strSfMvip, int iSfPort, String strSfAdmin, String strSfPassword, long lVolumeId) + { + SolidFireVolume sfVolume = getSolidFireVolume(strSfMvip, iSfPort, strSfAdmin, strSfPassword, lVolumeId); + + final Gson gson = new GsonBuilder().create(); + + VolumeToDelete volumeToDelete = new VolumeToDelete(lVolumeId); + + String strVolumeToDeleteJson = gson.toJson(volumeToDelete); + + executeJsonRpc(strVolumeToDeleteJson, strSfMvip, iSfPort, strSfAdmin, strSfPassword); + + return sfVolume; + } + + public static void purgeSolidFireVolume(String strSfMvip, int iSfPort, String strSfAdmin, String strSfPassword, long lVolumeId) + { + final Gson gson = new GsonBuilder().create(); + + VolumeToPurge volumeToPurge = new VolumeToPurge(lVolumeId); + + String strVolumeToPurgeJson = gson.toJson(volumeToPurge); + + executeJsonRpc(strVolumeToPurgeJson, strSfMvip, iSfPort, strSfAdmin, strSfPassword); + } + private static final String ACTIVE = "active"; public static class SolidFireVolume { @@ -166,13 +198,17 @@ public class SolidFireUtil { private final String _iqn; private final long _accountId; private final String _status; + private final long _totalSize; - public SolidFireVolume(long id, String name, String iqn, long accountId, String status) { + public SolidFireVolume(long id, String name, String iqn, + long accountId, String status, long totalSize) + { _id = id; _name = name; _iqn = "/" + iqn + "/0"; _accountId = accountId; _status = status; + _totalSize = totalSize; } public long getId() { @@ -195,6 +231,10 @@ public class SolidFireUtil { return ACTIVE.equalsIgnoreCase(_status); } + public long getTotalSize() { + return _totalSize; + } + @Override public int hashCode() { return _iqn.hashCode(); @@ -217,7 +257,9 @@ public class SolidFireUtil { SolidFireVolume sfv = (SolidFireVolume)obj; - if (_id == sfv._id && _name.equals(sfv._name) && _iqn.equals(sfv._iqn) && _accountId == sfv._accountId && isActive() == sfv.isActive()) { + if (_id == sfv._id && _name.equals(sfv._name) && + _iqn.equals(sfv._iqn) && _accountId == sfv._accountId && + isActive() == sfv.isActive() && getTotalSize() == sfv.getTotalSize()) { return true; } @@ -225,7 +267,8 @@ public class SolidFireUtil { } } - public static long createSolidFireAccount(String strSfMvip, int iSfPort, String strSfAdmin, String strSfPassword, String strAccountName) { + public static long createSolidFireAccount(String strSfMvip, int iSfPort, String strSfAdmin, String strSfPassword, String strAccountName) + { final Gson gson = new GsonBuilder().create(); AccountToAdd accountToAdd = new AccountToAdd(strAccountName); @@ -241,17 +284,8 @@ public class SolidFireUtil { return accountAddResult.result.accountID; } - public static void deleteSolidFireAccount(String strSfMvip, int iSfPort, String strSfAdmin, String strSfPassword, long lAccountId) { - final Gson gson = new GsonBuilder().create(); - - AccountToRemove accountToRemove = new AccountToRemove(lAccountId); - - String strAccountToRemoveJson = gson.toJson(accountToRemove); - - executeJsonRpc(strAccountToRemoveJson, strSfMvip, iSfPort, strSfAdmin, strSfPassword); - } - - public static SolidFireAccount getSolidFireAccountById(String strSfMvip, int iSfPort, String strSfAdmin, String strSfPassword, long lSfAccountId) { + public static SolidFireAccount getSolidFireAccountById(String strSfMvip, int iSfPort, String strSfAdmin, String strSfPassword, long lSfAccountId) + { final Gson gson = new GsonBuilder().create(); AccountToGetById accountToGetById = new AccountToGetById(lSfAccountId); @@ -271,7 +305,8 @@ public class SolidFireUtil { return new SolidFireAccount(lSfAccountId, strSfAccountName, strSfAccountInitiatorSecret, strSfAccountTargetSecret); } - public static SolidFireAccount getSolidFireAccountByName(String strSfMvip, int iSfPort, String strSfAdmin, String strSfPassword, String strSfAccountName) { + public static SolidFireAccount getSolidFireAccountByName(String strSfMvip, int iSfPort, String strSfAdmin, String strSfPassword, String strSfAccountName) + { final Gson gson = new GsonBuilder().create(); AccountToGetByName accountToGetByName = new AccountToGetByName(strSfAccountName); @@ -291,7 +326,19 @@ public class SolidFireUtil { return new SolidFireAccount(lSfAccountId, strSfAccountName, strSfAccountInitiatorSecret, strSfAccountTargetSecret); } - public static class SolidFireAccount { + public static void deleteSolidFireAccount(String strSfMvip, int iSfPort, String strSfAdmin, String strSfPassword, long lAccountId) + { + final Gson gson = new GsonBuilder().create(); + + AccountToRemove accountToRemove = new AccountToRemove(lAccountId); + + String strAccountToRemoveJson = gson.toJson(accountToRemove); + + executeJsonRpc(strAccountToRemoveJson, strSfMvip, iSfPort, strSfAdmin, strSfPassword); + } + + public static class SolidFireAccount + { private final long _id; private final String _name; private final String _initiatorSecret; @@ -342,7 +389,9 @@ public class SolidFireUtil { SolidFireAccount sfa = (SolidFireAccount)obj; - if (_id == sfa._id && _name.equals(sfa._name) && _initiatorSecret.equals(sfa._initiatorSecret) && _targetSecret.equals(sfa._targetSecret)) { + if (_id == sfa._id && _name.equals(sfa._name) && + _initiatorSecret.equals(sfa._initiatorSecret) && + _targetSecret.equals(sfa._targetSecret)) { return true; } @@ -350,32 +399,12 @@ public class SolidFireUtil { } } - public static List getDeletedVolumes(String strSfMvip, int iSfPort, String strSfAdmin, String strSfPassword) { + public static long createSolidFireVag(String strSfMvip, int iSfPort, String strSfAdmin, String strSfPassword, String strVagName, + String[] iqns, long[] volumeIds) + { final Gson gson = new GsonBuilder().create(); - ListDeletedVolumes listDeletedVolumes = new ListDeletedVolumes(); - - String strListDeletedVolumesJson = gson.toJson(listDeletedVolumes); - - String strListDeletedVolumesResultJson = executeJsonRpc(strListDeletedVolumesJson, strSfMvip, iSfPort, strSfAdmin, strSfPassword); - - VolumeGetResult volumeGetResult = gson.fromJson(strListDeletedVolumesResultJson, VolumeGetResult.class); - - verifyResult(volumeGetResult.result, strListDeletedVolumesResultJson, gson); - - List deletedVolumes = new ArrayList(); - - for (VolumeGetResult.Result.Volume volume : volumeGetResult.result.volumes) { - deletedVolumes.add(new SolidFireVolume(volume.volumeID, volume.name, volume.iqn, volume.accountID, volume.status)); - } - - return deletedVolumes; - } - - public static long createSolidFireVag(String strSfMvip, int iSfPort, String strSfAdmin, String strSfPassword, String strVagName) { - final Gson gson = new GsonBuilder().create(); - - VagToCreate vagToCreate = new VagToCreate(strVagName); + VagToCreate vagToCreate = new VagToCreate(strVagName, iqns, volumeIds); String strVagCreateJson = gson.toJson(vagToCreate); @@ -388,7 +417,67 @@ public class SolidFireUtil { return vagCreateResult.result.volumeAccessGroupID; } - public static void deleteSolidFireVag(String strSfMvip, int iSfPort, String strSfAdmin, String strSfPassword, long lVagId) { + public static void modifySolidFireVag(String strSfMvip, int iSfPort, String strSfAdmin, String strSfPassword, long lVagId, + String[] iqns, long[] volumeIds) + { + final Gson gson = new GsonBuilder().create(); + + VagToModify vagToModify = new VagToModify(lVagId, iqns, volumeIds); + + String strVagModifyJson = gson.toJson(vagToModify); + + executeJsonRpc(strVagModifyJson, strSfMvip, iSfPort, strSfAdmin, strSfPassword); + } + + public static SolidFireVag getSolidFireVag(String strSfMvip, int iSfPort, String strSfAdmin, String strSfPassword, long lVagId) + { + final Gson gson = new GsonBuilder().create(); + + VagToGet vagToGet = new VagToGet(lVagId); + + String strVagToGetJson = gson.toJson(vagToGet); + + String strVagGetResultJson = executeJsonRpc(strVagToGetJson, strSfMvip, iSfPort, strSfAdmin, strSfPassword); + + VagGetResult vagGetResult = gson.fromJson(strVagGetResultJson, VagGetResult.class); + + verifyResult(vagGetResult.result, strVagGetResultJson, gson); + + String[] vagIqns = getVagIqns(vagGetResult, lVagId); + long[] vagVolumeIds = getVagVolumeIds(vagGetResult, lVagId); + + return new SolidFireVag(lVagId, vagIqns, vagVolumeIds); + } + + public static List getAllSolidFireVags(String strSfMvip, int iSfPort, String strSfAdmin, String strSfPassword) + { + final Gson gson = new GsonBuilder().create(); + + AllVags allVags = new AllVags(); + + String strAllVagsJson = gson.toJson(allVags); + + String strAllVagsGetResultJson = executeJsonRpc(strAllVagsJson, strSfMvip, iSfPort, strSfAdmin, strSfPassword); + + VagGetResult allVagsGetResult = gson.fromJson(strAllVagsGetResultJson, VagGetResult.class); + + verifyResult(allVagsGetResult.result, strAllVagsGetResultJson, gson); + + List lstSolidFireVags = new ArrayList(); + + if (allVagsGetResult.result.volumeAccessGroups != null ) { + for (VagGetResult.Result.Vag vag : allVagsGetResult.result.volumeAccessGroups) { + SolidFireVag sfVag = new SolidFireVag(vag.volumeAccessGroupID, vag.initiators, vag.volumes); + + lstSolidFireVags.add(sfVag); + } + } + + return lstSolidFireVags; + } + + public static void deleteSolidFireVag(String strSfMvip, int iSfPort, String strSfAdmin, String strSfPassword, long lVagId) + { final Gson gson = new GsonBuilder().create(); VagToDelete vagToDelete = new VagToDelete(lVagId); @@ -398,6 +487,64 @@ public class SolidFireUtil { executeJsonRpc(strVagToDeleteJson, strSfMvip, iSfPort, strSfAdmin, strSfPassword); } + public static class SolidFireVag + { + private final long _id; + private final String[] _initiators; + private final long[] _volumeIds; + + public SolidFireVag(long id, String[] initiators, long[] volumeIds) + { + _id = id; + _initiators = initiators; + _volumeIds = volumeIds; + } + + public long getId() + { + return _id; + } + + public String[] getInitiators() + { + return _initiators; + } + + public long[] getVolumeIds() + { + return _volumeIds; + } + + @Override + public int hashCode() { + return String.valueOf(_id).hashCode(); + } + + @Override + public String toString() { + return String.valueOf(_id); + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + + if (!obj.getClass().equals(SolidFireVag.class)) { + return false; + } + + SolidFireVag sfvag = (SolidFireVag)obj; + + if (_id == sfvag._id) { + return true; + } + + return false; + } + } + @SuppressWarnings("unused") private static final class VolumeToCreate { private final String method = "CreateVolume"; @@ -450,7 +597,59 @@ public class SolidFireUtil { } @SuppressWarnings("unused") - private static final class VolumeToDelete { + private static final class VolumeToGet + { + private final String method = "ListActiveVolumes"; + private final VolumeToGetParams params; + + private VolumeToGet(final long lVolumeId) + { + params = new VolumeToGetParams(lVolumeId); + } + + private static final class VolumeToGetParams + { + private final long startVolumeID; + private final long limit = 1; + + private VolumeToGetParams(final long lVolumeId) + { + startVolumeID = lVolumeId; + } + } + } + + @SuppressWarnings("unused") + private static final class VolumesToGetForAccount + { + private final String method = "ListVolumesForAccount"; + private final VolumesToGetForAccountParams params; + + private VolumesToGetForAccount(final long lAccountId) + { + params = new VolumesToGetForAccountParams(lAccountId); + } + + private static final class VolumesToGetForAccountParams + { + private final long accountID; + + private VolumesToGetForAccountParams(final long lAccountId) + { + accountID = lAccountId; + } + } + } + + @SuppressWarnings("unused") + private static final class ListDeletedVolumes + { + private final String method = "ListDeletedVolumes"; + } + + @SuppressWarnings("unused") + private static final class VolumeToDelete + { private final String method = "DeleteVolume"; private final VolumeToDeleteParams params; @@ -468,12 +667,8 @@ public class SolidFireUtil { } @SuppressWarnings("unused") - private static final class ListDeletedVolumes { - private final String method = "ListDeletedVolumes"; - } - - @SuppressWarnings("unused") - private static final class VolumeToPurge { + private static final class VolumeToPurge + { private final String method = "PurgeDeletedVolume"; private final VolumeToPurgeParams params; @@ -491,56 +686,67 @@ public class SolidFireUtil { } @SuppressWarnings("unused") - private static final class VolumeToGet { - private final String method = "ListActiveVolumes"; - private final VolumeToGetParams params; + private static final class AccountToAdd + { + private final String method = "AddAccount"; + private final AccountToAddParams params; - private VolumeToGet(final long lVolumeId) { - params = new VolumeToGetParams(lVolumeId); + private AccountToAdd(final String strAccountName) + { + params = new AccountToAddParams(strAccountName); } - private static final class VolumeToGetParams { - private final long startVolumeID; - private final long limit = 1; + private static final class AccountToAddParams + { + private final String username; - private VolumeToGetParams(final long lVolumeId) { - startVolumeID = lVolumeId; + private AccountToAddParams(final String strAccountName) + { + username = strAccountName; } } } @SuppressWarnings("unused") - private static final class VolumesToGetForAccount { - private final String method = "ListVolumesForAccount"; - private final VolumesToGetForAccountParams params; + private static final class AccountToGetById + { + private final String method = "GetAccountByID"; + private final AccountToGetByIdParams params; - private VolumesToGetForAccount(final long lAccountId) { - params = new VolumesToGetForAccountParams(lAccountId); + private AccountToGetById(final long lAccountId) + { + params = new AccountToGetByIdParams(lAccountId); } - private static final class VolumesToGetForAccountParams { + private static final class AccountToGetByIdParams + { private final long accountID; - private VolumesToGetForAccountParams(final long lAccountId) { + private AccountToGetByIdParams(final long lAccountId) + { accountID = lAccountId; } } } @SuppressWarnings("unused") - private static final class AccountToAdd { - private final String method = "AddAccount"; - private final AccountToAddParams params; + private static final class AccountToGetByName + { + private final String method = "GetAccountByName"; + private final AccountToGetByNameParams params; - private AccountToAdd(final String strAccountName) { - params = new AccountToAddParams(strAccountName); + private AccountToGetByName(final String strUsername) + { + params = new AccountToGetByNameParams(strUsername); } - private static final class AccountToAddParams { + private static final class AccountToGetByNameParams + { private final String username; - private AccountToAddParams(final String strAccountName) { - username = strAccountName; + private AccountToGetByNameParams(final String strUsername) + { + username = strUsername; } } } @@ -564,61 +770,98 @@ public class SolidFireUtil { } @SuppressWarnings("unused") - private static final class AccountToGetById { - private final String method = "GetAccountByID"; - private final AccountToGetByIdParams params; - - private AccountToGetById(final long lAccountId) { - params = new AccountToGetByIdParams(lAccountId); - } - - private static final class AccountToGetByIdParams { - private final long accountID; - - private AccountToGetByIdParams(final long lAccountId) { - accountID = lAccountId; - } - } - } - - @SuppressWarnings("unused") - private static final class AccountToGetByName { - private final String method = "GetAccountByName"; - private final AccountToGetByNameParams params; - - private AccountToGetByName(final String strUsername) { - params = new AccountToGetByNameParams(strUsername); - } - - private static final class AccountToGetByNameParams { - private final String username; - - private AccountToGetByNameParams(final String strUsername) { - username = strUsername; - } - } - } - - @SuppressWarnings("unused") - private static final class VagToCreate { + private static final class VagToCreate + { private final String method = "CreateVolumeAccessGroup"; private final VagToCreateParams params; - private VagToCreate(final String strVagName) { - params = new VagToCreateParams(strVagName); + private VagToCreate(final String strVagName, final String[] iqns, final long[] volumeIds) + { + params = new VagToCreateParams(strVagName, iqns, volumeIds); } - private static final class VagToCreateParams { + private static final class VagToCreateParams + { private final String name; + private final String[] initiators; + private final long[] volumes; - private VagToCreateParams(final String strVagName) { + private VagToCreateParams(final String strVagName, final String[] iqns, final long[] volumeIds) + { name = strVagName; + initiators = iqns; + volumes = volumeIds; } } } @SuppressWarnings("unused") - private static final class VagToDelete { + private static final class VagToModify + { + private final String method = "ModifyVolumeAccessGroup"; + private final VagToModifyParams params; + + private VagToModify(final long lVagName, final String[] iqns, final long[] volumeIds) + { + params = new VagToModifyParams(lVagName, iqns, volumeIds); + } + + private static final class VagToModifyParams + { + private final long volumeAccessGroupID; + private final String[] initiators; + private final long[] volumes; + + private VagToModifyParams(final long lVagName, final String[] iqns, final long[] volumeIds) + { + volumeAccessGroupID = lVagName; + initiators = iqns; + volumes = volumeIds; + } + } + } + + @SuppressWarnings("unused") + private static final class VagToGet + { + private final String method = "ListVolumeAccessGroups"; + private final VagToGetParams params; + + private VagToGet(final long lVagId) + { + params = new VagToGetParams(lVagId); + } + + private static final class VagToGetParams + { + private final long startVolumeAccessGroupID; + private final long limit = 1; + + private VagToGetParams(final long lVagId) + { + startVolumeAccessGroupID = lVagId; + } + } + } + + @SuppressWarnings("unused") + private static final class AllVags + { + private final String method = "ListVolumeAccessGroups"; + private final VagToGetParams params; + + private AllVags() + { + params = new VagToGetParams(); + } + + private static final class VagToGetParams + {} + } + + @SuppressWarnings("unused") + private static final class VagToDelete + { private final String method = "DeleteVolumeAccessGroup"; private final VagToDeleteParams params; @@ -655,6 +898,7 @@ public class SolidFireUtil { private String iqn; private long accountID; private String status; + private long totalSize; } } } @@ -690,7 +934,25 @@ public class SolidFireUtil { } } - private static final class JsonError { + private static final class VagGetResult + { + private Result result; + + private static final class Result + { + private Vag[] volumeAccessGroups; + + private static final class Vag + { + private long volumeAccessGroupID; + private String[] initiators; + private long[] volumes; + } + } + } + + private static final class JsonError + { private Error error; private static final class Error { @@ -745,7 +1007,7 @@ public class SolidFireUtil { httpClient = getHttpClient(iPort); - URI uri = new URI("https://" + strMvip + ":" + iPort + "/json-rpc/1.0"); + URI uri = new URI("https://" + strMvip + ":" + iPort + "/json-rpc/5.0"); AuthScope authScope = new AuthScope(uri.getHost(), uri.getPort(), AuthScope.ANY_SCHEME); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(strAdmin, strPassword); @@ -811,7 +1073,7 @@ public class SolidFireUtil { return volumeGetResult.result.volumes[0].name; } - throw new CloudRuntimeException("Could not determine the name of the volume, " + "but the volume was created with an ID of " + lVolumeId + "."); + throw new CloudRuntimeException("Could not determine the name of the volume for volume ID of " + lVolumeId + "."); } private static String getVolumeIqn(VolumeGetResult volumeGetResult, long lVolumeId) { @@ -819,7 +1081,7 @@ public class SolidFireUtil { return volumeGetResult.result.volumes[0].iqn; } - throw new CloudRuntimeException("Could not determine the IQN of the volume, " + "but the volume was created with an ID of " + lVolumeId + "."); + throw new CloudRuntimeException("Could not determine the IQN of the volume for volume ID of " + lVolumeId + "."); } private static long getVolumeAccountId(VolumeGetResult volumeGetResult, long lVolumeId) { @@ -827,7 +1089,7 @@ public class SolidFireUtil { return volumeGetResult.result.volumes[0].accountID; } - throw new CloudRuntimeException("Could not determine the volume's account ID, " + "but the volume was created with an ID of " + lVolumeId + "."); + throw new CloudRuntimeException("Could not determine the account ID of the volume for volume ID of " + lVolumeId + "."); } private static String getVolumeStatus(VolumeGetResult volumeGetResult, long lVolumeId) { @@ -835,6 +1097,39 @@ public class SolidFireUtil { return volumeGetResult.result.volumes[0].status; } - throw new CloudRuntimeException("Could not determine the status of the volume, " + "but the volume was created with an ID of " + lVolumeId + "."); + throw new CloudRuntimeException("Could not determine the status of the volume for volume ID of " + lVolumeId + "."); + } + + private static long getVolumeTotalSize(VolumeGetResult volumeGetResult, long lVolumeId) + { + if (volumeGetResult.result.volumes != null && volumeGetResult.result.volumes.length == 1 && + volumeGetResult.result.volumes[0].volumeID == lVolumeId) + { + return volumeGetResult.result.volumes[0].totalSize; + } + + throw new CloudRuntimeException("Could not determine the total size of the volume for volume ID of " + lVolumeId + "."); + } + + private static String[] getVagIqns(VagGetResult vagGetResult, long lVagId) + { + if (vagGetResult.result.volumeAccessGroups != null && vagGetResult.result.volumeAccessGroups.length == 1 && + vagGetResult.result.volumeAccessGroups[0].volumeAccessGroupID == lVagId) + { + return vagGetResult.result.volumeAccessGroups[0].initiators; + } + + throw new CloudRuntimeException("Could not determine the IQNs of the volume access group for volume access group ID of " + lVagId + "."); + } + + private static long[] getVagVolumeIds(VagGetResult vagGetResult, long lVagId) + { + if (vagGetResult.result.volumeAccessGroups != null && vagGetResult.result.volumeAccessGroups.length == 1 && + vagGetResult.result.volumeAccessGroups[0].volumeAccessGroupID == lVagId) + { + return vagGetResult.result.volumeAccessGroups[0].volumes; + } + + throw new CloudRuntimeException("Could not determine the volume IDs of the volume access group for volume access group ID of " + lVagId + "."); } } diff --git a/plugins/user-authenticators/ldap/pom.xml b/plugins/user-authenticators/ldap/pom.xml index 4d1b7fa4ffa..46eec81b946 100644 --- a/plugins/user-authenticators/ldap/pom.xml +++ b/plugins/user-authenticators/ldap/pom.xml @@ -90,42 +90,7 @@ - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - - org.codehaus.gmaven - - - gmaven-plugin - - [1.3,) - - compile - testCompile - - - - - - - - - - - - - diff --git a/plugins/user-authenticators/ldap/src/org/apache/cloudstack/api/command/LDAPConfigCmd.java b/plugins/user-authenticators/ldap/src/org/apache/cloudstack/api/command/LDAPConfigCmd.java new file mode 100644 index 00000000000..5e424dee9b4 --- /dev/null +++ b/plugins/user-authenticators/ldap/src/org/apache/cloudstack/api/command/LDAPConfigCmd.java @@ -0,0 +1,277 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command; + +import java.util.ArrayList; +import java.util.List; + +import javax.inject.Inject; + +import org.apache.commons.lang.StringEscapeUtils; +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.LDAPConfigResponse; +import org.apache.cloudstack.api.response.LdapConfigurationResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.framework.config.dao.ConfigurationDao; +import org.apache.cloudstack.framework.config.impl.ConfigurationVO; +import org.apache.cloudstack.ldap.LdapConfiguration; +import org.apache.cloudstack.ldap.LdapConfigurationVO; +import org.apache.cloudstack.ldap.LdapManager; + +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.user.Account; +import com.cloud.utils.Pair; + +/** + * @deprecated as of 4.3 use the new api {@link LdapAddConfigurationCmd} + */ +@Deprecated +@APICommand(name = "ldapConfig", description = "Configure the LDAP context for this site.", responseObject = LDAPConfigResponse.class, since = "3.0.0") +public class LDAPConfigCmd extends BaseCmd { + public static final Logger s_logger = Logger.getLogger(LDAPConfigCmd.class.getName()); + + private static final String s_name = "ldapconfigresponse"; + + @Inject + private ConfigurationDao _configDao; + + @Inject + private LdapManager _ldapManager; + + @Inject + private LdapConfiguration _ldapConfiguration; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + @Parameter(name = ApiConstants.LIST_ALL, type = CommandType.BOOLEAN, description = "If true return current LDAP configuration") + private Boolean listAll; + + @Parameter(name = ApiConstants.HOST_NAME, type = CommandType.STRING, description = "Hostname or ip address of the ldap server eg: my.ldap.com") + private String hostname; + + @Parameter(name = ApiConstants.PORT, type = CommandType.INTEGER, description = "Specify the LDAP port if required, default is 389.") + private Integer port = 0; + + @Parameter(name = ApiConstants.USE_SSL, type = CommandType.BOOLEAN, description = "Check Use SSL if the external LDAP server is configured for LDAP over SSL.") + private Boolean useSSL; + + @Parameter(name = ApiConstants.SEARCH_BASE, + type = CommandType.STRING, + description = "The search base defines the starting point for the search in the directory tree Example: dc=cloud,dc=com.") + private String searchBase; + + @Parameter(name = ApiConstants.QUERY_FILTER, + type = CommandType.STRING, + description = "You specify a query filter here, which narrows down the users, who can be part of this domain.") + private String queryFilter; + + @Parameter(name = ApiConstants.BIND_DN, + type = CommandType.STRING, + description = "Specify the distinguished name of a user with the search permission on the directory.") + private String bindDN; + + @Parameter(name = ApiConstants.BIND_PASSWORD, type = CommandType.STRING, description = "Enter the password.") + private String bindPassword; + + @Parameter(name = ApiConstants.TRUST_STORE, type = CommandType.STRING, description = "Enter the path to trust certificates store.") + private String trustStore; + + @Parameter(name = ApiConstants.TRUST_STORE_PASSWORD, type = CommandType.STRING, description = "Enter the password for trust store.") + private String trustStorePassword; + + public Boolean getListAll() { + return listAll == null ? Boolean.FALSE : listAll; + } + + public String getBindPassword() { + return bindPassword; + } + + public String getBindDN() { + return bindDN; + } + + public void setBindDN(String bdn) { + bindDN = bdn; + } + + public String getQueryFilter() { + return queryFilter; + } + + public void setQueryFilter(String queryFilter) { + this.queryFilter = StringEscapeUtils.unescapeHtml(queryFilter); + } + + public String getSearchBase() { + return searchBase; + } + + public void setSearchBase(String searchBase) { + this.searchBase = searchBase; + } + + public Boolean getUseSSL() { + return useSSL == null ? Boolean.FALSE : useSSL; + } + + public void setUseSSL(Boolean useSSL) { + this.useSSL = useSSL; + } + + public String getHostname() { + return hostname; + } + + public void setHostname(String hostname) { + this.hostname = hostname; + } + + public Integer getPort() { + return port <= 0 ? 389 : port; + } + + public void setPort(Integer port) { + this.port = port; + } + + public String getTrustStore() { + return trustStore; + } + + public void setTrustStore(String trustStore) { + this.trustStore = trustStore; + } + + public String getTrustStorePassword() { + return trustStorePassword; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, + ResourceAllocationException { + if (getListAll()) { + // return the existing conf + + LdapListConfigurationCmd listConfigurationCmd = new LdapListConfigurationCmd(_ldapManager); + Pair, Integer> result = _ldapManager.listConfigurations(listConfigurationCmd); + ListResponse response = new ListResponse(); + List responses = new ArrayList(); + + if (result.second() > 0) { + boolean useSSlConfig = _ldapConfiguration.getSSLStatus(); + String searchBaseConfig = _ldapConfiguration.getBaseDn(); + String bindDnConfig = _ldapConfiguration.getBindPrincipal(); + for (LdapConfigurationVO ldapConfigurationVO : result.first()) { + responses.add(createLDAPConfigResponse(ldapConfigurationVO.getHostname(), ldapConfigurationVO.getPort(), useSSlConfig, null, searchBaseConfig, + bindDnConfig)); + } + } + response.setResponses(responses); + response.setResponseName(getCommandName()); + setResponseObject(response); + } else if (getHostname() == null || getPort() == null) { + throw new InvalidParameterValueException("You need to provide hostname, port to configure your LDAP server"); + } else { + boolean result = updateLDAP(); + if (result) { + LDAPConfigResponse lr = createLDAPConfigResponse(getHostname(), getPort(), getUseSSL(), getQueryFilter(), getSearchBase(), getBindDN()); + lr.setResponseName(getCommandName()); + setResponseObject(lr); + } + } + + } + + private LDAPConfigResponse createLDAPConfigResponse(String hostname, Integer port, Boolean useSSL, String queryFilter, String searchBase, String bindDN) { + LDAPConfigResponse lr = new LDAPConfigResponse(); + lr.setHostname(hostname); + lr.setPort(port.toString()); + lr.setUseSSL(useSSL.toString()); + lr.setQueryFilter(queryFilter); + lr.setBindDN(bindDN); + lr.setSearchBase(searchBase); + lr.setObjectName("ldapconfig"); + return lr; + } + + private boolean updateLDAP() { + LdapConfigurationResponse response = _ldapManager.addConfiguration(hostname, port); + + /** + * There is no query filter now. It is derived from ldap.user.object and ldap.search.group.principle + */ +// ConfigurationVO cvo = _configDao.findByName(LDAPParams.queryfilter.toString()); +// _configDao.update(cvo.getName(),cvo.getCategory(),getQueryFilter()); + + ConfigurationVO cvo = _configDao.findByName("ldap.basedn"); + _configDao.update(cvo.getName(), cvo.getCategory(), getSearchBase()); + + /** + * There is no ssl now. it is derived from the presence of trust store and password + */ +// cvo = _configDao.findByName(LDAPParams.usessl.toString()); +// _configDao.update(cvo.getName(),cvo.getCategory(),getUseSSL().toString()); + + cvo = _configDao.findByName("ldap.bind.principal"); + _configDao.update(cvo.getName(), cvo.getCategory(), getBindDN()); + + cvo = _configDao.findByName("ldap.bind.password"); + _configDao.update(cvo.getName(), cvo.getCategory(), getBindPassword()); + + cvo = _configDao.findByName("ldap.truststore"); + _configDao.update(cvo.getName(), cvo.getCategory(), getTrustStore()); + + cvo = _configDao.findByName("ldap.truststore.password"); + _configDao.update(cvo.getName(), cvo.getCategory(), getTrustStorePassword()); + + return true; + } + + private List listLDAPConfig() { + + LdapListConfigurationCmd listConfigurationCmd = new LdapListConfigurationCmd(_ldapManager); + Pair, Integer> result = _ldapManager.listConfigurations(listConfigurationCmd); + return result.first(); + } + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + +} diff --git a/plugins/user-authenticators/ldap/src/org/apache/cloudstack/api/command/LDAPRemoveCmd.java b/plugins/user-authenticators/ldap/src/org/apache/cloudstack/api/command/LDAPRemoveCmd.java new file mode 100644 index 00000000000..535a545ade7 --- /dev/null +++ b/plugins/user-authenticators/ldap/src/org/apache/cloudstack/api/command/LDAPRemoveCmd.java @@ -0,0 +1,77 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command; + +import java.util.List; + +import javax.inject.Inject; + +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.response.LDAPConfigResponse; +import org.apache.cloudstack.api.response.LDAPRemoveResponse; +import org.apache.cloudstack.ldap.LdapConfigurationVO; +import org.apache.cloudstack.ldap.LdapManager; +import org.apache.log4j.Logger; + +import com.cloud.user.Account; +import com.cloud.utils.Pair; + +/** + * @deprecated as of 4.3 use the new api {@link LdapDeleteConfigurationCmd} + */ +@Deprecated +@APICommand(name = "ldapRemove", description = "Remove the LDAP context for this site.", responseObject = LDAPConfigResponse.class, since = "3.0.1") +public class LDAPRemoveCmd extends BaseCmd { + public static final Logger s_logger = Logger.getLogger(LDAPRemoveCmd.class.getName()); + + @Inject + private LdapManager _ldapManager; + + private static final String s_name = "ldapremoveresponse"; + + @Override + public void execute() { + boolean result = this.removeLDAP(); + if (result) { + LDAPRemoveResponse lr = new LDAPRemoveResponse(); + lr.setObjectName("ldapremove"); + lr.setResponseName(getCommandName()); + this.setResponseObject(lr); + } + } + + private boolean removeLDAP() { + LdapListConfigurationCmd listConfigurationCmd = new LdapListConfigurationCmd(_ldapManager); + Pair, Integer> result = _ldapManager.listConfigurations(listConfigurationCmd); + for (LdapConfigurationVO config : result.first()) { + _ldapManager.deleteConfiguration(config.getHostname()); + } + return true; + } + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + +} diff --git a/plugins/user-authenticators/ldap/src/org/apache/cloudstack/api/command/LdapImportUsersCmd.java b/plugins/user-authenticators/ldap/src/org/apache/cloudstack/api/command/LdapImportUsersCmd.java index d817c334de8..89cec6555b1 100644 --- a/plugins/user-authenticators/ldap/src/org/apache/cloudstack/api/command/LdapImportUsersCmd.java +++ b/plugins/user-authenticators/ldap/src/org/apache/cloudstack/api/command/LdapImportUsersCmd.java @@ -59,29 +59,29 @@ public class LdapImportUsersCmd extends BaseListCmd { private static final String s_name = "ldapuserresponse"; @Parameter(name = ApiConstants.TIMEZONE, - type = CommandType.STRING, - description = "Specifies a timezone for this command. For more information on the timezone parameter, see Time Zone Format.") + type = CommandType.STRING, + description = "Specifies a timezone for this command. For more information on the timezone parameter, see Time Zone Format.") private String timezone; @Parameter(name = ApiConstants.ACCOUNT_TYPE, - type = CommandType.SHORT, - required = true, - description = "Type of the account. Specify 0 for user, 1 for root admin, and 2 for domain admin") + type = CommandType.SHORT, + required = true, + description = "Type of the account. Specify 0 for user, 1 for root admin, and 2 for domain admin") private Short accountType; @Parameter(name = ApiConstants.ACCOUNT_DETAILS, type = CommandType.MAP, description = "details for account used to store specific parameters") private Map details; @Parameter(name = ApiConstants.DOMAIN_ID, - type = CommandType.UUID, - entityType = DomainResponse.class, - description = "Specifies the domain to which the ldap users are to be " - + "imported. If no domain is specified, a domain will created using group parameter. If the group is also not specified, a domain name based on the OU information will be " - + "created. If no OU hierarchy exists, will be defaulted to ROOT domain") + type = CommandType.UUID, + entityType = DomainResponse.class, + description = "Specifies the domain to which the ldap users are to be " + + "imported. If no domain is specified, a domain will created using group parameter. If the group is also not specified, a domain name based on the OU information will be " + + "created. If no OU hierarchy exists, will be defaulted to ROOT domain") private Long domainId; @Parameter(name = ApiConstants.GROUP, type = CommandType.STRING, description = "Specifies the group name from which the ldap users are to be imported. " - + "If no group is specified, all the users will be imported.") + + "If no group is specified, all the users will be imported.") private String groupName; private Domain _domain; @@ -102,7 +102,7 @@ public class LdapImportUsersCmd extends BaseListCmd { @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException, NetworkRuleConflictException { + ResourceAllocationException, NetworkRuleConflictException { List users; try { @@ -122,7 +122,7 @@ public class LdapImportUsersCmd extends BaseListCmd { Domain domain = getDomain(user); try { _accountService.createUserAccount(user.getUsername(), generatePassword(), user.getFirstname(), user.getLastname(), user.getEmail(), timezone, - user.getUsername(), accountType, domain.getId(), domain.getNetworkDomain(), details, UUID.randomUUID().toString(), UUID.randomUUID().toString()); + user.getUsername(), accountType, domain.getId(), domain.getNetworkDomain(), details, UUID.randomUUID().toString(), UUID.randomUUID().toString()); addedUsers.add(user); } catch (InvalidParameterValueException ex) { s_logger.error("Failed to create user with username: " + user.getUsername() + " ::: " + ex.getMessage()); diff --git a/plugins/user-authenticators/ldap/src/org/apache/cloudstack/api/response/LDAPConfigResponse.java b/plugins/user-authenticators/ldap/src/org/apache/cloudstack/api/response/LDAPConfigResponse.java new file mode 100644 index 00000000000..8570bacab06 --- /dev/null +++ b/plugins/user-authenticators/ldap/src/org/apache/cloudstack/api/response/LDAPConfigResponse.java @@ -0,0 +1,115 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.response; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; + +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; + +/** + * @deprecated as of 4.3 along with the api {@link org.apache.cloudstack.api.command.LDAPConfigCmd} + */ +@Deprecated +public class LDAPConfigResponse extends BaseResponse { + + @SerializedName(ApiConstants.HOST_NAME) + @Param(description = "Hostname or ip address of the ldap server eg: my.ldap.com") + private String hostname; + + @SerializedName(ApiConstants.PORT) + @Param(description = "Specify the LDAP port if required, default is 389") + private String port; + + @SerializedName(ApiConstants.USE_SSL) + @Param(description = "Check Use SSL if the external LDAP server is configured for LDAP over SSL") + private String useSSL; + + @SerializedName(ApiConstants.SEARCH_BASE) + @Param(description = "The search base defines the starting point for the search in the directory tree Example: dc=cloud,dc=com") + private String searchBase; + + @SerializedName(ApiConstants.QUERY_FILTER) + @Param(description = "You specify a query filter here, which narrows down the users, who can be part of this domain") + private String queryFilter; + + @SerializedName(ApiConstants.BIND_DN) + @Param(description = "Specify the distinguished name of a user with the search permission on the directory") + private String bindDN; + + @SerializedName(ApiConstants.BIND_PASSWORD) + @Param(description = "DN password") + private String bindPassword; + + public String getHostname() { + return hostname; + } + + public void setHostname(String hostname) { + this.hostname = hostname; + } + + public String getPort() { + return port; + } + + public void setPort(String port) { + this.port = port; + } + + public String getUseSSL() { + return useSSL; + } + + public void setUseSSL(String useSSL) { + this.useSSL = useSSL; + } + + public String getSearchBase() { + return searchBase; + } + + public void setSearchBase(String searchBase) { + this.searchBase = searchBase; + } + + public String getQueryFilter() { + return queryFilter; + } + + public void setQueryFilter(String queryFilter) { + this.queryFilter = queryFilter; + } + + public String getBindDN() { + return bindDN; + } + + public void setBindDN(String bindDN) { + this.bindDN = bindDN; + } + + public String getBindPassword() { + return bindPassword; + } + + public void setBindPassword(String bindPassword) { + this.bindPassword = bindPassword; + } + +} diff --git a/plugins/user-authenticators/ldap/src/org/apache/cloudstack/api/response/LDAPRemoveResponse.java b/plugins/user-authenticators/ldap/src/org/apache/cloudstack/api/response/LDAPRemoveResponse.java new file mode 100644 index 00000000000..9b473d2f385 --- /dev/null +++ b/plugins/user-authenticators/ldap/src/org/apache/cloudstack/api/response/LDAPRemoveResponse.java @@ -0,0 +1,30 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.response; + +import org.apache.cloudstack.api.BaseResponse; + +/** + * @deprecated as of 4.3 along with the api {@link org.apache.cloudstack.api.command.LDAPRemoveCmd} + */ +@Deprecated +public class LDAPRemoveResponse extends BaseResponse { + + public LDAPRemoveResponse() { + super(); + } +} diff --git a/plugins/user-authenticators/ldap/src/org/apache/cloudstack/ldap/LdapAuthenticator.java b/plugins/user-authenticators/ldap/src/org/apache/cloudstack/ldap/LdapAuthenticator.java index 0bfbab60424..afba27238a4 100644 --- a/plugins/user-authenticators/ldap/src/org/apache/cloudstack/ldap/LdapAuthenticator.java +++ b/plugins/user-authenticators/ldap/src/org/apache/cloudstack/ldap/LdapAuthenticator.java @@ -25,6 +25,7 @@ import org.apache.log4j.Logger; import com.cloud.server.auth.DefaultUserAuthenticator; import com.cloud.user.UserAccount; import com.cloud.user.dao.UserAccountDao; +import com.cloud.utils.Pair; public class LdapAuthenticator extends DefaultUserAuthenticator { private static final Logger s_logger = Logger.getLogger(LdapAuthenticator.class.getName()); @@ -45,17 +46,23 @@ public class LdapAuthenticator extends DefaultUserAuthenticator { } @Override - public boolean authenticate(final String username, final String password, final Long domainId, final Map requestParameters) { + public Pair authenticate(final String username, final String password, final Long domainId, final Map requestParameters) { final UserAccount user = _userAccountDao.getUserAccount(username, domainId); if (user == null) { s_logger.debug("Unable to find user with " + username + " in domain " + domainId); - return false; + return new Pair(false, null); } else if (_ldapManager.isLdapEnabled()) { - return _ldapManager.canAuthenticate(username, password); + boolean result = _ldapManager.canAuthenticate(username, password); + ActionOnFailedAuthentication action = null; + if (result == false) { + action = ActionOnFailedAuthentication.INCREMENT_INCORRECT_LOGIN_ATTEMPT_COUNT; + } + return new Pair(result, action); + } else { - return false; + return new Pair(false, ActionOnFailedAuthentication.INCREMENT_INCORRECT_LOGIN_ATTEMPT_COUNT); } } diff --git a/plugins/user-authenticators/ldap/src/org/apache/cloudstack/ldap/LdapManagerImpl.java b/plugins/user-authenticators/ldap/src/org/apache/cloudstack/ldap/LdapManagerImpl.java index f41bd3a8b7e..6d71f4f17dd 100644 --- a/plugins/user-authenticators/ldap/src/org/apache/cloudstack/ldap/LdapManagerImpl.java +++ b/plugins/user-authenticators/ldap/src/org/apache/cloudstack/ldap/LdapManagerImpl.java @@ -28,6 +28,8 @@ import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import org.apache.cloudstack.api.LdapValidator; +import org.apache.cloudstack.api.command.LDAPConfigCmd; +import org.apache.cloudstack.api.command.LDAPRemoveCmd; import org.apache.cloudstack.api.command.LdapAddConfigurationCmd; import org.apache.cloudstack.api.command.LdapCreateAccountCmd; import org.apache.cloudstack.api.command.LdapDeleteConfigurationCmd; @@ -153,6 +155,8 @@ public class LdapManagerImpl implements LdapManager, LdapValidator { cmdList.add(LdapListConfigurationCmd.class); cmdList.add(LdapCreateAccountCmd.class); cmdList.add(LdapImportUsersCmd.class); + cmdList.add(LDAPConfigCmd.class); + cmdList.add(LDAPRemoveCmd.class); return cmdList; } @@ -224,4 +228,4 @@ public class LdapManagerImpl implements LdapManager, LdapValidator { closeContext(context); } } -} \ No newline at end of file +} diff --git a/plugins/user-authenticators/md5/src/com/cloud/server/auth/MD5UserAuthenticator.java b/plugins/user-authenticators/md5/src/com/cloud/server/auth/MD5UserAuthenticator.java index f1fe448ffb5..c1415d256bb 100644 --- a/plugins/user-authenticators/md5/src/com/cloud/server/auth/MD5UserAuthenticator.java +++ b/plugins/user-authenticators/md5/src/com/cloud/server/auth/MD5UserAuthenticator.java @@ -27,6 +27,7 @@ import org.apache.log4j.Logger; import com.cloud.user.UserAccount; import com.cloud.user.dao.UserAccountDao; +import com.cloud.utils.Pair; import com.cloud.utils.exception.CloudRuntimeException; /** @@ -42,21 +43,21 @@ public class MD5UserAuthenticator extends DefaultUserAuthenticator { private UserAccountDao _userAccountDao; @Override - public boolean authenticate(String username, String password, Long domainId, Map requestParameters) { + public Pair authenticate(String username, String password, Long domainId, Map requestParameters) { if (s_logger.isDebugEnabled()) { s_logger.debug("Retrieving user: " + username); } UserAccount user = _userAccountDao.getUserAccount(username, domainId); if (user == null) { s_logger.debug("Unable to find user with " + username + " in domain " + domainId); - return false; + return new Pair(false, null); } if (!user.getPassword().equals(encode(password))) { s_logger.debug("Password does not match"); - return false; + return new Pair(false, ActionOnFailedAuthentication.INCREMENT_INCORRECT_LOGIN_ATTEMPT_COUNT); } - return true; + return new Pair(true, null); } @Override diff --git a/plugins/user-authenticators/plain-text/src/com/cloud/server/auth/PlainTextUserAuthenticator.java b/plugins/user-authenticators/plain-text/src/com/cloud/server/auth/PlainTextUserAuthenticator.java index ac03fde1dda..0afbbfc1c95 100644 --- a/plugins/user-authenticators/plain-text/src/com/cloud/server/auth/PlainTextUserAuthenticator.java +++ b/plugins/user-authenticators/plain-text/src/com/cloud/server/auth/PlainTextUserAuthenticator.java @@ -24,6 +24,7 @@ import org.apache.log4j.Logger; import com.cloud.user.UserAccount; import com.cloud.user.dao.UserAccountDao; +import com.cloud.utils.Pair; @Local(value = {UserAuthenticator.class}) public class PlainTextUserAuthenticator extends DefaultUserAuthenticator { @@ -33,7 +34,7 @@ public class PlainTextUserAuthenticator extends DefaultUserAuthenticator { private UserAccountDao _userAccountDao; @Override - public boolean authenticate(String username, String password, Long domainId, Map requestParameters) { + public Pair authenticate(String username, String password, Long domainId, Map requestParameters) { if (s_logger.isDebugEnabled()) { s_logger.debug("Retrieving user: " + username); } @@ -41,14 +42,14 @@ public class PlainTextUserAuthenticator extends DefaultUserAuthenticator { UserAccount user = _userAccountDao.getUserAccount(username, domainId); if (user == null) { s_logger.debug("Unable to find user with " + username + " in domain " + domainId); - return false; + return new Pair(false, null); } if (!user.getPassword().equals(password)) { s_logger.debug("Password does not match"); - return false; + return new Pair(false, ActionOnFailedAuthentication.INCREMENT_INCORRECT_LOGIN_ATTEMPT_COUNT); } - return true; + return new Pair(true, null); } @Override diff --git a/plugins/user-authenticators/sha256salted/src/com/cloud/server/auth/SHA256SaltedUserAuthenticator.java b/plugins/user-authenticators/sha256salted/src/com/cloud/server/auth/SHA256SaltedUserAuthenticator.java index 8dac9c49714..36305f18c99 100644 --- a/plugins/user-authenticators/sha256salted/src/com/cloud/server/auth/SHA256SaltedUserAuthenticator.java +++ b/plugins/user-authenticators/sha256salted/src/com/cloud/server/auth/SHA256SaltedUserAuthenticator.java @@ -30,6 +30,7 @@ import org.bouncycastle.util.encoders.Base64; import com.cloud.user.UserAccount; import com.cloud.user.dao.UserAccountDao; +import com.cloud.utils.Pair; import com.cloud.utils.exception.CloudRuntimeException; @Local(value = {UserAuthenticator.class}) @@ -45,7 +46,7 @@ public class SHA256SaltedUserAuthenticator extends DefaultUserAuthenticator { * @see com.cloud.server.auth.UserAuthenticator#authenticate(java.lang.String, java.lang.String, java.lang.Long, java.util.Map) */ @Override - public boolean authenticate(String username, String password, Long domainId, Map requestParameters) { + public Pair authenticate(String username, String password, Long domainId, Map requestParameters) { if (s_logger.isDebugEnabled()) { s_logger.debug("Retrieving user: " + username); } @@ -71,7 +72,12 @@ public class SHA256SaltedUserAuthenticator extends DefaultUserAuthenticator { try { String hashedPassword = encode(password, salt); /* constantTimeEquals comes first in boolean since we need to thwart timing attacks */ - return constantTimeEquals(realPassword, hashedPassword) && realUser; + boolean result = constantTimeEquals(realPassword, hashedPassword) && realUser; + ActionOnFailedAuthentication action = null; + if (!result && realUser) { + action = ActionOnFailedAuthentication.INCREMENT_INCORRECT_LOGIN_ATTEMPT_COUNT; + } + return new Pair(result, action); } catch (NoSuchAlgorithmException e) { throw new CloudRuntimeException("Unable to hash password", e); } catch (UnsupportedEncodingException e) { diff --git a/plugins/user-authenticators/sha256salted/test/src/com/cloud/server/auth/test/AuthenticatorTest.java b/plugins/user-authenticators/sha256salted/test/src/com/cloud/server/auth/test/AuthenticatorTest.java index 46d9af89a24..0a9bd2fa7c2 100644 --- a/plugins/user-authenticators/sha256salted/test/src/com/cloud/server/auth/test/AuthenticatorTest.java +++ b/plugins/user-authenticators/sha256salted/test/src/com/cloud/server/auth/test/AuthenticatorTest.java @@ -92,11 +92,11 @@ public class AuthenticatorTest { @Test public void testAuthentication() throws UnsupportedEncodingException, NoSuchAlgorithmException { Map dummyMap = new HashMap(); - assertEquals("32 byte salt authenticated", true, authenticator.authenticate("admin", "password", 0L, dummyMap)); - assertEquals("20 byte salt authenticated", true, authenticator.authenticate("admin20Byte", "password", 0L, dummyMap)); - assertEquals("fake user not authenticated", false, authenticator.authenticate("fake", "fake", 0L, dummyMap)); - assertEquals("bad password not authenticated", false, authenticator.authenticate("admin", "fake", 0L, dummyMap)); - assertEquals("20 byte user bad password not authenticated", false, authenticator.authenticate("admin20Byte", "fake", 0L, dummyMap)); + assertEquals("32 byte salt authenticated", true, authenticator.authenticate("admin", "password", 0L, dummyMap).first()); + assertEquals("20 byte salt authenticated", true, authenticator.authenticate("admin20Byte", "password", 0L, dummyMap).first()); + assertEquals("fake user not authenticated", false, authenticator.authenticate("fake", "fake", 0L, dummyMap).first()); + assertEquals("bad password not authenticated", false, authenticator.authenticate("admin", "fake", 0L, dummyMap).first()); + assertEquals("20 byte user bad password not authenticated", false, authenticator.authenticate("admin20Byte", "fake", 0L, dummyMap).first()); } // @Test diff --git a/pom.xml b/pom.xml index 3ddaeb03d3c..1d2304ffcc6 100644 --- a/pom.xml +++ b/pom.xml @@ -34,7 +34,7 @@ - 1.6 + 1.7 UTF-8 1.2.16 @@ -87,6 +87,7 @@ 1.0.10 4.0.0 2.11 + 2.5 @@ -160,6 +161,7 @@ + tools/checkstyle api agent core @@ -170,12 +172,10 @@ engine plugins framework - test client services maven-standard quickcloud - parents/checkstyle @@ -445,37 +445,43 @@ ${basedir}/${cs.target.dir}/classes ${basedir}/${cs.target.dir}/test-classes - @@ -483,6 +489,63 @@ org.apache.maven.plugins maven-checkstyle-plugin ${cs.checkstyle.version} + + + org.apache.cloudstack + checkstyle + ${project.version} + + + + + cloudstack-checkstyle + validate + + check + + + + + true + cloud-style.xml + true + true + ${project.basedir} + **\/*.java + **\/deps\/,**\/test\/,**\/target\/,**\/bin\/,**\/*.xml,**\/*.ini,**\/*.sh,**\/*.bat,**\/awsapi\/,**\/XenServerJava\/,**\/apidoc\/ + + + + com.mycila + license-maven-plugin + ${cs.mycila.license.version} + + + cloudstack-checklicence + process-classes + + check + + + + + true + true +
LICENSE.header
+ + XML_STYLE +     DOUBLESLASH_STYLE +     SEMICOLON_STYLE + + false + + **/target/** + .settings/** + .checkstyle + .project + .classpath + +
maven-clean-plugin @@ -527,6 +590,15 @@ + + org.apache.maven.plugins + maven-site-plugin + 3.3 + + 9000 + ${basedir}/target/site/tempdir + + @@ -549,6 +621,47 @@ + + + org.apache.maven.plugins + maven-dependency-plugin + [2.0,) + + copy-dependencies + + + + + + + + + com.mycila + license-maven-plugin + [2.5,) + + format + check + + + + + + + + + org.codehaus.gmaven + gmaven-plugin + [1.3,) + + compile + testCompile + + + + + + @@ -653,7 +766,6 @@ ui/lib/qunit/qunit.js ui/lib/reset.css ui/lib/require.js - waf systemvm/conf/agent.properties systemvm/conf/environment.properties systemvm/js/jquery.js @@ -750,10 +862,64 @@ + + org.codehaus.mojo + findbugs-maven-plugin + 2.5.3 + + Max + High + true + false + 2048 + + + + cloudstack-findbugs + + check + + + +
- + + + + org.codehaus.mojo + findbugs-maven-plugin + + Low + Default + + + + org.apache.maven.plugins + maven-javadoc-plugin + + 128m + 1g + + + + org.apache.maven.plugins + maven-project-info-reports-plugin + 2.7 + + + org.codehaus.mojo + cobertura-maven-plugin + 2.6 + + + org.apache.maven.plugins + maven-site-plugin + 3.3 + + + awsapi @@ -784,6 +950,7 @@ tools/devcloud/devcloud.cfg + test developer tools @@ -795,7 +962,6 @@ developer - @@ -809,5 +975,41 @@ vmware-base + + disablecheckstyle + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + cloudstack-checkstyle + none + true + + + + + + + + enablefindbugs + + + + org.codehaus.mojo + findbugs-maven-plugin + + + cloudstack-findbugs + process-classes + true + + + + + + diff --git a/scripts/network/domr/bumpUpPriority.sh b/scripts/network/domr/bumpUpPriority.sh deleted file mode 100755 index 3a7eaf94e4e..00000000000 --- a/scripts/network/domr/bumpUpPriority.sh +++ /dev/null @@ -1,47 +0,0 @@ -#!/bin/bash -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - - -usage() { - printf "Usage:\n %s \n" $(basename $0) >&2 - printf " %s \n" $(basename $0) >&2 -} - -cert="/root/.ssh/id_rsa.cloud" -domRIp=$1 -shift - -check_gw() { - ping -c 1 -n -q $1 > /dev/null - if [ $? -gt 0 ] - then - sleep 1 - ping -c 1 -n -q $1 > /dev/null - fi - return $?; -} - - -check_gw "$domRIp" -if [ $? -gt 0 ] -then - exit 1 -fi - -ssh -p 3922 -q -o StrictHostKeyChecking=no -i $cert root@$domRIp "/root/bumpup_priority.sh" -exit $? diff --git a/scripts/network/domr/call_firewall.sh b/scripts/network/domr/call_firewall.sh deleted file mode 100755 index f6ad0be1316..00000000000 --- a/scripts/network/domr/call_firewall.sh +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/env bash -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - - -# $Id: call_firewall.sh 9132 2010-06-04 20:17:43Z manuel $ $HeadURL: svn://svn.lab.vmops.com/repos/branches/2.0.0/java/scripts/vm/hypervisor/xenserver/patch/call_firewall.sh $ -# firewall.sh -- allow some ports / protocols to vm instances -usage() { - printf "Usage for Firewall rule : %s: -F " $(basename $0) >&2 - printf "Usage for other purposes : %s: (-A|-D) -i -r -P protocol (-p port_range | -t icmp_type_code) -l -d [-f -u -y -z ] \n" $(basename $0) >&2 -} - -#set -x - -check_gw() { - ping -c 1 -n -q $1 > /dev/null - if [ $? -gt 0 ] - then - sleep 1 - ping -c 1 -n -q $1 > /dev/null - fi - return $?; -} - -cert="/root/.ssh/id_rsa.cloud" -domRIp=$1 -shift - -check_gw "$domRIp" -if [ $? -gt 0 ] -then - exit 1 -fi -fflag= -eflag= -while getopts ':FE' OPTION -do - case $OPTION in - F) fflag=1 - ;; - E) eflag=1 - ;; - \?) ;; - esac -done - -if [ -n "$eflag" ] -then - ssh -p 3922 -q -o StrictHostKeyChecking=no -i $cert root@$domRIp "/root/firewallRule_egress.sh $*" -elif [ -n "$fflag" ] -then - ssh -p 3922 -q -o StrictHostKeyChecking=no -i $cert root@$domRIp "/root/firewall_rule.sh $*" -else - ssh -p 3922 -q -o StrictHostKeyChecking=no -i $cert root@$domRIp "/root/firewall.sh $*" -fi -exit $? diff --git a/scripts/network/domr/call_loadbalancer.sh b/scripts/network/domr/call_loadbalancer.sh deleted file mode 100755 index 070947cbb15..00000000000 --- a/scripts/network/domr/call_loadbalancer.sh +++ /dev/null @@ -1,101 +0,0 @@ -#!/usr/bin/env bash -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - - -# $Id: call_loadbalancer.sh 9132 2010-06-04 20:17:43Z manuel $ $HeadURL: svn://svn.lab.vmops.com/repos/branches/2.0.0/java/scripts/vm/hypervisor/xenserver/patch/call_loadbalancer.sh $ -# loadbalancer.sh -- reconfigure loadbalancer rules - -usage() { - printf "Usage: %s: -i -a -d -f -s \n" $(basename $0) >&2 -} - -set -x - -check_gw() { - ping -c 1 -n -q $1 > /dev/null - if [ $? -gt 0 ] - then - sleep 1 - ping -c 1 -n -q $1 > /dev/null - fi - return $?; -} - -copy_haproxy() { - local domRIp=$1 - local cfg=$2 - - scp -P 3922 -q -o StrictHostKeyChecking=no -i $cert $cfg root@$domRIp:/etc/haproxy/haproxy.cfg.new - return $? -} - -iflag= -aflag= -dflag= -fflag= -sflag= - -while getopts 'i:a:d:f:s:' OPTION -do - case $OPTION in - i) iflag=1 - domRIp="$OPTARG" - ;; - a) aflag=1 - addedIps="$OPTARG" - ;; - d) dflag=1 - removedIps="$OPTARG" - ;; - f) fflag=1 - cfgfile="$OPTARG" - ;; - s) sflag=1 - statsIps="$OPTARG" - ;; - ?) usage - exit 2 - ;; - esac -done - -cert="/root/.ssh/id_rsa.cloud" - -if [ "$iflag$fflag" != "11" ] -then - usage - exit 2 -fi - -# Check if DomR is up and running. If it isn't, exit 1. -check_gw "$domRIp" -if [ $? -gt 0 ] -then - exit 1 -fi - -copy_haproxy $domRIp $cfgfile - -if [ $? -gt 0 ] -then - printf "Reconfiguring loadbalancer failed\n" - exit 1 -fi - -ssh -p 3922 -q -o StrictHostKeyChecking=no -i $cert root@$domRIp "/root/loadbalancer.sh $*" -exit $? diff --git a/scripts/network/domr/dhcp_entry.sh b/scripts/network/domr/dhcp_entry.sh deleted file mode 100755 index fb5a1669e72..00000000000 --- a/scripts/network/domr/dhcp_entry.sh +++ /dev/null @@ -1,82 +0,0 @@ -#!/bin/bash -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - - -# $Id: dhcp_entry.sh 9804 2010-06-22 18:36:49Z alex $ $HeadURL: svn://svn.lab.vmops.com/repos/vmdev/java/scripts/network/domr/dhcp_entry.sh $ -# dhcp_entry.sh -- add dhcp entry on domr -# @VERSION@ - -usage() { - printf "Usage: %s: -r -m -v -n -s -d -N -6 -u [-z]\n" $(basename $0) >&2 - exit 2 -} - -cert="/root/.ssh/id_rsa.cloud" - -domrIp= -vmMac= -vmIp= -vmName= -staticrt= -dfltrt= -dns= -ipv6= -duid= - -opts= - -while getopts 'r:m:v:n:d:s:N:6:u:z' OPTION -do - case $OPTION in - r) domrIp="$OPTARG" - ;; - v) vmIp="$OPTARG" - opts="$opts -4 $vmIp" - ;; - m) vmMac="$OPTARG" - opts="$opts -m $vmMac" - ;; - n) vmName="$OPTARG" - opts="$opts -h $vmName" - ;; - s) staticrt="$OPTARG" - opts="$opts -s $staticrt" - ;; - d) dfltrt="$OPTARG" - opts="$opts -d $dfltrt" - ;; - N) dns="$OPTARG" - opts="$opts -n $dns" - ;; - 6) ipv6="$OPTARG" - opts="$opts -6 $ipv6" - ;; - u) duid="$OPTARG" - opts="$opts -u $duid" - ;; - z) opts="$opts -N" - ;; - ?) usage - exit 1 - ;; - esac -done - -ssh -p 3922 -o StrictHostKeyChecking=no -i $cert root@$domrIp "/root/edithosts.sh $opts " >/dev/null - -exit $? diff --git a/scripts/network/domr/save_password_to_domr.sh b/scripts/network/domr/save_password_to_domr.sh deleted file mode 100755 index 9b44663fd79..00000000000 --- a/scripts/network/domr/save_password_to_domr.sh +++ /dev/null @@ -1,73 +0,0 @@ -#!/bin/bash -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - - -# $Id: save_password_to_domr.sh 9804 2010-06-22 18:36:49Z alex $ $HeadURL: svn://svn.lab.vmops.com/repos/vmdev/java/scripts/network/domr/save_password_to_domr.sh $ -# @VERSION@ - -PASSWD_FILE=/var/cache/cloud/passwords - -# $1 filename -# $2 keyname -# $3 value -replace_in_file_on_domr() { - local filename=$1 - local keyname=$2 - local value=$3 - $VIA_SSH "sed -i /$keyname=/d $filename; \ - echo "$keyname=$value" >> $filename " - - # $VIA_SSH "sed -e /$keyname/d $filename > $filename.new; \ - # mv $filename.new $filename;\ - # echo "$keyname=$value" >> $filename " - - return $? -} - -cert="/root/.ssh/id_rsa.cloud" - -while getopts 'r:v:p:' OPTION -do - case $OPTION in - r) - DOMR_IP="$OPTARG" - ;; - v) VM_IP="$OPTARG" - ;; - p) - ENCODEDPASSWORD="$OPTARG" - PASSWORD=$(echo $ENCODEDPASSWORD | tr '[a-m][n-z][A-M][N-Z]' '[n-z][a-m][N-Z][A-M]') - ;; - ?) echo "Incorrect usage" - exit 1 - ;; - esac -done - -VIA_SSH="ssh -p 3922 -o StrictHostKeyChecking=no -i $cert root@$DOMR_IP" - -$VIA_SSH "if [ ! -f $PASSWD_FILE ]; then touch $PASSWD_FILE; fi;" - -replace_in_file_on_domr $PASSWD_FILE $VM_IP $PASSWORD - -if [ $? -ne 0 ] -then - exit 1 -fi - -exit 0 diff --git a/scripts/storage/secondary/createtmplt.sh b/scripts/storage/secondary/createtmplt.sh index 05874b4be09..6b31232bc9e 100755 --- a/scripts/storage/secondary/createtmplt.sh +++ b/scripts/storage/secondary/createtmplt.sh @@ -174,7 +174,7 @@ isCifs() { #then check if the template file is from cifs using df -P filename #Currently only cifs is supported in hyperv zone. mount | grep "type cifs" > /dev/null - return $? + echo $? } if [ "$tflag$nflag$fflag$sflag" != "1111" ] @@ -204,7 +204,7 @@ rollback_if_needed $tmpltfs $? "tar archives not supported\n" if [ ${tmpltname%.vhd} != ${tmpltname} ] then - if [ isCifs -ne 0 ] ; + if [ $(isCifs) -ne 0 ] ; then if which vhd-util &>/dev/null then diff --git a/scripts/storage/secondary/createvolume.sh b/scripts/storage/secondary/createvolume.sh index f11df1d7c67..8cbccc66e19 100755 --- a/scripts/storage/secondary/createvolume.sh +++ b/scripts/storage/secondary/createvolume.sh @@ -111,6 +111,14 @@ uncompress() { return 0 } +isCifs() { + #TO:DO incase of multiple zone where cifs and nfs exists, + #then check if the template file is from cifs using df -P filename + #Currently only cifs is supported in hyperv zone. + mount | grep "type cifs" > /dev/null + echo $? +} + create_from_file() { local tmpltfs=$1 local tmpltimg=$2 @@ -196,12 +204,15 @@ rollback_if_needed $tmpltfs $? "tar archives not supported\n" if [ ${tmpltname%.vhd} != ${tmpltname} ] then - if which vhd-util &>/dev/null - then - vhd-util check -n ${tmpltimg2} > /dev/null - rollback_if_needed $tmpltfs $? "vhd check of $tmpltimg2 failed\n" - vhd-util set -n ${tmpltimg2} -f "hidden" -v "0" > /dev/null - rollback_if_needed $tmpltfs $? "vhd remove $tmpltimg2 hidden failed\n" + if [ isCifs -ne 0 ] ; + then + if which vhd-util &>/dev/null + then + vhd-util check -n ${tmpltimg2} > /dev/null + rollback_if_needed $tmpltfs $? "vhd check of $tmpltimg2 failed\n" + vhd-util set -n ${tmpltimg2} -f "hidden" -v "0" > /dev/null + rollback_if_needed $tmpltfs $? "vhd remove $tmpltimg2 hidden failed\n" + fi fi fi diff --git a/scripts/vm/hypervisor/xenserver/cloudlog b/scripts/vm/hypervisor/xenserver/cloudlog index 19560ef50e2..6689efeb920 100644 --- a/scripts/vm/hypervisor/xenserver/cloudlog +++ b/scripts/vm/hypervisor/xenserver/cloudlog @@ -1,3 +1,28 @@ +#!/usr/bin/python +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# Version @VERSION@ +# +# A log rotat config for CS plugin log + + + + /var/log/cloud/vmops.log { daily size 1M diff --git a/scripts/vm/hypervisor/xenserver/hostvmstats.py b/scripts/vm/hypervisor/xenserver/hostvmstats.py index 38609b15c9f..61cf2de99f2 100644 --- a/scripts/vm/hypervisor/xenserver/hostvmstats.py +++ b/scripts/vm/hypervisor/xenserver/hostvmstats.py @@ -21,8 +21,17 @@ import XenAPI import urllib import time import logging -logging.basicConfig(filename='/tmp/xapilog',level=logging.DEBUG) - +import logging.handlers + +LOG_FILENAME = '/tmp/xapilog' +logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG) +stats_logger = logging.getLogger('statsLogger') +stats_logger.setLevel(logging.DEBUG) + +#handler with maxBytes=10MiB +handler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=10*1024*1024, backupCount=5) +stats_logger.addHandler(handler) + def get_stats(session, collect_host_stats, consolidation_function, interval, start_time): try: @@ -41,12 +50,12 @@ def get_stats(session, collect_host_stats, consolidation_function, interval, sta url += "&interval=" + str(interval) url += "&start=" + str(int(time.time())-100) - logging.debug("Calling URL: %s",url) + stats_logger.debug("Calling URL: %s",url) sock = urllib.URLopener().open(url) xml = sock.read() sock.close() - logging.debug("Size of returned XML: %s",len(xml)) + stats_logger.debug("Size of returned XML: %s",len(xml)) return xml except Exception,e: - logging.exception("get_stats() failed") + stats_logger.exception("get_stats() failed") raise diff --git a/scripts/vm/hypervisor/xenserver/ovstunnel b/scripts/vm/hypervisor/xenserver/ovstunnel index 6ecd8ea7757..106be0441ce 100755 --- a/scripts/vm/hypervisor/xenserver/ovstunnel +++ b/scripts/vm/hypervisor/xenserver/ovstunnel @@ -82,6 +82,10 @@ def setup_ovs_bridge(session, args): # TODO: Make sure xs-network-uuid is set into external_ids lib.do_cmd([lib.VSCTL_PATH, "set", "Bridge", bridge, "external_ids:xs-network-uuid=%s" % xs_nw_uuid]) + + # enable stp + lib.do_cmd([lib.VSCTL_PATH, "set", "Bridge", bridge, "stp_enable=true"]) + # Non empty result means something went wrong if res: result = "FAILURE:%s" % res diff --git a/scripts/vm/hypervisor/xenserver/vhd-util b/scripts/vm/hypervisor/xenserver/vhd-util deleted file mode 100755 index 46d62dd44d9..00000000000 Binary files a/scripts/vm/hypervisor/xenserver/vhd-util and /dev/null differ diff --git a/scripts/vm/hypervisor/xenserver/vmops b/scripts/vm/hypervisor/xenserver/vmops index 2e14fad5b9c..2f0f347c783 100755 --- a/scripts/vm/hypervisor/xenserver/vmops +++ b/scripts/vm/hypervisor/xenserver/vmops @@ -177,21 +177,6 @@ def savePassword(session, args): return txt -@echo -def saveDhcpEntry(session, args): - sargs = args['args'] - cmd = sargs.split(' ') - cmd.insert(0, "/opt/cloud/bin/dhcp_entry.sh") - cmd.insert(0, "/bin/bash") - try: - txt = util.pread2(cmd) - txt = 'success' - except: - logging.debug(" save dhcp entry failed " ) - txt = '' - - return txt - @echo def setLinkLocalIP(session, args): brName = args['brName'] @@ -237,23 +222,6 @@ def setLinkLocalIP(session, args): txt = 'success' return txt - - -@echo -def setFirewallRule(session, args): - sargs = args['args'] - cmd = sargs.split(' ') - cmd.insert(0, "/opt/cloud/bin/call_firewall.sh") - cmd.insert(0, "/bin/bash") - try: - txt = util.pread2(cmd) - txt = 'success' - except: - logging.debug(" set firewall rule failed " ) - txt = '' - - return txt - @echo def routerProxy(session, args): sargs = args['args'] @@ -262,69 +230,10 @@ def routerProxy(session, args): cmd.insert(0, "/bin/bash") try: txt = util.pread2(cmd) - if txt is None or len(txt) == 0 : - txt = 'success' + txt = 'succ#' + txt except: logging.debug("routerProxy command " + sargs + " failed " ) - txt = '' - - return txt - - - -@echo -def setLoadBalancerRule(session, args): - sargs = args['args'] - cmd = sargs.split(' ') - cmd.insert(0, "/opt/cloud/bin/call_loadbalancer.sh") - cmd.insert(0, "/bin/bash") - try: - txt = util.pread2(cmd) - txt = 'success' - except: - logging.debug(" set loadbalancer rule failed " ) - txt = '' - - return txt -@echo -def configdnsmasq(session, args): - routerip = args['routerip'] - args = args['args'] - target = "root@"+routerip - try: - util.pread2(['ssh','-p','3922','-q','-o','StrictHostKeyChecking=no','-i','/root/.ssh/id_rsa.cloud',target,'/root/dnsmasq.sh',args]) - txt='success' - except: - logging.debug("failed to config dnsmasq server") - txt='' - return txt - -@echo -def createipAlias(session, args): - args = args['args'] - cmd = args.split(' ') - cmd.insert(0, "/opt/cloud/bin/createipAlias.sh") - cmd.insert(0, "bin/bash") - try: - txt=util.pread2(cmd) - txt='success' - except: - logging.debug("failed to create ip alias on router vm") - txt='' - return txt - -@echo -def deleteipAlias(session, args): - args = args['args'] - cmd = args.split(' ') - cmd.insert(0, "/opt/cloud/bin/deleteipAlias.sh") - cmd.insert(0, "bin/bash") - try: - txt=util.pread2(cmd) - txt='success' - except: - logging.debug("failed to create ip alias on router vm") - txt='' + txt = 'fail#' + txt return txt @echo @@ -354,13 +263,12 @@ def createFileInDomr(session, args): f.write(file_contents) f.close() target = "root@" + domrip + ":" + file_path - util.pread2(['scp','-P','3922','-q','-o','StrictHostKeyChecking=no','-i','/root/.ssh/id_rsa.cloud',tmpfile, target]) + txt = util.pread2(['scp','-P','3922','-q','-o','StrictHostKeyChecking=no','-i','/root/.ssh/id_rsa.cloud',tmpfile, target]) util.pread2(['rm',tmpfile]) - txt = 'success' + txt = 'succ#' + txt except: - logging.debug(" failed to create HA proxy cfg file ") - txt = '' - + logging.debug("failed to create file " + file_path + " in VR, contain: " + file_contents) + txt = 'fail#' + txt return txt @echo @@ -1608,41 +1516,21 @@ def network_rules(session, args): except: logging.debug("Failed to network rule !") -@echo -def bumpUpPriority(session, args): - sargs = args['args'] - cmd = sargs.split(' ') - cmd.insert(0, "/opt/cloud/bin/bumpUpPriority.sh") - cmd.insert(0, "/bin/bash") - try: - txt = util.pread2(cmd) - txt = 'success' - except: - logging.debug("bump up priority fail! ") - txt = '' - - return txt - - if __name__ == "__main__": XenAPIPlugin.dispatch({"pingtest": pingtest, "setup_iscsi":setup_iscsi, "gethostvmstats": gethostvmstats, "getgateway": getgateway, "preparemigration": preparemigration, "setIptables": setIptables, "pingdomr": pingdomr, "pingxenserver": pingxenserver, "savePassword": savePassword, - "saveDhcpEntry": saveDhcpEntry, "setFirewallRule": setFirewallRule, "routerProxy": routerProxy, - "setLoadBalancerRule": setLoadBalancerRule, "createFile": createFile, "deleteFile": deleteFile, + "routerProxy": routerProxy, + "createFile": createFile, "deleteFile": deleteFile, "network_rules":network_rules, "can_bridge_firewall":can_bridge_firewall, "default_network_rules":default_network_rules, "destroy_network_rules_for_vm":destroy_network_rules_for_vm, "default_network_rules_systemvm":default_network_rules_systemvm, "network_rules_vmSecondaryIp":network_rules_vmSecondaryIp, - "createipAlias":createipAlias, - "configdnsmasq":configdnsmasq, - "deleteipAlias":deleteipAlias, "get_rule_logs_for_vms":get_rule_logs_for_vms, "add_to_VCPUs_params_live":add_to_VCPUs_params_live, "setLinkLocalIP":setLinkLocalIP, "cleanup_rules":cleanup_rules, - "bumpUpPriority":bumpUpPriority, "createFileInDomr":createFileInDomr, "kill_copy_process":kill_copy_process}) diff --git a/scripts/vm/hypervisor/xenserver/vmopsSnapshot b/scripts/vm/hypervisor/xenserver/vmopsSnapshot index a9a5a72ea62..5fd69a633f8 100755 --- a/scripts/vm/hypervisor/xenserver/vmopsSnapshot +++ b/scripts/vm/hypervisor/xenserver/vmopsSnapshot @@ -487,6 +487,18 @@ def getVhdParent(session, args): return baseCopyUuid +def getSnapshotSize(session, args): + primaryStorageSRUuid = args['primaryStorageSRUuid'] + snapshotUuid = args['snapshotUuid'] + isISCSI = getIsTrueString(args['isISCSI']) + + primarySRPath = getPrimarySRPath(primaryStorageSRUuid, isISCSI) + logging.debug("primarySRPath: " + primarySRPath) + + snapshotVHD = getVHD(snapshotUuid, isISCSI) + snapshotPath = os.path.join(primarySRPath, snapshotVHD) + physicalSize = vhdutil.getSizePhys(snapshotPath) + return str(physicalSize) def backupSnapshot(session, args): logging.debug("Called backupSnapshot with " + str(args)) @@ -515,6 +527,7 @@ def backupSnapshot(session, args): prevBackupUuid = prevBackupUuid.split("/")[-1] # Check existence of snapshot on primary storage isfile(baseCopyPath, isISCSI) + physicalSize = vhdutil.getSizePhys(baseCopyPath) if prevBackupUuid: # Check existence of prevBackupFile prevBackupVHD = getBackupVHD(prevBackupUuid) @@ -535,7 +548,7 @@ def backupSnapshot(session, args): # If there was a previous snapshot setParent(prevBackupFile, backupFile) - txt = "1#" + backupUuid + txt = "1#" + backupUuid + "#" + str(physicalSize) return txt @echo @@ -596,6 +609,6 @@ def revert_memory_snapshot(session, args): return "0" if __name__ == "__main__": - XenAPIPlugin.dispatch({"getVhdParent":getVhdParent, "create_secondary_storage_folder":create_secondary_storage_folder, "delete_secondary_storage_folder":delete_secondary_storage_folder, "post_create_private_template":post_create_private_template, "backupSnapshot": backupSnapshot, "deleteSnapshotBackup": deleteSnapshotBackup, "unmountSnapshotsDir": unmountSnapshotsDir, "revert_memory_snapshot":revert_memory_snapshot}) + XenAPIPlugin.dispatch({"getVhdParent":getVhdParent, "create_secondary_storage_folder":create_secondary_storage_folder, "delete_secondary_storage_folder":delete_secondary_storage_folder, "post_create_private_template":post_create_private_template, "backupSnapshot": backupSnapshot, "deleteSnapshotBackup": deleteSnapshotBackup, "unmountSnapshotsDir": unmountSnapshotsDir, "revert_memory_snapshot":revert_memory_snapshot, "getSnapshotSize":getSnapshotSize}) diff --git a/scripts/vm/hypervisor/xenserver/vmopspremium b/scripts/vm/hypervisor/xenserver/vmopspremium index 143aa922a8a..06b0a51f7ed 100755 --- a/scripts/vm/hypervisor/xenserver/vmopspremium +++ b/scripts/vm/hypervisor/xenserver/vmopspremium @@ -28,7 +28,6 @@ if os.path.exists("/usr/lib/xcp/sm"): sys.path.extend(["/usr/lib/xcp/sm/", "/usr/local/sbin/", "/sbin/"]) import util import socket -import perfmon import cloudstack_pluginlib as lib import logging @@ -149,8 +148,12 @@ def heartbeat(session, args): @echo def asmonitor(session, args): - result = perfmon.get_vm_group_perfmon(args) - return result + try: + perfmod = __import__("perfmon") + result = perfmod.get_vm_group_perfmon(args) + return result + except: + return 'fail' if __name__ == "__main__": XenAPIPlugin.dispatch({"forceShutdownVM":forceShutdownVM, "upgrade_snapshot":upgrade_snapshot, "create_privatetemplate_from_snapshot":create_privatetemplate_from_snapshot, "copy_vhd_to_secondarystorage":copy_vhd_to_secondarystorage, "copy_vhd_from_secondarystorage":copy_vhd_from_secondarystorage, "setup_heartbeat_sr":setup_heartbeat_sr, "setup_heartbeat_file":setup_heartbeat_file, "check_heartbeat":check_heartbeat, "heartbeat": heartbeat, "asmonitor": asmonitor}) diff --git a/scripts/vm/hypervisor/xenserver/xenserver56/patch b/scripts/vm/hypervisor/xenserver/xenserver56/patch index 50116935789..9473bca8d5c 100644 --- a/scripts/vm/hypervisor/xenserver/xenserver56/patch +++ b/scripts/vm/hypervisor/xenserver/xenserver56/patch @@ -29,6 +29,7 @@ NFSSR.py=/opt/xensource/sm vmops=..,0755,/etc/xapi.d/plugins vmopsSnapshot=..,0755,/etc/xapi.d/plugins +cloudstack_pluginlib.py=..,0755,/etc/xapi.d/plugins hostvmstats.py=..,0755,/opt/xensource/sm systemvm.iso=../../../../../vms,0644,/opt/xensource/packages/iso id_rsa.cloud=../../../systemvm,0600,/root/.ssh diff --git a/scripts/vm/hypervisor/xenserver/xenserver56fp1/patch b/scripts/vm/hypervisor/xenserver/xenserver56fp1/patch index 55d538edf4a..c91aa73821a 100644 --- a/scripts/vm/hypervisor/xenserver/xenserver56fp1/patch +++ b/scripts/vm/hypervisor/xenserver/xenserver56fp1/patch @@ -29,6 +29,7 @@ NFSSR.py=/opt/xensource/sm vmops=..,0755,/etc/xapi.d/plugins vmopsSnapshot=..,0755,/etc/xapi.d/plugins +cloudstack_pluginlib.py=..,0755,/etc/xapi.d/plugins hostvmstats.py=..,0755,/opt/xensource/sm systemvm.iso=../../../../../vms,0644,/opt/xensource/packages/iso id_rsa.cloud=../../../systemvm,0600,/root/.ssh diff --git a/scripts/vm/hypervisor/xenserver/xenserver62/cloud-plugin-storage b/scripts/vm/hypervisor/xenserver/xenserver62/cloud-plugin-storage new file mode 100644 index 00000000000..03a05b75480 --- /dev/null +++ b/scripts/vm/hypervisor/xenserver/xenserver62/cloud-plugin-storage @@ -0,0 +1,301 @@ +#!/usr/bin/python +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# Version @VERSION@ +# +# A plugin for executing script needed by vmops cloud + +import os, sys, time +import XenAPIPlugin +if os.path.exists("/opt/xensource/sm"): + sys.path.extend(["/opt/xensource/sm/", "/usr/local/sbin/", "/sbin/"]) +if os.path.exists("/usr/lib/xcp/sm"): + sys.path.extend(["/usr/lib/xcp/sm/", "/usr/local/sbin/", "/sbin/"]) + +import SR, VDI, SRCommand, util, lvutil +from util import CommandException +import vhdutil +import shutil +import lvhdutil +import errno +import subprocess +import xs_errors +import cleanup +import stat +import random +import cloudstack_pluginlib as lib +import logging + +lib.setup_logging("/var/log/cloud/vmops.log") + +VHDUTIL = "vhd-util" +VHD_PREFIX = 'VHD-' +CLOUD_DIR = '/var/run/cloud_mount' + +def echo(fn): + def wrapped(*v, **k): + name = fn.__name__ + logging.debug("#### VMOPS enter %s ####" % name ) + res = fn(*v, **k) + logging.debug("#### VMOPS exit %s ####" % name ) + return res + return wrapped + +def getPrimarySRPath(primaryStorageSRUuid, isISCSI): + if isISCSI: + primarySRDir = lvhdutil.VG_PREFIX + primaryStorageSRUuid + return os.path.join(lvhdutil.VG_LOCATION, primarySRDir) + else: + return os.path.join(SR.MOUNT_BASE, primaryStorageSRUuid) + +def getBackupVHD(UUID): + return UUID + '.' + SR.DEFAULT_TAP + +def getVHD(UUID, isISCSI): + if isISCSI: + return VHD_PREFIX + UUID + else: + return UUID + '.' + SR.DEFAULT_TAP + +def getIsTrueString(stringValue): + booleanValue = False + if (stringValue and stringValue == 'true'): + booleanValue = True + return booleanValue + +def makeUnavailable(uuid, primarySRPath, isISCSI): + if not isISCSI: + return + VHD = getVHD(uuid, isISCSI) + path = os.path.join(primarySRPath, VHD) + manageAvailability(path, '-an') + return + +def manageAvailability(path, value): + if path.__contains__("/var/run/sr-mount"): + return + logging.debug("Setting availability of " + path + " to " + value) + try: + cmd = ['/usr/sbin/lvchange', value, path] + util.pread2(cmd) + except: #CommandException, (rc, cmdListStr, stderr): + #errMsg = "CommandException thrown while executing: " + cmdListStr + " with return code: " + str(rc) + " and stderr: " + stderr + errMsg = "Unexpected exception thrown by lvchange" + logging.debug(errMsg) + if value == "-ay": + # Raise an error only if we are trying to make it available. + # Just warn if we are trying to make it unavailable after the + # snapshot operation is done. + raise xs_errors.XenError(errMsg) + return + + +def checkVolumeAvailablility(path): + try: + if not isVolumeAvailable(path): + # The VHD file is not available on XenSever. The volume is probably + # inactive or detached. + # Do lvchange -ay to make it available on XenServer + manageAvailability(path, '-ay') + except: + errMsg = "Could not determine status of ISCSI path: " + path + logging.debug(errMsg) + raise xs_errors.XenError(errMsg) + + success = False + i = 0 + while i < 6: + i = i + 1 + # Check if the vhd is actually visible by checking for the link + # set isISCSI to true + success = isVolumeAvailable(path) + if success: + logging.debug("Made vhd: " + path + " available and confirmed that it is visible") + break + + # Sleep for 10 seconds before checking again. + time.sleep(10) + + # If not visible within 1 min fail + if not success: + logging.debug("Could not make vhd: " + path + " available despite waiting for 1 minute. Does it exist?") + + return success + +def isVolumeAvailable(path): + # Check if iscsi volume is available on this XenServer. + status = "0" + try: + p = subprocess.Popen(["/bin/bash", "-c", "if [ -L " + path + " ]; then echo 1; else echo 0;fi"], stdout=subprocess.PIPE) + status = p.communicate()[0].strip("\n") + except: + errMsg = "Could not determine status of ISCSI path: " + path + logging.debug(errMsg) + raise xs_errors.XenError(errMsg) + + return (status == "1") + +def scanParent(path): + # Do a scan for the parent for ISCSI volumes + # Note that the parent need not be visible on the XenServer + parentUUID = '' + try: + lvName = os.path.basename(path) + dirname = os.path.dirname(path) + vgName = os.path.basename(dirname) + vhdInfo = vhdutil.getVHDInfoLVM(lvName, lvhdutil.extractUuid, vgName) + parentUUID = vhdInfo.parentUuid + except: + errMsg = "Could not get vhd parent of " + path + logging.debug(errMsg) + raise xs_errors.XenError(errMsg) + return parentUUID + +def getParentOfSnapshot(snapshotUuid, primarySRPath, isISCSI): + snapshotVHD = getVHD(snapshotUuid, isISCSI) + snapshotPath = os.path.join(primarySRPath, snapshotVHD) + + baseCopyUuid = '' + if isISCSI: + checkVolumeAvailablility(snapshotPath) + baseCopyUuid = scanParent(snapshotPath) + else: + baseCopyUuid = getParent(snapshotPath, isISCSI) + + logging.debug("Base copy of snapshotUuid: " + snapshotUuid + " is " + baseCopyUuid) + return baseCopyUuid + +def getParent(path, isISCSI): + parentUUID = '' + try : + if isISCSI: + parentUUID = vhdutil.getParent(path, lvhdutil.extractUuid) + else: + parentUUID = vhdutil.getParent(path, cleanup.FileVDI.extractUuid) + except: + errMsg = "Could not get vhd parent of " + path + logging.debug(errMsg) + raise xs_errors.XenError(errMsg) + return parentUUID + +def getVhdParent(session, args): + logging.debug("getParent with " + str(args)) + try: + primaryStorageSRUuid = args['primaryStorageSRUuid'] + snapshotUuid = args['snapshotUuid'] + isISCSI = getIsTrueString(args['isISCSI']) + + primarySRPath = getPrimarySRPath(primaryStorageSRUuid, isISCSI) + logging.debug("primarySRPath: " + primarySRPath) + + baseCopyUuid = getParentOfSnapshot(snapshotUuid, primarySRPath, isISCSI) + + return baseCopyUuid + except: + logging.debug('getVhdParent', exc_info=True) + raise xs_errors.XenError("Failed to getVhdParent") +def makedirs(path): + if not os.path.isdir(path): + try: + os.makedirs(path) + except OSError, (errno, strerror): + umount(path) + if os.path.isdir(path): + return + errMsg = "OSError while creating " + path + " with errno: " + str(errno) + " and strerr: " + strerror + logging.debug(errMsg) + raise xs_errors.XenError(errMsg) + return + +def umount(localDir): + try: + cmd = ['umount', localDir] + util.pread2(cmd) + except CommandException: + errMsg = "CommandException raised while trying to umount " + localDir + logging.debug(errMsg) + raise xs_errors.XenError(errMsg) + + logging.debug("Successfully unmounted " + localDir) + return + +@echo +def mountNfsSecondaryStorage(session, args): + remoteDir = args['remoteDir'] + localDir = args['localDir'] + mounted = False + f = open("/proc/mounts", 'r') + for line in f: + tokens = line.split(" ") + if len(tokens) > 2 and tokens[0] == remoteDir and tokens[1] == localDir: + mounted = True + + if mounted: + return "true" + + makedirs(localDir) + options = "soft,tcp,timeo=133,retrans=1" + try: + cmd = ['mount', '-o', options, remoteDir, localDir] + txt = util.pread2(cmd) + except: + txt = '' + errMsg = "Unexpected error while trying to mount " + remoteDir + " to " + localDir + logging.debug(errMsg) + raise xs_errors.XenError(errMsg) + logging.debug("Successfully mounted " + remoteDir + " to " + localDir) + + return "true" + +@echo +def umountNfsSecondaryStorage(session, args): + localDir = args['localDir'] + try: + cmd = ['umount', localDir] + util.pread2(cmd) + except CommandException: + errMsg = "CommandException raised while trying to umount " + localDir + logging.debug(errMsg) + raise xs_errors.XenError(errMsg) + try: + os.system("rmdir " + localDir) + except: + pass + logging.debug("Successfully unmounted " + localDir) + return "true" + +@echo +def makeDirectory(session, args): + path = args['path'] + if not os.path.isdir(path): + try: + os.makedirs(path) + except OSError, (errno, strerror): + if os.path.isdir(path): + return "true" + errMsg = "OSError while creating " + path + " with errno: " + str(errno) + " and strerr: " + strerror + logging.debug(errMsg) + raise xs_errors.XenError(errMsg) + return "true" + +if __name__ == "__main__": + XenAPIPlugin.dispatch({"getVhdParent":getVhdParent, "mountNfsSecondaryStorage":mountNfsSecondaryStorage, + "umountNfsSecondaryStorage":umountNfsSecondaryStorage, + "makeDirectory":makeDirectory}) + + diff --git a/scripts/vm/hypervisor/xenserver/xenserver62/patch b/scripts/vm/hypervisor/xenserver/xenserver62/patch new file mode 100644 index 00000000000..70b86b4ffe5 --- /dev/null +++ b/scripts/vm/hypervisor/xenserver/xenserver62/patch @@ -0,0 +1,74 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# This file specifies the files that need +# to be transferred over to the XenServer. +# The format of this file is as follows: +# [Name of file]=[source path],[file permission],[destination path] +# [destination path] is required. +# If [file permission] is missing, 755 is assumed. +# If [source path] is missing, it looks in the same +# directory as the patch file. +# If [source path] starts with '/', then it is absolute path. +# If [source path] starts with '~', then it is path relative to management server home directory. +# If [source path] does not start with '/' or '~', then it is relative path to the location of the patch file. +vmops=..,0755,/etc/xapi.d/plugins +vmopspremium=..,0755,/etc/xapi.d/plugins +xen-ovs-vif-flows.rules=..,0644,/etc/udev/rules.d +ovs-vif-flows.py=..,0755,/etc/xapi.d/plugins +cloudstack_plugins.conf=..,0644,/etc/xensource +cloudstack_pluginlib.py=..,0755,/etc/xapi.d/plugins +ovstunnel=..,0755,/etc/xapi.d/plugins +cloud-plugin-storage=,0755,/etc/xapi.d/plugins +hostvmstats.py=..,0755,/opt/xensource/sm +systemvm.iso=../../../../../vms,0644,/opt/xensource/packages/iso +id_rsa.cloud=../../../systemvm,0600,/root/.ssh +network_info.sh=..,0755,/opt/cloud/bin +setupxenserver.sh=..,0755,/opt/cloud/bin +make_migratable.sh=..,0755,/opt/cloud/bin +createipAlias.sh=..,0755,/opt/cloud/bin +deleteipAlias.sh=..,0755,/opt/cloud/bin +setup_iscsi.sh=..,0755,/opt/cloud/bin +pingtest.sh=../../..,0755,/opt/cloud/bin +dhcp_entry.sh=../../../../network/domr/,0755,/opt/cloud/bin +save_password_to_domr.sh=../../../../network/domr/,0755,/opt/cloud/bin +call_firewall.sh=../../../../network/domr/,0755,/opt/cloud/bin +call_loadbalancer.sh=../../../../network/domr/,0755,/opt/cloud/bin +router_proxy.sh=../../../../network/domr/,0755,/opt/cloud/bin +cloud-setup-bonding.sh=..,0755,/opt/cloud/bin +kill_copy_process.sh=..,0755,/opt/cloud/bin +setup_heartbeat_sr.sh=..,0755,/opt/cloud/bin +setup_heartbeat_file.sh=..,0755,/opt/cloud/bin +check_heartbeat.sh=..,0755,/opt/cloud/bin +xenheartbeat.sh=..,0755,/opt/cloud/bin +launch_hb.sh=..,0755,/opt/cloud/bin +vhd-util=..,0755,/opt/cloud/bin +upgrade_snapshot.sh=..,0755,/opt/cloud/bin +cloud-clean-vlan.sh=..,0755,/opt/cloud/bin +cloud-prepare-upgrade.sh=..,0755,/opt/cloud/bin +bumpUpPriority.sh=../../../../network/domr/,0755,/opt/cloud/bin +swift=..,0755,/opt/cloud/bin +swiftxen=..,0755,/etc/xapi.d/plugins +s3xen=..,0755,/etc/xapi.d/plugins +add_to_vcpus_params_live.sh=..,0755,/opt/cloud/bin +ovs-pvlan=..,0755,/etc/xapi.d/plugins +ovs-pvlan-dhcp-host.sh=../../../network,0755,/opt/cloud/bin +ovs-pvlan-vm.sh=../../../network,0755,/opt/cloud/bin +ovs-pvlan-cleanup.sh=../../../network,0755,/opt/cloud/bin +ovs-get-dhcp-iface.sh=..,0755,/opt/cloud/bin +ovs-get-bridge.sh=..,0755,/opt/cloud/bin +cloudlog=..,0644,/etc/logrotate.d diff --git a/scripts/vm/network/security_group.py b/scripts/vm/network/security_group.py index a7c64b0984e..1d94de3d60b 100755 --- a/scripts/vm/network/security_group.py +++ b/scripts/vm/network/security_group.py @@ -700,7 +700,7 @@ def cleanup_rules(): logging.debug("vm " + vm_name + " is not running or paused, cleaning up iptable rules") cleanup.append(vm_name) - chainscmd = """ebtables-save | awk '/:i/ { gsub(/(^:|-(in|out))/, "") ; print $1}'""" + chainscmd = """ebtables-save | awk '/:i/ { gsub(/(^:|-(in|out|ips))/, "") ; print $1}'""" chains = execute(chainscmd).split('\n') for chain in chains: if 1 in [ chain.startswith(c) for c in ['r-', 'i-', 's-', 'v-'] ]: diff --git a/scripts/vm/network/vnet/ovstunnel.py b/scripts/vm/network/vnet/ovstunnel.py index 225876a88e1..9e054133b40 100755 --- a/scripts/vm/network/vnet/ovstunnel.py +++ b/scripts/vm/network/vnet/ovstunnel.py @@ -42,6 +42,10 @@ def setup_ovs_bridge(bridge, key, cs_host_id): #set gre_key to bridge res = lib.do_cmd([lib.VSCTL_PATH, "set", "bridge", bridge, "other_config:gre_key=%s" % key]) + + # enable stp + lib.do_cmd([lib.VSCTL_PATH, "set", "Bridge", bridge, "stp_enable=true"]) + logging.debug("Bridge has been manually created:%s" % res) if res: # result = "FAILURE:%s" % res diff --git a/server/pom.xml b/server/pom.xml index 7929cdf5830..1646dc706df 100644 --- a/server/pom.xml +++ b/server/pom.xml @@ -36,6 +36,11 @@ cloud-framework-cluster ${project.version}
+ + org.apache.cloudstack + cloud-framework-security + ${project.version} + javax.servlet servlet-api @@ -50,13 +55,6 @@ cloud-framework-jobs ${project.version} - org.apache.httpcomponents httpclient @@ -137,11 +135,6 @@
- - - resources - - test/resources @@ -196,7 +189,6 @@ maven-antrun-plugin - 1.7 generate-resource @@ -228,38 +220,5 @@ - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - - org.apache.maven.plugins - - - maven-antrun-plugin - - [1.7,) - - run - - - - - - - - - - - - diff --git a/server/resources/META-INF/cloudstack/core/spring-server-core-managers-context.xml b/server/resources/META-INF/cloudstack/core/spring-server-core-managers-context.xml index d37303476a8..53a294e4e00 100644 --- a/server/resources/META-INF/cloudstack/core/spring-server-core-managers-context.xml +++ b/server/resources/META-INF/cloudstack/core/spring-server-core-managers-context.xml @@ -20,11 +20,16 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" + xmlns:util="http://www.springframework.org/schema/util" + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd - http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd + http://www.springframework.org/schema/aop + http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context - http://www.springframework.org/schema/context/spring-context-3.0.xsd" + http://www.springframework.org/schema/context/spring-context-3.0.xsd + http://www.springframework.org/schema/util + http://www.springframework.org/schema/util/spring-util-3.0.xsd" > @@ -60,6 +65,7 @@ + @@ -114,12 +120,8 @@ - - - - @@ -230,5 +232,4 @@ class="org.apache.cloudstack.region.gslb.GlobalLoadBalancingRulesServiceImpl" /> - diff --git a/server/src/com/cloud/acl/DomainChecker.java b/server/src/com/cloud/acl/DomainChecker.java index 2e43da3b1da..31b273ff2d0 100755 --- a/server/src/com/cloud/acl/DomainChecker.java +++ b/server/src/com/cloud/acl/DomainChecker.java @@ -307,7 +307,9 @@ public class DomainChecker extends AdapterBase implements SecurityChecker { } } //didn't find in upper tree - if (zoneDomainRecord.getPath().contains(accountDomainRecord.getPath())) { + if (zoneDomainRecord != null && + accountDomainRecord != null && + zoneDomainRecord.getPath().contains(accountDomainRecord.getPath())) { return true; } } diff --git a/server/src/com/cloud/agent/manager/allocator/impl/FirstFitAllocator.java b/server/src/com/cloud/agent/manager/allocator/impl/FirstFitAllocator.java index 0bfe1926d1d..b77f8acce4d 100755 --- a/server/src/com/cloud/agent/manager/allocator/impl/FirstFitAllocator.java +++ b/server/src/com/cloud/agent/manager/allocator/impl/FirstFitAllocator.java @@ -296,7 +296,7 @@ public class FirstFitAllocator extends AdapterBase implements HostAllocator { boolean hostHasCpuCapability = _capacityMgr.checkIfHostHasCpuCapability(host.getId(), offering.getCpu(), offering.getSpeed()); boolean hostHasCapacity = _capacityMgr.checkIfHostHasCapacity(host.getId(), cpu_requested, ram_requested, false, cpuOvercommitRatio, memoryOvercommitRatio, - considerReservedCapacity); + considerReservedCapacity); if (hostHasCpuCapability && hostHasCapacity) { if (s_logger.isDebugEnabled()) { @@ -305,7 +305,7 @@ public class FirstFitAllocator extends AdapterBase implements HostAllocator { suitableHosts.add(host); } else { if (s_logger.isDebugEnabled()) { - s_logger.debug("Not using host " + host.getId() + "; host has cpu capability? " + hostHasCpuCapability + ", host has capacity?" + hostHasCapacity); + s_logger.debug("Not using host " + host.getId() + "; host has cpu capability? " + hostHasCpuCapability + ", host has capacity?" + hostHasCapacity); } avoid.addHost(host.getId()); } diff --git a/server/src/com/cloud/agent/manager/allocator/impl/UserConcentratedAllocator.java b/server/src/com/cloud/agent/manager/allocator/impl/UserConcentratedAllocator.java index b67eccbd2d7..946eee6da49 100755 --- a/server/src/com/cloud/agent/manager/allocator/impl/UserConcentratedAllocator.java +++ b/server/src/com/cloud/agent/manager/allocator/impl/UserConcentratedAllocator.java @@ -243,35 +243,36 @@ public class UserConcentratedAllocator extends AdapterBase implements PodAllocat // List vms = _vmInstanceDao.listByLastHostId(hostId); List vms = null; long usedCapacity = 0; - for (VMInstanceVO vm : vms) { - if (skipCalculation(vm)) { - continue; - } - - ServiceOffering so = null; - - if (vm.getType() == VirtualMachine.Type.User) { - UserVmVO userVm = _vmDao.findById(vm.getId()); - if (userVm == null) { + if (vms != null) { + for (VMInstanceVO vm : vms) { + if (skipCalculation(vm)) { continue; } - } - so = _offeringDao.findById(vm.getId(), vm.getServiceOfferingId()); + ServiceOffering so = null; - if (capacityType == Capacity.CAPACITY_TYPE_MEMORY) { - usedCapacity += so.getRamSize() * 1024L * 1024L; - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Counting memory capacity used by vm: " + vm.getId() + ", size: " + so.getRamSize() + "MB, host: " + hostId + ", currently counted: " + - usedCapacity + " Bytes"); + if (vm.getType() == VirtualMachine.Type.User) { + UserVmVO userVm = _vmDao.findById(vm.getId()); + if (userVm == null) { + continue; + } } - } else if (capacityType == Capacity.CAPACITY_TYPE_CPU) { - usedCapacity += so.getCpu() * so.getSpeed(); - if (s_logger.isDebugEnabled()) { - s_logger.debug("Counting cpu capacity used by vm: " + vm.getId() + ", cpu: " + so.getCpu() + ", speed: " + so.getSpeed() + ", currently counted: " + - usedCapacity + " Bytes"); + so = _offeringDao.findById(vm.getId(), vm.getServiceOfferingId()); + if (capacityType == Capacity.CAPACITY_TYPE_MEMORY) { + usedCapacity += so.getRamSize() * 1024L * 1024L; + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Counting memory capacity used by vm: " + vm.getId() + ", size: " + so.getRamSize() + "MB, host: " + hostId + ", currently counted: " + + usedCapacity + " Bytes"); + } + } else if (capacityType == Capacity.CAPACITY_TYPE_CPU) { + usedCapacity += so.getCpu() * so.getSpeed(); + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Counting cpu capacity used by vm: " + vm.getId() + ", cpu: " + so.getCpu() + ", speed: " + so.getSpeed() + ", currently counted: " + + usedCapacity + " Bytes"); + } } } } diff --git a/server/src/com/cloud/alert/AlertManagerImpl.java b/server/src/com/cloud/alert/AlertManagerImpl.java index c742813e17e..2a343d5c4b3 100755 --- a/server/src/com/cloud/alert/AlertManagerImpl.java +++ b/server/src/com/cloud/alert/AlertManagerImpl.java @@ -40,7 +40,12 @@ import javax.mail.URLName; import javax.mail.internet.InternetAddress; import javax.naming.ConfigurationException; -import org.apache.cloudstack.alert.AlertService.AlertType; +import org.apache.log4j.Logger; + +import com.sun.mail.smtp.SMTPMessage; +import com.sun.mail.smtp.SMTPSSLTransport; +import com.sun.mail.smtp.SMTPTransport; + import org.apache.cloudstack.framework.config.ConfigDepot; import org.apache.cloudstack.framework.config.ConfigKey; import org.apache.cloudstack.framework.config.Configurable; @@ -48,7 +53,6 @@ import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.managed.context.ManagedContextTimerTask; import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; -import org.apache.log4j.Logger; import com.cloud.alert.dao.AlertDao; import com.cloud.api.ApiDBUtils; @@ -81,11 +85,7 @@ import com.cloud.storage.StorageManager; import com.cloud.utils.NumbersUtil; import com.cloud.utils.component.ManagerBase; import com.cloud.utils.concurrency.NamedThreadFactory; -import com.cloud.utils.db.DB; import com.cloud.utils.db.SearchCriteria; -import com.sun.mail.smtp.SMTPMessage; -import com.sun.mail.smtp.SMTPSSLTransport; -import com.sun.mail.smtp.SMTPTransport; @Local(value = {AlertManager.class}) public class AlertManagerImpl extends ManagerBase implements AlertManager, Configurable { @@ -94,8 +94,8 @@ public class AlertManagerImpl extends ManagerBase implements AlertManager, Confi private static final long INITIAL_CAPACITY_CHECK_DELAY = 30L * 1000L; // thirty seconds expressed in milliseconds - private static final DecimalFormat _dfPct = new DecimalFormat("###.##"); - private static final DecimalFormat _dfWhole = new DecimalFormat("########"); + private static final DecimalFormat DfPct = new DecimalFormat("###.##"); + private static final DecimalFormat DfWhole = new DecimalFormat("########"); private EmailAlert _emailAlert; @Inject @@ -259,6 +259,7 @@ public class AlertManagerImpl extends ManagerBase implements AlertManager, Confi } } + @Override public void recalculateCapacity() { // FIXME: the right way to do this is to register a listener (see RouterStatsListener, VMSyncListener) // for the vm sync state. The listener model has connects/disconnects to keep things in sync much better @@ -542,7 +543,7 @@ public class AlertManagerImpl extends ManagerBase implements AlertManager, Confi String msgContent = null; String totalStr; String usedStr; - String pctStr = formatPercent(usedCapacity/totalCapacity); + String pctStr = formatPercent(usedCapacity / totalCapacity); AlertType alertType = null; Long podId = pod == null ? null : pod.getId(); Long clusterId = cluster == null ? null : cluster.getId(); @@ -559,8 +560,8 @@ public class AlertManagerImpl extends ManagerBase implements AlertManager, Confi break; case Capacity.CAPACITY_TYPE_CPU: msgSubject = "System Alert: Low Unallocated CPU in cluster " + cluster.getName() + " pod " + pod.getName() + " of availability zone " + dc.getName(); - totalStr = _dfWhole.format(totalCapacity); - usedStr = _dfWhole.format(usedCapacity); + totalStr = DfWhole.format(totalCapacity); + usedStr = DfWhole.format(usedCapacity); msgContent = "Unallocated CPU is low, total: " + totalStr + " Mhz, used: " + usedStr + " Mhz (" + pctStr + "%)"; alertType = AlertManager.AlertType.ALERT_TYPE_CPU; break; @@ -684,7 +685,8 @@ public class AlertManagerImpl extends ManagerBase implements AlertManager, Confi private int _smtpTimeout; private int _smtpConnectionTimeout; - public EmailAlert(String[] recipientList, String smtpHost, int smtpPort, int smtpConnectionTimeout, int smtpTimeout, boolean smtpUseAuth, final String smtpUsername, + public EmailAlert(String[] recipientList, String smtpHost, int smtpPort, int smtpConnectionTimeout, int smtpTimeout, boolean smtpUseAuth, + final String smtpUsername, final String smtpPassword, String emailSender, boolean smtpDebug) { if (recipientList != null) { _recipientList = new InternetAddress[recipientList.length]; @@ -710,7 +712,7 @@ public class AlertManagerImpl extends ManagerBase implements AlertManager, Confi Properties smtpProps = new Properties(); smtpProps.put("mail.smtp.host", smtpHost); smtpProps.put("mail.smtp.port", smtpPort); - smtpProps.put("mail.smtp.auth", ""+smtpUseAuth); + smtpProps.put("mail.smtp.auth", "" + smtpUseAuth); smtpProps.put("mail.smtp.timeout", _smtpTimeout); smtpProps.put("mail.smtp.connectiontimeout", _smtpConnectionTimeout); @@ -720,7 +722,7 @@ public class AlertManagerImpl extends ManagerBase implements AlertManager, Confi smtpProps.put("mail.smtps.host", smtpHost); smtpProps.put("mail.smtps.port", smtpPort); - smtpProps.put("mail.smtps.auth", ""+smtpUseAuth); + smtpProps.put("mail.smtps.auth", "" + smtpUseAuth); smtpProps.put("mail.smtps.timeout", _smtpTimeout); smtpProps.put("mail.smtps.connectiontimeout", _smtpConnectionTimeout); @@ -745,18 +747,19 @@ public class AlertManagerImpl extends ManagerBase implements AlertManager, Confi } // TODO: make sure this handles SSL transport (useAuth is true) and regular - public void sendAlert(AlertType alertType, long dataCenterId, Long podId, Long clusterId, String subject, String content) throws MessagingException, UnsupportedEncodingException { + public void sendAlert(AlertType alertType, long dataCenterId, Long podId, Long clusterId, String subject, String content) throws MessagingException, + UnsupportedEncodingException { s_alertsLogger.warn(" alertType:: " + alertType + " // dataCenterId:: " + dataCenterId + " // podId:: " + podId + " // clusterId:: " + null + " // message:: " + subject); AlertVO alert = null; if ((alertType != AlertManager.AlertType.ALERT_TYPE_HOST) && - (alertType != AlertManager.AlertType.ALERT_TYPE_USERVM) && - (alertType != AlertManager.AlertType.ALERT_TYPE_DOMAIN_ROUTER) && - (alertType != AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY) && - (alertType != AlertManager.AlertType.ALERT_TYPE_SSVM) && - (alertType != AlertManager.AlertType.ALERT_TYPE_STORAGE_MISC) && - (alertType != AlertManager.AlertType.ALERT_TYPE_MANAGMENT_NODE) && - (alertType != AlertManager.AlertType.ALERT_TYPE_RESOURCE_LIMIT_EXCEEDED)) { + (alertType != AlertManager.AlertType.ALERT_TYPE_USERVM) && + (alertType != AlertManager.AlertType.ALERT_TYPE_DOMAIN_ROUTER) && + (alertType != AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY) && + (alertType != AlertManager.AlertType.ALERT_TYPE_SSVM) && + (alertType != AlertManager.AlertType.ALERT_TYPE_STORAGE_MISC) && + (alertType != AlertManager.AlertType.ALERT_TYPE_MANAGMENT_NODE) && + (alertType != AlertManager.AlertType.ALERT_TYPE_RESOURCE_LIMIT_EXCEEDED)) { alert = _alertDao.getLastAlert(alertType.getType(), dataCenterId, podId, clusterId); } @@ -816,7 +819,7 @@ public class AlertManagerImpl extends ManagerBase implements AlertManager, Confi } } }); - } + } public void clearAlert(short alertType, long dataCenterId, Long podId) { if (alertType != -1) { @@ -831,12 +834,12 @@ public class AlertManagerImpl extends ManagerBase implements AlertManager, Confi } private static String formatPercent(double percentage) { - return _dfPct.format(percentage * 100); + return DfPct.format(percentage * 100); } private static String formatBytesToMegabytes(double bytes) { double megaBytes = (bytes / (1024 * 1024)); - return _dfWhole.format(megaBytes); + return DfWhole.format(megaBytes); } @Override @@ -850,7 +853,7 @@ public class AlertManagerImpl extends ManagerBase implements AlertManager, Confi } @Override - @ActionEvent(eventType = EventTypes.ALERT_GENERATE, eventDescription = "generating alert", async=true) + @ActionEvent(eventType = EventTypes.ALERT_GENERATE, eventDescription = "generating alert", async = true) public boolean generateAlert(AlertType alertType, long dataCenterId, Long podId, String msg) { try { sendAlert(alertType, dataCenterId, podId, msg, msg); diff --git a/server/src/com/cloud/alert/ClusterAlertAdapter.java b/server/src/com/cloud/alert/ClusterAlertAdapter.java index 568fc0fb5c6..ccb10746c86 100644 --- a/server/src/com/cloud/alert/ClusterAlertAdapter.java +++ b/server/src/com/cloud/alert/ClusterAlertAdapter.java @@ -92,7 +92,8 @@ public class ClusterAlertAdapter extends AdapterBase implements AlertAdapter { if (s_logger.isDebugEnabled()) { s_logger.debug("Detected management server node " + mshost.getServiceIP() + " is down, send alert"); } - _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_MANAGMENT_NODE, 0, new Long(0), "Management server node " + mshost.getServiceIP() + " is down", ""); + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_MANAGMENT_NODE, 0, new Long(0), "Management server node " + mshost.getServiceIP() + " is down", + ""); } else { if (s_logger.isDebugEnabled()) { s_logger.debug("Detected management server node " + mshost.getServiceIP() + " is down, but alert has already been set"); diff --git a/server/src/com/cloud/alert/ConsoleProxyAlertAdapter.java b/server/src/com/cloud/alert/ConsoleProxyAlertAdapter.java index 86f7fc1e101..df4f5ba953e 100644 --- a/server/src/com/cloud/alert/ConsoleProxyAlertAdapter.java +++ b/server/src/com/cloud/alert/ConsoleProxyAlertAdapter.java @@ -68,9 +68,10 @@ public class ConsoleProxyAlertAdapter extends AdapterBase implements AlertAdapte s_logger.debug("Console proxy is up, zone: " + dc.getName() + ", proxy: " + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + proxy.getPrivateIpAddress()); - _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY, args.getZoneId(), proxy.getPodIdToDeployIn(), "Console proxy up in zone: " + dc.getName() + - ", proxy: " + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + - (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress()), "Console proxy up (zone " + dc.getName() + ")"); + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY, args.getZoneId(), proxy.getPodIdToDeployIn(), + "Console proxy up in zone: " + dc.getName() + + ", proxy: " + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + + (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress()), "Console proxy up (zone " + dc.getName() + ")"); break; case ConsoleProxyAlertEventArgs.PROXY_DOWN: @@ -78,9 +79,10 @@ public class ConsoleProxyAlertAdapter extends AdapterBase implements AlertAdapte s_logger.debug("Console proxy is down, zone: " + dc.getName() + ", proxy: " + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress())); - _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY, args.getZoneId(), proxy.getPodIdToDeployIn(), "Console proxy down in zone: " + dc.getName() + - ", proxy: " + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + - (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress()), "Console proxy down (zone " + dc.getName() + ")"); + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY, args.getZoneId(), proxy.getPodIdToDeployIn(), + "Console proxy down in zone: " + dc.getName() + + ", proxy: " + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + + (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress()), "Console proxy down (zone " + dc.getName() + ")"); break; case ConsoleProxyAlertEventArgs.PROXY_REBOOTED: diff --git a/server/src/com/cloud/alert/SecondaryStorageVmAlertAdapter.java b/server/src/com/cloud/alert/SecondaryStorageVmAlertAdapter.java index 9d4de55f579..b7834bb0341 100644 --- a/server/src/com/cloud/alert/SecondaryStorageVmAlertAdapter.java +++ b/server/src/com/cloud/alert/SecondaryStorageVmAlertAdapter.java @@ -106,9 +106,10 @@ public class SecondaryStorageVmAlertAdapter extends AdapterBase implements Alert s_logger.debug("Secondary Storage Vm creation failure, zone: " + dc.getName() + ", secStorageVm: " + secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() + ", private IP: " + (secStorageVm.getPrivateIpAddress() == null ? "N/A" : secStorageVm.getPrivateIpAddress())); - _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SSVM, args.getZoneId(), secStorageVm.getPodIdToDeployIn(), "Secondary Storage Vm creation failure. zone: " + - dc.getName() + ", secStorageVm: " + secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() + ", private IP: " + - (secStorageVm.getPrivateIpAddress() == null ? "N/A" : secStorageVm.getPrivateIpAddress()) + ", error details: " + args.getMessage(), + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SSVM, args.getZoneId(), secStorageVm.getPodIdToDeployIn(), + "Secondary Storage Vm creation failure. zone: " + + dc.getName() + ", secStorageVm: " + secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() + ", private IP: " + + (secStorageVm.getPrivateIpAddress() == null ? "N/A" : secStorageVm.getPrivateIpAddress()) + ", error details: " + args.getMessage(), "Secondary Storage Vm creation failure (zone " + dc.getName() + ")"); break; @@ -117,9 +118,10 @@ public class SecondaryStorageVmAlertAdapter extends AdapterBase implements Alert s_logger.debug("Secondary Storage Vm startup failure, zone: " + dc.getName() + ", secStorageVm: " + secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() + ", private IP: " + (secStorageVm.getPrivateIpAddress() == null ? "N/A" : secStorageVm.getPrivateIpAddress())); - _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SSVM, args.getZoneId(), secStorageVm.getPodIdToDeployIn(), "Secondary Storage Vm startup failure. zone: " + - dc.getName() + ", secStorageVm: " + secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() + ", private IP: " + - (secStorageVm.getPrivateIpAddress() == null ? "N/A" : secStorageVm.getPrivateIpAddress()) + ", error details: " + args.getMessage(), + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SSVM, args.getZoneId(), secStorageVm.getPodIdToDeployIn(), + "Secondary Storage Vm startup failure. zone: " + + dc.getName() + ", secStorageVm: " + secStorageVm.getHostName() + ", public IP: " + secStorageVm.getPublicIpAddress() + ", private IP: " + + (secStorageVm.getPrivateIpAddress() == null ? "N/A" : secStorageVm.getPrivateIpAddress()) + ", error details: " + args.getMessage(), "Secondary Storage Vm startup failure (zone " + dc.getName() + ")"); break; diff --git a/server/src/com/cloud/api/ApiDBUtils.java b/server/src/com/cloud/api/ApiDBUtils.java index 097c2aec660..a23244b86f0 100755 --- a/server/src/com/cloud/api/ApiDBUtils.java +++ b/server/src/com/cloud/api/ApiDBUtils.java @@ -59,7 +59,6 @@ import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.framework.jobs.AsyncJob; import org.apache.cloudstack.framework.jobs.AsyncJobManager; import org.apache.cloudstack.framework.jobs.dao.AsyncJobDao; -import org.apache.cloudstack.lb.dao.ApplicationLoadBalancerRuleDao; import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; @@ -124,7 +123,6 @@ import com.cloud.dc.VlanVO; import com.cloud.dc.dao.AccountVlanMapDao; import com.cloud.dc.dao.ClusterDao; import com.cloud.dc.dao.DataCenterDao; -import com.cloud.dc.dao.DataCenterDetailsDao; import com.cloud.dc.dao.HostPodDao; import com.cloud.dc.dao.VlanDao; import com.cloud.domain.DomainVO; @@ -225,7 +223,6 @@ import com.cloud.server.StatsCollector; import com.cloud.server.TaggedResourceService; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; -import com.cloud.service.dao.ServiceOfferingDetailsDao; import com.cloud.storage.DiskOfferingVO; import com.cloud.storage.GuestOS; import com.cloud.storage.GuestOSCategoryVO; @@ -293,116 +290,116 @@ import com.cloud.vm.snapshot.VMSnapshot; import com.cloud.vm.snapshot.dao.VMSnapshotDao; public class ApiDBUtils { - private static ManagementServer _ms; - static AsyncJobManager _asyncMgr; - static SecurityGroupManager _securityGroupMgr; - static StorageManager _storageMgr; - static VolumeOrchestrationService _volumeMgr; - static UserVmManager _userVmMgr; - static NetworkModel _networkModel; - static NetworkOrchestrationService _networkMgr; - static TemplateManager _templateMgr; - static ConfigurationManager _configMgr; + private static ManagementServer s_ms; + static AsyncJobManager s_asyncMgr; + static SecurityGroupManager s_securityGroupMgr; + static StorageManager s_storageMgr; + static VolumeOrchestrationService s_volumeMgr; + static UserVmManager s_userVmMgr; + static NetworkModel s_networkModel; + static NetworkOrchestrationService s_networkMgr; + static TemplateManager s_templateMgr; + static ConfigurationManager s_configMgr; - static StatsCollector _statsCollector; + static StatsCollector s_statsCollector; - static AccountDao _accountDao; - static AccountVlanMapDao _accountVlanMapDao; - static ClusterDao _clusterDao; - static CapacityDao _capacityDao; - static DiskOfferingDao _diskOfferingDao; - static DiskOfferingJoinDao _diskOfferingJoinDao; - static DataCenterJoinDao _dcJoinDao; - static DomainDao _domainDao; - static DomainRouterDao _domainRouterDao; - static DomainRouterJoinDao _domainRouterJoinDao; - static GuestOSDao _guestOSDao; - static GuestOSCategoryDao _guestOSCategoryDao; - static HostDao _hostDao; - static AccountGuestVlanMapDao _accountGuestVlanMapDao; - static IPAddressDao _ipAddressDao; - static LoadBalancerDao _loadBalancerDao; - static SecurityGroupDao _securityGroupDao; - static SecurityGroupJoinDao _securityGroupJoinDao; - static ServiceOfferingJoinDao _serviceOfferingJoinDao; - static NetworkRuleConfigDao _networkRuleConfigDao; - static HostPodDao _podDao; - static ServiceOfferingDao _serviceOfferingDao; - static SnapshotDao _snapshotDao; - static PrimaryDataStoreDao _storagePoolDao; - static VMTemplateDao _templateDao; - static VMTemplateDetailsDao _templateDetailsDao; - static UploadDao _uploadDao; - static UserDao _userDao; - static UserStatisticsDao _userStatsDao; - static UserVmDao _userVmDao; - static UserVmJoinDao _userVmJoinDao; - static VlanDao _vlanDao; - static VolumeDao _volumeDao; - static Site2SiteVpnGatewayDao _site2SiteVpnGatewayDao; - static Site2SiteCustomerGatewayDao _site2SiteCustomerGatewayDao; - static DataCenterDao _zoneDao; - static NetworkOfferingDao _networkOfferingDao; - static NetworkDao _networkDao; - static PhysicalNetworkDao _physicalNetworkDao; - static ConfigurationService _configSvc; - static ConfigurationDao _configDao; - static ConsoleProxyDao _consoleProxyDao; - static FirewallRulesCidrsDao _firewallCidrsDao; - static VMInstanceDao _vmDao; - static ResourceLimitService _resourceLimitMgr; - static ProjectService _projectMgr; - static ResourceManager _resourceMgr; - static AccountDetailsDao _accountDetailsDao; - static NetworkDomainDao _networkDomainDao; - static HighAvailabilityManager _haMgr; - static VpcManager _vpcMgr; - static TaggedResourceService _taggedResourceService; - static UserVmDetailsDao _userVmDetailsDao; - static SSHKeyPairDao _sshKeyPairDao; + static AccountDao s_accountDao; + static AccountVlanMapDao s_accountVlanMapDao; + static ClusterDao s_clusterDao; + static CapacityDao s_capacityDao; + static DiskOfferingDao s_diskOfferingDao; + static DiskOfferingJoinDao s_diskOfferingJoinDao; + static DataCenterJoinDao s_dcJoinDao; + static DomainDao s_domainDao; + static DomainRouterDao s_domainRouterDao; + static DomainRouterJoinDao s_domainRouterJoinDao; + static GuestOSDao s_guestOSDao; + static GuestOSCategoryDao s_guestOSCategoryDao; + static HostDao s_hostDao; + static AccountGuestVlanMapDao s_accountGuestVlanMapDao; + static IPAddressDao s_ipAddressDao; + static LoadBalancerDao s_loadBalancerDao; + static SecurityGroupDao s_securityGroupDao; + static SecurityGroupJoinDao s_securityGroupJoinDao; + static ServiceOfferingJoinDao s_serviceOfferingJoinDao; + static NetworkRuleConfigDao s_networkRuleConfigDao; + static HostPodDao s_podDao; + static ServiceOfferingDao s_serviceOfferingDao; + static SnapshotDao s_snapshotDao; + static PrimaryDataStoreDao s_storagePoolDao; + static VMTemplateDao s_templateDao; + static VMTemplateDetailsDao s_templateDetailsDao; + static UploadDao s_uploadDao; + static UserDao s_userDao; + static UserStatisticsDao s_userStatsDao; + static UserVmDao s_userVmDao; + static UserVmJoinDao s_userVmJoinDao; + static VlanDao s_vlanDao; + static VolumeDao s_volumeDao; + static Site2SiteVpnGatewayDao s_site2SiteVpnGatewayDao; + static Site2SiteCustomerGatewayDao s_site2SiteCustomerGatewayDao; + static DataCenterDao s_zoneDao; + static NetworkOfferingDao s_networkOfferingDao; + static NetworkDao s_networkDao; + static PhysicalNetworkDao s_physicalNetworkDao; + static ConfigurationService s_configSvc; + static ConfigurationDao s_configDao; + static ConsoleProxyDao s_consoleProxyDao; + static FirewallRulesCidrsDao s_firewallCidrsDao; + static VMInstanceDao s_vmDao; + static ResourceLimitService s_resourceLimitMgr; + static ProjectService s_projectMgr; + static ResourceManager s_resourceMgr; + static AccountDetailsDao s_accountDetailsDao; + static NetworkDomainDao s_networkDomainDao; + static HighAvailabilityManager s_haMgr; + static VpcManager s_vpcMgr; + static TaggedResourceService s_taggedResourceService; + static UserVmDetailsDao s_userVmDetailsDao; + static SSHKeyPairDao s_sshKeyPairDao; - static ConditionDao _asConditionDao; - static AutoScalePolicyConditionMapDao _asPolicyConditionMapDao; - static AutoScaleVmGroupPolicyMapDao _asVmGroupPolicyMapDao; - static AutoScalePolicyDao _asPolicyDao; - static AutoScaleVmProfileDao _asVmProfileDao; - static AutoScaleVmGroupDao _asVmGroupDao; - static CounterDao _counterDao; - static ResourceTagJoinDao _tagJoinDao; - static EventJoinDao _eventJoinDao; - static InstanceGroupJoinDao _vmGroupJoinDao; - static UserAccountJoinDao _userAccountJoinDao; - static ProjectJoinDao _projectJoinDao; - static ProjectAccountJoinDao _projectAccountJoinDao; - static ProjectInvitationJoinDao _projectInvitationJoinDao; - static HostJoinDao _hostJoinDao; - static VolumeJoinDao _volJoinDao; - static StoragePoolJoinDao _poolJoinDao; - static ImageStoreJoinDao _imageStoreJoinDao; - static AccountJoinDao _accountJoinDao; - static AsyncJobJoinDao _jobJoinDao; - static TemplateJoinDao _templateJoinDao; + static ConditionDao s_asConditionDao; + static AutoScalePolicyConditionMapDao s_asPolicyConditionMapDao; + static AutoScaleVmGroupPolicyMapDao s_asVmGroupPolicyMapDao; + static AutoScalePolicyDao s_asPolicyDao; + static AutoScaleVmProfileDao s_asVmProfileDao; + static AutoScaleVmGroupDao s_asVmGroupDao; + static CounterDao s_counterDao; + static ResourceTagJoinDao s_tagJoinDao; + static EventJoinDao s_eventJoinDao; + static InstanceGroupJoinDao s_vmGroupJoinDao; + static UserAccountJoinDao s_userAccountJoinDao; + static ProjectJoinDao s_projectJoinDao; + static ProjectAccountJoinDao s_projectAccountJoinDao; + static ProjectInvitationJoinDao s_projectInvitationJoinDao; + static HostJoinDao s_hostJoinDao; + static VolumeJoinDao s_volJoinDao; + static StoragePoolJoinDao s_poolJoinDao; + static ImageStoreJoinDao s_imageStoreJoinDao; + static AccountJoinDao s_accountJoinDao; + static AsyncJobJoinDao s_jobJoinDao; + static TemplateJoinDao s_templateJoinDao; - static PhysicalNetworkTrafficTypeDao _physicalNetworkTrafficTypeDao; - static PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; - static FirewallRulesDao _firewallRuleDao; - static StaticRouteDao _staticRouteDao; - static VpcGatewayDao _vpcGatewayDao; - static VpcDao _vpcDao; - static VpcOfferingDao _vpcOfferingDao; - static SnapshotPolicyDao _snapshotPolicyDao; - static AsyncJobDao _asyncJobDao; - static HostDetailsDao _hostDetailsDao; - static VMSnapshotDao _vmSnapshotDao; - static ClusterDetailsDao _clusterDetailsDao; - static NicSecondaryIpDao _nicSecondaryIpDao; - static VpcProvisioningService _vpcProvSvc; - static AffinityGroupDao _affinityGroupDao; - static AffinityGroupJoinDao _affinityGroupJoinDao; - static GlobalLoadBalancingRulesService _gslbService; - static NetworkACLDao _networkACLDao; - static AccountService _accountService; - static ResourceMetaDataService _resourceDetailsService; + static PhysicalNetworkTrafficTypeDao s_physicalNetworkTrafficTypeDao; + static PhysicalNetworkServiceProviderDao s_physicalNetworkServiceProviderDao; + static FirewallRulesDao s_firewallRuleDao; + static StaticRouteDao s_staticRouteDao; + static VpcGatewayDao s_vpcGatewayDao; + static VpcDao s_vpcDao; + static VpcOfferingDao s_vpcOfferingDao; + static SnapshotPolicyDao s_snapshotPolicyDao; + static AsyncJobDao s_asyncJobDao; + static HostDetailsDao s_hostDetailsDao; + static VMSnapshotDao s_vmSnapshotDao; + static ClusterDetailsDao s_clusterDetailsDao; + static NicSecondaryIpDao s_nicSecondaryIpDao; + static VpcProvisioningService s_vpcProvSvc; + static AffinityGroupDao s_affinityGroupDao; + static AffinityGroupJoinDao s_affinityGroupJoinDao; + static GlobalLoadBalancingRulesService s_gslbService; + static NetworkACLDao s_networkACLDao; + static AccountService s_accountService; + static ResourceMetaDataService s_resourceDetailsService; @Inject private ManagementServer ms; @@ -606,8 +603,6 @@ public class ApiDBUtils { @Inject private VpcProvisioningService vpcProvSvc; @Inject - private ApplicationLoadBalancerRuleDao _appLbDao; - @Inject private AffinityGroupDao affinityGroupDao; @Inject private AffinityGroupJoinDao affinityGroupJoinDao; @@ -616,126 +611,122 @@ public class ApiDBUtils { @Inject private NetworkACLDao networkACLDao; @Inject - private ServiceOfferingDetailsDao serviceOfferingDetailsDao; - @Inject private AccountService accountService; @Inject private ConfigurationManager configMgr; @Inject - private DataCenterDetailsDao zoneDetailsDao; - @Inject private ResourceMetaDataService resourceDetailsService; @PostConstruct void init() { - _ms = ms; - _configMgr = configMgr; - _asyncMgr = asyncMgr; - _securityGroupMgr = securityGroupMgr; - _storageMgr = storageMgr; - _userVmMgr = userVmMgr; - _networkModel = networkModel; - _networkMgr = networkMgr; - _configSvc = configSvc; - _templateMgr = templateMgr; + s_ms = ms; + s_configMgr = configMgr; + s_asyncMgr = asyncMgr; + s_securityGroupMgr = securityGroupMgr; + s_storageMgr = storageMgr; + s_userVmMgr = userVmMgr; + s_networkModel = networkModel; + s_networkMgr = networkMgr; + s_configSvc = configSvc; + s_templateMgr = templateMgr; - _accountDao = accountDao; - _accountGuestVlanMapDao = accountGuestVlanMapDao; - _accountVlanMapDao = accountVlanMapDao; - _clusterDao = clusterDao; - _capacityDao = capacityDao; - _dcJoinDao = dcJoinDao; - _diskOfferingDao = diskOfferingDao; - _diskOfferingJoinDao = diskOfferingJoinDao; - _domainDao = domainDao; - _domainRouterDao = domainRouterDao; - _domainRouterJoinDao = domainRouterJoinDao; - _guestOSDao = guestOSDao; - _guestOSCategoryDao = guestOSCategoryDao; - _hostDao = hostDao; - _ipAddressDao = ipAddressDao; - _loadBalancerDao = loadBalancerDao; - _networkRuleConfigDao = networkRuleConfigDao; - _podDao = podDao; - _serviceOfferingDao = serviceOfferingDao; - _serviceOfferingJoinDao = serviceOfferingJoinDao; - _snapshotDao = snapshotDao; - _storagePoolDao = storagePoolDao; - _templateDao = templateDao; - _templateDetailsDao = templateDetailsDao; - _uploadDao = uploadDao; - _userDao = userDao; - _userStatsDao = userStatsDao; - _userVmDao = userVmDao; - _userVmJoinDao = userVmJoinDao; - _vlanDao = vlanDao; - _volumeDao = volumeDao; - _site2SiteVpnGatewayDao = site2SiteVpnGatewayDao; - _site2SiteCustomerGatewayDao = site2SiteCustomerGatewayDao; - _zoneDao = zoneDao; - _securityGroupDao = securityGroupDao; - _securityGroupJoinDao = securityGroupJoinDao; - _networkOfferingDao = networkOfferingDao; - _networkDao = networkDao; - _physicalNetworkDao = physicalNetworkDao; - _configDao = configDao; - _consoleProxyDao = consoleProxyDao; - _firewallCidrsDao = firewallCidrsDao; - _vmDao = vmDao; - _resourceLimitMgr = resourceLimitMgr; - _projectMgr = projectMgr; - _resourceMgr = resourceMgr; - _accountDetailsDao = accountDetailsDao; - _networkDomainDao = networkDomainDao; - _haMgr = haMgr; - _vpcMgr = vpcMgr; - _taggedResourceService = taggedResourceService; - _sshKeyPairDao = sshKeyPairDao; - _userVmDetailsDao = userVmDetailsDao; - _asConditionDao = asConditionDao; - _asPolicyDao = asPolicyDao; - _asPolicyConditionMapDao = asPolicyConditionMapDao; - _counterDao = counterDao; - _asVmGroupPolicyMapDao = asVmGroupPolicyMapDao; - _tagJoinDao = tagJoinDao; - _vmGroupJoinDao = vmGroupJoinDao; - _eventJoinDao = eventJoinDao; - _userAccountJoinDao = userAccountJoinDao; - _projectJoinDao = projectJoinDao; - _projectAccountJoinDao = projectAccountJoinDao; - _projectInvitationJoinDao = projectInvitationJoinDao; - _hostJoinDao = hostJoinDao; - _volJoinDao = volJoinDao; - _poolJoinDao = poolJoinDao; - _imageStoreJoinDao = imageStoreJoinDao; - _accountJoinDao = accountJoinDao; - _jobJoinDao = jobJoinDao; - _templateJoinDao = templateJoinDao; + s_accountDao = accountDao; + s_accountGuestVlanMapDao = accountGuestVlanMapDao; + s_accountVlanMapDao = accountVlanMapDao; + s_clusterDao = clusterDao; + s_capacityDao = capacityDao; + s_dcJoinDao = dcJoinDao; + s_diskOfferingDao = diskOfferingDao; + s_diskOfferingJoinDao = diskOfferingJoinDao; + s_domainDao = domainDao; + s_domainRouterDao = domainRouterDao; + s_domainRouterJoinDao = domainRouterJoinDao; + s_guestOSDao = guestOSDao; + s_guestOSCategoryDao = guestOSCategoryDao; + s_hostDao = hostDao; + s_ipAddressDao = ipAddressDao; + s_loadBalancerDao = loadBalancerDao; + s_networkRuleConfigDao = networkRuleConfigDao; + s_podDao = podDao; + s_serviceOfferingDao = serviceOfferingDao; + s_serviceOfferingJoinDao = serviceOfferingJoinDao; + s_snapshotDao = snapshotDao; + s_storagePoolDao = storagePoolDao; + s_templateDao = templateDao; + s_templateDetailsDao = templateDetailsDao; + s_uploadDao = uploadDao; + s_userDao = userDao; + s_userStatsDao = userStatsDao; + s_userVmDao = userVmDao; + s_userVmJoinDao = userVmJoinDao; + s_vlanDao = vlanDao; + s_volumeDao = volumeDao; + s_site2SiteVpnGatewayDao = site2SiteVpnGatewayDao; + s_site2SiteCustomerGatewayDao = site2SiteCustomerGatewayDao; + s_zoneDao = zoneDao; + s_securityGroupDao = securityGroupDao; + s_securityGroupJoinDao = securityGroupJoinDao; + s_networkOfferingDao = networkOfferingDao; + s_networkDao = networkDao; + s_physicalNetworkDao = physicalNetworkDao; + s_configDao = configDao; + s_consoleProxyDao = consoleProxyDao; + s_firewallCidrsDao = firewallCidrsDao; + s_vmDao = vmDao; + s_resourceLimitMgr = resourceLimitMgr; + s_projectMgr = projectMgr; + s_resourceMgr = resourceMgr; + s_accountDetailsDao = accountDetailsDao; + s_networkDomainDao = networkDomainDao; + s_haMgr = haMgr; + s_vpcMgr = vpcMgr; + s_taggedResourceService = taggedResourceService; + s_sshKeyPairDao = sshKeyPairDao; + s_userVmDetailsDao = userVmDetailsDao; + s_asConditionDao = asConditionDao; + s_asPolicyDao = asPolicyDao; + s_asPolicyConditionMapDao = asPolicyConditionMapDao; + s_counterDao = counterDao; + s_asVmGroupPolicyMapDao = asVmGroupPolicyMapDao; + s_tagJoinDao = tagJoinDao; + s_vmGroupJoinDao = vmGroupJoinDao; + s_eventJoinDao = eventJoinDao; + s_userAccountJoinDao = userAccountJoinDao; + s_projectJoinDao = projectJoinDao; + s_projectAccountJoinDao = projectAccountJoinDao; + s_projectInvitationJoinDao = projectInvitationJoinDao; + s_hostJoinDao = hostJoinDao; + s_volJoinDao = volJoinDao; + s_poolJoinDao = poolJoinDao; + s_imageStoreJoinDao = imageStoreJoinDao; + s_accountJoinDao = accountJoinDao; + s_jobJoinDao = jobJoinDao; + s_templateJoinDao = templateJoinDao; - _physicalNetworkTrafficTypeDao = physicalNetworkTrafficTypeDao; - _physicalNetworkServiceProviderDao = physicalNetworkServiceProviderDao; - _firewallRuleDao = firewallRuleDao; - _staticRouteDao = staticRouteDao; - _vpcGatewayDao = vpcGatewayDao; - _asVmProfileDao = asVmProfileDao; - _asVmGroupDao = asVmGroupDao; - _vpcDao = vpcDao; - _vpcOfferingDao = vpcOfferingDao; - _snapshotPolicyDao = snapshotPolicyDao; - _asyncJobDao = asyncJobDao; - _hostDetailsDao = hostDetailsDao; - _clusterDetailsDao = clusterDetailsDao; - _vmSnapshotDao = vmSnapshotDao; - _nicSecondaryIpDao = nicSecondaryIpDao; - _vpcProvSvc = vpcProvSvc; - _affinityGroupDao = affinityGroupDao; - _affinityGroupJoinDao = affinityGroupJoinDao; - _gslbService = gslbService; + s_physicalNetworkTrafficTypeDao = physicalNetworkTrafficTypeDao; + s_physicalNetworkServiceProviderDao = physicalNetworkServiceProviderDao; + s_firewallRuleDao = firewallRuleDao; + s_staticRouteDao = staticRouteDao; + s_vpcGatewayDao = vpcGatewayDao; + s_asVmProfileDao = asVmProfileDao; + s_asVmGroupDao = asVmGroupDao; + s_vpcDao = vpcDao; + s_vpcOfferingDao = vpcOfferingDao; + s_snapshotPolicyDao = snapshotPolicyDao; + s_asyncJobDao = asyncJobDao; + s_hostDetailsDao = hostDetailsDao; + s_clusterDetailsDao = clusterDetailsDao; + s_vmSnapshotDao = vmSnapshotDao; + s_nicSecondaryIpDao = nicSecondaryIpDao; + s_vpcProvSvc = vpcProvSvc; + s_affinityGroupDao = affinityGroupDao; + s_affinityGroupJoinDao = affinityGroupJoinDao; + s_gslbService = gslbService; // Note: stats collector should already have been initialized by this time, otherwise a null instance is returned - _statsCollector = StatsCollector.getInstance(); - _networkACLDao = networkACLDao; - _accountService = accountService; - _resourceDetailsService = resourceDetailsService; + s_statsCollector = StatsCollector.getInstance(); + s_networkACLDao = networkACLDao; + s_accountService = accountService; + s_resourceDetailsService = resourceDetailsService; } @@ -744,15 +735,7 @@ public class ApiDBUtils { // /////////////////////////////////////////////////////////// public static VMInstanceVO findVMInstanceById(long vmId) { - return _vmDao.findById(vmId); - } - - public static long getMemoryOrCpuCapacitybyHost(Long hostId, short capacityType) { - // TODO: This method is for the API only, but it has configuration values (ramSize for system vms) - // so if this Utils class can have some kind of config rather than a static initializer (maybe from - // management server instantiation?) then maybe the management server method can be moved entirely - // into this utils class. - return _ms.getMemoryOrCpuCapacityByHost(hostId, capacityType); + return s_vmDao.findById(vmId); } public static long getStorageCapacitybyPool(Long poolId, short capacityType) { @@ -760,15 +743,15 @@ public class ApiDBUtils { // so if this Utils class can have some kind of config rather than a static initializer (maybe from // management server instantiation?) then maybe the management server method can be moved entirely // into this utils class. - return _ms.getMemoryOrCpuCapacityByHost(poolId, capacityType); + return s_ms.getMemoryOrCpuCapacityByHost(poolId, capacityType); } public static List getCapacityByClusterPodZone(Long zoneId, Long podId, Long clusterId) { - return _capacityDao.findByClusterPodZone(zoneId, podId, clusterId); + return s_capacityDao.findByClusterPodZone(zoneId, podId, clusterId); } public static List findNonSharedStorageForClusterPodZone(Long zoneId, Long podId, Long clusterId) { - return _capacityDao.findNonSharedStorageForClusterPodZone(zoneId, podId, clusterId); + return s_capacityDao.findNonSharedStorageForClusterPodZone(zoneId, podId, clusterId); } public static List getCapacityByPod() { @@ -777,19 +760,15 @@ public class ApiDBUtils { } public static Long getPodIdForVlan(long vlanDbId) { - return _networkModel.getPodIdForVlan(vlanDbId); + return s_networkModel.getPodIdForVlan(vlanDbId); } public static String getVersion() { - return _ms.getVersion(); + return s_ms.getVersion(); } public static List searchForUserVMs(Criteria c, List permittedAccounts) { - return _userVmMgr.searchForUserVMs(c, _accountDao.findById(Account.ACCOUNT_ID_SYSTEM), null, false, permittedAccounts, false, null, null).first(); - } - - public static List searchForStoragePools(Criteria c) { - return _ms.searchForStoragePools(c).first(); + return s_userVmMgr.searchForUserVMs(c, s_accountDao.findById(Account.ACCOUNT_ID_SYSTEM), null, false, permittedAccounts, false, null, null).first(); } // /////////////////////////////////////////////////////////// @@ -797,52 +776,52 @@ public class ApiDBUtils { // /////////////////////////////////////////////////////////// public static long findCorrectResourceLimit(ResourceType type, long accountId) { - AccountVO account = _accountDao.findById(accountId); + AccountVO account = s_accountDao.findById(accountId); if (account == null) { return -1; } - return _resourceLimitMgr.findCorrectResourceLimitForAccount(account, type); + return s_resourceLimitMgr.findCorrectResourceLimitForAccount(account, type); } public static long findCorrectResourceLimit(Long limit, short accountType, ResourceType type) { - return _resourceLimitMgr.findCorrectResourceLimitForAccount(accountType, limit, type); + return s_resourceLimitMgr.findCorrectResourceLimitForAccount(accountType, limit, type); } public static long getResourceCount(ResourceType type, long accountId) { - AccountVO account = _accountDao.findById(accountId); + AccountVO account = s_accountDao.findById(accountId); if (account == null) { return -1; } - return _resourceLimitMgr.getResourceCount(account, type); + return s_resourceLimitMgr.getResourceCount(account, type); } public static String getSecurityGroupsNamesForVm(long vmId) { - return _securityGroupMgr.getSecurityGroupsNamesForVm(vmId); + return s_securityGroupMgr.getSecurityGroupsNamesForVm(vmId); } public static List getSecurityGroupsForVm(long vmId) { - return _securityGroupMgr.getSecurityGroupsForVm(vmId); + return s_securityGroupMgr.getSecurityGroupsForVm(vmId); } public static String getSnapshotIntervalTypes(long snapshotId) { - SnapshotVO snapshot = _snapshotDao.findById(snapshotId); + SnapshotVO snapshot = s_snapshotDao.findById(snapshotId); return snapshot.getRecurringType().name(); } public static String getStoragePoolTags(long poolId) { - return _storageMgr.getStoragePoolTags(poolId); + return s_storageMgr.getStoragePoolTags(poolId); } public static boolean isLocalStorageActiveOnHost(Long hostId) { - return _storageMgr.isLocalStorageActiveOnHost(hostId); + return s_storageMgr.isLocalStorageActiveOnHost(hostId); } public static InstanceGroupVO findInstanceGroupForVM(long vmId) { - return _userVmMgr.getGroupForVm(vmId); + return s_userVmMgr.getGroupForVm(vmId); } // /////////////////////////////////////////////////////////// @@ -850,27 +829,27 @@ public class ApiDBUtils { // /////////////////////////////////////////////////////////// public static HostStats getHostStatistics(long hostId) { - return _statsCollector.getHostStats(hostId); + return s_statsCollector.getHostStats(hostId); } public static StorageStats getStoragePoolStatistics(long id) { - return _statsCollector.getStoragePoolStats(id); + return s_statsCollector.getStoragePoolStats(id); } public static VmStats getVmStatistics(long hostId) { - return _statsCollector.getVmStats(hostId); + return s_statsCollector.getVmStats(hostId); } public static StorageStats getSecondaryStorageStatistics(long id) { - return _statsCollector.getStorageStats(id); + return s_statsCollector.getStorageStats(id); } public static CapacityVO getStoragePoolUsedStats(Long poolId, Long clusterId, Long podId, Long zoneId) { - return _storageMgr.getStoragePoolUsedStats(poolId, clusterId, podId, zoneId); + return s_storageMgr.getStoragePoolUsedStats(poolId, clusterId, podId, zoneId); } public static CapacityVO getSecondaryStorageUsedStats(Long hostId, Long zoneId) { - return _storageMgr.getSecondaryStorageUsedStats(hostId, zoneId); + return s_storageMgr.getSecondaryStorageUsedStats(hostId, zoneId); } // /////////////////////////////////////////////////////////// @@ -878,23 +857,23 @@ public class ApiDBUtils { // /////////////////////////////////////////////////////////// public static Account findAccountById(Long accountId) { - return _accountDao.findByIdIncludingRemoved(accountId); + return s_accountDao.findByIdIncludingRemoved(accountId); } public static Account findAccountByIdIncludingRemoved(Long accountId) { - return _accountDao.findByIdIncludingRemoved(accountId); + return s_accountDao.findByIdIncludingRemoved(accountId); } public static Account findAccountByNameDomain(String accountName, Long domainId) { - return _accountDao.findActiveAccount(accountName, domainId); + return s_accountDao.findActiveAccount(accountName, domainId); } public static ClusterVO findClusterById(long clusterId) { - return _clusterDao.findById(clusterId); + return s_clusterDao.findById(clusterId); } public static String findClusterDetails(long clusterId, String name) { - ClusterDetailsVO detailsVO = _clusterDetailsDao.findDetail(clusterId, name); + ClusterDetailsVO detailsVO = s_clusterDetailsDao.findDetail(clusterId, name); if (detailsVO != null) { return detailsVO.getValue(); } @@ -903,73 +882,73 @@ public class ApiDBUtils { } public static DiskOfferingVO findDiskOfferingById(Long diskOfferingId) { - return _diskOfferingDao.findByIdIncludingRemoved(diskOfferingId); + return s_diskOfferingDao.findByIdIncludingRemoved(diskOfferingId); } public static DomainVO findDomainById(Long domainId) { - return _domainDao.findByIdIncludingRemoved(domainId); + return s_domainDao.findByIdIncludingRemoved(domainId); } public static DomainVO findDomainByIdIncludingRemoved(Long domainId) { - return _domainDao.findByIdIncludingRemoved(domainId); + return s_domainDao.findByIdIncludingRemoved(domainId); } public static boolean isChildDomain(long parentId, long childId) { - return _domainDao.isChildDomain(parentId, childId); + return s_domainDao.isChildDomain(parentId, childId); } public static DomainRouterVO findDomainRouterById(Long routerId) { - return _domainRouterDao.findByIdIncludingRemoved(routerId); + return s_domainRouterDao.findByIdIncludingRemoved(routerId); } public static GuestOS findGuestOSById(Long id) { - return _guestOSDao.findByIdIncludingRemoved(id); + return s_guestOSDao.findByIdIncludingRemoved(id); } public static GuestOS findGuestOSByDisplayName(String displayName) { - return _guestOSDao.listByDisplayName(displayName); + return s_guestOSDao.listByDisplayName(displayName); } public static HostVO findHostById(Long hostId) { - return _hostDao.findByIdIncludingRemoved(hostId); + return s_hostDao.findByIdIncludingRemoved(hostId); } public static IPAddressVO findIpAddressById(long addressId) { - return _ipAddressDao.findById(addressId); + return s_ipAddressDao.findById(addressId); } public static GuestOSCategoryVO getHostGuestOSCategory(long hostId) { - Long guestOSCategoryID = _resourceMgr.getGuestOSCategoryId(hostId); + Long guestOSCategoryID = s_resourceMgr.getGuestOSCategoryId(hostId); if (guestOSCategoryID != null) { - return _guestOSCategoryDao.findById(guestOSCategoryID); + return s_guestOSCategoryDao.findById(guestOSCategoryID); } else { return null; } } public static String getHostTags(long hostId) { - return _resourceMgr.getHostTags(hostId); + return s_resourceMgr.getHostTags(hostId); } public static LoadBalancerVO findLoadBalancerById(Long loadBalancerId) { - return _loadBalancerDao.findById(loadBalancerId); + return s_loadBalancerDao.findById(loadBalancerId); } public static NetworkRuleConfigVO findNetworkRuleById(Long ruleId) { - return _networkRuleConfigDao.findById(ruleId); + return s_networkRuleConfigDao.findById(ruleId); } public static SecurityGroup findSecurityGroupById(Long groupId) { - return _securityGroupDao.findById(groupId); + return s_securityGroupDao.findById(groupId); } public static HostPodVO findPodById(Long podId) { - return _podDao.findById(podId); + return s_podDao.findById(podId); } public static VolumeVO findRootVolume(long vmId) { - List volumes = _volumeDao.findByInstanceAndType(vmId, Type.ROOT); + List volumes = s_volumeDao.findByInstanceAndType(vmId, Type.ROOT); if (volumes != null && volumes.size() == 1) { return volumes.get(0); } else { @@ -978,11 +957,11 @@ public class ApiDBUtils { } public static ServiceOffering findServiceOfferingById(Long serviceOfferingId) { - return _serviceOfferingDao.findByIdIncludingRemoved(serviceOfferingId); + return s_serviceOfferingDao.findByIdIncludingRemoved(serviceOfferingId); } public static Snapshot findSnapshotById(long snapshotId) { - SnapshotVO snapshot = _snapshotDao.findById(snapshotId); + SnapshotVO snapshot = s_snapshotDao.findById(snapshotId); if (snapshot != null && snapshot.getRemoved() == null && snapshot.getState() == Snapshot.State.BackedUp) { return snapshot; } else { @@ -991,13 +970,13 @@ public class ApiDBUtils { } public static StoragePoolVO findStoragePoolById(Long storagePoolId) { - return _storagePoolDao.findByIdIncludingRemoved(storagePoolId); + return s_storagePoolDao.findByIdIncludingRemoved(storagePoolId); } public static VMTemplateVO findTemplateById(Long templateId) { - VMTemplateVO template = _templateDao.findByIdIncludingRemoved(templateId); + VMTemplateVO template = s_templateDao.findByIdIncludingRemoved(templateId); if (template != null) { - Map details = _templateDetailsDao.listDetailsKeyPairs(templateId); + Map details = s_templateDetailsDao.listDetailsKeyPairs(templateId); if (details != null && !details.isEmpty()) { template.setDetails(details); } @@ -1006,43 +985,43 @@ public class ApiDBUtils { } public static UploadVO findUploadById(Long id) { - return _uploadDao.findById(id); + return s_uploadDao.findById(id); } public static User findUserById(Long userId) { - return _userDao.findById(userId); + return s_userDao.findById(userId); } public static UserVm findUserVmById(Long vmId) { - return _userVmDao.findById(vmId); + return s_userVmDao.findById(vmId); } public static VlanVO findVlanById(long vlanDbId) { - return _vlanDao.findById(vlanDbId); + return s_vlanDao.findById(vlanDbId); } public static VolumeVO findVolumeById(Long volumeId) { - return _volumeDao.findByIdIncludingRemoved(volumeId); + return s_volumeDao.findByIdIncludingRemoved(volumeId); } public static Site2SiteVpnGatewayVO findVpnGatewayById(Long vpnGatewayId) { - return _site2SiteVpnGatewayDao.findById(vpnGatewayId); + return s_site2SiteVpnGatewayDao.findById(vpnGatewayId); } public static Site2SiteCustomerGatewayVO findCustomerGatewayById(Long customerGatewayId) { - return _site2SiteCustomerGatewayDao.findById(customerGatewayId); + return s_site2SiteCustomerGatewayDao.findById(customerGatewayId); } public static List listUsersByAccount(long accountId) { - return _userDao.listByAccount(accountId); + return s_userDao.listByAccount(accountId); } public static DataCenterVO findZoneById(Long zoneId) { - return _zoneDao.findById(zoneId); + return s_zoneDao.findById(zoneId); } public static Long getAccountIdForVlan(long vlanDbId) { - List accountVlanMaps = _accountVlanMapDao.listAccountVlanMapsByVlan(vlanDbId); + List accountVlanMaps = s_accountVlanMapDao.listAccountVlanMapsByVlan(vlanDbId); if (accountVlanMaps.isEmpty()) { return null; } else { @@ -1051,7 +1030,7 @@ public class ApiDBUtils { } public static Long getAccountIdForGuestVlan(long vlanDbId) { - List accountGuestVlanMaps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByVlan(vlanDbId); + List accountGuestVlanMaps = s_accountGuestVlanMapDao.listAccountGuestVlanMapsByVlan(vlanDbId); if (accountGuestVlanMaps.isEmpty()) { return null; } else { @@ -1060,73 +1039,84 @@ public class ApiDBUtils { } public static HypervisorType getVolumeHyperType(long volumeId) { - return _volumeDao.getHypervisorType(volumeId); + return s_volumeDao.getHypervisorType(volumeId); } - public static HypervisorType getHypervisorTypeFromFormat(ImageFormat format) { - return _storageMgr.getHypervisorTypeFromFormat(format); + public static HypervisorType getHypervisorTypeFromFormat(long dcId, ImageFormat format){ + HypervisorType type = s_storageMgr.getHypervisorTypeFromFormat(format); + if (format == ImageFormat.VHD) { + // Xenserver and Hyperv both support vhd format. Additionally hyperv is only supported + // in a dc/zone if there aren't any other hypervisor types present in the zone). If the + // format type is VHD check is any xenserver clusters are present. If not, we assume it + // is a hyperv zone and update the type. + List xenClusters = s_clusterDao.listByDcHyType(dcId, HypervisorType.XenServer.toString()); + if (xenClusters.isEmpty()) { + type = HypervisorType.Hyperv; + } + } + return type; } public static List listUserStatsBy(Long accountId) { - return _userStatsDao.listBy(accountId); + return s_userStatsDao.listBy(accountId); } public static List listUserVMsByHostId(long hostId) { - return _userVmDao.listByHostId(hostId); + return s_userVmDao.listByHostId(hostId); } public static List listZones() { - return _zoneDao.listAll(); + return s_zoneDao.listAll(); } public static boolean volumeIsOnSharedStorage(long volumeId) { // Check that the volume is valid - VolumeVO volume = _volumeDao.findById(volumeId); + VolumeVO volume = s_volumeDao.findById(volumeId); if (volume == null) { throw new InvalidParameterValueException("Please specify a valid volume ID."); } - return _volumeMgr.volumeOnSharedStoragePool(volume); + return s_volumeMgr.volumeOnSharedStoragePool(volume); } public static List getNics(VirtualMachine vm) { - return _networkMgr.getNicProfiles(vm); + return s_networkMgr.getNicProfiles(vm); } public static NetworkProfile getNetworkProfile(long networkId) { - return _networkMgr.convertNetworkToNetworkProfile(networkId); + return s_networkMgr.convertNetworkToNetworkProfile(networkId); } public static NetworkOfferingVO findNetworkOfferingById(long networkOfferingId) { - return _networkOfferingDao.findByIdIncludingRemoved(networkOfferingId); + return s_networkOfferingDao.findByIdIncludingRemoved(networkOfferingId); } public static List listVlanByNetworkId(long networkId) { - return _vlanDao.listVlansByNetworkId(networkId); + return s_vlanDao.listVlansByNetworkId(networkId); } public static PhysicalNetworkVO findPhysicalNetworkById(long id) { - return _physicalNetworkDao.findById(id); + return s_physicalNetworkDao.findById(id); } public static PhysicalNetworkTrafficTypeVO findPhysicalNetworkTrafficTypeById(long id) { - return _physicalNetworkTrafficTypeDao.findById(id); + return s_physicalNetworkTrafficTypeDao.findById(id); } public static NetworkVO findNetworkById(long id) { - return _networkDao.findById(id); + return s_networkDao.findById(id); } public static Map> getNetworkCapabilities(long networkId, long zoneId) { - return _networkModel.getNetworkCapabilities(networkId); + return s_networkModel.getNetworkCapabilities(networkId); } public static long getPublicNetworkIdByZone(long zoneId) { - return _networkModel.getSystemNetworkByZoneAndTrafficType(zoneId, TrafficType.Public).getId(); + return s_networkModel.getSystemNetworkByZoneAndTrafficType(zoneId, TrafficType.Public).getId(); } public static Long getVlanNetworkId(long vlanId) { - VlanVO vlan = _vlanDao.findById(vlanId); + VlanVO vlan = s_vlanDao.findById(vlanId); if (vlan != null) { return vlan.getNetworkId(); } else { @@ -1135,15 +1125,15 @@ public class ApiDBUtils { } public static Integer getNetworkRate(long networkOfferingId) { - return _configMgr.getNetworkOfferingNetworkRate(networkOfferingId, null); + return s_configMgr.getNetworkOfferingNetworkRate(networkOfferingId, null); } public static Account getVlanAccount(long vlanId) { - return _configSvc.getVlanAccount(vlanId); + return s_configSvc.getVlanAccount(vlanId); } public static boolean isSecurityGroupEnabledInZone(long zoneId) { - DataCenterVO dc = _zoneDao.findById(zoneId); + DataCenterVO dc = s_zoneDao.findById(zoneId); if (dc == null) { return false; } else { @@ -1152,138 +1142,138 @@ public class ApiDBUtils { } public static Long getDedicatedNetworkDomain(long networkId) { - return _networkModel.getDedicatedNetworkDomain(networkId); + return s_networkModel.getDedicatedNetworkDomain(networkId); } public static float getCpuOverprovisioningFactor() { - String opFactor = _configDao.getValue(CapacityManager.CpuOverprovisioningFactorCK); + String opFactor = s_configDao.getValue(CapacityManager.CpuOverprovisioningFactorCK); float cpuOverprovisioningFactor = NumbersUtil.parseFloat(opFactor, 1); return cpuOverprovisioningFactor; } public static boolean isExtractionDisabled() { - String disableExtractionString = _configDao.getValue(Config.DisableExtraction.toString()); + String disableExtractionString = s_configDao.getValue(Config.DisableExtraction.toString()); boolean disableExtraction = (disableExtractionString == null) ? false : Boolean.parseBoolean(disableExtractionString); return disableExtraction; } public static SecurityGroup getSecurityGroup(String groupName, long ownerId) { - return _securityGroupMgr.getSecurityGroup(groupName, ownerId); + return s_securityGroupMgr.getSecurityGroup(groupName, ownerId); } public static ConsoleProxyVO findConsoleProxy(long id) { - return _consoleProxyDao.findById(id); + return s_consoleProxyDao.findById(id); } public static List findFirewallSourceCidrs(long id) { - return _firewallCidrsDao.getSourceCidrs(id); + return s_firewallCidrsDao.getSourceCidrs(id); } public static Account getProjectOwner(long projectId) { - return _projectMgr.getProjectOwner(projectId); + return s_projectMgr.getProjectOwner(projectId); } public static Project findProjectByProjectAccountId(long projectAccountId) { - return _projectMgr.findByProjectAccountId(projectAccountId); + return s_projectMgr.findByProjectAccountId(projectAccountId); } public static Project findProjectByProjectAccountIdIncludingRemoved(long projectAccountId) { - return _projectMgr.findByProjectAccountIdIncludingRemoved(projectAccountId); + return s_projectMgr.findByProjectAccountIdIncludingRemoved(projectAccountId); } public static Project findProjectById(long projectId) { - return _projectMgr.getProject(projectId); + return s_projectMgr.getProject(projectId); } public static long getProjectOwnwerId(long projectId) { - return _projectMgr.getProjectOwner(projectId).getId(); + return s_projectMgr.getProjectOwner(projectId).getId(); } public static Map getAccountDetails(long accountId) { - Map details = _accountDetailsDao.findDetails(accountId); + Map details = s_accountDetailsDao.findDetails(accountId); return details.isEmpty() ? null : details; } public static Map> listNetworkOfferingServices(long networkOfferingId) { - return _networkModel.getNetworkOfferingServiceProvidersMap(networkOfferingId); + return s_networkModel.getNetworkOfferingServiceProvidersMap(networkOfferingId); } public static List getElementServices(Provider provider) { - return _networkModel.getElementServices(provider); + return s_networkModel.getElementServices(provider); } public static List getProvidersForService(Service service) { - return _networkModel.listSupportedNetworkServiceProviders(service.getName()); + return s_networkModel.listSupportedNetworkServiceProviders(service.getName()); } public static boolean canElementEnableIndividualServices(Provider serviceProvider) { - return _networkModel.canElementEnableIndividualServices(serviceProvider); + return s_networkModel.canElementEnableIndividualServices(serviceProvider); } public static Pair getDomainNetworkDetails(long networkId) { - NetworkDomainVO map = _networkDomainDao.getDomainNetworkMapByNetworkId(networkId); + NetworkDomainVO map = s_networkDomainDao.getDomainNetworkMapByNetworkId(networkId); - boolean subdomainAccess = (map.isSubdomainAccess() != null) ? map.isSubdomainAccess() : _networkModel.getAllowSubdomainAccessGlobal(); + boolean subdomainAccess = (map.isSubdomainAccess() != null) ? map.isSubdomainAccess() : s_networkModel.getAllowSubdomainAccessGlobal(); return new Pair(map.getDomainId(), subdomainAccess); } public static long countFreePublicIps() { - return _ipAddressDao.countFreePublicIPs(); + return s_ipAddressDao.countFreePublicIPs(); } public static long findDefaultRouterServiceOffering() { - ServiceOfferingVO serviceOffering = _serviceOfferingDao.findByName(ServiceOffering.routerDefaultOffUniqueName); + ServiceOfferingVO serviceOffering = s_serviceOfferingDao.findByName(ServiceOffering.routerDefaultOffUniqueName); return serviceOffering.getId(); } public static IpAddress findIpByAssociatedVmId(long vmId) { - return _ipAddressDao.findByAssociatedVmId(vmId); + return s_ipAddressDao.findByAssociatedVmId(vmId); } public static String getHaTag() { - return _haMgr.getHaTag(); + return s_haMgr.getHaTag(); } public static Map> listVpcOffServices(long vpcOffId) { - return _vpcMgr.getVpcOffSvcProvidersMap(vpcOffId); + return s_vpcMgr.getVpcOffSvcProvidersMap(vpcOffId); } public static List listVpcNetworks(long vpcId) { - return _networkModel.listNetworksByVpc(vpcId); + return s_networkModel.listNetworksByVpc(vpcId); } public static boolean canUseForDeploy(Network network) { - return _networkModel.canUseForDeploy(network); + return s_networkModel.canUseForDeploy(network); } public static VMSnapshot getVMSnapshotById(Long vmSnapshotId) { - VMSnapshot vmSnapshot = _vmSnapshotDao.findById(vmSnapshotId); + VMSnapshot vmSnapshot = s_vmSnapshotDao.findById(vmSnapshotId); return vmSnapshot; } public static String getUuid(String resourceId, ResourceObjectType resourceType) { - return _taggedResourceService.getUuid(resourceId, resourceType); + return s_taggedResourceService.getUuid(resourceId, resourceType); } public static List listByResourceTypeAndId(ResourceObjectType type, long resourceId) { - return _taggedResourceService.listByResourceTypeAndId(type, resourceId); + return s_taggedResourceService.listByResourceTypeAndId(type, resourceId); } public static List getAutoScalePolicyConditions(long policyId) { - List vos = _asPolicyConditionMapDao.listByAll(policyId, null); + List vos = s_asPolicyConditionMapDao.listByAll(policyId, null); ArrayList conditions = new ArrayList(vos.size()); for (AutoScalePolicyConditionMapVO vo : vos) { - conditions.add(_asConditionDao.findById(vo.getConditionId())); + conditions.add(s_asConditionDao.findById(vo.getConditionId())); } return conditions; } public static void getAutoScaleVmGroupPolicyIds(long vmGroupId, List scaleUpPolicyIds, List scaleDownPolicyIds) { - List vos = _asVmGroupPolicyMapDao.listByVmGroupId(vmGroupId); + List vos = s_asVmGroupPolicyMapDao.listByVmGroupId(vmGroupId); for (AutoScaleVmGroupPolicyMapVO vo : vos) { - AutoScalePolicy autoScalePolicy = _asPolicyDao.findById(vo.getPolicyId()); + AutoScalePolicy autoScalePolicy = s_asPolicyDao.findById(vo.getPolicyId()); if (autoScalePolicy.getAction().equals("scaleup")) { scaleUpPolicyIds.add(autoScalePolicy.getId()); } else { @@ -1293,7 +1283,7 @@ public class ApiDBUtils { } public static String getKeyPairName(String sshPublicKey) { - SSHKeyPairVO sshKeyPair = _sshKeyPairDao.findByPublicKey(sshPublicKey); + SSHKeyPairVO sshKeyPair = s_sshKeyPairDao.findByPublicKey(sshPublicKey); //key might be removed prior to this point if (sshKeyPair != null) { return sshKeyPair.getName(); @@ -1302,13 +1292,13 @@ public class ApiDBUtils { } public static UserVmDetailVO findPublicKeyByVmId(long vmId) { - return _userVmDetailsDao.findDetail(vmId, "SSH.PublicKey"); + return s_userVmDetailsDao.findDetail(vmId, "SSH.PublicKey"); } public static void getAutoScaleVmGroupPolicies(long vmGroupId, List scaleUpPolicies, List scaleDownPolicies) { - List vos = _asVmGroupPolicyMapDao.listByVmGroupId(vmGroupId); + List vos = s_asVmGroupPolicyMapDao.listByVmGroupId(vmGroupId); for (AutoScaleVmGroupPolicyMapVO vo : vos) { - AutoScalePolicy autoScalePolicy = _asPolicyDao.findById(vo.getPolicyId()); + AutoScalePolicy autoScalePolicy = s_asPolicyDao.findById(vo.getPolicyId()); if (autoScalePolicy.getAction().equals("scaleup")) { scaleUpPolicies.add(autoScalePolicy); } else { @@ -1318,63 +1308,63 @@ public class ApiDBUtils { } public static CounterVO getCounter(long counterId) { - return _counterDao.findById(counterId); + return s_counterDao.findById(counterId); } public static ConditionVO findConditionById(long conditionId) { - return _asConditionDao.findById(conditionId); + return s_asConditionDao.findById(conditionId); } public static PhysicalNetworkServiceProviderVO findPhysicalNetworkServiceProviderById(long providerId) { - return _physicalNetworkServiceProviderDao.findById(providerId); + return s_physicalNetworkServiceProviderDao.findById(providerId); } public static FirewallRuleVO findFirewallRuleById(long ruleId) { - return _firewallRuleDao.findById(ruleId); + return s_firewallRuleDao.findById(ruleId); } public static StaticRouteVO findStaticRouteById(long routeId) { - return _staticRouteDao.findById(routeId); + return s_staticRouteDao.findById(routeId); } public static VpcGatewayVO findVpcGatewayById(long gatewayId) { - return _vpcGatewayDao.findById(gatewayId); + return s_vpcGatewayDao.findById(gatewayId); } public static AutoScalePolicyVO findAutoScalePolicyById(long policyId) { - return _asPolicyDao.findById(policyId); + return s_asPolicyDao.findById(policyId); } public static AutoScaleVmProfileVO findAutoScaleVmProfileById(long profileId) { - return _asVmProfileDao.findById(profileId); + return s_asVmProfileDao.findById(profileId); } public static AutoScaleVmGroupVO findAutoScaleVmGroupById(long groupId) { - return _asVmGroupDao.findById(groupId); + return s_asVmGroupDao.findById(groupId); } public static GuestOSCategoryVO findGuestOsCategoryById(long catId) { - return _guestOSCategoryDao.findById(catId); + return s_guestOSCategoryDao.findById(catId); } public static VpcVO findVpcById(long vpcId) { - return _vpcDao.findById(vpcId); + return s_vpcDao.findById(vpcId); } public static SnapshotPolicy findSnapshotPolicyById(long policyId) { - return _snapshotPolicyDao.findById(policyId); + return s_snapshotPolicyDao.findById(policyId); } public static VpcOffering findVpcOfferingById(long offeringId) { - return _vpcOfferingDao.findById(offeringId); + return s_vpcOfferingDao.findById(offeringId); } public static NetworkACL findByNetworkACLId(long aclId) { - return _networkACLDao.findById(aclId); + return s_networkACLDao.findById(aclId); } public static AsyncJob findAsyncJobById(long jobId) { - return _asyncJobDao.findById(jobId); + return s_asyncJobDao.findById(jobId); } public static String findJobInstanceUuid(AsyncJob job) { @@ -1503,55 +1493,55 @@ public class ApiDBUtils { /////////////////////////////////////////////////////////////////////// public static DomainRouterResponse newDomainRouterResponse(DomainRouterJoinVO vr, Account caller) { - return _domainRouterJoinDao.newDomainRouterResponse(vr, caller); + return s_domainRouterJoinDao.newDomainRouterResponse(vr, caller); } public static DomainRouterResponse fillRouterDetails(DomainRouterResponse vrData, DomainRouterJoinVO vr) { - return _domainRouterJoinDao.setDomainRouterResponse(vrData, vr); + return s_domainRouterJoinDao.setDomainRouterResponse(vrData, vr); } public static List newDomainRouterView(VirtualRouter vr) { - return _domainRouterJoinDao.newDomainRouterView(vr); + return s_domainRouterJoinDao.newDomainRouterView(vr); } public static UserVmResponse newUserVmResponse(String objectName, UserVmJoinVO userVm, EnumSet details, Account caller) { - return _userVmJoinDao.newUserVmResponse(objectName, userVm, details, caller); + return s_userVmJoinDao.newUserVmResponse(objectName, userVm, details, caller); } public static UserVmResponse fillVmDetails(UserVmResponse vmData, UserVmJoinVO vm) { - return _userVmJoinDao.setUserVmResponse(vmData, vm); + return s_userVmJoinDao.setUserVmResponse(vmData, vm); } public static List newUserVmView(UserVm... userVms) { - return _userVmJoinDao.newUserVmView(userVms); + return s_userVmJoinDao.newUserVmView(userVms); } public static SecurityGroupResponse newSecurityGroupResponse(SecurityGroupJoinVO vsg, Account caller) { - return _securityGroupJoinDao.newSecurityGroupResponse(vsg, caller); + return s_securityGroupJoinDao.newSecurityGroupResponse(vsg, caller); } public static SecurityGroupResponse fillSecurityGroupDetails(SecurityGroupResponse vsgData, SecurityGroupJoinVO sg) { - return _securityGroupJoinDao.setSecurityGroupResponse(vsgData, sg); + return s_securityGroupJoinDao.setSecurityGroupResponse(vsgData, sg); } public static List newSecurityGroupView(SecurityGroup sg) { - return _securityGroupJoinDao.newSecurityGroupView(sg); + return s_securityGroupJoinDao.newSecurityGroupView(sg); } public static List findSecurityGroupViewById(Long sgId) { - return _securityGroupJoinDao.searchByIds(sgId); + return s_securityGroupJoinDao.searchByIds(sgId); } public static ResourceTagResponse newResourceTagResponse(ResourceTagJoinVO vsg, boolean keyValueOnly) { - return _tagJoinDao.newResourceTagResponse(vsg, keyValueOnly); + return s_tagJoinDao.newResourceTagResponse(vsg, keyValueOnly); } public static ResourceTagJoinVO newResourceTagView(ResourceTag sg) { - return _tagJoinDao.newResourceTagView(sg); + return s_tagJoinDao.newResourceTagView(sg); } public static ResourceTagJoinVO findResourceTagViewById(Long tagId) { - List tags = _tagJoinDao.searchByIds(tagId); + List tags = s_tagJoinDao.searchByIds(tagId); if (tags != null && tags.size() > 0) { return tags.get(0); } else { @@ -1560,19 +1550,19 @@ public class ApiDBUtils { } public static EventResponse newEventResponse(EventJoinVO ve) { - return _eventJoinDao.newEventResponse(ve); + return s_eventJoinDao.newEventResponse(ve); } public static EventJoinVO newEventView(Event e) { - return _eventJoinDao.newEventView(e); + return s_eventJoinDao.newEventView(e); } public static InstanceGroupResponse newInstanceGroupResponse(InstanceGroupJoinVO ve) { - return _vmGroupJoinDao.newInstanceGroupResponse(ve); + return s_vmGroupJoinDao.newInstanceGroupResponse(ve); } public static InstanceGroupJoinVO newInstanceGroupView(InstanceGroup e) { - return _vmGroupJoinDao.newInstanceGroupView(e); + return s_vmGroupJoinDao.newInstanceGroupView(e); } public static UserResponse newUserResponse(UserAccountJoinVO usr) { @@ -1580,7 +1570,7 @@ public class ApiDBUtils { } public static UserResponse newUserResponse(UserAccountJoinVO usr, Long domainId) { - UserResponse response = _userAccountJoinDao.newUserResponse(usr); + UserResponse response = s_userAccountJoinDao.newUserResponse(usr); if (domainId != null && usr.getDomainId() != domainId) response.setIsCallerChildDomain(true); else @@ -1589,221 +1579,221 @@ public class ApiDBUtils { } public static UserAccountJoinVO newUserView(User usr) { - return _userAccountJoinDao.newUserView(usr); + return s_userAccountJoinDao.newUserView(usr); } public static UserAccountJoinVO newUserView(UserAccount usr) { - return _userAccountJoinDao.newUserView(usr); + return s_userAccountJoinDao.newUserView(usr); } public static ProjectResponse newProjectResponse(ProjectJoinVO proj) { - return _projectJoinDao.newProjectResponse(proj); + return s_projectJoinDao.newProjectResponse(proj); } public static ProjectResponse fillProjectDetails(ProjectResponse rsp, ProjectJoinVO proj) { - return _projectJoinDao.setProjectResponse(rsp, proj); + return s_projectJoinDao.setProjectResponse(rsp, proj); } public static List newProjectView(Project proj) { - return _projectJoinDao.newProjectView(proj); + return s_projectJoinDao.newProjectView(proj); } public static List findUserViewByAccountId(Long accountId) { - return _userAccountJoinDao.searchByAccountId(accountId); + return s_userAccountJoinDao.searchByAccountId(accountId); } public static ProjectAccountResponse newProjectAccountResponse(ProjectAccountJoinVO proj) { - return _projectAccountJoinDao.newProjectAccountResponse(proj); + return s_projectAccountJoinDao.newProjectAccountResponse(proj); } public static ProjectAccountJoinVO newProjectAccountView(ProjectAccount proj) { - return _projectAccountJoinDao.newProjectAccountView(proj); + return s_projectAccountJoinDao.newProjectAccountView(proj); } public static ProjectInvitationResponse newProjectInvitationResponse(ProjectInvitationJoinVO proj) { - return _projectInvitationJoinDao.newProjectInvitationResponse(proj); + return s_projectInvitationJoinDao.newProjectInvitationResponse(proj); } public static ProjectInvitationJoinVO newProjectInvitationView(ProjectInvitation proj) { - return _projectInvitationJoinDao.newProjectInvitationView(proj); + return s_projectInvitationJoinDao.newProjectInvitationView(proj); } public static HostResponse newHostResponse(HostJoinVO vr, EnumSet details) { - return _hostJoinDao.newHostResponse(vr, details); + return s_hostJoinDao.newHostResponse(vr, details); } public static HostResponse fillHostDetails(HostResponse vrData, HostJoinVO vr) { - return _hostJoinDao.setHostResponse(vrData, vr); + return s_hostJoinDao.setHostResponse(vrData, vr); } public static HostForMigrationResponse newHostForMigrationResponse(HostJoinVO vr, EnumSet details) { - return _hostJoinDao.newHostForMigrationResponse(vr, details); + return s_hostJoinDao.newHostForMigrationResponse(vr, details); } public static HostForMigrationResponse fillHostForMigrationDetails(HostForMigrationResponse vrData, HostJoinVO vr) { - return _hostJoinDao.setHostForMigrationResponse(vrData, vr); + return s_hostJoinDao.setHostForMigrationResponse(vrData, vr); } public static List newHostView(Host vr) { - return _hostJoinDao.newHostView(vr); + return s_hostJoinDao.newHostView(vr); } public static VolumeResponse newVolumeResponse(VolumeJoinVO vr) { - return _volJoinDao.newVolumeResponse(vr); + return s_volJoinDao.newVolumeResponse(vr); } public static VolumeResponse fillVolumeDetails(VolumeResponse vrData, VolumeJoinVO vr) { - return _volJoinDao.setVolumeResponse(vrData, vr); + return s_volJoinDao.setVolumeResponse(vrData, vr); } public static List newVolumeView(Volume vr) { - return _volJoinDao.newVolumeView(vr); + return s_volJoinDao.newVolumeView(vr); } public static StoragePoolResponse newStoragePoolResponse(StoragePoolJoinVO vr) { - return _poolJoinDao.newStoragePoolResponse(vr); + return s_poolJoinDao.newStoragePoolResponse(vr); } public static StoragePoolResponse fillStoragePoolDetails(StoragePoolResponse vrData, StoragePoolJoinVO vr) { - return _poolJoinDao.setStoragePoolResponse(vrData, vr); + return s_poolJoinDao.setStoragePoolResponse(vrData, vr); } public static StoragePoolResponse newStoragePoolForMigrationResponse(StoragePoolJoinVO vr) { - return _poolJoinDao.newStoragePoolForMigrationResponse(vr); + return s_poolJoinDao.newStoragePoolForMigrationResponse(vr); } public static StoragePoolResponse fillStoragePoolForMigrationDetails(StoragePoolResponse vrData, StoragePoolJoinVO vr) { - return _poolJoinDao.setStoragePoolForMigrationResponse(vrData, vr); + return s_poolJoinDao.setStoragePoolForMigrationResponse(vrData, vr); } public static List newStoragePoolView(StoragePool vr) { - return _poolJoinDao.newStoragePoolView(vr); + return s_poolJoinDao.newStoragePoolView(vr); } public static ImageStoreResponse newImageStoreResponse(ImageStoreJoinVO vr) { - return _imageStoreJoinDao.newImageStoreResponse(vr); + return s_imageStoreJoinDao.newImageStoreResponse(vr); } public static ImageStoreResponse fillImageStoreDetails(ImageStoreResponse vrData, ImageStoreJoinVO vr) { - return _imageStoreJoinDao.setImageStoreResponse(vrData, vr); + return s_imageStoreJoinDao.setImageStoreResponse(vrData, vr); } public static List newImageStoreView(ImageStore vr) { - return _imageStoreJoinDao.newImageStoreView(vr); + return s_imageStoreJoinDao.newImageStoreView(vr); } public static AccountResponse newAccountResponse(AccountJoinVO ve) { - return _accountJoinDao.newAccountResponse(ve); + return s_accountJoinDao.newAccountResponse(ve); } public static AccountJoinVO newAccountView(Account e) { - return _accountJoinDao.newAccountView(e); + return s_accountJoinDao.newAccountView(e); } public static AccountJoinVO findAccountViewById(Long accountId) { - return _accountJoinDao.findByIdIncludingRemoved(accountId); + return s_accountJoinDao.findByIdIncludingRemoved(accountId); } public static AsyncJobResponse newAsyncJobResponse(AsyncJobJoinVO ve) { - return _jobJoinDao.newAsyncJobResponse(ve); + return s_jobJoinDao.newAsyncJobResponse(ve); } public static AsyncJobJoinVO newAsyncJobView(AsyncJob e) { - return _jobJoinDao.newAsyncJobView(e); + return s_jobJoinDao.newAsyncJobView(e); } public static DiskOfferingResponse newDiskOfferingResponse(DiskOfferingJoinVO offering) { - return _diskOfferingJoinDao.newDiskOfferingResponse(offering); + return s_diskOfferingJoinDao.newDiskOfferingResponse(offering); } public static DiskOfferingJoinVO newDiskOfferingView(DiskOffering offering) { - return _diskOfferingJoinDao.newDiskOfferingView(offering); + return s_diskOfferingJoinDao.newDiskOfferingView(offering); } public static ServiceOfferingResponse newServiceOfferingResponse(ServiceOfferingJoinVO offering) { - return _serviceOfferingJoinDao.newServiceOfferingResponse(offering); + return s_serviceOfferingJoinDao.newServiceOfferingResponse(offering); } public static ServiceOfferingJoinVO newServiceOfferingView(ServiceOffering offering) { - return _serviceOfferingJoinDao.newServiceOfferingView(offering); + return s_serviceOfferingJoinDao.newServiceOfferingView(offering); } public static ZoneResponse newDataCenterResponse(DataCenterJoinVO dc, Boolean showCapacities) { - return _dcJoinDao.newDataCenterResponse(dc, showCapacities); + return s_dcJoinDao.newDataCenterResponse(dc, showCapacities); } public static DataCenterJoinVO newDataCenterView(DataCenter dc) { - return _dcJoinDao.newDataCenterView(dc); + return s_dcJoinDao.newDataCenterView(dc); } public static Map findHostDetailsById(long hostId) { - return _hostDetailsDao.findDetails(hostId); + return s_hostDetailsDao.findDetails(hostId); } public static List findNicSecondaryIps(long nicId) { - return _nicSecondaryIpDao.listByNicId(nicId); + return s_nicSecondaryIpDao.listByNicId(nicId); } public static TemplateResponse newTemplateUpdateResponse(TemplateJoinVO vr) { - return _templateJoinDao.newUpdateResponse(vr); + return s_templateJoinDao.newUpdateResponse(vr); } public static TemplateResponse newTemplateResponse(TemplateJoinVO vr) { - return _templateJoinDao.newTemplateResponse(vr); + return s_templateJoinDao.newTemplateResponse(vr); } public static TemplateResponse newIsoResponse(TemplateJoinVO vr) { - return _templateJoinDao.newIsoResponse(vr); + return s_templateJoinDao.newIsoResponse(vr); } public static TemplateResponse fillTemplateDetails(TemplateResponse vrData, TemplateJoinVO vr) { - return _templateJoinDao.setTemplateResponse(vrData, vr); + return s_templateJoinDao.setTemplateResponse(vrData, vr); } public static List newTemplateView(VirtualMachineTemplate vr) { - return _templateJoinDao.newTemplateView(vr); + return s_templateJoinDao.newTemplateView(vr); } public static List newTemplateView(VirtualMachineTemplate vr, long zoneId, boolean readyOnly) { - return _templateJoinDao.newTemplateView(vr, zoneId, readyOnly); + return s_templateJoinDao.newTemplateView(vr, zoneId, readyOnly); } public static AffinityGroup getAffinityGroup(String groupName, long accountId) { - return _affinityGroupDao.findByAccountAndName(accountId, groupName); + return s_affinityGroupDao.findByAccountAndName(accountId, groupName); } public static AffinityGroupResponse newAffinityGroupResponse(AffinityGroupJoinVO group) { - return _affinityGroupJoinDao.newAffinityGroupResponse(group); + return s_affinityGroupJoinDao.newAffinityGroupResponse(group); } public static AffinityGroupResponse fillAffinityGroupDetails(AffinityGroupResponse resp, AffinityGroupJoinVO group) { - return _affinityGroupJoinDao.setAffinityGroupResponse(resp, group); + return s_affinityGroupJoinDao.setAffinityGroupResponse(resp, group); } public static List listSiteLoadBalancers(long gslbRuleId) { - return _gslbService.listSiteLoadBalancers(gslbRuleId); + return s_gslbService.listSiteLoadBalancers(gslbRuleId); } public static String getDnsNameConfiguredForGslb() { - String providerDnsName = _configDao.getValue(Config.CloudDnsName.key()); + String providerDnsName = s_configDao.getValue(Config.CloudDnsName.key()); return providerDnsName; } public static Map getResourceDetails(long resourceId, ResourceObjectType resourceType) { Map details = null; if (isAdmin(CallContext.current().getCallingAccount())) { - details = _resourceDetailsService.getDetailsMap(resourceId, resourceType, null); + details = s_resourceDetailsService.getDetailsMap(resourceId, resourceType, null); } else { - details = _resourceDetailsService.getDetailsMap(resourceId, resourceType, true); + details = s_resourceDetailsService.getDetailsMap(resourceId, resourceType, true); } return details.isEmpty() ? null : details; } public static boolean isAdmin(Account account) { - return _accountService.isAdmin(account.getType()); + return s_accountService.isAdmin(account.getType()); } public static List listResourceTagViewByResourceUUID(String resourceUUID, ResourceObjectType resourceType) { - return _tagJoinDao.listBy(resourceUUID, resourceType); + return s_tagJoinDao.listBy(resourceUUID, resourceType); } } diff --git a/server/src/com/cloud/api/ApiDispatcher.java b/server/src/com/cloud/api/ApiDispatcher.java index 225cbdc43b6..55ef53ae2b9 100755 --- a/server/src/com/cloud/api/ApiDispatcher.java +++ b/server/src/com/cloud/api/ApiDispatcher.java @@ -173,7 +173,7 @@ public class ApiDispatcher { pageSize = Long.valueOf((String)pageSizeObj); } - if ((unpackedParams.get(ApiConstants.PAGE) == null) && (pageSize != null && !pageSize.equals(BaseListCmd.PAGESIZE_UNLIMITED))) { + if ((unpackedParams.get(ApiConstants.PAGE) == null) && (pageSize != null && !pageSize.equals(BaseListCmd.s_pageSizeUnlimited))) { ServerApiException ex = new ServerApiException(ApiErrorCode.PARAM_ERROR, "\"page\" parameter is required when \"pagesize\" is specified"); ex.setCSErrorCode(CSExceptionErrorCode.getCSErrCode(ex.getClass().getName())); throw ex; @@ -427,8 +427,8 @@ public class ApiDispatcher { } } else { DateFormat format = BaseCmd.INPUT_FORMAT; - format.setLenient(false); synchronized (format) { + format.setLenient(false); field.set(cmdObj, format.parse(paramObj.toString())); } } diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index 6a99fa630e7..a50b3eeffb2 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -26,7 +26,6 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.StringTokenizer; import java.util.TimeZone; import javax.inject.Inject; @@ -145,7 +144,6 @@ import org.apache.cloudstack.network.lb.ApplicationLoadBalancerRule; import org.apache.cloudstack.region.PortableIp; import org.apache.cloudstack.region.PortableIpRange; import org.apache.cloudstack.region.Region; -import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; import org.apache.cloudstack.usage.Usage; import org.apache.cloudstack.usage.UsageService; import org.apache.cloudstack.usage.UsageTypes; @@ -259,7 +257,6 @@ import com.cloud.projects.Project; import com.cloud.projects.ProjectAccount; import com.cloud.projects.ProjectInvitation; import com.cloud.region.ha.GlobalLoadBalancerRule; -import com.cloud.server.Criteria; import com.cloud.server.ResourceTag; import com.cloud.server.ResourceTag.ResourceObjectType; import com.cloud.service.ServiceOfferingVO; @@ -270,7 +267,6 @@ import com.cloud.storage.GuestOSCategoryVO; import com.cloud.storage.ImageStore; import com.cloud.storage.Snapshot; import com.cloud.storage.SnapshotVO; -import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.StoragePool; import com.cloud.storage.Upload; import com.cloud.storage.UploadVO; @@ -288,7 +284,6 @@ import com.cloud.uservm.UserVm; import com.cloud.utils.Pair; import com.cloud.utils.StringUtils; import com.cloud.utils.db.EntityManager; -import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.Ip; import com.cloud.utils.net.NetUtils; import com.cloud.vm.ConsoleProxyVO; @@ -389,8 +384,9 @@ public class ApiResponseHelper implements ResponseGenerator { populateDomain(resourceLimitResponse, accountTemp.getDomainId()); } resourceLimitResponse.setResourceType(Integer.valueOf(limit.getType().getOrdinal()).toString()); + if ((limit.getType() == ResourceType.primary_storage || limit.getType() == ResourceType.secondary_storage) && limit.getMax() >= 0) { - resourceLimitResponse.setMax((long)Math.ceil(limit.getMax() / ResourceType.bytesToGiB)); + resourceLimitResponse.setMax((long)Math.ceil((double)limit.getMax() / ResourceType.bytesToGiB)); } else { resourceLimitResponse.setMax(limit.getMax()); } @@ -465,11 +461,12 @@ public class ApiResponseHelper implements ResponseGenerator { } if (snapshotInfo == null) { - throw new CloudRuntimeException("Unable to find info for image store snapshot with uuid '" + snapshot.getUuid() + "'"); + s_logger.debug("Unable to find info for image store snapshot with uuid " + snapshot.getUuid()); + snapshotResponse.setRevertable(false); + } else { + snapshotResponse.setRevertable(snapshotInfo.isRevertable()); } - snapshotResponse.setRevertable(snapshotInfo.isRevertable()); - // set tag information List tags = ApiDBUtils.listByResourceTypeAndId(ResourceObjectType.Snapshot, snapshot.getId()); List tagResponses = new ArrayList(); @@ -1015,7 +1012,7 @@ public class ApiResponseHelper implements ResponseGenerator { response.setPublicEndPort(Integer.toString(fwRule.getSourcePortEnd())); List cidrs = ApiDBUtils.findFirewallSourceCidrs(fwRule.getId()); response.setCidrList(StringUtils.join(cidrs, ",")); - + Network guestNtwk = ApiDBUtils.findNetworkById(fwRule.getNetworkId()); response.setNetworkId(guestNtwk.getUuid()); @@ -1671,152 +1668,6 @@ public class ApiResponseHelper implements ResponseGenerator { return ApiDBUtils.newEventResponse(vEvent); } - private List sumCapacities(List hostCapacities) { - Map totalCapacityMap = new HashMap(); - Map usedCapacityMap = new HashMap(); - - Set poolIdsToIgnore = new HashSet(); - Criteria c = new Criteria(); - // TODO: implement - List allStoragePools = ApiDBUtils.searchForStoragePools(c); - for (StoragePoolVO pool : allStoragePools) { - StoragePoolType poolType = pool.getPoolType(); - if (!(poolType.isShared())) {// All the non shared storages - // shouldn't show up in the capacity - // calculation - poolIdsToIgnore.add(pool.getId()); - } - } - - float cpuOverprovisioningFactor = ApiDBUtils.getCpuOverprovisioningFactor(); - - // collect all the capacity types, sum allocated/used and sum - // total...get one capacity number for each - for (Capacity capacity : hostCapacities) { - - // check if zone exist - DataCenter zone = ApiDBUtils.findZoneById(capacity.getDataCenterId()); - if (zone == null) { - continue; - } - - short capacityType = capacity.getCapacityType(); - - // If local storage then ignore - if ((capacityType == Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED || capacityType == Capacity.CAPACITY_TYPE_STORAGE) && - poolIdsToIgnore.contains(capacity.getHostOrPoolId())) { - continue; - } - - String key = capacity.getCapacityType() + "_" + capacity.getDataCenterId(); - String keyForPodTotal = key + "_-1"; - - boolean sumPodCapacity = false; - if (capacity.getPodId() != null) { - key += "_" + capacity.getPodId(); - sumPodCapacity = true; - } - - Long totalCapacity = totalCapacityMap.get(key); - Long usedCapacity = usedCapacityMap.get(key); - - // reset overprovisioning factor to 1 - float overprovisioningFactor = 1; - if (capacityType == Capacity.CAPACITY_TYPE_CPU) { - overprovisioningFactor = cpuOverprovisioningFactor; - } - - if (totalCapacity == null) { - totalCapacity = new Long((long)(capacity.getTotalCapacity() * overprovisioningFactor)); - } else { - totalCapacity = new Long((long)(capacity.getTotalCapacity() * overprovisioningFactor)) + totalCapacity; - } - - if (usedCapacity == null) { - usedCapacity = new Long(capacity.getUsedCapacity()); - } 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(); - } - - totalCapacityMap.put(key, totalCapacity); - usedCapacityMap.put(key, usedCapacity); - - if (sumPodCapacity) { - totalCapacity = totalCapacityMap.get(keyForPodTotal); - usedCapacity = usedCapacityMap.get(keyForPodTotal); - - overprovisioningFactor = 1; - if (capacityType == Capacity.CAPACITY_TYPE_CPU) { - overprovisioningFactor = cpuOverprovisioningFactor; - } - - if (totalCapacity == null) { - totalCapacity = new Long((long)(capacity.getTotalCapacity() * overprovisioningFactor)); - } else { - totalCapacity = new Long((long)(capacity.getTotalCapacity() * overprovisioningFactor)) + totalCapacity; - } - - if (usedCapacity == null) { - usedCapacity = new Long(capacity.getUsedCapacity()); - } 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(); - } - - totalCapacityMap.put(keyForPodTotal, totalCapacity); - usedCapacityMap.put(keyForPodTotal, usedCapacity); - } - } - - List summedCapacities = new ArrayList(); - for (String key : totalCapacityMap.keySet()) { - CapacityVO summedCapacity = new CapacityVO(); - - StringTokenizer st = new StringTokenizer(key, "_"); - summedCapacity.setCapacityType(Short.parseShort(st.nextToken())); - summedCapacity.setDataCenterId(Long.parseLong(st.nextToken())); - if (st.hasMoreTokens()) { - summedCapacity.setPodId(Long.parseLong(st.nextToken())); - } - - summedCapacity.setTotalCapacity(totalCapacityMap.get(key)); - summedCapacity.setUsedCapacity(usedCapacityMap.get(key)); - - summedCapacities.add(summedCapacity); - } - return summedCapacities; - } - @Override public List createCapacityResponse(List result, DecimalFormat format) { List capacityResponses = new ArrayList(); @@ -1954,8 +1805,6 @@ public class ApiResponseHelper implements ResponseGenerator { public SecurityGroupResponse createSecurityGroupResponseFromSecurityGroupRule(List securityRules) { SecurityGroupResponse response = new SecurityGroupResponse(); Map securiytGroupAccounts = new HashMap(); - Map allowedSecurityGroups = new HashMap(); - Map allowedSecuriytGroupAccounts = new HashMap(); if ((securityRules != null) && !securityRules.isEmpty()) { SecurityGroupJoinVO securityGroup = ApiDBUtils.findSecurityGroupViewById(securityRules.get(0).getSecurityGroupId()).get(0); @@ -2197,8 +2046,7 @@ public class ApiResponseHelper implements ResponseGenerator { reservation = (NetUtils.long2Ip(startGuestIp) + "-" + NetUtils.long2Ip(startVmIp - 1)); } if (startVmIp > startGuestIp + 1 && endVmIp < endGuestIp - 1) { - reservation = - (NetUtils.long2Ip(startGuestIp) + "-" + NetUtils.long2Ip(startVmIp - 1) + " , " + NetUtils.long2Ip(endVmIp + 1) + "-" + NetUtils.long2Ip(endGuestIp)); + reservation = (NetUtils.long2Ip(startGuestIp) + "-" + NetUtils.long2Ip(startVmIp - 1) + " , " + NetUtils.long2Ip(endVmIp + 1) + "-" + NetUtils.long2Ip(endGuestIp)); } } response.setReservedIpRange(reservation); @@ -2209,10 +2057,10 @@ public class ApiResponseHelper implements ResponseGenerator { response.setBroadcastUri(broadcastUri); String vlan = "N/A"; switch (BroadcastDomainType.getSchemeValue(network.getBroadcastUri())) { - case Vlan: - case Vxlan: - vlan = BroadcastDomainType.getValue(network.getBroadcastUri()); - break; + case Vlan: + case Vxlan: + vlan = BroadcastDomainType.getValue(network.getBroadcastUri()); + break; } // return vlan information only to Root admin response.setVlan(vlan); @@ -2380,10 +2228,10 @@ public class ApiResponseHelper implements ResponseGenerator { response.setPublicIpAddressId(ip.getUuid()); response.setPublicIpAddress(ip.getAddress().addr()); } - + Network network = ApiDBUtils.findNetworkById(fwRule.getNetworkId()); response.setNetworkId(network.getUuid()); - + FirewallRule.State state = fwRule.getState(); String stateToSet = state.toString(); if (state.equals(FirewallRule.State.Revoke)) { @@ -2625,8 +2473,8 @@ public class ApiResponseHelper implements ResponseGenerator { CapabilityResponse capabilityResponse = new CapabilityResponse(); capabilityResponse.setName(cap.getName()); capabilityResponse.setObjectName("capability"); - if (cap.getName().equals(Capability.SupportedLBIsolation.getName()) || cap.getName().equals(Capability.SupportedSourceNatTypes.getName()) || - cap.getName().equals(Capability.RedundantRouter.getName())) { + if (cap.getName().equals(Capability.SupportedLBIsolation.getName()) || cap.getName().equals(Capability.SupportedSourceNatTypes.getName()) + || cap.getName().equals(Capability.RedundantRouter.getName())) { capabilityResponse.setCanChoose(true); } else { capabilityResponse.setCanChoose(false); @@ -2640,8 +2488,8 @@ public class ApiResponseHelper implements ResponseGenerator { List serviceProvidersResponses = new ArrayList(); for (Network.Provider serviceProvider : serviceProviders) { // return only Virtual Router/JuniperSRX/CiscoVnmc as a provider for the firewall - if (service == Service.Firewall && - !(serviceProvider == Provider.VirtualRouter || serviceProvider == Provider.JuniperSRX || serviceProvider == Provider.CiscoVnmc || serviceProvider == Provider.PaloAlto)) { + if (service == Service.Firewall + && !(serviceProvider == Provider.VirtualRouter || serviceProvider == Provider.JuniperSRX || serviceProvider == Provider.CiscoVnmc || serviceProvider == Provider.PaloAlto)) { continue; } @@ -2685,6 +2533,10 @@ public class ApiResponseHelper implements ResponseGenerator { } response.setServices(services); + Provider serviceProvider = Provider.getProvider(result.getProviderName()); + boolean canEnableIndividualServices = ApiDBUtils.canElementEnableIndividualServices(serviceProvider); + response.setCanEnableIndividualServices(canEnableIndividualServices); + response.setObjectName("networkserviceprovider"); return response; } @@ -2728,21 +2580,20 @@ public class ApiResponseHelper implements ResponseGenerator { return response; } - @Override - public OvsProviderResponse createOvsProviderResponse(OvsProvider result) { + @Override + public OvsProviderResponse createOvsProviderResponse(OvsProvider result) { - OvsProviderResponse response = new OvsProviderResponse(); - response.setId(result.getUuid()); - PhysicalNetworkServiceProvider nsp = ApiDBUtils - .findPhysicalNetworkServiceProviderById(result.getNspId()); - if (nsp != null) { - response.setNspId(nsp.getUuid()); - } - response.setEnabled(result.isEnabled()); + OvsProviderResponse response = new OvsProviderResponse(); + response.setId(result.getUuid()); + PhysicalNetworkServiceProvider nsp = ApiDBUtils.findPhysicalNetworkServiceProviderById(result.getNspId()); + if (nsp != null) { + response.setNspId(nsp.getUuid()); + } + response.setEnabled(result.isEnabled()); - response.setObjectName("ovselement"); - return response; - } + response.setObjectName("ovselement"); + return response; + } @Override public LBStickinessResponse createLBStickinessPolicyResponse(StickinessPolicy stickinessPolicy, LoadBalancer lb) { @@ -3013,7 +2864,7 @@ public class ApiResponseHelper implements ResponseGenerator { response.setState(result.getState().toString()); response.setSourceNat(result.getSourceNat()); - NetworkACL acl = ApiDBUtils.findByNetworkACLId(result.getNetworkACLId()); + NetworkACL acl = ApiDBUtils.findByNetworkACLId(result.getNetworkACLId()); if (acl != null) { response.setAclId(acl.getUuid()); } @@ -3156,11 +3007,10 @@ public class ApiResponseHelper implements ResponseGenerator { response.setCidr(result.getCidr()); StaticRoute.State state = result.getState(); - String stateToSet = state.toString(); - if (state.equals(FirewallRule.State.Revoke)) { - stateToSet = "Deleting"; + if (state.equals(StaticRoute.State.Revoke)) { + state = StaticRoute.State.Deleting; } - response.setState(stateToSet); + response.setState(state.toString()); populateAccount(response, result.getAccountId()); populateDomain(response, result.getDomainId()); @@ -3372,8 +3222,8 @@ public class ApiResponseHelper implements ResponseGenerator { NetworkVO network = _entityMgr.findById(NetworkVO.class, usageRecord.getNetworkId().toString()); usageRecResponse.setNetworkId(network.getUuid()); - } else if (usageRecord.getUsageType() == UsageTypes.VM_DISK_IO_READ || usageRecord.getUsageType() == UsageTypes.VM_DISK_IO_WRITE || - usageRecord.getUsageType() == UsageTypes.VM_DISK_BYTES_READ || usageRecord.getUsageType() == UsageTypes.VM_DISK_BYTES_WRITE) { + } else if (usageRecord.getUsageType() == UsageTypes.VM_DISK_IO_READ || usageRecord.getUsageType() == UsageTypes.VM_DISK_IO_WRITE + || usageRecord.getUsageType() == UsageTypes.VM_DISK_BYTES_READ || usageRecord.getUsageType() == UsageTypes.VM_DISK_BYTES_WRITE) { //Device Type usageRecResponse.setType(usageRecord.getType()); //VM Instance Id @@ -3613,6 +3463,8 @@ public class ApiResponseHelper implements ResponseGenerator { response.setIp6Address(result.getIp6Address()); } + response.setDeviceId(String.valueOf(result.getDeviceId())); + response.setIsDefault(result.isDefaultNic()); return response; } @@ -3647,11 +3499,11 @@ public class ApiResponseHelper implements ResponseGenerator { ApplicationLoadBalancerRuleResponse ruleResponse = new ApplicationLoadBalancerRuleResponse(); ruleResponse.setInstancePort(lb.getDefaultPortStart()); ruleResponse.setSourcePort(lb.getSourcePortStart()); - String stateToSet = lb.getState().toString(); + FirewallRule.State stateToSet = lb.getState(); if (stateToSet.equals(FirewallRule.State.Revoke)) { - stateToSet = "Deleting"; + stateToSet = FirewallRule.State.Deleting; } - ruleResponse.setState(stateToSet); + ruleResponse.setState(stateToSet.toString()); ruleResponse.setObjectName("loadbalancerrule"); ruleResponses.add(ruleResponse); lbResponse.setLbRules(ruleResponses); @@ -3736,7 +3588,7 @@ public class ApiResponseHelper implements ResponseGenerator { public PortableIpResponse createPortableIPResponse(PortableIp portableIp) { PortableIpResponse response = new PortableIpResponse(); response.setAddress(portableIp.getAddress()); - Long accountId = portableIp.getAllocatedInDomainId(); + Long accountId = portableIp.getAllocatedInDomainId(); if (accountId != null) { Account account = ApiDBUtils.findAccountById(accountId); response.setAllocatedToAccountId(account.getAccountName()); diff --git a/server/src/com/cloud/api/ApiSerializerHelper.java b/server/src/com/cloud/api/ApiSerializerHelper.java index cd5c7e65fdc..7426d9f1675 100644 --- a/server/src/com/cloud/api/ApiSerializerHelper.java +++ b/server/src/com/cloud/api/ApiSerializerHelper.java @@ -24,7 +24,7 @@ import org.apache.cloudstack.api.ResponseObject; public class ApiSerializerHelper { public static final Logger s_logger = Logger.getLogger(ApiSerializerHelper.class.getName()); - public static String token = "/"; + private static String token = "/"; public static String toSerializedString(Object result) { if (result != null) { diff --git a/server/src/com/cloud/api/ApiServer.java b/server/src/com/cloud/api/ApiServer.java index a75218026ee..d715db65c67 100755 --- a/server/src/com/cloud/api/ApiServer.java +++ b/server/src/com/cloud/api/ApiServer.java @@ -159,11 +159,10 @@ public class ApiServer extends ManagerBase implements HttpRequestHandler, ApiSer private static final Logger s_logger = Logger.getLogger(ApiServer.class.getName()); private static final Logger s_accessLogger = Logger.getLogger("apiserver." + ApiServer.class.getName()); - public static boolean encodeApiResponse = false; - public static String jsonContentType = "text/javascript"; - public static String controlCharacters = "[\000-\011\013-\014\016-\037\177]"; // Non-printable ASCII characters - numbers 0 to 31 and 127 decimal - @Inject - ApiDispatcher _dispatcher; + private static boolean encodeApiResponse = false; + private static String jsonContentType = "text/javascript"; + private static String controlCharacters = "[\000-\011\013-\014\016-\037\177]"; // Non-printable ASCII characters - numbers 0 to 31 and 127 decimal + @Inject ApiDispatcher _dispatcher; @Inject private AccountManager _accountMgr; @@ -181,11 +180,11 @@ public class ApiServer extends ManagerBase implements HttpRequestHandler, ApiSer @Inject protected ApiAsyncJobDispatcher _asyncDispatcher; - private static int _workerCount = 0; - private static final DateFormat _dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); - private static Map> _apiNameCmdClassMap = new HashMap>(); + private static int s_workerCount = 0; + private static final DateFormat DateFormatToUse = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); + private static Map> s_apiNameCmdClassMap = new HashMap>(); - private static ExecutorService _executor = new ThreadPoolExecutor(10, 150, 60, TimeUnit.SECONDS, new LinkedBlockingQueue(), new NamedThreadFactory( + private static ExecutorService s_executor = new ThreadPoolExecutor(10, 150, 60, TimeUnit.SECONDS, new LinkedBlockingQueue(), new NamedThreadFactory( "ApiServer")); public ApiServer() { @@ -234,14 +233,14 @@ public class ApiServer extends ManagerBase implements HttpRequestHandler, ApiSer throw new CloudRuntimeException(String.format("%s is claimed as a API command, but it doesn't have @APICommand annotation", cmdClass.getName())); } String apiName = at.name(); - if (_apiNameCmdClassMap.containsKey(apiName)) { + if (s_apiNameCmdClassMap.containsKey(apiName)) { s_logger.error("API Cmd class " + cmdClass.getName() + " has non-unique apiname" + apiName); continue; } - _apiNameCmdClassMap.put(apiName, cmdClass); + s_apiNameCmdClassMap.put(apiName, cmdClass); } - encodeApiResponse = Boolean.valueOf(_configDao.getValue(Config.EncodeApiResponse.key())); + setEncodeApiResponse(Boolean.valueOf(_configDao.getValue(Config.EncodeApiResponse.key()))); String jsonType = _configDao.getValue(Config.JavaScriptDefaultContentType.key()); if (jsonType != null) { jsonContentType = jsonType; @@ -379,7 +378,7 @@ public class ApiServer extends ManagerBase implements HttpRequestHandler, ApiSer buildAuditTrail(auditTrailSb, command[0], response); } else { if (!command[0].equalsIgnoreCase("login") && !command[0].equalsIgnoreCase("logout")) { - String errorString = "Unknown API command: " + ((command == null) ? "null" : command[0]); + String errorString = "Unknown API command: " + command[0]; s_logger.warn(errorString); auditTrailSb.append(" " + errorString); throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, errorString); @@ -630,7 +629,7 @@ public class ApiServer extends ManagerBase implements HttpRequestHandler, ApiSer return true; } else { // check against every available command to see if the command exists or not - if (!_apiNameCmdClassMap.containsKey(commandName) && !commandName.equals("login") && !commandName.equals("logout")) { + if (!s_apiNameCmdClassMap.containsKey(commandName) && !commandName.equals("login") && !commandName.equals("logout")) { s_logger.debug("The given command:" + commandName + " does not exist or it is not available for user with id:" + userId); throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, "The given command does not exist or it is not available for user"); } @@ -686,9 +685,9 @@ public class ApiServer extends ManagerBase implements HttpRequestHandler, ApiSer s_logger.debug("Missing Expires parameter -- ignoring request. Signature: " + signature + ", apiKey: " + apiKey); return false; } - synchronized (_dateFormat) { + synchronized (DateFormatToUse) { try { - expiresTS = _dateFormat.parse(expires); + expiresTS = DateFormatToUse.parse(expires); } catch (ParseException pe) { s_logger.debug("Incorrect date format for Expires parameter", pe); return false; @@ -722,10 +721,13 @@ public class ApiServer extends ManagerBase implements HttpRequestHandler, ApiSer try { checkCommandAvailable(user, commandName); + } catch (RequestLimitException ex) { + s_logger.debug(ex.getMessage()); + throw new ServerApiException(ApiErrorCode.API_LIMIT_EXCEED, ex.getMessage()); } catch (PermissionDeniedException ex) { s_logger.debug("The given command:" + commandName + " does not exist or it is not available for user"); - throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, "The given command:" + commandName + - " does not exist or it is not available for user with id:" + userId); + throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, "The given command:" + commandName + " does not exist or it is not available for user with id:" + + userId); } // verify secret key exists @@ -760,7 +762,11 @@ public class ApiServer extends ManagerBase implements HttpRequestHandler, ApiSer @Override public Long fetchDomainId(String domainUUID) { - return _domainMgr.getDomain(domainUUID).getId(); + Domain domain = _domainMgr.getDomain(domainUUID); + if (domain != null) + return domain.getId(); + else + return null; } @Override @@ -872,7 +878,7 @@ public class ApiServer extends ManagerBase implements HttpRequestHandler, ApiSer } private Class getCmdClass(String cmdName) { - return _apiNameCmdClassMap.get(cmdName); + return s_apiNameCmdClassMap.get(cmdName); } // FIXME: rather than isError, we might was to pass in the status code to give more flexibility @@ -957,7 +963,7 @@ public class ApiServer extends ManagerBase implements HttpRequestHandler, ApiSer conn.bind(socket, _params); // Execute a new worker task to handle the request - _executor.execute(new WorkerTask(_httpService, conn, _workerCount++)); + s_executor.execute(new WorkerTask(_httpService, conn, s_workerCount++)); } catch (InterruptedIOException ex) { break; } catch (IOException e) { @@ -1094,8 +1100,8 @@ public class ApiServer extends ManagerBase implements HttpRequestHandler, ApiSer } @Inject - public void setPluggableServices(List _pluggableServices) { - this._pluggableServices = _pluggableServices; + public void setPluggableServices(List pluggableServices) { + _pluggableServices = pluggableServices; } public List getApiAccessCheckers() { @@ -1103,7 +1109,19 @@ public class ApiServer extends ManagerBase implements HttpRequestHandler, ApiSer } @Inject - public void setApiAccessCheckers(List _apiAccessCheckers) { - this._apiAccessCheckers = _apiAccessCheckers; + public void setApiAccessCheckers(List apiAccessCheckers) { + _apiAccessCheckers = apiAccessCheckers; + } + + public static boolean isEncodeApiResponse() { + return encodeApiResponse; + } + + private static void setEncodeApiResponse(boolean encodeApiResponse) { + ApiServer.encodeApiResponse = encodeApiResponse; + } + + public static String getJsonContentType() { + return jsonContentType; } } diff --git a/server/src/com/cloud/api/ApiServlet.java b/server/src/com/cloud/api/ApiServlet.java index 6a33c14baaf..46f7eba8bee 100755 --- a/server/src/com/cloud/api/ApiServlet.java +++ b/server/src/com/cloud/api/ApiServlet.java @@ -375,7 +375,7 @@ public class ApiServlet extends HttpServlet { private void writeResponse(HttpServletResponse resp, String response, int responseCode, String responseType) { try { if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) { - resp.setContentType(ApiServer.jsonContentType + "; charset=UTF-8"); + resp.setContentType(ApiServer.getJsonContentType() + "; charset=UTF-8"); } else { resp.setContentType("text/xml; charset=UTF-8"); } diff --git a/server/src/com/cloud/api/EncodedStringTypeAdapter.java b/server/src/com/cloud/api/EncodedStringTypeAdapter.java index cde144830aa..50dbd0d48cd 100644 --- a/server/src/com/cloud/api/EncodedStringTypeAdapter.java +++ b/server/src/com/cloud/api/EncodedStringTypeAdapter.java @@ -37,7 +37,7 @@ public class EncodedStringTypeAdapter implements JsonSerializer { } private static String encodeString(String value) { - if (!ApiServer.encodeApiResponse) { + if (!ApiServer.isEncodeApiResponse()) { return value; } try { diff --git a/server/src/com/cloud/api/doc/Alert.java b/server/src/com/cloud/api/doc/Alert.java index e73cb0e5351..3e61d0ba268 100644 --- a/server/src/com/cloud/api/doc/Alert.java +++ b/server/src/com/cloud/api/doc/Alert.java @@ -16,9 +16,15 @@ // under the License. package com.cloud.api.doc; -public class Alert { - private String type; - private int value; +import java.io.Serializable; + +public class Alert implements Serializable{ + /** + * + */ + private static final long serialVersionUID = 960408026527837920L; + private final String type; + private final int value; public Alert(String type, int value) { this.type = type; diff --git a/server/src/com/cloud/api/doc/ApiXmlDocWriter.java b/server/src/com/cloud/api/doc/ApiXmlDocWriter.java index d3a8ade7176..c19f7af8c35 100644 --- a/server/src/com/cloud/api/doc/ApiXmlDocWriter.java +++ b/server/src/com/cloud/api/doc/ApiXmlDocWriter.java @@ -41,6 +41,11 @@ import java.util.TreeMap; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; +import org.apache.log4j.Logger; + +import com.google.gson.annotations.SerializedName; +import com.thoughtworks.xstream.XStream; + import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseAsyncCreateCmd; @@ -56,29 +61,26 @@ import org.apache.cloudstack.api.response.StoragePoolResponse; import org.apache.cloudstack.api.response.TemplateResponse; import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.cloudstack.api.response.VolumeResponse; -import org.apache.log4j.Logger; import com.cloud.alert.AlertManager; import com.cloud.serializer.Param; import com.cloud.utils.IteratorUtil; import com.cloud.utils.ReflectUtil; -import com.google.gson.annotations.SerializedName; -import com.thoughtworks.xstream.XStream; public class ApiXmlDocWriter { public static final Logger s_logger = Logger.getLogger(ApiXmlDocWriter.class.getName()); private static final short DOMAIN_ADMIN_COMMAND = 4; private static final short USER_COMMAND = 8; - private static Map> _apiNameCmdClassMap = new HashMap>(); - private static LinkedHashMap all_api_commands = new LinkedHashMap(); - private static LinkedHashMap domain_admin_api_commands = new LinkedHashMap(); - private static LinkedHashMap regular_user_api_commands = new LinkedHashMap(); - private static TreeMap all_api_commands_sorted = new TreeMap(); - private static TreeMap domain_admin_api_commands_sorted = new TreeMap(); - private static TreeMap regular_user_api_commands_sorted = new TreeMap(); - private static String dirName = ""; - private static final List _asyncResponses = setAsyncResponses(); + private static Map> s_apiNameCmdClassMap = new HashMap>(); + private static LinkedHashMap s_allApiCommands = new LinkedHashMap(); + private static LinkedHashMap s_domainAdminApiCommands = new LinkedHashMap(); + private static LinkedHashMap s_regularUserApiCommands = new LinkedHashMap(); + private static TreeMap s_allApiCommandsSorted = new TreeMap(); + private static TreeMap s_domainAdminApiCommandsSorted = new TreeMap(); + private static TreeMap s_regularUserApiCommandsSorted = new TreeMap(); + private static String s_dirName = ""; + private static final List AsyncResponses = setAsyncResponses(); private static List setAsyncResponses() { List asyncResponses = new ArrayList(); @@ -102,11 +104,11 @@ public class ApiXmlDocWriter { for (Class cmdClass : cmdClasses) { String apiName = cmdClass.getAnnotation(APICommand.class).name(); - if (_apiNameCmdClassMap.containsKey(apiName)) { + if (s_apiNameCmdClassMap.containsKey(apiName)) { System.out.println("Warning, API Cmd class " + cmdClass.getName() + " has non-unique apiname" + apiName); continue; } - _apiNameCmdClassMap.put(apiName, cmdClass); + s_apiNameCmdClassMap.put(apiName, cmdClass); } LinkedProperties preProcessedCommands = new LinkedProperties(); @@ -121,7 +123,7 @@ public class ApiXmlDocWriter { fileNames = iter.next().split(","); } if (arg.equals("-d")) { - dirName = iter.next(); + s_dirName = iter.next(); } } @@ -151,13 +153,13 @@ public class ApiXmlDocWriter { String preProcessedCommand = preProcessedCommands.getProperty(key); int splitIndex = preProcessedCommand.lastIndexOf(";"); String commandRoleMask = preProcessedCommand.substring(splitIndex + 1); - Class cmdClass = _apiNameCmdClassMap.get(key); + Class cmdClass = s_apiNameCmdClassMap.get(key); if (cmdClass == null) { System.out.println("Check, is this api part of another build profile? Null value for key: " + key + " preProcessedCommand=" + preProcessedCommand); continue; } String commandName = cmdClass.getName(); - all_api_commands.put(key, commandName); + s_allApiCommands.put(key, commandName); short cmdPermissions = 1; if (commandRoleMask != null) { @@ -165,32 +167,32 @@ public class ApiXmlDocWriter { } if ((cmdPermissions & DOMAIN_ADMIN_COMMAND) != 0) { - domain_admin_api_commands.put(key, commandName); + s_domainAdminApiCommands.put(key, commandName); } if ((cmdPermissions & USER_COMMAND) != 0) { - regular_user_api_commands.put(key, commandName); + s_regularUserApiCommands.put(key, commandName); } } // Login and logout commands are hardcoded - all_api_commands.put("login", "login"); - domain_admin_api_commands.put("login", "login"); - regular_user_api_commands.put("login", "login"); + s_allApiCommands.put("login", "login"); + s_domainAdminApiCommands.put("login", "login"); + s_regularUserApiCommands.put("login", "login"); - all_api_commands.put("logout", "logout"); - domain_admin_api_commands.put("logout", "logout"); - regular_user_api_commands.put("logout", "logout"); + s_allApiCommands.put("logout", "logout"); + s_domainAdminApiCommands.put("logout", "logout"); + s_regularUserApiCommands.put("logout", "logout"); - all_api_commands_sorted.putAll(all_api_commands); - domain_admin_api_commands_sorted.putAll(domain_admin_api_commands); - regular_user_api_commands_sorted.putAll(regular_user_api_commands); + s_allApiCommandsSorted.putAll(s_allApiCommands); + s_domainAdminApiCommandsSorted.putAll(s_domainAdminApiCommands); + s_regularUserApiCommandsSorted.putAll(s_regularUserApiCommands); try { // Create object writer XStream xs = new XStream(); xs.alias("command", Command.class); xs.alias("arg", Argument.class); - String xmlDocDir = dirName + "/xmldoc"; + String xmlDocDir = s_dirName + "/xmldoc"; String rootAdminDirName = xmlDocDir + "/root_admin"; String domainAdminDirName = xmlDocDir + "/domain_admin"; String regularUserDirName = xmlDocDir + "/regular_user"; @@ -198,7 +200,7 @@ public class ApiXmlDocWriter { (new File(domainAdminDirName)).mkdirs(); (new File(regularUserDirName)).mkdirs(); - ObjectOutputStream out = xs.createObjectOutputStream(new FileWriter(dirName + "/commands.xml"), "commands"); + ObjectOutputStream out = xs.createObjectOutputStream(new FileWriter(s_dirName + "/commands.xml"), "commands"); ObjectOutputStream rootAdmin = xs.createObjectOutputStream(new FileWriter(rootAdminDirName + "/" + "rootAdminSummary.xml"), "commands"); ObjectOutputStream rootAdminSorted = xs.createObjectOutputStream(new FileWriter(rootAdminDirName + "/" + "rootAdminSummarySorted.xml"), "commands"); ObjectOutputStream domainAdmin = xs.createObjectOutputStream(new FileWriter(domainAdminDirName + "/" + "domainAdminSummary.xml"), "commands"); @@ -207,7 +209,7 @@ public class ApiXmlDocWriter { ObjectOutputStream regularUserSorted = xs.createObjectOutputStream(new FileWriter(regularUserDirName + "/regularUserSummarySorted.xml"), "commands"); // Write commands in the order they are represented in commands.properties.in file - Iterator it = all_api_commands.keySet().iterator(); + Iterator it = s_allApiCommands.keySet().iterator(); while (it.hasNext()) { String key = (String)it.next(); @@ -259,14 +261,14 @@ public class ApiXmlDocWriter { singleRootAdminCommandOs.close(); } - if (domain_admin_api_commands.containsKey(key)) { + if (s_domainAdminApiCommands.containsKey(key)) { writeCommand(domainAdmin, key); ObjectOutputStream singleDomainAdminCommandOs = xs.createObjectOutputStream(new FileWriter(domainAdminDirName + "/" + key + ".xml"), "command"); writeCommand(singleDomainAdminCommandOs, key); singleDomainAdminCommandOs.close(); } - if (regular_user_api_commands.containsKey(key)) { + if (s_regularUserApiCommands.containsKey(key)) { writeCommand(regularUser, key); ObjectOutputStream singleRegularUserCommandOs = xs.createObjectOutputStream(new FileWriter(regularUserDirName + "/" + key + ".xml"), "command"); writeCommand(singleRegularUserCommandOs, key); @@ -276,7 +278,7 @@ public class ApiXmlDocWriter { } // Write sorted commands - it = all_api_commands_sorted.keySet().iterator(); + it = s_allApiCommandsSorted.keySet().iterator(); while (it.hasNext()) { String key = (String)it.next(); @@ -291,11 +293,11 @@ public class ApiXmlDocWriter { } else { writeCommand(rootAdminSorted, key); - if (domain_admin_api_commands.containsKey(key)) { + if (s_domainAdminApiCommands.containsKey(key)) { writeCommand(outDomainAdminSorted, key); } - if (regular_user_api_commands.containsKey(key)) { + if (s_regularUserApiCommands.containsKey(key)) { writeCommand(regularUserSorted, key); } } @@ -325,7 +327,7 @@ public class ApiXmlDocWriter { } private static void writeCommand(ObjectOutputStream out, String command) throws ClassNotFoundException, IOException { - Class clas = Class.forName(all_api_commands.get(command)); + Class clas = Class.forName(s_allApiCommands.get(command)); ArrayList request = new ArrayList(); ArrayList response = new ArrayList(); @@ -394,13 +396,13 @@ public class ApiXmlDocWriter { // Generate request request.add(new Argument("username", "Username", true)); request.add(new Argument( - "password", - "Hashed password (Default is MD5). If you wish to use any other hashing algorithm, you would need to write a custom authentication adapter See Docs section.", - true)); + "password", + "Hashed password (Default is MD5). If you wish to use any other hashing algorithm, you would need to write a custom authentication adapter See Docs section.", + true)); request.add(new Argument("domain", - "path of the domain that the user belongs to. Example: domain=/com/cloud/internal. If no domain is passed in, the ROOT domain is assumed.", false)); + "path of the domain that the user belongs to. Example: domain=/com/cloud/internal. If no domain is passed in, the ROOT domain is assumed.", false)); request.add(new Argument("domainId", - "id of the domain that the user belongs to. If both domain and domainId are passed in, \"domainId\" parameter takes precendence", false)); + "id of the domain that the user belongs to. If both domain and domainId are passed in, \"domainId\" parameter takes precendence", false)); apiCommand.setRequest(request); // Generate response @@ -551,7 +553,7 @@ public class ApiXmlDocWriter { if (responseClas.getName().equalsIgnoreCase(AsyncJobResponse.class.getName())) { Argument jobIdArg = new Argument("jobid", "the ID of the async job"); arguments.add(jobIdArg); - } else if (_asyncResponses.contains(responseClas.getName())) { + } else if (AsyncResponses.contains(responseClas.getName())) { Argument jobIdArg = new Argument("jobid", "the ID of the latest async job acting on this object"); Argument jobStatusArg = new Argument("jobstatus", "the current status of the latest async job acting on this object"); arguments.add(jobIdArg); @@ -571,7 +573,7 @@ public class ApiXmlDocWriter { static void addDir(File dirObj, ZipOutputStream out) throws IOException { File[] files = dirObj.listFiles(); byte[] tmpBuf = new byte[1024]; - String pathToDir = dirName; + String pathToDir = s_dirName; for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { diff --git a/server/src/com/cloud/api/doc/Command.java b/server/src/com/cloud/api/doc/Command.java index 998b39fefab..549ca291ffe 100644 --- a/server/src/com/cloud/api/doc/Command.java +++ b/server/src/com/cloud/api/doc/Command.java @@ -16,10 +16,15 @@ // under the License. package com.cloud.api.doc; +import java.io.Serializable; import java.util.ArrayList; -public class Command { +public class Command implements Serializable{ + /** + * + */ + private static final long serialVersionUID = -4318310162503004975L; private String name; private String description; private String usage; @@ -85,7 +90,7 @@ public class Command { } public Argument getReqArgByName(String name) { - for (Argument a : this.getRequest()) { + for (Argument a : getRequest()) { if (a.getName().equals(name)) { return a; } @@ -94,7 +99,7 @@ public class Command { } public Argument getResArgByName(String name) { - for (Argument a : this.getResponse()) { + for (Argument a : getResponse()) { if (a.getName().equals(name)) { return a; } diff --git a/server/src/com/cloud/api/query/QueryManagerImpl.java b/server/src/com/cloud/api/query/QueryManagerImpl.java index 91222760dc1..27a05290807 100644 --- a/server/src/com/cloud/api/query/QueryManagerImpl.java +++ b/server/src/com/cloud/api/query/QueryManagerImpl.java @@ -26,9 +26,6 @@ import java.util.Set; import javax.ejb.Local; import javax.inject.Inject; -import org.apache.log4j.Logger; -import org.springframework.stereotype.Component; - import org.apache.cloudstack.acl.ControlledEntity.ACLType; import org.apache.cloudstack.affinity.AffinityGroupDomainMapVO; import org.apache.cloudstack.affinity.AffinityGroupResponse; @@ -90,6 +87,8 @@ import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; import org.apache.cloudstack.engine.subsystem.api.storage.TemplateState; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.query.QueryService; +import org.apache.log4j.Logger; +import org.springframework.stereotype.Component; import com.cloud.api.query.dao.AccountJoinDao; import com.cloud.api.query.dao.AffinityGroupJoinDao; @@ -175,6 +174,7 @@ import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.dao.VolumeDetailsDao; import com.cloud.tags.ResourceTagVO; import com.cloud.tags.dao.ResourceTagDao; +import com.cloud.template.VirtualMachineTemplate.State; import com.cloud.template.VirtualMachineTemplate.TemplateFilter; import com.cloud.user.Account; import com.cloud.user.AccountManager; @@ -424,8 +424,7 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { ssc.addOr("email", SearchCriteria.Op.LIKE, "%" + keyword + "%"); ssc.addOr("state", SearchCriteria.Op.LIKE, "%" + keyword + "%"); ssc.addOr("accountName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("type", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("accountState", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("accountType", SearchCriteria.Op.LIKE, "%" + keyword + "%"); sc.addAnd("username", SearchCriteria.Op.SC, ssc); } @@ -2084,7 +2083,7 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { if (keyword != null) { SearchCriteria ssc = _imageStoreJoinDao.createSearchCriteria(); ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("provider", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("providerName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); sc.addAnd("name", SearchCriteria.Op.SC, ssc); } @@ -2717,6 +2716,7 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { TemplateFilter templateFilter = TemplateFilter.valueOf(cmd.getTemplateFilter()); Long id = cmd.getId(); Map tags = cmd.getTags(); + boolean showRemovedTmpl = cmd.getShowRemoved(); Account caller = CallContext.current().getCallingAccount(); boolean listAll = false; @@ -2741,12 +2741,12 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { HypervisorType hypervisorType = HypervisorType.getType(cmd.getHypervisor()); return searchForTemplatesInternal(id, cmd.getTemplateName(), cmd.getKeyword(), templateFilter, false, null, cmd.getPageSizeVal(), cmd.getStartIndex(), - cmd.getZoneId(), hypervisorType, showDomr, cmd.listInReadyState(), permittedAccounts, caller, listProjectResourcesCriteria, tags); + cmd.getZoneId(), hypervisorType, showDomr, cmd.listInReadyState(), permittedAccounts, caller, listProjectResourcesCriteria, tags, showRemovedTmpl); } private Pair, Integer> searchForTemplatesInternal(Long templateId, String name, String keyword, TemplateFilter templateFilter, boolean isIso, Boolean bootable, Long pageSize, Long startIndex, Long zoneId, HypervisorType hyperType, boolean showDomr, boolean onlyReady, List permittedAccounts, - Account caller, ListProjectResourcesCriteria listProjectResourcesCriteria, Map tags) { + Account caller, ListProjectResourcesCriteria listProjectResourcesCriteria, Map tags, boolean showRemovedTmpl) { // check if zone is configured, if not, just return empty list List hypers = null; @@ -2827,10 +2827,17 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { if (!permittedAccounts.isEmpty()) { for (Account account : permittedAccounts) { permittedAccountIds.add(account.getId()); - DomainVO accountDomain = _domainDao.findById(account.getDomainId()); + boolean publicTemplates = (templateFilter == TemplateFilter.featured || templateFilter == TemplateFilter.community); // get all parent domain ID's all the way till root domain - DomainVO domainTreeNode = accountDomain; + DomainVO domainTreeNode = null; + //if template filter is featured, or community, all child domains should be included in search + if (publicTemplates) { + domainTreeNode = _domainDao.findById(Domain.ROOT_DOMAIN); + + } else { + domainTreeNode = _domainDao.findById(account.getDomainId()); + } relatedDomainIds.add(domainTreeNode.getId()); while (domainTreeNode.getParent() != null) { domainTreeNode = _domainDao.findById(domainTreeNode.getParent()); @@ -2838,8 +2845,8 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { } // get all child domain ID's - if (_accountMgr.isAdmin(account.getType()) || (templateFilter == TemplateFilter.featured || templateFilter == TemplateFilter.community)) { - List allChildDomains = _domainDao.findAllChildren(accountDomain.getPath(), accountDomain.getId()); + if (_accountMgr.isAdmin(account.getType()) || publicTemplates) { + List allChildDomains = _domainDao.findAllChildren(domainTreeNode.getPath(), domainTreeNode.getId()); for (DomainVO childDomain : allChildDomains) { relatedDomainIds.add(childDomain.getId()); } @@ -2965,7 +2972,14 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { // sc.addAnd("removed", SearchCriteria.Op.NULL); // search unique templates and find details by Ids - Pair, Integer> uniqueTmplPair = _templateJoinDao.searchAndCount(sc, searchFilter); + Pair, Integer> uniqueTmplPair = null; + if(showRemovedTmpl){ + uniqueTmplPair = _templateJoinDao.searchIncludingRemovedAndCount(sc, searchFilter); + } else { + sc.addAnd("templateState", SearchCriteria.Op.EQ, State.Active); + uniqueTmplPair = _templateJoinDao.searchAndCount(sc, searchFilter); + } + Integer count = uniqueTmplPair.second(); if (count.intValue() == 0) { // empty result @@ -2977,7 +2991,7 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { for (TemplateJoinVO v : uniqueTmpls) { tzIds[i++] = v.getTempZonePair(); } - List vrs = _templateJoinDao.searchByTemplateZonePair(tzIds); + List vrs = _templateJoinDao.searchByTemplateZonePair(showRemovedTmpl, tzIds); return new Pair, Integer>(vrs, count); // TODO: revisit the special logic for iso search in @@ -3001,6 +3015,7 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { TemplateFilter isoFilter = TemplateFilter.valueOf(cmd.getIsoFilter()); Long id = cmd.getId(); Map tags = cmd.getTags(); + boolean showRemovedISO = cmd.getShowRemoved(); Account caller = CallContext.current().getCallingAccount(); boolean listAll = false; @@ -3024,22 +3039,25 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { HypervisorType hypervisorType = HypervisorType.getType(cmd.getHypervisor()); return searchForTemplatesInternal(cmd.getId(), cmd.getIsoName(), cmd.getKeyword(), isoFilter, true, cmd.isBootable(), cmd.getPageSizeVal(), cmd.getStartIndex(), - cmd.getZoneId(), hypervisorType, true, cmd.listInReadyState(), permittedAccounts, caller, listProjectResourcesCriteria, tags); + cmd.getZoneId(), hypervisorType, true, cmd.listInReadyState(), permittedAccounts, caller, listProjectResourcesCriteria, tags, showRemovedISO); } @Override - public ListResponse listAffinityGroups(Long affinityGroupId, String affinityGroupName, String affinityGroupType, Long vmId, - String accountName, Long domainId, boolean isRecursive, boolean listAll, Long startIndex, Long pageSize) { - Pair, Integer> result = - listAffinityGroupsInternal(affinityGroupId, affinityGroupName, affinityGroupType, vmId, accountName, domainId, isRecursive, listAll, startIndex, pageSize); + public ListResponse listAffinityGroups(Long affinityGroupId, String affinityGroupName, + String affinityGroupType, Long vmId, String accountName, Long domainId, boolean isRecursive, + boolean listAll, Long startIndex, Long pageSize, String keyword) { + Pair, Integer> result = listAffinityGroupsInternal(affinityGroupId, + affinityGroupName, affinityGroupType, vmId, accountName, domainId, isRecursive, listAll, startIndex, + pageSize, keyword); ListResponse response = new ListResponse(); List agResponses = ViewResponseHelper.createAffinityGroupResponses(result.first()); response.setResponses(agResponses, result.second()); return response; } - public Pair, Integer> listAffinityGroupsInternal(Long affinityGroupId, String affinityGroupName, String affinityGroupType, Long vmId, - String accountName, Long domainId, boolean isRecursive, boolean listAll, Long startIndex, Long pageSize) { + public Pair, Integer> listAffinityGroupsInternal(Long affinityGroupId, + String affinityGroupName, String affinityGroupType, Long vmId, String accountName, Long domainId, + boolean isRecursive, boolean listAll, Long startIndex, Long pageSize, String keyword) { Account caller = CallContext.current().getCallingAccount(); @@ -3063,9 +3081,8 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); Filter searchFilter = new Filter(AffinityGroupJoinVO.class, "id", true, startIndex, pageSize); - SearchCriteria sc = - buildAffinityGroupSearchCriteria(domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria, affinityGroupId, affinityGroupName, - affinityGroupType); + SearchCriteria sc = buildAffinityGroupSearchCriteria(domainId, isRecursive, + permittedAccounts, listProjectResourcesCriteria, affinityGroupId, affinityGroupName, affinityGroupType, keyword); Pair, Integer> uniqueGroupsPair = _affinityGroupJoinDao.searchAndCount(sc, searchFilter); // search group details by ids @@ -3084,26 +3101,26 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { if (!permittedAccounts.isEmpty()) { // add domain level affinity groups if (domainId != null) { - SearchCriteria scDomain = - buildAffinityGroupSearchCriteria(null, isRecursive, new ArrayList(), listProjectResourcesCriteria, affinityGroupId, affinityGroupName, - affinityGroupType); + SearchCriteria scDomain = buildAffinityGroupSearchCriteria(null, isRecursive, + new ArrayList(), listProjectResourcesCriteria, affinityGroupId, affinityGroupName, + affinityGroupType, keyword); vrs.addAll(listDomainLevelAffinityGroups(scDomain, searchFilter, domainId)); } else { for (Long permAcctId : permittedAccounts) { Account permittedAcct = _accountDao.findById(permAcctId); - SearchCriteria scDomain = - buildAffinityGroupSearchCriteria(null, isRecursive, new ArrayList(), listProjectResourcesCriteria, affinityGroupId, affinityGroupName, - affinityGroupType); + SearchCriteria scDomain = buildAffinityGroupSearchCriteria( + null, isRecursive, new ArrayList(), + listProjectResourcesCriteria, affinityGroupId, affinityGroupName, affinityGroupType, keyword); vrs.addAll(listDomainLevelAffinityGroups(scDomain, searchFilter, permittedAcct.getDomainId())); } } } else if (((permittedAccounts.isEmpty()) && (domainId != null) && isRecursive)) { // list all domain level affinity groups for the domain admin case - SearchCriteria scDomain = - buildAffinityGroupSearchCriteria(null, isRecursive, new ArrayList(), listProjectResourcesCriteria, affinityGroupId, affinityGroupName, - affinityGroupType); + SearchCriteria scDomain = buildAffinityGroupSearchCriteria(null, isRecursive, + new ArrayList(), listProjectResourcesCriteria, affinityGroupId, affinityGroupName, + affinityGroupType, keyword); vrs.addAll(listDomainLevelAffinityGroups(scDomain, searchFilter, domainId)); } @@ -3111,8 +3128,9 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { } - private SearchCriteria buildAffinityGroupSearchCriteria(Long domainId, boolean isRecursive, List permittedAccounts, - ListProjectResourcesCriteria listProjectResourcesCriteria, Long affinityGroupId, String affinityGroupName, String affinityGroupType) { + private SearchCriteria buildAffinityGroupSearchCriteria(Long domainId, boolean isRecursive, + List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria, + Long affinityGroupId, String affinityGroupName, String affinityGroupType, String keyword) { SearchBuilder groupSearch = _affinityGroupJoinDao.createSearchBuilder(); _accountMgr.buildACLViewSearchBuilder(groupSearch, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); @@ -3135,6 +3153,14 @@ public class QueryManagerImpl extends ManagerBase implements QueryService { sc.addAnd("type", SearchCriteria.Op.EQ, affinityGroupType); } + if (keyword != null) { + SearchCriteria ssc = _affinityGroupJoinDao.createSearchCriteria(); + ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("type", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + + sc.addAnd("name", SearchCriteria.Op.SC, ssc); + } + return sc; } diff --git a/server/src/com/cloud/api/query/ViewResponseHelper.java b/server/src/com/cloud/api/query/ViewResponseHelper.java index 5a953dea25b..149b0d906f0 100644 --- a/server/src/com/cloud/api/query/ViewResponseHelper.java +++ b/server/src/com/cloud/api/query/ViewResponseHelper.java @@ -19,6 +19,7 @@ package com.cloud.api.query; import java.util.ArrayList; import java.util.EnumSet; import java.util.Hashtable; +import java.util.LinkedHashMap; import java.util.List; import org.apache.log4j.Logger; @@ -360,7 +361,7 @@ public class ViewResponseHelper { } public static List createTemplateResponse(TemplateJoinVO... templates) { - Hashtable vrDataList = new Hashtable(); + LinkedHashMap vrDataList = new LinkedHashMap(); for (TemplateJoinVO vr : templates) { TemplateResponse vrData = vrDataList.get(vr.getTempZonePair()); if (vrData == null) { diff --git a/server/src/com/cloud/api/query/dao/DiskOfferingJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/DiskOfferingJoinDaoImpl.java index b61822d9ea2..d15371215c5 100644 --- a/server/src/com/cloud/api/query/dao/DiskOfferingJoinDaoImpl.java +++ b/server/src/com/cloud/api/query/dao/DiskOfferingJoinDaoImpl.java @@ -41,7 +41,7 @@ public class DiskOfferingJoinDaoImpl extends GenericDaoBase dofIdSearch; private final Attribute _typeAttr; - protected DiskOfferingJoinDaoImpl() { + protected DiskOfferingJoinDaoImpl() { dofIdSearch = createSearchBuilder(); dofIdSearch.and("id", dofIdSearch.entity().getId(), SearchCriteria.Op.EQ); diff --git a/server/src/com/cloud/api/query/dao/DomainRouterJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/DomainRouterJoinDaoImpl.java index c1fd4d8e1d9..f8838d84c35 100644 --- a/server/src/com/cloud/api/query/dao/DomainRouterJoinDaoImpl.java +++ b/server/src/com/cloud/api/query/dao/DomainRouterJoinDaoImpl.java @@ -80,7 +80,10 @@ public class DomainRouterJoinDaoImpl extends GenericDaoBase 0) { - ImageStoreDetailResponse osdResponse = new ImageStoreDetailResponse(detailName, ids.getDetailValue()); + if ( detailName != null && detailName.length() > 0 ){ + String detailValue = ids.getDetailValue(); + if (detailName.equals(ApiConstants.KEY) || detailName.equals(ApiConstants.S3_SECRET_KEY)) { + detailValue = DBEncryptionUtil.decrypt(detailValue); + } + ImageStoreDetailResponse osdResponse = new ImageStoreDetailResponse(detailName, detailValue); osResponse.addDetail(osdResponse); } osResponse.setObjectName("imagestore"); @@ -84,8 +96,12 @@ public class ImageStoreJoinDaoImpl extends GenericDaoBase 0) { - ImageStoreDetailResponse osdResponse = new ImageStoreDetailResponse(detailName, ids.getDetailValue()); + if ( detailName != null && detailName.length() > 0 ){ + String detailValue = ids.getDetailValue(); + if (detailName.equals(ApiConstants.KEY) || detailName.equals(ApiConstants.S3_SECRET_KEY)) { + detailValue = DBEncryptionUtil.decrypt(detailValue); + } + ImageStoreDetailResponse osdResponse = new ImageStoreDetailResponse(detailName, detailValue); response.addDetail(osdResponse); } return response; diff --git a/server/src/com/cloud/api/query/dao/StoragePoolJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/StoragePoolJoinDaoImpl.java index 0a5fb5eb66e..274bf1c24b8 100644 --- a/server/src/com/cloud/api/query/dao/StoragePoolJoinDaoImpl.java +++ b/server/src/com/cloud/api/query/dao/StoragePoolJoinDaoImpl.java @@ -34,6 +34,7 @@ import com.cloud.capacity.Capacity; import com.cloud.storage.ScopeType; import com.cloud.storage.StoragePool; import com.cloud.storage.StorageStats; +import com.cloud.utils.StringUtils; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; @@ -60,7 +61,7 @@ public class StoragePoolJoinDaoImpl extends GenericDaoBase { List newTemplateView(VirtualMachineTemplate tmpl, long zoneId, boolean readyOnly); - List searchByTemplateZonePair(String... pairs); + List searchByTemplateZonePair( Boolean showRemoved, String... pairs); List listActiveTemplates(long storeId); + Pair, Integer> searchIncludingRemovedAndCount(final SearchCriteria sc, final Filter filter); + } diff --git a/server/src/com/cloud/api/query/dao/TemplateJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/TemplateJoinDaoImpl.java index 792ac0998d7..fedc13d055a 100644 --- a/server/src/com/cloud/api/query/dao/TemplateJoinDaoImpl.java +++ b/server/src/com/cloud/api/query/dao/TemplateJoinDaoImpl.java @@ -44,10 +44,13 @@ import com.cloud.storage.VMTemplateHostVO; import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; +import com.cloud.utils.Pair; +import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; + @Component @Local(value = {TemplateJoinDao.class}) public class TemplateJoinDaoImpl extends GenericDaoBase implements TemplateJoinDao { @@ -68,6 +71,7 @@ public class TemplateJoinDaoImpl extends GenericDaoBase im protected TemplateJoinDaoImpl() { tmpltIdPairSearch = createSearchBuilder(); + tmpltIdPairSearch.and("templateState", tmpltIdPairSearch.entity().getTemplateState(), SearchCriteria.Op.EQ); tmpltIdPairSearch.and("tempZonePairIN", tmpltIdPairSearch.entity().getTempZonePair(), SearchCriteria.Op.IN); tmpltIdPairSearch.done(); @@ -84,10 +88,11 @@ public class TemplateJoinDaoImpl extends GenericDaoBase im activeTmpltSearch = createSearchBuilder(); activeTmpltSearch.and("store_id", activeTmpltSearch.entity().getDataStoreId(), SearchCriteria.Op.EQ); activeTmpltSearch.and("type", activeTmpltSearch.entity().getTemplateType(), SearchCriteria.Op.EQ); + activeTmpltSearch.and("templateState", activeTmpltSearch.entity().getTemplateState(), SearchCriteria.Op.EQ); activeTmpltSearch.done(); // select distinct pair (template_id, zone_id) - this._count = "select count(distinct temp_zone_pair) from template_view WHERE "; + _count = "select count(distinct temp_zone_pair) from template_view WHERE "; } private String getTemplateStatus(TemplateJoinVO template) { @@ -371,7 +376,7 @@ public class TemplateJoinDaoImpl extends GenericDaoBase im } @Override - public List searchByTemplateZonePair(String... idPairs) { + public List searchByTemplateZonePair(Boolean showRemoved, String... idPairs) { // set detail batch query size int DETAILS_BATCH_SIZE = 2000; String batchCfg = _configDao.getValue("detail.batch.query.size"); @@ -379,6 +384,9 @@ public class TemplateJoinDaoImpl extends GenericDaoBase im DETAILS_BATCH_SIZE = Integer.parseInt(batchCfg); } // query details by batches + Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm")); + isAscending = (isAscending == null ? true : isAscending); + Filter searchFilter = new Filter(TemplateJoinVO.class, "sortKey", isAscending, null, null); List uvList = new ArrayList(); // query details by batches int curr_index = 0; @@ -389,8 +397,11 @@ public class TemplateJoinDaoImpl extends GenericDaoBase im labels[k] = idPairs[j]; } SearchCriteria sc = tmpltIdPairSearch.create(); + if (!showRemoved) { + sc.setParameters("templateState", VirtualMachineTemplate.State.Active); + } sc.setParameters("tempZonePairIN", labels); - List vms = searchIncludingRemoved(sc, null, null, false); + List vms = searchIncludingRemoved(sc, searchFilter, null, false); if (vms != null) { uvList.addAll(vms); } @@ -404,8 +415,11 @@ public class TemplateJoinDaoImpl extends GenericDaoBase im labels[k] = idPairs[j]; } SearchCriteria sc = tmpltIdPairSearch.create(); + if (!showRemoved) { + sc.setParameters("templateState", VirtualMachineTemplate.State.Active); + } sc.setParameters("tempZonePairIN", labels); - List vms = searchIncludingRemoved(sc, null, null, false); + List vms = searchIncludingRemoved(sc, searchFilter, null, false); if (vms != null) { uvList.addAll(vms); } @@ -418,7 +432,15 @@ public class TemplateJoinDaoImpl extends GenericDaoBase im SearchCriteria sc = activeTmpltSearch.create(); sc.setParameters("store_id", storeId); sc.setParameters("type", TemplateType.USER); + sc.setParameters("templateState", VirtualMachineTemplate.State.Active); return searchIncludingRemoved(sc, null, null, false); } + @Override + public Pair, Integer> searchIncludingRemovedAndCount(final SearchCriteria sc, final Filter filter) { + List objects = searchIncludingRemoved(sc, filter, null, false); + Integer count = getCount(sc); + return new Pair, Integer>(objects, count); + } + } diff --git a/server/src/com/cloud/api/query/dao/UserAccountJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/UserAccountJoinDaoImpl.java index 42a1b0f1c4a..923a2382fdd 100644 --- a/server/src/com/cloud/api/query/dao/UserAccountJoinDaoImpl.java +++ b/server/src/com/cloud/api/query/dao/UserAccountJoinDaoImpl.java @@ -107,7 +107,7 @@ public class UserAccountJoinDaoImpl extends GenericDaoBase searchByAccountId(Long accountId) { SearchCriteria sc = vrAcctIdSearch.create(); sc.setParameters("accountId", accountId); - return searchIncludingRemoved(sc, null, null, false); + return search(sc, null, null, false); } } diff --git a/server/src/com/cloud/api/query/dao/UserVmJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/UserVmJoinDaoImpl.java index 3e218ecad48..08478e2958b 100644 --- a/server/src/com/cloud/api/query/dao/UserVmJoinDaoImpl.java +++ b/server/src/com/cloud/api/query/dao/UserVmJoinDaoImpl.java @@ -28,15 +28,14 @@ import java.util.Set; import javax.ejb.Local; import javax.inject.Inject; -import org.apache.log4j.Logger; -import org.springframework.stereotype.Component; - import org.apache.cloudstack.affinity.AffinityGroupResponse; import org.apache.cloudstack.api.ApiConstants.VMDetails; import org.apache.cloudstack.api.response.NicResponse; import org.apache.cloudstack.api.response.SecurityGroupResponse; import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; +import org.apache.log4j.Logger; +import org.springframework.stereotype.Component; import com.cloud.api.ApiDBUtils; import com.cloud.api.query.vo.ResourceTagJoinVO; @@ -47,9 +46,11 @@ import com.cloud.uservm.UserVm; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; +import com.cloud.vm.UserVmDetailVO; import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.VmDetailConstants; import com.cloud.vm.VmStats; +import com.cloud.vm.dao.UserVmDetailsDao; @Component @Local(value = {UserVmJoinDao.class}) @@ -58,6 +59,8 @@ public class UserVmJoinDaoImpl extends GenericDaoBase implem @Inject private ConfigurationDao _configDao; + @Inject + private UserVmDetailsDao _userVmDetailsDao; private final SearchBuilder VmDetailSearch; private final SearchBuilder activeVmByIsoSearch; @@ -96,7 +99,11 @@ public class UserVmJoinDaoImpl extends GenericDaoBase implem userVmResponse.setId(userVm.getUuid()); userVmResponse.setName(userVm.getName()); - userVmResponse.setDisplayName(userVm.getDisplayName()); + if (userVm.getDisplayName() != null) { + userVmResponse.setDisplayName(userVm.getDisplayName()); + } else { + userVmResponse.setDisplayName(userVm.getName()); + } if (userVm.getAccountType() == Account.ACCOUNT_TYPE_PROJECT) { userVmResponse.setProjectId(userVm.getProjectUuid()); @@ -142,6 +149,10 @@ public class UserVmJoinDaoImpl extends GenericDaoBase implem userVmResponse.setServiceOfferingId(userVm.getServiceOfferingUuid()); userVmResponse.setServiceOfferingName(userVm.getServiceOfferingName()); } + if (details.contains(VMDetails.all) || details.contains(VMDetails.diskoff)) { + userVmResponse.setDiskOfferingId(userVm.getDiskOfferingUuid()); + userVmResponse.setDiskOfferingName(userVm.getDiskOfferingName()); + } if (details.contains(VMDetails.all) || details.contains(VMDetails.servoff) || details.contains(VMDetails.stats)) { userVmResponse.setCpuNumber(userVm.getCpu()); userVmResponse.setCpuSpeed(userVm.getSpeed()); @@ -164,6 +175,7 @@ public class UserVmJoinDaoImpl extends GenericDaoBase implem userVmResponse.setPublicIpId(userVm.getPublicIpUuid()); userVmResponse.setPublicIp(userVm.getPublicIpAddress()); userVmResponse.setKeyPairName(userVm.getKeypairName()); + userVmResponse.setOsTypeId(userVm.getGuestOsId()); if (details.contains(VMDetails.all) || details.contains(VMDetails.stats)) { // stats calculation @@ -175,8 +187,7 @@ public class UserVmJoinDaoImpl extends GenericDaoBase implem userVmResponse.setNetworkKbsWrite((long)vmStats.getNetworkWriteKBs()); - if ((userVm.getHypervisorType() != null) && - (userVm.getHypervisorType().equals(HypervisorType.KVM) || userVm.getHypervisorType().equals(HypervisorType.XenServer))) { // support KVM and XenServer only util 2013.06.25 + if ((userVm.getHypervisorType() != null) && (userVm.getHypervisorType().equals(HypervisorType.KVM) || userVm.getHypervisorType().equals(HypervisorType.XenServer))) { // support KVM and XenServer only util 2013.06.25 userVmResponse.setDiskKbsRead((long)vmStats.getDiskReadKBs()); userVmResponse.setDiskKbsWrite((long)vmStats.getDiskWriteKBs()); @@ -261,10 +272,11 @@ public class UserVmJoinDaoImpl extends GenericDaoBase implem } // set resource details map - // only hypervisortoolsversion can be returned to the end user } - if (userVm.getDetailName() != null && userVm.getDetailName().equalsIgnoreCase(VmDetailConstants.HYPERVISOR_TOOLS_VERSION)) { + // only hypervisortoolsversion can be returned to the end user + UserVmDetailVO hypervisorToolsVersion = _userVmDetailsDao.findDetail(userVm.getId(), VmDetailConstants.HYPERVISOR_TOOLS_VERSION); + if (hypervisorToolsVersion != null) { Map resourceDetails = new HashMap(); - resourceDetails.put(userVm.getDetailName(), userVm.getDetailValue()); + resourceDetails.put(hypervisorToolsVersion.getName(), hypervisorToolsVersion.getValue()); userVmResponse.setDetails(resourceDetails); } diff --git a/server/src/com/cloud/api/query/dao/VolumeJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/VolumeJoinDaoImpl.java index a8631f781ed..3604883c4ea 100644 --- a/server/src/com/cloud/api/query/dao/VolumeJoinDaoImpl.java +++ b/server/src/com/cloud/api/query/dao/VolumeJoinDaoImpl.java @@ -111,7 +111,7 @@ public class VolumeJoinDaoImpl extends GenericDaoBase implem volResponse.setCreated(volume.getCreatedOnStore()); if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) - volResponse.setHypervisor(ApiDBUtils.getHypervisorTypeFromFormat(volume.getFormat()).toString()); + volResponse.setHypervisor(ApiDBUtils.getHypervisorTypeFromFormat(volume.getDataCenterId(), volume.getFormat()).toString()); if (volume.getDownloadState() != Status.DOWNLOADED) { String volumeStatus = "Processing"; if (volume.getDownloadState() == VMTemplateHostVO.Status.DOWNLOAD_IN_PROGRESS) { @@ -175,7 +175,7 @@ public class VolumeJoinDaoImpl extends GenericDaoBase implem if (volume.getHypervisorType() != null) { volResponse.setHypervisor(volume.getHypervisorType().toString()); } else { - volResponse.setHypervisor(ApiDBUtils.getHypervisorTypeFromFormat(volume.getFormat()).toString()); + volResponse.setHypervisor(ApiDBUtils.getHypervisorTypeFromFormat(volume.getDataCenterId(), volume.getFormat()).toString()); } } Long poolId = volume.getPoolId(); diff --git a/server/src/com/cloud/api/query/vo/ServiceOfferingJoinVO.java b/server/src/com/cloud/api/query/vo/ServiceOfferingJoinVO.java index cfcc9b71989..06b9e6b4231 100644 --- a/server/src/com/cloud/api/query/vo/ServiceOfferingJoinVO.java +++ b/server/src/com/cloud/api/query/vo/ServiceOfferingJoinVO.java @@ -82,10 +82,10 @@ public class ServiceOfferingJoinVO extends BaseViewVO implements InternalIdentit private String hostTag; @Column(name = "default_use") - private boolean default_use; + private boolean defaultUse; @Column(name = "vm_type") - private String vm_type; + private String vmType; @Column(name = "sort_key") int sortKey; @@ -217,11 +217,11 @@ public class ServiceOfferingJoinVO extends BaseViewVO implements InternalIdentit } public boolean isDefaultUse() { - return default_use; + return defaultUse; } public String getSystemVmType() { - return vm_type; + return vmType; } public String getDeploymentPlanner() { diff --git a/server/src/com/cloud/api/query/vo/TemplateJoinVO.java b/server/src/com/cloud/api/query/vo/TemplateJoinVO.java index e295272d748..c096279888d 100644 --- a/server/src/com/cloud/api/query/vo/TemplateJoinVO.java +++ b/server/src/com/cloud/api/query/vo/TemplateJoinVO.java @@ -27,6 +27,7 @@ import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; +import com.cloud.template.VirtualMachineTemplate.State; import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine; import com.cloud.hypervisor.Hypervisor.HypervisorType; @@ -200,6 +201,10 @@ public class TemplateJoinVO extends BaseViewVO implements ControlledViewEntity { @Column(name = "size") private long size; + @Column(name = "template_state") + @Enumerated(EnumType.STRING) + private State templateState; + @Column(name = "destroyed") boolean destroyed = false; @@ -532,4 +537,6 @@ public class TemplateJoinVO extends BaseViewVO implements ControlledViewEntity { public String getTempZonePair() { return tempZonePair; } + + public State getTemplateState() { return templateState; } } diff --git a/server/src/com/cloud/api/query/vo/UserVmJoinVO.java b/server/src/com/cloud/api/query/vo/UserVmJoinVO.java index 5bb4f35aacd..9e4fc21caeb 100644 --- a/server/src/com/cloud/api/query/vo/UserVmJoinVO.java +++ b/server/src/com/cloud/api/query/vo/UserVmJoinVO.java @@ -34,8 +34,8 @@ import com.cloud.network.Networks.TrafficType; import com.cloud.server.ResourceTag.ResourceObjectType; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.Volume; -import com.cloud.utils.db.Encrypt; import com.cloud.utils.db.GenericDao; +import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine.State; @@ -48,10 +48,10 @@ public class UserVmJoinVO extends BaseViewVO implements ControlledViewEntity { private long id; @Column(name = "name", updatable = false, nullable = false, length = 255) - private String name = null; + private final String name = null; @Column(name = "display_name", updatable = false, nullable = false, length = 255) - private String displayName = null; + private final String displayName = null; @Column(name = "account_id") private long accountId; @@ -60,7 +60,7 @@ public class UserVmJoinVO extends BaseViewVO implements ControlledViewEntity { private String accountUuid; @Column(name = "account_name") - private String accountName = null; + private final String accountName = null; @Column(name = "account_type") private short accountType; @@ -72,10 +72,10 @@ public class UserVmJoinVO extends BaseViewVO implements ControlledViewEntity { private String domainUuid; @Column(name = "domain_name") - private String domainName = null; + private final String domainName = null; @Column(name = "domain_path") - private String domainPath = null; + private final String domainPath = null; @Column(name = "instance_group_id") private long instanceGroupId; @@ -97,7 +97,7 @@ public class UserVmJoinVO extends BaseViewVO implements ControlledViewEntity { */ @Enumerated(value = EnumType.STRING) @Column(name = "state", updatable = true, nullable = false, length = 32) - private State state = null; + private final State state = null; @Column(name = GenericDao.CREATED_COLUMN) private Date created; @@ -121,10 +121,6 @@ public class UserVmJoinVO extends BaseViewVO implements ControlledViewEntity { @Column(name = "ha_enabled", updatable = true, nullable = true) private boolean haEnabled; - @Encrypt - @Column(name = "vnc_password", updatable = true, nullable = false, length = 255) - protected String vncPassword; - @Column(name = "limit_cpu_use", updatable = true, nullable = true) private boolean limitCpuUse; @@ -153,7 +149,7 @@ public class UserVmJoinVO extends BaseViewVO implements ControlledViewEntity { private String dataCenterUuid; @Column(name = "data_center_name") - private String dataCenterName = null; + private final String dataCenterName = null; @Column(name = "security_group_enabled") private boolean securityGroupEnabled; @@ -194,6 +190,15 @@ public class UserVmJoinVO extends BaseViewVO implements ControlledViewEntity { @Column(name = "iso_display_text", length = 4096) private String isoDisplayText; + @Column(name = "disk_offering_id") + private long diskOfferingId; + + @Column(name = "disk_offering_uuid") + private String diskOfferingUuid; + + @Column(name = "disk_offering_name") + private String diskOfferingName; + @Column(name = "service_offering_id") private long serviceOfferingId; @@ -223,13 +228,13 @@ public class UserVmJoinVO extends BaseViewVO implements ControlledViewEntity { private StoragePoolType poolType; @Column(name = "volume_id") - private long volume_id; + private long volumeId; @Column(name = "volume_uuid") - private String volume_uuid; + private String volumeUuid; @Column(name = "volume_device_id") - private Long volumeDeviceId = null; + private final Long volumeDeviceId = null; @Column(name = "volume_type") @Enumerated(EnumType.STRING) @@ -416,6 +421,18 @@ public class UserVmJoinVO extends BaseViewVO implements ControlledViewEntity { return password; } + public String getDiskOfferingName() { + return diskOfferingName; + } + + public String getDiskOfferingUuid() { + return diskOfferingUuid; + } + + public long getDiskOfferingId() { + return diskOfferingId; + } + public void setPassword(String password) { this.password = password; } @@ -516,10 +533,6 @@ public class UserVmJoinVO extends BaseViewVO implements ControlledViewEntity { return haEnabled; } - public String getVncPassword() { - return vncPassword; - } - public String getPrivateIpAddress() { return privateIpAddress; } @@ -640,8 +653,8 @@ public class UserVmJoinVO extends BaseViewVO implements ControlledViewEntity { return poolType; } - public long getVolume_id() { - return volume_id; + public long getVolumeId() { + return volumeId; } public Long getVolumeDeviceId() { @@ -733,9 +746,11 @@ public class UserVmJoinVO extends BaseViewVO implements ControlledViewEntity { } public String getDetail(String name) { - assert (details != null) : "Did you forget to load the details?"; + if (details == null) { + throw new CloudRuntimeException("No details to get. Did you forget to load the details?"); + } - return details != null ? details.get(name) : null; + return details.get(name); } public String getUserData() { @@ -813,7 +828,7 @@ public class UserVmJoinVO extends BaseViewVO implements ControlledViewEntity { } public String getVolume_uuid() { - return volume_uuid; + return volumeUuid; } public String getSecurityGroupUuid() { diff --git a/server/src/com/cloud/api/response/ApiResponseSerializer.java b/server/src/com/cloud/api/response/ApiResponseSerializer.java index 6cdf6c6b45b..f276e89d5e1 100644 --- a/server/src/com/cloud/api/response/ApiResponseSerializer.java +++ b/server/src/com/cloud/api/response/ApiResponseSerializer.java @@ -26,11 +26,6 @@ import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.apache.log4j.Logger; - -import com.google.gson.Gson; -import com.google.gson.annotations.SerializedName; - import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.ResponseObject; @@ -39,6 +34,7 @@ import org.apache.cloudstack.api.response.CreateCmdResponse; import org.apache.cloudstack.api.response.ExceptionResponse; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.log4j.Logger; import com.cloud.api.ApiDBUtils; import com.cloud.api.ApiResponseGsonHelper; @@ -46,6 +42,8 @@ import com.cloud.api.ApiServer; import com.cloud.utils.encoding.URLEncoder; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.ExceptionProxyObject; +import com.google.gson.Gson; +import com.google.gson.annotations.SerializedName; public class ApiResponseSerializer { private static final Logger s_logger = Logger.getLogger(ApiResponseSerializer.class.getName()); @@ -241,6 +239,8 @@ public class ApiResponseSerializer { if (idFieldName != null) { sb.append("<" + "uuidProperty" + ">" + idFieldName + ""); } + } else if (value instanceof String) { + sb.append("<").append(serializedName.value()).append(">").append(value).append(""); } } if (usedUuidList) { @@ -291,7 +291,7 @@ public class ApiResponseSerializer { } private static String encodeParam(String value) { - if (!ApiServer.encodeApiResponse) { + if (!ApiServer.isEncodeApiResponse()) { return value; } try { diff --git a/server/src/com/cloud/capacity/CapacityManagerImpl.java b/server/src/com/cloud/capacity/CapacityManagerImpl.java index e42879cbbd2..957a5d0d974 100755 --- a/server/src/com/cloud/capacity/CapacityManagerImpl.java +++ b/server/src/com/cloud/capacity/CapacityManagerImpl.java @@ -27,12 +27,12 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; -import com.cloud.deploy.DeploymentClusterPlanner; -import com.cloud.deploy.DeploymentPlanner; -import com.cloud.event.UsageEventVO; -import com.cloud.utils.exception.CloudRuntimeException; import org.apache.log4j.Logger; +import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreDriver; +import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProvider; +import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProviderManager; +import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver; import org.apache.cloudstack.framework.config.ConfigDepot; import org.apache.cloudstack.framework.config.ConfigKey; import org.apache.cloudstack.framework.config.Configurable; @@ -57,6 +57,8 @@ import com.cloud.dc.ClusterDetailsDao; import com.cloud.dc.ClusterDetailsVO; import com.cloud.dc.ClusterVO; import com.cloud.dc.dao.ClusterDao; +import com.cloud.deploy.DeploymentClusterPlanner; +import com.cloud.event.UsageEventVO; import com.cloud.exception.ConnectionException; import com.cloud.host.Host; import com.cloud.host.HostVO; @@ -74,6 +76,7 @@ import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.storage.StorageManager; import com.cloud.storage.VMTemplateStoragePoolVO; import com.cloud.storage.VMTemplateVO; +import com.cloud.storage.VolumeVO; import com.cloud.storage.dao.VMTemplatePoolDao; import com.cloud.storage.dao.VolumeDao; import com.cloud.utils.DateUtil; @@ -86,6 +89,7 @@ import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; import com.cloud.utils.db.TransactionCallbackNoReturn; import com.cloud.utils.db.TransactionStatus; +import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.fsm.StateListener; import com.cloud.vm.UserVmDetailVO; import com.cloud.vm.UserVmVO; @@ -97,7 +101,6 @@ import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.UserVmDetailsDao; import com.cloud.vm.dao.VMInstanceDao; import com.cloud.vm.snapshot.dao.VMSnapshotDao; -import org.springframework.instrument.classloading.glassfish.GlassFishLoadTimeWeaver; @Local(value = CapacityManager.class) public class CapacityManagerImpl extends ManagerBase implements CapacityManager, StateListener, Listener, ResourceListener, @@ -137,6 +140,8 @@ public class CapacityManagerImpl extends ManagerBase implements CapacityManager, ClusterDao _clusterDao; @Inject ConfigDepot _configDepot; + @Inject + DataStoreProviderManager _dataStoreProviderMgr; @Inject ClusterDetailsDao _clusterDetailsDao; @@ -356,29 +361,31 @@ public class CapacityManagerImpl extends ManagerBase implements CapacityManager, } } - public boolean checkIfHostHasCpuCapability(long hostId, Integer cpuNum, Integer cpuSpeed){ + @Override + public boolean checkIfHostHasCpuCapability(long hostId, Integer cpuNum, Integer cpuSpeed) { // Check host can support the Cpu Number and Speed. Host host = _hostDao.findById(hostId); boolean isCpuNumGood = host.getCpus().intValue() >= cpuNum; boolean isCpuSpeedGood = host.getSpeed().intValue() >= cpuSpeed; - if(isCpuNumGood && isCpuSpeedGood){ + if (isCpuNumGood && isCpuSpeedGood) { if (s_logger.isDebugEnabled()) { - s_logger.debug("Host: " + hostId + " has cpu capability (cpu:" +host.getCpus()+ ", speed:" + host.getSpeed() + - ") to support requested CPU: " + cpuNum + " and requested speed: " + cpuSpeed); + s_logger.debug("Host: " + hostId + " has cpu capability (cpu:" + host.getCpus() + ", speed:" + host.getSpeed() + + ") to support requested CPU: " + cpuNum + " and requested speed: " + cpuSpeed); } return true; - }else{ + } else { if (s_logger.isDebugEnabled()) { - s_logger.debug("Host: " + hostId + " doesn't have cpu capability (cpu:" +host.getCpus()+ ", speed:" + host.getSpeed() + - ") to support requested CPU: " + cpuNum + " and requested speed: " + cpuSpeed); + s_logger.debug("Host: " + hostId + " doesn't have cpu capability (cpu:" + host.getCpus() + ", speed:" + host.getSpeed() + + ") to support requested CPU: " + cpuNum + " and requested speed: " + cpuSpeed); } return false; } } @Override - public boolean checkIfHostHasCapacity(long hostId, Integer cpu, long ram, boolean checkFromReservedCapacity, float cpuOvercommitRatio, float memoryOvercommitRatio, boolean considerReservedCapacity) { + public boolean checkIfHostHasCapacity(long hostId, Integer cpu, long ram, boolean checkFromReservedCapacity, float cpuOvercommitRatio, float memoryOvercommitRatio, + boolean considerReservedCapacity) { boolean hasCapacity = false; if (s_logger.isDebugEnabled()) { @@ -498,12 +505,48 @@ public class CapacityManagerImpl extends ManagerBase implements CapacityManager, } + private long getUsedBytes(StoragePoolVO pool) { + long usedBytes = 0; + + List volumes = _volumeDao.findByPoolId(pool.getId(), null); + + if (volumes != null && volumes.size() > 0) { + DataStoreProvider storeProvider = _dataStoreProviderMgr.getDataStoreProvider(pool.getStorageProviderName()); + DataStoreDriver storeDriver = storeProvider.getDataStoreDriver(); + PrimaryDataStoreDriver primaryStoreDriver = null; + + if (storeDriver instanceof PrimaryDataStoreDriver) { + primaryStoreDriver = (PrimaryDataStoreDriver)storeDriver; + } + + for (VolumeVO volume : volumes) { + if (primaryStoreDriver != null) { + usedBytes += primaryStoreDriver.getVolumeSizeIncludingHypervisorSnapshotReserve(volume, pool); + } + else { + usedBytes += volume.getSize(); + } + } + } + + return usedBytes; + } + @Override public long getAllocatedPoolCapacity(StoragePoolVO pool, VMTemplateVO templateForVmCreation) { + long totalAllocatedSize = 0; - // Get size for all the non-destroyed volumes - Pair sizes = _volumeDao.getNonDestroyedCountAndTotalByPool(pool.getId()); - long totalAllocatedSize = sizes.second() + sizes.first() * _extraBytesPerVolume; + // if the storage pool is managed, the used bytes can be larger than the sum of the sizes of all of the non-destroyed volumes + // in this case, call getUsedBytes(StoragePoolVO) + if (pool.isManaged()) { + totalAllocatedSize = getUsedBytes(pool); + } + else { + // Get size for all the non-destroyed volumes + Pair sizes = _volumeDao.getNonDestroyedCountAndTotalByPool(pool.getId()); + + totalAllocatedSize = sizes.second() + sizes.first() * _extraBytesPerVolume; + } // Get size for VM Snapshots totalAllocatedSize = totalAllocatedSize + _volumeDao.getVMSnapshotSizeByPool(pool.getId()); @@ -857,14 +900,14 @@ public class CapacityManagerImpl extends ManagerBase implements CapacityManager, } @Override - public float getClusterOverProvisioningFactor(Long clusterId, short capacityType){ + public float getClusterOverProvisioningFactor(Long clusterId, short capacityType) { String capacityOverProvisioningName = ""; - if(capacityType == Capacity.CAPACITY_TYPE_CPU){ + if (capacityType == Capacity.CAPACITY_TYPE_CPU) { capacityOverProvisioningName = "cpuOvercommitRatio"; - }else if(capacityType == Capacity.CAPACITY_TYPE_MEMORY){ + } else if (capacityType == Capacity.CAPACITY_TYPE_MEMORY) { capacityOverProvisioningName = "memoryOvercommitRatio"; - }else{ + } else { throw new CloudRuntimeException("Invalid capacityType - " + capacityType); } @@ -875,7 +918,7 @@ public class CapacityManagerImpl extends ManagerBase implements CapacityManager, } @Override - public boolean checkIfClusterCrossesThreshold(Long clusterId, Integer cpuRequested, long ramRequested){ + public boolean checkIfClusterCrossesThreshold(Long clusterId, Integer cpuRequested, long ramRequested) { Float clusterCpuOverProvisioning = getClusterOverProvisioningFactor(clusterId, Capacity.CAPACITY_TYPE_CPU); Float clusterMemoryOverProvisioning = getClusterOverProvisioningFactor(clusterId, Capacity.CAPACITY_TYPE_MEMORY); @@ -883,16 +926,16 @@ public class CapacityManagerImpl extends ManagerBase implements CapacityManager, Float clusterMemoryCapacityDisableThreshold = DeploymentClusterPlanner.ClusterMemoryCapacityDisableThreshold.valueIn(clusterId); float cpuConsumption = _capacityDao.findClusterConsumption(clusterId, Capacity.CAPACITY_TYPE_CPU, cpuRequested); - if(cpuConsumption/clusterCpuOverProvisioning > clusterCpuCapacityDisableThreshold){ - s_logger.debug("Cluster: " +clusterId + " cpu consumption " + cpuConsumption/clusterCpuOverProvisioning - + " crosses disable threshold " + clusterCpuCapacityDisableThreshold); + if (cpuConsumption / clusterCpuOverProvisioning > clusterCpuCapacityDisableThreshold) { + s_logger.debug("Cluster: " + clusterId + " cpu consumption " + cpuConsumption / clusterCpuOverProvisioning + + " crosses disable threshold " + clusterCpuCapacityDisableThreshold); return true; } float memoryConsumption = _capacityDao.findClusterConsumption(clusterId, Capacity.CAPACITY_TYPE_MEMORY, ramRequested); - if(memoryConsumption/clusterMemoryOverProvisioning > clusterMemoryCapacityDisableThreshold){ - s_logger.debug("Cluster: " +clusterId + " memory consumption " + memoryConsumption/clusterMemoryOverProvisioning - + " crosses disable threshold " + clusterMemoryCapacityDisableThreshold); + if (memoryConsumption / clusterMemoryOverProvisioning > clusterMemoryCapacityDisableThreshold) { + s_logger.debug("Cluster: " + clusterId + " memory consumption " + memoryConsumption / clusterMemoryOverProvisioning + + " crosses disable threshold " + clusterMemoryCapacityDisableThreshold); return true; } diff --git a/server/src/com/cloud/capacity/ComputeCapacityListener.java b/server/src/com/cloud/capacity/ComputeCapacityListener.java index 75bfe65bcf2..dc8cb0bb70b 100755 --- a/server/src/com/cloud/capacity/ComputeCapacityListener.java +++ b/server/src/com/cloud/capacity/ComputeCapacityListener.java @@ -36,10 +36,10 @@ public class ComputeCapacityListener implements Listener { CapacityManager _capacityMgr; float _cpuOverProvisioningFactor = 1.0f; - public ComputeCapacityListener(CapacityDao _capacityDao, CapacityManager _capacityMgr) { + public ComputeCapacityListener(CapacityDao capacityDao, CapacityManager capacityMgr) { super(); - this._capacityDao = _capacityDao; - this._capacityMgr = _capacityMgr; + this._capacityDao = capacityDao; + this._capacityMgr = capacityMgr; } @Override diff --git a/server/src/com/cloud/configuration/Config.java b/server/src/com/cloud/configuration/Config.java index f08ca2445ae..975eecdc117 100755 --- a/server/src/com/cloud/configuration/Config.java +++ b/server/src/com/cloud/configuration/Config.java @@ -41,7 +41,6 @@ import com.cloud.vm.snapshot.VMSnapshotManager; public enum Config { - // Alert AlertEmailAddresses( @@ -65,7 +64,14 @@ public enum Config { AlertSMTPPort("Alert", ManagementServer.class, Integer.class, "alert.smtp.port", "465", "Port the SMTP server is listening on.", null), AlertSMTPConnectionTimeout("Alert", ManagementServer.class, Integer.class, "alert.smtp.connectiontimeout", "30000", "Socket connection timeout value in milliseconds. -1 for infinite timeout.", null), - AlertSMTPTimeout("Alert", ManagementServer.class, Integer.class, "alert.smtp.timeout", "30000", "Socket I/O timeout value in milliseconds. -1 for infinite timeout.", null), + AlertSMTPTimeout( + "Alert", + ManagementServer.class, + Integer.class, + "alert.smtp.timeout", + "30000", + "Socket I/O timeout value in milliseconds. -1 for infinite timeout.", + null), AlertSMTPUseAuth("Alert", ManagementServer.class, String.class, "alert.smtp.useAuth", null, "If true, use SMTP authentication when sending emails.", null), AlertSMTPUsername( "Alert", @@ -396,6 +402,10 @@ public enum Config { "10", "The maximum number of subnets per customer gateway", null), + MaxNumberOfSecondaryIPsPerNIC( + "Network", ManagementServer.class, Integer.class, + "vm.network.nic.max.secondary.ipaddresses", "256", + "Specify the number of secondary ip addresses per nic per vm", null), // Console Proxy ConsoleProxyCapacityStandby( @@ -975,7 +985,6 @@ public enum Config { "FirstFitPlanner", "'FirstFitPlanner', 'UserDispersingPlanner', 'UserConcentratedPodPlanner': DeploymentPlanner heuristic that will be used for VM deployment.", null), - EndpointeUrl("Advanced", ManagementServer.class, String.class, "endpointe.url", "http://localhost:8080/client/api", "Endpointe Url", null), ElasticLoadBalancerEnabled( "Advanced", ManagementServer.class, @@ -1103,6 +1112,13 @@ public enum Config { "xenserver61", "default Xen PV driver version for registered template, valid value:xenserver56,xenserver61 ", "xenserver56,xenserver61"), + XenServerHotFix("Advanced", + ManagementServer.class, + Boolean.class, + "xen.hotfix.enabled", + "false", + "Enable/Disable xenserver hot fix", + null), // VMware VmwareUseNexusVSwitch( @@ -1359,9 +1375,6 @@ public enum Config { "The allowable clock difference in milliseconds between when an SSO login request is made and when it is received.", null), //NetworkType("Hidden", ManagementServer.class, String.class, "network.type", "vlan", "The type of network that this deployment will use.", "vlan,direct"), - HashKey("Hidden", ManagementServer.class, String.class, "security.hash.key", null, "for generic key-ed hash", null), - EncryptionKey("Hidden", ManagementServer.class, String.class, "security.encryption.key", null, "base64 encoded key data", null), - EncryptionIV("Hidden", ManagementServer.class, String.class, "security.encryption.iv", null, "base64 encoded IV data", null), RouterRamSize("Hidden", NetworkOrchestrationService.class, Integer.class, "router.ram.size", "128", "Default RAM for router VM (in MB).", null), DefaultPageSize("Advanced", ManagementServer.class, Long.class, "default.page.size", "500", "Default page size for API list* commands", null), @@ -1699,8 +1712,6 @@ public enum Config { "false", "Should be set to true, if there will be multiple NetScaler devices providing EIP service in a zone", null), - CustomDiskOfferingMinSize("Advanced", ManagementServer.class, Long.class, "custom.diskoffering.size.min", "1", "Minimum size in GB for custom disk offering", null), - CustomDiskOfferingMaxSize("Advanced", ManagementServer.class, Long.class, "custom.diskoffering.size.max", "1024", "Maximum size in GB for custom disk offering", null), ConsoleProxyServiceOffering( "Advanced", ManagementServer.class, @@ -1892,49 +1903,49 @@ public enum Config { private final String _range; private final String _scope; // Parameter can be at different levels (Zone/cluster/pool/account), by default every parameter is at global - private static final HashMap> _scopeLevelConfigsMap = new HashMap>(); + private static final HashMap> s_scopeLevelConfigsMap = new HashMap>(); static { - _scopeLevelConfigsMap.put(ConfigKey.Scope.Zone.toString(), new ArrayList()); - _scopeLevelConfigsMap.put(ConfigKey.Scope.Cluster.toString(), new ArrayList()); - _scopeLevelConfigsMap.put(ConfigKey.Scope.StoragePool.toString(), new ArrayList()); - _scopeLevelConfigsMap.put(ConfigKey.Scope.Account.toString(), new ArrayList()); - _scopeLevelConfigsMap.put(ConfigKey.Scope.Global.toString(), new ArrayList()); + s_scopeLevelConfigsMap.put(ConfigKey.Scope.Zone.toString(), new ArrayList()); + s_scopeLevelConfigsMap.put(ConfigKey.Scope.Cluster.toString(), new ArrayList()); + s_scopeLevelConfigsMap.put(ConfigKey.Scope.StoragePool.toString(), new ArrayList()); + s_scopeLevelConfigsMap.put(ConfigKey.Scope.Account.toString(), new ArrayList()); + s_scopeLevelConfigsMap.put(ConfigKey.Scope.Global.toString(), new ArrayList()); for (Config c : Config.values()) { //Creating group of parameters per each level (zone/cluster/pool/account) StringTokenizer tokens = new StringTokenizer(c.getScope(), ","); while (tokens.hasMoreTokens()) { String scope = tokens.nextToken().trim(); - List currentConfigs = _scopeLevelConfigsMap.get(scope); + List currentConfigs = s_scopeLevelConfigsMap.get(scope); currentConfigs.add(c); - _scopeLevelConfigsMap.put(scope, currentConfigs); + s_scopeLevelConfigsMap.put(scope, currentConfigs); } } } - private static final HashMap> _configs = new HashMap>(); + private static final HashMap> Configs = new HashMap>(); static { // Add categories - _configs.put("Alert", new ArrayList()); - _configs.put("Storage", new ArrayList()); - _configs.put("Snapshots", new ArrayList()); - _configs.put("Network", new ArrayList()); - _configs.put("Usage", new ArrayList()); - _configs.put("Console Proxy", new ArrayList()); - _configs.put("Advanced", new ArrayList()); - _configs.put("Usage", new ArrayList()); - _configs.put("Developer", new ArrayList()); - _configs.put("Hidden", new ArrayList()); - _configs.put("Account Defaults", new ArrayList()); - _configs.put("Project Defaults", new ArrayList()); - _configs.put("Secure", new ArrayList()); + Configs.put("Alert", new ArrayList()); + Configs.put("Storage", new ArrayList()); + Configs.put("Snapshots", new ArrayList()); + Configs.put("Network", new ArrayList()); + Configs.put("Usage", new ArrayList()); + Configs.put("Console Proxy", new ArrayList()); + Configs.put("Advanced", new ArrayList()); + Configs.put("Usage", new ArrayList()); + Configs.put("Developer", new ArrayList()); + Configs.put("Hidden", new ArrayList()); + Configs.put("Account Defaults", new ArrayList()); + Configs.put("Project Defaults", new ArrayList()); + Configs.put("Secure", new ArrayList()); // Add values into HashMap for (Config c : Config.values()) { String category = c.getCategory(); - List currentConfigs = _configs.get(category); + List currentConfigs = Configs.get(category); currentConfigs.add(c); - _configs.put(category, currentConfigs); + Configs.put(category, currentConfigs); } } @@ -2026,7 +2037,7 @@ public enum Config { } public static List getConfigs(String category) { - return _configs.get(category); + return Configs.get(category); } public static Config getConfig(String name) { @@ -2044,7 +2055,7 @@ public enum Config { } public static List getCategories() { - Object[] keys = _configs.keySet().toArray(); + Object[] keys = Configs.keySet().toArray(); List categories = new ArrayList(); for (Object key : keys) { categories.add((String)key); @@ -2053,6 +2064,6 @@ public enum Config { } public static List getConfigListByScope(String scope) { - return _scopeLevelConfigsMap.get(scope); + return s_scopeLevelConfigsMap.get(scope); } } diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java index c345795fe37..20037167487 100755 --- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java @@ -315,7 +315,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati // FIXME - why don't we have interface for DataCenterLinkLocalIpAddressDao? @Inject - protected DataCenterLinkLocalIpAddressDao _LinkLocalIpAllocDao; + protected DataCenterLinkLocalIpAddressDao _linkLocalIpAllocDao; private int _maxVolumeSizeInGb = Integer.parseInt(Config.MaxVolumeSize.getDefaultValue()); private long _defaultPageSize = Long.parseLong(Config.DefaultPageSize.getDefaultValue()); @@ -403,13 +403,13 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati if (localCidrs.length > 0) { s_logger.warn("Management network CIDR is not configured originally. Set it default to " + localCidrs[0]); - _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_MANAGMENT_NODE, 0, new Long(0), "Management network CIDR is not configured originally. Set it default to " + - localCidrs[0], ""); + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_MANAGMENT_NODE, 0, new Long(0), "Management network CIDR is not configured originally. Set it default to " + + localCidrs[0], ""); _configDao.update(Config.ManagementNetwork.key(), Config.ManagementNetwork.getCategory(), localCidrs[0]); } else { s_logger.warn("Management network CIDR is not properly configured and we are not able to find a default setting"); _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_MANAGMENT_NODE, 0, new Long(0), - "Management network CIDR is not properly configured and we are not able to find a default setting", ""); + "Management network CIDR is not properly configured and we are not able to find a default setting", ""); } } @@ -438,53 +438,53 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati // global parameter updation if (scope != null && !scope.isEmpty() && !ConfigKey.Scope.Global.toString().equalsIgnoreCase(scope)) { switch (ConfigKey.Scope.valueOf(scope)) { - case Zone: - DataCenterVO zone = _zoneDao.findById(resourceId); - if (zone == null) { - throw new InvalidParameterValueException("unable to find zone by id " + resourceId); - } - _dcDetailsDao.addDetail(resourceId, name, value); - break; - case Cluster: - ClusterVO cluster = _clusterDao.findById(resourceId); - if (cluster == null) { - throw new InvalidParameterValueException("unable to find cluster by id " + resourceId); - } - ClusterDetailsVO clusterDetailsVO = _clusterDetailsDao.findDetail(resourceId, name); - if (clusterDetailsVO == null) { - clusterDetailsVO = new ClusterDetailsVO(resourceId, name, value); - _clusterDetailsDao.persist(clusterDetailsVO); - } else { - clusterDetailsVO.setValue(value); - _clusterDetailsDao.update(clusterDetailsVO.getId(), clusterDetailsVO); - } - break; + case Zone: + DataCenterVO zone = _zoneDao.findById(resourceId); + if (zone == null) { + throw new InvalidParameterValueException("unable to find zone by id " + resourceId); + } + _dcDetailsDao.addDetail(resourceId, name, value); + break; + case Cluster: + ClusterVO cluster = _clusterDao.findById(resourceId); + if (cluster == null) { + throw new InvalidParameterValueException("unable to find cluster by id " + resourceId); + } + ClusterDetailsVO clusterDetailsVO = _clusterDetailsDao.findDetail(resourceId, name); + if (clusterDetailsVO == null) { + clusterDetailsVO = new ClusterDetailsVO(resourceId, name, value); + _clusterDetailsDao.persist(clusterDetailsVO); + } else { + clusterDetailsVO.setValue(value); + _clusterDetailsDao.update(clusterDetailsVO.getId(), clusterDetailsVO); + } + break; - case StoragePool: - StoragePoolVO pool = _storagePoolDao.findById(resourceId); - if (pool == null) { - throw new InvalidParameterValueException("unable to find storage pool by id " + resourceId); - } - _storagePoolDetailsDao.addDetail(resourceId, name, value); + case StoragePool: + StoragePoolVO pool = _storagePoolDao.findById(resourceId); + if (pool == null) { + throw new InvalidParameterValueException("unable to find storage pool by id " + resourceId); + } + _storagePoolDetailsDao.addDetail(resourceId, name, value); - break; + break; - case Account: - AccountVO account = _accountDao.findById(resourceId); - if (account == null) { - throw new InvalidParameterValueException("unable to find account by id " + resourceId); - } - AccountDetailVO accountDetailVO = _accountDetailsDao.findDetail(resourceId, name); - if (accountDetailVO == null) { - accountDetailVO = new AccountDetailVO(resourceId, name, value); - _accountDetailsDao.persist(accountDetailVO); - } else { - accountDetailVO.setValue(value); - _accountDetailsDao.update(accountDetailVO.getId(), accountDetailVO); - } - break; - default: - throw new InvalidParameterValueException("Scope provided is invalid"); + case Account: + AccountVO account = _accountDao.findById(resourceId); + if (account == null) { + throw new InvalidParameterValueException("unable to find account by id " + resourceId); + } + AccountDetailVO accountDetailVO = _accountDetailsDao.findDetail(resourceId, name); + if (accountDetailVO == null) { + accountDetailVO = new AccountDetailVO(resourceId, name, value); + _accountDetailsDao.persist(accountDetailVO); + } else { + accountDetailVO.setValue(value); + _accountDetailsDao.update(accountDetailVO.getId(), accountDetailVO); + } + break; + default: + throw new InvalidParameterValueException("Scope provided is invalid"); } return value; } @@ -598,8 +598,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati Long clusterId = cmd.getClusterId(); Long storagepoolId = cmd.getStoragepoolId(); Long accountId = cmd.getAccountId(); - CallContext.current().setEventDetails( - " Name: " + name + " New Value: " + (((name.toLowerCase()).contains("password")) ? "*****" : (((value == null) ? "" : value)))); + CallContext.current().setEventDetails(" Name: " + name + " New Value: " + (((name.toLowerCase()).contains("password")) ? "*****" : (((value == null) ? "" : value)))); // check if config value exists ConfigurationVO config = _configDao.findByName(name); String catergory = null; @@ -780,8 +779,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati if (route != null) { String routeToVerify = route.trim(); if (!NetUtils.isValidCIDR(routeToVerify)) { - throw new InvalidParameterValueException("Invalid value for blacklisted route: " + route + ". Valid format is list" + - " of cidrs separated by coma. Example: 10.1.1.0/24,192.168.0.0/24"); + throw new InvalidParameterValueException("Invalid value for blacklisted route: " + route + ". Valid format is list" + + " of cidrs separated by coma. Example: 10.1.1.0/24,192.168.0.0/24"); } } } @@ -861,8 +860,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati String errorMsg = table.get(2); String dbName; - if (tableName.equals("event") || tableName.equals("cloud_usage") || tableName.equals("usage_vm_instance") || tableName.equals("usage_ip_address") || - tableName.equals("usage_network") || tableName.equals("usage_job") || tableName.equals("account") || tableName.equals("user_statistics")) { + if (tableName.equals("event") || tableName.equals("cloud_usage") || tableName.equals("usage_vm_instance") || tableName.equals("usage_ip_address") + || tableName.equals("usage_network") || tableName.equals("usage_job") || tableName.equals("account") || tableName.equals("user_statistics")) { dbName = "cloud_usage"; } else { dbName = "cloud"; @@ -889,7 +888,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati } private void checkPodAttributes(long podId, String podName, long zoneId, String gateway, String cidr, String startIp, String endIp, String allocationStateStr, - boolean checkForDuplicates, boolean skipGatewayOverlapCheck) { + boolean checkForDuplicates, boolean skipGatewayOverlapCheck) { if (checkForDuplicates) { // Check if the pod already exists if (validPod(podName, zoneId)) { @@ -979,9 +978,9 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati } // Delete link local ip addresses for the pod - List localIps = _LinkLocalIpAllocDao.listByPodIdDcId(podId, pod.getDataCenterId()); + List localIps = _linkLocalIpAllocDao.listByPodIdDcId(podId, pod.getDataCenterId()); if (!localIps.isEmpty()) { - if (!(_LinkLocalIpAllocDao.deleteIpAddressByPod(podId))) { + if (!(_linkLocalIpAllocDao.deleteIpAddressByPod(podId))) { throw new CloudRuntimeException("Failed to cleanup private ip addresses for pod " + podId); } } @@ -1179,7 +1178,17 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati @Override public Pod createPod(long zoneId, String name, String startIp, String endIp, String gateway, String netmask, String allocationState) { + // Check if the gateway is a valid IP address + if (!NetUtils.isValidIp(gateway)) { + throw new InvalidParameterValueException("The gateway is invalid"); + } + + if (!NetUtils.isValidNetmask(netmask)) { + throw new InvalidParameterValueException("The netmask is invalid"); + } + String cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask); + Long userId = CallContext.current().getCallingUserId(); if (allocationState == null) { @@ -1190,8 +1199,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati @Override @DB - public HostPodVO createPod(long userId, String podName, final long zoneId, String gateway, String cidr, final String startIp, String endIp, - String allocationStateStr, boolean skipGatewayOverlapCheck) { + public HostPodVO createPod(long userId, String podName, final long zoneId, String gateway, String cidr, final String startIp, String endIp, String allocationStateStr, + boolean skipGatewayOverlapCheck) { // Check if the zone is valid if (!validZone(zoneId)) { @@ -1353,7 +1362,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati } private void checkZoneParameters(String zoneName, String dns1, String dns2, String internalDns1, String internalDns2, boolean checkForDuplicates, Long domainId, - String allocationStateStr, String ip6Dns1, String ip6Dns2) { + String allocationStateStr, String ip6Dns1, String ip6Dns2) { if (checkForDuplicates) { // Check if a zone with the specified name already exists if (validZone(zoneName)) { @@ -1540,7 +1549,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati String value = (String)detail.get("value"); if ((key == null) || (value == null)) { throw new InvalidParameterValueException( - "Invalid Zone Detail specified, fields 'key' and 'value' cannot be null, please specify details in the form: details[0].key=XXX&details[0].value=YYY"); + "Invalid Zone Detail specified, fields 'key' and 'value' cannot be null, please specify details in the form: details[0].key=XXX&details[0].value=YYY"); } // validate the zone detail keys are known keys /* @@ -1557,8 +1566,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati for (String dom : dnsSearchOrder) { if (!NetUtils.verifyDomainName(dom)) { throw new InvalidParameterValueException( - "Invalid network domain suffixes. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " - + "and the hyphen ('-'); can't start or end with \"-\""); + "Invalid network domain suffixes. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " + + "and the hyphen ('-'); can't start or end with \"-\""); } } newDetails.put(ZoneConfig.DnsSearchOrder.getName(), StringUtils.join(dnsSearchOrder, ",")); @@ -1620,8 +1629,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati if (networkDomain != null && !networkDomain.isEmpty()) { if (!NetUtils.verifyDomainName(networkDomain)) { throw new InvalidParameterValueException( - "Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " - + "and the hyphen ('-'); can't start or end with \"-\""); + "Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " + + "and the hyphen ('-'); can't start or end with \"-\""); } } @@ -1681,11 +1690,11 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Storage); } catch (InvalidParameterValueException noStorage) { PhysicalNetworkTrafficTypeVO mgmtTraffic = _trafficTypeDao.findBy(mgmtPhyNetwork.getId(), TrafficType.Management); - _networkSvc.addTrafficTypeToPhysicalNetwork(mgmtPhyNetwork.getId(), TrafficType.Storage.toString(), mgmtTraffic.getXenNetworkLabel(), - mgmtTraffic.getKvmNetworkLabel(), mgmtTraffic.getVmwareNetworkLabel(), mgmtTraffic.getSimulatorNetworkLabel(), mgmtTraffic.getVlan(), - mgmtTraffic.getHypervNetworkLabel()); - s_logger.info("No storage traffic type was specified by admin, create default storage traffic on physical network " + - mgmtPhyNetwork.getId() + " with same configure of management traffic type"); + _networkSvc.addTrafficTypeToPhysicalNetwork(mgmtPhyNetwork.getId(), TrafficType.Storage.toString(), "vlan", mgmtTraffic.getXenNetworkLabel(), + mgmtTraffic.getKvmNetworkLabel(), mgmtTraffic.getVmwareNetworkLabel(), mgmtTraffic.getSimulatorNetworkLabel(), mgmtTraffic.getVlan(), + mgmtTraffic.getHypervNetworkLabel()); + s_logger.info("No storage traffic type was specified by admin, create default storage traffic on physical network " + mgmtPhyNetwork.getId() + + " with same configure of management traffic type"); } } catch (InvalidParameterValueException ex) { throw new InvalidParameterValueException("Cannot enable this Zone since: " + ex.getMessage()); @@ -1734,8 +1743,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati @Override @DB public DataCenterVO createZone(long userId, String zoneName, String dns1, String dns2, String internalDns1, String internalDns2, String guestCidr, String domain, - final Long domainId, NetworkType zoneType, String allocationStateStr, String networkDomain, boolean isSecurityGroupEnabled, boolean isLocalStorageEnabled, - String ip6Dns1, String ip6Dns2) { + final Long domainId, NetworkType zoneType, String allocationStateStr, String networkDomain, boolean isSecurityGroupEnabled, boolean isLocalStorageEnabled, + String ip6Dns1, String ip6Dns2) { // checking the following params outside checkzoneparams method as we do // not use these params for updatezone @@ -1748,8 +1757,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati if (networkDomain != null) { if (!NetUtils.verifyDomainName(networkDomain)) { throw new InvalidParameterValueException( - "Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " - + "and the hyphen ('-'); can't start or end with \"-\""); + "Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " + + "and the hyphen ('-'); can't start or end with \"-\""); } } @@ -1759,8 +1768,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati String zoneToken = UUID.nameUUIDFromBytes(bytes).toString(); // Create the new zone in the database - final DataCenterVO zoneFinal = - new DataCenterVO(zoneName, null, dns1, dns2, internalDns1, internalDns2, guestCidr, domain, domainId, zoneType, zoneToken, networkDomain, + final DataCenterVO zoneFinal = new DataCenterVO(zoneName, null, dns1, dns2, internalDns1, internalDns2, guestCidr, domain, domainId, zoneType, zoneToken, networkDomain, isSecurityGroupEnabled, isLocalStorageEnabled, ip6Dns1, ip6Dns2); if (allocationStateStr != null && !allocationStateStr.isEmpty()) { Grouping.AllocationState allocationState = Grouping.AllocationState.valueOf(allocationStateStr); @@ -1911,8 +1919,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati isSecurityGroupEnabled = true; } - return createZone(userId, zoneName, dns1, dns2, internalDns1, internalDns2, guestCidr, domainVO != null ? domainVO.getName() : null, domainId, zoneType, - allocationState, networkDomain, isSecurityGroupEnabled, isLocalStorageEnabled, ip6Dns1, ip6Dns2); + return createZone(userId, zoneName, dns1, dns2, internalDns1, internalDns2, guestCidr, domainVO != null ? domainVO.getName() : null, domainId, zoneType, allocationState, + networkDomain, isSecurityGroupEnabled, isLocalStorageEnabled, ip6Dns1, ip6Dns2); } @Override @@ -1936,7 +1944,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati //restricting the createserviceoffering to allow setting all or none of the dynamic parameters to null if (cpuNumber == null || cpuSpeed == null || memory == null) { - if (cpuNumber !=null || cpuSpeed !=null || memory !=null) { + if (cpuNumber != null || cpuSpeed != null || memory != null) { throw new InvalidParameterValueException("For creating a custom compute offering cpu, cpu speed and memory all should be null"); } } @@ -1984,8 +1992,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati } else if (VirtualMachine.Type.InternalLoadBalancerVm.toString().toLowerCase().equals(vmTypeString)) { vmType = VirtualMachine.Type.InternalLoadBalancerVm; } else { - throw new InvalidParameterValueException("Invalid systemVmType. Supported types are: " + VirtualMachine.Type.DomainRouter + ", " + - VirtualMachine.Type.ConsoleProxy + ", " + VirtualMachine.Type.SecondaryStorageVm); + throw new InvalidParameterValueException("Invalid systemVmType. Supported types are: " + VirtualMachine.Type.DomainRouter + ", " + VirtualMachine.Type.ConsoleProxy + + ", " + VirtualMachine.Type.SecondaryStorageVm); } } else { allowNetworkRate = true; @@ -1993,8 +2001,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati } if (cmd.getNetworkRate() != null && !allowNetworkRate) { - throw new InvalidParameterValueException( - "Network rate can be specified only for non-System offering and system offerings having \"domainrouter\" systemvmtype"); + throw new InvalidParameterValueException("Network rate can be specified only for non-System offering and system offerings having \"domainrouter\" systemvmtype"); } if (cmd.getDeploymentPlanner() != null) { @@ -2008,19 +2015,17 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati } } - return createServiceOffering(userId, cmd.getIsSystem(), vmType, cmd.getServiceOfferingName(), cpuNumber, memory, cpuSpeed, cmd.getDisplayText(), - localStorageRequired, offerHA, limitCpuUse, volatileVm, cmd.getTags(), cmd.getDomainId(), cmd.getHostTag(), cmd.getNetworkRate(), cmd.getDeploymentPlanner(), - cmd.getDetails(), cmd.getBytesReadRate(), cmd.getBytesWriteRate(), cmd.getIopsReadRate(), cmd.getIopsWriteRate()); + return createServiceOffering(userId, cmd.getIsSystem(), vmType, cmd.getServiceOfferingName(), cpuNumber, memory, cpuSpeed, cmd.getDisplayText(), localStorageRequired, + offerHA, limitCpuUse, volatileVm, cmd.getTags(), cmd.getDomainId(), cmd.getHostTag(), cmd.getNetworkRate(), cmd.getDeploymentPlanner(), cmd.getDetails(), + cmd.getBytesReadRate(), cmd.getBytesWriteRate(), cmd.getIopsReadRate(), cmd.getIopsWriteRate()); } - protected ServiceOfferingVO createServiceOffering(long userId, boolean isSystem, VirtualMachine.Type vm_type, String name, Integer cpu, Integer ramSize, - Integer speed, String displayText, boolean localStorageRequired, boolean offerHA, boolean limitResourceUse, boolean volatileVm, String tags, Long domainId, - String hostTag, Integer networkRate, String deploymentPlanner, Map details, Long bytesReadRate, Long bytesWriteRate, Long iopsReadRate, - Long iopsWriteRate) { + protected ServiceOfferingVO createServiceOffering(long userId, boolean isSystem, VirtualMachine.Type vmType, String name, Integer cpu, Integer ramSize, Integer speed, + String displayText, boolean localStorageRequired, boolean offerHA, boolean limitResourceUse, boolean volatileVm, String tags, Long domainId, String hostTag, + Integer networkRate, String deploymentPlanner, Map details, Long bytesReadRate, Long bytesWriteRate, Long iopsReadRate, Long iopsWriteRate) { tags = StringUtils.cleanupTags(tags); - ServiceOfferingVO offering = - new ServiceOfferingVO(name, cpu, ramSize, speed, networkRate, null, offerHA, limitResourceUse, volatileVm, displayText, localStorageRequired, false, tags, - isSystem, vm_type, domainId, hostTag, deploymentPlanner); + ServiceOfferingVO offering = new ServiceOfferingVO(name, cpu, ramSize, speed, networkRate, null, offerHA, limitResourceUse, volatileVm, displayText, localStorageRequired, + false, tags, isSystem, vmType, domainId, hostTag, deploymentPlanner); if ((bytesReadRate != null) && (bytesReadRate > 0)) offering.setBytesReadRate(bytesReadRate); if ((bytesWriteRate != null) && (bytesWriteRate > 0)) @@ -2118,9 +2123,9 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati } } - protected DiskOfferingVO createDiskOffering(Long domainId, String name, String description, Long numGibibytes, String tags, boolean isCustomized, - boolean localStorageRequired, boolean isDisplayOfferingEnabled, Boolean isCustomizedIops, Long minIops, Long maxIops, Long bytesReadRate, Long bytesWriteRate, - Long iopsReadRate, Long iopsWriteRate, Integer hypervisorSnapshotReserve) { + protected DiskOfferingVO createDiskOffering(Long domainId, String name, String description, Long numGibibytes, String tags, boolean isCustomized, boolean localStorageRequired, + boolean isDisplayOfferingEnabled, Boolean isCustomizedIops, Long minIops, Long maxIops, Long bytesReadRate, Long bytesWriteRate, Long iopsReadRate, Long iopsWriteRate, + Integer hypervisorSnapshotReserve) { long diskSize = 0;// special case for custom disk offerings if (numGibibytes != null && (numGibibytes <= 0)) { throw new InvalidParameterValueException("Please specify a disk size of at least 1 Gb."); @@ -2238,8 +2243,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati Long iopsWriteRate = cmd.getIopsWriteRate(); Integer hypervisorSnapshotReserve = cmd.getHypervisorSnapshotReserve(); - return createDiskOffering(domainId, name, description, numGibibytes, tags, isCustomized, localStorageRequired, isDisplayOfferingEnabled, isCustomizedIops, - minIops, maxIops, bytesReadRate, bytesWriteRate, iopsReadRate, iopsWriteRate, hypervisorSnapshotReserve); + return createDiskOffering(domainId, name, description, numGibibytes, tags, isCustomized, localStorageRequired, isDisplayOfferingEnabled, isCustomizedIops, minIops, + maxIops, bytesReadRate, bytesWriteRate, iopsReadRate, iopsWriteRate, hypervisorSnapshotReserve); } @Override @@ -2368,7 +2373,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati @DB @ActionEvent(eventType = EventTypes.EVENT_VLAN_IP_RANGE_CREATE, eventDescription = "creating vlan ip range", async = false) public Vlan createVlanAndPublicIpRange(CreateVlanIpRangeCmd cmd) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, - ResourceAllocationException { + ResourceAllocationException { Long zoneId = cmd.getZoneId(); Long podId = cmd.getPodId(); String startIP = cmd.getStartIp(); @@ -2544,8 +2549,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati if (zone.getNetworkType() == DataCenter.NetworkType.Advanced) { if (network.getTrafficType() == TrafficType.Guest) { if (network.getGuestType() != GuestType.Shared) { - throw new InvalidParameterValueException("Can execute createVLANIpRanges on shared guest network, but type of this guest network " + network.getId() + - " is " + network.getGuestType()); + throw new InvalidParameterValueException("Can execute createVLANIpRanges on shared guest network, but type of this guest network " + network.getId() + " is " + + network.getGuestType()); } List vlans = _vlanDao.listVlansByNetworkId(network.getId()); @@ -2553,9 +2558,9 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati VlanVO vlan = vlans.get(0); if (vlanId == null) { vlanId = vlan.getVlanTag(); - } else if (!vlan.getVlanTag().equals(vlanId)) { - throw new InvalidParameterValueException("there is already one vlan " + vlan.getVlanTag() + " on network :" + +network.getId() + - ", only one vlan is allowed on guest network"); + } else if (!NetUtils.isSameIsolationId(vlan.getVlanTag(), vlanId)) { + throw new InvalidParameterValueException("there is already one vlan " + vlan.getVlanTag() + " on network :" + +network.getId() + + ", only one vlan is allowed on guest network"); } } sameSubnet = validateIpRange(startIP, endIP, newVlanGateway, newVlanNetmask, vlans, ipv4, ipv6, ip6Gateway, ip6Cidr, startIPv6, endIPv6, network); @@ -2587,24 +2592,23 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati checkOverlapPrivateIpRange(zoneId, startIP, endIP); } - return commitVlan(zoneId, podId, startIP, endIP, newVlanGateway, newVlanNetmask, vlanId, forVirtualNetwork, networkId, physicalNetworkId, startIPv6, endIPv6, - ip6Gateway, ip6Cidr, vlanOwner, network, sameSubnet); + return commitVlan(zoneId, podId, startIP, endIP, newVlanGateway, newVlanNetmask, vlanId, forVirtualNetwork, networkId, physicalNetworkId, startIPv6, endIPv6, ip6Gateway, + ip6Cidr, vlanOwner, network, sameSubnet); } - private Vlan commitVlan(final Long zoneId, final Long podId, final String startIP, final String endIP, final String newVlanGatewayFinal, - final String newVlanNetmaskFinal, final String vlanId, final Boolean forVirtualNetwork, final Long networkId, final Long physicalNetworkId, - final String startIPv6, final String endIPv6, final String ip6Gateway, final String ip6Cidr, final Account vlanOwner, final Network network, - final Pair> sameSubnet) { + private Vlan commitVlan(final Long zoneId, final Long podId, final String startIP, final String endIP, final String newVlanGatewayFinal, final String newVlanNetmaskFinal, + final String vlanId, final Boolean forVirtualNetwork, final Long networkId, final Long physicalNetworkId, final String startIPv6, final String endIPv6, + final String ip6Gateway, final String ip6Cidr, final Account vlanOwner, final Network network, final Pair> sameSubnet) { return Transaction.execute(new TransactionCallback() { @Override public Vlan doInTransaction(TransactionStatus status) { String newVlanNetmask = newVlanNetmaskFinal; String newVlanGateway = newVlanGatewayFinal; - if ((sameSubnet == null || sameSubnet.first() == false) && (network.getTrafficType() == TrafficType.Guest) && - (network.getGuestType() == GuestType.Shared) && (_vlanDao.listVlansByNetworkId(networkId) != null)) { - Map dhcpCapabilities = - _networkSvc.getNetworkOfferingServiceCapabilities(_networkOfferingDao.findById(network.getNetworkOfferingId()), Service.Dhcp); + if ((sameSubnet == null || sameSubnet.first() == false) && (network.getTrafficType() == TrafficType.Guest) && (network.getGuestType() == GuestType.Shared) + && (_vlanDao.listVlansByNetworkId(networkId) != null)) { + Map dhcpCapabilities = _networkSvc.getNetworkOfferingServiceCapabilities(_networkOfferingDao.findById(network.getNetworkOfferingId()), + Service.Dhcp); String supportsMultipleSubnets = dhcpCapabilities.get(Capability.DhcpAccrossMultipleSubnets); if (supportsMultipleSubnets == null || !Boolean.valueOf(supportsMultipleSubnets)) { throw new InvalidParameterValueException("The Dhcp serivice provider for this network dose not support the dhcp across multiple subnets"); @@ -2617,8 +2621,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati newVlanGateway = sameSubnet.second().first(); newVlanNetmask = sameSubnet.second().second(); } - Vlan vlan = - createVlanAndPublicIpRange(zoneId, networkId, physicalNetworkId, forVirtualNetwork, podId, startIP, endIP, newVlanGateway, newVlanNetmask, vlanId, + Vlan vlan = createVlanAndPublicIpRange(zoneId, networkId, physicalNetworkId, forVirtualNetwork, podId, startIP, endIP, newVlanGateway, newVlanNetmask, vlanId, vlanOwner, startIPv6, endIPv6, ip6Gateway, ip6Cidr); // create an entry in the nic_secondary table. This will be the new // gateway that will be configured on the corresponding routervm. @@ -2638,8 +2641,9 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati } } return NetUtils.supersetOrSubset.neitherSubetNorSuperset; - } else if (newVlanGateway == null || newVlanGateway == null) { - throw new InvalidParameterValueException("either both netmask and gateway should be passed or both should me omited."); + } else if (newVlanGateway == null || newVlanNetmask == null) { + throw new InvalidParameterValueException( + "either both netmask and gateway should be passed or both should me omited."); } else { if (!NetUtils.sameSubnet(startIP, newVlanGateway, newVlanNetmask)) { throw new InvalidParameterValueException("The start ip and gateway do not belong to the same subnet"); @@ -2654,8 +2658,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati return (NetUtils.isNetowrkASubsetOrSupersetOfNetworkB(cidrnew, existing_cidr)); } - public Pair> validateIpRange(String startIP, String endIP, String newVlanGateway, String newVlanNetmask, List vlans, - boolean ipv4, boolean ipv6, String ip6Gateway, String ip6Cidr, String startIPv6, String endIPv6, Network network) { + public Pair> validateIpRange(String startIP, String endIP, String newVlanGateway, String newVlanNetmask, List vlans, boolean ipv4, + boolean ipv6, String ip6Gateway, String ip6Cidr, String startIPv6, String endIPv6, Network network) { String vlanGateway = null; String vlanNetmask = null; boolean sameSubnet = false; @@ -2669,8 +2673,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati if (val == NetUtils.supersetOrSubset.isSuperset) { // this means that new cidr is a superset of the // existing subnet. - throw new InvalidParameterValueException("The subnet you are trying to add is a superset of the existing subnet having gateway" + - vlan.getVlanGateway() + " and netmask " + vlan.getVlanNetmask()); + throw new InvalidParameterValueException("The subnet you are trying to add is a superset of the existing subnet having gateway" + vlan.getVlanGateway() + + " and netmask " + vlan.getVlanNetmask()); } else if (val == NetUtils.supersetOrSubset.neitherSubetNorSuperset) { // this implies the user is trying to add a new subnet // which is not a superset or subset of this subnet. @@ -2678,8 +2682,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati continue; } else if (val == NetUtils.supersetOrSubset.isSubset) { // this means he is trying to add to the same subnet. - throw new InvalidParameterValueException("The subnet you are trying to add is a subset of the existing subnet having gateway" + - vlan.getVlanGateway() + " and netmask " + vlan.getVlanNetmask()); + throw new InvalidParameterValueException("The subnet you are trying to add is a subset of the existing subnet having gateway" + vlan.getVlanGateway() + + " and netmask " + vlan.getVlanNetmask()); } else if (val == NetUtils.supersetOrSubset.sameSubnet) { sameSubnet = true; //check if the gateway provided by the user is same as that of the subnet. @@ -2704,8 +2708,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati } } if (newVlanGateway == null && newVlanNetmask == null && sameSubnet == false) { - throw new InvalidParameterValueException( - "The ip range dose not belong to any of the existing subnets, Provide the netmask and gateway if you want to add new subnet"); + throw new InvalidParameterValueException("The ip range dose not belong to any of the existing subnets, Provide the netmask and gateway if you want to add new subnet"); } Pair vlanDetails = null; @@ -2726,7 +2729,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati @Override @DB public Vlan createVlanAndPublicIpRange(long zoneId, long networkId, long physicalNetworkId, boolean forVirtualNetwork, Long podId, String startIP, String endIP, - String vlanGateway, String vlanNetmask, String vlanId, Account vlanOwner, String startIPv6, String endIPv6, String vlanIp6Gateway, String vlanIp6Cidr) { + String vlanGateway, String vlanNetmask, String vlanId, Account vlanOwner, String startIPv6, String endIPv6, String vlanIp6Gateway, String vlanIp6Cidr) { Network network = _networkModel.getNetwork(networkId); boolean ipv4 = false, ipv6 = false; @@ -2768,8 +2771,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati } // pod vlans can be created in basic zone only if (zone.getNetworkType() != NetworkType.Basic || network.getTrafficType() != TrafficType.Guest) { - throw new InvalidParameterValueException("Pod id can be specified only for the networks of type " + TrafficType.Guest + " in zone of type " + - NetworkType.Basic); + throw new InvalidParameterValueException("Pod id can be specified only for the networks of type " + TrafficType.Guest + " in zone of type " + NetworkType.Basic); } } @@ -2789,15 +2791,14 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati if (vlanId != null) { // if vlan is specified, throw an error if it's not equal to // network's vlanId - if (networkVlanId != null && !networkVlanId.equalsIgnoreCase(vlanId)) { + if (networkVlanId != null && !NetUtils.isSameIsolationId(networkVlanId, vlanId)) { throw new InvalidParameterValueException("Vlan doesn't match vlan of the network"); } } else { vlanId = networkVlanId; } } else if (network.getTrafficType() == TrafficType.Public && vlanId == null) { - // vlan id is required for public network - throw new InvalidParameterValueException("Vlan id is required when add ip range to the public network"); + throw new InvalidParameterValueException("Unable to determine vlan id or untagged vlan for public network"); } if (vlanId == null) { @@ -2835,8 +2836,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati String newCidr = NetUtils.getCidrFromGatewayAndNetmask(vlanGateway, vlanNetmask); //Make sure start and end ips are with in the range of cidr calculated for this gateway and netmask { - if (!NetUtils.isIpWithtInCidrRange(vlanGateway, newCidr) || !NetUtils.isIpWithtInCidrRange(startIP, newCidr) || - !NetUtils.isIpWithtInCidrRange(endIP, newCidr)) { + if (!NetUtils.isIpWithtInCidrRange(vlanGateway, newCidr) || !NetUtils.isIpWithtInCidrRange(startIP, newCidr) || !NetUtils.isIpWithtInCidrRange(endIP, newCidr)) { throw new InvalidParameterValueException("Please specify a valid IP range or valid netmask or valid gateway"); } @@ -2846,8 +2846,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati String guestNetworkCidr = zone.getGuestNetworkCidr(); if (guestNetworkCidr != null) { if (NetUtils.isNetworksOverlap(newCidr, guestNetworkCidr)) { - throw new InvalidParameterValueException("The new IP range you have specified has overlapped with the guest network in zone: " + zone.getName() + - ". Please specify a different gateway/netmask."); + throw new InvalidParameterValueException("The new IP range you have specified has overlapped with the guest network in zone: " + zone.getName() + + ". Please specify a different gateway/netmask."); } } @@ -2875,13 +2875,13 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati continue; } // from here, subnet overlaps - if (!vlanId.equals(vlan.getVlanTag())) { - throw new InvalidParameterValueException("The IP range with tag: " + vlan.getVlanTag() + " in zone " + zone.getName() + - " has overlapped with the subnet. Please specify a different gateway/netmask."); + if (!NetUtils.isSameIsolationId(vlanId, vlan.getVlanTag())) { + throw new InvalidParameterValueException("The IP range with tag: " + vlan.getVlanTag() + " in zone " + zone.getName() + + " has overlapped with the subnet. Please specify a different gateway/netmask."); } if (vlan.getNetworkId() != networkId) { - throw new InvalidParameterValueException("This subnet is overlapped with subnet in other network " + vlan.getNetworkId() + " in zone " + - zone.getName() + " . Please specify a different gateway/netmask."); + throw new InvalidParameterValueException("This subnet is overlapped with subnet in other network " + vlan.getNetworkId() + " in zone " + zone.getName() + + " . Please specify a different gateway/netmask."); } String[] otherVlanIpRange = vlan.getIpRange().split("\\-"); @@ -2893,12 +2893,11 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati //extend IP range if (!vlanGateway.equals(otherVlanGateway) || !vlanNetmask.equals(vlan.getVlanNetmask())) { - throw new InvalidParameterValueException("The IP range has already been added with gateway " + otherVlanGateway + " ,and netmask " + - otherVlanNetmask + ", Please specify the gateway/netmask if you want to extend ip range"); + throw new InvalidParameterValueException("The IP range has already been added with gateway " + otherVlanGateway + " ,and netmask " + otherVlanNetmask + + ", Please specify the gateway/netmask if you want to extend ip range"); } if (NetUtils.ipRangesOverlap(startIP, endIP, otherVlanStartIP, otherVlanEndIP)) { - throw new InvalidParameterValueException("The IP range already has IPs that overlap with the new range." - + " Please specify a different start IP/end IP."); + throw new InvalidParameterValueException("The IP range already has IPs that overlap with the new range." + " Please specify a different start IP/end IP."); } } } @@ -2915,15 +2914,15 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati if (vlan.getIp6Gateway() == null) { continue; } - if (vlanId.equals(vlan.getVlanTag())) { + if (NetUtils.isSameIsolationId(vlanId, vlan.getVlanTag())) { if (NetUtils.isIp6RangeOverlap(ipv6Range, vlan.getIp6Range())) { - throw new InvalidParameterValueException("The IPv6 range with tag: " + vlan.getVlanTag() + - " already has IPs that overlap with the new range. Please specify a different start IP/end IP."); + throw new InvalidParameterValueException("The IPv6 range with tag: " + vlan.getVlanTag() + + " already has IPs that overlap with the new range. Please specify a different start IP/end IP."); } if (!vlanIp6Gateway.equals(vlan.getIp6Gateway())) { - throw new InvalidParameterValueException("The IP range with tag: " + vlan.getVlanTag() + " has already been added with gateway " + - vlan.getIp6Gateway() + ". Please specify a different tag."); + throw new InvalidParameterValueException("The IP range with tag: " + vlan.getVlanTag() + " has already been added with gateway " + vlan.getIp6Gateway() + + ". Please specify a different tag."); } } } @@ -2931,8 +2930,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati // Check if the vlan is being used if (_zoneDao.findVnet(zoneId, physicalNetworkId, vlanId).size() > 0) { - throw new InvalidParameterValueException("The VLAN tag " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone " + - zone.getName()); + throw new InvalidParameterValueException("The VLAN tag " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone " + + zone.getName()); } String ipRange = null; @@ -2945,21 +2944,19 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati } // Everything was fine, so persist the VLAN - VlanVO vlan = - commitVlanAndIpRange(zoneId, networkId, physicalNetworkId, podId, startIP, endIP, vlanGateway, vlanNetmask, vlanId, vlanOwner, vlanIp6Gateway, vlanIp6Cidr, + VlanVO vlan = commitVlanAndIpRange(zoneId, networkId, physicalNetworkId, podId, startIP, endIP, vlanGateway, vlanNetmask, vlanId, vlanOwner, vlanIp6Gateway, vlanIp6Cidr, ipv4, zone, vlanType, ipv6Range, ipRange); return vlan; } - private VlanVO commitVlanAndIpRange(final long zoneId, final long networkId, final long physicalNetworkId, final Long podId, final String startIP, - final String endIP, final String vlanGateway, final String vlanNetmask, final String vlanId, final Account vlanOwner, final String vlanIp6Gateway, - final String vlanIp6Cidr, final boolean ipv4, final DataCenterVO zone, final VlanType vlanType, final String ipv6Range, final String ipRange) { + private VlanVO commitVlanAndIpRange(final long zoneId, final long networkId, final long physicalNetworkId, final Long podId, final String startIP, final String endIP, + final String vlanGateway, final String vlanNetmask, final String vlanId, final Account vlanOwner, final String vlanIp6Gateway, final String vlanIp6Cidr, + final boolean ipv4, final DataCenterVO zone, final VlanType vlanType, final String ipv6Range, final String ipRange) { return Transaction.execute(new TransactionCallback() { @Override public VlanVO doInTransaction(TransactionStatus status) { - VlanVO vlan = - new VlanVO(vlanType, vlanId, vlanGateway, vlanNetmask, zone.getId(), ipRange, networkId, physicalNetworkId, vlanIp6Gateway, vlanIp6Cidr, ipv6Range); + VlanVO vlan = new VlanVO(vlanType, vlanId, vlanGateway, vlanNetmask, zone.getId(), ipRange, networkId, physicalNetworkId, vlanIp6Gateway, vlanIp6Cidr, ipv6Range); s_logger.debug("Saving vlan range " + vlan); vlan = _vlanDao.persist(vlan); @@ -2981,8 +2978,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati // range List ips = _publicIpAddressDao.listByVlanId(vlan.getId()); for (IPAddressVO ip : ips) { - UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_IP_ASSIGN, vlanOwner.getId(), ip.getDataCenterId(), ip.getId(), - ip.getAddress().toString(), ip.isSourceNat(), vlan.getVlanType().toString(), ip.getSystem(), ip.getClass().getName(), ip.getUuid()); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_IP_ASSIGN, vlanOwner.getId(), ip.getDataCenterId(), ip.getId(), ip.getAddress().toString(), + ip.isSourceNat(), vlan.getVlanType().toString(), ip.getSystem(), ip.getClass().getName(), ip.getUuid()); } // increment resource count for dedicated public ip's _resourceLimitMgr.incrementResourceCount(vlanOwner.getId(), ResourceType.public_ip, new Long(ips.size())); @@ -3030,19 +3027,19 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati } for (IPAddressVO ip : ips) { if (ip.isOneToOneNat()) { - throw new InvalidParameterValueException("Can't delete account specific vlan " + vlanDbId + " as ip " + ip + - " belonging to the range is used for static nat purposes. Cleanup the rules first"); + throw new InvalidParameterValueException("Can't delete account specific vlan " + vlanDbId + " as ip " + ip + + " belonging to the range is used for static nat purposes. Cleanup the rules first"); } if (ip.isSourceNat()) { - throw new InvalidParameterValueException("Can't delete account specific vlan " + vlanDbId + " as ip " + ip + - " belonging to the range is a source nat ip for the network id=" + ip.getSourceNetworkId() + - ". IP range with the source nat ip address can be removed either as a part of Network, or account removal"); + throw new InvalidParameterValueException("Can't delete account specific vlan " + vlanDbId + " as ip " + ip + + " belonging to the range is a source nat ip for the network id=" + ip.getSourceNetworkId() + + ". IP range with the source nat ip address can be removed either as a part of Network, or account removal"); } if (_firewallDao.countRulesByIpId(ip.getId()) > 0) { - throw new InvalidParameterValueException("Can't delete account specific vlan " + vlanDbId + " as ip " + ip + - " belonging to the range has firewall rules applied. Cleanup the rules first"); + throw new InvalidParameterValueException("Can't delete account specific vlan " + vlanDbId + " as ip " + ip + + " belonging to the range has firewall rules applied. Cleanup the rules first"); } // release public ip address here success = success && _ipAddrMgr.disassociatePublicIpAddress(ip.getId(), userId, caller); @@ -3051,8 +3048,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati s_logger.warn("Some ip addresses failed to be released as a part of vlan " + vlanDbId + " removal"); } else { for (IPAddressVO ip : ips) { - UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_IP_RELEASE, acctVln.get(0).getId(), ip.getDataCenterId(), ip.getId(), ip.getAddress() - .toString(), ip.isSourceNat(), vlanRange.getVlanType().toString(), ip.getSystem(), ip.getClass().getName(), ip.getUuid()); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_IP_RELEASE, acctVln.get(0).getId(), ip.getDataCenterId(), ip.getId(), + ip.getAddress().toString(), ip.isSourceNat(), vlanRange.getVlanType().toString(), ip.getSystem(), ip.getClass().getName(), ip.getUuid()); } } } finally { @@ -3062,8 +3059,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati NicIpAliasVO ipAlias = _nicIpAliasDao.findByGatewayAndNetworkIdAndState(vlanRange.getVlanGateway(), vlanRange.getNetworkId(), NicIpAlias.state.active); //check if the ipalias belongs to the vlan range being deleted. if (ipAlias != null && vlanDbId == _publicIpAddressDao.findByIpAndSourceNetworkId(vlanRange.getNetworkId(), ipAlias.getIp4Address()).getVlanId()) { - throw new InvalidParameterValueException("Cannot delete vlan range " + vlanDbId + " as " + ipAlias.getIp4Address() + - "is being used for providing dhcp service in this subnet. Delete all VMs in this subnet and try again"); + throw new InvalidParameterValueException("Cannot delete vlan range " + vlanDbId + " as " + ipAlias.getIp4Address() + + "is being used for providing dhcp service in this subnet. Delete all VMs in this subnet and try again"); } allocIpCount = _publicIpAddressDao.countIPs(vlanRange.getDataCenterId(), vlanDbId, true); if (allocIpCount > 0) { @@ -3158,8 +3155,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati // generate usage event for dedication of every ip address in the range for (IPAddressVO ip : ips) { - UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_IP_ASSIGN, vlanOwner.getId(), ip.getDataCenterId(), ip.getId(), ip.getAddress().toString(), - ip.isSourceNat(), vlan.getVlanType().toString(), ip.getSystem(), ip.getClass().getName(), ip.getUuid()); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_IP_ASSIGN, vlanOwner.getId(), ip.getDataCenterId(), ip.getId(), ip.getAddress().toString(), ip.isSourceNat(), + vlan.getVlanType().toString(), ip.getSystem(), ip.getClass().getName(), ip.getUuid()); } // increment resource count for dedicated public ip's @@ -3229,8 +3226,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati // generate usage events to remove dedication for every ip in the range that has been disassociated for (IPAddressVO ip : ips) { if (!ipsInUse.contains(ip)) { - UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_IP_RELEASE, acctVln.get(0).getAccountId(), ip.getDataCenterId(), ip.getId(), ip.getAddress() - .toString(), ip.isSourceNat(), vlan.getVlanType().toString(), ip.getSystem(), ip.getClass().getName(), ip.getUuid()); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_IP_RELEASE, acctVln.get(0).getAccountId(), ip.getDataCenterId(), ip.getId(), ip.getAddress().toString(), + ip.isSourceNat(), vlan.getVlanType().toString(), ip.getSystem(), ip.getClass().getName(), ip.getUuid()); } } // decrement resource count for dedicated public ip's @@ -3293,15 +3290,15 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati private void checkConflictsWithPortableIpRange(long zoneId, String vlanId, String vlanGateway, String vlanNetmask, String startIP, String endIP) { // check and throw exception if there is portable IP range that overlaps with public ip range being configured if (checkOverlapPortableIpRange(_regionDao.getRegionId(), startIP, endIP)) { - throw new InvalidParameterValueException("Ip range: " + startIP + "-" + endIP + " overlaps with a portable" + " IP range already configured in the region " + - _regionDao.getRegionId()); + throw new InvalidParameterValueException("Ip range: " + startIP + "-" + endIP + " overlaps with a portable" + " IP range already configured in the region " + + _regionDao.getRegionId()); } // verify and throw exception if the VLAN Id is used by any portable IP range List existingPortableIPRanges = _portableIpRangeDao.listByRegionId(_regionDao.getRegionId()); if (existingPortableIPRanges != null && !existingPortableIPRanges.isEmpty()) { for (PortableIpRangeVO portableIpRange : existingPortableIPRanges) { - if (portableIpRange.getVlanTag().equalsIgnoreCase(vlanId)) { + if (NetUtils.isSameIsolationId(portableIpRange.getVlanTag(), vlanId)) { throw new InvalidParameterValueException("The VLAN tag " + vlanId + " is already being used for portable ip range in this region"); } } @@ -3376,10 +3373,14 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati if (cidrSubnet.equals(guestSubnet)) { if (podName.equals("newPod")) { throw new InvalidParameterValueException( - "The subnet of the pod you are adding conflicts with the subnet of the Guest IP Network. Please specify a different CIDR."); + "The subnet of the pod you are adding conflicts with the subnet of the Guest IP Network. Please specify a different CIDR."); } else { - throw new InvalidParameterValueException("Warning: The subnet of pod " + podName + " in zone " + zoneName + - " conflicts with the subnet of the Guest IP Network. Please change either the pod's CIDR or the Guest IP Network's subnet, and re-run install-vmops-management."); + throw new InvalidParameterValueException( + "Warning: The subnet of pod " + + podName + + " in zone " + + zoneName + + " conflicts with the subnet of the Guest IP Network. Please change either the pod's CIDR or the Guest IP Network's subnet, and re-run install-vmops-management."); } } } @@ -3407,11 +3408,11 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati if (cidrSubnet.equals(otherCidrSubnet)) { String otherPodName = getPodName(otherPodId.longValue()); if (podName.equals("newPod")) { - throw new InvalidParameterValueException("The subnet of the pod you are adding conflicts with the subnet of pod " + otherPodName + " in zone " + - zoneName + ". Please specify a different CIDR."); + throw new InvalidParameterValueException("The subnet of the pod you are adding conflicts with the subnet of pod " + otherPodName + " in zone " + zoneName + + ". Please specify a different CIDR."); } else { - throw new InvalidParameterValueException("Warning: The pods " + podName + " and " + otherPodName + " in zone " + zoneName + - " have conflicting CIDR subnets. Please change the CIDR of one of these pods."); + throw new InvalidParameterValueException("Warning: The pods " + podName + " and " + otherPodName + " in zone " + zoneName + + " have conflicting CIDR subnets. Please change the CIDR of one of these pods."); } } } @@ -3628,8 +3629,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati // Allow to specify more than 1 provider per service only if // the service is LB if (!serviceStr.equalsIgnoreCase(Service.Lb.getName()) && svcPrv.get(serviceStr) != null && svcPrv.get(serviceStr).size() > 1) { - throw new InvalidParameterValueException("In the current release only one provider can be " - + "specified for the service if the service is not LB"); + throw new InvalidParameterValueException("In the current release only one provider can be " + "specified for the service if the service is not LB"); } for (String prvNameStr : svcPrv.get(serviceStr)) { // check if provider is supported @@ -3718,10 +3718,10 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati Set firewallProviderSet = new HashSet(); firewallProviderSet.add(firewallProvider); serviceProviderMap.put(Service.Firewall, firewallProviderSet); - if (!(firewallProvider.getName().equals(Provider.JuniperSRX.getName()) || firewallProvider.getName().equals(Provider.PaloAlto.getName()) || firewallProvider.getName().equals(Provider.VirtualRouter.getName())) && - egressDefaultPolicy == false) { - throw new InvalidParameterValueException("Firewall egress with default policy " + egressDefaultPolicy + " is not supported by the provider " + - firewallProvider.getName()); + if (!(firewallProvider.getName().equals(Provider.JuniperSRX.getName()) || firewallProvider.getName().equals(Provider.PaloAlto.getName()) || firewallProvider.getName() + .equals(Provider.VirtualRouter.getName())) && egressDefaultPolicy == false) { + throw new InvalidParameterValueException("Firewall egress with default policy " + egressDefaultPolicy + " is not supported by the provider " + + firewallProvider.getName()); } } @@ -3742,8 +3742,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati } } - NetworkOffering offering = - createNetworkOffering(name, displayText, trafficType, tags, specifyVlan, availability, networkRate, serviceProviderMap, false, guestType, false, + NetworkOffering offering = createNetworkOffering(name, displayText, trafficType, tags, specifyVlan, availability, networkRate, serviceProviderMap, false, guestType, false, serviceOfferingId, conserveMode, serviceCapabilityMap, specifyIpRanges, isPersistent, details, egressDefaultPolicy, maxconn, enableKeepAlive); CallContext.current().setEventDetails(" Id: " + offering.getId() + " Name: " + name); return offering; @@ -3752,8 +3751,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati void validateLoadBalancerServiceCapabilities(Map lbServiceCapabilityMap) { if (lbServiceCapabilityMap != null && !lbServiceCapabilityMap.isEmpty()) { if (lbServiceCapabilityMap.keySet().size() > 3 || !lbServiceCapabilityMap.containsKey(Capability.SupportedLBIsolation)) { - throw new InvalidParameterValueException("Only " + Capability.SupportedLBIsolation.getName() + ", " + Capability.ElasticLb.getName() + ", " + - Capability.InlineMode.getName() + " capabilities can be sepcified for LB service"); + throw new InvalidParameterValueException("Only " + Capability.SupportedLBIsolation.getName() + ", " + Capability.ElasticLb.getName() + ", " + + Capability.InlineMode.getName() + " capabilities can be sepcified for LB service"); } for (Capability cap : lbServiceCapabilityMap.keySet()) { @@ -3783,8 +3782,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati throw new InvalidParameterValueException("Unknown specified value for " + Capability.LbSchemes.getName()); } } else { - throw new InvalidParameterValueException("Only " + Capability.SupportedLBIsolation.getName() + ", " + Capability.ElasticLb.getName() + ", " + - Capability.InlineMode.getName() + ", " + Capability.LbSchemes.getName() + " capabilities can be sepcified for LB service"); + throw new InvalidParameterValueException("Only " + Capability.SupportedLBIsolation.getName() + ", " + Capability.ElasticLb.getName() + ", " + + Capability.InlineMode.getName() + ", " + Capability.LbSchemes.getName() + " capabilities can be sepcified for LB service"); } } } @@ -3793,8 +3792,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati void validateSourceNatServiceCapablities(Map sourceNatServiceCapabilityMap) { if (sourceNatServiceCapabilityMap != null && !sourceNatServiceCapabilityMap.isEmpty()) { if (sourceNatServiceCapabilityMap.keySet().size() > 2) { - throw new InvalidParameterValueException("Only " + Capability.SupportedSourceNatTypes.getName() + " and " + Capability.RedundantRouter + - " capabilities can be sepcified for source nat service"); + throw new InvalidParameterValueException("Only " + Capability.SupportedSourceNatTypes.getName() + " and " + Capability.RedundantRouter + + " capabilities can be sepcified for source nat service"); } for (Capability capability : sourceNatServiceCapabilityMap.keySet()) { @@ -3803,8 +3802,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati boolean perAccount = value.contains("peraccount"); boolean perZone = value.contains("perzone"); if ((perAccount && perZone) || (!perAccount && !perZone)) { - throw new InvalidParameterValueException("Either peraccount or perzone source NAT type can be specified for " + - Capability.SupportedSourceNatTypes.getName()); + throw new InvalidParameterValueException("Either peraccount or perzone source NAT type can be specified for " + + Capability.SupportedSourceNatTypes.getName()); } } else if (capability == Capability.RedundantRouter) { boolean enabled = value.contains("true"); @@ -3813,8 +3812,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati throw new InvalidParameterValueException("Unknown specified value for " + Capability.RedundantRouter.getName()); } } else { - throw new InvalidParameterValueException("Only " + Capability.SupportedSourceNatTypes.getName() + " and " + Capability.RedundantRouter + - " capabilities can be sepcified for source nat service"); + throw new InvalidParameterValueException("Only " + Capability.SupportedSourceNatTypes.getName() + " and " + Capability.RedundantRouter + + " capabilities can be sepcified for source nat service"); } } } @@ -3834,13 +3833,13 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati } else if (capability == Capability.AssociatePublicIP) { associatePublicIP = value.contains("true"); } else { - throw new InvalidParameterValueException("Only " + Capability.ElasticIp.getName() + " and " + Capability.AssociatePublicIP.getName() + - " capabilitiy can be sepcified for static nat service"); + throw new InvalidParameterValueException("Only " + Capability.ElasticIp.getName() + " and " + Capability.AssociatePublicIP.getName() + + " capabilitiy can be sepcified for static nat service"); } } if ((!eipEnabled) && associatePublicIP) { - throw new InvalidParameterValueException("Capability " + Capability.AssociatePublicIP.getName() + " can only be set when capability " + - Capability.ElasticIp.getName() + " is true"); + throw new InvalidParameterValueException("Capability " + Capability.AssociatePublicIP.getName() + " can only be set when capability " + + Capability.ElasticIp.getName() + " is true"); } } } @@ -3848,9 +3847,9 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati @Override @DB public NetworkOfferingVO createNetworkOffering(String name, String displayText, TrafficType trafficType, String tags, boolean specifyVlan, Availability availability, - Integer networkRate, final Map> serviceProviderMap, boolean isDefault, Network.GuestType type, boolean systemOnly, Long serviceOfferingId, - boolean conserveMode, Map> serviceCapabilityMap, boolean specifyIpRanges, boolean isPersistent, - final Map details, boolean egressDefaultPolicy, final Integer maxconn, final boolean enableKeepAlive) { + Integer networkRate, final Map> serviceProviderMap, boolean isDefault, Network.GuestType type, boolean systemOnly, Long serviceOfferingId, + boolean conserveMode, Map> serviceCapabilityMap, boolean specifyIpRanges, boolean isPersistent, + final Map details, boolean egressDefaultPolicy, final Integer maxconn, final boolean enableKeepAlive) { String multicastRateStr = _configDao.getValue("multicast.throttling.rate"); int multicastRate = ((multicastRateStr == null) ? 10 : Integer.parseInt(multicastRateStr)); @@ -3885,15 +3884,14 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati if (availability == NetworkOffering.Availability.Required) { boolean canOffBeRequired = (type == GuestType.Isolated && serviceProviderMap.containsKey(Service.SourceNat)); if (!canOffBeRequired) { - throw new InvalidParameterValueException("Availability can be " + NetworkOffering.Availability.Required + " only for networkOfferings of type " + - GuestType.Isolated + " and with " + Service.SourceNat.getName() + " enabled"); + throw new InvalidParameterValueException("Availability can be " + NetworkOffering.Availability.Required + " only for networkOfferings of type " + + GuestType.Isolated + " and with " + Service.SourceNat.getName() + " enabled"); } // only one network offering in the system can be Required List offerings = _networkOfferingDao.listByAvailability(Availability.Required, false); if (!offerings.isEmpty()) { - throw new InvalidParameterValueException("System already has network offering id=" + offerings.get(0).getId() + " with availability " + - Availability.Required); + throw new InvalidParameterValueException("System already has network offering id=" + offerings.get(0).getId() + " with availability " + Availability.Required); } } @@ -3951,8 +3949,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati if ((sourceNatServiceCapabilityMap != null) && (!sourceNatServiceCapabilityMap.isEmpty())) { String sourceNatType = sourceNatServiceCapabilityMap.get(Capability.SupportedSourceNatTypes); if (sourceNatType != null) { - _networkModel.checkCapabilityForProvider(serviceProviderMap.get(Service.SourceNat), Service.SourceNat, Capability.SupportedSourceNatTypes, - sourceNatType); + _networkModel.checkCapabilityForProvider(serviceProviderMap.get(Service.SourceNat), Service.SourceNat, Capability.SupportedSourceNatTypes, sourceNatType); sharedSourceNat = sourceNatType.contains("perzone"); } @@ -3981,10 +3978,9 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati publicLb = true; } - final NetworkOfferingVO offeringFinal = - new NetworkOfferingVO(name, displayText, trafficType, systemOnly, specifyVlan, networkRate, multicastRate, isDefault, availability, tags, type, conserveMode, - dedicatedLb, sharedSourceNat, redundantRouter, elasticIp, elasticLb, specifyIpRanges, inline, isPersistent, associatePublicIp, publicLb, internalLb, - egressDefaultPolicy); + final NetworkOfferingVO offeringFinal = new NetworkOfferingVO(name, displayText, trafficType, systemOnly, specifyVlan, networkRate, multicastRate, isDefault, availability, + tags, type, conserveMode, dedicatedLb, sharedSourceNat, redundantRouter, elasticIp, elasticLb, specifyIpRanges, inline, isPersistent, associatePublicIp, publicLb, + internalLb, egressDefaultPolicy); if (serviceOfferingId != null) { offeringFinal.setServiceOfferingId(serviceOfferingId); @@ -4059,8 +4055,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati } if (lbProvider == null) { - throw new InvalidParameterValueException("Invalid value " + details.get(detail) + " for the detail " + detail + - ". The provider is not supported by the network offering"); + throw new InvalidParameterValueException("Invalid value " + details.get(detail) + " for the detail " + detail + + ". The provider is not supported by the network offering"); } // 2) validate if the provider supports the scheme @@ -4326,8 +4322,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati // though) int networkCount = _networkDao.getNetworkCountByNetworkOffId(offeringId); if (networkCount > 0) { - throw new InvalidParameterValueException("Can't delete network offering " + offeringId + " as its used by " + networkCount + " networks. " + - "To make the network offering unavaiable, disable it"); + throw new InvalidParameterValueException("Can't delete network offering " + offeringId + " as its used by " + networkCount + " networks. " + + "To make the network offering unavaiable, disable it"); } if (_networkOfferingDao.remove(offeringId)) { @@ -4399,19 +4395,18 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati throw new InvalidParameterValueException("Invalid value for Availability. Supported types: " + Availability.Required + ", " + Availability.Optional); } else { if (availability == NetworkOffering.Availability.Required) { - boolean canOffBeRequired = - (offeringToUpdate.getGuestType() == GuestType.Isolated && _networkModel.areServicesSupportedByNetworkOffering(offeringToUpdate.getId(), - Service.SourceNat)); + boolean canOffBeRequired = (offeringToUpdate.getGuestType() == GuestType.Isolated && _networkModel.areServicesSupportedByNetworkOffering( + offeringToUpdate.getId(), Service.SourceNat)); if (!canOffBeRequired) { - throw new InvalidParameterValueException("Availability can be " + NetworkOffering.Availability.Required + " only for networkOfferings of type " + - GuestType.Isolated + " and with " + Service.SourceNat.getName() + " enabled"); + throw new InvalidParameterValueException("Availability can be " + NetworkOffering.Availability.Required + " only for networkOfferings of type " + + GuestType.Isolated + " and with " + Service.SourceNat.getName() + " enabled"); } // only one network offering in the system can be Required List offerings = _networkOfferingDao.listByAvailability(Availability.Required, false); if (!offerings.isEmpty() && offerings.get(0).getId() != offeringToUpdate.getId()) { - throw new InvalidParameterValueException("System already has network offering id=" + offerings.get(0).getId() + " with availability " + - Availability.Required); + throw new InvalidParameterValueException("System already has network offering id=" + offerings.get(0).getId() + " with availability " + + Availability.Required); } } offering.setAvailability(availability); @@ -4651,17 +4646,16 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati if (!NetUtils.sameSubnet(startIP, gateway, netmask)) { throw new InvalidParameterValueException("Please ensure that your start IP is in the same subnet as " - + "your portable IP range's gateway and as per the IP range's netmask."); + + "your portable IP range's gateway and as per the IP range's netmask."); } if (!NetUtils.sameSubnet(endIP, gateway, netmask)) { throw new InvalidParameterValueException("Please ensure that your end IP is in the same subnet as " - + "your portable IP range's gateway and as per the IP range's netmask."); + + "your portable IP range's gateway and as per the IP range's netmask."); } if (checkOverlapPortableIpRange(regionId, startIP, endIP)) { - throw new InvalidParameterValueException("Ip range: " + startIP + "-" + endIP + " overlaps with a portable" + " IP range already configured in the region " + - regionId); + throw new InvalidParameterValueException("Ip range: " + startIP + "-" + endIP + " overlaps with a portable" + " IP range already configured in the region " + regionId); } if (vlanId == null) { @@ -4676,8 +4670,8 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati for (DataCenterVO zone : zones) { // check if there is zone vlan with same id if (_vlanDao.findByZoneAndVlanId(zone.getId(), vlanId) != null) - throw new InvalidParameterValueException("Found a VLAN id " + vlanId + " already existing in" + " zone " + zone.getUuid() + - " that conflicts with VLAN id of the portable ip range being configured"); + throw new InvalidParameterValueException("Found a VLAN id " + vlanId + " already existing in" + " zone " + zone.getUuid() + + " that conflicts with VLAN id of the portable ip range being configured"); //check if there is a public ip range that overlaps with portable ip range being created checkOverlapPublicIpRange(zone.getId(), startIP, endIP); } diff --git a/server/src/com/cloud/configuration/ZoneConfig.java b/server/src/com/cloud/configuration/ZoneConfig.java index 3756e5985f2..62bf57eaffd 100644 --- a/server/src/com/cloud/configuration/ZoneConfig.java +++ b/server/src/com/cloud/configuration/ZoneConfig.java @@ -35,13 +35,13 @@ public enum ZoneConfig { private final String _description; private final String _range; - private static final List _zoneConfigKeys = new ArrayList(); + private static final List ZoneConfigKeys = new ArrayList(); static { // Add keys into List for (ZoneConfig c : ZoneConfig.values()) { String key = c.key(); - _zoneConfigKeys.add(key); + ZoneConfigKeys.add(key); } } @@ -79,7 +79,7 @@ public enum ZoneConfig { } public static boolean doesKeyExist(String key) { - return _zoneConfigKeys.contains(key); + return ZoneConfigKeys.contains(key); } } diff --git a/server/src/com/cloud/consoleproxy/AgentBasedConsoleProxyManager.java b/server/src/com/cloud/consoleproxy/AgentBasedConsoleProxyManager.java index 0f4b27a40b6..3a1c387c344 100755 --- a/server/src/com/cloud/consoleproxy/AgentBasedConsoleProxyManager.java +++ b/server/src/com/cloud/consoleproxy/AgentBasedConsoleProxyManager.java @@ -25,6 +25,8 @@ import javax.naming.ConfigurationException; import org.apache.log4j.Logger; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; +import org.apache.cloudstack.framework.security.keys.KeysManager; +import org.apache.cloudstack.framework.security.keystore.KeystoreManager; import com.cloud.agent.AgentManager; import com.cloud.agent.api.GetVncPortAnswer; @@ -33,7 +35,6 @@ import com.cloud.agent.api.StartupProxyCommand; import com.cloud.host.HostVO; import com.cloud.host.dao.HostDao; import com.cloud.info.ConsoleProxyInfo; -import com.cloud.keystore.KeystoreManager; import com.cloud.server.ManagementServer; import com.cloud.utils.NumbersUtil; import com.cloud.utils.component.ManagerBase; @@ -53,7 +54,6 @@ public class AgentBasedConsoleProxyManager extends ManagerBase implements Consol protected HostDao _hostDao; @Inject protected UserVmDao _userVmDao; - private String _instance; protected String _consoleProxyUrlDomain; @Inject private VMInstanceDao _instanceDao; @@ -74,11 +74,13 @@ public class AgentBasedConsoleProxyManager extends ManagerBase implements Consol ConfigurationDao _configDao; @Inject ManagementServer _ms; + @Inject + KeysManager _keysMgr; public class AgentBasedAgentHook extends AgentHookBase { - public AgentBasedAgentHook(VMInstanceDao instanceDao, HostDao hostDao, ConfigurationDao cfgDao, KeystoreManager ksMgr, AgentManager agentMgr, ManagementServer ms) { - super(instanceDao, hostDao, cfgDao, ksMgr, agentMgr, ms); + public AgentBasedAgentHook(VMInstanceDao instanceDao, HostDao hostDao, ConfigurationDao cfgDao, KeystoreManager ksMgr, AgentManager agentMgr, KeysManager keysMgr) { + super(instanceDao, hostDao, cfgDao, ksMgr, agentMgr, keysMgr); } @Override @@ -119,11 +121,9 @@ public class AgentBasedConsoleProxyManager extends ManagerBase implements Consol _sslEnabled = true; } - _instance = configs.get("instance.name"); - _consoleProxyUrlDomain = configs.get("consoleproxy.url.domain"); - _listener = new ConsoleProxyListener(new AgentBasedAgentHook(_instanceDao, _hostDao, _configDao, _ksMgr, _agentMgr, _ms)); + _listener = new ConsoleProxyListener(new AgentBasedAgentHook(_instanceDao, _hostDao, _configDao, _ksMgr, _agentMgr, _keysMgr)); _agentMgr.registerForHostEvents(_listener, true, true, false); if (s_logger.isInfoEnabled()) { diff --git a/server/src/com/cloud/consoleproxy/AgentHookBase.java b/server/src/com/cloud/consoleproxy/AgentHookBase.java index 62777f5b405..2e0bada3abb 100644 --- a/server/src/com/cloud/consoleproxy/AgentHookBase.java +++ b/server/src/com/cloud/consoleproxy/AgentHookBase.java @@ -26,6 +26,8 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; +import org.apache.cloudstack.framework.security.keys.KeysManager; +import org.apache.cloudstack.framework.security.keystore.KeystoreManager; import com.cloud.agent.AgentManager; import com.cloud.agent.api.AgentControlAnswer; @@ -44,11 +46,10 @@ import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.Status; import com.cloud.host.dao.HostDao; -import com.cloud.keystore.KeystoreManager; -import com.cloud.server.ManagementServer; import com.cloud.servlet.ConsoleProxyPasswordBasedEncryptor; import com.cloud.servlet.ConsoleProxyServlet; import com.cloud.utils.Ternary; +import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.VirtualMachine; import com.cloud.vm.dao.VMInstanceDao; @@ -65,17 +66,16 @@ public abstract class AgentHookBase implements AgentHook { ConfigurationDao _configDao; AgentManager _agentMgr; KeystoreManager _ksMgr; - ManagementServer _ms; final Random _random = new Random(System.currentTimeMillis()); - private String _hashKey; + KeysManager _keysMgr; - public AgentHookBase(VMInstanceDao instanceDao, HostDao hostDao, ConfigurationDao cfgDao, KeystoreManager ksMgr, AgentManager agentMgr, ManagementServer ms) { - this._instanceDao = instanceDao; - this._hostDao = hostDao; - this._agentMgr = agentMgr; - this._configDao = cfgDao; - this._ksMgr = ksMgr; - this._ms = ms; + public AgentHookBase(VMInstanceDao instanceDao, HostDao hostDao, ConfigurationDao cfgDao, KeystoreManager ksMgr, AgentManager agentMgr, KeysManager keysMgr) { + _instanceDao = instanceDao; + _hostDao = hostDao; + _agentMgr = agentMgr; + _configDao = cfgDao; + _ksMgr = ksMgr; + _keysMgr = keysMgr; } @Override @@ -193,7 +193,9 @@ public abstract class AgentHookBase implements AgentHook { assert (ksBits != null); if (ksBits == null) { - s_logger.error("Could not find and construct a valid SSL certificate"); + String msg = "Could not find and construct a valid SSL certificate"; + s_logger.error(msg); + throw new CloudRuntimeException(msg); } cmd = new StartConsoleProxyAgentHttpHandlerCommand(ksBits, storePassword); cmd.setEncryptorPassword(getEncryptorPassword()); @@ -230,15 +232,15 @@ public abstract class AgentHookBase implements AgentHook { // if we failed after reset, something is definitely wrong for (int i = 0; i < 2; i++) { - key = _ms.getEncryptionKey(); - iv = _ms.getEncryptionIV(); + key = _keysMgr.getEncryptionKey(); + iv = _keysMgr.getEncryptionIV(); keyIvPair = new ConsoleProxyPasswordBasedEncryptor.KeyIVPair(key, iv); if (keyIvPair.getIvBytes() == null || keyIvPair.getIvBytes().length != 16 || keyIvPair.getKeyBytes() == null || keyIvPair.getKeyBytes().length != 16) { s_logger.warn("Console access AES KeyIV sanity check failed, reset and regenerate"); - _ms.resetEncryptionKeyIV(); + _keysMgr.resetEncryptionKeyIV(); } else { break; } diff --git a/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java b/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java index f6e742f8eb1..813888707a3 100755 --- a/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java +++ b/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java @@ -17,6 +17,7 @@ package com.cloud.consoleproxy; import java.nio.charset.Charset; +import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.Iterator; @@ -28,18 +29,19 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; -import org.apache.log4j.Logger; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - +import org.apache.cloudstack.config.ApiServiceConfiguration; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; +import org.apache.cloudstack.framework.security.keys.KeysManager; +import org.apache.cloudstack.framework.security.keystore.KeystoreDao; +import org.apache.cloudstack.framework.security.keystore.KeystoreManager; +import org.apache.cloudstack.framework.security.keystore.KeystoreVO; import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreDao; import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO; +import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; @@ -51,7 +53,6 @@ import com.cloud.agent.api.check.CheckSshAnswer; import com.cloud.agent.api.check.CheckSshCommand; import com.cloud.agent.api.proxy.ConsoleProxyLoadAnswer; import com.cloud.agent.manager.Commands; -import com.cloud.certificate.dao.CertificateDao; import com.cloud.cluster.ClusterManager; import com.cloud.configuration.Config; import com.cloud.configuration.ZoneConfig; @@ -80,9 +81,6 @@ import com.cloud.info.ConsoleProxyStatus; import com.cloud.info.RunningHostCountInfo; import com.cloud.info.RunningHostInfoAgregator; import com.cloud.info.RunningHostInfoAgregator.ZoneHostInfo; -import com.cloud.keystore.KeystoreDao; -import com.cloud.keystore.KeystoreManager; -import com.cloud.keystore.KeystoreVO; import com.cloud.network.Network; import com.cloud.network.NetworkModel; import com.cloud.network.Networks.TrafficType; @@ -99,16 +97,13 @@ import com.cloud.resource.ResourceManager; import com.cloud.resource.ResourceStateAdapter; import com.cloud.resource.ServerResource; import com.cloud.resource.UnableDeleteHostException; -import com.cloud.server.ManagementServer; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; -import com.cloud.storage.StorageManager; import com.cloud.storage.StoragePoolStatus; import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; import com.cloud.storage.VMTemplateVO; import com.cloud.storage.dao.DiskOfferingDao; import com.cloud.storage.dao.VMTemplateDao; -import com.cloud.template.TemplateManager; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.utils.DateUtil; @@ -141,6 +136,8 @@ import com.cloud.vm.VirtualMachineProfile; import com.cloud.vm.dao.ConsoleProxyDao; import com.cloud.vm.dao.UserVmDetailsDao; import com.cloud.vm.dao.VMInstanceDao; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; // // Possible console proxy state transition cases @@ -165,7 +162,7 @@ public class ConsoleProxyManagerImpl extends ManagerBase implements ConsoleProxy private int _consoleProxyPort = ConsoleProxyManager.DEFAULT_PROXY_VNC_PORT; - private int _mgmt_port = 8250; + private int _mgmtPort = 8250; private List _consoleProxyAllocators; @@ -182,57 +179,44 @@ public class ConsoleProxyManagerImpl extends ManagerBase implements ConsoleProxy @Inject private ConfigurationDao _configDao; @Inject - private CertificateDao _certDao; - @Inject private VMInstanceDao _instanceDao; @Inject private TemplateDataStoreDao _vmTemplateStoreDao; @Inject private AgentManager _agentMgr; @Inject - private StorageManager _storageMgr; + private NetworkOrchestrationService _networkMgr; @Inject - NetworkOrchestrationService _networkMgr; + private NetworkModel _networkModel; @Inject - NetworkModel _networkModel; + private AccountManager _accountMgr; @Inject - AccountManager _accountMgr; + private ServiceOfferingDao _offeringDao; @Inject - ServiceOfferingDao _offeringDao; + private DiskOfferingDao _diskOfferingDao; @Inject - DiskOfferingDao _diskOfferingDao; + private NetworkOfferingDao _networkOfferingDao; @Inject - NetworkOfferingDao _networkOfferingDao; + private PrimaryDataStoreDao _storagePoolDao; @Inject - PrimaryDataStoreDao _storagePoolDao; + private UserVmDetailsDao _vmDetailsDao; @Inject - UserVmDetailsDao _vmDetailsDao; + private ResourceManager _resourceMgr; @Inject - ResourceManager _resourceMgr; + private NetworkDao _networkDao; @Inject - NetworkDao _networkDao; + private RulesManager _rulesMgr; @Inject - RulesManager _rulesMgr; + private IPAddressDao _ipAddressDao; @Inject - TemplateManager templateMgr; + private KeysManager _keysMgr; @Inject - IPAddressDao _ipAddressDao; - @Inject - ManagementServer _ms; - @Inject - ClusterManager _clusterMgr; + private VirtualMachineManager _itMgr; private ConsoleProxyListener _listener; private ServiceOfferingVO _serviceOffering; - NetworkOffering _publicNetworkOffering; - NetworkOffering _managementNetworkOffering; - NetworkOffering _linkLocalNetworkOffering; - - @Inject - private VirtualMachineManager _itMgr; - /* * private final ExecutorService _requestHandlerScheduler = Executors.newCachedThreadPool(new * NamedThreadFactory("Request-handler")); @@ -241,9 +225,9 @@ public class ConsoleProxyManagerImpl extends ManagerBase implements ConsoleProxy private int _capacityPerProxy = ConsoleProxyManager.DEFAULT_PROXY_CAPACITY; private int _standbyCapacity = ConsoleProxyManager.DEFAULT_STANDBY_CAPACITY; - private boolean _use_lvm; - private boolean _use_storage_vm; - private boolean _disable_rp_filter = false; + private boolean _useLvm; + private boolean _useStorageVm; + private boolean _disableRpFilter = false; private String _instance; private int _proxySessionTimeoutValue = DEFAULT_PROXY_SESSION_TIMEOUT; @@ -267,8 +251,8 @@ public class ConsoleProxyManagerImpl extends ManagerBase implements ConsoleProxy public class VmBasedAgentHook extends AgentHookBase { - public VmBasedAgentHook(VMInstanceDao instanceDao, HostDao hostDao, ConfigurationDao cfgDao, KeystoreManager ksMgr, AgentManager agentMgr, ManagementServer ms) { - super(instanceDao, hostDao, cfgDao, ksMgr, agentMgr, ms); + public VmBasedAgentHook(VMInstanceDao instanceDao, HostDao hostDao, ConfigurationDao cfgDao, KeystoreManager ksMgr, AgentManager agentMgr, KeysManager keysMgr) { + super(instanceDao, hostDao, cfgDao, ksMgr, agentMgr, keysMgr); } @Override @@ -500,7 +484,7 @@ public class ConsoleProxyManagerImpl extends ManagerBase implements ConsoleProxy byte[] details = proxy.getSessionDetails(); status = gson.fromJson(details != null ? new String(details, Charset.forName("US-ASCII")) : null, ConsoleProxyStatus.class); } catch (Throwable e) { - s_logger.warn("Unable to parse proxy session details : " + proxy.getSessionDetails()); + s_logger.warn("Unable to parse proxy session details : " + Arrays.toString(proxy.getSessionDetails())); } if (status != null && status.getConnections() != null) { @@ -549,7 +533,7 @@ public class ConsoleProxyManagerImpl extends ManagerBase implements ConsoleProxy } if (proxy.getState() == VirtualMachine.State.Stopped) { - _itMgr.advanceStart(proxy.getUuid(), null); + _itMgr.advanceStart(proxy.getUuid(), null, null); proxy = _consoleProxyDao.findById(proxy.getId()); } @@ -884,14 +868,6 @@ public class ConsoleProxyManagerImpl extends ManagerBase implements ConsoleProxy return l.size() < launchLimit; } - private HypervisorType currentHypervisorType(long dcId) { - List l = - _consoleProxyDao.getProxyListInStates(dcId, VirtualMachine.State.Starting, VirtualMachine.State.Running, VirtualMachine.State.Stopping, - VirtualMachine.State.Stopped, VirtualMachine.State.Migrating, VirtualMachine.State.Shutdowned, VirtualMachine.State.Unknown); - - return l.size() > 0 ? l.get(0).getHypervisorType() : HypervisorType.Any; - } - private boolean checkCapacity(ConsoleProxyLoadInfo proxyCountInfo, ConsoleProxyLoadInfo vmCountInfo) { if (proxyCountInfo.getCount() * _capacityPerProxy - vmCountInfo.getCount() <= _standbyCapacity) { @@ -959,7 +935,7 @@ public class ConsoleProxyManagerImpl extends ManagerBase implements ConsoleProxy TemplateDataStoreVO templateHostRef = _vmTemplateStoreDao.findByTemplateZoneDownloadStatus(template.getId(), dataCenterId, Status.DOWNLOADED); if (templateHostRef != null) { - List> l = _consoleProxyDao.getDatacenterStoragePoolHostInfo(dataCenterId, _use_lvm); + List> l = _consoleProxyDao.getDatacenterStoragePoolHostInfo(dataCenterId, _useLvm); if (l != null && l.size() > 0 && l.get(0).second().intValue() > 0) { return true; } else { @@ -969,11 +945,7 @@ public class ConsoleProxyManagerImpl extends ManagerBase implements ConsoleProxy } } else { if (s_logger.isDebugEnabled()) { - if (template == null) { - s_logger.debug("Zone host is ready, but console proxy template is null"); - } else { - s_logger.debug("Zone host is ready, but console proxy template: " + template.getId() + " is not ready on secondary storage."); - } + s_logger.debug("Zone host is ready, but console proxy template: " + template.getId() + " is not ready on secondary storage."); } } } @@ -982,7 +954,7 @@ public class ConsoleProxyManagerImpl extends ManagerBase implements ConsoleProxy private boolean isZoneHostReady(ZoneHostInfo zoneHostInfo) { int expectedFlags = 0; - if (_use_storage_vm) { + if (_useStorageVm) { expectedFlags = RunningHostInfoAgregator.ZoneHostInfo.ROUTING_HOST_MASK; } else { expectedFlags = RunningHostInfoAgregator.ZoneHostInfo.ALL_HOST_MASK; @@ -1232,17 +1204,17 @@ public class ConsoleProxyManagerImpl extends ManagerBase implements ConsoleProxy value = configs.get(Config.ConsoleProxyDisableRpFilter.key()); if (value != null && value.equalsIgnoreCase("true")) { - _disable_rp_filter = true; + _disableRpFilter = true; } value = configs.get(Config.SystemVMUseLocalStorage.key()); if (value != null && value.equalsIgnoreCase("true")) { - _use_lvm = true; + _useLvm = true; } value = configs.get("secondary.storage.vm"); if (value != null && value.equalsIgnoreCase("true")) { - _use_storage_vm = true; + _useStorageVm = true; } if (s_logger.isInfoEnabled()) { @@ -1260,9 +1232,9 @@ public class ConsoleProxyManagerImpl extends ManagerBase implements ConsoleProxy Map agentMgrConfigs = _configDao.getConfiguration("AgentManager", params); value = agentMgrConfigs.get("port"); - _mgmt_port = NumbersUtil.parseInt(value, 8250); + _mgmtPort = NumbersUtil.parseInt(value, 8250); - _listener = new ConsoleProxyListener(new VmBasedAgentHook(_instanceDao, _hostDao, _configDao, _ksMgr, _agentMgr, _ms)); + _listener = new ConsoleProxyListener(new VmBasedAgentHook(_instanceDao, _hostDao, _configDao, _ksMgr, _agentMgr, _keysMgr)); _agentMgr.registerForHostEvents(_listener, true, true, false); _itMgr.registerGuru(VirtualMachine.Type.ConsoleProxy, this); @@ -1327,8 +1299,8 @@ public class ConsoleProxyManagerImpl extends ManagerBase implements ConsoleProxy StringBuilder buf = profile.getBootArgsBuilder(); buf.append(" template=domP type=consoleproxy"); - buf.append(" host=").append(ClusterManager.ManagementHostIPAdr.value()); - buf.append(" port=").append(_mgmt_port); + buf.append(" host=").append(ApiServiceConfiguration.ManagementHostIPAdr.value()); + buf.append(" port=").append(_mgmtPort); buf.append(" name=").append(profile.getVirtualMachine().getHostName()); if (_sslEnabled) { buf.append(" premium=true"); @@ -1337,7 +1309,7 @@ public class ConsoleProxyManagerImpl extends ManagerBase implements ConsoleProxy buf.append(" pod=").append(dest.getPod().getId()); buf.append(" guid=Proxy.").append(profile.getId()); buf.append(" proxy_vm=").append(profile.getId()); - if (_disable_rp_filter) { + if (_disableRpFilter) { buf.append(" disable_rp_filter=true"); } @@ -1440,6 +1412,11 @@ public class ConsoleProxyManagerImpl extends ManagerBase implements ConsoleProxy controlNic = managementNic; } + // verify ssh access on management nic for system vm running on HyperV + if(profile.getHypervisorType() == HypervisorType.Hyperv) { + controlNic = managementNic; + } + CheckSshCommand check = new CheckSshCommand(profile.getInstanceName(), controlNic.getIp4Address(), 3922); cmds.addCommand("checkSsh", check); @@ -1672,13 +1649,11 @@ public class ConsoleProxyManagerImpl extends ManagerBase implements ConsoleProxy @Override public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map details, List hostTags) { - // TODO Auto-generated method stub return null; } @Override public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { - // TODO Auto-generated method stub return null; } @@ -1699,7 +1674,7 @@ public class ConsoleProxyManagerImpl extends ManagerBase implements ConsoleProxy @Inject public void setConsoleProxyAllocators(List consoleProxyAllocators) { - this._consoleProxyAllocators = consoleProxyAllocators; + _consoleProxyAllocators = consoleProxyAllocators; } } diff --git a/server/src/com/cloud/consoleproxy/StaticConsoleProxyManager.java b/server/src/com/cloud/consoleproxy/StaticConsoleProxyManager.java index de1b34f7b2d..27bdcbe47fb 100755 --- a/server/src/com/cloud/consoleproxy/StaticConsoleProxyManager.java +++ b/server/src/com/cloud/consoleproxy/StaticConsoleProxyManager.java @@ -27,6 +27,8 @@ import javax.naming.ConfigurationException; import org.apache.log4j.Logger; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; +import org.apache.cloudstack.framework.security.keystore.KeystoreDao; +import org.apache.cloudstack.framework.security.keystore.KeystoreManager; import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupProxyCommand; @@ -34,8 +36,6 @@ import com.cloud.host.Host.Type; import com.cloud.host.HostVO; import com.cloud.host.dao.HostDao; import com.cloud.info.ConsoleProxyInfo; -import com.cloud.keystore.KeystoreDao; -import com.cloud.keystore.KeystoreManager; import com.cloud.resource.ResourceManager; import com.cloud.resource.ResourceStateAdapter; import com.cloud.resource.ServerResource; diff --git a/server/src/com/cloud/dc/DedicatedResourceVO.java b/server/src/com/cloud/dc/DedicatedResourceVO.java index 9948f504158..e7d7b3b282c 100644 --- a/server/src/com/cloud/dc/DedicatedResourceVO.java +++ b/server/src/com/cloud/dc/DedicatedResourceVO.java @@ -29,6 +29,11 @@ import javax.persistence.Table; @Table(name = "dedicated_resources") public class DedicatedResourceVO implements DedicatedResources { + /** + * + */ + private static final long serialVersionUID = -6659510127145101917L; + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") @@ -59,7 +64,7 @@ public class DedicatedResourceVO implements DedicatedResources { private long affinityGroupId; public DedicatedResourceVO() { - this.uuid = UUID.randomUUID().toString(); + uuid = UUID.randomUUID().toString(); } public DedicatedResourceVO(Long dataCenterId, Long podId, Long clusterId, Long hostId, Long domainId, Long accountId, long affinityGroupId) { @@ -69,7 +74,7 @@ public class DedicatedResourceVO implements DedicatedResources { this.hostId = hostId; this.domainId = domainId; this.accountId = accountId; - this.uuid = UUID.randomUUID().toString(); + uuid = UUID.randomUUID().toString(); this.affinityGroupId = affinityGroupId; } @@ -115,7 +120,7 @@ public class DedicatedResourceVO implements DedicatedResources { } public DedicatedResourceVO(long dedicatedResourceId) { - this.id = dedicatedResourceId; + id = dedicatedResourceId; } @Override @@ -138,7 +143,7 @@ public class DedicatedResourceVO implements DedicatedResources { @Override public String getUuid() { - return this.uuid; + return uuid; } public void setUuid(String uuid) { @@ -153,7 +158,7 @@ public class DedicatedResourceVO implements DedicatedResources { @Override public boolean equals(Object obj) { if (obj instanceof DedicatedResourceVO) { - return ((DedicatedResourceVO)obj).getId() == this.getId(); + return ((DedicatedResourceVO)obj).getId() == getId(); } else { return false; } diff --git a/server/src/com/cloud/deploy/DeploymentPlanningManagerImpl.java b/server/src/com/cloud/deploy/DeploymentPlanningManagerImpl.java index 69230e08050..35a0b39acb2 100644 --- a/server/src/com/cloud/deploy/DeploymentPlanningManagerImpl.java +++ b/server/src/com/cloud/deploy/DeploymentPlanningManagerImpl.java @@ -17,6 +17,7 @@ package com.cloud.deploy; import java.util.ArrayList; +import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; @@ -91,6 +92,7 @@ import com.cloud.org.Grouping; import com.cloud.resource.ResourceState; import com.cloud.storage.DiskOfferingVO; import com.cloud.storage.ScopeType; +import com.cloud.storage.Storage; import com.cloud.storage.StorageManager; import com.cloud.storage.StoragePool; import com.cloud.storage.StoragePoolHostVO; @@ -162,8 +164,8 @@ public class DeploymentPlanningManagerImpl extends ManagerBase implements Deploy return _storagePoolAllocators; } - public void setStoragePoolAllocators(List _storagePoolAllocators) { - this._storagePoolAllocators = _storagePoolAllocators; + public void setStoragePoolAllocators(List storagePoolAllocators) { + _storagePoolAllocators = storagePoolAllocators; } protected List _hostAllocators; @@ -172,8 +174,8 @@ public class DeploymentPlanningManagerImpl extends ManagerBase implements Deploy return _hostAllocators; } - public void setHostAllocators(List _hostAllocators) { - this._hostAllocators = _hostAllocators; + public void setHostAllocators(List hostAllocators) { + _hostAllocators = hostAllocators; } @Inject @@ -218,8 +220,8 @@ public class DeploymentPlanningManagerImpl extends ManagerBase implements Deploy return _planners; } - public void setPlanners(List _planners) { - this._planners = _planners; + public void setPlanners(List planners) { + _planners = planners; } protected List _affinityProcessors; @@ -229,12 +231,12 @@ public class DeploymentPlanningManagerImpl extends ManagerBase implements Deploy } public void setAffinityGroupProcessors(List affinityProcessors) { - this._affinityProcessors = affinityProcessors; + _affinityProcessors = affinityProcessors; } @Override - public DeployDestination planDeployment(VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoids) throws InsufficientServerCapacityException, - AffinityConflictException { + public DeployDestination planDeployment(VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoids, DeploymentPlanner planner) + throws InsufficientServerCapacityException, AffinityConflictException { // call affinitygroup chain VirtualMachine vm = vmProfile.getVirtualMachine(); @@ -265,19 +267,20 @@ public class DeploymentPlanningManagerImpl extends ManagerBase implements Deploy } ServiceOffering offering = vmProfile.getServiceOffering(); - String plannerName = offering.getDeploymentPlanner(); - if (plannerName == null) { - if (vm.getHypervisorType() == HypervisorType.BareMetal) { - plannerName = "BareMetalPlanner"; - } else { - plannerName = _configDao.getValue(Config.VmDeploymentPlanner.key()); + if(planner == null){ + String plannerName = offering.getDeploymentPlanner(); + if (plannerName == null) { + if (vm.getHypervisorType() == HypervisorType.BareMetal) { + plannerName = "BareMetalPlanner"; + } else { + plannerName = _configDao.getValue(Config.VmDeploymentPlanner.key()); + } } - } - DeploymentPlanner planner = null; - for (DeploymentPlanner plannerInList : _planners) { - if (plannerName.equals(plannerInList.getName())) { - planner = plannerInList; - break; + for (DeploymentPlanner plannerInList : _planners) { + if (plannerName.equals(plannerInList.getName())) { + planner = plannerInList; + break; + } } } @@ -325,8 +328,8 @@ public class DeploymentPlanningManagerImpl extends ManagerBase implements Deploy List suitableHosts = new ArrayList(); suitableHosts.add(host); Pair> potentialResources = findPotentialDeploymentResources( - suitableHosts, suitableVolumeStoragePools, avoids, - getPlannerUsage(planner, vmProfile, plan, avoids), readyAndReusedVolumes); + suitableHosts, suitableVolumeStoragePools, avoids, + getPlannerUsage(planner, vmProfile, plan, avoids), readyAndReusedVolumes); if (potentialResources != null) { Pod pod = _podDao.findById(host.getPodId()); Cluster cluster = _clusterDao.findById(host.getClusterId()); @@ -365,7 +368,7 @@ public class DeploymentPlanningManagerImpl extends ManagerBase implements Deploy Float cpuOvercommitRatio = Float.parseFloat(cluster_detail_cpu.getValue()); Float memoryOvercommitRatio = Float.parseFloat(cluster_detail_ram.getValue()); if (_capacityMgr.checkIfHostHasCapacity(host.getId(), cpu_requested, ram_requested, true, cpuOvercommitRatio, memoryOvercommitRatio, true) - && _capacityMgr.checkIfHostHasCpuCapability(host.getId(), offering.getCpu(), offering.getSpeed())) { + && _capacityMgr.checkIfHostHasCpuCapability(host.getId(), offering.getCpu(), offering.getSpeed())) { s_logger.debug("The last host of this VM is UP and has enough capacity"); s_logger.debug("Now checking for suitable pools under zone: " + host.getDataCenterId() + ", pod: " + host.getPodId() + ", cluster: " + host.getClusterId()); @@ -383,8 +386,8 @@ public class DeploymentPlanningManagerImpl extends ManagerBase implements Deploy List suitableHosts = new ArrayList(); suitableHosts.add(host); Pair> potentialResources = findPotentialDeploymentResources( - suitableHosts, suitableVolumeStoragePools, avoids, - getPlannerUsage(planner, vmProfile, plan, avoids), readyAndReusedVolumes); + suitableHosts, suitableVolumeStoragePools, avoids, + getPlannerUsage(planner, vmProfile, plan, avoids), readyAndReusedVolumes); if (potentialResources != null) { Pod pod = _podDao.findById(host.getPodId()); Cluster cluster = _clusterDao.findById(host.getClusterId()); @@ -474,7 +477,7 @@ public class DeploymentPlanningManagerImpl extends ManagerBase implements Deploy // check if zone is dedicated. if yes check if vm owner has acess to it. DedicatedResourceVO dedicatedZone = _dedicatedDao.findByZoneId(dc.getId()); - if (dedicatedZone != null) { + if (dedicatedZone != null && !_accountMgr.isRootAdmin(vmProfile.getOwner().getType())) { long accountDomainId = vmProfile.getOwner().getDomainId(); long accountId = vmProfile.getOwner().getAccountId(); @@ -845,7 +848,7 @@ public class DeploymentPlanningManagerImpl extends ManagerBase implements Deploy // /refactoring planner methods private DeployDestination checkClustersforDestination(List clusterList, VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoid, DataCenter dc, - DeploymentPlanner.PlannerResourceUsage resourceUsageRequired, ExcludeList PlannerAvoidOutput) { + DeploymentPlanner.PlannerResourceUsage resourceUsageRequired, ExcludeList plannerAvoidOutput) { if (s_logger.isTraceEnabled()) { s_logger.trace("ClusterId List to consider: " + clusterList); @@ -886,8 +889,8 @@ public class DeploymentPlanningManagerImpl extends ManagerBase implements Deploy // choose the potential host and pool for the VM if (!suitableVolumeStoragePools.isEmpty()) { Pair> potentialResources = findPotentialDeploymentResources( - suitableHosts, suitableVolumeStoragePools, avoid, resourceUsageRequired, - readyAndReusedVolumes); + suitableHosts, suitableVolumeStoragePools, avoid, resourceUsageRequired, + readyAndReusedVolumes); if (potentialResources != null) { Pod pod = _podDao.findById(clusterVO.getPodId()); @@ -909,7 +912,7 @@ public class DeploymentPlanningManagerImpl extends ManagerBase implements Deploy s_logger.debug("No suitable hosts found under this Cluster: " + clusterId); } - if (canAvoidCluster(clusterVO, avoid, PlannerAvoidOutput, vmProfile)) { + if (canAvoidCluster(clusterVO, avoid, plannerAvoidOutput, vmProfile)) { avoid.addCluster(clusterVO.getId()); } } @@ -1139,9 +1142,9 @@ public class DeploymentPlanningManagerImpl extends ManagerBase implements Deploy List suitablePools = new ArrayList(); StoragePool pool = null; if (toBeCreated.getPoolId() != null) { - pool = (StoragePool)this.dataStoreMgr.getPrimaryDataStore(toBeCreated.getPoolId()); + pool = (StoragePool)dataStoreMgr.getPrimaryDataStore(toBeCreated.getPoolId()); } else { - pool = (StoragePool)this.dataStoreMgr.getPrimaryDataStore(plan.getPoolId()); + pool = (StoragePool)dataStoreMgr.getPrimaryDataStore(plan.getPoolId()); } if (!pool.isInMaintenance()) { @@ -1153,7 +1156,7 @@ public class DeploymentPlanningManagerImpl extends ManagerBase implements Deploy if (plan.getDataCenterId() == exstPoolDcId && plan.getPodId() == exstPoolPodId && plan.getClusterId() == exstPoolClusterId) { canReusePool = true; } else if (plan.getDataCenterId() == exstPoolDcId) { - DataStore dataStore = this.dataStoreMgr.getPrimaryDataStore(pool.getId()); + DataStore dataStore = dataStoreMgr.getPrimaryDataStore(pool.getId()); if (dataStore != null && dataStore.getScope() != null && dataStore.getScope().getScopeType() == ScopeType.ZONE) { canReusePool = true; } @@ -1201,8 +1204,12 @@ public class DeploymentPlanningManagerImpl extends ManagerBase implements Deploy s_logger.debug("Calling StoragePoolAllocators to find suitable pools"); DiskOfferingVO diskOffering = _diskOfferingDao.findById(toBeCreated.getDiskOfferingId()); - DiskProfile diskProfile = new DiskProfile(toBeCreated, diskOffering, vmProfile.getHypervisorType()); + if (vmProfile.getTemplate().getFormat() == Storage.ImageFormat.ISO && vmProfile.getServiceOffering().getTagsArray().length != 0) { + diskOffering.setTagsArray(Arrays.asList(vmProfile.getServiceOffering().getTagsArray())); + } + + DiskProfile diskProfile = new DiskProfile(toBeCreated, diskOffering, vmProfile.getHypervisorType()); boolean useLocalStorage = false; if (vmProfile.getType() != VirtualMachine.Type.User) { String ssvmUseLocalStorage = _configDao.getValue(Config.SystemVMUseLocalStorage.key()); @@ -1252,9 +1259,14 @@ public class DeploymentPlanningManagerImpl extends ManagerBase implements Deploy } } - if (suitableVolumeStoragePools.values() != null) { - poolsToAvoidOutput.removeAll(suitableVolumeStoragePools.values()); + HashSet toRemove = new HashSet(); + for (List lsp : suitableVolumeStoragePools.values()) { + for (StoragePool sp : lsp) { + toRemove.add(sp.getId()); + } } + poolsToAvoidOutput.removeAll(toRemove); + if (avoid.getPoolsToAvoid() != null) { avoid.getPoolsToAvoid().addAll(poolsToAvoidOutput); } diff --git a/server/src/com/cloud/deploy/FirstFitPlanner.java b/server/src/com/cloud/deploy/FirstFitPlanner.java index ec817c1871a..1c79a67e780 100755 --- a/server/src/com/cloud/deploy/FirstFitPlanner.java +++ b/server/src/com/cloud/deploy/FirstFitPlanner.java @@ -35,7 +35,6 @@ import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import com.cloud.capacity.Capacity; import com.cloud.capacity.CapacityManager; -import com.cloud.capacity.CapacityVO; import com.cloud.capacity.dao.CapacityDao; import com.cloud.configuration.Config; import com.cloud.dc.ClusterDetailsDao; @@ -260,7 +259,15 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentClusterPla return capacityList; } - private void removeClustersCrossingThreshold(List clusterListForVmAllocation, ExcludeList avoid, VirtualMachineProfile vmProfile, DeploymentPlan plan) { + /** + * This method should remove the clusters crossing capacity threshold to avoid further vm allocation on it. + * @param clusterListForVmAllocation + * @param avoid + * @param vmProfile + * @param plan + */ + protected void removeClustersCrossingThreshold(List clusterListForVmAllocation, ExcludeList avoid, + VirtualMachineProfile vmProfile, DeploymentPlan plan) { List capacityList = getCapacitiesForCheckingThreshold(); List clustersCrossingThreshold = new ArrayList(); @@ -482,11 +489,11 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentClusterPla ServiceOffering offering = vm.getServiceOffering(); if (vm.getHypervisorType() != HypervisorType.BareMetal) { if (offering != null && offering.getDeploymentPlanner() != null) { - if (offering.getDeploymentPlanner().equals(this.getName())) { + if (offering.getDeploymentPlanner().equals(getName())) { return true; } } else { - if (_globalDeploymentPlanner != null && _globalDeploymentPlanner.equals(this._name)) { + if (_globalDeploymentPlanner != null && _globalDeploymentPlanner.equals(_name)) { return true; } } diff --git a/server/src/com/cloud/event/ActionEventUtils.java b/server/src/com/cloud/event/ActionEventUtils.java index 3fa68e5fbbf..d435381b69b 100755 --- a/server/src/com/cloud/event/ActionEventUtils.java +++ b/server/src/com/cloud/event/ActionEventUtils.java @@ -25,7 +25,7 @@ import java.util.Map; import javax.annotation.PostConstruct; import javax.inject.Inject; -import com.cloud.domain.Domain; +import com.cloud.vm.VirtualMachine; import org.apache.log4j.Logger; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -33,8 +33,8 @@ import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.framework.events.EventBus; import org.apache.cloudstack.framework.events.EventBusException; +import com.cloud.domain.Domain; import com.cloud.event.dao.EventDao; -import com.cloud.server.ManagementServer; import com.cloud.server.ManagementService; import com.cloud.user.Account; import com.cloud.user.AccountVO; @@ -46,10 +46,10 @@ import com.cloud.utils.component.ComponentContext; public class ActionEventUtils { private static final Logger s_logger = Logger.getLogger(ActionEventUtils.class); - private static EventDao _eventDao; - private static AccountDao _accountDao; - protected static UserDao _userDao; - protected static EventBus _eventBus = null; + private static EventDao s_eventDao; + private static AccountDao s_accountDao; + protected static UserDao s_userDao; + protected static EventBus s_eventBus = null; public static final String EventDetails = "event_details"; public static final String EventId = "event_id"; @@ -69,9 +69,9 @@ public class ActionEventUtils { @PostConstruct void init() { - _eventDao = eventDao; - _accountDao = accountDao; - _userDao = userDao; + s_eventDao = eventDao; + s_accountDao = accountDao; + s_userDao = userDao; } public static Long onActionEvent(Long userId, Long accountId, Long domainId, String type, String description) { @@ -158,13 +158,13 @@ public class ActionEventUtils { if (startEventId != null) { event.setStartId(startEventId); } - event = _eventDao.persist(event); + event = s_eventDao.persist(event); return event; } private static void publishOnEventBus(long userId, long accountId, String eventCategory, String eventType, Event.State state, String description) { try { - _eventBus = ComponentContext.getComponent(EventBus.class); + s_eventBus = ComponentContext.getComponent(EventBus.class); } catch (NoSuchBeanDefinitionException nbe) { return; // no provider is configured to provide events bus, so just return } @@ -177,15 +177,16 @@ public class ActionEventUtils { { CallContext context = CallContext.current(); entityUuid = (String)context.getContextParameter(entityKey); - if (entityUuid != null) entityType = entityKey.getName(); + if (entityUuid != null) + entityType = entityKey.getName(); } org.apache.cloudstack.framework.events.Event event = - new org.apache.cloudstack.framework.events.Event(ManagementService.Name, eventCategory, eventType, EventTypes.getEntityForEvent(eventType), null); + new org.apache.cloudstack.framework.events.Event(ManagementService.Name, eventCategory, eventType, EventTypes.getEntityForEvent(eventType), entityUuid); Map eventDescription = new HashMap(); - Account account = _accountDao.findById(accountId); - User user = _userDao.findById(userId); + Account account = s_accountDao.findById(accountId); + User user = s_userDao.findById(userId); // if account has been deleted, this might be called during cleanup of resources and results in null pointer if (account == null) return; @@ -205,14 +206,14 @@ public class ActionEventUtils { event.setDescription(eventDescription); try { - _eventBus.publish(event); + s_eventBus.publish(event); } catch (EventBusException e) { s_logger.warn("Failed to publish action event on the the event bus."); } } private static long getDomainId(long accountId) { - AccountVO account = _accountDao.findByIdIncludingRemoved(accountId); + AccountVO account = s_accountDao.findByIdIncludingRemoved(accountId); if (account == null) { s_logger.error("Failed to find account(including removed ones) by id '" + accountId + "'"); return 0; @@ -233,6 +234,8 @@ public class ActionEventUtils { else if (eventType.startsWith("USER.")) { return User.class; + }else if (eventType.startsWith("VM.")){ + return VirtualMachine.class; } return null; diff --git a/server/src/com/cloud/event/AlertGenerator.java b/server/src/com/cloud/event/AlertGenerator.java index 2103a1488ba..5982eea351e 100644 --- a/server/src/com/cloud/event/AlertGenerator.java +++ b/server/src/com/cloud/event/AlertGenerator.java @@ -36,7 +36,6 @@ import com.cloud.dc.DataCenterVO; import com.cloud.dc.HostPodVO; import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.HostPodDao; -import com.cloud.server.ManagementServer; import com.cloud.server.ManagementService; import com.cloud.utils.component.ComponentContext; @@ -44,9 +43,9 @@ import com.cloud.utils.component.ComponentContext; public class AlertGenerator { private static final Logger s_logger = Logger.getLogger(AlertGenerator.class); - private static DataCenterDao _dcDao; - private static HostPodDao _podDao; - protected static EventBus _eventBus = null; + private static DataCenterDao s_dcDao; + private static HostPodDao s_podDao; + protected static EventBus s_eventBus = null; @Inject DataCenterDao dcDao; @@ -58,13 +57,13 @@ public class AlertGenerator { @PostConstruct void init() { - _dcDao = dcDao; - _podDao = podDao; + s_dcDao = dcDao; + s_podDao = podDao; } public static void publishAlertOnEventBus(String alertType, long dataCenterId, Long podId, String subject, String body) { try { - _eventBus = ComponentContext.getComponent(EventBus.class); + s_eventBus = ComponentContext.getComponent(EventBus.class); } catch (NoSuchBeanDefinitionException nbe) { return; // no provider is configured to provide events bus, so just return } @@ -73,8 +72,8 @@ public class AlertGenerator { new org.apache.cloudstack.framework.events.Event(ManagementService.Name, EventCategory.ALERT_EVENT.getName(), alertType, null, null); Map eventDescription = new HashMap(); - DataCenterVO dc = _dcDao.findById(dataCenterId); - HostPodVO pod = _podDao.findById(podId); + DataCenterVO dc = s_dcDao.findById(dataCenterId); + HostPodVO pod = s_podDao.findById(podId); eventDescription.put("event", alertType); if (dc != null) { @@ -96,7 +95,7 @@ public class AlertGenerator { event.setDescription(eventDescription); try { - _eventBus.publish(event); + s_eventBus.publish(event); } catch (EventBusException e) { s_logger.warn("Failed to publish alert on the the event bus."); } diff --git a/server/src/com/cloud/ha/HighAvailabilityManagerImpl.java b/server/src/com/cloud/ha/HighAvailabilityManagerImpl.java index aec1b8dd2b7..3963f29ec81 100755 --- a/server/src/com/cloud/ha/HighAvailabilityManagerImpl.java +++ b/server/src/com/cloud/ha/HighAvailabilityManagerImpl.java @@ -32,12 +32,11 @@ import javax.naming.ConfigurationException; import org.apache.log4j.Logger; import org.apache.log4j.NDC; +import com.cloud.deploy.HAPlanner; import org.apache.cloudstack.engine.orchestration.service.VolumeOrchestrationService; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.managed.context.ManagedContext; import org.apache.cloudstack.managed.context.ManagedContextRunnable; -import org.apache.log4j.Logger; -import org.apache.log4j.NDC; import com.cloud.agent.AgentManager; import com.cloud.alert.AlertManager; @@ -123,26 +122,36 @@ public class HighAvailabilityManagerImpl extends ManagerBase implements HighAvai @Inject ManagedContext _managedContext; - List _investigators; + List investigators; public List getInvestigators() { - return _investigators; + return investigators; } - public void setInvestigators(List _investigators) { - this._investigators = _investigators; + public void setInvestigators(List investigators) { + this.investigators = investigators; } - List _fenceBuilders; + List fenceBuilders; public List getFenceBuilders() { - return _fenceBuilders; + return fenceBuilders; } - public void setFenceBuilders(List _fenceBuilders) { - this._fenceBuilders = _fenceBuilders; + public void setFenceBuilders(List fenceBuilders) { + this.fenceBuilders = fenceBuilders; } + List _haPlanners; + public List getHaPlanners() { + return _haPlanners; + } + + public void setHaPlanners(List haPlanners) { + this._haPlanners = haPlanners; + } + + @Inject AgentManager _agentMgr; @Inject @@ -190,7 +199,7 @@ public class HighAvailabilityManagerImpl extends ManagerBase implements HighAvai } Status hostState = null; - for (Investigator investigator : _investigators) { + for (Investigator investigator : investigators) { hostState = investigator.isAgentAlive(host); if (hostState != null) { if (s_logger.isDebugEnabled()) { @@ -245,7 +254,8 @@ public class HighAvailabilityManagerImpl extends ManagerBase implements HighAvai HostPodVO podVO = _podDao.findById(host.getPodId()); String hostDesc = "name: " + host.getName() + " (id:" + host.getId() + "), availability zone: " + dcVO.getName() + ", pod: " + podVO.getName(); - _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, host.getDataCenterId(), host.getPodId(), "Host is down, " + hostDesc, "Host [" + hostDesc + "] is down." + + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, host.getDataCenterId(), host.getPodId(), "Host is down, " + hostDesc, "Host [" + hostDesc + + "] is down." + ((sb != null) ? sb.toString() : "")); for (final VMInstanceVO vm : vms) { @@ -341,6 +351,7 @@ public class HighAvailabilityManagerImpl extends ManagerBase implements HighAvai try { _itMgr.advanceStop(vm.getUuid(), true); + vm = _instanceDao.findByUuid(vm.getUuid()); } catch (ResourceUnavailableException e) { assert false : "How do we hit this when force is true?"; throw new CloudRuntimeException("Caught exception even though it should be handled.", e); @@ -449,7 +460,7 @@ public class HighAvailabilityManagerImpl extends ManagerBase implements HighAvai } Investigator investigator = null; - for (Investigator it : _investigators) { + for (Investigator it : investigators) { investigator = it; alive = investigator.isVmAlive(vm, host); s_logger.info(investigator.getName() + " found " + vm + "to be alive? " + alive); @@ -461,7 +472,7 @@ public class HighAvailabilityManagerImpl extends ManagerBase implements HighAvai boolean fenced = false; if (alive == null) { s_logger.debug("Fencing off VM that we don't know the state of"); - for (FenceBuilder fb : _fenceBuilders) { + for (FenceBuilder fb : fenceBuilders) { Boolean result = fb.fenceOff(vm, host); s_logger.info("Fencer " + fb.getName() + " returned " + result); if (result != null && result) { @@ -549,7 +560,14 @@ public class HighAvailabilityManagerImpl extends ManagerBase implements HighAvai if (_haTag != null) { params.put(VirtualMachineProfile.Param.HaTag, _haTag); } - _itMgr.advanceStart(vm.getUuid(), params); + + try{ + // First try starting the vm with its original planner, if it doesn't succeed send HAPlanner as its an emergency. + _itMgr.advanceStart(vm.getUuid(), params, null); + }catch (InsufficientCapacityException e){ + s_logger.warn("Failed to deploy vm " + vmId + " with original planner, sending HAPlanner"); + _itMgr.advanceStart(vm.getUuid(), params, _haPlanners.get(0)); + } VMInstanceVO started = _instanceDao.findById(vm.getId()); if (started != null && started.getState() == VirtualMachine.State.Running) { @@ -592,8 +610,14 @@ public class HighAvailabilityManagerImpl extends ManagerBase implements HighAvai _haDao.update(work.getId(), work); VMInstanceVO vm = _instanceDao.findById(vmId); - - _itMgr.migrateAway(vm.getUuid(), srcHostId); + // First try starting the vm with its original planner, if it doesn't succeed send HAPlanner as its an emergency. + boolean result = false; + try { + _itMgr.migrateAway(vm.getUuid(), srcHostId, null); + }catch (InsufficientServerCapacityException e) { + s_logger.warn("Failed to deploy vm " + vmId + " with original planner, sending HAPlanner"); + _itMgr.migrateAway(vm.getUuid(), srcHostId, _haPlanners.get(0)); + } return null; } catch (InsufficientServerCapacityException e) { s_logger.warn("Insufficient capacity for migrating a VM."); diff --git a/server/src/com/cloud/hypervisor/HypervisorGuruBase.java b/server/src/com/cloud/hypervisor/HypervisorGuruBase.java index aa0fa590a47..7fb79fa1578 100644 --- a/server/src/com/cloud/hypervisor/HypervisorGuruBase.java +++ b/server/src/com/cloud/hypervisor/HypervisorGuruBase.java @@ -150,4 +150,9 @@ public abstract class HypervisorGuruBase extends AdapterBase implements Hypervis public List finalizeExpungeNics(VirtualMachine vm, List nics) { return null; } + + @Override + public List finalizeExpungeVolumes(VirtualMachine vm) { + return null; + } } diff --git a/server/src/com/cloud/hypervisor/kvm/discoverer/LibvirtServerDiscoverer.java b/server/src/com/cloud/hypervisor/kvm/discoverer/LibvirtServerDiscoverer.java index da1bb88bbba..770099c65fd 100644 --- a/server/src/com/cloud/hypervisor/kvm/discoverer/LibvirtServerDiscoverer.java +++ b/server/src/com/cloud/hypervisor/kvm/discoverer/LibvirtServerDiscoverer.java @@ -28,8 +28,6 @@ import javax.naming.ConfigurationException; import org.apache.log4j.Logger; -import org.apache.cloudstack.framework.config.dao.ConfigurationDao; - import com.cloud.agent.AgentManager; import com.cloud.agent.Listener; import com.cloud.agent.api.AgentControlAnswer; @@ -41,7 +39,6 @@ import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupRoutingCommand; import com.cloud.configuration.Config; import com.cloud.dc.ClusterVO; -import com.cloud.dc.dao.ClusterDao; import com.cloud.exception.AgentUnavailableException; import com.cloud.exception.DiscoveredWithErrorException; import com.cloud.exception.DiscoveryException; @@ -49,10 +46,8 @@ import com.cloud.exception.OperationTimedoutException; import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.Status; -import com.cloud.host.dao.HostDao; import com.cloud.hypervisor.Hypervisor; import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.network.NetworkModel; import com.cloud.network.PhysicalNetworkSetupInfo; import com.cloud.resource.Discoverer; import com.cloud.resource.DiscovererBase; @@ -70,17 +65,9 @@ public abstract class LibvirtServerDiscoverer extends DiscovererBase implements private String _kvmPublicNic; private String _kvmGuestNic; @Inject - HostDao _hostDao = null; - @Inject - ClusterDao _clusterDao; - @Inject ResourceManager _resourceMgr; @Inject AgentManager _agentMgr; - @Inject - ConfigurationDao _configDao; - @Inject - NetworkModel _networkMgr; @Override public abstract Hypervisor.HypervisorType getHypervisorType(); diff --git a/server/src/com/cloud/metadata/ResourceMetaDataManagerImpl.java b/server/src/com/cloud/metadata/ResourceMetaDataManagerImpl.java index e1fc37fa2f7..5393a6a6b3f 100644 --- a/server/src/com/cloud/metadata/ResourceMetaDataManagerImpl.java +++ b/server/src/com/cloud/metadata/ResourceMetaDataManagerImpl.java @@ -26,10 +26,16 @@ import javax.naming.ConfigurationException; import org.apache.cloudstack.api.ResourceDetail; import org.apache.cloudstack.resourcedetail.ResourceDetailsDao; +import org.apache.cloudstack.resourcedetail.dao.AutoScaleVmProfileDetailsDao; +import org.apache.cloudstack.resourcedetail.dao.DiskOfferingDetailsDao; import org.apache.cloudstack.resourcedetail.dao.FirewallRuleDetailsDao; import org.apache.cloudstack.resourcedetail.dao.NetworkACLItemDetailsDao; import org.apache.cloudstack.resourcedetail.dao.NetworkACLListDetailsDao; import org.apache.cloudstack.resourcedetail.dao.RemoteAccessVpnDetailsDao; +import org.apache.cloudstack.resourcedetail.dao.Site2SiteCustomerGatewayDetailsDao; +import org.apache.cloudstack.resourcedetail.dao.Site2SiteVpnConnectionDetailsDao; +import org.apache.cloudstack.resourcedetail.dao.Site2SiteVpnGatewayDetailsDao; +import org.apache.cloudstack.resourcedetail.dao.UserDetailsDao; import org.apache.cloudstack.resourcedetail.dao.UserIpAddressDetailsDao; import org.apache.cloudstack.resourcedetail.dao.VpcDetailsDao; import org.apache.cloudstack.resourcedetail.dao.VpcGatewayDetailsDao; @@ -92,30 +98,46 @@ public class ResourceMetaDataManagerImpl extends ManagerBase implements Resource NetworkACLListDetailsDao _networkACLListDetailsDao; @Inject NetworkACLItemDetailsDao _networkACLDetailsDao; - + @Inject + Site2SiteVpnGatewayDetailsDao _vpnGatewayDetailsDao; + @Inject + Site2SiteCustomerGatewayDetailsDao _customerGatewayDetailsDao; + @Inject + Site2SiteVpnConnectionDetailsDao _vpnConnectionDetailsDao; + @Inject + DiskOfferingDetailsDao _diskOfferingDetailsDao; + @Inject + UserDetailsDao _userDetailsDao; + @Inject + AutoScaleVmProfileDetailsDao _autoScaleVmProfileDetailsDao; - private static Map> _daoMap = - new HashMap>(); + private static Map> s_daoMap = new HashMap>(); @Override public boolean configure(String name, Map params) throws ConfigurationException { - _daoMap.put(ResourceObjectType.UserVm, _userVmDetailDao); - _daoMap.put(ResourceObjectType.Volume, _volumeDetailDao); - _daoMap.put(ResourceObjectType.Template, _templateDetailsDao); - _daoMap.put(ResourceObjectType.Network, _networkDetailsDao); - _daoMap.put(ResourceObjectType.Nic, _nicDetailDao); - _daoMap.put(ResourceObjectType.ServiceOffering, _serviceOfferingDetailsDao); - _daoMap.put(ResourceObjectType.Zone, _dcDetailsDao); - _daoMap.put(ResourceObjectType.Storage, _storageDetailsDao); - _daoMap.put(ResourceObjectType.FirewallRule, _firewallRuleDetailsDao); - _daoMap.put(ResourceObjectType.PublicIpAddress, _userIpAddressDetailsDao); - _daoMap.put(ResourceObjectType.PortForwardingRule, _firewallRuleDetailsDao); - _daoMap.put(ResourceObjectType.LoadBalancer, _firewallRuleDetailsDao); - _daoMap.put(ResourceObjectType.RemoteAccessVpn, _vpnDetailsDao); - _daoMap.put(ResourceObjectType.Vpc, _vpcDetailsDao); - _daoMap.put(ResourceObjectType.PrivateGateway, _vpcGatewayDetailsDao); - _daoMap.put(ResourceObjectType.NetworkACLList, _networkACLListDetailsDao); - _daoMap.put(ResourceObjectType.NetworkACL, _networkACLDetailsDao); + s_daoMap.put(ResourceObjectType.UserVm, _userVmDetailDao); + s_daoMap.put(ResourceObjectType.Volume, _volumeDetailDao); + s_daoMap.put(ResourceObjectType.Template, _templateDetailsDao); + s_daoMap.put(ResourceObjectType.Network, _networkDetailsDao); + s_daoMap.put(ResourceObjectType.Nic, _nicDetailDao); + s_daoMap.put(ResourceObjectType.ServiceOffering, _serviceOfferingDetailsDao); + s_daoMap.put(ResourceObjectType.Zone, _dcDetailsDao); + s_daoMap.put(ResourceObjectType.Storage, _storageDetailsDao); + s_daoMap.put(ResourceObjectType.FirewallRule, _firewallRuleDetailsDao); + s_daoMap.put(ResourceObjectType.PublicIpAddress, _userIpAddressDetailsDao); + s_daoMap.put(ResourceObjectType.PortForwardingRule, _firewallRuleDetailsDao); + s_daoMap.put(ResourceObjectType.LoadBalancer, _firewallRuleDetailsDao); + s_daoMap.put(ResourceObjectType.RemoteAccessVpn, _vpnDetailsDao); + s_daoMap.put(ResourceObjectType.Vpc, _vpcDetailsDao); + s_daoMap.put(ResourceObjectType.PrivateGateway, _vpcGatewayDetailsDao); + s_daoMap.put(ResourceObjectType.NetworkACLList, _networkACLListDetailsDao); + s_daoMap.put(ResourceObjectType.NetworkACL, _networkACLDetailsDao); + s_daoMap.put(ResourceObjectType.VpnGateway, _vpnGatewayDetailsDao); + s_daoMap.put(ResourceObjectType.CustomerGateway, _customerGatewayDetailsDao); + s_daoMap.put(ResourceObjectType.VpnConnection, _vpnConnectionDetailsDao); + s_daoMap.put(ResourceObjectType.DiskOffering, _diskOfferingDetailsDao); + s_daoMap.put(ResourceObjectType.User, _userDetailsDao); + s_daoMap.put(ResourceObjectType.AutoScaleVmProfile, _autoScaleVmProfileDetailsDao); return true; } @@ -174,11 +196,11 @@ public class ResourceMetaDataManagerImpl extends ManagerBase implements Resource throw new UnsupportedOperationException("ResourceType " + resourceType + " doesn't support metadata"); } this.resourceType = resourceType; - ResourceDetailsDao dao = _daoMap.get(resourceType); + ResourceDetailsDao dao = s_daoMap.get(resourceType); if (dao == null) { throw new UnsupportedOperationException("ResourceType " + resourceType + " doesn't support metadata"); } - this.dao = (ResourceDetailsDao) _daoMap.get(resourceType); + this.dao = (ResourceDetailsDao)s_daoMap.get(resourceType); } private void removeDetail(long resourceId, String key) { diff --git a/server/src/com/cloud/network/ExternalIpAddressAllocator.java b/server/src/com/cloud/network/ExternalIpAddressAllocator.java index 2b84231c050..3cf358067ee 100644 --- a/server/src/com/cloud/network/ExternalIpAddressAllocator.java +++ b/server/src/com/cloud/network/ExternalIpAddressAllocator.java @@ -40,7 +40,6 @@ import com.cloud.utils.exception.CloudRuntimeException; @Local(value = IpAddrAllocator.class) public class ExternalIpAddressAllocator extends AdapterBase implements IpAddrAllocator { private static final Logger s_logger = Logger.getLogger(ExternalIpAddressAllocator.class); - String _name; @Inject ConfigurationDao _configDao = null; @Inject @@ -52,10 +51,10 @@ public class ExternalIpAddressAllocator extends AdapterBase implements IpAddrAll @Override public IpAddr getPrivateIpAddress(String macAddr, long dcId, long podId) { - if (_externalIpAllocatorUrl == null || this._externalIpAllocatorUrl.equalsIgnoreCase("")) { + if (_externalIpAllocatorUrl == null || _externalIpAllocatorUrl.equalsIgnoreCase("")) { return new IpAddr(); } - String urlString = this._externalIpAllocatorUrl + "?command=getIpAddr&mac=" + macAddr + "&dc=" + dcId + "&pod=" + podId; + String urlString = _externalIpAllocatorUrl + "?command=getIpAddr&mac=" + macAddr + "&dc=" + dcId + "&pod=" + podId; s_logger.debug("getIP:" + urlString); BufferedReader in = null; @@ -101,11 +100,11 @@ public class ExternalIpAddressAllocator extends AdapterBase implements IpAddrAll @Override public boolean releasePrivateIpAddress(String ip, long dcId, long podId) { /*TODO: call API to release the ip address from external DHCP server*/ - if (_externalIpAllocatorUrl == null || this._externalIpAllocatorUrl.equalsIgnoreCase("")) { + if (_externalIpAllocatorUrl == null || _externalIpAllocatorUrl.equalsIgnoreCase("")) { return false; } - String urlString = this._externalIpAllocatorUrl + "?command=releaseIpAddr&ip=" + ip + "&dc=" + dcId + "&pod=" + podId; + String urlString = _externalIpAllocatorUrl + "?command=releaseIpAddr&ip=" + ip + "&dc=" + dcId + "&pod=" + podId; s_logger.debug("releaseIP:" + urlString); BufferedReader in = null; diff --git a/server/src/com/cloud/network/IpAddrAllocator.java b/server/src/com/cloud/network/IpAddrAllocator.java index 0f87cd1b3a2..5a23a0e1111 100644 --- a/server/src/com/cloud/network/IpAddrAllocator.java +++ b/server/src/com/cloud/network/IpAddrAllocator.java @@ -37,14 +37,14 @@ public interface IpAddrAllocator extends Adapter { } } - public class networkInfo { + public class NetworkInfo { public String _ipAddr; public String _netMask; public String _gateWay; public Long _vlanDbId; public String _vlanid; - public networkInfo(String ip, String netMask, String gateway, Long vlanDbId, String vlanId) { + public NetworkInfo(String ip, String netMask, String gateway, Long vlanDbId, String vlanId) { _ipAddr = ip; _netMask = netMask; _gateWay = gateway; diff --git a/server/src/com/cloud/network/IpAddressManagerImpl.java b/server/src/com/cloud/network/IpAddressManagerImpl.java index 230f19db902..09f73a4d17a 100644 --- a/server/src/com/cloud/network/IpAddressManagerImpl.java +++ b/server/src/com/cloud/network/IpAddressManagerImpl.java @@ -17,6 +17,7 @@ package com.cloud.network; import java.util.ArrayList; +import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; @@ -389,9 +390,8 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage SearchBuilder podVlanMapSB = _podVlanMapDao.createSearchBuilder(); podVlanMapSB.and("podId", podVlanMapSB.entity().getPodId(), Op.EQ); AssignIpAddressFromPodVlanSearch.join("podVlanMapSB", podVlanMapSB, podVlanMapSB.entity().getVlanDbId(), AssignIpAddressFromPodVlanSearch.entity().getVlanId(), - JoinType.INNER); - AssignIpAddressFromPodVlanSearch.join("vlan", podVlanSearch, podVlanSearch.entity().getId(), AssignIpAddressFromPodVlanSearch.entity().getVlanId(), - JoinType.INNER); + JoinType.INNER); + AssignIpAddressFromPodVlanSearch.join("vlan", podVlanSearch, podVlanSearch.entity().getId(), AssignIpAddressFromPodVlanSearch.entity().getVlanId(), JoinType.INNER); AssignIpAddressFromPodVlanSearch.done(); Network.State.getStateMachine().registerListener(new NetworkStateListener(_usageEventDao, _networksDao)); @@ -402,7 +402,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage } private IpAddress allocateIP(Account ipOwner, boolean isSystem, long zoneId) throws ResourceAllocationException, InsufficientAddressCapacityException, - ConcurrentOperationException { + ConcurrentOperationException { Account caller = CallContext.current().getCallingAccount(); long callerUserId = CallContext.current().getCallingUserId(); // check permissions @@ -465,7 +465,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage @Override public boolean applyRules(List rules, FirewallRule.Purpose purpose, NetworkRuleApplier applier, boolean continueOnError) - throws ResourceUnavailableException { + throws ResourceUnavailableException { if (rules == null || rules.size() == 0) { s_logger.debug("There are no rules to forward to the network elements"); return true; @@ -572,8 +572,9 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage IPAddressVO ip = markIpAsUnavailable(addrId); - assert (ip != null) : "Unable to mark the ip address id=" + addrId + " as unavailable."; if (ip == null) { + String msg = "Unable to mark the ip address id=" + addrId + " as unavailable."; + s_logger.error(msg); return true; } @@ -640,20 +641,19 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage @Override public PublicIp assignPublicIpAddress(long dcId, Long podId, Account owner, VlanType type, Long networkId, String requestedIp, boolean isSystem) - throws InsufficientAddressCapacityException { + throws InsufficientAddressCapacityException { return fetchNewPublicIp(dcId, podId, null, owner, type, networkId, false, true, requestedIp, isSystem, null); } @Override - public PublicIp assignPublicIpAddressFromVlans(long dcId, Long podId, Account owner, VlanType type, List vlanDbIds, Long networkId, String requestedIp, - boolean isSystem) throws InsufficientAddressCapacityException { + public PublicIp assignPublicIpAddressFromVlans(long dcId, Long podId, Account owner, VlanType type, List vlanDbIds, Long networkId, String requestedIp, boolean isSystem) + throws InsufficientAddressCapacityException { return fetchNewPublicIp(dcId, podId, vlanDbIds, owner, type, networkId, false, true, requestedIp, isSystem, null); } @DB - public PublicIp fetchNewPublicIp(final long dcId, final Long podId, final List vlanDbIds, final Account owner, final VlanType vlanUse, - final Long guestNetworkId, final boolean sourceNat, final boolean assign, final String requestedIp, final boolean isSystem, final Long vpcId) - throws InsufficientAddressCapacityException { + public PublicIp fetchNewPublicIp(final long dcId, final Long podId, final List vlanDbIds, final Account owner, final VlanType vlanUse, final Long guestNetworkId, + final boolean sourceNat, final boolean assign, final String requestedIp, final boolean isSystem, final Long vpcId) throws InsufficientAddressCapacityException { IPAddressVO addr = Transaction.execute(new TransactionCallbackWithException() { @Override public IPAddressVO doInTransaction(TransactionStatus status) throws InsufficientAddressCapacityException { @@ -687,10 +687,10 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage if (dedicatedVlanDbIds != null && !dedicatedVlanDbIds.isEmpty()) { fetchFromDedicatedRange = true; sc.setParameters("vlanId", dedicatedVlanDbIds.toArray()); - errorMessage.append(", vlanId id=" + dedicatedVlanDbIds.toArray()); + errorMessage.append(", vlanId id=" + Arrays.toString(dedicatedVlanDbIds.toArray())); } else if (nonDedicatedVlanDbIds != null && !nonDedicatedVlanDbIds.isEmpty()) { sc.setParameters("vlanId", nonDedicatedVlanDbIds.toArray()); - errorMessage.append(", vlanId id=" + nonDedicatedVlanDbIds.toArray()); + errorMessage.append(", vlanId id=" + Arrays.toString(nonDedicatedVlanDbIds.toArray())); } else { if (podId != null) { InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException("Insufficient address capacity", Pod.class, podId); @@ -730,7 +730,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage if (useSystemIps && nonDedicatedVlanDbIds != null && !nonDedicatedVlanDbIds.isEmpty()) { fetchFromDedicatedRange = false; sc.setParameters("vlanId", nonDedicatedVlanDbIds.toArray()); - errorMessage.append(", vlanId id=" + nonDedicatedVlanDbIds.toArray()); + errorMessage.append(", vlanId id=" + Arrays.toString(nonDedicatedVlanDbIds.toArray())); addrs = _ipAddressDao.lockRows(sc, filter, true); } } @@ -796,8 +796,8 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage @Override public void markPublicIpAsAllocated(final IPAddressVO addr) { - assert (addr.getState() == IpAddress.State.Allocating || addr.getState() == IpAddress.State.Free) : "Unable to transition from state " + addr.getState() + - " to " + IpAddress.State.Allocated; + assert (addr.getState() == IpAddress.State.Allocating || addr.getState() == IpAddress.State.Free) : "Unable to transition from state " + addr.getState() + " to " + + IpAddress.State.Allocated; Transaction.execute(new TransactionCallbackNoReturn() { @Override public void doInTransactionWithoutResult(TransactionStatus status) { @@ -813,8 +813,8 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage String guestType = vlan.getVlanType().toString(); if (!isIpDedicated(addr)) { - UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_IP_ASSIGN, owner.getId(), addr.getDataCenterId(), addr.getId(), addr.getAddress() - .toString(), addr.isSourceNat(), guestType, addr.getSystem(), addr.getClass().getName(), addr.getUuid()); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_IP_ASSIGN, owner.getId(), addr.getDataCenterId(), addr.getId(), addr.getAddress().toString(), + addr.isSourceNat(), guestType, addr.getSystem(), addr.getClass().getName(), addr.getUuid()); } if (updateIpResourceCount(addr)) { @@ -835,7 +835,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage @Override public PublicIp assignSourceNatIpAddressToGuestNetwork(Account owner, Network guestNetwork) throws InsufficientAddressCapacityException, ConcurrentOperationException { assert (guestNetwork.getTrafficType() != null) : "You're asking for a source nat but your network " - + "can't participate in source nat. What do you have to say for yourself?"; + + "can't participate in source nat. What do you have to say for yourself?"; long dcId = guestNetwork.getDataCenterId(); IPAddressVO sourceNatIp = getExistingSourceNatInNetwork(owner.getId(), guestNetwork.getId()); @@ -853,7 +853,12 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage @DB @Override public PublicIp assignDedicateIpAddress(Account owner, final Long guestNtwkId, final Long vpcId, final long dcId, final boolean isSourceNat) - throws ConcurrentOperationException, InsufficientAddressCapacityException { + throws ConcurrentOperationException, InsufficientAddressCapacityException { + + if (owner == null) { + s_logger.error("No account to assign an ip to."); + return null; + } final long ownerId = owner.getId(); @@ -886,13 +891,11 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage return ip; } finally { - if (owner != null) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Releasing lock account " + ownerId); - } - - _accountDao.releaseFromLockTable(ownerId); + if (s_logger.isDebugEnabled()) { + s_logger.debug("Releasing lock account " + ownerId); } + _accountDao.releaseFromLockTable(ownerId); + if (ip == null) { s_logger.error("Unable to get source nat ip address for account " + ownerId); } @@ -932,7 +935,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage // but still be associated with the account. Its up to caller of this function to decide when to invoke IPAssociation @Override public boolean applyIpAssociations(Network network, boolean postApplyRules, boolean continueOnError, List publicIps) - throws ResourceUnavailableException { + throws ResourceUnavailableException { boolean success = true; Map> ipToServices = _networkModel.getIpToServices(publicIps, postApplyRules, true); @@ -976,8 +979,8 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage @DB @Override - public IpAddress allocateIp(final Account ipOwner, final boolean isSystem, Account caller, long callerUserId, final DataCenter zone) - throws ConcurrentOperationException, ResourceAllocationException, InsufficientAddressCapacityException { + public IpAddress allocateIp(final Account ipOwner, final boolean isSystem, Account caller, long callerUserId, final DataCenter zone) throws ConcurrentOperationException, + ResourceAllocationException, InsufficientAddressCapacityException { final VlanType vlanType = VlanType.VirtualNetwork; final boolean assign = false; @@ -1012,8 +1015,8 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage PublicIp ip = fetchNewPublicIp(zone.getId(), null, null, ipOwner, vlanType, null, false, assign, null, isSystem, null); if (ip == null) { - InsufficientAddressCapacityException ex = - new InsufficientAddressCapacityException("Unable to find available public IP addresses", DataCenter.class, zone.getId()); + InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException("Unable to find available public IP addresses", DataCenter.class, zone + .getId()); ex.addProxyObject(ApiDBUtils.findZoneById(zone.getId()).getUuid()); throw ex; } @@ -1040,8 +1043,8 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage @Override @DB - public IpAddress allocatePortableIp(final Account ipOwner, Account caller, final long dcId, final Long networkId, final Long vpcID) - throws ConcurrentOperationException, ResourceAllocationException, InsufficientAddressCapacityException { + public IpAddress allocatePortableIp(final Account ipOwner, Account caller, final long dcId, final Long networkId, final Long vpcID) throws ConcurrentOperationException, + ResourceAllocationException, InsufficientAddressCapacityException { GlobalLock portableIpLock = GlobalLock.getInternLock("PortablePublicIpRange"); IPAddressVO ipaddr; @@ -1056,8 +1059,8 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage List portableIpVOs = _portableIpDao.listByRegionIdAndState(1, PortableIp.State.Free); if (portableIpVOs == null || portableIpVOs.isEmpty()) { - InsufficientAddressCapacityException ex = - new InsufficientAddressCapacityException("Unable to find available portable IP addresses", Region.class, new Long(1)); + InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException("Unable to find available portable IP addresses", Region.class, + new Long(1)); throw ex; } @@ -1077,22 +1080,20 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage long physicalNetworkId = _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(dcId, TrafficType.Public).getId(); Network network = _networkModel.getSystemNetworkByZoneAndTrafficType(dcId, TrafficType.Public); String range = allocatedPortableIp.getAddress() + "-" + allocatedPortableIp.getAddress(); - VlanVO vlan = - new VlanVO(VlanType.VirtualNetwork, allocatedPortableIp.getVlan(), allocatedPortableIp.getGateway(), allocatedPortableIp.getNetmask(), dcId, + VlanVO vlan = new VlanVO(VlanType.VirtualNetwork, allocatedPortableIp.getVlan(), allocatedPortableIp.getGateway(), allocatedPortableIp.getNetmask(), dcId, range, network.getId(), physicalNetworkId, null, null, null); vlan = _vlanDao.persist(vlan); // provision the portable IP in to user_ip_address table - IPAddressVO ipaddr = - new IPAddressVO(new Ip(allocatedPortableIp.getAddress()), dcId, networkId, vpcID, physicalNetworkId, network.getId(), vlan.getId(), true); + IPAddressVO ipaddr = new IPAddressVO(new Ip(allocatedPortableIp.getAddress()), dcId, networkId, vpcID, physicalNetworkId, network.getId(), vlan.getId(), true); ipaddr.setState(State.Allocated); ipaddr.setAllocatedTime(new Date()); ipaddr.setAllocatedInDomainId(ipOwner.getDomainId()); ipaddr.setAllocatedToAccountId(ipOwner.getId()); ipaddr = _ipAddressDao.persist(ipaddr); - UsageEventUtils.publishUsageEvent(EventTypes.EVENT_PORTABLE_IP_ASSIGN, ipaddr.getId(), ipaddr.getDataCenterId(), ipaddr.getId(), ipaddr.getAddress() - .toString(), ipaddr.isSourceNat(), null, ipaddr.getSystem(), ipaddr.getClass().getName(), ipaddr.getUuid()); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_PORTABLE_IP_ASSIGN, ipaddr.getId(), ipaddr.getDataCenterId(), ipaddr.getId(), + ipaddr.getAddress().toString(), ipaddr.isSourceNat(), null, ipaddr.getSystem(), ipaddr.getClass().getName(), ipaddr.getUuid()); return ipaddr; } @@ -1105,8 +1106,14 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage } protected IPAddressVO getExistingSourceNatInNetwork(long ownerId, Long networkId) { - - List addrs = _networkModel.listPublicIpsAssignedToGuestNtwk(ownerId, networkId, true); + List addrs; + Network guestNetwork = _networksDao.findById(networkId); + if (guestNetwork.getGuestType() == GuestType.Shared) { + // ignore the account id for the shared network + addrs = _networkModel.listPublicIpsAssignedToGuestNtwk(networkId, true); + } else { + addrs = _networkModel.listPublicIpsAssignedToGuestNtwk(ownerId, networkId, true); + } IPAddressVO sourceNatIp = null; if (addrs.isEmpty()) { @@ -1129,7 +1136,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage @DB @Override public IPAddressVO associateIPToGuestNetwork(long ipId, long networkId, boolean releaseOnFailure) throws ResourceAllocationException, ResourceUnavailableException, - InsufficientAddressCapacityException, ConcurrentOperationException { + InsufficientAddressCapacityException, ConcurrentOperationException { Account caller = CallContext.current().getCallingAccount(); Account owner = null; @@ -1147,7 +1154,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage _accountMgr.checkAccess(CallContext.current().getCallingAccount(), AccessType.UseNetwork, false, network); } else { throw new InvalidParameterValueException("IP can be associated with guest network of 'shared' type only if " - + "network services Source Nat, Static Nat, Port Forwarding, Load balancing, firewall are enabled in the network"); + + "network services Source Nat, Static Nat, Port Forwarding, Load balancing, firewall are enabled in the network"); } } } else { @@ -1192,15 +1199,15 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage if (zone.getNetworkType() == NetworkType.Advanced) { // In Advance zone allow to do IP assoc only for Isolated networks with source nat service enabled if (network.getGuestType() == GuestType.Isolated && !(_networkModel.areServicesSupportedInNetwork(network.getId(), Service.SourceNat))) { - throw new InvalidParameterValueException("In zone of type " + NetworkType.Advanced + " ip address can be associated only to the network of guest type " + - GuestType.Isolated + " with the " + Service.SourceNat.getName() + " enabled"); + throw new InvalidParameterValueException("In zone of type " + NetworkType.Advanced + " ip address can be associated only to the network of guest type " + + GuestType.Isolated + " with the " + Service.SourceNat.getName() + " enabled"); } // In Advance zone allow to do IP assoc only for shared networks with source nat/static nat/lb/pf services enabled if (network.getGuestType() == GuestType.Shared && !isSharedNetworkOfferingWithServices(network.getNetworkOfferingId())) { - throw new InvalidParameterValueException("In zone of type " + NetworkType.Advanced + " ip address can be associated with network of guest type " + - GuestType.Shared + "only if at " + "least one of the services " + Service.SourceNat.getName() + "/" + Service.StaticNat.getName() + "/" + - Service.Lb.getName() + "/" + Service.PortForwarding.getName() + " is enabled"); + throw new InvalidParameterValueException("In zone of type " + NetworkType.Advanced + " ip address can be associated with network of guest type " + GuestType.Shared + + "only if at " + "least one of the services " + Service.SourceNat.getName() + "/" + Service.StaticNat.getName() + "/" + Service.Lb.getName() + "/" + + Service.PortForwarding.getName() + " is enabled"); } } @@ -1217,7 +1224,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage s_logger.debug("Associating ip " + ipToAssoc + " to network " + network); - IPAddressVO ip = _ipAddressDao.findById(ipId); + IPAddressVO ip = ipToAssoc; //_ipAddressDao.findById(ipId); //update ip address with networkId ip.setAssociatedWithNetworkId(networkId); ip.setSourceNat(isSourceNat); @@ -1234,18 +1241,16 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage return ip; } finally { if (!success && releaseOnFailure) { - if (ip != null) { - try { - s_logger.warn("Failed to associate ip address, so releasing ip from the database " + ip); - _ipAddressDao.markAsUnavailable(ip.getId()); - if (!applyIpAssociations(network, true)) { - // if fail to apply ip assciations again, unassign ip address without updating resource - // count and generating usage event as there is no need to keep it in the db - _ipAddressDao.unassignIpAddress(ip.getId()); - } - } catch (Exception e) { - s_logger.warn("Unable to disassociate ip address for recovery", e); + try { + s_logger.warn("Failed to associate ip address, so releasing ip from the database " + ip); + _ipAddressDao.markAsUnavailable(ip.getId()); + if (!applyIpAssociations(network, true)) { + // if fail to apply ip assciations again, unassign ip address without updating resource + // count and generating usage event as there is no need to keep it in the db + _ipAddressDao.unassignIpAddress(ip.getId()); } + } catch (Exception e) { + s_logger.warn("Unable to disassociate ip address for recovery", e); } } } @@ -1253,27 +1258,27 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage protected boolean isSharedNetworkOfferingWithServices(long networkOfferingId) { NetworkOfferingVO networkOffering = _networkOfferingDao.findById(networkOfferingId); - if ((networkOffering.getGuestType() == Network.GuestType.Shared) && - (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.SourceNat) || - _networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.StaticNat) || - _networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Firewall) || - _networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.PortForwarding) || _networkModel.areServicesSupportedByNetworkOffering( - networkOfferingId, Service.Lb))) { + if ((networkOffering.getGuestType() == Network.GuestType.Shared) + && (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.SourceNat) + || _networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.StaticNat) + || _networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Firewall) + || _networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.PortForwarding) || _networkModel.areServicesSupportedByNetworkOffering( + networkOfferingId, Service.Lb))) { return true; } return false; } @Override - public IPAddressVO associatePortableIPToGuestNetwork(long ipAddrId, long networkId, boolean releaseOnFailure) throws ResourceAllocationException, - ResourceUnavailableException, InsufficientAddressCapacityException, ConcurrentOperationException { + public IPAddressVO associatePortableIPToGuestNetwork(long ipAddrId, long networkId, boolean releaseOnFailure) throws ResourceAllocationException, ResourceUnavailableException, + InsufficientAddressCapacityException, ConcurrentOperationException { return associateIPToGuestNetwork(ipAddrId, networkId, releaseOnFailure); } @DB @Override public IPAddressVO disassociatePortableIPToGuestNetwork(long ipId, long networkId) throws ResourceAllocationException, ResourceUnavailableException, - InsufficientAddressCapacityException, ConcurrentOperationException { + InsufficientAddressCapacityException, ConcurrentOperationException { Account caller = CallContext.current().getCallingAccount(); Account owner = null; @@ -1326,7 +1331,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage PublicIp publicIp = PublicIp.createFromAddrAndVlan(ipToAssoc, _vlanDao.findById(ipToAssoc.getVlanId())); ipList.add(publicIp); Map> ipToServices = _networkModel.getIpToServices(ipList, false, true); - if (ipToServices != null & !ipToServices.isEmpty()) { + if (ipToServices != null && !ipToServices.isEmpty()) { Set services = ipToServices.get(publicIp); if (services != null && !services.isEmpty()) { throw new InvalidParameterValueException("IP " + ipToAssoc + " has services and rules associated in the network " + networkId); @@ -1367,7 +1372,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage PublicIp publicIp = PublicIp.createFromAddrAndVlan(ip, _vlanDao.findById(ip.getVlanId())); ipList.add(publicIp); Map> ipToServices = _networkModel.getIpToServices(ipList, false, true); - if (ipToServices != null & !ipToServices.isEmpty()) { + if (ipToServices != null && !ipToServices.isEmpty()) { Set ipServices = ipToServices.get(publicIp); if (ipServices != null && !ipServices.isEmpty()) { return false; @@ -1380,7 +1385,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage @DB @Override public void transferPortableIP(final long ipAddrId, long currentNetworkId, long newNetworkId) throws ResourceAllocationException, ResourceUnavailableException, - InsufficientAddressCapacityException, ConcurrentOperationException { + InsufficientAddressCapacityException, ConcurrentOperationException { Network srcNetwork = _networksDao.findById(currentNetworkId); if (srcNetwork == null) { @@ -1448,7 +1453,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage // trigger an action event for the transfer of portable IP across the networks, so that external entities // monitoring for this event can initiate the route advertisement for the availability of IP from the zoe ActionEventUtils.onActionEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, Domain.ROOT_DOMAIN, EventTypes.EVENT_PORTABLE_IP_TRANSFER, - "Portable IP associated is transferred from network " + currentNetworkId + " to " + newNetworkId); + "Portable IP associated is transferred from network " + currentNetworkId + " to " + newNetworkId); } protected List getIsolatedNetworksWithSourceNATOwnedByAccountInZone(long zoneId, Account owner) { @@ -1459,7 +1464,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage @Override @DB public boolean associateIpAddressListToAccount(long userId, final long accountId, final long zoneId, final Long vlanId, final Network guestNetworkFinal) - throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, ResourceAllocationException { + throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, ResourceAllocationException { final Account owner = _accountMgr.getActiveAccountById(accountId); if (guestNetworkFinal != null && guestNetworkFinal.getTrafficType() != TrafficType.Guest) { @@ -1471,7 +1476,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage pair = Transaction.execute(new TransactionCallbackWithException, Network>, Exception>() { @Override public Ternary, Network> doInTransaction(TransactionStatus status) throws InsufficientCapacityException, - ResourceAllocationException { + ResourceAllocationException { boolean createNetwork = false; Network guestNetwork = guestNetworkFinal; @@ -1483,41 +1488,37 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage guestNetwork = networks.get(0); } else { throw new InvalidParameterValueException("Error, more than 1 Guest Isolated Networks with SourceNAT " - + "service enabled found for this account, cannot assosiate the IP range, please provide the network ID"); + + "service enabled found for this account, cannot assosiate the IP range, please provide the network ID"); } } // create new Virtual network (Isolated with SourceNAT) for the user if it doesn't exist List requiredOfferings = _networkOfferingDao.listByAvailability(Availability.Required, false); if (requiredOfferings.size() < 1) { - throw new CloudRuntimeException("Unable to find network offering with availability=" + Availability.Required + - " to automatically create the network as part of createVlanIpRange"); + throw new CloudRuntimeException("Unable to find network offering with availability=" + Availability.Required + + " to automatically create the network as part of createVlanIpRange"); } if (createNetwork) { if (requiredOfferings.get(0).getState() == NetworkOffering.State.Enabled) { - long physicalNetworkId = - _networkModel.findPhysicalNetworkId(zoneId, requiredOfferings.get(0).getTags(), requiredOfferings.get(0).getTrafficType()); + long physicalNetworkId = _networkModel.findPhysicalNetworkId(zoneId, requiredOfferings.get(0).getTags(), requiredOfferings.get(0).getTrafficType()); // Validate physical network PhysicalNetwork physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId); if (physicalNetwork == null) { - throw new InvalidParameterValueException("Unable to find physical network with id: " + physicalNetworkId + " and tag: " + - requiredOfferings.get(0).getTags()); + throw new InvalidParameterValueException("Unable to find physical network with id: " + physicalNetworkId + " and tag: " + + requiredOfferings.get(0).getTags()); } - s_logger.debug("Creating network for account " + owner + " from the network offering id=" + requiredOfferings.get(0).getId() + - " as a part of createVlanIpRange process"); - guestNetwork = - _networkMgr.createGuestNetwork(requiredOfferings.get(0).getId(), owner.getAccountName() + "-network", - owner.getAccountName() + "-network", null, null, null, null, owner, null, physicalNetwork, zoneId, ACLType.Account, null, null, null, - null, true, null); + s_logger.debug("Creating network for account " + owner + " from the network offering id=" + requiredOfferings.get(0).getId() + + " as a part of createVlanIpRange process"); + guestNetwork = _networkMgr.createGuestNetwork(requiredOfferings.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + + "-network", null, null, null, null, owner, null, physicalNetwork, zoneId, ACLType.Account, null, null, null, null, true, null); if (guestNetwork == null) { s_logger.warn("Failed to create default Virtual network for the account " + accountId + "in zone " + zoneId); - throw new CloudRuntimeException("Failed to create a Guest Isolated Networks with SourceNAT " + - "service enabled as a part of createVlanIpRange, for the account " + accountId + "in zone " + zoneId); + throw new CloudRuntimeException("Failed to create a Guest Isolated Networks with SourceNAT " + + "service enabled as a part of createVlanIpRange, for the account " + accountId + "in zone " + zoneId); } } else { - throw new CloudRuntimeException("Required network offering id=" + requiredOfferings.get(0).getId() + " is not in " + - NetworkOffering.State.Enabled); + throw new CloudRuntimeException("Required network offering id=" + requiredOfferings.get(0).getId() + " is not in " + NetworkOffering.State.Enabled); } } @@ -1580,8 +1581,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage guestNetwork = implementedNetwork.second(); } catch (Exception ex) { s_logger.warn("Failed to implement network " + guestNetwork + " elements and resources as a part of" + " network provision due to ", ex); - CloudRuntimeException e = - new CloudRuntimeException("Failed to implement network (with specified id)" + CloudRuntimeException e = new CloudRuntimeException("Failed to implement network (with specified id)" + " elements and resources as a part of network provision for persistent network"); e.addProxyObject(guestNetwork.getUuid(), "networkId"); throw e; @@ -1615,8 +1615,8 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage String guestType = vlan.getVlanType().toString(); if (!isIpDedicated(ip)) { String eventType = ip.isPortable() ? EventTypes.EVENT_PORTABLE_IP_RELEASE : EventTypes.EVENT_NET_IP_RELEASE; - UsageEventUtils.publishUsageEvent(eventType, ip.getAllocatedToAccountId(), ip.getDataCenterId(), addrId, ip.getAddress().addr(), - ip.isSourceNat(), guestType, ip.getSystem(), ip.getClass().getName(), ip.getUuid()); + UsageEventUtils.publishUsageEvent(eventType, ip.getAllocatedToAccountId(), ip.getDataCenterId(), addrId, ip.getAddress().addr(), ip.isSourceNat(), + guestType, ip.getSystem(), ip.getClass().getName(), ip.getUuid()); } } @@ -1644,7 +1644,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage Set availableIps = _networkModel.getAvailableIps(network, requestedIp); if (availableIps == null || availableIps.isEmpty()) { - s_logger.debug("There are no free ips in the network " + network ); + s_logger.debug("There are no free ips in the network " + network); return null; } @@ -1675,14 +1675,14 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage @Override public boolean applyStaticNats(List staticNats, boolean continueOnError, boolean forRevoke) throws ResourceUnavailableException { - Network network = _networksDao.findById(staticNats.get(0).getNetworkId()); - boolean success = true; - if (staticNats == null || staticNats.size() == 0) { s_logger.debug("There are no static nat rules for the network elements"); return true; } + Network network = _networksDao.findById(staticNats.get(0).getNetworkId()); + boolean success = true; + // get the list of public ip's owned by the network List userIps = _ipAddressDao.listByAssociatedNetwork(network.getId(), null); List publicIps = new ArrayList(); @@ -1811,7 +1811,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage @Override @DB public void allocateDirectIp(final NicProfile nic, final DataCenter dc, final VirtualMachineProfile vm, final Network network, final String requestedIpv4, - final String requestedIpv6) throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException { + final String requestedIpv6) throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException { Transaction.execute(new TransactionCallbackWithExceptionNoReturn() { @Override public void doInTransactionWithoutResult(TransactionStatus status) throws InsufficientAddressCapacityException { @@ -1892,8 +1892,8 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage } @Override - public String allocatePublicIpForGuestNic(Long networkId, DataCenter dc, Pod pod, Account owner, String requestedIp) throws InsufficientAddressCapacityException { - PublicIp ip = assignPublicIpAddress(dc.getId(), null, owner, VlanType.DirectAttached, networkId, requestedIp, false); + public String allocatePublicIpForGuestNic(Network network, Long podId, Account owner, String requestedIp) throws InsufficientAddressCapacityException { + PublicIp ip = assignPublicIpAddress(network.getDataCenterId(), podId, owner, VlanType.DirectAttached, network.getId(), requestedIp, false); if (ip == null) { s_logger.debug("There is no free public ip address"); return null; @@ -1903,16 +1903,8 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage } @Override - public String allocateGuestIP(Account ipOwner, boolean isSystem, long zoneId, Long networkId, String requestedIp) throws InsufficientAddressCapacityException { - String ipaddr = null; - Account caller = CallContext.current().getCallingAccount(); - // check permissions - Network network = _networksDao.findById(networkId); - - _accountMgr.checkAccess(caller, null, false, network); - - ipaddr = acquireGuestIpAddress(network, requestedIp); - return ipaddr; + public String allocateGuestIP(Network network, String requestedIp) throws InsufficientAddressCapacityException { + return acquireGuestIpAddress(network, requestedIp); } @Override diff --git a/server/src/com/cloud/network/NetworkModelImpl.java b/server/src/com/cloud/network/NetworkModelImpl.java index 71fbbf5c149..68807d38939 100755 --- a/server/src/com/cloud/network/NetworkModelImpl.java +++ b/server/src/com/cloud/network/NetworkModelImpl.java @@ -154,14 +154,14 @@ public class NetworkModelImpl extends ManagerBase implements NetworkModel { @Inject ConfigurationServer _configServer; - List _networkElements; + List networkElements; public List getNetworkElements() { - return _networkElements; + return networkElements; } - public void setNetworkElements(List _networkElements) { - this._networkElements = _networkElements; + public void setNetworkElements(List networkElements) { + this.networkElements = networkElements; } @Inject @@ -200,7 +200,7 @@ public class NetworkModelImpl extends ManagerBase implements NetworkModel { NetworkOfferingDetailsDao _ntwkOffDetailsDao; private final HashMap _systemNetworks = new HashMap(5); - static Long _privateOfferingId = null; + static Long s_privateOfferingId = null; SearchBuilder IpAddressSearch; SearchBuilder NicForTrafficTypeSearch; @@ -226,7 +226,7 @@ public class NetworkModelImpl extends ManagerBase implements NetworkModel { @Override public NetworkElement getElementImplementingProvider(String providerName) { String elementName = s_providerToNetworkElementMap.get(providerName); - NetworkElement element = AdapterBase.getAdapterByName(_networkElements, elementName); + NetworkElement element = AdapterBase.getAdapterByName(networkElements, elementName); return element; } @@ -296,7 +296,7 @@ public class NetworkModelImpl extends ManagerBase implements NetworkModel { ex.addProxyObject(ipAddrUuid, "networkId"); throw ex; } - } + } ipToServices.put(ip, services); // if IP in allocating state then it will not have any rules attached so skip IPAssoc to network service @@ -433,9 +433,9 @@ public class NetworkModelImpl extends ManagerBase implements NetworkModel { NetworkElement oldElement = getElementImplementingProvider(oldProvider.getName()); NetworkElement newElement = getElementImplementingProvider(newProvider.getName()); if (oldElement instanceof IpDeployingRequester && newElement instanceof IpDeployingRequester) { - IpDeployer oldIpDeployer = ((IpDeployingRequester)oldElement).getIpDeployer(network); - IpDeployer newIpDeployer = ((IpDeployingRequester)newElement).getIpDeployer(network); - // FIXME: I ignored this check + IpDeployer oldIpDeployer = ((IpDeployingRequester)oldElement).getIpDeployer(network); + IpDeployer newIpDeployer = ((IpDeployingRequester)newElement).getIpDeployer(network); + // FIXME: I ignored this check } else { throw new InvalidParameterException("Ip cannot be applied for new provider!"); } @@ -523,6 +523,19 @@ public class NetworkModelImpl extends ManagerBase implements NetworkModel { return _ipAddressDao.search(sc, null); } + @Override + public List listPublicIpsAssignedToGuestNtwk(long associatedNetworkId, Boolean sourceNat) { + SearchCriteria sc = IpAddressSearch.create(); + sc.setParameters("associatedWithNetworkId", associatedNetworkId); + + if (sourceNat != null) { + sc.addAnd("sourceNat", SearchCriteria.Op.EQ, sourceNat); + } + sc.setJoinParameters("virtualNetworkVlanSB", "vlanType", VlanType.VirtualNetwork); + + return _ipAddressDao.search(sc, null); + } + @Override public List listPublicIpsAssignedToAccount(long accountId, long dcId, Boolean sourceNat) { SearchCriteria sc = IpAddressSearch.create(); @@ -1004,14 +1017,14 @@ public class NetworkModelImpl extends ManagerBase implements NetworkModel { List map = _ntwkOfferingSrvcDao.listByNetworkOfferingId(networkOfferingId); for (NetworkOfferingServiceMapVO instance : map) { - String service = instance.getService(); + Service service = Network.Service.getService(instance.getService()); Set providers; providers = serviceProviderMap.get(service); if (providers == null) { providers = new HashSet(); } providers.add(Provider.getProvider(instance.getProvider())); - serviceProviderMap.put(Service.getService(service), providers); + serviceProviderMap.put(service, providers); } return serviceProviderMap; @@ -1520,6 +1533,9 @@ public class NetworkModelImpl extends ManagerBase implements NetworkModel { @Override public void checkNetworkPermissions(Account owner, Network network) { + if (network == null) { + throw new CloudRuntimeException("no network to check permissions for."); + } // Perform account permission check if (network.getGuestType() != Network.GuestType.Shared || (network.getGuestType() == Network.GuestType.Shared && network.getAclType() == ACLType.Account)) { AccountVO networkOwner = _accountDao.findById(network.getAccountId()); @@ -1654,7 +1670,7 @@ public class NetworkModelImpl extends ManagerBase implements NetworkModel { @Override public boolean isPrivateGateway(Nic guestNic) { Network network = getNetwork(guestNic.getNetworkId()); - if (network.getTrafficType() != TrafficType.Guest || network.getNetworkOfferingId() != _privateOfferingId.longValue()) { + if (network.getTrafficType() != TrafficType.Guest || network.getNetworkOfferingId() != s_privateOfferingId.longValue()) { return false; } return true; @@ -1929,7 +1945,7 @@ public class NetworkModelImpl extends ManagerBase implements NetworkModel { NetworkOfferingVO privateGatewayNetworkOffering = new NetworkOfferingVO(NetworkOffering.SystemPrivateGatewayNetworkOffering, GuestType.Isolated); privateGatewayNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(privateGatewayNetworkOffering); _systemNetworks.put(NetworkOffering.SystemPrivateGatewayNetworkOffering, privateGatewayNetworkOffering); - _privateOfferingId = privateGatewayNetworkOffering.getId(); + s_privateOfferingId = privateGatewayNetworkOffering.getId(); IpAddressSearch = _ipAddressDao.createSearchBuilder(); IpAddressSearch.and("accountId", IpAddressSearch.entity().getAllocatedToAccountId(), Op.EQ); @@ -1958,7 +1974,7 @@ public class NetworkModelImpl extends ManagerBase implements NetworkModel { public boolean start() { // populate s_serviceToImplementedProvidersMap & s_providerToNetworkElementMap with current _networkElements // Need to do this in start() since _networkElements are not completely configured until then. - for (NetworkElement element : _networkElements) { + for (NetworkElement element : networkElements) { Map> capabilities = element.getCapabilities(); Provider implementedProvider = element.getProvider(); if (implementedProvider != null) { @@ -2185,7 +2201,7 @@ public class NetworkModelImpl extends ManagerBase implements NetworkModel { } @Override - public boolean getNetworkEgressDefaultPolicy (Long networkId) { + public boolean getNetworkEgressDefaultPolicy(Long networkId) { NetworkVO network = _networksDao.findById(networkId); if (network != null) { diff --git a/server/src/com/cloud/network/NetworkServiceImpl.java b/server/src/com/cloud/network/NetworkServiceImpl.java index cf4a1c50bf2..d02f1760e1d 100755 --- a/server/src/com/cloud/network/NetworkServiceImpl.java +++ b/server/src/com/cloud/network/NetworkServiceImpl.java @@ -19,7 +19,6 @@ package com.cloud.network; import java.net.Inet6Address; import java.net.InetAddress; import java.net.URI; - import java.net.UnknownHostException; import java.security.InvalidParameterException; import java.sql.PreparedStatement; @@ -41,8 +40,6 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; -import org.apache.log4j.Logger; - import org.apache.cloudstack.acl.ControlledEntity.ACLType; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.command.admin.network.DedicateGuestVlanRangeCmd; @@ -56,15 +53,16 @@ import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.network.element.InternalLoadBalancerElementService; +import org.apache.log4j.Logger; import com.cloud.api.ApiDBUtils; import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationManager; +import com.cloud.configuration.Resource; import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter.NetworkType; import com.cloud.dc.DataCenterVO; import com.cloud.dc.DataCenterVnetVO; -import com.cloud.dc.Pod; import com.cloud.dc.Vlan.VlanType; import com.cloud.dc.VlanVO; import com.cloud.dc.dao.AccountVlanMapDao; @@ -294,19 +292,19 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { @Inject InternalLoadBalancerElementService _internalLbElementSvc; @Inject - DataCenterVnetDao _datacneter_vnet; + DataCenterVnetDao _datacneterVnet; @Inject AccountGuestVlanMapDao _accountGuestVlanMapDao; @Inject VpcDao _vpcDao; @Inject NetworkACLDao _networkACLDao; - @Inject - OvsProviderDao _ovsProviderDao; - @Inject - IpAddressManager _ipAddrMgr; - @Inject - EntityManager _entityMgr; + @Inject + OvsProviderDao _ovsProviderDao; + @Inject + IpAddressManager _ipAddrMgr; + @Inject + EntityManager _entityMgr; int _cidrLimit; boolean _allowSubdomainNetworkAccess; @@ -425,8 +423,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { throw new InvalidParameterException("There are multiple services used ip " + ip.getAddress() + "."); } if (service != null && !((Service)services.toArray()[0] == service || service.equals(Service.Firewall))) { - throw new InvalidParameterException("The IP " + ip.getAddress() + " is already used as " + ((Service)services.toArray()[0]).getName() + " rather than " + - service.getName()); + throw new InvalidParameterException("The IP " + ip.getAddress() + " is already used as " + ((Service)services.toArray()[0]).getName() + " rather than " + + service.getName()); } return true; } @@ -516,7 +514,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { @Override @ActionEvent(eventType = EventTypes.EVENT_NET_IP_ASSIGN, eventDescription = "allocating Ip", create = true) public IpAddress allocateIP(Account ipOwner, long zoneId, Long networkId) throws ResourceAllocationException, InsufficientAddressCapacityException, - ConcurrentOperationException { + ConcurrentOperationException { Account caller = CallContext.current().getCallingAccount(); long callerUserId = CallContext.current().getCallingUserId(); @@ -542,7 +540,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { return _ipAddrMgr.allocateIp(ipOwner, false, caller, callerUserId, zone); } else { throw new InvalidParameterValueException("Associate IP address can only be called on the shared networks in the advanced zone" - + " with Firewall/Source Nat/Static Nat/Port Forwarding/Load balancing services enabled"); + + " with Firewall/Source Nat/Static Nat/Port Forwarding/Load balancing services enabled"); } } } @@ -556,7 +554,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { @Override @ActionEvent(eventType = EventTypes.EVENT_PORTABLE_IP_ASSIGN, eventDescription = "allocating portable public Ip", create = true) public IpAddress allocatePortableIP(Account ipOwner, int regionId, Long zoneId, Long networkId, Long vpcId) throws ResourceAllocationException, - InsufficientAddressCapacityException, ConcurrentOperationException { + InsufficientAddressCapacityException, ConcurrentOperationException { Account caller = CallContext.current().getCallingAccount(); long callerUserId = CallContext.current().getCallingUserId(); DataCenter zone = _entityMgr.findById(DataCenter.class, zoneId); @@ -585,7 +583,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { return _ipAddrMgr.allocatePortableIp(ipOwner, caller, zoneId, networkId, null); } else { throw new InvalidParameterValueException("Associate IP address can only be called on the shared networks in the advanced zone" - + " with Firewall/Source Nat/Static Nat/Port Forwarding/Load balancing services enabled"); + + " with Firewall/Source Nat/Static Nat/Port Forwarding/Load balancing services enabled"); } } } @@ -641,14 +639,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } @Override - public NicSecondaryIp allocateSecondaryGuestIP(Account ipOwner, long zoneId, final Long nicId, final Long networkId, String requestedIp) - throws InsufficientAddressCapacityException { - - String ipaddr = null; - - if (networkId == null) { - throw new InvalidParameterValueException("Invalid network id is given"); - } + public NicSecondaryIp allocateSecondaryGuestIP(final long nicId, String requestedIp) throws InsufficientAddressCapacityException { Account caller = CallContext.current().getCallingAccount(); @@ -666,47 +657,50 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { if (vm == null) { throw new InvalidParameterValueException("There is no vm with the nic"); } + + final long networkId = nicVO.getNetworkId(); + final Account ipOwner = _accountMgr.getAccount(vm.getAccountId()); + // verify permissions - _accountMgr.checkAccess(ipOwner, null, true, vm); + _accountMgr.checkAccess(caller, null, true, vm); Network network = _networksDao.findById(networkId); if (network == null) { throw new InvalidParameterValueException("Invalid network id is given"); } - final Long accountId = ipOwner.getAccountId(); - final Long domainId = ipOwner.getDomainId(); - // Validate network offering - NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(network.getNetworkOfferingId()); - - DataCenter dc = _dcDao.findById(network.getDataCenterId()); - - DataCenter zone = _entityMgr.findById(DataCenter.class, zoneId); - if (zone == null) { - throw new InvalidParameterValueException("Invalid zone Id is given"); + int maxAllowedIpsPerNic = NumbersUtil.parseInt(_configDao.getValue(Config.MaxNumberOfSecondaryIPsPerNIC.key()), 10); + Long nicWiseIpCount = _nicSecondaryIpDao.countByNicId(nicId); + if(nicWiseIpCount.intValue() >= maxAllowedIpsPerNic) { + s_logger.error("Maximum Number of Ips \"vm.network.nic.max.secondary.ipaddresses = \"" + maxAllowedIpsPerNic + " per Nic has been crossed for the nic " + nicId + "."); + throw new InsufficientAddressCapacityException("Maximum Number of Ips per Nic has been crossed.", Nic.class, nicId); } + s_logger.debug("Calling the ip allocation ..."); - if (dc.getNetworkType() == NetworkType.Advanced && network.getGuestType() == Network.GuestType.Isolated) { + String ipaddr = null; + //Isolated network can exist in Basic zone only, so no need to verify the zone type + if (network.getGuestType() == Network.GuestType.Isolated) { try { - ipaddr = _ipAddrMgr.allocateGuestIP(ipOwner, false, zoneId, networkId, requestedIp); + ipaddr = _ipAddrMgr.allocateGuestIP(network, requestedIp); } catch (InsufficientAddressCapacityException e) { throw new InvalidParameterValueException("Allocating guest ip for nic failed"); } - } else if (dc.getNetworkType() == NetworkType.Basic || ntwkOff.getGuestType() == Network.GuestType.Shared) { - //handle the basic networks here - VMInstanceVO vmi = (VMInstanceVO)vm; - Long podId = vmi.getPodIdToDeployIn(); - if (podId == null) { - throw new InvalidParameterValueException("vm pod id is null"); - } - Pod pod = _hostPodDao.findById(podId); - if (pod == null) { - throw new InvalidParameterValueException("vm pod is null"); + } else if (network.getGuestType() == Network.GuestType.Shared) { + //for basic zone, need to provide the podId to ensure proper ip alloation + Long podId = null; + DataCenter dc = _dcDao.findById(network.getDataCenterId()); + + if (dc.getNetworkType() == NetworkType.Basic) { + VMInstanceVO vmi = (VMInstanceVO)vm; + podId = vmi.getPodIdToDeployIn(); + if (podId == null) { + throw new InvalidParameterValueException("vm pod id is null in Basic zone; can't decide the range for ip allocation"); + } } try { - ipaddr = _ipAddrMgr.allocatePublicIpForGuestNic(networkId, dc, pod, caller, requestedIp); + ipaddr = _ipAddrMgr.allocatePublicIpForGuestNic(network, podId, ipOwner, requestedIp); if (ipaddr == null) { throw new InvalidParameterValueException("Allocating ip to guest nic " + nicId + " failed"); } @@ -735,7 +729,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { s_logger.debug("Setting nic_secondary_ip table ..."); Long vmId = nicVO.getInstanceId(); - NicSecondaryIpVO secondaryIpVO = new NicSecondaryIpVO(nicId, addrFinal, vmId, accountId, domainId, networkId); + NicSecondaryIpVO secondaryIpVO = new NicSecondaryIpVO(nicId, addrFinal, vmId, ipOwner.getId(), ipOwner.getDomainId(), networkId); _nicSecondaryIpDao.persist(secondaryIpVO); return secondaryIpVO.getId(); } @@ -756,12 +750,12 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { // Verify input parameters NicSecondaryIpVO secIpVO = _nicSecondaryIpDao.findById(ipAddressId); if (secIpVO == null) { - throw new InvalidParameterValueException("Unable to find ip address by id"); + throw new InvalidParameterValueException("Unable to find secondary ip address by id"); } VirtualMachine vm = _userVmDao.findById(secIpVO.getVmId()); if (vm == null) { - throw new InvalidParameterValueException("There is no vm with the nic"); + throw new InvalidParameterValueException("There is no vm with the given secondary ip"); } // verify permissions _accountMgr.checkAccess(caller, null, true, vm); @@ -790,7 +784,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { throw new InvalidParameterValueException("Invalid zone Id is given"); } - s_logger.debug("Calling the ip allocation ..."); + s_logger.debug("Calling secondary ip " + secIpVO.getIp4Address() + " release "); if (dc.getNetworkType() == NetworkType.Advanced && network.getGuestType() == Network.GuestType.Isolated) { //check PF or static NAT is configured on this ip address String secondaryIp = secIpVO.getIp4Address(); @@ -808,11 +802,10 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { IPAddressVO publicIpVO = _ipAddressDao.findByVmIp(secondaryIp); if (publicIpVO != null) { s_logger.debug("VM nic IP " + secondaryIp + " is associated with the static NAT rule public IP address id " + publicIpVO.getId()); - throw new InvalidParameterValueException("Can' remove the ip " + secondaryIp + "is associate with static NAT rule public IP address id " + - publicIpVO.getId()); + throw new InvalidParameterValueException("Can' remove the ip " + secondaryIp + "is associate with static NAT rule public IP address id " + publicIpVO.getId()); } } else if (dc.getNetworkType() == NetworkType.Basic || ntwkOff.getGuestType() == Network.GuestType.Shared) { - final IPAddressVO ip = _ipAddressDao.findByIpAndNetworkId(secIpVO.getNetworkId(), secIpVO.getIp4Address()); + final IPAddressVO ip = _ipAddressDao.findByIpAndSourceNetworkId(secIpVO.getNetworkId(), secIpVO.getIp4Address()); if (ip != null) { Transaction.execute(new TransactionCallbackNoReturn() { @Override @@ -1066,8 +1059,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } } else if (ntwkOff.getGuestType() == GuestType.Shared) { if (!(aclType == ACLType.Domain || aclType == ACLType.Account)) { - throw new InvalidParameterValueException("AclType should be " + ACLType.Domain + " or " + ACLType.Account + " for network of type " + - Network.GuestType.Shared); + throw new InvalidParameterValueException("AclType should be " + ACLType.Domain + " or " + ACLType.Account + " for network of type " + Network.GuestType.Shared); } } } else { @@ -1097,8 +1089,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { if (domainId != null) { if (ntwkOff.getTrafficType() != TrafficType.Guest || ntwkOff.getGuestType() != Network.GuestType.Shared) { - throw new InvalidParameterValueException("Domain level networks are supported just for traffic type " + TrafficType.Guest + " and guest type " + - Network.GuestType.Shared); + throw new InvalidParameterValueException("Domain level networks are supported just for traffic type " + TrafficType.Guest + " and guest type " + + Network.GuestType.Shared); } DomainVO domain = _domainDao.findById(domainId); @@ -1196,11 +1188,11 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } // Regular user can create Guest Isolated Source Nat enabled network only - if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL && - (ntwkOff.getTrafficType() != TrafficType.Guest || ntwkOff.getGuestType() != Network.GuestType.Isolated && - areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) { - throw new InvalidParameterValueException("Regular user can create a network only from the network" + " offering having traffic type " + TrafficType.Guest + - " and network type " + Network.GuestType.Isolated + " with a service " + Service.SourceNat.getName() + " enabled"); + if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL + && (ntwkOff.getTrafficType() != TrafficType.Guest || ntwkOff.getGuestType() != Network.GuestType.Isolated + && areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) { + throw new InvalidParameterValueException("Regular user can create a network only from the network" + " offering having traffic type " + TrafficType.Guest + + " and network type " + Network.GuestType.Isolated + " with a service " + Service.SourceNat.getName() + " enabled"); } // Don't allow to specify vlan if the caller is not ROOT admin @@ -1261,10 +1253,9 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { throw ex; } - Network network = - commitNetwork(networkOfferingId, gateway, startIP, endIP, netmask, networkDomain, vlanId, name, displayText, caller, physicalNetworkId, zoneId, domainId, - isDomainSpecific, subdomainAccess, vpcId, startIPv6, endIPv6, ip6Gateway, ip6Cidr, displayNetwork, aclId, isolatedPvlan, ntwkOff, pNtwk, aclType, owner, - cidr, createVlan); + Network network = commitNetwork(networkOfferingId, gateway, startIP, endIP, netmask, networkDomain, vlanId, name, displayText, caller, physicalNetworkId, zoneId, domainId, + isDomainSpecific, subdomainAccess, vpcId, startIPv6, endIPv6, ip6Gateway, ip6Cidr, displayNetwork, aclId, isolatedPvlan, ntwkOff, pNtwk, aclType, owner, cidr, + createVlan); // if the network offering has persistent set to true, implement the network if (ntwkOff.getIsPersistent()) { @@ -1293,12 +1284,11 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { return network; } - private Network commitNetwork(final Long networkOfferingId, final String gateway, final String startIP, final String endIP, final String netmask, - final String networkDomain, final String vlanId, final String name, final String displayText, final Account caller, final Long physicalNetworkId, - final Long zoneId, final Long domainId, final boolean isDomainSpecific, final Boolean subdomainAccessFinal, final Long vpcId, final String startIPv6, - final String endIPv6, final String ip6Gateway, final String ip6Cidr, final Boolean displayNetwork, final Long aclId, final String isolatedPvlan, - final NetworkOfferingVO ntwkOff, final PhysicalNetwork pNtwk, final ACLType aclType, final Account ownerFinal, final String cidr, final boolean createVlan) - throws InsufficientCapacityException, ResourceAllocationException { + private Network commitNetwork(final Long networkOfferingId, final String gateway, final String startIP, final String endIP, final String netmask, final String networkDomain, + final String vlanId, final String name, final String displayText, final Account caller, final Long physicalNetworkId, final Long zoneId, final Long domainId, + final boolean isDomainSpecific, final Boolean subdomainAccessFinal, final Long vpcId, final String startIPv6, final String endIPv6, final String ip6Gateway, + final String ip6Cidr, final Boolean displayNetwork, final Long aclId, final String isolatedPvlan, final NetworkOfferingVO ntwkOff, final PhysicalNetwork pNtwk, + final ACLType aclType, final Account ownerFinal, final String cidr, final boolean createVlan) throws InsufficientCapacityException, ResourceAllocationException { try { return Transaction.execute(new TransactionCallbackWithException() { @Override @@ -1342,9 +1332,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } } } - network = - _vpcMgr.createVpcGuestNetwork(networkOfferingId, name, displayText, gateway, cidr, vlanId, networkDomain, owner, sharedDomainId, pNtwk, - zoneId, aclType, subdomainAccess, vpcId, aclId, caller, displayNetwork); + network = _vpcMgr.createVpcGuestNetwork(networkOfferingId, name, displayText, gateway, cidr, vlanId, networkDomain, owner, sharedDomainId, pNtwk, zoneId, + aclType, subdomainAccess, vpcId, aclId, caller, displayNetwork); } else { if (_configMgr.isOfferingForVpc(ntwkOff)) { throw new InvalidParameterValueException("Network offering can be used for VPC networks only"); @@ -1353,15 +1342,14 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { throw new InvalidParameterValueException("Internal Lb can be enabled on vpc networks only"); } - network = - _networkMgr.createGuestNetwork(networkOfferingId, name, displayText, gateway, cidr, vlanId, networkDomain, owner, sharedDomainId, pNtwk, - zoneId, aclType, subdomainAccess, vpcId, ip6Gateway, ip6Cidr, displayNetwork, isolatedPvlan); + network = _networkMgr.createGuestNetwork(networkOfferingId, name, displayText, gateway, cidr, vlanId, networkDomain, owner, sharedDomainId, pNtwk, zoneId, + aclType, subdomainAccess, vpcId, ip6Gateway, ip6Cidr, displayNetwork, isolatedPvlan); } if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN && createVlan) { // Create vlan ip range - _configMgr.createVlanAndPublicIpRange(pNtwk.getDataCenterId(), network.getId(), physicalNetworkId, false, null, startIP, endIP, gateway, netmask, - vlanId, null, startIPv6, endIPv6, ip6Gateway, ip6Cidr); + _configMgr.createVlanAndPublicIpRange(pNtwk.getDataCenterId(), network.getId(), physicalNetworkId, false, null, startIP, endIP, gateway, netmask, vlanId, + null, startIPv6, endIPv6, ip6Gateway, ip6Cidr); } return network; } @@ -1375,7 +1363,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } @Override - public List searchForNetworks(ListNetworksCmd cmd) { + public Pair, Integer> searchForNetworks(ListNetworksCmd cmd) { Long id = cmd.getId(); String keyword = cmd.getKeyword(); Long zoneId = cmd.getZoneId(); @@ -1530,35 +1518,34 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { if (!permittedAccounts.isEmpty()) { //get account level networks networksToReturn.addAll(listAccountSpecificNetworks( - buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, - restartRequired, specifyIpRanges, vpcId, tags), searchFilter, permittedAccounts)); + buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired, + specifyIpRanges, vpcId, tags), searchFilter, permittedAccounts)); //get domain level networks if (domainId != null) { networksToReturn.addAll(listDomainLevelNetworks( - buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, true, restartRequired, - specifyIpRanges, vpcId, tags), searchFilter, domainId, false)); + buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, true, restartRequired, + specifyIpRanges, vpcId, tags), searchFilter, domainId, false)); } } else { //add account specific networks networksToReturn.addAll(listAccountSpecificNetworksByDomainPath( - buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, - restartRequired, specifyIpRanges, vpcId, tags), searchFilter, path, isRecursive)); + buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired, + specifyIpRanges, vpcId, tags), searchFilter, path, isRecursive)); //add domain specific networks of domain + parent domains networksToReturn.addAll(listDomainSpecificNetworksByDomainPath( - buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, - restartRequired, specifyIpRanges, vpcId, tags), searchFilter, path, isRecursive)); + buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired, + specifyIpRanges, vpcId, tags), searchFilter, path, isRecursive)); //add networks of subdomains if (domainId == null) { networksToReturn.addAll(listDomainLevelNetworks( - buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, true, restartRequired, - specifyIpRanges, vpcId, tags), searchFilter, caller.getDomainId(), true)); + buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, true, restartRequired, + specifyIpRanges, vpcId, tags), searchFilter, caller.getDomainId(), true)); } } } else { - networksToReturn = - _networksDao.search( - buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, null, skipProjectNetworks, - restartRequired, specifyIpRanges, vpcId, tags), searchFilter); + networksToReturn = _networksDao.search( + buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, null, skipProjectNetworks, restartRequired, + specifyIpRanges, vpcId, tags), searchFilter); } if (supportedServicesStr != null && !supportedServicesStr.isEmpty() && !networksToReturn.isEmpty()) { @@ -1598,37 +1585,34 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { //Now apply pagination //Most likely pageSize will never exceed int value, and we need integer to partition the listToReturn boolean notNull = cmd.getStartIndex() != null && cmd.getPageSizeVal() != null; - if (notNull && cmd.getStartIndex() <= Integer.MAX_VALUE && cmd.getStartIndex() >= Integer.MIN_VALUE && - cmd.getPageSizeVal() <= Integer.MAX_VALUE && cmd.getPageSizeVal() >= Integer.MIN_VALUE) { - int startIndex = cmd.getStartIndex().intValue() == 0 ? 0 : cmd.getStartIndex().intValue() - 1; + if (notNull && cmd.getStartIndex() <= Integer.MAX_VALUE && cmd.getStartIndex() >= Integer.MIN_VALUE && cmd.getPageSizeVal() <= Integer.MAX_VALUE + && cmd.getPageSizeVal() >= Integer.MIN_VALUE) { + int index = cmd.getStartIndex().intValue() == 0 ? 0 : cmd.getStartIndex().intValue() / cmd.getPageSizeVal().intValue(); List wPagination = new ArrayList(); List> partitions = partitionNetworks(networksToReturn, cmd.getPageSizeVal().intValue()); - if (startIndex< partitions.size()) { - wPagination = partitions.get(startIndex); + if (index < partitions.size()) { + wPagination = partitions.get(index); } - return wPagination; + return new Pair, Integer>(wPagination, networksToReturn.size()); } - return networksToReturn; + return new Pair, Integer>(networksToReturn, networksToReturn.size()); } - private static List> partitionNetworks(List originalList, - int chunkSize) { + private static List> partitionNetworks(List originalList, int chunkSize) { List> listOfChunks = new ArrayList>(); for (int i = 0; i < originalList.size() / chunkSize; i++) { - listOfChunks.add(originalList.subList(i * chunkSize, i * chunkSize - + chunkSize)); + listOfChunks.add(originalList.subList(i * chunkSize, i * chunkSize + chunkSize)); } if (originalList.size() % chunkSize != 0) { - listOfChunks.add(originalList.subList(originalList.size() - - originalList.size() % chunkSize, originalList.size())); + listOfChunks.add(originalList.subList(originalList.size() - originalList.size() % chunkSize, originalList.size())); } return listOfChunks; } private SearchCriteria buildNetworkSearchCriteria(SearchBuilder sb, String keyword, Long id, Boolean isSystem, Long zoneId, String guestIpType, - String trafficType, Long physicalNetworkId, String aclType, boolean skipProjectNetworks, Boolean restartRequired, Boolean specifyIpRanges, Long vpcId, - Map tags) { + String trafficType, Long physicalNetworkId, String aclType, boolean skipProjectNetworks, Boolean restartRequired, Boolean specifyIpRanges, Long vpcId, + Map tags) { SearchCriteria sc = sb.create(); @@ -1786,7 +1770,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { @Override @ActionEvent(eventType = EventTypes.EVENT_NETWORK_DELETE, eventDescription = "deleting network", async = true) - public boolean deleteNetwork(long networkId) { + public boolean deleteNetwork(long networkId, boolean forced) { Account caller = CallContext.current().getCallingAccount(); @@ -1812,16 +1796,19 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { // Perform permission check _accountMgr.checkAccess(caller, null, true, network); + if (forced && !_accountMgr.isRootAdmin(caller.getType())) { + throw new InvalidParameterValueException("Delete network with 'forced' option can only be called by root admins"); + } + User callerUser = _accountMgr.getActiveUser(CallContext.current().getCallingUserId()); ReservationContext context = new ReservationContextImpl(null, null, callerUser, owner); - return _networkMgr.destroyNetwork(networkId, context); + return _networkMgr.destroyNetwork(networkId, context, forced); } @Override @ActionEvent(eventType = EventTypes.EVENT_NETWORK_RESTART, eventDescription = "restarting network", async = true) - public boolean restartNetwork(RestartNetworkCmd cmd, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException, - InsufficientCapacityException { + public boolean restartNetwork(RestartNetworkCmd cmd, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { // This method restarts all network elements belonging to the network and re-applies all the rules Long networkId = cmd.getNetworkId(); @@ -1838,8 +1825,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { // Don't allow to restart network if it's not in Implemented/Setup state if (!(network.getState() == Network.State.Implemented || network.getState() == Network.State.Setup)) { - throw new InvalidParameterValueException("Network is not in the right state to be restarted. Correct states are: " + Network.State.Implemented + ", " + - Network.State.Setup); + throw new InvalidParameterValueException("Network is not in the right state to be restarted. Correct states are: " + Network.State.Implemented + ", " + + Network.State.Setup); } if (network.getBroadcastDomainType() == BroadcastDomainType.Lswitch) { @@ -1899,8 +1886,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { if (elementCapabilities == null || !elementCapabilities.containsKey(service)) { // TBD: We should be sending providerId and not the offering object itself. - throw new UnsupportedServiceException("Service " + service.getName() + " is not supported by the element=" + element.getName() + - " implementing Provider=" + provider); + throw new UnsupportedServiceException("Service " + service.getName() + " is not supported by the element=" + element.getName() + " implementing Provider=" + + provider); } serviceCapabilities = elementCapabilities.get(service); } @@ -1925,10 +1912,10 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { protected boolean isSharedNetworkOfferingWithServices(long networkOfferingId) { NetworkOfferingVO networkOffering = _networkOfferingDao.findById(networkOfferingId); - if ((networkOffering.getGuestType() == Network.GuestType.Shared) && - (areServicesSupportedByNetworkOffering(networkOfferingId, Service.SourceNat) || areServicesSupportedByNetworkOffering(networkOfferingId, Service.StaticNat) || - areServicesSupportedByNetworkOffering(networkOfferingId, Service.Firewall) || - areServicesSupportedByNetworkOffering(networkOfferingId, Service.PortForwarding) || areServicesSupportedByNetworkOffering(networkOfferingId, Service.Lb))) { + if ((networkOffering.getGuestType() == Network.GuestType.Shared) + && (areServicesSupportedByNetworkOffering(networkOfferingId, Service.SourceNat) || areServicesSupportedByNetworkOffering(networkOfferingId, Service.StaticNat) + || areServicesSupportedByNetworkOffering(networkOfferingId, Service.Firewall) + || areServicesSupportedByNetworkOffering(networkOfferingId, Service.PortForwarding) || areServicesSupportedByNetworkOffering(networkOfferingId, Service.Lb))) { return true; } return false; @@ -1943,8 +1930,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } private boolean checkForNonStoppedVmInNetwork(long networkId) { - List vms = - _userVmDao.listByNetworkIdAndStates(networkId, VirtualMachine.State.Starting, VirtualMachine.State.Running, VirtualMachine.State.Migrating, + List vms = _userVmDao.listByNetworkIdAndStates(networkId, VirtualMachine.State.Starting, VirtualMachine.State.Running, VirtualMachine.State.Migrating, VirtualMachine.State.Stopping); return vms.isEmpty(); } @@ -1953,7 +1939,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { @DB @ActionEvent(eventType = EventTypes.EVENT_NETWORK_UPDATE, eventDescription = "updating network", async = true) public Network updateGuestNetwork(final long networkId, String name, String displayText, Account callerAccount, User callerUser, String domainSuffix, - final Long networkOfferingId, Boolean changeCidr, String guestVmCidr, Boolean displayNetwork) { + final Long networkOfferingId, Boolean changeCidr, String guestVmCidr, Boolean displayNetwork) { boolean restartNetwork = false; @@ -1998,10 +1984,18 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { network.setDisplayText(displayText); } - if (displayNetwork != null) { + // display flag is not null and has changed + if (displayNetwork != null && displayNetwork != network.getDisplayNetwork()) { if (!_accountMgr.isRootAdmin(callerAccount.getType())) { throw new PermissionDeniedException("Only admin allowed to update displaynetwork parameter"); } + + // Update resource count if it needs to be updated + NetworkOffering networkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId()); + if (_networkMgr.resourceCountNeedsUpdate(networkOffering, network.getAclType())) { + _resourceLimitMgr.changeResourceCount(network.getAccountId(), Resource.ResourceType.network, displayNetwork); + } + network.setDisplayNetwork(displayNetwork); } @@ -2024,8 +2018,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { // network offering should be in Enabled state if (networkOffering.getState() != NetworkOffering.State.Enabled) { - InvalidParameterValueException ex = - new InvalidParameterValueException("Network offering with specified id is not in " + NetworkOffering.State.Enabled + " state, can't upgrade to it"); + InvalidParameterValueException ex = new InvalidParameterValueException("Network offering with specified id is not in " + NetworkOffering.State.Enabled + + " state, can't upgrade to it"); ex.addProxyObject(networkOffering.getUuid(), "networkOfferingId"); throw ex; } @@ -2046,33 +2040,31 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } if (changeCidr) { if (!checkForNonStoppedVmInNetwork(network.getId())) { - InvalidParameterValueException ex = - new InvalidParameterValueException("All user vm of network of specified id should be stopped before changing CIDR!"); + InvalidParameterValueException ex = new InvalidParameterValueException("All user vm of network of specified id should be stopped before changing CIDR!"); ex.addProxyObject(network.getUuid(), "networkId"); throw ex; } } // check if the network is upgradable if (!canUpgrade(network, oldNetworkOfferingId, networkOfferingId)) { - throw new InvalidParameterValueException("Can't upgrade from network offering " + oldNtwkOff.getUuid() + " to " + networkOffering.getUuid() + - "; check logs for more information"); + throw new InvalidParameterValueException("Can't upgrade from network offering " + oldNtwkOff.getUuid() + " to " + networkOffering.getUuid() + + "; check logs for more information"); } restartNetwork = true; networkOfferingChanged = true; } } - final Map newSvcProviders = - networkOfferingChanged ? _networkMgr.finalizeServicesAndProvidersForNetwork(_entityMgr.findById(NetworkOffering.class, networkOfferingId), - network.getPhysicalNetworkId()) : new HashMap(); + final Map newSvcProviders = networkOfferingChanged ? _networkMgr.finalizeServicesAndProvidersForNetwork( + _entityMgr.findById(NetworkOffering.class, networkOfferingId), network.getPhysicalNetworkId()) : new HashMap(); // don't allow to modify network domain if the service is not supported if (domainSuffix != null) { // validate network domain if (!NetUtils.verifyDomainName(domainSuffix)) { throw new InvalidParameterValueException( - "Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " - + "and the hyphen ('-'); can't start or end with \"-\""); + "Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " + + "and the hyphen ('-'); can't start or end with \"-\""); } long offeringId = oldNetworkOfferingId; @@ -2108,8 +2100,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { throw new InvalidParameterValueException("Cannot specify this nework offering change and guestVmCidr at same time. Specify only one."); } if (!(network.getState() == Network.State.Implemented)) { - throw new InvalidParameterValueException("The network must be in " + Network.State.Implemented + " state. IP Reservation cannot be applied in " + - network.getState() + " state"); + throw new InvalidParameterValueException("The network must be in " + Network.State.Implemented + " state. IP Reservation cannot be applied in " + + network.getState() + " state"); } if (!NetUtils.isValidCIDR(guestVmCidr)) { throw new InvalidParameterValueException("Invalid format of Guest VM CIDR."); @@ -2122,13 +2114,13 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { // But in case networkCidr is a non null value (IP reservation already exists), it implies network cidr is networkCidr if (networkCidr != null) { if (!NetUtils.isNetworkAWithinNetworkB(guestVmCidr, networkCidr)) { - throw new InvalidParameterValueException("Invalid value of Guest VM CIDR. For IP Reservation, Guest VM CIDR should be a subset of network CIDR : " + - networkCidr); + throw new InvalidParameterValueException("Invalid value of Guest VM CIDR. For IP Reservation, Guest VM CIDR should be a subset of network CIDR : " + + networkCidr); } } else { if (!NetUtils.isNetworkAWithinNetworkB(guestVmCidr, network.getCidr())) { - throw new InvalidParameterValueException("Invalid value of Guest VM CIDR. For IP Reservation, Guest VM CIDR should be a subset of network CIDR : " + - network.getCidr()); + throw new InvalidParameterValueException("Invalid value of Guest VM CIDR. For IP Reservation, Guest VM CIDR should be a subset of network CIDR : " + + network.getCidr()); } } @@ -2158,15 +2150,15 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { // the IP ranges exactly matches, in these special cases make sure no Reservation gets applied if (network.getNetworkCidr() == null) { if (NetUtils.isSameIpRange(guestVmCidr, network.getCidr()) && !guestVmCidr.equals(network.getCidr())) { - throw new InvalidParameterValueException("The Start IP and End IP of guestvmcidr: " + guestVmCidr + " and CIDR: " + network.getCidr() + - " are same, " + "even though both the cidrs appear to be different. As a precaution no IP Reservation will be applied."); + throw new InvalidParameterValueException("The Start IP and End IP of guestvmcidr: " + guestVmCidr + " and CIDR: " + network.getCidr() + " are same, " + + "even though both the cidrs appear to be different. As a precaution no IP Reservation will be applied."); } } else { if (NetUtils.isSameIpRange(guestVmCidr, network.getNetworkCidr()) && !guestVmCidr.equals(network.getNetworkCidr())) { - throw new InvalidParameterValueException("The Start IP and End IP of guestvmcidr: " + guestVmCidr + " and Network CIDR: " + network.getNetworkCidr() + - " are same, " + - "even though both the cidrs appear to be different. As a precaution IP Reservation will not be affected. If you want to reset IP Reservation, " + - "specify guestVmCidr to be: " + network.getNetworkCidr()); + throw new InvalidParameterValueException("The Start IP and End IP of guestvmcidr: " + guestVmCidr + " and Network CIDR: " + network.getNetworkCidr() + + " are same, " + + "even though both the cidrs appear to be different. As a precaution IP Reservation will not be affected. If you want to reset IP Reservation, " + + "specify guestVmCidr to be: " + network.getNetworkCidr()); } } @@ -2191,8 +2183,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { ReservationContext context = new ReservationContextImpl(null, null, callerUser, callerAccount); // 1) Shutdown all the elements and cleanup all the rules. Don't allow to shutdown network in intermediate // states - Shutdown and Implementing - boolean validStateToShutdown = - (network.getState() == Network.State.Implemented || network.getState() == Network.State.Setup || network.getState() == Network.State.Allocated); + boolean validStateToShutdown = (network.getState() == Network.State.Implemented || network.getState() == Network.State.Setup || network.getState() == Network.State.Allocated); if (restartNetwork) { if (validStateToShutdown) { if (!changeCidr) { @@ -2200,8 +2191,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { if (!_networkMgr.shutdownNetworkElementsAndResources(context, true, network)) { s_logger.warn("Failed to shutdown the network elements and resources as a part of network restart: " + network); - CloudRuntimeException ex = - new CloudRuntimeException("Failed to shutdown the network elements and resources as a part of update to network of specified id"); + CloudRuntimeException ex = new CloudRuntimeException("Failed to shutdown the network elements and resources as a part of update to network of specified id"); ex.addProxyObject(network.getUuid(), "networkId"); throw ex; } @@ -2211,8 +2201,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { //check if network has reservation if (NetUtils.isNetworkAWithinNetworkB(network.getCidr(), network.getNetworkCidr())) { - s_logger.warn("Existing IP reservation will become ineffective for the network with id = " + networkId + - " You need to reapply reservation after network reimplementation."); + s_logger.warn("Existing IP reservation will become ineffective for the network with id = " + networkId + + " You need to reapply reservation after network reimplementation."); //set cidr to the newtork cidr network.setCidr(network.getNetworkCidr()); //set networkCidr to null to bring network back to no IP reservation state @@ -2227,10 +2217,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } } } else { - CloudRuntimeException ex = - new CloudRuntimeException( - "Failed to shutdown the network elements and resources as a part of update to network with specified id; network is in wrong state: " + - network.getState()); + CloudRuntimeException ex = new CloudRuntimeException( + "Failed to shutdown the network elements and resources as a part of update to network with specified id; network is in wrong state: " + network.getState()); ex.addProxyObject(network.getUuid(), "networkId"); throw ex; } @@ -2241,8 +2229,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { Network.State networkState = _networksDao.findById(networkId).getState(); boolean validStateToImplement = (networkState == Network.State.Implemented || networkState == Network.State.Setup || networkState == Network.State.Allocated); if (restartNetwork && !validStateToImplement) { - CloudRuntimeException ex = - new CloudRuntimeException( + CloudRuntimeException ex = new CloudRuntimeException( "Failed to implement the network elements and resources as a part of update to network with specified id; network is in wrong state: " + networkState); ex.addProxyObject(network.getUuid(), "networkId"); throw ex; @@ -2269,16 +2256,16 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { long isDefault = (nic.isDefaultNic()) ? 1 : 0; String nicIdString = Long.toString(nic.getId()); UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_REMOVE, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), nicIdString, - oldNetworkOfferingId, null, isDefault, VirtualMachine.class.getName(), vm.getUuid()); + oldNetworkOfferingId, null, isDefault, VirtualMachine.class.getName(), vm.getUuid()); UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_ASSIGN, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), nicIdString, - networkOfferingId, null, isDefault, VirtualMachine.class.getName(), vm.getUuid()); + networkOfferingId, null, isDefault, VirtualMachine.class.getName(), vm.getUuid()); } } }); } else { network.setNetworkOfferingId(networkOfferingId); _networksDao.update(networkId, network, - _networkMgr.finalizeServicesAndProvidersForNetwork(_entityMgr.findById(NetworkOffering.class, networkOfferingId), network.getPhysicalNetworkId())); + _networkMgr.finalizeServicesAndProvidersForNetwork(_entityMgr.findById(NetworkOffering.class, networkOfferingId), network.getPhysicalNetworkId())); } } else { _networksDao.update(networkId, network); @@ -2297,8 +2284,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } } catch (Exception ex) { s_logger.warn("Failed to implement network " + network + " elements and resources as a part of network update due to ", ex); - CloudRuntimeException e = - new CloudRuntimeException("Failed to implement network (with specified id) elements and resources as a part of network update"); + CloudRuntimeException e = new CloudRuntimeException("Failed to implement network (with specified id) elements and resources as a part of network update"); e.addProxyObject(network.getUuid(), "networkId"); throw e; } @@ -2314,8 +2300,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { _networkMgr.implementNetwork(network.getId(), dest, context); } catch (Exception ex) { s_logger.warn("Failed to implement network " + network + " elements and resources as a part o" + "f network update due to ", ex); - CloudRuntimeException e = - new CloudRuntimeException("Failed to implement network (with specified" + " id) elements and resources as a part of network update"); + CloudRuntimeException e = new CloudRuntimeException("Failed to implement network (with specified" + " id) elements and resources as a part of network update"); e.addProxyObject(network.getUuid(), "networkId"); throw e; } @@ -2357,8 +2342,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } // security group service should be the same - if (areServicesSupportedByNetworkOffering(oldNetworkOfferingId, Service.SecurityGroup) != areServicesSupportedByNetworkOffering(newNetworkOfferingId, - Service.SecurityGroup)) { + if (areServicesSupportedByNetworkOffering(oldNetworkOfferingId, Service.SecurityGroup) != areServicesSupportedByNetworkOffering(newNetworkOfferingId, Service.SecurityGroup)) { s_logger.debug("Offerings " + newNetworkOfferingId + " and " + oldNetworkOfferingId + " have different securityGroupProperty, can't upgrade"); return false; } @@ -2372,8 +2356,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { // tags should be the same if (newNetworkOffering.getTags() != null) { if (oldNetworkOffering.getTags() == null) { - s_logger.debug("New network offering id=" + newNetworkOfferingId + " has tags and old network offering id=" + oldNetworkOfferingId + - " doesn't, can't upgrade"); + s_logger.debug("New network offering id=" + newNetworkOfferingId + " has tags and old network offering id=" + oldNetworkOfferingId + " doesn't, can't upgrade"); return false; } if (!oldNetworkOffering.getTags().equalsIgnoreCase(newNetworkOffering.getTags())) { @@ -2429,7 +2412,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { @DB @ActionEvent(eventType = EventTypes.EVENT_PHYSICAL_NETWORK_CREATE, eventDescription = "Creating Physical Network", create = true) public PhysicalNetwork createPhysicalNetwork(final Long zoneId, final String vnetRange, final String networkSpeed, final List isolationMethods, - String broadcastDomainRangeStr, final Long domainId, final List tags, final String name) { + String broadcastDomainRangeStr, final Long domainId, final List tags, final String name) { // Check if zone exists if (zoneId == null) { @@ -2451,8 +2434,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { if (zoneType == NetworkType.Basic) { if (!_physicalNetworkDao.listByZone(zoneId).isEmpty()) { // TBD: Send uuid instead of zoneId; may have to hardcode tablename in call to addProxyObject(). - throw new CloudRuntimeException("Cannot add the physical network to basic zone id: " + zoneId + - ", there is a physical network already existing in this basic Zone"); + throw new CloudRuntimeException("Cannot add the physical network to basic zone id: " + zoneId + ", there is a physical network already existing in this basic Zone"); } } if (tags != null && tags.size() > 1) { @@ -2466,8 +2448,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { if (vnetRange != null) { // Verify zone type if (zoneType == NetworkType.Basic || (zoneType == NetworkType.Advanced && zone.isSecurityGroupEnabled())) { - throw new InvalidParameterValueException("Can't add vnet range to the physical network in the zone that supports " + zoneType + - " network, Security Group enabled: " + zone.isSecurityGroupEnabled()); + throw new InvalidParameterValueException("Can't add vnet range to the physical network in the zone that supports " + zoneType + + " network, Security Group enabled: " + zone.isSecurityGroupEnabled()); } } @@ -2540,7 +2522,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } } - @Override + @Override public Pair, Integer> searchPhysicalNetworks(Long id, Long zoneId, String keyword, Long startIndex, Long pageSize, String name) { Filter searchFilter = new Filter(PhysicalNetworkVO.class, "id", Boolean.TRUE, startIndex, pageSize); SearchCriteria sc = _physicalNetworkDao.createSearchCriteria(); @@ -2583,8 +2565,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } if (newVnetRange != null) { if (zone.getNetworkType() == NetworkType.Basic || (zone.getNetworkType() == NetworkType.Advanced && zone.isSecurityGroupEnabled())) { - throw new InvalidParameterValueException("Can't add vnet range to the physical network in the zone that supports " + zone.getNetworkType() + - " network, Security Group enabled: " + zone.isSecurityGroupEnabled()); + throw new InvalidParameterValueException("Can't add vnet range to the physical network in the zone that supports " + zone.getNetworkType() + + " network, Security Group enabled: " + zone.isSecurityGroupEnabled()); } } @@ -2639,7 +2621,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { removeVnets = getVnetsToremove(network, vnetranges); //computing vnets to add - vnetsInDb.addAll(_datacneter_vnet.listVnetsByPhysicalNetworkAndDataCenter(network.getDataCenterId(), network.getId())); + vnetsInDb.addAll(_datacneterVnet.listVnetsByPhysicalNetworkAndDataCenter(network.getDataCenterId(), network.getId())); tempVnets.addAll(vnetsInDb); for (Pair vlan : vnetranges) { for (i = vlan.first(); i <= vlan.second(); i++) { @@ -2672,16 +2654,16 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { @Override public void doInTransactionWithoutResult(TransactionStatus status) { if (addVnetsFinal != null) { - s_logger.debug("Adding vnet range " + addVnetsFinal.toString() + " for the physicalNetwork id= " + network.getId() + " and zone id=" + - network.getDataCenterId() + " as a part of updatePhysicalNetwork call"); + s_logger.debug("Adding vnet range " + addVnetsFinal.toString() + " for the physicalNetwork id= " + network.getId() + " and zone id=" + + network.getDataCenterId() + " as a part of updatePhysicalNetwork call"); //add vnet takes a list of strings to be added. each string is a vnet. _dcDao.addVnet(network.getDataCenterId(), network.getId(), addVnetsFinal); } if (removeVnetsFinal != null) { - s_logger.debug("removing vnet range " + removeVnetsFinal.toString() + " for the physicalNetwork id= " + network.getId() + " and zone id=" + - network.getDataCenterId() + " as a part of updatePhysicalNetwork call"); + s_logger.debug("removing vnet range " + removeVnetsFinal.toString() + " for the physicalNetwork id= " + network.getId() + " and zone id=" + + network.getDataCenterId() + " as a part of updatePhysicalNetwork call"); //deleteVnets takes a list of strings to be removed. each string is a vnet. - _datacneter_vnet.deleteVnets(TransactionLegacy.currentTxn(), network.getDataCenterId(), network.getId(), removeVnetsFinal); + _datacneterVnet.deleteVnets(TransactionLegacy.currentTxn(), network.getDataCenterId(), network.getId(), removeVnetsFinal); } _physicalNetworkDao.update(network.getId(), network); } @@ -2717,7 +2699,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { // since adding a range adds each VNI to the database, need only check min/max for (String vnet : VnetRange) { s_logger.debug("Looking to see if VNI " + vnet + " already exists on another network in zone " + network.getDataCenterId()); - List vnis = _datacneter_vnet.findVnet(network.getDataCenterId(), vnet); + List vnis = _datacneterVnet.findVnet(network.getDataCenterId(), vnet); if (vnis != null && !vnis.isEmpty()) { for (DataCenterVnetVO vni : vnis) { if (vni.getPhysicalNetworkId() != network.getId()) { @@ -2733,8 +2715,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { return vlanTokens; } if (VnetRange.length < 2) { - throw new InvalidParameterValueException( - "Please provide valid vnet range. vnet range should be a coma seperated list of vlan ranges. example 500-500,600-601" + rangeMessage); + throw new InvalidParameterValueException("Please provide valid vnet range. vnet range should be a coma seperated list of vlan ranges. example 500-500,600-601" + + rangeMessage); } if (VnetRange[0] == null || VnetRange[1] == null) { @@ -2746,8 +2728,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { EndVnet = Integer.parseInt(VnetRange[1]); } catch (NumberFormatException e) { s_logger.warn("Unable to parse vnet range:", e); - throw new InvalidParameterValueException("Please provide valid vnet range. The vnet range should be a coma seperated list example 2001-2012,3000-3005." + - rangeMessage); + throw new InvalidParameterValueException("Please provide valid vnet range. The vnet range should be a coma seperated list example 2001-2012,3000-3005." + + rangeMessage); } if (StartVnet < minVnet || EndVnet > maxVnet) { throw new InvalidParameterValueException("Vnet range has to be" + rangeMessage); @@ -2791,13 +2773,13 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { int i; List removeVnets = new ArrayList(); HashSet vnetsInDb = new HashSet(); - vnetsInDb.addAll(_datacneter_vnet.listVnetsByPhysicalNetworkAndDataCenter(network.getDataCenterId(), network.getId())); + vnetsInDb.addAll(_datacneterVnet.listVnetsByPhysicalNetworkAndDataCenter(network.getDataCenterId(), network.getId())); //remove all the vnets from vnets in db to check if there are any vnets that are not there in given list. //remove all the vnets not in the list of vnets passed by the user. if (vnetRanges.size() == 0) { //this implies remove all vlans. removeVnets.addAll(vnetsInDb); - int allocated_vnets = _datacneter_vnet.countAllocatedVnets(network.getId()); + int allocated_vnets = _datacneterVnet.countAllocatedVnets(network.getId()); if (allocated_vnets > 0) { throw new InvalidParameterValueException("physicalnetwork " + network.getId() + " has " + allocated_vnets + " vnets in use"); } @@ -2820,8 +2802,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { String[] range = vnet.split("-"); Integer start = Integer.parseInt(range[0]); Integer end = Integer.parseInt(range[1]); - _datacneter_vnet.lockRange(network.getDataCenterId(), network.getId(), start, end); - List result = _datacneter_vnet.listAllocatedVnetsInRange(network.getDataCenterId(), network.getId(), start, end); + _datacneterVnet.lockRange(network.getDataCenterId(), network.getId(), start, end); + List result = _datacneterVnet.listAllocatedVnetsInRange(network.getDataCenterId(), network.getId(), start, end); if (!result.isEmpty()) { throw new InvalidParameterValueException("physicalnetwork " + network.getId() + " has allocated vnets in the range " + start + "-" + end); @@ -2833,8 +2815,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { Integer dedicatedStartVlan = Integer.parseInt(vlans[0]); Integer dedicatedEndVlan = Integer.parseInt(vlans[1]); if ((start >= dedicatedStartVlan && start <= dedicatedEndVlan) || (end >= dedicatedStartVlan && end <= dedicatedEndVlan)) { - throw new InvalidParameterValueException("Vnet range " + map.getGuestVlanRange() + " is dedicated" + " to an account. The specified range " + start + - "-" + end + " overlaps with the dedicated range " + " Please release the overlapping dedicated range before deleting the range"); + throw new InvalidParameterValueException("Vnet range " + map.getGuestVlanRange() + " is dedicated" + " to an account. The specified range " + start + "-" + end + + " overlaps with the dedicated range " + " Please release the overlapping dedicated range before deleting the range"); } } } @@ -3047,13 +3029,12 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { // Verify guest vlans in the range don't belong to a network of a different account for (int i = startVlan; i <= endVlan; i++) { - List allocatedVlans = - _datacneter_vnet.listAllocatedVnetsInRange(physicalNetwork.getDataCenterId(), physicalNetwork.getId(), startVlan, endVlan); + List allocatedVlans = _datacneterVnet.listAllocatedVnetsInRange(physicalNetwork.getDataCenterId(), physicalNetwork.getId(), startVlan, endVlan); if (allocatedVlans != null && !allocatedVlans.isEmpty()) { for (DataCenterVnetVO allocatedVlan : allocatedVlans) { if (allocatedVlan.getAccountId() != vlanOwner.getAccountId()) { - throw new InvalidParameterValueException("Guest vlan from this range " + allocatedVlan.getVnet() + " is allocated to a different account." + - " Can only dedicate a range which has no allocated vlans or has vlans allocated to the same account "); + throw new InvalidParameterValueException("Guest vlan from this range " + allocatedVlan.getVnet() + " is allocated to a different account." + + " Can only dedicate a range which has no allocated vlans or has vlans allocated to the same account "); } } } @@ -3098,7 +3079,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { List vlanTokens2 = getVlanFromRange(guestVlanMaps.get(i + 1).getGuestVlanRange()); // Range extends 2 vlan ranges, both to the right and left if (endVlan == (vlanTokens2.get(0).intValue() - 1) & guestVlanMaps.get(i + 1).getAccountId() == vlanOwnerId) { - _datacneter_vnet.releaseDedicatedGuestVlans(guestVlanMaps.get(i + 1).getId()); + _datacneterVnet.releaseDedicatedGuestVlans(guestVlanMaps.get(i + 1).getId()); _accountGuestVlanMapDao.remove(guestVlanMaps.get(i + 1).getId()); updatedVlanRange = vlanTokens1.get(0).intValue() + "-" + vlanTokens2.get(1).intValue(); break; @@ -3122,9 +3103,9 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { // For every guest vlan set the corresponding account guest vlan map id List finaVlanTokens = getVlanFromRange(accountGuestVlanMapVO.getGuestVlanRange()); for (int i = finaVlanTokens.get(0).intValue(); i <= finaVlanTokens.get(1).intValue(); i++) { - List dataCenterVnet = _datacneter_vnet.findVnet(physicalNetwork.getDataCenterId(), physicalNetworkId, ((Integer)i).toString()); + List dataCenterVnet = _datacneterVnet.findVnet(physicalNetwork.getDataCenterId(), physicalNetworkId, ((Integer)i).toString()); dataCenterVnet.get(0).setAccountGuestVlanMapId(accountGuestVlanMapVO.getId()); - _datacneter_vnet.update(dataCenterVnet.get(0).getId(), dataCenterVnet.get(0)); + _datacneterVnet.update(dataCenterVnet.get(0).getId(), dataCenterVnet.get(0)); } return accountGuestVlanMapVO; } @@ -3195,8 +3176,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { if (zoneId != null) { SearchBuilder physicalnetworkSearch = _physicalNetworkDao.createSearchBuilder(); physicalnetworkSearch.and("zoneId", physicalnetworkSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); - sb.join("physicalnetworkSearch", physicalnetworkSearch, sb.entity().getPhysicalNetworkId(), physicalnetworkSearch.entity().getId(), - JoinBuilder.JoinType.INNER); + sb.join("physicalnetworkSearch", physicalnetworkSearch, sb.entity().getPhysicalNetworkId(), physicalnetworkSearch.entity().getId(), JoinBuilder.JoinType.INNER); } SearchCriteria sc = sb.create(); @@ -3236,7 +3216,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } // Remove dedication for the guest vlan - _datacneter_vnet.releaseDedicatedGuestVlans(dedicatedGuestVlan.getId()); + _datacneterVnet.releaseDedicatedGuestVlans(dedicatedGuestVlan.getId()); if (_accountGuestVlanMapDao.remove(dedicatedGuestVlanRangeId)) { return true; } else { @@ -3269,8 +3249,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { @Override @DB @ActionEvent(eventType = EventTypes.EVENT_SERVICE_PROVIDER_CREATE, eventDescription = "Creating Physical Network ServiceProvider", create = true) - public PhysicalNetworkServiceProvider addProviderToPhysicalNetwork(Long physicalNetworkId, String providerName, Long destinationPhysicalNetworkId, - List enabledServices) { + public PhysicalNetworkServiceProvider addProviderToPhysicalNetwork(Long physicalNetworkId, String providerName, Long destinationPhysicalNetworkId, List enabledServices) { // verify input parameters PhysicalNetworkVO network = _physicalNetworkDao.findById(physicalNetworkId); @@ -3312,8 +3291,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { if (enabledServices != null) { if (!element.canEnableIndividualServices()) { if (enabledServices.size() != element.getCapabilities().keySet().size()) { - throw new InvalidParameterValueException( - "Cannot enable subset of Services, Please specify the complete list of Services for this Service Provider '" + providerName + "'"); + throw new InvalidParameterValueException("Cannot enable subset of Services, Please specify the complete list of Services for this Service Provider '" + + providerName + "'"); } } @@ -3363,7 +3342,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { @Override public Pair, Integer> listNetworkServiceProviders(Long physicalNetworkId, String name, String state, Long startIndex, - Long pageSize) { + Long pageSize) { Filter searchFilter = new Filter(PhysicalNetworkServiceProviderVO.class, "id", false, startIndex, pageSize); SearchBuilder sb = _pNSPDao.createSearchBuilder(); @@ -3412,25 +3391,25 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { if (state != null) { if (s_logger.isDebugEnabled()) { - s_logger.debug("trying to update the state of the service provider id=" + id + " on physical network: " + provider.getPhysicalNetworkId() + - " to state: " + stateStr); + s_logger.debug("trying to update the state of the service provider id=" + id + " on physical network: " + provider.getPhysicalNetworkId() + " to state: " + + stateStr); } switch (state) { - case Enabled: - if (element != null && element.isReady(provider)) { - provider.setState(PhysicalNetworkServiceProvider.State.Enabled); - update = true; - } else { - throw new CloudRuntimeException("Provider is not ready, cannot Enable the provider, please configure the provider first"); - } - break; - case Disabled: - // do we need to do anything for the provider instances before disabling? - provider.setState(PhysicalNetworkServiceProvider.State.Disabled); + case Enabled: + if (element != null && element.isReady(provider)) { + provider.setState(PhysicalNetworkServiceProvider.State.Enabled); update = true; - break; - case Shutdown: - throw new InvalidParameterValueException("Updating the provider state to 'Shutdown' is not supported"); + } else { + throw new CloudRuntimeException("Provider is not ready, cannot Enable the provider, please configure the provider first"); + } + break; + case Disabled: + // do we need to do anything for the provider instances before disabling? + provider.setState(PhysicalNetworkServiceProvider.State.Disabled); + update = true; + break; + case Shutdown: + throw new InvalidParameterValueException("Updating the provider state to 'Shutdown' is not supported"); } } @@ -3473,7 +3452,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { List networks = _networksDao.listByPhysicalNetworkAndProvider(provider.getPhysicalNetworkId(), provider.getProviderName()); if (networks != null && !networks.isEmpty()) { throw new CloudRuntimeException( - "Provider is not deletable because there are active networks using this provider, please upgrade these networks to new network offerings"); + "Provider is not deletable because there are active networks using this provider, please upgrade these networks to new network offerings"); } User callerUser = _accountMgr.getActiveUser(CallContext.current().getCallingUserId()); @@ -3532,8 +3511,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { if (pNtwks.size() > 1) { if (tag == null) { - throw new InvalidParameterValueException("More than one physical networks exist in zone id=" + zoneId + - " and no tags are specified in order to make a choice"); + throw new InvalidParameterValueException("More than one physical networks exist in zone id=" + zoneId + " and no tags are specified in order to make a choice"); } Long pNtwkId = null; @@ -3556,8 +3534,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { @Override @DB @ActionEvent(eventType = EventTypes.EVENT_TRAFFIC_TYPE_CREATE, eventDescription = "Creating Physical Network TrafficType", create = true) - public PhysicalNetworkTrafficType addTrafficTypeToPhysicalNetwork(Long physicalNetworkId, String trafficTypeStr, String xenLabel, String kvmLabel, - String vmwareLabel, String simulatorLabel, String vlan, String hypervLabel) { + public PhysicalNetworkTrafficType addTrafficTypeToPhysicalNetwork(Long physicalNetworkId, String trafficTypeStr, String isolationMethod, String xenLabel, String kvmLabel, String vmwareLabel, + String simulatorLabel, String vlan, String hypervLabel) { // verify input parameters PhysicalNetworkVO network = _physicalNetworkDao.findById(physicalNetworkId); @@ -3583,19 +3561,18 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { if (TrafficType.isSystemNetwork(trafficType) || TrafficType.Public.equals(trafficType) || TrafficType.Storage.equals(trafficType)) { if (!_physicalNetworkDao.listByZoneAndTrafficType(network.getDataCenterId(), trafficType).isEmpty()) { - throw new CloudRuntimeException("Fail to add the traffic type to physical network because Zone already has a physical network with this traffic type: " + - trafficType); + throw new CloudRuntimeException("Fail to add the traffic type to physical network because Zone already has a physical network with this traffic type: " + + trafficType); } } if (TrafficType.Storage.equals(trafficType)) { List ssvms = _stnwMgr.getSSVMWithNoStorageNetwork(network.getDataCenterId()); if (!ssvms.isEmpty()) { - StringBuilder sb = - new StringBuilder( - "Cannot add " + - trafficType + - " traffic type as there are below secondary storage vm still running. Please stop them all and add Storage traffic type again, then destory them all to allow CloudStack recreate them with storage network(If you have added storage network ip range)"); + StringBuilder sb = new StringBuilder( + "Cannot add " + + trafficType + + " traffic type as there are below secondary storage vm still running. Please stop them all and add Storage traffic type again, then destory them all to allow CloudStack recreate them with storage network(If you have added storage network ip range)"); sb.append("SSVMs:"); for (SecondaryStorageVmVO ssvm : ssvms) { sb.append(ssvm.getInstanceName()).append(":").append(ssvm.getState()); @@ -3609,10 +3586,24 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { if (xenLabel == null) { xenLabel = getDefaultXenNetworkLabel(trafficType); } - PhysicalNetworkTrafficTypeVO pNetworktrafficType = - new PhysicalNetworkTrafficTypeVO(physicalNetworkId, trafficType, xenLabel, kvmLabel, vmwareLabel, simulatorLabel, vlan, hypervLabel); + PhysicalNetworkTrafficTypeVO pNetworktrafficType = new PhysicalNetworkTrafficTypeVO(physicalNetworkId, trafficType, xenLabel, kvmLabel, vmwareLabel, simulatorLabel, + vlan, hypervLabel); pNetworktrafficType = _pNTrafficTypeDao.persist(pNetworktrafficType); + // For public traffic, get isolation method of physical network and update the public network accordingly + // each broadcast type will individually need to be qualified for support of public traffic + List isolationMethods = network.getIsolationMethods(); + if ((isolationMethods.size() == 1 && isolationMethods.get(0).toLowerCase().equals("vxlan")) + || (isolationMethod != null && isolationMethods.contains(isolationMethod) && isolationMethod.toLowerCase().equals("vxlan"))) { + // find row in networks table that is defined as 'Public', created when zone was deployed + NetworkVO publicNetwork = _networksDao.listByZoneAndTrafficType(network.getDataCenterId(),TrafficType.Public).get(0); + if (publicNetwork != null) { + s_logger.debug("setting public network " + publicNetwork + " to broadcast type vxlan"); + publicNetwork.setBroadcastDomainType(BroadcastDomainType.Vxlan); + _networksDao.persist(publicNetwork); + } + } + return pNetworktrafficType; } catch (Exception ex) { s_logger.warn("Exception: ", ex); @@ -3624,24 +3615,24 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { private String getDefaultXenNetworkLabel(TrafficType trafficType) { String xenLabel = null; switch (trafficType) { - case Public: - xenLabel = _configDao.getValue(Config.XenPublicNetwork.key()); - break; - case Guest: - xenLabel = _configDao.getValue(Config.XenGuestNetwork.key()); - break; - case Storage: - xenLabel = _configDao.getValue(Config.XenStorageNetwork1.key()); - break; - case Management: - xenLabel = _configDao.getValue(Config.XenPrivateNetwork.key()); - break; - case Control: - xenLabel = "cloud_link_local_network"; - break; - case Vpn: - case None: - break; + case Public: + xenLabel = _configDao.getValue(Config.XenPublicNetwork.key()); + break; + case Guest: + xenLabel = _configDao.getValue(Config.XenGuestNetwork.key()); + break; + case Storage: + xenLabel = _configDao.getValue(Config.XenStorageNetwork1.key()); + break; + case Management: + xenLabel = _configDao.getValue(Config.XenPrivateNetwork.key()); + break; + case Control: + xenLabel = "cloud_link_local_network"; + break; + case Vpn: + case None: + break; } return xenLabel; } @@ -3704,14 +3695,13 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { // check if there are any networks associated to this physical network with this traffic type if (TrafficType.Guest.equals(trafficType.getTrafficType())) { if (!_networksDao.listByPhysicalNetworkTrafficType(trafficType.getPhysicalNetworkId(), trafficType.getTrafficType()).isEmpty()) { - throw new CloudRuntimeException("The Traffic Type is not deletable because there are existing networks with this traffic type:" + - trafficType.getTrafficType()); + throw new CloudRuntimeException("The Traffic Type is not deletable because there are existing networks with this traffic type:" + trafficType.getTrafficType()); } } else if (TrafficType.Storage.equals(trafficType.getTrafficType())) { PhysicalNetworkVO pn = _physicalNetworkDao.findById(trafficType.getPhysicalNetworkId()); if (_stnwMgr.isAnyStorageIpInUseInZone(pn.getDataCenterId())) { - throw new CloudRuntimeException("The Traffic Type is not deletable because there are still some storage network ip addresses in use:" + - trafficType.getTrafficType()); + throw new CloudRuntimeException("The Traffic Type is not deletable because there are still some storage network ip addresses in use:" + + trafficType.getTrafficType()); } } return _pNTrafficTypeDao.remove(id); @@ -3732,17 +3722,15 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { @Override //TODO: duplicated in NetworkModel - public - NetworkVO getExclusiveGuestNetwork(long zoneId) { + public NetworkVO getExclusiveGuestNetwork(long zoneId) { List networks = _networksDao.listBy(Account.ACCOUNT_ID_SYSTEM, zoneId, GuestType.Shared, TrafficType.Guest); if (networks == null || networks.isEmpty()) { - throw new InvalidParameterValueException("Unable to find network with trafficType " + TrafficType.Guest + " and guestType " + GuestType.Shared + " in zone " + - zoneId); + throw new InvalidParameterValueException("Unable to find network with trafficType " + TrafficType.Guest + " and guestType " + GuestType.Shared + " in zone " + zoneId); } if (networks.size() > 1) { - throw new InvalidParameterValueException("Found more than 1 network with trafficType " + TrafficType.Guest + " and guestType " + GuestType.Shared + - " in zone " + zoneId); + throw new InvalidParameterValueException("Found more than 1 network with trafficType " + TrafficType.Guest + " and guestType " + GuestType.Shared + " in zone " + + zoneId); } @@ -3764,22 +3752,21 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { return nsp; } - private PhysicalNetworkServiceProvider addDefaultOvsToPhysicalNetwork(long physicalNetworkId) { - PhysicalNetworkServiceProvider nsp = addProviderToPhysicalNetwork(physicalNetworkId, Network.Provider.Ovs.getName(), null, null); - NetworkElement networkElement = _networkModel.getElementImplementingProvider(Network.Provider.Ovs.getName()); - if (networkElement == null) { + private PhysicalNetworkServiceProvider addDefaultOvsToPhysicalNetwork(long physicalNetworkId) { + PhysicalNetworkServiceProvider nsp = addProviderToPhysicalNetwork(physicalNetworkId, Network.Provider.Ovs.getName(), null, null); + NetworkElement networkElement = _networkModel.getElementImplementingProvider(Network.Provider.Ovs.getName()); + if (networkElement == null) { throw new CloudRuntimeException("Unable to find the Network Element implementing the Ovs Provider"); } - OvsProviderVO element = _ovsProviderDao.findByNspId(nsp.getId()); - if (element != null) { - s_logger.debug("There is already a Ovs element with service provider id " - + nsp.getId()); - return nsp; - } - element = new OvsProviderVO(nsp.getId()); - _ovsProviderDao.persist(element); - return nsp; - } + OvsProviderVO element = _ovsProviderDao.findByNspId(nsp.getId()); + if (element != null) { + s_logger.debug("There is already a Ovs element with service provider id " + nsp.getId()); + return nsp; + } + element = new OvsProviderVO(nsp.getId()); + _ovsProviderDao.persist(element); + return nsp; + } protected PhysicalNetworkServiceProvider addDefaultVpcVirtualRouterToPhysicalNetwork(long physicalNetworkId) { @@ -3873,8 +3860,8 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { @Override @ActionEvent(eventType = EventTypes.EVENT_NET_IP_ASSIGN, eventDescription = "associating Ip", async = true) - public IpAddress associateIPToNetwork(long ipId, long networkId) throws InsufficientAddressCapacityException, ResourceAllocationException, - ResourceUnavailableException, ConcurrentOperationException { + public IpAddress associateIPToNetwork(long ipId, long networkId) throws InsufficientAddressCapacityException, ResourceAllocationException, ResourceUnavailableException, + ConcurrentOperationException { Network network = _networksDao.findById(networkId); if (network == null) { @@ -3882,8 +3869,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } if (network.getVpcId() != null) { - throw new InvalidParameterValueException("Can't assign ip to the network directly when network belongs" - + " to VPC.Specify vpcId to associate ip address to VPC"); + throw new InvalidParameterValueException("Can't assign ip to the network directly when network belongs" + " to VPC.Specify vpcId to associate ip address to VPC"); } return _ipAddrMgr.associateIPToGuestNetwork(ipId, networkId, true); @@ -3891,9 +3877,9 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { @Override @DB - public Network createPrivateNetwork(final String networkName, final String displayText, long physicalNetworkId, String broadcastUriString, final String startIp, - String endIp, final String gateway, String netmask, final long networkOwnerId, final Long vpcId, final Boolean sourceNat, final Long networkOfferingId) - throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException { + public Network createPrivateNetwork(final String networkName, final String displayText, long physicalNetworkId, String broadcastUriString, final String startIp, String endIp, + final String gateway, String netmask, final long networkOwnerId, final Long vpcId, final Boolean sourceNat, final Long networkOfferingId) + throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException { final Account owner = _accountMgr.getAccount(networkOwnerId); @@ -3955,24 +3941,23 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { Network privateNetwork = _networksDao.getPrivateNetwork(uriString, cidr, networkOwnerId, pNtwk.getDataCenterId(), networkOfferingId); if (privateNetwork == null) { //create Guest network - privateNetwork = - _networkMgr.createGuestNetwork(ntwkOffFinal.getId(), networkName, displayText, gateway, cidr, uriString, null, owner, null, pNtwk, + privateNetwork = _networkMgr.createGuestNetwork(ntwkOffFinal.getId(), networkName, displayText, gateway, cidr, uriString, null, owner, null, pNtwk, pNtwk.getDataCenterId(), ACLType.Account, null, vpcId, null, null, true, null); s_logger.debug("Created private network " + privateNetwork); } else { s_logger.debug("Private network already exists: " + privateNetwork); //Do not allow multiple private gateways with same Vlan within a VPC if (vpcId.equals(privateNetwork.getVpcId())) { - throw new InvalidParameterValueException("Private network for the vlan: " + uriString + " and cidr " + cidr + " already exists " + - "for Vpc " + vpcId + " in zone " + _entityMgr.findById(DataCenter.class, pNtwk.getDataCenterId()).getName()); + throw new InvalidParameterValueException("Private network for the vlan: " + uriString + " and cidr " + cidr + " already exists " + "for Vpc " + vpcId + + " in zone " + _entityMgr.findById(DataCenter.class, pNtwk.getDataCenterId()).getName()); } } //add entry to private_ip_address table PrivateIpVO privateIp = _privateIpDao.findByIpAndSourceNetworkIdAndVpcId(privateNetwork.getId(), startIp, vpcId); if (privateIp != null) { - throw new InvalidParameterValueException("Private ip address " + startIp + " already used for private gateway" + " in zone " + - _entityMgr.findById(DataCenter.class, pNtwk.getDataCenterId()).getName()); + throw new InvalidParameterValueException("Private ip address " + startIp + " already used for private gateway" + " in zone " + + _entityMgr.findById(DataCenter.class, pNtwk.getDataCenterId()).getName()); } Long mac = dc.getMacAddress(); @@ -4016,17 +4001,18 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { public List listNics(ListNicsCmd cmd) { Account caller = CallContext.current().getCallingAccount(); Long nicId = cmd.getNicId(); - Long vmId = cmd.getVmId(); + long vmId = cmd.getVmId(); + Long networkId = cmd.getNetworkId(); UserVmVO userVm = _userVmDao.findById(vmId); if (userVm == null) { InvalidParameterValueException ex = new InvalidParameterValueException("Virtual mahine id does not exist"); - ex.addProxyObject(vmId.toString(), "vmId"); + ex.addProxyObject(Long.valueOf(vmId).toString(), "vmId"); throw ex; } _accountMgr.checkAccess(caller, null, true, userVm); - return _networkMgr.listVmNics(vmId, nicId); + return _networkMgr.listVmNics(vmId, nicId, networkId); } public List getNetworkGurus() { diff --git a/server/src/com/cloud/network/NetworkUsageManagerImpl.java b/server/src/com/cloud/network/NetworkUsageManagerImpl.java index 021ae7f46e7..e9b039369aa 100755 --- a/server/src/com/cloud/network/NetworkUsageManagerImpl.java +++ b/server/src/com/cloud/network/NetworkUsageManagerImpl.java @@ -75,7 +75,6 @@ import com.cloud.resource.UnableDeleteHostException; import com.cloud.usage.UsageIPAddressVO; import com.cloud.user.Account; import com.cloud.user.AccountManager; -import com.cloud.user.AccountVO; import com.cloud.user.UserStatisticsVO; import com.cloud.user.dao.UserStatisticsDao; import com.cloud.utils.NumbersUtil; @@ -256,7 +255,7 @@ public class NetworkUsageManagerImpl extends ManagerBase implements NetworkUsage private int _interval; - private long mgmtSrvrId = MacAddress.getMacAddress().toLong(); + private final long mgmtSrvrId = MacAddress.getMacAddress().toLong(); protected DirectNetworkStatsListener(int interval) { _interval = interval; diff --git a/server/src/com/cloud/network/as/AutoScaleManager.java b/server/src/com/cloud/network/as/AutoScaleManager.java index 9c841d451be..410fb8f923e 100644 --- a/server/src/com/cloud/network/as/AutoScaleManager.java +++ b/server/src/com/cloud/network/as/AutoScaleManager.java @@ -20,7 +20,7 @@ public interface AutoScaleManager extends AutoScaleService { void cleanUpAutoScaleResources(Long accountId); - void doScaleUp(long groupId, Integer numVm); + void doScaleUp(long groupId, Integer numVm); - void doScaleDown(long groupId); + void doScaleDown(long groupId); } diff --git a/server/src/com/cloud/network/as/AutoScaleManagerImpl.java b/server/src/com/cloud/network/as/AutoScaleManagerImpl.java index fd415b1fe90..7492c9ace6b 100644 --- a/server/src/com/cloud/network/as/AutoScaleManagerImpl.java +++ b/server/src/com/cloud/network/as/AutoScaleManagerImpl.java @@ -50,13 +50,13 @@ import org.apache.cloudstack.api.command.user.autoscale.UpdateAutoScalePolicyCmd import org.apache.cloudstack.api.command.user.autoscale.UpdateAutoScaleVmGroupCmd; import org.apache.cloudstack.api.command.user.autoscale.UpdateAutoScaleVmProfileCmd; import org.apache.cloudstack.api.command.user.vm.DeployVMCmd; +import org.apache.cloudstack.config.ApiServiceConfiguration; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.log4j.Logger; import com.cloud.api.ApiDBUtils; import com.cloud.api.ApiDispatcher; -import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationManager; import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter.NetworkType; @@ -174,10 +174,10 @@ public class AutoScaleManagerImpl extends ManagerBase implements AutoScale UserVmService _userVmService; @Inject UserVmManager _userVmManager; - @Inject - LoadBalancerVMMapDao _LbVmMapDao; - @Inject - LoadBalancingRulesService _LoadBalancingRulesService; + @Inject + LoadBalancerVMMapDao _lbVmMapDao; + @Inject + LoadBalancingRulesService _loadBalancingRulesService; public List getSupportedAutoScaleCounters(long networkid) { String capability = _lbRulesMgr.getLBCapability(networkid, Capability.AutoScaleCounters.getName()); @@ -312,7 +312,7 @@ public class AutoScaleManagerImpl extends ManagerBase implements AutoScale String apiKey = user.getApiKey(); String secretKey = user.getSecretKey(); - String csUrl = _configDao.getValue(Config.EndpointeUrl.key()); + String csUrl = ApiServiceConfiguration.ApiServletPath.value(); if (apiKey == null) { throw new InvalidParameterValueException("apiKey for user: " + user.getUsername() + " is empty. Please generate it"); @@ -437,12 +437,14 @@ public class AutoScaleManagerImpl extends ManagerBase implements AutoScale Long id = cmd.getId(); Long templateId = cmd.getTemplateId(); String otherDeployParams = cmd.getOtherDeployParams(); + Long serviceOffId = cmd.getServiceOfferingId(); SearchWrapper searchWrapper = new SearchWrapper(_autoScaleVmProfileDao, AutoScaleVmProfileVO.class, cmd, cmd.getId()); SearchBuilder sb = searchWrapper.getSearchBuilder(); sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("templateId", sb.entity().getTemplateId(), SearchCriteria.Op.EQ); + sb.and("serviceOfferingId", sb.entity().getServiceOfferingId(), SearchCriteria.Op.EQ); sb.and("otherDeployParams", sb.entity().getOtherDeployParams(), SearchCriteria.Op.LIKE); SearchCriteria sc = searchWrapper.buildSearchCriteria(); @@ -455,6 +457,11 @@ public class AutoScaleManagerImpl extends ManagerBase implements AutoScale if (otherDeployParams != null) { sc.addAnd("otherDeployParams", SearchCriteria.Op.LIKE, "%" + otherDeployParams + "%"); } + + if (serviceOffId != null) { + sc.setParameters("serviceOfferingId", serviceOffId); + } + return searchWrapper.search(); } @@ -739,7 +746,7 @@ public class AutoScaleManagerImpl extends ManagerBase implements AutoScale } AutoScaleVmGroupVO vmGroupVO = new AutoScaleVmGroupVO(cmd.getLbRuleId(), zoneId, loadBalancer.getDomainId(), loadBalancer.getAccountId(), minMembers, maxMembers, - loadBalancer.getDefaultPortStart(), interval, null, cmd.getProfileId(), AutoScaleVmGroup.State_New); + loadBalancer.getDefaultPortStart(), interval, null, cmd.getProfileId(), AutoScaleVmGroup.State_New); vmGroupVO = checkValidityAndPersist(vmGroupVO, cmd.getScaleUpPolicyIds(), cmd.getScaleDownPolicyIds()); s_logger.info("Successfully created Autoscale Vm Group with Id: " + vmGroupVO.getId()); @@ -1202,36 +1209,36 @@ public class AutoScaleManagerImpl extends ManagerBase implements AutoScale } } - private boolean checkConditionUp(AutoScaleVmGroupVO asGroup, Integer numVm) { - // check maximum - Integer currentVM = _autoScaleVmGroupVmMapDao.countByGroup(asGroup.getId()); - Integer maxVm = asGroup.getMaxMembers(); - if (currentVM + numVm > maxVm) { - s_logger.warn("number of VM will greater than the maximum in this group if scaling up, so do nothing more"); - return false; - } - return true; + private boolean checkConditionUp(AutoScaleVmGroupVO asGroup, Integer numVm) { + // check maximum + Integer currentVM = _autoScaleVmGroupVmMapDao.countByGroup(asGroup.getId()); + Integer maxVm = asGroup.getMaxMembers(); + if (currentVM + numVm > maxVm) { + s_logger.warn("number of VM will greater than the maximum in this group if scaling up, so do nothing more"); + return false; + } + return true; } - - private boolean checkConditionDown(AutoScaleVmGroupVO asGroup) { - Integer currentVM = _autoScaleVmGroupVmMapDao.countByGroup(asGroup.getId()); - Integer minVm = asGroup.getMinMembers(); - if (currentVM - 1 < minVm) { - s_logger.warn("number of VM will less than the minimum in this group if scaling down, so do nothing more"); - return false; - } - return true; - } - - private long createNewVM(AutoScaleVmGroupVO asGroup) { - AutoScaleVmProfileVO profileVo = _autoScaleVmProfileDao.findById(asGroup.getProfileId()); - long templateId = profileVo.getTemplateId(); - long serviceOfferingId = profileVo.getServiceOfferingId(); - if (templateId == -1) { - return -1; - } - // create new VM into DB - try { + + private boolean checkConditionDown(AutoScaleVmGroupVO asGroup) { + Integer currentVM = _autoScaleVmGroupVmMapDao.countByGroup(asGroup.getId()); + Integer minVm = asGroup.getMinMembers(); + if (currentVM - 1 < minVm) { + s_logger.warn("number of VM will less than the minimum in this group if scaling down, so do nothing more"); + return false; + } + return true; + } + + private long createNewVM(AutoScaleVmGroupVO asGroup) { + AutoScaleVmProfileVO profileVo = _autoScaleVmProfileDao.findById(asGroup.getProfileId()); + long templateId = profileVo.getTemplateId(); + long serviceOfferingId = profileVo.getServiceOfferingId(); + if (templateId == -1) { + return -1; + } + // create new VM into DB + try { //Verify that all objects exist before passing them to the service Account owner = _accountService.getActiveAccountById(profileVo.getAccountId()); @@ -1258,26 +1265,31 @@ public class AutoScaleManagerImpl extends ManagerBase implements AutoScale } UserVm vm = null; - IpAddresses addrs = new IpAddresses(null, null); - if (zone.getNetworkType() == NetworkType.Basic) { - vm = _userVmService.createBasicSecurityGroupVirtualMachine(zone, serviceOffering, template, null, owner, "autoScaleVm-" + asGroup.getId() + "-" + getCurrentTimeStampString(), - "autoScaleVm-" + asGroup.getId() + "-" + getCurrentTimeStampString(), null, null, null, HypervisorType.XenServer, HTTPMethod.GET, null, null, null, null, true, null, null, null, null); + IpAddresses addrs = new IpAddresses(null, null); + if (zone.getNetworkType() == NetworkType.Basic) { + vm = _userVmService.createBasicSecurityGroupVirtualMachine(zone, serviceOffering, template, null, owner, "autoScaleVm-" + asGroup.getId() + "-" + + getCurrentTimeStampString(), + "autoScaleVm-" + asGroup.getId() + "-" + getCurrentTimeStampString(), null, null, null, HypervisorType.XenServer, HTTPMethod.GET, null, null, null, + null, true, null, null, null, null); } else { - if (zone.isSecurityGroupEnabled()) { + if (zone.isSecurityGroupEnabled()) { vm = _userVmService.createAdvancedSecurityGroupVirtualMachine(zone, serviceOffering, template, null, null, - owner, "autoScaleVm-" + asGroup.getId() + "-" + getCurrentTimeStampString(), "autoScaleVm-" + asGroup.getId() + "-" + getCurrentTimeStampString(), null, null, null, HypervisorType.XenServer, HTTPMethod.GET, null, null, null, null, true, null, null, null, null); + owner, "autoScaleVm-" + asGroup.getId() + "-" + getCurrentTimeStampString(), + "autoScaleVm-" + asGroup.getId() + "-" + getCurrentTimeStampString(), null, null, null, HypervisorType.XenServer, HTTPMethod.GET, null, null, + null, null, true, null, null, null, null); } else { - vm = _userVmService.createAdvancedVirtualMachine(zone, serviceOffering, template, null, owner, "autoScaleVm-" + asGroup.getId() + "-" + getCurrentTimeStampString(), "autoScaleVm-" + asGroup.getId() + "-" + getCurrentTimeStampString(), - null, null, null, HypervisorType.XenServer, HTTPMethod.GET, null, null, null, addrs, true, null, null, null, null); + vm = _userVmService.createAdvancedVirtualMachine(zone, serviceOffering, template, null, owner, "autoScaleVm-" + asGroup.getId() + "-" + + getCurrentTimeStampString(), "autoScaleVm-" + asGroup.getId() + "-" + getCurrentTimeStampString(), + null, null, null, HypervisorType.XenServer, HTTPMethod.GET, null, null, null, addrs, true, null, null, null, null); } } if (vm != null) { - return vm.getId(); + return vm.getId(); } else { - return -1; + return -1; } } catch (InsufficientCapacityException ex) { s_logger.info(ex); @@ -1286,26 +1298,26 @@ public class AutoScaleManagerImpl extends ManagerBase implements AutoScale } catch (ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); - } catch (ConcurrentOperationException ex) { + } catch (ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } catch (ResourceAllocationException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_ALLOCATION_ERROR, ex.getMessage()); } - } - - private String getCurrentTimeStampString(){ - Date current = new Date(); - SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); - - return sdf.format(current); - } + } - private boolean startNewVM(long vmId) { - try { - CallContext.current().setEventDetails("Vm Id: "+vmId); - _userVmManager.startVirtualMachine(vmId, null, null); + private String getCurrentTimeStampString() { + Date current = new Date(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); + + return sdf.format(current); + } + + private boolean startNewVM(long vmId) { + try { + CallContext.current().setEventDetails("Vm Id: " + vmId); + _userVmManager.startVirtualMachine(vmId, null, null); } catch (ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); @@ -1315,7 +1327,7 @@ public class AutoScaleManagerImpl extends ManagerBase implements AutoScale } catch (InsufficientCapacityException ex) { StringBuilder message = new StringBuilder(ex.getMessage()); if (ex instanceof InsufficientServerCapacityException) { - if(((InsufficientServerCapacityException)ex).isAffinityApplied()){ + if (((InsufficientServerCapacityException)ex).isAffinityApplied()) { message.append(", Please check the affinity groups provided, there may not be sufficient capacity to follow them"); } } @@ -1323,144 +1335,143 @@ public class AutoScaleManagerImpl extends ManagerBase implements AutoScale s_logger.info(message.toString(), ex); throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, message.toString()); } - return true; - } - - private boolean assignLBruleToNewVm(long vmId, AutoScaleVmGroupVO asGroup) { - List lstVmId = new ArrayList(); - long lbId = asGroup.getLoadBalancerId(); - - List LbVmMapVos = _LbVmMapDao.listByLoadBalancerId(lbId); - if ((LbVmMapVos != null) && (LbVmMapVos.size() > 0)) { - for (LoadBalancerVMMapVO LbVmMapVo : LbVmMapVos) { - long instanceId = LbVmMapVo.getInstanceId(); - if (instanceId == vmId) { - s_logger.warn("the new VM is already mapped to LB rule. What's wrong?"); - return true; - } - } - } - lstVmId.add(new Long(vmId)); - return _LoadBalancingRulesService.assignToLoadBalancer(lbId, lstVmId); + return true; + } - } + private boolean assignLBruleToNewVm(long vmId, AutoScaleVmGroupVO asGroup) { + List lstVmId = new ArrayList(); + long lbId = asGroup.getLoadBalancerId(); - private long removeLBrule(AutoScaleVmGroupVO asGroup) { - long lbId = asGroup.getLoadBalancerId(); - long instanceId = -1; - List LbVmMapVos = _LbVmMapDao.listByLoadBalancerId(lbId); - if ((LbVmMapVos != null) && (LbVmMapVos.size() > 0)) { - for (LoadBalancerVMMapVO LbVmMapVo : LbVmMapVos) { - instanceId = LbVmMapVo.getInstanceId(); - } - } - // take last VM out of the list - List lstVmId = new ArrayList(); - if (instanceId != -1) - lstVmId.add(instanceId); - if (_LoadBalancingRulesService.removeFromLoadBalancer(lbId, lstVmId)) - return instanceId; - else - return -1; - } + List LbVmMapVos = _lbVmMapDao.listByLoadBalancerId(lbId); + if ((LbVmMapVos != null) && (LbVmMapVos.size() > 0)) { + for (LoadBalancerVMMapVO LbVmMapVo : LbVmMapVos) { + long instanceId = LbVmMapVo.getInstanceId(); + if (instanceId == vmId) { + s_logger.warn("the new VM is already mapped to LB rule. What's wrong?"); + return true; + } + } + } + lstVmId.add(new Long(vmId)); + return _loadBalancingRulesService.assignToLoadBalancer(lbId, lstVmId); - @Override - public void doScaleUp(long groupId, Integer numVm) { - AutoScaleVmGroupVO asGroup = _autoScaleVmGroupDao.findById(groupId); - if (asGroup == null) { - s_logger.error("Can not find the groupid " + groupId + " for scaling up"); - return; - } - if (!checkConditionUp(asGroup, numVm)) { - return; - } - for (int i = 0; i < numVm; i++) { - long vmId = createNewVM(asGroup); - if (vmId == -1) { - s_logger.error("Can not deploy new VM for scaling up in the group " - + asGroup.getId() + ". Waiting for next round"); - break; - } - if (startNewVM(vmId)) { - if (assignLBruleToNewVm(vmId, asGroup)) { - // persist to DB - AutoScaleVmGroupVmMapVO GroupVmVO = new AutoScaleVmGroupVmMapVO( - asGroup.getId(), vmId); - _autoScaleVmGroupVmMapDao.persist(GroupVmVO); - // update last_quiettime - List GroupPolicyVOs = _autoScaleVmGroupPolicyMapDao - .listByVmGroupId(groupId); - for (AutoScaleVmGroupPolicyMapVO GroupPolicyVO : GroupPolicyVOs) { - AutoScalePolicyVO vo = _autoScalePolicyDao - .findById(GroupPolicyVO.getPolicyId()); - if (vo.getAction().equals("scaleup")) { - vo.setLastQuiteTime(new Date()); - _autoScalePolicyDao.persist(vo); - break; - } - } - } else { - s_logger.error("Can not assign LB rule for this new VM"); - break; - } - } else { - s_logger.error("Can not deploy new VM for scaling up in the group " - + asGroup.getId() + ". Waiting for next round"); - break; - } - } - } + } - @Override - public void doScaleDown(final long groupId) { - AutoScaleVmGroupVO asGroup = _autoScaleVmGroupDao.findById(groupId); - if (asGroup == null) { - s_logger.error("Can not find the groupid " + groupId + " for scaling up"); - return; - } - if (!checkConditionDown(asGroup)) { - return; - } - final long vmId = removeLBrule(asGroup); - if (vmId != -1) { - long profileId = asGroup.getProfileId(); + private long removeLBrule(AutoScaleVmGroupVO asGroup) { + long lbId = asGroup.getLoadBalancerId(); + long instanceId = -1; + List LbVmMapVos = _lbVmMapDao.listByLoadBalancerId(lbId); + if ((LbVmMapVos != null) && (LbVmMapVos.size() > 0)) { + for (LoadBalancerVMMapVO LbVmMapVo : LbVmMapVos) { + instanceId = LbVmMapVo.getInstanceId(); + } + } + // take last VM out of the list + List lstVmId = new ArrayList(); + if (instanceId != -1) + lstVmId.add(instanceId); + if (_loadBalancingRulesService.removeFromLoadBalancer(lbId, lstVmId)) + return instanceId; + else + return -1; + } - // update group-vm mapping - _autoScaleVmGroupVmMapDao.remove(groupId, vmId); - // update last_quiettime - List GroupPolicyVOs = _autoScaleVmGroupPolicyMapDao.listByVmGroupId(groupId); - for (AutoScaleVmGroupPolicyMapVO GroupPolicyVO : GroupPolicyVOs) { - AutoScalePolicyVO vo = _autoScalePolicyDao.findById(GroupPolicyVO.getPolicyId()); - if (vo.getAction().equals("scaledown")) { - vo.setLastQuiteTime(new Date()); - _autoScalePolicyDao.persist(vo); - break; - } - } + @Override + public void doScaleUp(long groupId, Integer numVm) { + AutoScaleVmGroupVO asGroup = _autoScaleVmGroupDao.findById(groupId); + if (asGroup == null) { + s_logger.error("Can not find the groupid " + groupId + " for scaling up"); + return; + } + if (!checkConditionUp(asGroup, numVm)) { + return; + } + for (int i = 0; i < numVm; i++) { + long vmId = createNewVM(asGroup); + if (vmId == -1) { + s_logger.error("Can not deploy new VM for scaling up in the group " + + asGroup.getId() + ". Waiting for next round"); + break; + } + if (startNewVM(vmId)) { + if (assignLBruleToNewVm(vmId, asGroup)) { + // persist to DB + AutoScaleVmGroupVmMapVO GroupVmVO = new AutoScaleVmGroupVmMapVO( + asGroup.getId(), vmId); + _autoScaleVmGroupVmMapDao.persist(GroupVmVO); + // update last_quiettime + List GroupPolicyVOs = _autoScaleVmGroupPolicyMapDao + .listByVmGroupId(groupId); + for (AutoScaleVmGroupPolicyMapVO GroupPolicyVO : GroupPolicyVOs) { + AutoScalePolicyVO vo = _autoScalePolicyDao + .findById(GroupPolicyVO.getPolicyId()); + if (vo.getAction().equals("scaleup")) { + vo.setLastQuiteTime(new Date()); + _autoScalePolicyDao.persist(vo); + break; + } + } + } else { + s_logger.error("Can not assign LB rule for this new VM"); + break; + } + } else { + s_logger.error("Can not deploy new VM for scaling up in the group " + + asGroup.getId() + ". Waiting for next round"); + break; + } + } + } - // get destroyvmgrace param - AutoScaleVmProfileVO asProfile = _autoScaleVmProfileDao.findById(profileId); - Integer destroyVmGracePeriod = asProfile.getDestroyVmGraceperiod(); - if (destroyVmGracePeriod >= 0) { - _executor.schedule(new Runnable() { - @Override - public void run() { - try { + @Override + public void doScaleDown(final long groupId) { + AutoScaleVmGroupVO asGroup = _autoScaleVmGroupDao.findById(groupId); + if (asGroup == null) { + s_logger.error("Can not find the groupid " + groupId + " for scaling up"); + return; + } + if (!checkConditionDown(asGroup)) { + return; + } + final long vmId = removeLBrule(asGroup); + if (vmId != -1) { + long profileId = asGroup.getProfileId(); - _userVmManager.destroyVm(vmId); + // update group-vm mapping + _autoScaleVmGroupVmMapDao.remove(groupId, vmId); + // update last_quiettime + List GroupPolicyVOs = _autoScaleVmGroupPolicyMapDao.listByVmGroupId(groupId); + for (AutoScaleVmGroupPolicyMapVO GroupPolicyVO : GroupPolicyVOs) { + AutoScalePolicyVO vo = _autoScalePolicyDao.findById(GroupPolicyVO.getPolicyId()); + if (vo.getAction().equals("scaledown")) { + vo.setLastQuiteTime(new Date()); + _autoScalePolicyDao.persist(vo); + break; + } + } - } catch (ResourceUnavailableException e) { - e.printStackTrace(); - } catch (ConcurrentOperationException e) { - e.printStackTrace(); - } - } - }, destroyVmGracePeriod, TimeUnit.SECONDS); - } - } else { - s_logger.error("Can not remove LB rule for the VM being destroyed. Do nothing more."); - } - } - + // get destroyvmgrace param + AutoScaleVmProfileVO asProfile = _autoScaleVmProfileDao.findById(profileId); + Integer destroyVmGracePeriod = asProfile.getDestroyVmGraceperiod(); + if (destroyVmGracePeriod >= 0) { + _executor.schedule(new Runnable() { + @Override + public void run() { + try { + + _userVmManager.destroyVm(vmId); + + } catch (ResourceUnavailableException e) { + e.printStackTrace(); + } catch (ConcurrentOperationException e) { + e.printStackTrace(); + } + } + }, destroyVmGracePeriod, TimeUnit.SECONDS); + } + } else { + s_logger.error("Can not remove LB rule for the VM being destroyed. Do nothing more."); + } + } } diff --git a/server/src/com/cloud/network/element/CloudZonesNetworkElement.java b/server/src/com/cloud/network/element/CloudZonesNetworkElement.java index 3b3646aecfb..55cd5fa5cad 100644 --- a/server/src/com/cloud/network/element/CloudZonesNetworkElement.java +++ b/server/src/com/cloud/network/element/CloudZonesNetworkElement.java @@ -250,7 +250,7 @@ public class CloudZonesNetworkElement extends AdapterBase implements NetworkElem } @Override - public boolean saveSSHKey(Network network, NicProfile nic, VirtualMachineProfile vm, String SSHPublicKey) throws ResourceUnavailableException { + public boolean saveSSHKey(Network network, NicProfile nic, VirtualMachineProfile vm, String sshPublicKey) throws ResourceUnavailableException { // TODO Auto-generated method stub return false; } diff --git a/server/src/com/cloud/network/element/VirtualRouterElement.java b/server/src/com/cloud/network/element/VirtualRouterElement.java index 7833d241d6d..455e75ff91b 100755 --- a/server/src/com/cloud/network/element/VirtualRouterElement.java +++ b/server/src/com/cloud/network/element/VirtualRouterElement.java @@ -30,13 +30,11 @@ import org.apache.log4j.Logger; import com.google.gson.Gson; import org.apache.cloudstack.api.command.admin.router.ConfigureOvsElementCmd; - import org.apache.cloudstack.api.command.admin.router.ConfigureVirtualRouterElementCmd; import org.apache.cloudstack.api.command.admin.router.CreateVirtualRouterElementCmd; import org.apache.cloudstack.api.command.admin.router.ListOvsElementsCmd; import org.apache.cloudstack.api.command.admin.router.ListVirtualRouterElementsCmd; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; -import org.apache.log4j.Logger; import com.cloud.agent.api.to.LoadBalancerTO; import com.cloud.configuration.ConfigurationManager; @@ -103,23 +101,20 @@ import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.VirtualMachineProfile; import com.cloud.vm.dao.DomainRouterDao; import com.cloud.vm.dao.UserVmDao; -import com.google.gson.Gson; - -import com.google.gson.Gson; @Local(value = {NetworkElement.class, FirewallServiceProvider.class, - DhcpServiceProvider.class, UserDataServiceProvider.class, - StaticNatServiceProvider.class, LoadBalancingServiceProvider.class, - PortForwardingServiceProvider.class, IpDeployer.class, - RemoteAccessVPNServiceProvider.class, NetworkMigrationResponder.class} ) + DhcpServiceProvider.class, UserDataServiceProvider.class, + StaticNatServiceProvider.class, LoadBalancingServiceProvider.class, + PortForwardingServiceProvider.class, IpDeployer.class, + RemoteAccessVPNServiceProvider.class, NetworkMigrationResponder.class}) public class VirtualRouterElement extends AdapterBase implements VirtualRouterElementService, DhcpServiceProvider, - UserDataServiceProvider, SourceNatServiceProvider, StaticNatServiceProvider, FirewallServiceProvider, + UserDataServiceProvider, SourceNatServiceProvider, StaticNatServiceProvider, FirewallServiceProvider, LoadBalancingServiceProvider, PortForwardingServiceProvider, RemoteAccessVPNServiceProvider, IpDeployer, NetworkMigrationResponder { private static final Logger s_logger = Logger.getLogger(VirtualRouterElement.class); - public static final AutoScaleCounterType AutoScaleCounterCpu = new AutoScaleCounterType("cpu"); - public static final AutoScaleCounterType AutoScaleCounterMemory = new AutoScaleCounterType("memory"); - protected static final Map> capabilities = setCapabilities(); + public static final AutoScaleCounterType AutoScaleCounterCpu = new AutoScaleCounterType("cpu"); + public static final AutoScaleCounterType AutoScaleCounterMemory = new AutoScaleCounterType("memory"); + protected static final Map> capabilities = setCapabilities(); @Inject NetworkDao _networksDao; @@ -153,8 +148,8 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl @Inject VirtualRouterProviderDao _vrProviderDao; @Inject - OvsProviderDao _ovsProviderDao; - @Inject + OvsProviderDao _ovsProviderDao; + @Inject IPAddressDao _ipAddressDao; protected boolean canHandle(Network network, Service service) { @@ -246,10 +241,10 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl return true; } - if (rules != null && rules.size() == 1 ) { + if (rules != null && rules.size() == 1) { // for VR no need to add default egress rule to DENY traffic if (rules.get(0).getTrafficType() == FirewallRule.TrafficType.Egress && rules.get(0).getType() == FirewallRule.FirewallRuleType.System && - ! _networkMgr.getNetworkEgressDefaultPolicy(config.getId())) + !_networkMgr.getNetworkEgressDefaultPolicy(config.getId())) return true; } @@ -568,13 +563,13 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl lbCapabilities.put(Capability.SupportedProtocols, "tcp, udp"); lbCapabilities.put(Capability.SupportedStickinessMethods, getHAProxyStickinessCapability()); lbCapabilities.put(Capability.LbSchemes, LoadBalancerContainer.Scheme.Public.toString()); - + //specifies that LB rules can support autoscaling and the list of counters it supports AutoScaleCounter counter; List counterList = new ArrayList(); - counter = new AutoScaleCounter(AutoScaleCounterCpu); + counter = new AutoScaleCounter(AutoScaleCounterCpu); counterList.add(counter); - counter = new AutoScaleCounter(AutoScaleCounterMemory); + counter = new AutoScaleCounter(AutoScaleCounterMemory); counterList.add(counter); Gson gson = new Gson(); String autoScaleCounterList = gson.toJson(counterList); @@ -691,7 +686,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl } @Override - public boolean saveSSHKey(Network network, NicProfile nic, VirtualMachineProfile vm, String SSHPublicKey) throws ResourceUnavailableException { + public boolean saveSSHKey(Network network, NicProfile nic, VirtualMachineProfile vm, String sshPublicKey) throws ResourceUnavailableException { if (!canHandle(network, null)) { return false; } @@ -704,7 +699,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl @SuppressWarnings("unchecked") VirtualMachineProfile uservm = vm; - return _routerMgr.saveSSHPublicKeyToRouter(network, nic, uservm, routers, SSHPublicKey); + return _routerMgr.saveSSHPublicKeyToRouter(network, nic, uservm, routers, sshPublicKey); } @Override @@ -747,20 +742,20 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl return element; } - @Override - public OvsProvider configure(ConfigureOvsElementCmd cmd) { - OvsProviderVO element = _ovsProviderDao.findById(cmd.getId()); - if (element == null) { - s_logger.debug("Can't find Ovs element with network service provider id " - + cmd.getId()); - return null; - } + @Override + public OvsProvider configure(ConfigureOvsElementCmd cmd) { + OvsProviderVO element = _ovsProviderDao.findById(cmd.getId()); + if (element == null) { + s_logger.debug("Can't find Ovs element with network service provider id " + + cmd.getId()); + return null; + } - element.setEnabled(cmd.getEnabled()); - _ovsProviderDao.persist(element); + element.setEnabled(cmd.getEnabled()); + _ovsProviderDao.persist(element); - return element; - } + return element; + } @Override public VirtualRouterProvider addElement(Long nspId, Type providerType) { @@ -992,25 +987,25 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl return sc.list(); } - @Override - public List searchForOvsElement(ListOvsElementsCmd cmd) { - Long id = cmd.getId(); - Long nspId = cmd.getNspId(); - Boolean enabled = cmd.getEnabled(); - QueryBuilder sc = QueryBuilder.create(OvsProviderVO.class); + @Override + public List searchForOvsElement(ListOvsElementsCmd cmd) { + Long id = cmd.getId(); + Long nspId = cmd.getNspId(); + Boolean enabled = cmd.getEnabled(); + QueryBuilder sc = QueryBuilder.create(OvsProviderVO.class); - if (id != null) { - sc.and(sc.entity().getId(), Op.EQ, id); - } - if (nspId != null) { - sc.and(sc.entity().getNspId(), Op.EQ, nspId); - } - if (enabled != null) { - sc.and(sc.entity().isEnabled(), Op.EQ, enabled); - } + if (id != null) { + sc.and(sc.entity().getId(), Op.EQ, id); + } + if (nspId != null) { + sc.and(sc.entity().getNspId(), Op.EQ, nspId); + } + if (enabled != null) { + sc.and(sc.entity().isEnabled(), Op.EQ, enabled); + } - return sc.list(); - } + return sc.list(); + } @Override public boolean verifyServicesCombination(Set services) { diff --git a/server/src/com/cloud/network/element/VpcVirtualRouterElement.java b/server/src/com/cloud/network/element/VpcVirtualRouterElement.java index f535e2e959c..5695a2c9fcd 100644 --- a/server/src/com/cloud/network/element/VpcVirtualRouterElement.java +++ b/server/src/com/cloud/network/element/VpcVirtualRouterElement.java @@ -353,6 +353,9 @@ public class VpcVirtualRouterElement extends VirtualRouterElement implements Vpc s_logger.debug("Failed to apply network acl id " + gateway.getNetworkACLId() + " on gateway "); return false; } + } else { + s_logger.debug ("Failed to setup private gateway "+ gateway); + return false; } return true; } @@ -413,10 +416,15 @@ public class VpcVirtualRouterElement extends VirtualRouterElement implements Vpc return true; } - if (!_vpcRouterMgr.applyNetworkACLs(config, rules, routers, false)) { - throw new CloudRuntimeException("Failed to apply network acl rules in network " + config.getId()); - } else { - return true; + try { + if (!_vpcRouterMgr.applyNetworkACLs(config, rules, routers, false)) { + return false; + } else { + return true; + } + } catch (Exception ex) { + s_logger.debug("Failed to apply network acl in network " + config.getId()); + return false; } } else { return true; diff --git a/server/src/com/cloud/network/guru/ControlNetworkGuru.java b/server/src/com/cloud/network/guru/ControlNetworkGuru.java index 08cc3e6fd30..13ff385da90 100755 --- a/server/src/com/cloud/network/guru/ControlNetworkGuru.java +++ b/server/src/com/cloud/network/guru/ControlNetworkGuru.java @@ -66,11 +66,11 @@ public class ControlNetworkGuru extends PodBasedNetworkGuru implements NetworkGu String _cidr; String _gateway; - private static final TrafficType[] _trafficTypes = {TrafficType.Control}; + private static final TrafficType[] TrafficTypes = {TrafficType.Control}; @Override public boolean isMyTrafficType(TrafficType type) { - for (TrafficType t : _trafficTypes) { + for (TrafficType t : TrafficTypes) { if (t == type) { return true; } @@ -80,7 +80,7 @@ public class ControlNetworkGuru extends PodBasedNetworkGuru implements NetworkGu @Override public TrafficType[] getSupportedTrafficType() { - return _trafficTypes; + return TrafficTypes; } protected boolean canHandle(NetworkOffering offering) { @@ -173,8 +173,8 @@ public class ControlNetworkGuru extends PodBasedNetworkGuru implements NetworkGu @Override public boolean release(NicProfile nic, VirtualMachineProfile vm, String reservationId) { assert nic.getTrafficType() == TrafficType.Control; - - if (vm.getHypervisorType() == HypervisorType.VMware && isRouterVm(vm)) { + HypervisorType hType = vm.getHypervisorType(); + if ( ( (hType == HypervisorType.VMware) || (hType == HypervisorType.Hyperv) )&& isRouterVm(vm)) { long dcId = vm.getVirtualMachine().getDataCenterId(); DataCenterVO dcVo = _dcDao.findById(dcId); if (dcVo.getNetworkType() != NetworkType.Basic) { @@ -224,12 +224,12 @@ public class ControlNetworkGuru extends PodBasedNetworkGuru implements NetworkGu Map dbParams = _configDao.getConfiguration(params); - _cidr = dbParams.get(Config.ControlCidr); + _cidr = dbParams.get(Config.ControlCidr.toString()); if (_cidr == null) { _cidr = "169.254.0.0/16"; } - _gateway = dbParams.get(Config.ControlGateway); + _gateway = dbParams.get(Config.ControlGateway.toString()); if (_gateway == null) { _gateway = NetUtils.getLinkLocalGateway(); } diff --git a/server/src/com/cloud/network/guru/DirectNetworkGuru.java b/server/src/com/cloud/network/guru/DirectNetworkGuru.java index 0fec81f7093..e570dddfb9a 100755 --- a/server/src/com/cloud/network/guru/DirectNetworkGuru.java +++ b/server/src/com/cloud/network/guru/DirectNetworkGuru.java @@ -98,11 +98,11 @@ public class DirectNetworkGuru extends AdapterBase implements NetworkGuru { @Inject IpAddressManager _ipAddrMgr; - private static final TrafficType[] _trafficTypes = {TrafficType.Guest}; + private static final TrafficType[] TrafficTypes = {TrafficType.Guest}; @Override public boolean isMyTrafficType(TrafficType type) { - for (TrafficType t : _trafficTypes) { + for (TrafficType t : TrafficTypes) { if (t == type) { return true; } @@ -112,7 +112,7 @@ public class DirectNetworkGuru extends AdapterBase implements NetworkGuru { @Override public TrafficType[] getSupportedTrafficType() { - return _trafficTypes; + return TrafficTypes; } protected boolean canHandle(NetworkOffering offering, DataCenter dc) { diff --git a/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java b/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java index bea94285456..414eb7b6543 100644 --- a/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java +++ b/server/src/com/cloud/network/guru/ExternalGuestNetworkGuru.java @@ -26,7 +26,6 @@ import org.apache.log4j.Logger; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; -import com.cloud.configuration.Config; import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter.NetworkType; import com.cloud.dc.dao.DataCenterDao; @@ -48,6 +47,11 @@ import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.IPAddressVO; import com.cloud.network.dao.NetworkDao; import com.cloud.network.dao.NetworkVO; +import com.cloud.network.dao.FirewallRulesCidrsDao; +import com.cloud.network.dao.FirewallRulesDao; +import com.cloud.network.rules.FirewallRule; +import com.cloud.network.rules.FirewallRuleVO; +import com.cloud.network.dao.FirewallRulesCidrsVO; import com.cloud.network.rules.PortForwardingRuleVO; import com.cloud.network.rules.dao.PortForwardingRulesDao; import com.cloud.offering.NetworkOffering; @@ -77,6 +81,10 @@ public class ExternalGuestNetworkGuru extends GuestNetworkGuru { IPAddressDao _ipAddressDao; @Inject IpAddressManager _ipAddrMgr; + @Inject + FirewallRulesDao _fwRulesDao; + @Inject + FirewallRulesCidrsDao _fwRulesCidrDao; public ExternalGuestNetworkGuru() { super(); @@ -204,6 +212,29 @@ public class ExternalGuestNetworkGuru extends GuestNetworkGuru { } } + //Egress rules cidr is subset of guest nework cidr, we need to change + List fwEgressRules = _fwRulesDao.listByNetworkPurposeTrafficType(config.getId(), FirewallRule.Purpose.Firewall, FirewallRule.TrafficType.Egress); + + for (FirewallRuleVO rule: fwEgressRules) { + //get the cidr list for this rule + List fwRuleCidrsVo = _fwRulesCidrDao.listByFirewallRuleId(rule.getId()); + + for (FirewallRulesCidrsVO ruleCidrvo: fwRuleCidrsVo) { + String cidr = ruleCidrvo.getCidr(); + String cidrAddr = cidr.split("/")[0]; + String size = cidr.split("/")[1]; + + long ipMask = getIpMask(cidrAddr, cidrSize); + String newIp = NetUtils.long2Ip(newCidrAddress | ipMask); + String updatedCidr = newIp+"/"+size; + + ruleCidrvo.setSourceCidrList(updatedCidr); + _fwRulesCidrDao.update(ruleCidrvo.getId(), ruleCidrvo); + } + + } + + return implemented; } diff --git a/server/src/com/cloud/network/guru/GuestNetworkGuru.java b/server/src/com/cloud/network/guru/GuestNetworkGuru.java index 1fd3e7fb397..a759951b85e 100755 --- a/server/src/com/cloud/network/guru/GuestNetworkGuru.java +++ b/server/src/com/cloud/network/guru/GuestNetworkGuru.java @@ -117,7 +117,7 @@ public abstract class GuestNetworkGuru extends AdapterBase implements NetworkGur "If true, when account has dedicated guest vlan range(s), once the vlans dedicated to the account have been consumed vlans will be allocated from the system pool", false, ConfigKey.Scope.Account); - private static final TrafficType[] _trafficTypes = {TrafficType.Guest}; + private static final TrafficType[] TrafficTypes = {TrafficType.Guest}; // Currently set to anything except STT for the Nicira integration. protected IsolationMethod[] _isolationMethods; @@ -132,7 +132,7 @@ public abstract class GuestNetworkGuru extends AdapterBase implements NetworkGur @Override public boolean isMyTrafficType(TrafficType type) { - for (TrafficType t : _trafficTypes) { + for (TrafficType t : TrafficTypes) { if (t == type) { return true; } @@ -142,7 +142,7 @@ public abstract class GuestNetworkGuru extends AdapterBase implements NetworkGur @Override public TrafficType[] getSupportedTrafficType() { - return _trafficTypes; + return TrafficTypes; } public boolean isMyIsolationMethod(PhysicalNetwork physicalNetwork) { diff --git a/server/src/com/cloud/network/guru/PodBasedNetworkGuru.java b/server/src/com/cloud/network/guru/PodBasedNetworkGuru.java index 66b80c9e6b5..84c79d0e3a4 100755 --- a/server/src/com/cloud/network/guru/PodBasedNetworkGuru.java +++ b/server/src/com/cloud/network/guru/PodBasedNetworkGuru.java @@ -57,11 +57,11 @@ public class PodBasedNetworkGuru extends AdapterBase implements NetworkGuru { StorageNetworkManager _sNwMgr; Random _rand = new Random(System.currentTimeMillis()); - private static final TrafficType[] _trafficTypes = {TrafficType.Management}; + private static final TrafficType[] TrafficTypes = {TrafficType.Management}; @Override public boolean isMyTrafficType(TrafficType type) { - for (TrafficType t : _trafficTypes) { + for (TrafficType t : TrafficTypes) { if (t == type) { return true; } @@ -71,7 +71,7 @@ public class PodBasedNetworkGuru extends AdapterBase implements NetworkGuru { @Override public TrafficType[] getSupportedTrafficType() { - return _trafficTypes; + return TrafficTypes; } @Override diff --git a/server/src/com/cloud/network/guru/PrivateNetworkGuru.java b/server/src/com/cloud/network/guru/PrivateNetworkGuru.java index 1710c4db470..35b7b5c5061 100644 --- a/server/src/com/cloud/network/guru/PrivateNetworkGuru.java +++ b/server/src/com/cloud/network/guru/PrivateNetworkGuru.java @@ -66,7 +66,7 @@ public class PrivateNetworkGuru extends AdapterBase implements NetworkGuru { @Inject EntityManager _entityMgr; - private static final TrafficType[] _trafficTypes = {TrafficType.Guest}; + private static final TrafficType[] TrafficTypes = {TrafficType.Guest}; protected PrivateNetworkGuru() { super(); @@ -74,7 +74,7 @@ public class PrivateNetworkGuru extends AdapterBase implements NetworkGuru { @Override public boolean isMyTrafficType(TrafficType type) { - for (TrafficType t : _trafficTypes) { + for (TrafficType t : TrafficTypes) { if (t == type) { return true; } @@ -84,7 +84,7 @@ public class PrivateNetworkGuru extends AdapterBase implements NetworkGuru { @Override public TrafficType[] getSupportedTrafficType() { - return _trafficTypes; + return TrafficTypes; } protected boolean canHandle(NetworkOffering offering, DataCenter dc) { diff --git a/server/src/com/cloud/network/guru/PublicNetworkGuru.java b/server/src/com/cloud/network/guru/PublicNetworkGuru.java index 58816af87b6..95d7790f2cb 100755 --- a/server/src/com/cloud/network/guru/PublicNetworkGuru.java +++ b/server/src/com/cloud/network/guru/PublicNetworkGuru.java @@ -74,11 +74,11 @@ public class PublicNetworkGuru extends AdapterBase implements NetworkGuru { @Inject IpAddressManager _ipAddrMgr; - private static final TrafficType[] _trafficTypes = {TrafficType.Public}; + private static final TrafficType[] TrafficTypes = {TrafficType.Public}; @Override public boolean isMyTrafficType(TrafficType type) { - for (TrafficType t : _trafficTypes) { + for (TrafficType t : TrafficTypes) { if (t == type) { return true; } @@ -88,7 +88,7 @@ public class PublicNetworkGuru extends AdapterBase implements NetworkGuru { @Override public TrafficType[] getSupportedTrafficType() { - return _trafficTypes; + return TrafficTypes; } protected boolean canHandle(NetworkOffering offering) { @@ -103,7 +103,7 @@ public class PublicNetworkGuru extends AdapterBase implements NetworkGuru { if (offering.getTrafficType() == TrafficType.Public) { NetworkVO ntwk = - new NetworkVO(offering.getTrafficType(), Mode.Static, BroadcastDomainType.Vlan, offering.getId(), State.Setup, plan.getDataCenterId(), + new NetworkVO(offering.getTrafficType(), Mode.Static, network.getBroadcastDomainType(), offering.getId(), State.Setup, plan.getDataCenterId(), plan.getPhysicalNetworkId()); return ntwk; } else { @@ -122,9 +122,15 @@ public class PublicNetworkGuru extends AdapterBase implements NetworkGuru { nic.setIp4Address(ip.getAddress().toString()); nic.setGateway(ip.getGateway()); nic.setNetmask(ip.getNetmask()); - nic.setIsolationUri(IsolationType.Vlan.toUri(ip.getVlanTag())); - nic.setBroadcastUri(BroadcastDomainType.Vlan.toUri(ip.getVlanTag())); - nic.setBroadcastType(BroadcastDomainType.Vlan); + if (network.getBroadcastDomainType() == BroadcastDomainType.Vxlan) { + nic.setIsolationUri(BroadcastDomainType.Vxlan.toUri(ip.getVlanTag())); + nic.setBroadcastUri(BroadcastDomainType.Vxlan.toUri(ip.getVlanTag())); + nic.setBroadcastType(BroadcastDomainType.Vxlan); + } else { + nic.setIsolationUri(IsolationType.Vlan.toUri(ip.getVlanTag())); + nic.setBroadcastUri(BroadcastDomainType.Vlan.toUri(ip.getVlanTag())); + nic.setBroadcastType(BroadcastDomainType.Vlan); + } nic.setFormat(AddressFormat.Ip4); nic.setReservationId(String.valueOf(ip.getVlanTag())); nic.setMacAddress(ip.getMacAddress()); diff --git a/server/src/com/cloud/network/guru/StorageNetworkGuru.java b/server/src/com/cloud/network/guru/StorageNetworkGuru.java index 2c2bd9096da..33a5569d03d 100755 --- a/server/src/com/cloud/network/guru/StorageNetworkGuru.java +++ b/server/src/com/cloud/network/guru/StorageNetworkGuru.java @@ -56,11 +56,11 @@ public class StorageNetworkGuru extends PodBasedNetworkGuru implements NetworkGu super(); } - private static final TrafficType[] _trafficTypes = {TrafficType.Storage}; + private static final TrafficType[] TrafficTypes = {TrafficType.Storage}; @Override public boolean isMyTrafficType(TrafficType type) { - for (TrafficType t : _trafficTypes) { + for (TrafficType t : TrafficTypes) { if (t == type) { return true; } @@ -70,7 +70,7 @@ public class StorageNetworkGuru extends PodBasedNetworkGuru implements NetworkGu @Override public TrafficType[] getSupportedTrafficType() { - return _trafficTypes; + return TrafficTypes; } protected boolean canHandle(NetworkOffering offering) { diff --git a/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java b/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java index aab4c6ba273..67346e14b3b 100755 --- a/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java +++ b/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java @@ -30,11 +30,6 @@ import java.util.Set; import javax.ejb.Local; import javax.inject.Inject; -import org.apache.log4j.Logger; - -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.command.user.loadbalancer.CreateLBHealthCheckPolicyCmd; import org.apache.cloudstack.api.command.user.loadbalancer.CreateLBStickinessPolicyCmd; @@ -44,14 +39,15 @@ import org.apache.cloudstack.api.command.user.loadbalancer.ListLoadBalancerRuleI import org.apache.cloudstack.api.command.user.loadbalancer.ListLoadBalancerRulesCmd; import org.apache.cloudstack.api.command.user.loadbalancer.UpdateLoadBalancerRuleCmd; import org.apache.cloudstack.api.response.ServiceResponse; +import org.apache.cloudstack.config.ApiServiceConfiguration; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.lb.ApplicationLoadBalancerRuleVO; import org.apache.cloudstack.lb.dao.ApplicationLoadBalancerRuleDao; +import org.apache.log4j.Logger; import com.cloud.agent.api.to.LoadBalancerTO; -import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationManager; import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter.NetworkType; @@ -168,6 +164,8 @@ import com.cloud.vm.UserVmVO; import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.dao.NicDao; import com.cloud.vm.dao.UserVmDao; +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; @Local(value = {LoadBalancingRulesManager.class, LoadBalancingRulesService.class}) public class LoadBalancingRulesManagerImpl extends ManagerBase implements LoadBalancingRulesManager, LoadBalancingRulesService { @@ -305,7 +303,7 @@ public class LoadBalancingRulesManagerImpl extends ManagerBase implements User user = _userDao.findByIdIncludingRemoved(autoscaleUserId); String apiKey = user.getApiKey(); String secretKey = user.getSecretKey(); - String csUrl = _configDao.getValue(Config.EndpointeUrl.key()); + String csUrl = ApiServiceConfiguration.ApiServletPath.value(); String zoneId = _dcDao.findById(autoScaleVmProfile.getZoneId()).getUuid(); String domainId = _domainDao.findById(autoScaleVmProfile.getDomainId()).getUuid(); String serviceOfferingId = _offeringsDao.findById(autoScaleVmProfile.getServiceOfferingId()).getUuid(); @@ -915,8 +913,8 @@ public class LoadBalancingRulesManagerImpl extends ManagerBase implements if (provider == null || provider.size() == 0) { return false; } - if (provider.get(0) == Provider.Netscaler || provider.get(0) == Provider.F5BigIp || - provider.get(0) == Provider.VirtualRouter) { + if (provider.get(0) == Provider.Netscaler || provider.get(0) == Provider.F5BigIp || + provider.get(0) == Provider.VirtualRouter) { return true; } return false; diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManager.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManager.java index 86145fac6b5..e838530f844 100644 --- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManager.java +++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManager.java @@ -83,7 +83,7 @@ public interface VirtualNetworkApplianceManager extends Manager, VirtualNetworkA boolean savePasswordToRouter(Network network, NicProfile nic, VirtualMachineProfile profile, List routers) throws ResourceUnavailableException; - boolean saveSSHPublicKeyToRouter(Network network, NicProfile nic, VirtualMachineProfile profile, List routers, String SSHPublicKey) + boolean saveSSHPublicKeyToRouter(Network network, NicProfile nic, VirtualMachineProfile profile, List routers, String sshPublicKey) throws ResourceUnavailableException; boolean saveUserDataToRouter(Network network, NicProfile nic, VirtualMachineProfile profile, List routers) diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java index 2e8cde3bad7..bf2516a24a9 100755 --- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java @@ -42,11 +42,10 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; -import org.apache.log4j.Logger; - import org.apache.cloudstack.api.command.admin.router.RebootRouterCmd; import org.apache.cloudstack.api.command.admin.router.UpgradeRouterCmd; import org.apache.cloudstack.api.command.admin.router.UpgradeRouterTemplateCmd; +import org.apache.cloudstack.config.ApiServiceConfiguration; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; import org.apache.cloudstack.framework.config.ConfigDepot; @@ -57,6 +56,7 @@ import org.apache.cloudstack.framework.jobs.AsyncJobManager; import org.apache.cloudstack.framework.jobs.impl.AsyncJobVO; import org.apache.cloudstack.managed.context.ManagedContextRunnable; import org.apache.cloudstack.utils.identity.ManagementServerNode; +import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.Listener; @@ -107,7 +107,6 @@ import com.cloud.alert.AlertManager; import com.cloud.api.ApiAsyncJobDispatcher; import com.cloud.api.ApiDispatcher; import com.cloud.api.ApiGsonHelper; -import com.cloud.cluster.ClusterManager; import com.cloud.cluster.ManagementServerHostVO; import com.cloud.cluster.dao.ManagementServerHostDao; import com.cloud.configuration.Config; @@ -201,8 +200,8 @@ import com.cloud.network.router.VirtualRouter.RedundantState; import com.cloud.network.router.VirtualRouter.Role; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.FirewallRule.Purpose; -import com.cloud.network.rules.LoadBalancerContainer.Scheme; import com.cloud.network.rules.FirewallRuleVO; +import com.cloud.network.rules.LoadBalancerContainer.Scheme; import com.cloud.network.rules.PortForwardingRule; import com.cloud.network.rules.RulesManager; import com.cloud.network.rules.StaticNat; @@ -400,7 +399,7 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V int _routerCpuMHz; int _retry = 2; String _instance; - String _mgmt_cidr; + String _mgmtCidr; int _routerStatsInterval = 300; int _routerCheckInterval = 30; @@ -409,7 +408,7 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V private String _dnsBasicZoneUpdates = "all"; private final Set _guestOSNeedGatewayOnNonDefaultNetwork = new HashSet(); - private boolean _disable_rp_filter = false; + private boolean _disableRpFilter = false; int _routerExtraPublicNics = 2; private int _usageAggregationRange = 1440; private String _usageTimeZone = "GMT"; @@ -533,7 +532,7 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V @Override public boolean saveSSHPublicKeyToRouter(Network network, final NicProfile nic, VirtualMachineProfile profile, List routers, - final String SSHPublicKey) throws ResourceUnavailableException { + final String sshPublicKey) throws ResourceUnavailableException { final UserVmVO vm = _userVmDao.findById(profile.getVirtualMachine().getId()); _userVmDao.loadDetails(vm); @@ -549,7 +548,7 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V if (template != null && template.getEnablePassword()) { createPasswordCommand(router, updatedProfile, nicVo, cmds); } - createVmDataCommand(router, vm, nicVo, SSHPublicKey, cmds); + createVmDataCommand(router, vm, nicVo, sshPublicKey, cmds); return sendCommandsToRouter(router, cmds); } }); @@ -665,6 +664,10 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V static final ConfigKey UseExternalDnsServers = new ConfigKey(Boolean.class, "use.external.dns", "Advanced", "false", "Bypass internal dns, use external dns1 and dns2", true, ConfigKey.Scope.Zone, null); + static final ConfigKey routerVersionCheckEnabled = new ConfigKey("Advanced", Boolean.class, "router.version.check", "true", + "If true, router minimum required version is checked before sending command", false); + + @Override public boolean configure(final String name, final Map params) throws ConfigurationException { @@ -714,7 +717,7 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V String rpValue = configs.get("network.disable.rpfilter"); if (rpValue != null && rpValue.equalsIgnoreCase("true")) { - _disable_rp_filter = true; + _disableRpFilter = true; } _dnsBasicZoneUpdates = String.valueOf(_configDao.getValue(Config.DnsBasicZoneUpdates.key())); @@ -1278,7 +1281,8 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V "Virtual router (name: " + router.getHostName() + ", id: " + router.getId() + " and router (name: " + dupRouter.getHostName() + ", id: " + router.getId() + ") are both in MASTER state! If the problem persist, restart both of routers. "; _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_DOMAIN_ROUTER, router.getDataCenterId(), router.getPodIdToDeployIn(), title, context); - _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_DOMAIN_ROUTER, dupRouter.getDataCenterId(), dupRouter.getPodIdToDeployIn(), title, context); + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_DOMAIN_ROUTER, dupRouter.getDataCenterId(), dupRouter.getPodIdToDeployIn(), title, + context); s_logger.warn(context); } else { networkRouterMaps.put(routerGuestNtwkId, router); @@ -1356,8 +1360,8 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V } } - private final int DEFAULT_PRIORITY = 100; - private final int DEFAULT_DELTA = 2; + private final static int DEFAULT_PRIORITY = 100; + private final static int DEFAULT_DELTA = 2; protected int getUpdatedPriority(Network guestNetwork, List routers, DomainRouterVO exclude) throws InsufficientVirtualNetworkCapcityException { int priority; @@ -1830,9 +1834,17 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V defaultNic.setGateway(sourceNatIp.getGateway()); defaultNic.setNetmask(sourceNatIp.getNetmask()); defaultNic.setMacAddress(sourceNatIp.getMacAddress()); - defaultNic.setBroadcastType(BroadcastDomainType.Vlan); - defaultNic.setBroadcastUri(BroadcastDomainType.Vlan.toUri(sourceNatIp.getVlanTag())); - defaultNic.setIsolationUri(IsolationType.Vlan.toUri(sourceNatIp.getVlanTag())); + // get broadcast from public network + Network pubNet = _networkDao.findById(sourceNatIp.getNetworkId()); + if (pubNet.getBroadcastDomainType() == BroadcastDomainType.Vxlan) { + defaultNic.setBroadcastType(BroadcastDomainType.Vxlan); + defaultNic.setBroadcastUri(BroadcastDomainType.Vxlan.toUri(sourceNatIp.getVlanTag())); + defaultNic.setIsolationUri(BroadcastDomainType.Vxlan.toUri(sourceNatIp.getVlanTag())); + } else { + defaultNic.setBroadcastType(BroadcastDomainType.Vlan); + defaultNic.setBroadcastUri(BroadcastDomainType.Vlan.toUri(sourceNatIp.getVlanTag())); + defaultNic.setIsolationUri(IsolationType.Vlan.toUri(sourceNatIp.getVlanTag())); + } if (hasGuestNetwork) { defaultNic.setDeviceId(2); } @@ -2043,9 +2055,9 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V } else if (nic.getTrafficType() == TrafficType.Control) { controlNic = nic; // DOMR control command is sent over management server in VMware - if (dest.getHost().getHypervisorType() == HypervisorType.VMware) { + if (dest.getHost().getHypervisorType() == HypervisorType.VMware || dest.getHost().getHypervisorType() == HypervisorType.Hyperv) { s_logger.info("Check if we need to add management server explicit route to DomR. pod cidr: " + dest.getPod().getCidrAddress() + "/" + - dest.getPod().getCidrSize() + ", pod gateway: " + dest.getPod().getGateway() + ", management host: " + ClusterManager.ManagementHostIPAdr.value()); + dest.getPod().getCidrSize() + ", pod gateway: " + dest.getPod().getGateway() + ", management host: " + ApiServiceConfiguration.ManagementHostIPAdr.value()); if (s_logger.isInfoEnabled()) { s_logger.info("Add management server explicit route to DomR."); @@ -2053,9 +2065,9 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V // always add management explicit route, for basic networking setup, DomR may have two interfaces while both // are on the same subnet - _mgmt_cidr = _configDao.getValue(Config.ManagementNetwork.key()); - if (NetUtils.isValidCIDR(_mgmt_cidr)) { - buf.append(" mgmtcidr=").append(_mgmt_cidr); + _mgmtCidr = _configDao.getValue(Config.ManagementNetwork.key()); + if (NetUtils.isValidCIDR(_mgmtCidr)) { + buf.append(" mgmtcidr=").append(_mgmtCidr); buf.append(" localgw=").append(dest.getPod().getGateway()); } @@ -2081,28 +2093,28 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V String rpValue = _configDao.getValue(Config.NetworkRouterRpFilter.key()); if (rpValue != null && rpValue.equalsIgnoreCase("true")) { - _disable_rp_filter = true; + _disableRpFilter = true; } else { - _disable_rp_filter = false; + _disableRpFilter = false; } String rpFilter = " "; String type = null; if (router.getVpcId() != null) { type = "vpcrouter"; - if (_disable_rp_filter) { + if (_disableRpFilter) { rpFilter = " disable_rp_filter=true"; } } else if (!publicNetwork) { type = "dhcpsrvr"; } else { type = "router"; - if (_disable_rp_filter) { + if (_disableRpFilter) { rpFilter = " disable_rp_filter=true"; } } - if (_disable_rp_filter) { + if (_disableRpFilter) { rpFilter = " disable_rp_filter=true"; } @@ -2113,7 +2125,7 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V buf.append(" dnssearchorder=").append(domain_suffix); } - if (profile.getHypervisorType() == HypervisorType.VMware) { + if (profile.getHypervisorType() == HypervisorType.VMware || profile.getHypervisorType() == HypervisorType.Hyperv) { buf.append(" extra_pubnics=" + _routerExtraPublicNics); } @@ -2136,7 +2148,7 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V boolean useExtDns = !dnsProvided; /* For backward compatibility */ - useExtDns = UseExternalDnsServers.valueIn(dc.getId()); + useExtDns = useExtDns || UseExternalDnsServers.valueIn(dc.getId()); if (useExtDns) { buf.append(" useextdns=true"); @@ -2570,7 +2582,16 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V protected ArrayList getPublicIpsToApply(VirtualRouter router, Provider provider, Long guestNetworkId, com.cloud.network.IpAddress.State... skipInStates) { long ownerId = router.getAccountId(); - final List userIps = _networkModel.listPublicIpsAssignedToGuestNtwk(ownerId, guestNetworkId, null); + final List userIps; + + Network guestNetwork = _networkDao.findById(guestNetworkId); + if (guestNetwork.getGuestType() == GuestType.Shared) { + // ignore the account id for the shared network + userIps = _networkModel.listPublicIpsAssignedToGuestNtwk(guestNetworkId, null); + } else { + userIps = _networkModel.listPublicIpsAssignedToGuestNtwk(ownerId, guestNetworkId, null); + } + List allPublicIps = new ArrayList(); if (userIps != null && !userIps.isEmpty()) { boolean addIp = true; @@ -2754,7 +2775,7 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V throws StorageUnavailableException, InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException { s_logger.debug("Starting router " + router); try { - _itMgr.advanceStart(router.getUuid(), params, planToDeploy); + _itMgr.advanceStart(router.getUuid(), params, planToDeploy, null); } catch (OperationTimedoutException e) { throw new ResourceUnavailableException("Starting router " + router + " failed! " + e.toString(), DataCenter.class, router.getDataCenterId()); } @@ -3511,8 +3532,9 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V } protected boolean sendCommandsToRouter(final VirtualRouter router, Commands cmds) throws AgentUnavailableException { - if (!checkRouterVersion(router)) { - throw new CloudRuntimeException("Router requires upgrade. Unable to send command to router:" + router.getId()); + if(!checkRouterVersion(router)){ + s_logger.debug("Router requires upgrade. Unable to send command to router:" + router.getId()); + throw new CloudRuntimeException("Unable to send command. Upgrade in progress. Please contact administrator."); } Answer[] answers = null; try { @@ -3571,7 +3593,8 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V String context = "Virtual router (name: " + disconnectedRouter.getInstanceName() + ", id: " + disconnectedRouter.getId() + ") would be stopped after connecting back, due to: " + reason; - _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_DOMAIN_ROUTER, disconnectedRouter.getDataCenterId(), disconnectedRouter.getPodIdToDeployIn(), title, context); + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_DOMAIN_ROUTER, disconnectedRouter.getDataCenterId(), disconnectedRouter.getPodIdToDeployIn(), title, + context); disconnectedRouter.setStopPending(true); disconnectedRouter = _routerDao.persist(disconnectedRouter); @@ -3793,6 +3816,7 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V s_logger.debug("Router " + router.getInstanceName() + " is stop pending, so not sending apply " + typeString + " commands to the backend"); continue; } + try { result = applier.execute(network, router); connectedRouters.add(router); @@ -3950,8 +3974,10 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V List nics = _nicDao.listByVmId(routerId); for (NicVO n : nics) { NetworkVO nc = _networkDao.findById(n.getNetworkId()); - if (nc.getTrafficType() == TrafficType.Control) { + if (nc != null && nc.getTrafficType() == TrafficType.Control) { routerControlIpAddress = n.getIp4Address(); + // router will have only one control ip + break; } } @@ -4088,34 +4114,39 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V } } - Long accountId = cmd.getAccountId(); - if (accountId != null) { - params++; - routers = _routerDao.listBy(accountId); - } - Long domainId = cmd.getDomainId(); - if (domainId != null) { + if(domainId != null){ + String accountName = cmd.getAccount(); + //List by account, if account Name is specified along with domainId + if(accountName != null){ + Account account = _accountMgr.getActiveAccountByName(accountName, domainId); + if(account == null){ + throw new InvalidParameterValueException("Account :"+accountName+" does not exist in domain: "+domainId); + } + routers = _routerDao.listRunningByAccountId(account.getId()); + } else { + //List by domainId, account name not specified + routers = _routerDao.listRunningByDomain(domainId); + } params++; - routers = _routerDao.listByDomain(domainId); } Long clusterId = cmd.getClusterId(); if (clusterId != null) { params++; - routers = _routerDao.listByClusterId(clusterId); + routers = _routerDao.listRunningByClusterId(clusterId); } Long podId = cmd.getPodId(); if (podId != null) { params++; - routers = _routerDao.listByPodId(podId); + routers = _routerDao.listRunningByPodId(podId); } Long zoneId = cmd.getZoneId(); if (zoneId != null) { params++; - routers = _routerDao.listByDataCenter(zoneId); + routers = _routerDao.listRunningByDataCenter(zoneId); } if (params > 1) { @@ -4131,9 +4162,16 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V //Checks if the router is at the required version // Compares MS version and router version - private boolean checkRouterVersion(VirtualRouter router) { + protected boolean checkRouterVersion(VirtualRouter router){ + if(!routerVersionCheckEnabled.value()){ + //Router version check is disabled. + return true; + } + if(router.getTemplateVersion() == null){ + return false; + } String trimmedVersion = Version.trimRouterVersion(router.getTemplateVersion()); - return (Version.compare(trimmedVersion, _minVRVersion) >= 0); + return (Version.compare(trimmedVersion, MinVRVersion) >= 0); } private List rebootRouters(List routers) { @@ -4171,6 +4209,6 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V @Override public ConfigKey[] getConfigKeys() { - return new ConfigKey[] {UseExternalDnsServers}; + return new ConfigKey[] {UseExternalDnsServers, routerVersionCheckEnabled}; } } diff --git a/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java index c3099c7754a..6e4b771073f 100644 --- a/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java @@ -789,7 +789,7 @@ public class VpcVirtualNetworkApplianceManagerImpl extends VirtualNetworkApplian // should this be a vlan id or a broadcast uri??? String vlanTag = BroadcastDomainType.getValue(network.getBroadcastUri()); String netmask = NetUtils.getCidrNetmask(network.getCidr()); - PrivateIpAddress ip = new PrivateIpAddress(ipVO, vlanTag, network.getGateway(), netmask, guestNic.getMacAddress()); + PrivateIpAddress ip = new PrivateIpAddress(ipVO, network.getBroadcastUri().toString(), network.getGateway(), netmask, guestNic.getMacAddress()); List privateIps = new ArrayList(1); privateIps.add(ip); @@ -891,6 +891,10 @@ public class VpcVirtualNetworkApplianceManagerImpl extends VirtualNetworkApplian Network network = _networkModel.getNetwork(gateway.getNetworkId()); NicProfile requested = createPrivateNicProfileForGateway(gateway); + if (!checkRouterVersion(router)) { + s_logger.warn("Router requires upgrade. Unable to send command to router: " + router.getId()); + return false; + } NicProfile guestNic = _itMgr.addVmToNetwork(router, network, requested); //setup source nat @@ -932,18 +936,23 @@ public class VpcVirtualNetworkApplianceManagerImpl extends VirtualNetworkApplian // or maybe conditional; in case of vlan ... in case of lswitch String vlanTag = BroadcastDomainType.getValue(network.getBroadcastUri()); String netmask = NetUtils.getCidrNetmask(network.getCidr()); - PrivateIpAddress ip = new PrivateIpAddress(ipVO, vlanTag, network.getGateway(), netmask, privateNic.getMacAddress()); + PrivateIpAddress ip = new PrivateIpAddress(ipVO, network.getBroadcastUri().toString(), network.getGateway(), netmask, privateNic.getMacAddress()); List privateIps = new ArrayList(1); privateIps.add(ip); Commands cmds = new Commands(Command.OnError.Stop); createVpcAssociatePrivateIPCommands(router, privateIps, cmds, add); - if (sendCommandsToRouter(router, cmds)) { - s_logger.debug("Successfully applied ip association for ip " + ip + " in vpc network " + network); - return true; - } else { - s_logger.warn("Failed to associate ip address " + ip + " in vpc network " + network); + try{ + if (sendCommandsToRouter(router, cmds)) { + s_logger.debug("Successfully applied ip association for ip " + ip + " in vpc network " + network); + return true; + } else { + s_logger.warn("Failed to associate ip address " + ip + " in vpc network " + network); + return false; + } + }catch (Exception ex) { + s_logger.warn("Failed to send " + (add ?"add ":"delete ") + " private network " + network + " commands to rotuer "); return false; } } else if (router.getState() == State.Stopped || router.getState() == State.Stopping) { diff --git a/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java b/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java index d60d2f3d8bf..d5f9405bf59 100755 --- a/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java +++ b/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java @@ -122,8 +122,7 @@ import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.VMInstanceDao; @Local(value = {SecurityGroupManager.class, SecurityGroupService.class}) -public class SecurityGroupManagerImpl extends ManagerBase implements SecurityGroupManager, SecurityGroupService, - StateListener { +public class SecurityGroupManagerImpl extends ManagerBase implements SecurityGroupManager, SecurityGroupService, StateListener { public static final Logger s_logger = Logger.getLogger(SecurityGroupManagerImpl.class); @Inject @@ -375,7 +374,7 @@ public class SecurityGroupManagerImpl extends ManagerBase implements SecurityGro protected String generateRulesetSignature(Map> ingress, Map> egress) { String ruleset = ingress.toString(); - ruleset.concat(egress.toString()); + ruleset = ruleset.concat(egress.toString()); return DigestUtils.md5Hex(ruleset); } @@ -464,8 +463,8 @@ public class SecurityGroupManagerImpl extends ManagerBase implements SecurityGro // For each group, find the security rules that allow the group for (SecurityGroupVMMapVO mapVO : groupsForVm) {// FIXME: use custom sql in the dao //Add usage events for security group assign - UsageEventUtils.publishUsageEvent(EventTypes.EVENT_SECURITY_GROUP_ASSIGN, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), mapVO.getSecurityGroupId(), - vm.getClass().getName(), vm.getUuid()); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_SECURITY_GROUP_ASSIGN, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), mapVO.getSecurityGroupId(), vm + .getClass().getName(), vm.getUuid()); List allowingRules = _securityGroupRuleDao.listByAllowedSecurityGroupId(mapVO.getSecurityGroupId()); // For each security rule that allows a group that the vm belongs to, find the group it belongs to @@ -480,8 +479,8 @@ public class SecurityGroupManagerImpl extends ManagerBase implements SecurityGro // For each group, find the security rules rules that allow the group for (SecurityGroupVMMapVO mapVO : groupsForVm) {// FIXME: use custom sql in the dao //Add usage events for security group remove - UsageEventUtils.publishUsageEvent(EventTypes.EVENT_SECURITY_GROUP_REMOVE, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), mapVO.getSecurityGroupId(), - vm.getClass().getName(), vm.getUuid()); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_SECURITY_GROUP_REMOVE, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), mapVO.getSecurityGroupId(), vm + .getClass().getName(), vm.getUuid()); List allowingRules = _securityGroupRuleDao.listByAllowedSecurityGroupId(mapVO.getSecurityGroupId()); // For each security rule that allows a group that the vm belongs to, find the group it belongs to @@ -505,27 +504,27 @@ public class SecurityGroupManagerImpl extends ManagerBase implements SecurityGro } protected SecurityGroupRulesCmd generateRulesetCmd(String vmName, String guestIp, String guestMac, Long vmId, String signature, long seqnum, - Map> ingressRules, Map> egressRules, List secIps) { + Map> ingressRules, Map> egressRules, List secIps) { List ingressResult = new ArrayList(); List egressResult = new ArrayList(); for (PortAndProto pAp : ingressRules.keySet()) { Set cidrs = ingressRules.get(pAp); if (cidrs.size() > 0) { - IpPortAndProto ipPortAndProto = - new SecurityGroupRulesCmd.IpPortAndProto(pAp.getProto(), pAp.getStartPort(), pAp.getEndPort(), cidrs.toArray(new String[cidrs.size()])); + IpPortAndProto ipPortAndProto = new SecurityGroupRulesCmd.IpPortAndProto(pAp.getProto(), pAp.getStartPort(), pAp.getEndPort(), cidrs.toArray(new String[cidrs + .size()])); ingressResult.add(ipPortAndProto); } } for (PortAndProto pAp : egressRules.keySet()) { Set cidrs = egressRules.get(pAp); if (cidrs.size() > 0) { - IpPortAndProto ipPortAndProto = - new SecurityGroupRulesCmd.IpPortAndProto(pAp.getProto(), pAp.getStartPort(), pAp.getEndPort(), cidrs.toArray(new String[cidrs.size()])); + IpPortAndProto ipPortAndProto = new SecurityGroupRulesCmd.IpPortAndProto(pAp.getProto(), pAp.getStartPort(), pAp.getEndPort(), cidrs.toArray(new String[cidrs + .size()])); egressResult.add(ipPortAndProto); } } return new SecurityGroupRulesCmd(guestIp, guestMac, vmName, vmId, signature, seqnum, ingressResult.toArray(new IpPortAndProto[ingressResult.size()]), - egressResult.toArray(new IpPortAndProto[egressResult.size()]), secIps); + egressResult.toArray(new IpPortAndProto[egressResult.size()]), secIps); } protected void handleVmStopped(VMInstanceVO vm) { @@ -590,7 +589,7 @@ public class SecurityGroupManagerImpl extends ManagerBase implements SecurityGro } private List authorizeSecurityGroupRule(final Long securityGroupId, String protocol, Integer startPort, Integer endPort, Integer icmpType, - Integer icmpCode, final List cidrList, Map groupList, final SecurityRuleType ruleType) { + Integer icmpCode, final List cidrList, Map groupList, final SecurityRuleType ruleType) { Integer startPortOrType = null; Integer endPortOrCode = null; @@ -685,19 +684,19 @@ public class SecurityGroupManagerImpl extends ManagerBase implements SecurityGro if ((group == null) || (authorizedAccountName == null)) { throw new InvalidParameterValueException( - "Invalid user group specified, fields 'group' and 'account' cannot be null, please specify groups in the form: userGroupList[0].group=XXX&userGroupList[0].account=YYY"); + "Invalid user group specified, fields 'group' and 'account' cannot be null, please specify groups in the form: userGroupList[0].group=XXX&userGroupList[0].account=YYY"); } Account authorizedAccount = _accountDao.findActiveAccount(authorizedAccountName, domainId); if (authorizedAccount == null) { - throw new InvalidParameterValueException("Nonexistent account: " + authorizedAccountName + " when trying to authorize security group rule for " + - securityGroupId + ":" + protocol + ":" + startPortOrType + ":" + endPortOrCode); + throw new InvalidParameterValueException("Nonexistent account: " + authorizedAccountName + " when trying to authorize security group rule for " + + securityGroupId + ":" + protocol + ":" + startPortOrType + ":" + endPortOrCode); } SecurityGroupVO groupVO = _securityGroupDao.findByAccountAndName(authorizedAccount.getId(), group); if (groupVO == null) { - throw new InvalidParameterValueException("Nonexistent group " + group + " for account " + authorizedAccountName + "/" + domainId + - " is given, unable to authorize security group rule."); + throw new InvalidParameterValueException("Nonexistent group " + group + " for account " + authorizedAccountName + "/" + domainId + + " is given, unable to authorize security group rule."); } // Check permissions @@ -737,21 +736,19 @@ public class SecurityGroupManagerImpl extends ManagerBase implements SecurityGro throw new ConcurrentAccessException("Failed to acquire lock on security group: " + ngId); } } - SecurityGroupRuleVO securityGroupRule = - _securityGroupRuleDao.findByProtoPortsAndAllowedGroupId(securityGroup.getId(), protocolFinal, startPortOrTypeFinal, endPortOrCodeFinal, - ngVO.getId()); + SecurityGroupRuleVO securityGroupRule = _securityGroupRuleDao.findByProtoPortsAndAllowedGroupId(securityGroup.getId(), protocolFinal, startPortOrTypeFinal, + endPortOrCodeFinal, ngVO.getId()); if ((securityGroupRule != null) && (securityGroupRule.getRuleType() == ruleType)) { continue; // rule already exists. } - securityGroupRule = - new SecurityGroupRuleVO(ruleType, securityGroup.getId(), startPortOrTypeFinal, endPortOrCodeFinal, protocolFinal, ngVO.getId()); + securityGroupRule = new SecurityGroupRuleVO(ruleType, securityGroup.getId(), startPortOrTypeFinal, endPortOrCodeFinal, protocolFinal, ngVO.getId()); securityGroupRule = _securityGroupRuleDao.persist(securityGroupRule); newRules.add(securityGroupRule); } if (cidrList != null) { for (String cidr : cidrList) { - SecurityGroupRuleVO securityGroupRule = - _securityGroupRuleDao.findByProtoPortsAndCidr(securityGroup.getId(), protocolFinal, startPortOrTypeFinal, endPortOrCodeFinal, cidr); + SecurityGroupRuleVO securityGroupRule = _securityGroupRuleDao.findByProtoPortsAndCidr(securityGroup.getId(), protocolFinal, startPortOrTypeFinal, + endPortOrCodeFinal, cidr); if ((securityGroupRule != null) && (securityGroupRule.getRuleType() == ruleType)) { continue; } @@ -893,8 +890,8 @@ public class SecurityGroupManagerImpl extends ManagerBase implements SecurityGro _serverId = ManagementServerNode.getManagementServerId(); - s_logger.info("SecurityGroupManager: num worker threads=" + _numWorkerThreads + ", time between cleanups=" + _timeBetweenCleanups + " global lock timeout=" + - _globalWorkLockTimeout); + s_logger.info("SecurityGroupManager: num worker threads=" + _numWorkerThreads + ", time between cleanups=" + _timeBetweenCleanups + " global lock timeout=" + + _globalWorkLockTimeout); createThreadPools(); return true; @@ -928,7 +925,7 @@ public class SecurityGroupManagerImpl extends ManagerBase implements SecurityGro Account accVO = _accountDao.findById(accountId); if (accVO != null) { return createSecurityGroup(SecurityGroupManager.DEFAULT_GROUP_NAME, SecurityGroupManager.DEFAULT_GROUP_DESCRIPTION, accVO.getDomainId(), accVO.getId(), - accVO.getAccountName()); + accVO.getAccountName()); } } return groupVO; @@ -1002,8 +999,7 @@ public class SecurityGroupManagerImpl extends ManagerBase implements SecurityGro nicSecIps = _nicSecIpDao.getSecondaryIpAddressesForNic(nic.getId()); } } - SecurityGroupRulesCmd cmd = - generateRulesetCmd(vm.getInstanceName(), vm.getPrivateIpAddress(), vm.getPrivateMacAddress(), vm.getId(), + SecurityGroupRulesCmd cmd = generateRulesetCmd(vm.getInstanceName(), vm.getPrivateIpAddress(), vm.getPrivateMacAddress(), vm.getId(), generateRulesetSignature(ingressRules, egressRules), seqnum, ingressRules, egressRules, nicSecIps); Commands cmds = new Commands(cmd); try { @@ -1053,8 +1049,8 @@ public class SecurityGroupManagerImpl extends ManagerBase implements SecurityGro SecurityGroupVO ngrpLock = _securityGroupDao.lockRow(securityGroup.getId(), false); if (ngrpLock == null) { s_logger.warn("Failed to acquire lock on network group id=" + securityGroup.getId() + " name=" + securityGroup.getName()); - throw new ConcurrentModificationException("Failed to acquire lock on network group id=" + securityGroup.getId() + " name=" + - securityGroup.getName()); + throw new ConcurrentModificationException("Failed to acquire lock on network group id=" + securityGroup.getId() + " name=" + + securityGroup.getName()); } if (_securityGroupVMMapDao.findByVmIdGroupId(userVmId, securityGroup.getId()) == null) { SecurityGroupVMMapVO groupVmMapVO = new SecurityGroupVMMapVO(securityGroup.getId(), userVmId); @@ -1334,17 +1330,22 @@ public class SecurityGroupManagerImpl extends ManagerBase implements SecurityGro } @Override - public boolean securityGroupRulesForVmSecIp(Long nicId, Long networkId, String secondaryIp, boolean ruleAction) { + public boolean securityGroupRulesForVmSecIp(long nicId, String secondaryIp, boolean ruleAction) { + Account caller = CallContext.current().getCallingAccount(); - String vmMac = null; - String vmName = null; - - if (secondaryIp == null || nicId == null || networkId == null) { - throw new InvalidParameterValueException("Vm nicId or networkId or secondaryIp can't be null"); + if (secondaryIp == null) { + throw new InvalidParameterValueException("Vm secondaryIp can't be null"); } NicVO nic = _nicDao.findById(nicId); - Long vmId = nic.getInstanceId(); + long vmId = nic.getInstanceId(); + UserVm vm = _userVMDao.findById(vmId); + if (vm == null || vm.getType() != VirtualMachine.Type.User) { + throw new InvalidParameterValueException("Can't configure the SG ipset, arprules rules for the non existing or non user vm"); + } + + // Verify permissions + _accountMgr.checkAccess(caller, null, false, vm); // Validate parameters List vmSgGrps = getSecurityGroupsForVm(vmId); @@ -1353,28 +1354,17 @@ public class SecurityGroupManagerImpl extends ManagerBase implements SecurityGro return true; } - Account caller = CallContext.current().getCallingAccount(); - for (SecurityGroupVO securityGroup : vmSgGrps) { Account owner = _accountMgr.getAccount(securityGroup.getAccountId()); if (owner == null) { throw new InvalidParameterValueException("Unable to find security group owner by id=" + securityGroup.getAccountId()); } - // Verify permissions - _accountMgr.checkAccess(caller, null, true, securityGroup); } - UserVm vm = _userVMDao.findById(vmId); - if (vm.getType() != VirtualMachine.Type.User) { - throw new InvalidParameterValueException("Can't configure the SG ipset, arprules rules for the non user vm"); - } - - if (vm != null) { - vmMac = vm.getPrivateMacAddress(); - vmName = vm.getInstanceName(); - if (vmMac == null || vmName == null) { - throw new InvalidParameterValueException("vm name or vm mac can't be null"); - } + String vmMac = vm.getPrivateMacAddress(); + String vmName = vm.getInstanceName(); + if (vmMac == null || vmName == null) { + throw new InvalidParameterValueException("vm name or vm mac can't be null"); } //create command for the to add ip in ipset and arptables rules diff --git a/server/src/com/cloud/network/vpc/NetworkACLManagerImpl.java b/server/src/com/cloud/network/vpc/NetworkACLManagerImpl.java index c67bc5f1672..979d407697a 100644 --- a/server/src/com/cloud/network/vpc/NetworkACLManagerImpl.java +++ b/server/src/com/cloud/network/vpc/NetworkACLManagerImpl.java @@ -81,6 +81,8 @@ public class NetworkACLManagerImpl extends ManagerBase implements NetworkACLMana ConfigurationManager _configMgr; @Inject EntityManager _entityMgr; + @Inject + VpcService _vpcSvc; @Override public NetworkACL createNetworkACL(String name, String description, long vpcId) { @@ -105,7 +107,8 @@ public class NetworkACLManagerImpl extends ManagerBase implements NetworkACLMana List vpcGateways = _vpcGatewayDao.listByAclIdAndType(aclId, VpcGateway.Type.Private); for (VpcGatewayVO vpcGateway : vpcGateways) { - PrivateGateway privateGateway = _entityMgr.findById(PrivateGateway.class, vpcGateway.getId()); + PrivateGateway privateGateway = _vpcSvc.getVpcPrivateGateway(vpcGateway.getId()); + if (!applyACLToPrivateGw(privateGateway)) { aclApplyStatus = false; s_logger.debug("failed to apply network acl item on private gateway " + privateGateway.getId() + "acl id " + aclId); @@ -374,8 +377,12 @@ public class NetworkACLManagerImpl extends ManagerBase implements NetworkACLMana throw new CloudRuntimeException("Failed to initialize vpc elements"); } - for (VpcProvider provider : vpcElements) { - return provider.applyACLItemsToPrivateGw(gateway, rules); + try{ + for (VpcProvider provider : vpcElements) { + return provider.applyACLItemsToPrivateGw(gateway, rules); + } + } catch(Exception ex) { + s_logger.debug("Failed to apply acl to private gateway " + gateway); } return false; } diff --git a/server/src/com/cloud/network/vpc/NetworkACLServiceImpl.java b/server/src/com/cloud/network/vpc/NetworkACLServiceImpl.java index 90a6394d98c..e5a59ffd153 100644 --- a/server/src/com/cloud/network/vpc/NetworkACLServiceImpl.java +++ b/server/src/com/cloud/network/vpc/NetworkACLServiceImpl.java @@ -91,6 +91,8 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ EntityManager _entityMgr; @Inject VpcDao _vpcDao; + @Inject + VpcService _vpcSvc; @Override public NetworkACL createNetworkACL(String name, String description, long vpcId) { @@ -114,6 +116,7 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ String name = cmd.getName(); Long networkId = cmd.getNetworkId(); Long vpcId = cmd.getVpcId(); + String keyword = cmd.getKeyword(); SearchBuilder sb = _networkACLDao.createSearchBuilder(); sb.and("id", sb.entity().getId(), Op.EQ); sb.and("name", sb.entity().getName(), Op.EQ); @@ -121,14 +124,22 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ Account caller = CallContext.current().getCallingAccount(); - if(networkId != null){ + if (networkId != null) { SearchBuilder network = _networkDao.createSearchBuilder(); network.and("networkId", network.entity().getId(), Op.EQ); sb.join("networkJoin", network, sb.entity().getId(), network.entity().getNetworkACLId(), JoinBuilder.JoinType.INNER); } SearchCriteria sc = sb.create(); - if (id != null) { + + if (keyword != null) { + SearchCriteria ssc = _networkACLDao.createSearchCriteria(); + ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + sc.addAnd("name", SearchCriteria.Op.SC, ssc); + } + + if(id != null){ sc.setParameters("id", id); } @@ -136,9 +147,9 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ sc.setParameters("name", name); } - if(vpcId != null){ + if (vpcId != null) { Vpc vpc = _entityMgr.findById(Vpc.class, vpcId); - if(vpc == null){ + if (vpc == null) { throw new InvalidParameterValueException("Unable to find VPC"); } _accountMgr.checkAccess(caller, null, true, vpc); @@ -156,9 +167,9 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ Long projectId = cmd.getProjectId(); boolean listAll = cmd.listAll(); Ternary domainIdRecursiveListProject = new Ternary(domainId, isRecursive, null); + ListProjectResourcesCriteria>(domainId, isRecursive, null); _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject, - listAll, false); + listAll, false); domainId = domainIdRecursiveListProject.first(); isRecursive = domainIdRecursiveListProject.second(); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); @@ -239,7 +250,7 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ } } - PrivateGateway privateGateway = _entityMgr.findById(PrivateGateway.class, privateGatewayId); + PrivateGateway privateGateway = _vpcSvc.getVpcPrivateGateway(gateway.getId()); _accountMgr.checkAccess(caller, null, true, privateGateway); return _networkAclMgr.replaceNetworkACLForPrivateGw(acl, privateGateway); @@ -487,7 +498,7 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER); } - if(aclId == null){ + if (aclId == null) { //Join with network_acl table when aclId is not specified to list acl_items within permitted VPCs SearchBuilder vpcSearch = _networkACLDao.createSearchBuilder(); vpcSearch.and("vpcId", vpcSearch.entity().getVpcId(), Op.IN); @@ -509,12 +520,12 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ sc.setParameters("trafficType", trafficType); } - if(aclId != null){ + if (aclId != null) { // Get VPC and check access NetworkACL acl = _networkACLDao.findById(aclId); - if(acl.getVpcId() != 0){ + if (acl.getVpcId() != 0) { Vpc vpc = _vpcDao.findById(acl.getVpcId()); - if(vpc == null){ + if (vpc == null) { throw new InvalidParameterValueException("Unable to find VPC associated with acl"); } _accountMgr.checkAccess(caller, null, true, vpc); @@ -523,7 +534,6 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ } else { //ToDo: Add accountId to network_acl_item table for permission check - // aclId is not specified // List permitted VPCs and filter aclItems List permittedAccounts = new ArrayList(); @@ -533,9 +543,9 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ Long projectId = cmd.getProjectId(); boolean listAll = cmd.listAll(); Ternary domainIdRecursiveListProject = new Ternary(domainId, isRecursive, null); + ListProjectResourcesCriteria>(domainId, isRecursive, null); _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject, - listAll, false); + listAll, false); domainId = domainIdRecursiveListProject.first(); isRecursive = domainIdRecursiveListProject.second(); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); @@ -578,8 +588,16 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ @Override public boolean revokeNetworkACLItem(long ruleId) { NetworkACLItemVO aclItem = _networkACLItemDao.findById(ruleId); - if (aclItem != null) { - if ((aclItem.getAclId() == NetworkACL.DEFAULT_ALLOW) || (aclItem.getAclId() == NetworkACL.DEFAULT_DENY)) { + if(aclItem != null){ + NetworkACL acl = _networkAclMgr.getNetworkACL(aclItem.getAclId()); + + Vpc vpc = _entityMgr.findById(Vpc.class, acl.getVpcId()); + + Account caller = CallContext.current().getCallingAccount(); + + _accountMgr.checkAccess(caller, null, true, vpc); + + if((aclItem.getAclId() == NetworkACL.DEFAULT_ALLOW) || (aclItem.getAclId() == NetworkACL.DEFAULT_DENY)){ throw new InvalidParameterValueException("ACL Items in default ACL cannot be deleted"); } } diff --git a/server/src/com/cloud/network/vpc/VpcManagerImpl.java b/server/src/com/cloud/network/vpc/VpcManagerImpl.java index cb3d9afc7c3..51e476f4ee6 100644 --- a/server/src/com/cloud/network/vpc/VpcManagerImpl.java +++ b/server/src/com/cloud/network/vpc/VpcManagerImpl.java @@ -424,14 +424,14 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis List map = _vpcOffSvcMapDao.listByVpcOffId(vpcOffId); for (VpcOfferingServiceMapVO instance : map) { - String service = instance.getService(); + Service service = Service.getService(instance.getService()); Set providers; providers = serviceProviderMap.get(service); if (providers == null) { providers = new HashSet(); } providers.add(Provider.getProvider(instance.getProvider())); - serviceProviderMap.put(Service.getService(service), providers); + serviceProviderMap.put(service, providers); } return serviceProviderMap; @@ -1474,7 +1474,8 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis if (!success) { if (destroyOnFailure) { s_logger.debug("Destroying private gateway " + vo + " that failed to start"); - if (deleteVpcPrivateGateway(gatewayId)) { + // calling deleting from db because on createprivategateway fail, destroyPrivateGateway is already called + if (deletePrivateGatewayFromTheDB(getVpcPrivateGateway(gatewayId))) { s_logger.warn("Successfully destroyed vpc " + vo + " that failed to start"); } else { s_logger.warn("Failed to destroy vpc " + vo + " that failed to start"); @@ -1518,6 +1519,10 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis s_logger.debug("Private gateway " + gateway + " was applied succesfully on the backend"); } else { s_logger.warn("Private gateway " + gateway + " failed to apply on the backend"); + gatewayVO.setState(VpcGateway.State.Ready); + _vpcGatewayDao.update(gatewayVO.getId(), gatewayVO); + s_logger.debug("Marked gateway " + gatewayVO + " with state " + VpcGateway.State.Ready); + return false; } } @@ -1560,7 +1565,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis User callerUser = _accountMgr.getActiveUser(CallContext.current().getCallingUserId()); Account owner = _accountMgr.getAccount(Account.ACCOUNT_ID_SYSTEM); ReservationContext context = new ReservationContextImpl(null, null, callerUser, owner); - _ntwkMgr.destroyNetwork(networkId, context); + _ntwkMgr.destroyNetwork(networkId, context, false); s_logger.debug("Deleted private network id=" + networkId); } diff --git a/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java b/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java index 9fe3ad64bcf..ef4cccdab9b 100755 --- a/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java +++ b/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java @@ -529,7 +529,7 @@ public class RemoteAccessVpnManagerImpl extends ManagerBase implements RemoteAcc } } } - } catch (ResourceUnavailableException e) { + } catch (Exception e) { s_logger.warn("Unable to apply vpn users ", e); success = false; diff --git a/server/src/com/cloud/projects/ProjectManagerImpl.java b/server/src/com/cloud/projects/ProjectManagerImpl.java index 5e7d9a96617..5a0ed1cf64c 100755 --- a/server/src/com/cloud/projects/ProjectManagerImpl.java +++ b/server/src/com/cloud/projects/ProjectManagerImpl.java @@ -624,6 +624,7 @@ public class ProjectManagerImpl extends ManagerBase implements ProjectManager { domainUuid = domain.getUuid(); } ex.addProxyObject(domainUuid, "domainId"); + throw ex; } //verify permissions diff --git a/server/src/com/cloud/resource/ResourceManagerImpl.java b/server/src/com/cloud/resource/ResourceManagerImpl.java index 7c5041b03f7..c9e2e7ace56 100755 --- a/server/src/com/cloud/resource/ResourceManagerImpl.java +++ b/server/src/com/cloud/resource/ResourceManagerImpl.java @@ -120,7 +120,6 @@ import com.cloud.org.Grouping.AllocationState; import com.cloud.org.Managed; import com.cloud.serializer.GsonHelper; import com.cloud.storage.GuestOSCategoryVO; -import com.cloud.storage.GuestOsCategory; import com.cloud.storage.StorageManager; import com.cloud.storage.StoragePool; import com.cloud.storage.StoragePoolHostVO; @@ -155,7 +154,7 @@ import com.cloud.utils.fsm.NoTransitionException; import com.cloud.utils.net.Ip; import com.cloud.utils.net.NetUtils; import com.cloud.utils.ssh.SSHCmdHelper; -import com.cloud.utils.ssh.sshException; +import com.cloud.utils.ssh.SshException; import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.VirtualMachineManager; @@ -223,8 +222,8 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, return _discoverers; } - public void setDiscoverers(List _discoverers) { - this._discoverers = _discoverers; + public void setDiscoverers(List discoverers) { + _discoverers = discoverers; } @Inject @@ -1233,6 +1232,26 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, } } + @Override + public boolean checkAndMaintain(final long hostId) { + boolean hostInMaintenance = false; + HostVO host = _hostDao.findById(hostId); + + try { + if (host.getType() != Host.Type.Storage) { + List vos = _vmDao.listByHostId(hostId); + List vosMigrating = _vmDao.listVmsMigratingFromHost(hostId); + if (vos.isEmpty() && vosMigrating.isEmpty()) { + resourceStateTransitTo(host, ResourceState.Event.InternalEnterMaintenance, _nodeId); + hostInMaintenance = true; + } + } + } catch (NoTransitionException e) { + s_logger.debug("Cannot transmit host " + host.getId() + "to Maintenance state", e); + } + return hostInMaintenance; + } + @Override public Host updateHost(UpdateHostCmd cmd) throws NoTransitionException { Long hostId = cmd.getId(); @@ -1255,23 +1274,29 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, if (guestOSCategoryId != null) { // Verify that the guest OS Category exists - if (guestOSCategoryId > 0) { - if (_guestOSCategoryDao.findById(guestOSCategoryId) == null) { - throw new InvalidParameterValueException("Please specify a valid guest OS category."); - } + if (!(guestOSCategoryId > 0) || _guestOSCategoryDao.findById(guestOSCategoryId) == null) { + throw new InvalidParameterValueException("Please specify a valid guest OS category."); } GuestOSCategoryVO guestOSCategory = _guestOSCategoryDao.findById(guestOSCategoryId); - Map hostDetails = _hostDetailsDao.findDetails(hostId); + DetailVO guestOSDetail = _hostDetailsDao.findDetail(hostId, "guest.os.category.id"); - if (guestOSCategory != null) { - // Save a new entry for guest.os.category.id - hostDetails.put("guest.os.category.id", String.valueOf(guestOSCategory.getId())); + if (guestOSCategory != null && !GuestOSCategoryVO.CATEGORY_NONE.equalsIgnoreCase(guestOSCategory.getName())) { + // Create/Update an entry for guest.os.category.id + if (guestOSDetail != null) { + guestOSDetail.setValue(String.valueOf(guestOSCategory.getId())); + _hostDetailsDao.update(guestOSDetail.getId(), guestOSDetail); + } else { + Map detail = new HashMap(); + detail.put("guest.os.category.id", String.valueOf(guestOSCategory.getId())); + _hostDetailsDao.persist(hostId, detail); + } } else { // Delete any existing entry for guest.os.category.id - hostDetails.remove("guest.os.category.id"); + if (guestOSDetail != null) { + _hostDetailsDao.remove(guestOSDetail.getId()); + } } - _hostDetailsDao.persist(hostId, hostDetails); } List hostTags = cmd.getHostTags(); @@ -2066,7 +2091,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, try { SSHCmdHelper.sshExecuteCmdOneShot(connection, "service cloudstack-agent restart"); - } catch (sshException e) { + } catch (SshException e) { return false; } } diff --git a/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java b/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java index 6e5dce6bd3f..13c3051d861 100755 --- a/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java +++ b/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java @@ -35,8 +35,11 @@ import org.springframework.stereotype.Component; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.context.CallContext; +import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.managed.context.ManagedContextRunnable; +import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao; +import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO; import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreDao; import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO; @@ -47,7 +50,6 @@ import com.cloud.configuration.Resource.ResourceOwnerType; import com.cloud.configuration.Resource.ResourceType; import com.cloud.configuration.ResourceCount; import com.cloud.configuration.ResourceCountVO; -import com.cloud.configuration.ResourceLimit; import com.cloud.configuration.ResourceLimitVO; import com.cloud.configuration.dao.ResourceCountDao; import com.cloud.configuration.dao.ResourceLimitDao; @@ -69,6 +71,8 @@ import com.cloud.projects.dao.ProjectAccountDao; import com.cloud.projects.dao.ProjectDao; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; +import com.cloud.storage.DataStoreRole; +import com.cloud.storage.SnapshotVO; import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; import com.cloud.storage.VMTemplateVO; import com.cloud.storage.dao.SnapshotDao; @@ -150,8 +154,11 @@ public class ResourceLimitManagerImpl extends ManagerBase implements ResourceLim private TemplateDataStoreDao _vmTemplateStoreDao; @Inject private VlanDao _vlanDao; + @Inject + private SnapshotDataStoreDao _snapshotDataStoreDao; protected GenericSearchBuilder templateSizeSearch; + protected GenericSearchBuilder snapshotSizeSearch; protected SearchBuilder ResourceCountSearch; ScheduledExecutorService _rcExecutor; @@ -190,6 +197,15 @@ public class ResourceLimitManagerImpl extends ManagerBase implements ResourceLim templateSizeSearch.join("templates", join1, templateSizeSearch.entity().getTemplateId(), join1.entity().getId(), JoinBuilder.JoinType.INNER); templateSizeSearch.done(); + snapshotSizeSearch = _snapshotDataStoreDao.createSearchBuilder(SumCount.class); + snapshotSizeSearch.select("sum", Func.SUM, snapshotSizeSearch.entity().getSize()); + snapshotSizeSearch.and("state", snapshotSizeSearch.entity().getState(), Op.EQ); + snapshotSizeSearch.and("storeRole", snapshotSizeSearch.entity().getRole(), Op.EQ); + SearchBuilder join2 = _snapshotDao.createSearchBuilder(); + join2.and("accountId", join2.entity().getAccountId(), Op.EQ); + snapshotSizeSearch.join("snapshots", join2, snapshotSizeSearch.entity().getSnapshotId(), join2.entity().getId(), JoinBuilder.JoinType.INNER); + snapshotSizeSearch.done(); + _resourceCountCheckInterval = NumbersUtil.parseInt(_configDao.getValue(Config.ResourceCountCheckInterval.key()), 0); if (_resourceCountCheckInterval > 0) { _rcExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("ResourceCountChecker")); @@ -253,7 +269,8 @@ public class ResourceLimitManagerImpl extends ManagerBase implements ResourceLim long numToDecrement = (delta.length == 0) ? 1 : delta[0].longValue(); if (!updateResourceCountForAccount(accountId, type, false, numToDecrement)) { - _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_UPDATE_RESOURCE_COUNT, 0L, 0L, "Failed to decrement resource count of type " + type + " for account id=" + + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_UPDATE_RESOURCE_COUNT, 0L, 0L, "Failed to decrement resource count of type " + type + + " for account id=" + accountId, "Failed to decrement resource count of type " + type + " for account id=" + accountId + "; use updateResourceCount API to recalculate/fix the problem"); } @@ -860,7 +877,7 @@ public class ResourceLimitManagerImpl extends ManagerBase implements ResourceLim } _resourceCountDao.setResourceCount(accountId, ResourceOwnerType.Account, type, (newCount == null) ? 0 : newCount.longValue()); - if (oldCount != newCount) { + if (!Long.valueOf(oldCount).equals(newCount)) { s_logger.info("Discrepency in the resource count " + "(original count=" + oldCount + " correct count = " + newCount + ") for type " + type + " for account ID " + accountId + " is fixed during resource count recalculation."); } @@ -879,6 +896,7 @@ public class ResourceLimitManagerImpl extends ManagerBase implements ResourceLim join1.and("accountId", join1.entity().getAccountId(), Op.EQ); join1.and("type", join1.entity().getType(), Op.EQ); join1.and("state", join1.entity().getState(), SearchCriteria.Op.NIN); + join1.and("displayVm", join1.entity().isDisplayVm(), Op.EQ); cpuSearch.join("offerings", join1, cpuSearch.entity().getId(), join1.entity().getServiceOfferingId(), JoinBuilder.JoinType.INNER); cpuSearch.done(); @@ -886,6 +904,7 @@ public class ResourceLimitManagerImpl extends ManagerBase implements ResourceLim sc.setJoinParameters("offerings", "accountId", accountId); sc.setJoinParameters("offerings", "type", VirtualMachine.Type.User); sc.setJoinParameters("offerings", "state", new Object[] {State.Destroyed, State.Error, State.Expunging}); + sc.setJoinParameters("offerings", "displayVm", 1); List cpus = _serviceOfferingDao.customSearch(sc, null); if (cpus != null) { return cpus.get(0).sum; @@ -901,6 +920,7 @@ public class ResourceLimitManagerImpl extends ManagerBase implements ResourceLim join1.and("accountId", join1.entity().getAccountId(), Op.EQ); join1.and("type", join1.entity().getType(), Op.EQ); join1.and("state", join1.entity().getState(), SearchCriteria.Op.NIN); + join1.and("displayVm", join1.entity().isDisplayVm(), Op.EQ); memorySearch.join("offerings", join1, memorySearch.entity().getId(), join1.entity().getServiceOfferingId(), JoinBuilder.JoinType.INNER); memorySearch.done(); @@ -908,6 +928,7 @@ public class ResourceLimitManagerImpl extends ManagerBase implements ResourceLim sc.setJoinParameters("offerings", "accountId", accountId); sc.setJoinParameters("offerings", "type", VirtualMachine.Type.User); sc.setJoinParameters("offerings", "state", new Object[] {State.Destroyed, State.Error, State.Expunging}); + sc.setJoinParameters("offerings", "displayVm", 1); List memory = _serviceOfferingDao.customSearch(sc, null); if (memory != null) { return memory.get(0).sum; @@ -918,7 +939,7 @@ public class ResourceLimitManagerImpl extends ManagerBase implements ResourceLim public long calculateSecondaryStorageForAccount(long accountId) { long totalVolumesSize = _volumeDao.secondaryStorageUsedForAccount(accountId); - long totalSnapshotsSize = _snapshotDao.secondaryStorageUsedForAccount(accountId); + long totalSnapshotsSize = 0; long totalTemplatesSize = 0; SearchCriteria sc = templateSizeSearch.create(); @@ -930,6 +951,14 @@ public class ResourceLimitManagerImpl extends ManagerBase implements ResourceLim totalTemplatesSize = templates.get(0).sum; } + SearchCriteria sc2 = snapshotSizeSearch.create(); + sc2.setParameters("state", ObjectInDataStoreStateMachine.State.Ready); + sc2.setParameters("storeRole", DataStoreRole.Image); + sc2.setJoinParameters("snapshots", "accountId", accountId); + List snapshots = _snapshotDataStoreDao.customSearch(sc2, null); + if (snapshots != null) { + totalSnapshotsSize = snapshots.get(0).sum; + } return totalVolumesSize + totalSnapshotsSize + totalTemplatesSize; } @@ -954,14 +983,17 @@ public class ResourceLimitManagerImpl extends ManagerBase implements ResourceLim return _resourceCountDao.getResourceCount(account.getId(), ResourceOwnerType.Account, type); } + private boolean isDisplayFlagOn(Boolean displayResource){ + + // 1. If its null assume displayResource = 1 + // 2. If its not null then send true if displayResource = 1 + return (displayResource == null) || (displayResource != null && displayResource); + } + @Override public void checkResourceLimit(Account account, ResourceType type, Boolean displayResource, long... count) throws ResourceAllocationException { - // By default its always on. - // TODO boilerplate code. - boolean displayflag = (displayResource == null) || (displayResource != null && displayResource); - - if(displayflag){ + if (isDisplayFlagOn(displayResource)) { checkResourceLimit(account, type, count); } } @@ -969,9 +1001,7 @@ public class ResourceLimitManagerImpl extends ManagerBase implements ResourceLim @Override public void incrementResourceCount(long accountId, ResourceType type, Boolean displayResource, Long... delta) { - // 1. If its null assume displayResource = 1 - // 2. If its not null then increment if displayResource = 1 - if(displayResource == null || (displayResource != null && displayResource)){ + if (isDisplayFlagOn(displayResource)) { incrementResourceCount(accountId, type, delta); } } @@ -979,9 +1009,7 @@ public class ResourceLimitManagerImpl extends ManagerBase implements ResourceLim @Override public void decrementResourceCount(long accountId, ResourceType type, Boolean displayResource, Long... delta) { - // 1. If its null assume displayResource = 1 - // 2. If its not null then decrement if displayResource = 1 - if(displayResource == null || (displayResource != null && displayResource)){ + if (isDisplayFlagOn(displayResource)) { decrementResourceCount(accountId, type, delta); } } @@ -990,13 +1018,13 @@ public class ResourceLimitManagerImpl extends ManagerBase implements ResourceLim public void changeResourceCount(long accountId, ResourceType type, Boolean displayResource, Long... delta) { // meaning that the display flag is not changed so neither increment or decrement - if(displayResource == null) return; + if (displayResource == null) + return; // Increment because the display is turned on. - if(displayResource){ - // checkResourceLimit((Account)_accountDao.findById(accountId), type, delta); + if (displayResource) { incrementResourceCount(accountId, type, delta); - }else{ + } else { decrementResourceCount(accountId, type, delta); } } diff --git a/server/src/com/cloud/server/ConfigurationServerImpl.java b/server/src/com/cloud/server/ConfigurationServerImpl.java index f907831767d..cbf3728de80 100755 --- a/server/src/com/cloud/server/ConfigurationServerImpl.java +++ b/server/src/com/cloud/server/ConfigurationServerImpl.java @@ -34,6 +34,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; +import java.util.Set; import java.util.UUID; import java.util.regex.Pattern; @@ -42,6 +43,7 @@ import javax.crypto.SecretKey; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.cloudstack.config.ApiServiceConfiguration; import org.apache.cloudstack.framework.config.ConfigDepot; import org.apache.cloudstack.framework.config.ConfigDepotAdmin; import org.apache.cloudstack.framework.config.ConfigKey; @@ -51,7 +53,6 @@ import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; -import com.cloud.cluster.ClusterManager; import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.Resource; @@ -151,6 +152,7 @@ public class ConfigurationServerImpl extends ManagerBase implements Configuratio @Inject protected ConfigurationManager _configMgr; + public ConfigurationServerImpl() { setRunLevel(ComponentLifecycle.RUN_LEVEL_FRAMEWORK_BOOTSTRAP); } @@ -239,14 +241,14 @@ public class ConfigurationServerImpl extends ManagerBase implements Configuratio if (hostIpAdr != null) { Boolean devel = Boolean.valueOf(_configDao.getValue("developer")); if (devel) { - String value = _configDao.getValue(ClusterManager.ManagementHostIPAdr.key()); + String value = _configDao.getValue(ApiServiceConfiguration.ManagementHostIPAdr.key()); if (value != null && !value.equals("localhost")) { needUpdateHostIp = false; } } if (needUpdateHostIp) { - _configDao.update(ClusterManager.ManagementHostIPAdr.key(), ClusterManager.ManagementHostIPAdr.category(), hostIpAdr); + _configDepot.createOrUpdateConfigObject(ApiServiceConfiguration.class.getSimpleName(), ApiServiceConfiguration.ManagementHostIPAdr, hostIpAdr); s_logger.debug("ConfigurationServer saved \"" + hostIpAdr + "\" as host."); } } @@ -283,7 +285,7 @@ public class ConfigurationServerImpl extends ManagerBase implements Configuratio long startIPLong = NetUtils.ip2Long(startIp); long endIPLong = NetUtils.ip2Long(endIp); config.savePublicIPRange(TransactionLegacy.currentTxn(), startIPLong, endIPLong, vlan.getDataCenterId(), vlan.getId(), vlan.getNetworkId(), - vlan.getPhysicalNetworkId()); + vlan.getPhysicalNetworkId()); } }); @@ -370,16 +372,16 @@ public class ConfigurationServerImpl extends ManagerBase implements Configuratio if (resouce == null) continue; if (resouce.equalsIgnoreCase("com.cloud.hypervisor.xen.resource.XenServer56Resource") || - resouce.equalsIgnoreCase("com.cloud.hypervisor.xen.resource.XenServer56FP1Resource") || - resouce.equalsIgnoreCase("com.cloud.hypervisor.xen.resource.XenServer56SP2Resource") || - resouce.equalsIgnoreCase("com.cloud.hypervisor.xen.resource.XenServer600Resource") || - resouce.equalsIgnoreCase("com.cloud.hypervisor.xen.resource.XenServer602Resource")) { + resouce.equalsIgnoreCase("com.cloud.hypervisor.xen.resource.XenServer56FP1Resource") || + resouce.equalsIgnoreCase("com.cloud.hypervisor.xen.resource.XenServer56SP2Resource") || + resouce.equalsIgnoreCase("com.cloud.hypervisor.xen.resource.XenServer600Resource") || + resouce.equalsIgnoreCase("com.cloud.hypervisor.xen.resource.XenServer602Resource")) { pvdriverversion = "xenserver56"; break; } } _configDao.getValueAndInitIfNotExist(Config.XenPVdriverVersion.key(), Config.XenPVdriverVersion.getCategory(), pvdriverversion, - Config.XenPVdriverVersion.getDescription()); + Config.XenPVdriverVersion.getDescription()); sql = "select id from vm_template where hypervisor_type='XenServer' and format!='ISO' and removed is null"; pstmt = txn.prepareAutoCloseStatement(sql); rs2 = pstmt.executeQuery(); @@ -455,8 +457,8 @@ public class ConfigurationServerImpl extends ManagerBase implements Configuratio } // insert system user insertSql = - "INSERT INTO `cloud`.`user` (id, uuid, username, password, account_id, firstname, lastname, created, user.default)" - + " VALUES (1, UUID(), 'system', RAND(), 1, 'system', 'cloud', now(), 1)"; + "INSERT INTO `cloud`.`user` (id, uuid, username, password, account_id, firstname, lastname, created, user.default)" + + " VALUES (1, UUID(), 'system', RAND(), 1, 'system', 'cloud', now(), 1)"; txn = TransactionLegacy.currentTxn(); try { PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql); @@ -473,7 +475,7 @@ public class ConfigurationServerImpl extends ManagerBase implements Configuratio // create an account for the admin user first insertSql = - "INSERT INTO `cloud`.`account` (id, uuid, account_name, type, domain_id, account.default) VALUES (" + id + ", UUID(), '" + username + "', '1', '1', 1)"; + "INSERT INTO `cloud`.`account` (id, uuid, account_name, type, domain_id, account.default) VALUES (" + id + ", UUID(), '" + username + "', '1', '1', 1)"; txn = TransactionLegacy.currentTxn(); try { PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql); @@ -483,7 +485,7 @@ public class ConfigurationServerImpl extends ManagerBase implements Configuratio // now insert the user insertSql = - "INSERT INTO `cloud`.`user` (id, uuid, username, password, account_id, firstname, lastname, created, state, user.default) " + "VALUES (" + id + + "INSERT INTO `cloud`.`user` (id, uuid, username, password, account_id, firstname, lastname, created, state, user.default) " + "VALUES (" + id + ", UUID(), '" + username + "', RAND(), 2, '" + firstname + "','" + lastname + "',now(), 'disabled', 1)"; txn = TransactionLegacy.currentTxn(); @@ -511,11 +513,11 @@ public class ConfigurationServerImpl extends ManagerBase implements Configuratio // save default security group if (tableName.equals("security_group")) { insertSql = - "INSERT INTO " + tableName + " (uuid, name, description, account_id, domain_id) " + "VALUES (UUID(), 'default', 'Default Security Group', 2, 1)"; + "INSERT INTO " + tableName + " (uuid, name, description, account_id, domain_id) " + "VALUES (UUID(), 'default', 'Default Security Group', 2, 1)"; } else { insertSql = - "INSERT INTO " + tableName + " (name, description, account_id, domain_id, account_name) " + - "VALUES ('default', 'Default Security Group', 2, 1, 'admin')"; + "INSERT INTO " + tableName + " (name, description, account_id, domain_id, account_name) " + + "VALUES ('default', 'Default Security Group', 2, 1, 'admin')"; } txn = TransactionLegacy.currentTxn(); @@ -618,8 +620,8 @@ public class ConfigurationServerImpl extends ManagerBase implements Configuratio } String base64Keystore = getBase64Keystore(keystorePath); ConfigurationVO configVO = - new ConfigurationVO("Hidden", "DEFAULT", "management-server", "ssl.keystore", DBEncryptionUtil.encrypt(base64Keystore), - "SSL Keystore for the management servers"); + new ConfigurationVO("Hidden", "DEFAULT", "management-server", "ssl.keystore", DBEncryptionUtil.encrypt(base64Keystore), + "SSL Keystore for the management servers"); _configDao.persist(configVO); s_logger.info("Stored SSL keystore to database."); } else if (null != keystoreFile && keystoreFile.exists()) { // and dbExisted @@ -675,9 +677,9 @@ public class ConfigurationServerImpl extends ManagerBase implements Configuratio try { String rpassword = PasswordGenerator.generatePresharedKey(8); String wSql = - "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " + - "VALUES ('Secure','DEFAULT', 'management-server','system.vm.password', '" + DBEncryptionUtil.encrypt(rpassword) + - "','randmon password generated each management server starts for system vm')"; + "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " + + "VALUES ('Secure','DEFAULT', 'management-server','system.vm.password', '" + DBEncryptionUtil.encrypt(rpassword) + + "','randmon password generated each management server starts for system vm')"; PreparedStatement stmt = txn.prepareAutoCloseStatement(wSql); stmt.executeUpdate(wSql); s_logger.info("Updated systemvm password in database"); @@ -752,13 +754,13 @@ public class ConfigurationServerImpl extends ManagerBase implements Configuratio String publicKey = new String(arr2).trim(); String insertSql1 = - "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " + - "VALUES ('Hidden','DEFAULT', 'management-server','ssh.privatekey', '" + DBEncryptionUtil.encrypt(privateKey) + - "','Private key for the entire CloudStack')"; + "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " + + "VALUES ('Hidden','DEFAULT', 'management-server','ssh.privatekey', '" + DBEncryptionUtil.encrypt(privateKey) + + "','Private key for the entire CloudStack')"; String insertSql2 = - "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " + - "VALUES ('Hidden','DEFAULT', 'management-server','ssh.publickey', '" + DBEncryptionUtil.encrypt(publicKey) + - "','Public key for the entire CloudStack')"; + "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " + + "VALUES ('Hidden','DEFAULT', 'management-server','ssh.publickey', '" + DBEncryptionUtil.encrypt(publicKey) + + "','Public key for the entire CloudStack')"; TransactionLegacy txn = TransactionLegacy.currentTxn(); try { @@ -801,7 +803,7 @@ public class ConfigurationServerImpl extends ManagerBase implements Configuratio public List getConfigListByScope(String scope, Long resourceId) { // Getting the list of parameters defined at the scope - List> configList = _configDepot.getConfigListByScope(scope); + Set> configList = _configDepot.getConfigListByScope(scope); List configVOList = new ArrayList(); for (ConfigKey param : configList) { ConfigurationVO configVo = _configDao.findByName(param.toString()); @@ -891,9 +893,9 @@ public class ConfigurationServerImpl extends ManagerBase implements Configuratio String password = PasswordGenerator.generateRandomPassword(12); String insertSql1 = - "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " + - "VALUES ('Hidden','DEFAULT', 'management-server','secstorage.copy.password', '" + DBEncryptionUtil.encrypt(password) + - "','Password used to authenticate zone-to-zone template copy requests')"; + "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " + + "VALUES ('Hidden','DEFAULT', 'management-server','secstorage.copy.password', '" + DBEncryptionUtil.encrypt(password) + + "','Password used to authenticate zone-to-zone template copy requests')"; TransactionLegacy txn = TransactionLegacy.currentTxn(); try { @@ -924,7 +926,7 @@ public class ConfigurationServerImpl extends ManagerBase implements Configuratio @DB protected HostPodVO createPod(long userId, String podName, final long zoneId, String gateway, String cidr, final String startIp, String endIp) - throws InternalErrorException { + throws InternalErrorException { String[] cidrPair = cidr.split("\\/"); String cidrAddress = cidrPair[0]; int cidrSize = Integer.parseInt(cidrPair[1]); @@ -983,7 +985,7 @@ public class ConfigurationServerImpl extends ManagerBase implements Configuratio } private DiskOfferingVO createdefaultDiskOffering(Long domainId, String name, String description, int numGibibytes, String tags, boolean isCustomized, - boolean isSystemUse) { + boolean isSystemUse) { long diskSize = numGibibytes; diskSize = diskSize * 1024 * 1024 * 1024; tags = cleanupTags(tags); @@ -996,10 +998,10 @@ public class ConfigurationServerImpl extends ManagerBase implements Configuratio } private ServiceOfferingVO createServiceOffering(long userId, String name, int cpu, int ramSize, int speed, String displayText, boolean localStorageRequired, - boolean offerHA, String tags) { + boolean offerHA, String tags) { tags = cleanupTags(tags); ServiceOfferingVO offering = - new ServiceOfferingVO(name, cpu, ramSize, speed, null, null, offerHA, displayText, localStorageRequired, false, tags, false, null, false); + new ServiceOfferingVO(name, cpu, ramSize, speed, null, null, offerHA, displayText, localStorageRequired, false, tags, false, null, false); offering.setUniqueName("Cloud.Com-" + name); offering = _serviceOfferingDao.persistSystemServiceOffering(offering); return offering; @@ -1074,87 +1076,87 @@ public class ConfigurationServerImpl extends ManagerBase implements Configuratio public void doInTransactionWithoutResult(TransactionStatus status) { // Offering #1 NetworkOfferingVO defaultSharedSGNetworkOffering = - new NetworkOfferingVO(NetworkOffering.DefaultSharedNetworkOfferingWithSGService, "Offering for Shared Security group enabled networks", - TrafficType.Guest, false, true, null, null, true, Availability.Optional, null, Network.GuestType.Shared, true, true, false, false, false); + new NetworkOfferingVO(NetworkOffering.DefaultSharedNetworkOfferingWithSGService, "Offering for Shared Security group enabled networks", + TrafficType.Guest, false, true, null, null, true, Availability.Optional, null, Network.GuestType.Shared, true, true, false, false, false); defaultSharedSGNetworkOffering.setState(NetworkOffering.State.Enabled); defaultSharedSGNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultSharedSGNetworkOffering); for (Service service : defaultSharedSGNetworkOfferingProviders.keySet()) { NetworkOfferingServiceMapVO offService = - new NetworkOfferingServiceMapVO(defaultSharedSGNetworkOffering.getId(), service, defaultSharedSGNetworkOfferingProviders.get(service)); + new NetworkOfferingServiceMapVO(defaultSharedSGNetworkOffering.getId(), service, defaultSharedSGNetworkOfferingProviders.get(service)); _ntwkOfferingServiceMapDao.persist(offService); s_logger.trace("Added service for the network offering: " + offService); } // Offering #2 NetworkOfferingVO defaultSharedNetworkOffering = - new NetworkOfferingVO(NetworkOffering.DefaultSharedNetworkOffering, "Offering for Shared networks", TrafficType.Guest, false, true, null, null, true, - Availability.Optional, null, Network.GuestType.Shared, true, true, false, false, false); + new NetworkOfferingVO(NetworkOffering.DefaultSharedNetworkOffering, "Offering for Shared networks", TrafficType.Guest, false, true, null, null, true, + Availability.Optional, null, Network.GuestType.Shared, true, true, false, false, false); defaultSharedNetworkOffering.setState(NetworkOffering.State.Enabled); defaultSharedNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultSharedNetworkOffering); for (Service service : defaultSharedNetworkOfferingProviders.keySet()) { NetworkOfferingServiceMapVO offService = - new NetworkOfferingServiceMapVO(defaultSharedNetworkOffering.getId(), service, defaultSharedNetworkOfferingProviders.get(service)); + new NetworkOfferingServiceMapVO(defaultSharedNetworkOffering.getId(), service, defaultSharedNetworkOfferingProviders.get(service)); _ntwkOfferingServiceMapDao.persist(offService); s_logger.trace("Added service for the network offering: " + offService); } // Offering #3 NetworkOfferingVO defaultIsolatedSourceNatEnabledNetworkOffering = - new NetworkOfferingVO(NetworkOffering.DefaultIsolatedNetworkOfferingWithSourceNatService, - "Offering for Isolated networks with Source Nat service enabled", TrafficType.Guest, false, false, null, null, true, Availability.Required, null, - Network.GuestType.Isolated, true, false, false, false, true); + new NetworkOfferingVO(NetworkOffering.DefaultIsolatedNetworkOfferingWithSourceNatService, + "Offering for Isolated networks with Source Nat service enabled", TrafficType.Guest, false, false, null, null, true, Availability.Required, null, + Network.GuestType.Isolated, true, false, false, false, true); defaultIsolatedSourceNatEnabledNetworkOffering.setState(NetworkOffering.State.Enabled); defaultIsolatedSourceNatEnabledNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultIsolatedSourceNatEnabledNetworkOffering); for (Service service : defaultIsolatedSourceNatEnabledNetworkOfferingProviders.keySet()) { NetworkOfferingServiceMapVO offService = - new NetworkOfferingServiceMapVO(defaultIsolatedSourceNatEnabledNetworkOffering.getId(), service, - defaultIsolatedSourceNatEnabledNetworkOfferingProviders.get(service)); + new NetworkOfferingServiceMapVO(defaultIsolatedSourceNatEnabledNetworkOffering.getId(), service, + defaultIsolatedSourceNatEnabledNetworkOfferingProviders.get(service)); _ntwkOfferingServiceMapDao.persist(offService); s_logger.trace("Added service for the network offering: " + offService); } // Offering #4 NetworkOfferingVO defaultIsolatedEnabledNetworkOffering = - new NetworkOfferingVO(NetworkOffering.DefaultIsolatedNetworkOffering, "Offering for Isolated networks with no Source Nat service", TrafficType.Guest, - false, true, null, null, true, Availability.Optional, null, Network.GuestType.Isolated, true, true, false, false, false); + new NetworkOfferingVO(NetworkOffering.DefaultIsolatedNetworkOffering, "Offering for Isolated networks with no Source Nat service", TrafficType.Guest, + false, true, null, null, true, Availability.Optional, null, Network.GuestType.Isolated, true, true, false, false, false); defaultIsolatedEnabledNetworkOffering.setState(NetworkOffering.State.Enabled); defaultIsolatedEnabledNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultIsolatedEnabledNetworkOffering); for (Service service : defaultIsolatedNetworkOfferingProviders.keySet()) { NetworkOfferingServiceMapVO offService = - new NetworkOfferingServiceMapVO(defaultIsolatedEnabledNetworkOffering.getId(), service, defaultIsolatedNetworkOfferingProviders.get(service)); + new NetworkOfferingServiceMapVO(defaultIsolatedEnabledNetworkOffering.getId(), service, defaultIsolatedNetworkOfferingProviders.get(service)); _ntwkOfferingServiceMapDao.persist(offService); s_logger.trace("Added service for the network offering: " + offService); } // Offering #5 NetworkOfferingVO defaultNetscalerNetworkOffering = - new NetworkOfferingVO(NetworkOffering.DefaultSharedEIPandELBNetworkOffering, - "Offering for Shared networks with Elastic IP and Elastic LB capabilities", TrafficType.Guest, false, true, null, null, true, - Availability.Optional, null, Network.GuestType.Shared, true, false, false, false, true, true, true, false, false, true, true, false, false); + new NetworkOfferingVO(NetworkOffering.DefaultSharedEIPandELBNetworkOffering, + "Offering for Shared networks with Elastic IP and Elastic LB capabilities", TrafficType.Guest, false, true, null, null, true, + Availability.Optional, null, Network.GuestType.Shared, true, false, false, false, true, true, true, false, false, true, true, false, false); defaultNetscalerNetworkOffering.setState(NetworkOffering.State.Enabled); defaultNetscalerNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultNetscalerNetworkOffering); for (Service service : netscalerServiceProviders.keySet()) { NetworkOfferingServiceMapVO offService = - new NetworkOfferingServiceMapVO(defaultNetscalerNetworkOffering.getId(), service, netscalerServiceProviders.get(service)); + new NetworkOfferingServiceMapVO(defaultNetscalerNetworkOffering.getId(), service, netscalerServiceProviders.get(service)); _ntwkOfferingServiceMapDao.persist(offService); s_logger.trace("Added service for the network offering: " + offService); } // Offering #6 NetworkOfferingVO defaultNetworkOfferingForVpcNetworks = - new NetworkOfferingVO(NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworks, - "Offering for Isolated Vpc networks with Source Nat service enabled", TrafficType.Guest, false, false, null, null, true, Availability.Optional, - null, Network.GuestType.Isolated, false, false, false, false, true); + new NetworkOfferingVO(NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworks, + "Offering for Isolated Vpc networks with Source Nat service enabled", TrafficType.Guest, false, false, null, null, true, Availability.Optional, + null, Network.GuestType.Isolated, false, false, false, false, true); defaultNetworkOfferingForVpcNetworks.setState(NetworkOffering.State.Enabled); defaultNetworkOfferingForVpcNetworks = _networkOfferingDao.persistDefaultNetworkOffering(defaultNetworkOfferingForVpcNetworks); @@ -1173,16 +1175,16 @@ public class ConfigurationServerImpl extends ManagerBase implements Configuratio for (Service service : defaultVpcNetworkOfferingProviders.keySet()) { NetworkOfferingServiceMapVO offService = - new NetworkOfferingServiceMapVO(defaultNetworkOfferingForVpcNetworks.getId(), service, defaultVpcNetworkOfferingProviders.get(service)); + new NetworkOfferingServiceMapVO(defaultNetworkOfferingForVpcNetworks.getId(), service, defaultVpcNetworkOfferingProviders.get(service)); _ntwkOfferingServiceMapDao.persist(offService); s_logger.trace("Added service for the network offering: " + offService); } // Offering #7 NetworkOfferingVO defaultNetworkOfferingForVpcNetworksNoLB = - new NetworkOfferingVO(NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworksNoLB, - "Offering for Isolated Vpc networks with Source Nat service enabled and LB service Disabled", TrafficType.Guest, false, false, null, null, true, - Availability.Optional, null, Network.GuestType.Isolated, false, false, false, false, false); + new NetworkOfferingVO(NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworksNoLB, + "Offering for Isolated Vpc networks with Source Nat service enabled and LB service Disabled", TrafficType.Guest, false, false, null, null, true, + Availability.Optional, null, Network.GuestType.Isolated, false, false, false, false, false); defaultNetworkOfferingForVpcNetworksNoLB.setState(NetworkOffering.State.Enabled); defaultNetworkOfferingForVpcNetworksNoLB = _networkOfferingDao.persistDefaultNetworkOffering(defaultNetworkOfferingForVpcNetworksNoLB); @@ -1200,16 +1202,16 @@ public class ConfigurationServerImpl extends ManagerBase implements Configuratio for (Service service : defaultVpcNetworkOfferingProvidersNoLB.keySet()) { NetworkOfferingServiceMapVO offService = - new NetworkOfferingServiceMapVO(defaultNetworkOfferingForVpcNetworksNoLB.getId(), service, defaultVpcNetworkOfferingProvidersNoLB.get(service)); + new NetworkOfferingServiceMapVO(defaultNetworkOfferingForVpcNetworksNoLB.getId(), service, defaultVpcNetworkOfferingProvidersNoLB.get(service)); _ntwkOfferingServiceMapDao.persist(offService); s_logger.trace("Added service for the network offering: " + offService); } //offering #8 - network offering with internal lb service NetworkOfferingVO internalLbOff = - new NetworkOfferingVO(NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworksWithInternalLB, - "Offering for Isolated Vpc networks with Internal LB support", TrafficType.Guest, false, false, null, null, true, Availability.Optional, null, - Network.GuestType.Isolated, false, false, false, true, false); + new NetworkOfferingVO(NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworksWithInternalLB, + "Offering for Isolated Vpc networks with Internal LB support", TrafficType.Guest, false, false, null, null, true, Availability.Optional, null, + Network.GuestType.Isolated, false, false, false, true, false); internalLbOff.setState(NetworkOffering.State.Enabled); internalLbOff = _networkOfferingDao.persistDefaultNetworkOffering(internalLbOff); @@ -1284,8 +1286,8 @@ public class ConfigurationServerImpl extends ManagerBase implements Configuratio if (broadcastDomainType != null) { NetworkVO network = - new NetworkVO(id, trafficType, mode, broadcastDomainType, networkOfferingId, domainId, accountId, related, null, null, networkDomain, - Network.GuestType.Shared, zoneId, null, null, specifyIpRanges, null); + new NetworkVO(id, trafficType, mode, broadcastDomainType, networkOfferingId, domainId, accountId, related, null, null, networkDomain, + Network.GuestType.Shared, zoneId, null, null, specifyIpRanges, null); network.setGuruName(guruNames.get(network.getTrafficType())); network.setDns1(zone.getDns1()); network.setDns2(zone.getDns2()); diff --git a/server/src/com/cloud/server/ManagementServer.java b/server/src/com/cloud/server/ManagementServer.java index 5a751e8c6c4..3b5f5ff206a 100755 --- a/server/src/com/cloud/server/ManagementServer.java +++ b/server/src/com/cloud/server/ManagementServer.java @@ -16,10 +16,7 @@ // under the License. package com.cloud.server; -import java.util.List; - -import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; - +import com.cloud.host.DetailVO; import com.cloud.host.HostVO; import com.cloud.storage.GuestOSVO; import com.cloud.utils.Pair; @@ -51,6 +48,8 @@ public interface ManagementServer extends ManagementService, PluggableService { */ HostVO getHostBy(long hostId); + DetailVO findDetail(long hostId, String name); + String getConsoleAccessUrlRoot(long vmId); GuestOSVO getGuestOs(Long guestOsId); @@ -65,14 +64,4 @@ public interface ManagementServer extends ManagementService, PluggableService { public long getMemoryOrCpuCapacityByHost(Long hostId, short capacityType); - Pair, Integer> searchForStoragePools(Criteria c); - - String getHashKey(); - - String getEncryptionKey(); - - String getEncryptionIV(); - - void resetEncryptionKeyIV(); - } diff --git a/server/src/com/cloud/server/ManagementServerImpl.java b/server/src/com/cloud/server/ManagementServerImpl.java index 2b0f0b8dc94..4bffa3f60dd 100755 --- a/server/src/com/cloud/server/ManagementServerImpl.java +++ b/server/src/com/cloud/server/ManagementServerImpl.java @@ -19,8 +19,6 @@ package com.cloud.server; import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.net.URLDecoder; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; @@ -42,11 +40,6 @@ import javax.crypto.spec.SecretKeySpec; import javax.inject.Inject; import javax.naming.ConfigurationException; -import com.cloud.service.ServiceOfferingVO; -import com.cloud.service.dao.ServiceOfferingDao; -import org.apache.commons.codec.binary.Base64; -import org.apache.log4j.Logger; - import org.apache.cloudstack.acl.ControlledEntity; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.affinity.AffinityGroupProcessor; @@ -165,7 +158,7 @@ import org.apache.cloudstack.api.command.admin.storage.ListSecondaryStagingStore import org.apache.cloudstack.api.command.admin.storage.ListStoragePoolsCmd; import org.apache.cloudstack.api.command.admin.storage.ListStorageProvidersCmd; import org.apache.cloudstack.api.command.admin.storage.PreparePrimaryStorageForMaintenanceCmd; -import org.apache.cloudstack.api.command.admin.storage.PrepareSecondaryStorageForMigrationCmd; +import org.apache.cloudstack.api.command.admin.storage.UpdateCloudToUseObjectStoreCmd; import org.apache.cloudstack.api.command.admin.storage.UpdateStoragePoolCmd; import org.apache.cloudstack.api.command.admin.swift.AddSwiftCmd; import org.apache.cloudstack.api.command.admin.swift.ListSwiftsCmd; @@ -205,6 +198,7 @@ import org.apache.cloudstack.api.command.admin.vlan.ListVlanIpRangesCmd; import org.apache.cloudstack.api.command.admin.vlan.ReleasePublicIpRangeCmd; import org.apache.cloudstack.api.command.admin.vm.AssignVMCmd; import org.apache.cloudstack.api.command.admin.vm.ExpungeVMCmd; +import org.apache.cloudstack.api.command.admin.vm.GetVMUserDataCmd; import org.apache.cloudstack.api.command.admin.vm.MigrateVMCmd; import org.apache.cloudstack.api.command.admin.vm.MigrateVirtualMachineWithVolumeCmd; import org.apache.cloudstack.api.command.admin.vm.RecoverVMCmd; @@ -443,15 +437,19 @@ import org.apache.cloudstack.engine.orchestration.service.VolumeOrchestrationSer import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; import org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory; +import org.apache.cloudstack.framework.config.ConfigDepot; import org.apache.cloudstack.framework.config.ConfigKey; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.framework.config.impl.ConfigurationVO; +import org.apache.cloudstack.framework.security.keystore.KeystoreManager; import org.apache.cloudstack.managed.context.ManagedContextRunnable; import org.apache.cloudstack.storage.datastore.db.ImageStoreDao; import org.apache.cloudstack.storage.datastore.db.ImageStoreVO; import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; import org.apache.cloudstack.utils.identity.ManagementServerNode; +import org.apache.commons.codec.binary.Base64; +import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.api.GetVncPortAnswer; @@ -518,7 +516,6 @@ import com.cloud.hypervisor.HypervisorCapabilities; import com.cloud.hypervisor.HypervisorCapabilitiesVO; import com.cloud.hypervisor.dao.HypervisorCapabilitiesDao; import com.cloud.info.ConsoleProxyInfo; -import com.cloud.keystore.KeystoreManager; import com.cloud.network.IpAddress; import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.IPAddressVO; @@ -534,6 +531,8 @@ import com.cloud.projects.ProjectManager; import com.cloud.resource.ResourceManager; import com.cloud.server.ResourceTag.ResourceObjectType; import com.cloud.server.auth.UserAuthenticator; +import com.cloud.service.ServiceOfferingVO; +import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.storage.DiskOfferingVO; import com.cloud.storage.GuestOS; import com.cloud.storage.GuestOSCategoryVO; @@ -690,7 +689,7 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe private LoadBalancerDao _loadbalancerDao; @Inject private HypervisorCapabilitiesDao _hypervisorCapabilitiesDao; - private List _hostAllocators; + private List hostAllocators; private List _storagePoolAllocators; @Inject private ResourceTagDao _resourceTagDao; @@ -714,6 +713,8 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe @Inject ConfigurationServer _configServer; @Inject + ConfigDepot _configDepot; + @Inject UserVmManager _userVmMgr; @Inject VolumeDataFactory _volFactory; @@ -748,15 +749,12 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe return _planners; } - public void setPlanners(List _planners) { - this._planners = _planners; + public void setPlanners(List planners) { + _planners = planners; } @Inject ClusterManager _clusterMgr; - private String _hashKey = null; - private String _encryptionKey = null; - private String _encryptionIV = null; @Inject protected AffinityGroupVMMapDao _affinityGroupVMMapDao; @@ -792,11 +790,11 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe } public List getHostAllocators() { - return _hostAllocators; + return hostAllocators; } - public void setHostAllocators(List _hostAllocators) { - this._hostAllocators = _hostAllocators; + public void setHostAllocators(List hostAllocators) { + this.hostAllocators = hostAllocators; } @Override @@ -856,6 +854,11 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe return _hostDao.findById(hostId); } + @Override + public DetailVO findDetail(long hostId, String name) { + return _detailsDao.findDetail(hostId, name); + } + @Override public long getId() { return MacAddress.getMacAddress().toLong(); @@ -940,15 +943,6 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe return result; } - private Date massageDate(Date date, int hourOfDay, int minute, int second) { - Calendar cal = Calendar.getInstance(); - cal.setTime(date); - cal.set(Calendar.HOUR_OF_DAY, hourOfDay); - cal.set(Calendar.MINUTE, minute); - cal.set(Calendar.SECOND, second); - return cal.getTime(); - } - @Override public List searchForClusters(long zoneId, Long startIndex, Long pageSizeVal, String hypervisorType) { Filter searchFilter = new Filter(ClusterVO.class, "id", true, startIndex, pageSizeVal); @@ -1039,8 +1033,8 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe Object resourceState = cmd.getResourceState(); Object haHosts = cmd.getHaHost(); - Pair, Integer> result = - searchForServers(cmd.getStartIndex(), cmd.getPageSizeVal(), name, type, state, zoneId, pod, cluster, id, keyword, resourceState, haHosts, null, null); + Pair, Integer> result = searchForServers(cmd.getStartIndex(), cmd.getPageSizeVal(), name, type, state, zoneId, pod, cluster, id, keyword, resourceState, + haHosts, null, null); return new Pair, Integer>(result.first(), result.second()); } @@ -1070,14 +1064,12 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe throw ex; } - if (!vm.getHypervisorType().equals(HypervisorType.XenServer) && !vm.getHypervisorType().equals(HypervisorType.VMware) - && !vm.getHypervisorType().equals(HypervisorType.KVM) && !vm.getHypervisorType().equals(HypervisorType.Ovm) - && !vm.getHypervisorType().equals(HypervisorType.Hyperv)) { + if (!vm.getHypervisorType().equals(HypervisorType.XenServer) && !vm.getHypervisorType().equals(HypervisorType.VMware) && !vm.getHypervisorType().equals(HypervisorType.KVM) + && !vm.getHypervisorType().equals(HypervisorType.Ovm) && !vm.getHypervisorType().equals(HypervisorType.Hyperv)) { if (s_logger.isDebugEnabled()) { s_logger.debug(vm + " is not XenServer/VMware/KVM/OVM/Hyperv, cannot migrate this VM."); } - throw new InvalidParameterValueException("Unsupported Hypervisor Type for VM migration, we support " + - "XenServer/VMware/KVM/Ovm/Hyperv only"); + throw new InvalidParameterValueException("Unsupported Hypervisor Type for VM migration, we support " + "XenServer/VMware/KVM/Ovm/Hyperv only"); } long srcHostId = vm.getHostId(); @@ -1096,8 +1088,7 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe boolean canMigrateWithStorage = false; if (vm.getType() == VirtualMachine.Type.User) { - HypervisorCapabilitiesVO capabilities = - _hypervisorCapabilitiesDao.findByHypervisorTypeAndVersion(srcHost.getHypervisorType(), srcHost.getHypervisorVersion()); + HypervisorCapabilitiesVO capabilities = _hypervisorCapabilitiesDao.findByHypervisorTypeAndVersion(srcHost.getHypervisorType(), srcHost.getHypervisorVersion()); if (capabilities != null) { canMigrateWithStorage = capabilities.isStorageMotionSupported(); } @@ -1127,8 +1118,7 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe DataCenterDeployment plan = null; boolean zoneWideStoragePool = false; if (canMigrateWithStorage) { - allHostsPair = - searchForServers(startIndex, pageSize, null, hostType, null, srcHost.getDataCenterId(), null, null, null, null, null, null, srcHost.getHypervisorType(), + allHostsPair = searchForServers(startIndex, pageSize, null, hostType, null, srcHost.getDataCenterId(), null, null, null, null, null, null, srcHost.getHypervisorType(), srcHost.getHypervisorVersion()); allHosts = allHostsPair.first(); allHosts.remove(srcHost); @@ -1176,7 +1166,7 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe } } - for (HostAllocator allocator : _hostAllocators) { + for (HostAllocator allocator : hostAllocators) { if (canMigrateWithStorage) { suitableHosts = allocator.allocateTo(vmProfile, plan, Host.Type.Routing, excludes, allHosts, HostAllocator.RETURN_UPTO_ALL, false); } else { @@ -1358,7 +1348,7 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe } private Pair, Integer> searchForServers(Long startIndex, Long pageSize, Object name, Object type, Object state, Object zone, Object pod, Object cluster, - Object id, Object keyword, Object resourceState, Object haHosts, Object hypervisorType, Object hypervisorVersion) { + Object id, Object keyword, Object resourceState, Object haHosts, Object hypervisorType, Object hypervisorVersion) { Filter searchFilter = new Filter(HostVO.class, "id", Boolean.TRUE, startIndex, pageSize); SearchBuilder sb = _hostDao.createSearchBuilder(); @@ -1649,15 +1639,6 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe throw new InvalidParameterValueException("cannot handle multiple IDs, provide only one ID corresponding to the scope"); } - if (scope != null && !scope.isEmpty()) { - // getting the list of parameters at requested scope - if (id == null) { - throw new InvalidParameterValueException("Invalid id null, id is needed corresponding to the scope"); - } - List configList = _configServer.getConfigListByScope(scope, id); - return new Pair, Integer>(configList, configList.size()); - } - if (keyword != null) { SearchCriteria ssc = _configDao.createSearchCriteria(); ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); @@ -1681,7 +1662,28 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe // hidden configurations are not displayed using the search API sc.addAnd("category", SearchCriteria.Op.NEQ, "Hidden"); + if (scope != null && !scope.isEmpty()) { + // getting the list of parameters at requested scope + if (id == null) { + throw new InvalidParameterValueException("Invalid id null, id is needed corresponding to the scope"); + } + sc.addAnd("scope", SearchCriteria.Op.EQ, scope); + } + Pair, Integer> result = _configDao.searchAndCount(sc, searchFilter); + + if (scope != null && !scope.isEmpty()) { + // Populate values corresponding the resource id + List configVOList = new ArrayList(); + for (ConfigurationVO param : result.first()) { + ConfigurationVO configVo = _configDao.findByName(param.getName()); + configVo.setValue(_configDepot.get(param.getName()).valueIn(id).toString()); + configVOList.add(configVo); + } + + return new Pair, Integer>(configVOList, configVOList.size()); + } + return new Pair, Integer>(result.first(), result.second()); } @@ -1823,9 +1825,8 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe throw new PermissionDeniedException("Parameter isrouting can only be specified by a Root Admin, permission denied"); } } - boolean updateNeeded = - !(name == null && displayText == null && format == null && guestOSId == null && passwordEnabled == null && bootable == null && sortKey == null && - isDynamicallyScalable == null && isRoutingTemplate == null); + boolean updateNeeded = !(name == null && displayText == null && format == null && guestOSId == null && passwordEnabled == null && bootable == null && sortKey == null + && isDynamicallyScalable == null && isRoutingTemplate == null); if (!updateNeeded) { return template; } @@ -1920,10 +1921,10 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe if (isAllocated) { Account caller = CallContext.current().getCallingAccount(); - Ternary domainIdRecursiveListProject = - new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, cmd.getId(), cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, - cmd.listAll(), false); + Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), + cmd.isRecursive(), null); + _accountMgr.buildACLSearchParameters(caller, cmd.getId(), cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), + false); domainId = domainIdRecursiveListProject.first(); isRecursive = domainIdRecursiveListProject.second(); listProjectResourcesCriteria = domainIdRecursiveListProject.third(); @@ -2103,8 +2104,7 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe return _consoleProxyMgr.startProxy(instanceId); } - private ConsoleProxyVO stopConsoleProxy(VMInstanceVO systemVm, boolean isForced) throws ResourceUnavailableException, OperationTimedoutException, - ConcurrentOperationException { + private ConsoleProxyVO stopConsoleProxy(VMInstanceVO systemVm, boolean isForced) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException { _itMgr.advanceStop(systemVm.getUuid(), isForced); return _consoleProxyDao.findById(systemVm.getId()); @@ -2188,8 +2188,8 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe boolean sameDomain = (domains.size() == 1 && domains.get(0).getId() == domainId); if (!domains.isEmpty() && !sameDomain) { - InvalidParameterValueException ex = - new InvalidParameterValueException("Failed to update specified domain id with name '" + domainName + "' since it already exists in the system"); + InvalidParameterValueException ex = new InvalidParameterValueException("Failed to update specified domain id with name '" + domainName + + "' since it already exists in the system"); ex.addProxyObject(domain.getUuid(), "domainId"); throw ex; } @@ -2199,8 +2199,8 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe if (networkDomain != null && !networkDomain.isEmpty()) { if (!NetUtils.verifyDomainName(networkDomain)) { throw new InvalidParameterValueException( - "Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " - + "and the hyphen ('-'); can't start or end with \"-\""); + "Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " + + "and the hyphen ('-'); can't start or end with \"-\""); } } @@ -2277,7 +2277,7 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe if (type != null) { sc.addAnd("type", SearchCriteria.Op.EQ, type); } - + if (name != null) { sc.addAnd("name", SearchCriteria.Op.EQ, name); } @@ -2316,20 +2316,17 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe List summedCapacities = new ArrayList(); if (zoneId == null && podId == null) {// Group by Zone, capacity type - List summedCapacitiesAtZone = - _capacityDao.listCapacitiesGroupedByLevelAndType(capacityType, zoneId, podId, clusterId, 1, cmd.getPageSizeVal()); + List summedCapacitiesAtZone = _capacityDao.listCapacitiesGroupedByLevelAndType(capacityType, zoneId, podId, clusterId, 1, cmd.getPageSizeVal()); if (summedCapacitiesAtZone != null) { summedCapacities.addAll(summedCapacitiesAtZone); } } else if (podId == null) {// Group by Pod, capacity type - List summedCapacitiesAtPod = - _capacityDao.listCapacitiesGroupedByLevelAndType(capacityType, zoneId, podId, clusterId, 2, cmd.getPageSizeVal()); + List summedCapacitiesAtPod = _capacityDao.listCapacitiesGroupedByLevelAndType(capacityType, zoneId, podId, clusterId, 2, cmd.getPageSizeVal()); if (summedCapacitiesAtPod != null) { summedCapacities.addAll(summedCapacitiesAtPod); } } else { // Group by Cluster, capacity type - List summedCapacitiesAtCluster = - _capacityDao.listCapacitiesGroupedByLevelAndType(capacityType, zoneId, podId, clusterId, 3, cmd.getPageSizeVal()); + List summedCapacitiesAtCluster = _capacityDao.listCapacitiesGroupedByLevelAndType(capacityType, zoneId, podId, clusterId, 3, cmd.getPageSizeVal()); if (summedCapacitiesAtCluster != null) { summedCapacities.addAll(summedCapacitiesAtCluster); } @@ -2364,8 +2361,7 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe summedCapacities = summedCapacities.subList(0, summedCapacities.size() < cmd.getPageSizeVal() ? summedCapacities.size() : pageSize); for (SummedCapacity summedCapacity : summedCapacities) { - CapacityVO capacity = - new CapacityVO(summedCapacity.getDataCenterId(), summedCapacity.getPodId(), summedCapacity.getClusterId(), summedCapacity.getCapacityType(), + CapacityVO capacity = new CapacityVO(summedCapacity.getDataCenterId(), summedCapacity.getPodId(), summedCapacity.getClusterId(), summedCapacity.getCapacityType(), summedCapacity.getPercentUsed()); capacity.setUsedCapacity(summedCapacity.getUsedCapacity() + summedCapacity.getReservedCapacity()); capacity.setTotalCapacity(summedCapacity.getTotalCapacity()); @@ -2388,9 +2384,8 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe } else { capacity.setUsedPercentage(0); } - SummedCapacity summedCapacity = - new SummedCapacity(capacity.getUsedCapacity(), capacity.getTotalCapacity(), capacity.getUsedPercentage(), capacity.getCapacityType(), - capacity.getDataCenterId(), capacity.getPodId(), capacity.getClusterId()); + SummedCapacity summedCapacity = new SummedCapacity(capacity.getUsedCapacity(), capacity.getTotalCapacity(), capacity.getUsedPercentage(), + capacity.getCapacityType(), capacity.getDataCenterId(), capacity.getPodId(), capacity.getClusterId()); list.add(summedCapacity); } else { List dcList = _dcDao.listEnabledZones(); @@ -2401,9 +2396,8 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe } else { capacity.setUsedPercentage(0); } - SummedCapacity summedCapacity = - new SummedCapacity(capacity.getUsedCapacity(), capacity.getTotalCapacity(), capacity.getUsedPercentage(), capacity.getCapacityType(), - capacity.getDataCenterId(), capacity.getPodId(), capacity.getClusterId()); + SummedCapacity summedCapacity = new SummedCapacity(capacity.getUsedCapacity(), capacity.getTotalCapacity(), capacity.getUsedPercentage(), + capacity.getCapacityType(), capacity.getDataCenterId(), capacity.getPodId(), capacity.getClusterId()); list.add(summedCapacity); }// End of for } @@ -2430,8 +2424,7 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe List capacities = new ArrayList(); for (SummedCapacity summedCapacity : summedCapacities) { - CapacityVO capacity = - new CapacityVO(null, summedCapacity.getDataCenterId(), podId, clusterId, summedCapacity.getUsedCapacity() + summedCapacity.getReservedCapacity(), + CapacityVO capacity = new CapacityVO(null, summedCapacity.getDataCenterId(), podId, clusterId, summedCapacity.getUsedCapacity() + summedCapacity.getReservedCapacity(), summedCapacity.getTotalCapacity(), summedCapacity.getCapacityType()); capacities.add(capacity); } @@ -2476,8 +2469,7 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe } public static boolean isAdmin(short accountType) { - return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) || - (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN)); + return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN)); } @Override @@ -2827,7 +2819,7 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe cmdList.add(CreateSecondaryStagingStoreCmd.class); cmdList.add(ListSecondaryStagingStoresCmd.class); cmdList.add(DeleteSecondaryStagingStoreCmd.class); - cmdList.add(PrepareSecondaryStorageForMigrationCmd.class); + cmdList.add(UpdateCloudToUseObjectStoreCmd.class); cmdList.add(CreateApplicationLoadBalancerCmd.class); cmdList.add(ListApplicationLoadBalancersCmd.class); cmdList.add(DeleteApplicationLoadBalancerCmd.class); @@ -2866,8 +2858,9 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe cmdList.add(AssignCertToLoadBalancerCmd.class); cmdList.add(RemoveCertFromLoadBalancerCmd.class); cmdList.add(GenerateAlertCmd.class); - cmdList.add(ListOvsElementsCmd.class); - cmdList.add(ConfigureOvsElementCmd.class); + cmdList.add(ListOvsElementsCmd.class); + cmdList.add(ConfigureOvsElementCmd.class); + cmdList.add(GetVMUserDataCmd.class); return cmdList; } @@ -2939,64 +2932,12 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe } } - @Override - public Pair, Integer> searchForStoragePools(Criteria c) { - Filter searchFilter = new Filter(StoragePoolVO.class, c.getOrderBy(), c.getAscending(), c.getOffset(), c.getLimit()); - SearchCriteria sc = _poolDao.createSearchCriteria(); - - Object id = c.getCriteria(Criteria.ID); - Object name = c.getCriteria(Criteria.NAME); - Object host = c.getCriteria(Criteria.HOST); - Object path = c.getCriteria(Criteria.PATH); - Object zone = c.getCriteria(Criteria.DATACENTERID); - Object pod = c.getCriteria(Criteria.PODID); - Object cluster = c.getCriteria(Criteria.CLUSTERID); - Object address = c.getCriteria(Criteria.ADDRESS); - Object keyword = c.getCriteria(Criteria.KEYWORD); - - if (keyword != null) { - SearchCriteria ssc = _poolDao.createSearchCriteria(); - ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("poolType", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - - sc.addAnd("name", SearchCriteria.Op.SC, ssc); - } - - if (id != null) { - sc.addAnd("id", SearchCriteria.Op.EQ, id); - } - - if (name != null) { - sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + name + "%"); - } - if (host != null) { - sc.addAnd("host", SearchCriteria.Op.EQ, host); - } - if (path != null) { - sc.addAnd("path", SearchCriteria.Op.EQ, path); - } - if (zone != null) { - sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zone); - } - if (pod != null) { - sc.addAnd("podId", SearchCriteria.Op.EQ, pod); - } - if (address != null) { - sc.addAnd("hostAddress", SearchCriteria.Op.EQ, address); - } - if (cluster != null) { - sc.addAnd("clusterId", SearchCriteria.Op.EQ, cluster); - } - - return _poolDao.searchAndCount(sc, searchFilter); - } - private SecondaryStorageVmVO startSecondaryStorageVm(long instanceId) { return _secStorageVmMgr.startSecStorageVm(instanceId); } private SecondaryStorageVmVO stopSecondaryStorageVm(VMInstanceVO systemVm, boolean isForced) throws ResourceUnavailableException, OperationTimedoutException, - ConcurrentOperationException { + ConcurrentOperationException { _itMgr.advanceStop(systemVm.getUuid(), isForced); return _secStorageVmDao.findById(systemVm.getId()); @@ -3270,7 +3211,7 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe } } - long diskOffMaxSize = Long.valueOf(_configDao.getValue(Config.CustomDiskOfferingMaxSize.key())); + long diskOffMaxSize = _volumeMgr.CustomDiskOfferingMaxSize.value(); KVMSnapshotEnabled = Boolean.parseBoolean(_configDao.getValue("KVM.snapshot.enabled")); boolean userPublicTemplateEnabled = TemplateManager.AllowPublicUserTemplates.valueIn(caller.getId()); @@ -3443,68 +3384,6 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe return result; } - @Override - public String getHashKey() { - // although we may have race conditioning here, database transaction serialization should - // give us the same key - if (_hashKey == null) { - _hashKey = - _configDao.getValueAndInitIfNotExist(Config.HashKey.key(), Config.HashKey.getCategory(), getBase64EncodedRandomKey(128), Config.HashKey.getDescription()); - } - return _hashKey; - } - - @Override - public String getEncryptionKey() { - if (_encryptionKey == null) { - _encryptionKey = - _configDao.getValueAndInitIfNotExist(Config.EncryptionKey.key(), Config.EncryptionKey.getCategory(), getBase64EncodedRandomKey(128), - Config.EncryptionKey.getDescription()); - } - return _encryptionKey; - } - - @Override - public String getEncryptionIV() { - if (_encryptionIV == null) { - _encryptionIV = - _configDao.getValueAndInitIfNotExist(Config.EncryptionIV.key(), Config.EncryptionIV.getCategory(), getBase64EncodedRandomKey(128), - Config.EncryptionIV.getDescription()); - } - return _encryptionIV; - } - - @Override - @DB - public void resetEncryptionKeyIV() { - - SearchBuilder sb = _configDao.createSearchBuilder(); - sb.and("name1", sb.entity().getName(), SearchCriteria.Op.EQ); - sb.or("name2", sb.entity().getName(), SearchCriteria.Op.EQ); - sb.done(); - - SearchCriteria sc = sb.create(); - sc.setParameters("name1", Config.EncryptionKey.key()); - sc.setParameters("name2", Config.EncryptionIV.key()); - - _configDao.expunge(sc); - _encryptionKey = null; - _encryptionIV = null; - } - - private static String getBase64EncodedRandomKey(int nBits) { - SecureRandom random; - try { - random = SecureRandom.getInstance("SHA1PRNG"); - byte[] keyBytes = new byte[nBits / 8]; - random.nextBytes(keyBytes); - return Base64.encodeBase64URLSafeString(keyBytes); - } catch (NoSuchAlgorithmException e) { - s_logger.error("Unhandled exception: ", e); - } - return null; - } - @Override public SSHKeyPair createSSHKeyPair(CreateSSHKeyPairCmd cmd) { Account caller = CallContext.current().getCallingAccount(); @@ -3540,9 +3419,8 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe SSHKeyPairVO s = _sshKeyPairDao.findByName(owner.getAccountId(), owner.getDomainId(), cmd.getName()); if (s == null) { - InvalidParameterValueException ex = - new InvalidParameterValueException("A key pair with name '" + cmd.getName() + "' does not exist for account " + owner.getAccountName() + - " in specified domain id"); + InvalidParameterValueException ex = new InvalidParameterValueException("A key pair with name '" + cmd.getName() + "' does not exist for account " + + owner.getAccountName() + " in specified domain id"); DomainVO domain = ApiDBUtils.findDomainById(owner.getDomainId()); String domainUuid = String.valueOf(owner.getDomainId()); if (domain != null) { @@ -3563,10 +3441,9 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe Account caller = CallContext.current().getCallingAccount(); List permittedAccounts = new ArrayList(); - Ternary domainIdRecursiveListProject = - new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), - false); + Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), + cmd.isRecursive(), null); + _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); Long domainId = domainIdRecursiveListProject.first(); Boolean isRecursive = domainIdRecursiveListProject.second(); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); @@ -3645,8 +3522,7 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe _userVmDao.loadDetails(vm); String password = vm.getDetail("Encrypted.Password"); if (password == null || password.equals("")) { - InvalidParameterValueException ex = - new InvalidParameterValueException("No password for VM with specified id found. " + InvalidParameterValueException ex = new InvalidParameterValueException("No password for VM with specified id found. " + "If VM is created from password enabled template and SSH keypair is assigned to VM then only password can be retrieved."); ex.addProxyObject(vm.getUuid(), "vmId"); throw ex; @@ -3724,7 +3600,7 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe @Override public Pair, Integer> listHypervisorCapabilities(Long id, HypervisorType hypervisorType, String keyword, Long startIndex, - Long pageSizeVal) { + Long pageSizeVal) { Filter searchFilter = new Filter(HypervisorCapabilitiesVO.class, "id", true, startIndex, pageSizeVal); SearchCriteria sc = _hypervisorCapabilitiesDao.createSearchCriteria(); @@ -3783,14 +3659,14 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe @Override @ActionEvent(eventType = EventTypes.EVENT_VM_UPGRADE, eventDescription = "Upgrading system VM", async = true) public VirtualMachine upgradeSystemVM(ScaleSystemVMCmd cmd) throws ResourceUnavailableException, ManagementServerException, VirtualMachineMigrationException, - ConcurrentOperationException { + ConcurrentOperationException { VMInstanceVO vmInstance = _vmInstanceDao.findById(cmd.getId()); if (vmInstance.getHypervisorType() == HypervisorType.XenServer && vmInstance.getState().equals(State.Running)) { throw new InvalidParameterValueException("Dynamic Scaling operation is not permitted for this hypervisor on system vm"); } - boolean result = _userVmMgr.upgradeVirtualMachine(cmd.getId(), cmd.getServiceOfferingId(), cmd.getCustomParameters()); - if(result){ + boolean result = _userVmMgr.upgradeVirtualMachine(cmd.getId(), cmd.getServiceOfferingId(), cmd.getDetails()); + if (result) { VirtualMachine vm = _vmInstanceDao.findById(cmd.getId()); return vm; } else { @@ -3802,11 +3678,11 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe public VirtualMachine upgradeSystemVM(UpgradeSystemVMCmd cmd) { Long systemVmId = cmd.getId(); Long serviceOfferingId = cmd.getServiceOfferingId(); - return upgradeStoppedSystemVm(systemVmId, serviceOfferingId, cmd.getCustomParameters()); + return upgradeStoppedSystemVm(systemVmId, serviceOfferingId, cmd.getDetails()); } - private VirtualMachine upgradeStoppedSystemVm(Long systemVmId, Long serviceOfferingId, Map customparameters){ + private VirtualMachine upgradeStoppedSystemVm(Long systemVmId, Long serviceOfferingId, Map customparameters) { Account caller = CallContext.current().getCallingAccount(); VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(systemVmId, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); @@ -3818,8 +3694,8 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe // Check that the specified service offering ID is valid ServiceOfferingVO newServiceOffering = _offeringDao.findById(serviceOfferingId); - ServiceOfferingVO currentServiceOffering = _offeringDao.findById(systemVmId,systemVm.getServiceOfferingId()); - if (newServiceOffering.isDynamic()){ + ServiceOfferingVO currentServiceOffering = _offeringDao.findById(systemVmId, systemVm.getServiceOfferingId()); + if (newServiceOffering.isDynamic()) { newServiceOffering.setDynamicFlag(true); _userVmMgr.validateCustomParameters(newServiceOffering, customparameters); newServiceOffering = _offeringDao.getcomputeOffering(newServiceOffering, customparameters); diff --git a/server/src/com/cloud/server/StatsCollector.java b/server/src/com/cloud/server/StatsCollector.java index 82f774fcbe6..548587cfa8e 100755 --- a/server/src/com/cloud/server/StatsCollector.java +++ b/server/src/com/cloud/server/StatsCollector.java @@ -118,52 +118,78 @@ import com.cloud.vm.dao.VMInstanceDao; @Component public class StatsCollector extends ManagerBase implements ComponentMethodInterceptable { - public static final Logger s_logger = Logger.getLogger(StatsCollector.class.getName()); + public static final Logger s_logger = Logger.getLogger(StatsCollector.class.getName()); - private static StatsCollector s_instance = null; + private static StatsCollector s_instance = null; - private ScheduledExecutorService _executor = null; - @Inject private AgentManager _agentMgr; - @Inject private UserVmManager _userVmMgr; - @Inject private HostDao _hostDao; - @Inject private UserVmDao _userVmDao; - @Inject private VolumeDao _volsDao; - @Inject private PrimaryDataStoreDao _storagePoolDao; - @Inject private ImageStoreDao _imageStoreDao; - @Inject private StorageManager _storageManager; - @Inject private StoragePoolHostDao _storagePoolHostDao; - @Inject private DataStoreManager _dataStoreMgr; - @Inject private ResourceManager _resourceMgr; - @Inject private ConfigurationDao _configDao; - @Inject private EndPointSelector _epSelector; - @Inject private VmDiskStatisticsDao _vmDiskStatsDao; - @Inject private ManagementServerHostDao _msHostDao; - @Inject private AutoScaleVmGroupDao _asGroupDao; - @Inject private AutoScaleVmGroupVmMapDao _asGroupVmDao; - @Inject private AutoScaleManager _asManager; - @Inject private VMInstanceDao _vmInstance; - @Inject private AutoScaleVmGroupPolicyMapDao _asGroupPolicyDao; - @Inject private AutoScalePolicyDao _asPolicyDao; - @Inject private AutoScalePolicyConditionMapDao _asConditionMapDao; - @Inject private ConditionDao _asConditionDao; - @Inject private CounterDao _asCounterDao; - @Inject private AutoScaleVmProfileDao _asProfileDao; - @Inject private ServiceOfferingDao _serviceOfferingDao; + private ScheduledExecutorService _executor = null; + @Inject + private AgentManager _agentMgr; + @Inject + private UserVmManager _userVmMgr; + @Inject + private HostDao _hostDao; + @Inject + private UserVmDao _userVmDao; + @Inject + private VolumeDao _volsDao; + @Inject + private PrimaryDataStoreDao _storagePoolDao; + @Inject + private ImageStoreDao _imageStoreDao; + @Inject + private StorageManager _storageManager; + @Inject + private StoragePoolHostDao _storagePoolHostDao; + @Inject + private DataStoreManager _dataStoreMgr; + @Inject + private ResourceManager _resourceMgr; + @Inject + private ConfigurationDao _configDao; + @Inject + private EndPointSelector _epSelector; + @Inject + private VmDiskStatisticsDao _vmDiskStatsDao; + @Inject + private ManagementServerHostDao _msHostDao; + @Inject + private AutoScaleVmGroupDao _asGroupDao; + @Inject + private AutoScaleVmGroupVmMapDao _asGroupVmDao; + @Inject + private AutoScaleManager _asManager; + @Inject + private VMInstanceDao _vmInstance; + @Inject + private AutoScaleVmGroupPolicyMapDao _asGroupPolicyDao; + @Inject + private AutoScalePolicyDao _asPolicyDao; + @Inject + private AutoScalePolicyConditionMapDao _asConditionMapDao; + @Inject + private ConditionDao _asConditionDao; + @Inject + private CounterDao _asCounterDao; + @Inject + private AutoScaleVmProfileDao _asProfileDao; + @Inject + private ServiceOfferingDao _serviceOfferingDao; - private ConcurrentHashMap _hostStats = new ConcurrentHashMap(); - private final ConcurrentHashMap _VmStats = new ConcurrentHashMap(); - private ConcurrentHashMap _volumeStats = new ConcurrentHashMap(); - private ConcurrentHashMap _storageStats = new ConcurrentHashMap(); - private ConcurrentHashMap _storagePoolStats = new ConcurrentHashMap(); + private ConcurrentHashMap _hostStats = new ConcurrentHashMap(); + private final ConcurrentHashMap _VmStats = new ConcurrentHashMap(); + private final ConcurrentHashMap _volumeStats = new ConcurrentHashMap(); + private ConcurrentHashMap _storageStats = new ConcurrentHashMap(); + private ConcurrentHashMap _storagePoolStats = new ConcurrentHashMap(); - long hostStatsInterval = -1L; - long hostAndVmStatsInterval = -1L; - long storageStatsInterval = -1L; - long volumeStatsInterval = -1L; - long autoScaleStatsInterval = -1L; - int vmDiskStatsInterval = 0; + long hostStatsInterval = -1L; + long hostAndVmStatsInterval = -1L; + long storageStatsInterval = -1L; + long volumeStatsInterval = -1L; + long autoScaleStatsInterval = -1L; + int vmDiskStatsInterval = 0; - private ScheduledExecutorService _diskStatsUpdateExecutor; + private ScheduledExecutorService _diskStatsUpdateExecutor; private int _usageAggregationRange = 1440; private String _usageTimeZone = "GMT"; private final long mgmtSrvrId = MacAddress.getMacAddress().toLong(); @@ -192,15 +218,15 @@ public class StatsCollector extends ManagerBase implements ComponentMethodInterc return true; } - private void init(Map configs) { - _executor = Executors.newScheduledThreadPool(4, new NamedThreadFactory("StatsCollector")); + private void init(Map configs) { + _executor = Executors.newScheduledThreadPool(4, new NamedThreadFactory("StatsCollector")); - hostStatsInterval = NumbersUtil.parseLong(configs.get("host.stats.interval"), 60000L); - hostAndVmStatsInterval = NumbersUtil.parseLong(configs.get("vm.stats.interval"), 60000L); - storageStatsInterval = NumbersUtil.parseLong(configs.get("storage.stats.interval"), 60000L); - volumeStatsInterval = NumbersUtil.parseLong(configs.get("volume.stats.interval"), -1L); - autoScaleStatsInterval = NumbersUtil.parseLong(configs.get("autoscale.stats.interval"), 60000L); - vmDiskStatsInterval = NumbersUtil.parseInt(configs.get("vm.disk.stats.interval"), 0); + hostStatsInterval = NumbersUtil.parseLong(configs.get("host.stats.interval"), 60000L); + hostAndVmStatsInterval = NumbersUtil.parseLong(configs.get("vm.stats.interval"), 60000L); + storageStatsInterval = NumbersUtil.parseLong(configs.get("storage.stats.interval"), 60000L); + volumeStatsInterval = NumbersUtil.parseLong(configs.get("volume.stats.interval"), -1L); + autoScaleStatsInterval = NumbersUtil.parseLong(configs.get("autoscale.stats.interval"), 60000L); + vmDiskStatsInterval = NumbersUtil.parseInt(configs.get("vm.disk.stats.interval"), 0); if (hostStatsInterval > 0) { _executor.scheduleWithFixedDelay(new HostCollector(), 15000L, hostStatsInterval, TimeUnit.MILLISECONDS); @@ -210,13 +236,13 @@ public class StatsCollector extends ManagerBase implements ComponentMethodInterc _executor.scheduleWithFixedDelay(new VmStatsCollector(), 15000L, hostAndVmStatsInterval, TimeUnit.MILLISECONDS); } - if (storageStatsInterval > 0) { - _executor.scheduleWithFixedDelay(new StorageCollector(), 15000L, storageStatsInterval, TimeUnit.MILLISECONDS); - } - - if (autoScaleStatsInterval > 0) { + if (storageStatsInterval > 0) { + _executor.scheduleWithFixedDelay(new StorageCollector(), 15000L, storageStatsInterval, TimeUnit.MILLISECONDS); + } + + if (autoScaleStatsInterval > 0) { _executor.scheduleWithFixedDelay(new AutoScaleMonitor(), 15000L, autoScaleStatsInterval, TimeUnit.MILLISECONDS); - } + } if (vmDiskStatsInterval > 0) { if (vmDiskStatsInterval < 300) @@ -606,300 +632,301 @@ public class StatsCollector extends ManagerBase implements ComponentMethodInterc } } _storagePoolStats = storagePoolStats; - } catch (Throwable t) { - s_logger.error("Error trying to retrieve storage stats", t); - } - } - } + } catch (Throwable t) { + s_logger.error("Error trying to retrieve storage stats", t); + } + } + } - class AutoScaleMonitor extends ManagedContextRunnable { - @Override - protected void runInContext() { - try { - if (s_logger.isDebugEnabled()) { - s_logger.debug("AutoScaling Monitor is running..."); - } - // list all AS VMGroups - List asGroups = _asGroupDao.listAll(); - for (AutoScaleVmGroupVO asGroup : asGroups) { - // check group state - if ((asGroup.getState().equals("enabled")) && (is_native(asGroup.getId()))) { - // check minimum vm of group - Integer currentVM = _asGroupVmDao.countByGroup(asGroup.getId()); - if (currentVM < asGroup.getMinMembers()) { - _asManager.doScaleUp(asGroup.getId(), asGroup.getMinMembers() - currentVM); - continue; - } - - //check interval - long now = (new Date()).getTime(); - if (asGroup.getLastInterval() != null) - if ((now - asGroup.getLastInterval().getTime()) < (long) asGroup - .getInterval()) { - continue; - } + class AutoScaleMonitor extends ManagedContextRunnable { + @Override + protected void runInContext() { + try { + if (s_logger.isDebugEnabled()) { + s_logger.debug("AutoScaling Monitor is running..."); + } + // list all AS VMGroups + List asGroups = _asGroupDao.listAll(); + for (AutoScaleVmGroupVO asGroup : asGroups) { + // check group state + if ((asGroup.getState().equals("enabled")) && (is_native(asGroup.getId()))) { + // check minimum vm of group + Integer currentVM = _asGroupVmDao.countByGroup(asGroup.getId()); + if (currentVM < asGroup.getMinMembers()) { + _asManager.doScaleUp(asGroup.getId(), asGroup.getMinMembers() - currentVM); + continue; + } - // update last_interval - asGroup.setLastInterval(new Date()); - _asGroupDao.persist(asGroup); + //check interval + long now = (new Date()).getTime(); + if (asGroup.getLastInterval() != null) + if ((now - asGroup.getLastInterval().getTime()) < asGroup + .getInterval()) { + continue; + } - // collect RRDs data for this group - if (s_logger.isDebugEnabled()) { - s_logger.debug("[AutoScale] Collecting RRDs data..."); - } - Map params = new HashMap(); - List asGroupVmVOs = _asGroupVmDao.listByGroup(asGroup.getId()); - params.put("total_vm", String.valueOf(asGroupVmVOs.size())); - for (int i = 0; i < asGroupVmVOs.size(); i++) { - long vmId = asGroupVmVOs.get(i).getInstanceId(); - VMInstanceVO vmVO = _vmInstance.findById(vmId); - //xe vm-list | grep vmname -B 1 | head -n 1 | awk -F':' '{print $2}' - params.put("vmname" + String.valueOf(i + 1), vmVO.getInstanceName()); - params.put("vmid" + String.valueOf(i + 1), String.valueOf(vmVO.getId())); + // update last_interval + asGroup.setLastInterval(new Date()); + _asGroupDao.persist(asGroup); - } - // get random hostid because all vms are in a cluster - long vmId = asGroupVmVOs.get(0).getInstanceId(); - VMInstanceVO vmVO = _vmInstance.findById(vmId); - Long receiveHost = vmVO.getHostId(); + // collect RRDs data for this group + if (s_logger.isDebugEnabled()) { + s_logger.debug("[AutoScale] Collecting RRDs data..."); + } + Map params = new HashMap(); + List asGroupVmVOs = _asGroupVmDao.listByGroup(asGroup.getId()); + params.put("total_vm", String.valueOf(asGroupVmVOs.size())); + for (int i = 0; i < asGroupVmVOs.size(); i++) { + long vmId = asGroupVmVOs.get(i).getInstanceId(); + VMInstanceVO vmVO = _vmInstance.findById(vmId); + //xe vm-list | grep vmname -B 1 | head -n 1 | awk -F':' '{print $2}' + params.put("vmname" + String.valueOf(i + 1), vmVO.getInstanceName()); + params.put("vmid" + String.valueOf(i + 1), String.valueOf(vmVO.getId())); - // setup parameters phase: duration and counter - // list pair [counter, duration] - List> lstPair = getPairofCounternameAndDuration(asGroup.getId()); - int total_counter = 0; - String[] lstCounter = new String[lstPair.size()]; - for (int i = 0; i < lstPair.size(); i++) { - Pair pair = lstPair.get(i); - String strCounterNames = pair.first(); - Integer duration = pair.second(); - - lstCounter[i] = strCounterNames.split(",")[0]; - total_counter++; - params.put("duration" + String.valueOf(total_counter), duration.toString()); - params.put("counter" + String.valueOf(total_counter), lstCounter[i]); - params.put("con" + String.valueOf(total_counter), strCounterNames.split(",")[1]); - } - params.put("total_counter", String.valueOf(total_counter)); + } + // get random hostid because all vms are in a cluster + long vmId = asGroupVmVOs.get(0).getInstanceId(); + VMInstanceVO vmVO = _vmInstance.findById(vmId); + Long receiveHost = vmVO.getHostId(); - PerformanceMonitorCommand perfMon = new PerformanceMonitorCommand(params, 20); + // setup parameters phase: duration and counter + // list pair [counter, duration] + List> lstPair = getPairofCounternameAndDuration(asGroup.getId()); + int total_counter = 0; + String[] lstCounter = new String[lstPair.size()]; + for (int i = 0; i < lstPair.size(); i++) { + Pair pair = lstPair.get(i); + String strCounterNames = pair.first(); + Integer duration = pair.second(); - try { - Answer answer = _agentMgr.send(receiveHost, perfMon); - if (answer == null || !answer.getResult()) { - s_logger.debug("Failed to send data to node !"); - } else { - String result = answer.getDetails(); - s_logger.debug("[AutoScale] RRDs collection answer: " + result); - HashMap avgCounter = new HashMap(); - - // extract data - String[] counterElements = result.split(","); - if ((counterElements != null) && (counterElements.length > 0)) { - for (String string : counterElements) { - try { - String[] counterVals = string.split(":"); - String[] counter_vm = counterVals[0].split("\\."); - - Long counterId = Long.parseLong(counter_vm[1]); - Long conditionId = Long.parseLong(params.get("con" + counter_vm[1])); - Double coVal = Double.parseDouble(counterVals[1]); + lstCounter[i] = strCounterNames.split(",")[0]; + total_counter++; + params.put("duration" + String.valueOf(total_counter), duration.toString()); + params.put("counter" + String.valueOf(total_counter), lstCounter[i]); + params.put("con" + String.valueOf(total_counter), strCounterNames.split(",")[1]); + } + params.put("total_counter", String.valueOf(total_counter)); - // Summary of all counter by counterId key - if (avgCounter.get(counterId) == null){ - /* initialize if data is not set */ - avgCounter.put(counterId, new Double(0)); - } - - String counterName = getCounternamebyCondition(conditionId.longValue()); - if (counterName == Counter.Source.memory.toString()) { - // calculate memory in percent - Long profileId = asGroup.getProfileId(); - AutoScaleVmProfileVO profileVo = _asProfileDao.findById(profileId); - ServiceOfferingVO serviceOff = _serviceOfferingDao.findById(profileVo.getServiceOfferingId()); - int maxRAM = serviceOff.getRamSize(); + PerformanceMonitorCommand perfMon = new PerformanceMonitorCommand(params, 20); - // get current RAM percent - coVal = coVal / maxRAM; - } else { - // cpu - coVal = coVal * 100; - } - - // update data entry - avgCounter.put(counterId, avgCounter.get(counterId)+ coVal); - - } catch (Exception e) { - e.printStackTrace(); - } - } + try { + Answer answer = _agentMgr.send(receiveHost, perfMon); + if (answer == null || !answer.getResult()) { + s_logger.debug("Failed to send data to node !"); + } else { + String result = answer.getDetails(); + s_logger.debug("[AutoScale] RRDs collection answer: " + result); + HashMap avgCounter = new HashMap(); - String scaleAction = getAutoscaleAction(avgCounter, asGroup.getId(), currentVM, params); - if (scaleAction != null) { - s_logger.debug("[AutoScale] Doing scale action: " + scaleAction + " for group " + asGroup.getId()); - if (scaleAction.equals("scaleup")) { - _asManager.doScaleUp(asGroup.getId(), 1); - } else { - _asManager.doScaleDown(asGroup.getId()); - } - } - } - } + // extract data + String[] counterElements = result.split(","); + if ((counterElements != null) && (counterElements.length > 0)) { + for (String string : counterElements) { + try { + String[] counterVals = string.split(":"); + String[] counter_vm = counterVals[0].split("\\."); - } catch (Exception e) { - e.printStackTrace(); - } + Long counterId = Long.parseLong(counter_vm[1]); + Long conditionId = Long.parseLong(params.get("con" + counter_vm[1])); + Double coVal = Double.parseDouble(counterVals[1]); - } - } + // Summary of all counter by counterId key + if (avgCounter.get(counterId) == null) { + /* initialize if data is not set */ + avgCounter.put(counterId, new Double(0)); + } - } catch (Throwable t) { - s_logger.error("Error trying to monitor autoscaling", t); - } + String counterName = getCounternamebyCondition(conditionId.longValue()); + if (Counter.Source.memory.toString().equals(counterName)) { + // calculate memory in percent + Long profileId = asGroup.getProfileId(); + AutoScaleVmProfileVO profileVo = _asProfileDao.findById(profileId); + ServiceOfferingVO serviceOff = _serviceOfferingDao.findById(profileVo.getServiceOfferingId()); + int maxRAM = serviceOff.getRamSize(); - } - - private boolean is_native(long groupId) { - List vos = _asGroupPolicyDao.listByVmGroupId(groupId); - for (AutoScaleVmGroupPolicyMapVO vo : vos) { - List ConditionPolicies = _asConditionMapDao.findByPolicyId(vo.getPolicyId()); - for (AutoScalePolicyConditionMapVO ConditionPolicy : ConditionPolicies) { - ConditionVO condition = _asConditionDao.findById(ConditionPolicy.getConditionId()); - CounterVO counter = _asCounterDao.findById(condition.getCounterid()); - if (counter.getSource() == Counter.Source.cpu || counter.getSource() == Counter.Source.memory) - return true; - } - } - return false; - } - - private String getAutoscaleAction(HashMap avgCounter, long groupId, long currentVM, Map params) { - - List listMap = _asGroupPolicyDao.listByVmGroupId(groupId); - if ( (listMap == null) || (listMap.size() == 0) ) - return null; - for (AutoScaleVmGroupPolicyMapVO asVmgPmap : listMap) { - AutoScalePolicyVO policyVO = _asPolicyDao.findById(asVmgPmap.getPolicyId()); - if (policyVO != null) { - Integer quitetime = policyVO.getQuietTime(); - Date quitetimeDate = policyVO.getLastQuiteTime(); - long last_quitetime = 0L; - if (quitetimeDate != null) { - last_quitetime = policyVO.getLastQuiteTime().getTime(); - } - long current_time = (new Date()).getTime(); + // get current RAM percent + coVal = coVal / maxRAM; + } else { + // cpu + coVal = coVal * 100; + } - // check quite time for this policy - if ((current_time - last_quitetime) >= (long) quitetime) { + // update data entry + avgCounter.put(counterId, avgCounter.get(counterId) + coVal); - // list all condition of this policy - boolean bValid = true; - List lstConditions = getConditionsbyPolicyId(policyVO.getId()); - if ((lstConditions != null) && (lstConditions.size() > 0)) { - // check whole conditions of this policy - for (ConditionVO conditionVO : lstConditions) { - long thresholdValue = conditionVO.getThreshold(); - Double thresholdPercent = (double)thresholdValue / 100; - CounterVO counterVO = _asCounterDao.findById(conditionVO.getCounterid()); -// Double sum = avgCounter.get(conditionVO.getCounterid()); - long counter_count=1; - do { - String counter_param = params.get("counter" + String.valueOf(counter_count)); - Counter.Source counter_source = counterVO.getSource(); - if (counter_param.equals(counter_source.toString())) - break; - counter_count++; - } while (1==1); - - Double sum = avgCounter.get(counter_count); - Double avg = sum / currentVM; - Operator op = conditionVO.getRelationalOperator(); - boolean bConditionCheck = ((op == com.cloud.network.as.Condition.Operator.EQ) && (thresholdPercent == avg)) - || ((op == com.cloud.network.as.Condition.Operator.GE) && (avg >= thresholdPercent)) - || ((op == com.cloud.network.as.Condition.Operator.GT) && (avg > thresholdPercent)) - || ((op == com.cloud.network.as.Condition.Operator.LE) && (avg <= thresholdPercent)) - || ((op == com.cloud.network.as.Condition.Operator.LT) && (avg < thresholdPercent)); + } catch (Exception e) { + e.printStackTrace(); + } + } - if (!bConditionCheck) { - bValid = false; - break; - } - } - if (bValid) { - return policyVO.getAction(); - } - } - } - } - } - return null; - } - - private List getConditionsbyPolicyId(long policyId){ - List conditionMap = _asConditionMapDao.findByPolicyId(policyId); - if ( (conditionMap == null) || (conditionMap.size() == 0)) - return null; - - List lstResult = new ArrayList(); - for (AutoScalePolicyConditionMapVO asPCmap : conditionMap) { - lstResult.add(_asConditionDao.findById(asPCmap.getConditionId())); - } - - return lstResult; - } + String scaleAction = getAutoscaleAction(avgCounter, asGroup.getId(), currentVM, params); + if (scaleAction != null) { + s_logger.debug("[AutoScale] Doing scale action: " + scaleAction + " for group " + asGroup.getId()); + if (scaleAction.equals("scaleup")) { + _asManager.doScaleUp(asGroup.getId(), 1); + } else { + _asManager.doScaleDown(asGroup.getId()); + } + } + } + } - public List> getPairofCounternameAndDuration( - long groupId) { - AutoScaleVmGroupVO groupVo = _asGroupDao.findById(groupId); - if (groupVo == null) - return null; - List> result = new ArrayList>(); - //list policy map - List groupPolicymap = _asGroupPolicyDao.listByVmGroupId(groupVo.getId()); - if (groupPolicymap == null) - return null; - for (AutoScaleVmGroupPolicyMapVO gpMap : groupPolicymap) { - //get duration - AutoScalePolicyVO policyVo = _asPolicyDao.findById(gpMap.getPolicyId()); - Integer duration = policyVo.getDuration(); - //get collection of counter name - String counterNames = ""; - List lstPCmap = _asConditionMapDao.findByPolicyId(policyVo.getId()); - for (AutoScalePolicyConditionMapVO pcMap : lstPCmap) { - String counterName = getCounternamebyCondition(pcMap.getConditionId()); - - counterNames += counterName + "," + pcMap.getConditionId(); - } - // add to result - Pair pair = new Pair(counterNames, duration); - result.add(pair); - } + } catch (Exception e) { + e.printStackTrace(); + } - return result; - } - - public String getCounternamebyCondition(long conditionId){ - - ConditionVO condition = _asConditionDao.findById(conditionId); - if (condition == null) - return ""; - - long counterId = condition.getCounterid(); - CounterVO counter = _asCounterDao.findById(counterId); - if (counter == null) - return ""; - - return counter.getSource().toString(); - } - } - public StorageStats getStorageStats(long id) { - return _storageStats.get(id); - } + } + } - public HostStats getHostStats(long hostId){ - return _hostStats.get(hostId); - } + } catch (Throwable t) { + s_logger.error("Error trying to monitor autoscaling", t); + } - public StorageStats getStoragePoolStats(long id) { - return _storagePoolStats.get(id); - } + } + + private boolean is_native(long groupId) { + List vos = _asGroupPolicyDao.listByVmGroupId(groupId); + for (AutoScaleVmGroupPolicyMapVO vo : vos) { + List ConditionPolicies = _asConditionMapDao.findByPolicyId(vo.getPolicyId()); + for (AutoScalePolicyConditionMapVO ConditionPolicy : ConditionPolicies) { + ConditionVO condition = _asConditionDao.findById(ConditionPolicy.getConditionId()); + CounterVO counter = _asCounterDao.findById(condition.getCounterid()); + if (counter.getSource() == Counter.Source.cpu || counter.getSource() == Counter.Source.memory) + return true; + } + } + return false; + } + + private String getAutoscaleAction(HashMap avgCounter, long groupId, long currentVM, Map params) { + + List listMap = _asGroupPolicyDao.listByVmGroupId(groupId); + if ((listMap == null) || (listMap.size() == 0)) + return null; + for (AutoScaleVmGroupPolicyMapVO asVmgPmap : listMap) { + AutoScalePolicyVO policyVO = _asPolicyDao.findById(asVmgPmap.getPolicyId()); + if (policyVO != null) { + Integer quitetime = policyVO.getQuietTime(); + Date quitetimeDate = policyVO.getLastQuiteTime(); + long last_quitetime = 0L; + if (quitetimeDate != null) { + last_quitetime = policyVO.getLastQuiteTime().getTime(); + } + long current_time = (new Date()).getTime(); + + // check quite time for this policy + if ((current_time - last_quitetime) >= (long)quitetime) { + + // list all condition of this policy + boolean bValid = true; + List lstConditions = getConditionsbyPolicyId(policyVO.getId()); + if ((lstConditions != null) && (lstConditions.size() > 0)) { + // check whole conditions of this policy + for (ConditionVO conditionVO : lstConditions) { + long thresholdValue = conditionVO.getThreshold(); + Double thresholdPercent = (double)thresholdValue / 100; + CounterVO counterVO = _asCounterDao.findById(conditionVO.getCounterid()); +//Double sum = avgCounter.get(conditionVO.getCounterid()); + long counter_count = 1; + do { + String counter_param = params.get("counter" + String.valueOf(counter_count)); + Counter.Source counter_source = counterVO.getSource(); + if (counter_param.equals(counter_source.toString())) + break; + counter_count++; + } while (1 == 1); + + Double sum = avgCounter.get(counter_count); + Double avg = sum / currentVM; + Operator op = conditionVO.getRelationalOperator(); + boolean bConditionCheck = ((op == com.cloud.network.as.Condition.Operator.EQ) && (thresholdPercent.equals(avg))) + || ((op == com.cloud.network.as.Condition.Operator.GE) && (avg.doubleValue() >= thresholdPercent.doubleValue())) + || ((op == com.cloud.network.as.Condition.Operator.GT) && (avg.doubleValue() > thresholdPercent.doubleValue())) + || ((op == com.cloud.network.as.Condition.Operator.LE) && (avg.doubleValue() <= thresholdPercent.doubleValue())) + || ((op == com.cloud.network.as.Condition.Operator.LT) && (avg.doubleValue() < thresholdPercent.doubleValue())); + + if (!bConditionCheck) { + bValid = false; + break; + } + } + if (bValid) { + return policyVO.getAction(); + } + } + } + } + } + return null; + } + + private List getConditionsbyPolicyId(long policyId) { + List conditionMap = _asConditionMapDao.findByPolicyId(policyId); + if ((conditionMap == null) || (conditionMap.size() == 0)) + return null; + + List lstResult = new ArrayList(); + for (AutoScalePolicyConditionMapVO asPCmap : conditionMap) { + lstResult.add(_asConditionDao.findById(asPCmap.getConditionId())); + } + + return lstResult; + } + + public List> getPairofCounternameAndDuration( + long groupId) { + AutoScaleVmGroupVO groupVo = _asGroupDao.findById(groupId); + if (groupVo == null) + return null; + List> result = new ArrayList>(); + //list policy map + List groupPolicymap = _asGroupPolicyDao.listByVmGroupId(groupVo.getId()); + if (groupPolicymap == null) + return null; + for (AutoScaleVmGroupPolicyMapVO gpMap : groupPolicymap) { + //get duration + AutoScalePolicyVO policyVo = _asPolicyDao.findById(gpMap.getPolicyId()); + Integer duration = policyVo.getDuration(); + //get collection of counter name + String counterNames = ""; + List lstPCmap = _asConditionMapDao.findByPolicyId(policyVo.getId()); + for (AutoScalePolicyConditionMapVO pcMap : lstPCmap) { + String counterName = getCounternamebyCondition(pcMap.getConditionId()); + + counterNames += counterName + "," + pcMap.getConditionId(); + } + // add to result + Pair pair = new Pair(counterNames, duration); + result.add(pair); + } + + return result; + } + + public String getCounternamebyCondition(long conditionId) { + + ConditionVO condition = _asConditionDao.findById(conditionId); + if (condition == null) + return ""; + + long counterId = condition.getCounterid(); + CounterVO counter = _asCounterDao.findById(counterId); + if (counter == null) + return ""; + + return counter.getSource().toString(); + } + } + + public StorageStats getStorageStats(long id) { + return _storageStats.get(id); + } + + public HostStats getHostStats(long hostId) { + return _hostStats.get(hostId); + } + + public StorageStats getStoragePoolStats(long id) { + return _storagePoolStats.get(id); + } } diff --git a/server/src/com/cloud/server/auth/UserAuthenticator.java b/server/src/com/cloud/server/auth/UserAuthenticator.java index 3fccebc4dc7..895c3c06a61 100644 --- a/server/src/com/cloud/server/auth/UserAuthenticator.java +++ b/server/src/com/cloud/server/auth/UserAuthenticator.java @@ -18,6 +18,7 @@ package com.cloud.server.auth; import java.util.Map; +import com.cloud.utils.Pair; import com.cloud.utils.component.Adapter; /** @@ -25,15 +26,18 @@ import com.cloud.utils.component.Adapter; * */ public interface UserAuthenticator extends Adapter { + public enum ActionOnFailedAuthentication { + INCREMENT_INCORRECT_LOGIN_ATTEMPT_COUNT; + } /** * * @param username * @param password * @param domainId - * @return true if the user has been successfully authenticated, false otherwise + * @return the pair of 2 booleans - first identifies the success of authenciation, the second - whether to increase incorrect login attempts count in case of failed authentication */ - public boolean authenticate(String username, String password, Long domainId, Map requestParameters); + public Pair authenticate(String username, String password, Long domainId, Map requestParameters); /** * @param password diff --git a/server/src/com/cloud/servlet/ConsoleProxyClientParam.java b/server/src/com/cloud/servlet/ConsoleProxyClientParam.java index 7ea17c8d3ef..ce06a9624a9 100644 --- a/server/src/com/cloud/servlet/ConsoleProxyClientParam.java +++ b/server/src/com/cloud/servlet/ConsoleProxyClientParam.java @@ -23,11 +23,15 @@ public class ConsoleProxyClientParam { private String clientHostPassword; private String clientTag; private String ticket; - + private String locale; private String clientTunnelUrl; private String clientTunnelSession; + private String hypervHost; + private String ajaxSessionId; + private String username; + private String password; public ConsoleProxyClientParam() { clientHostPort = 0; @@ -90,17 +94,50 @@ public class ConsoleProxyClientParam { } public String getAjaxSessionId() { - return this.ajaxSessionId; + return ajaxSessionId; } public void setAjaxSessionId(String ajaxSessionId) { this.ajaxSessionId = ajaxSessionId; } + public String getLocale() { + return locale; + } + + public void setLocale(String locale) { + this.locale = locale; + } + public String getClientMapKey() { if (clientTag != null && !clientTag.isEmpty()) return clientTag; return clientHostAddress + ":" + clientHostPort; } + + public void setHypervHost(String host) { + hypervHost = host; + } + + public String getHypervHost() { + return hypervHost; + } + + public void setUsername(String username) { + this.username = username; + + } + + public String getUsername() { + return username; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getPassword() { + return password; + } } diff --git a/server/src/com/cloud/servlet/ConsoleProxyServlet.java b/server/src/com/cloud/servlet/ConsoleProxyServlet.java index 06e542d110e..6a5c6a9060d 100644 --- a/server/src/com/cloud/servlet/ConsoleProxyServlet.java +++ b/server/src/com/cloud/servlet/ConsoleProxyServlet.java @@ -43,7 +43,7 @@ import org.springframework.web.context.support.SpringBeanAutowiringSupport; import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import org.apache.cloudstack.api.IdentityService; +import org.apache.cloudstack.framework.security.keys.KeysManager; import com.cloud.exception.PermissionDeniedException; import com.cloud.host.HostVO; @@ -57,8 +57,10 @@ import com.cloud.utils.Pair; import com.cloud.utils.Ternary; import com.cloud.utils.db.EntityManager; import com.cloud.utils.db.TransactionLegacy; +import com.cloud.vm.UserVmDetailVO; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineManager; +import com.cloud.vm.dao.UserVmDetailsDao; /** * Thumbnail access : /console?cmd=thumbnail&vm=xxx&w=xxx&h=xxx @@ -79,11 +81,13 @@ public class ConsoleProxyServlet extends HttpServlet { @Inject ManagementServer _ms; @Inject - IdentityService _identityService; - @Inject EntityManager _entityMgr; + @Inject + UserVmDetailsDao _userVmDetailsDao; + @Inject + KeysManager _keysMgr; - static ManagementServer s_ms; + static KeysManager s_keysMgr; private final Gson _gson = new GsonBuilder().create(); @@ -93,7 +97,7 @@ public class ConsoleProxyServlet extends HttpServlet { @Override public void init(ServletConfig config) throws ServletException { SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext()); - s_ms = _ms; + s_keysMgr = _keysMgr; } @Override @@ -110,7 +114,7 @@ public class ConsoleProxyServlet extends HttpServlet { return; } - if (_ms.getHashKey() == null) { + if (_keysMgr.getHashKey() == null) { s_logger.debug("Console/thumbnail access denied. Ticket service is not ready yet"); sendResponse(resp, "Service is not ready"); return; @@ -161,13 +165,15 @@ public class ConsoleProxyServlet extends HttpServlet { } String vmIdString = req.getParameter("vm"); - Long vmId = _identityService.getIdentityId("vm_instance", vmIdString); - if (vmId == null) { + VirtualMachine vm = _entityMgr.findByUuid(VirtualMachine.class, vmIdString); + if (vm == null) { s_logger.info("invalid console servlet command parameter: " + vmIdString); sendResponse(resp, ""); return; } + Long vmId = vm.getId(); + if (!checkSessionPermision(req, vmId, accountObj)) { sendResponse(resp, "Permission denied"); return; @@ -322,15 +328,21 @@ public class ConsoleProxyServlet extends HttpServlet { s_logger.info("Parse host info returned from executing GetVNCPortCommand. host info: " + hostInfo); - if (hostInfo != null && hostInfo.startsWith("consoleurl")) { - String tokens[] = hostInfo.split("&"); + if (hostInfo != null) { + if (hostInfo.startsWith("consoleurl")) { + String tokens[] = hostInfo.split("&"); - if (hostInfo.length() > 19 && hostInfo.indexOf('/', 19) > 19) { - host = hostInfo.substring(19, hostInfo.indexOf('/', 19)).trim(); - tunnelUrl = tokens[0].substring("consoleurl=".length()); - tunnelSession = tokens[1].split("=")[1]; + if (hostInfo.length() > 19 && hostInfo.indexOf('/', 19) > 19) { + host = hostInfo.substring(19, hostInfo.indexOf('/', 19)).trim(); + tunnelUrl = tokens[0].substring("consoleurl=".length()); + tunnelSession = tokens[1].split("=")[1]; + } else { + host = ""; + } + } else if (hostInfo.startsWith("instanceId")) { + host = hostInfo.substring(hostInfo.indexOf('=') + 1); } else { - host = ""; + host = hostInfo; } } else { host = hostInfo; @@ -340,8 +352,8 @@ public class ConsoleProxyServlet extends HttpServlet { } private String getEncryptorPassword() { - String key = _ms.getEncryptionKey(); - String iv = _ms.getEncryptionIV(); + String key = _keysMgr.getEncryptionKey(); + String iv = _keysMgr.getEncryptionIV(); ConsoleProxyPasswordBasedEncryptor.KeyIVPair keyIvPair = new ConsoleProxyPasswordBasedEncryptor.KeyIVPair(key, iv); return _gson.toJson(keyIvPair); @@ -356,9 +368,17 @@ public class ConsoleProxyServlet extends HttpServlet { Ternary parsedHostInfo = parseHostInfo(portInfo.first()); String sid = vm.getVncPassword(); - String tag = String.valueOf(vm.getId()); - tag = _identityService.getIdentityUuid("vm_instance", tag); - String ticket = genAccessTicket(host, String.valueOf(portInfo.second()), sid, tag); + String tag = vm.getUuid(); + + int port = -1; + if (portInfo.second() == -9) { + //for hyperv + port = Integer.parseInt(_ms.findDetail(hostVo.getId(), "rdp.server.port").getValue()); + } else { + port = portInfo.second(); + } + + String ticket = genAccessTicket(parsedHostInfo.first(), String.valueOf(port), sid, tag); ConsoleProxyPasswordBasedEncryptor encryptor = new ConsoleProxyPasswordBasedEncryptor(getEncryptorPassword()); ConsoleProxyClientParam param = new ConsoleProxyClientParam(); @@ -367,6 +387,12 @@ public class ConsoleProxyServlet extends HttpServlet { param.setClientHostPassword(sid); param.setClientTag(tag); param.setTicket(ticket); + if (portInfo.second() == -9) { + //For Hyperv Clinet Host Address will send Instance id + param.setHypervHost(host); + param.setUsername(_ms.findDetail(hostVo.getId(), "username").getValue()); + param.setPassword(_ms.findDetail(hostVo.getId(), "password").getValue()); + } if (parsedHostInfo.second() != null && parsedHostInfo.third() != null) { param.setClientTunnelUrl(parsedHostInfo.second()); param.setClientTunnelSession(parsedHostInfo.third()); @@ -391,16 +417,38 @@ public class ConsoleProxyServlet extends HttpServlet { Ternary parsedHostInfo = parseHostInfo(portInfo.first()); + int port = -1; + if (portInfo.second() == -9) { + //for hyperv + port = Integer.parseInt(_ms.findDetail(hostVo.getId(), "rdp.server.port").getValue()); + } else { + port = portInfo.second(); + } + String sid = vm.getVncPassword(); + UserVmDetailVO details = _userVmDetailsDao.findDetail(vm.getId(), "keyboard"); + String tag = vm.getUuid(); - String ticket = genAccessTicket(host, String.valueOf(portInfo.second()), sid, tag); + + String ticket = genAccessTicket(parsedHostInfo.first(), String.valueOf(port), sid, tag); ConsoleProxyPasswordBasedEncryptor encryptor = new ConsoleProxyPasswordBasedEncryptor(getEncryptorPassword()); ConsoleProxyClientParam param = new ConsoleProxyClientParam(); param.setClientHostAddress(parsedHostInfo.first()); - param.setClientHostPort(portInfo.second()); + param.setClientHostPort(port); param.setClientHostPassword(sid); param.setClientTag(tag); param.setTicket(ticket); + + if (details != null) { + param.setLocale(details.getValue()); + } + + if (portInfo.second() == -9) { + //For Hyperv Clinet Host Address will send Instance id + param.setHypervHost(host); + param.setUsername(_ms.findDetail(hostVo.getId(), "username").getValue()); + param.setPassword(_ms.findDetail(hostVo.getId(), "password").getValue()); + } if (parsedHostInfo.second() != null && parsedHostInfo.third() != null) { param.setClientTunnelUrl(parsedHostInfo.second()); param.setClientTunnelSession(parsedHostInfo.third()); @@ -432,7 +480,7 @@ public class ConsoleProxyServlet extends HttpServlet { long ts = normalizedHashTime.getTime(); ts = ts / 60000; // round up to 1 minute - String secretKey = s_ms.getHashKey(); + String secretKey = s_keysMgr.getHashKey(); SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1"); mac.init(keySpec); diff --git a/server/src/com/cloud/storage/StorageManagerImpl.java b/server/src/com/cloud/storage/StorageManagerImpl.java index 7a7f6b7dc75..52c2e7e0e4e 100755 --- a/server/src/com/cloud/storage/StorageManagerImpl.java +++ b/server/src/com/cloud/storage/StorageManagerImpl.java @@ -44,7 +44,6 @@ import javax.naming.ConfigurationException; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import org.apache.cloudstack.api.command.admin.storage.AddImageStoreCmd; import org.apache.cloudstack.api.command.admin.storage.CancelPrimaryStorageMaintenanceCmd; import org.apache.cloudstack.api.command.admin.storage.CreateSecondaryStagingStoreCmd; import org.apache.cloudstack.api.command.admin.storage.CreateStoragePoolCmd; @@ -55,6 +54,7 @@ import org.apache.cloudstack.api.command.admin.storage.UpdateStoragePoolCmd; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.engine.subsystem.api.storage.ClusterScope; import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; +import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreDriver; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreLifeCycle; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProvider; @@ -63,6 +63,7 @@ import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector; import org.apache.cloudstack.engine.subsystem.api.storage.HostScope; import org.apache.cloudstack.engine.subsystem.api.storage.HypervisorHostListener; import org.apache.cloudstack.engine.subsystem.api.storage.ImageStoreProvider; +import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver; import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreInfo; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotDataFactory; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; @@ -269,8 +270,8 @@ public class StorageManagerImpl extends ManagerBase implements StorageManager, C return _discoverers; } - public void setDiscoverers(List _discoverers) { - this._discoverers = _discoverers; + public void setDiscoverers(List discoverers) { + _discoverers = discoverers; } protected SearchBuilder HostTemplateStatesSearch; @@ -658,12 +659,12 @@ public class StorageManagerImpl extends ManagerBase implements StorageManager, C lifeCycle.attachZone(store, zoneScope, hypervisorType); } } catch (Exception e) { - s_logger.debug("Failed to add data store", e); + s_logger.debug("Failed to add data store: "+e.getMessage(), e); // clean up the db if (store != null) { lifeCycle.deleteDataStore(store); } - throw new CloudRuntimeException("Failed to add data store", e); + throw new CloudRuntimeException("Failed to add data store: "+e.getMessage(), e); } return (PrimaryDataStoreInfo)dataStoreMgr.getDataStore(store.getId(), DataStoreRole.Primary); @@ -1226,28 +1227,6 @@ public class StorageManagerImpl extends ManagerBase implements StorageManager, C return (PrimaryDataStoreInfo)dataStoreMgr.getDataStore(primaryStorage.getId(), DataStoreRole.Primary); } - @Override - @DB - public ImageStore prepareSecondaryStorageForObjectStoreMigration(Long storeId) throws ResourceUnavailableException, InsufficientCapacityException { - // Verify that image store exists - ImageStoreVO store = _imageStoreDao.findById(storeId); - if (store == null) { - throw new InvalidParameterValueException("Image store with id " + storeId + " doesn't exist"); - } else if (!store.getProviderName().equals(DataStoreProvider.NFS_IMAGE)) { - throw new InvalidParameterValueException("We only support migrate NFS secondary storage to use object store!"); - } - _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), store.getDataCenterId()); - - DataStoreProvider provider = dataStoreProviderMgr.getDataStoreProvider(store.getProviderName()); - DataStoreLifeCycle lifeCycle = provider.getDataStoreLifeCycle(); - DataStore secStore = dataStoreMgr.getDataStore(storeId, DataStoreRole.Image); - lifeCycle.migrateToObjectStore(secStore); - // update store_role in template_store_ref and snapshot_store_ref to ImageCache - _templateStoreDao.updateStoreRoleToCachce(storeId); - _snapshotStoreDao.updateStoreRoleToCache(storeId); - // converted to an image cache store - return (ImageStore)_dataStoreMgr.getDataStore(storeId, DataStoreRole.ImageCache); - } protected class StorageGarbageCollector extends ManagedContextRunnable { @@ -1506,11 +1485,13 @@ public class StorageManagerImpl extends ManagerBase implements StorageManager, C if (requestedVolumes == null || requestedVolumes.isEmpty() || pool == null) { return false; } - // Only Solidfire type primary storage is using/setting Iops. - // This check will fix to return the storage has enough Iops when capacityIops is set to NULL for any PS Storage provider - if (pool.getCapacityIops() == null) { + + // Only SolidFire-type primary storage is using/setting IOPS. + // This check returns true for storage that does not specify IOPS. + if (pool.getCapacityIops() == null ) { return true; } + long currentIops = 0; List volumesInPool = _volumeDao.findByPoolId(pool.getId(), null); @@ -1565,7 +1546,7 @@ public class StorageManagerImpl extends ManagerBase implements StorageManager, C } } if (volume.getState() != Volume.State.Ready) { - totalAskingSize = totalAskingSize + volume.getSize(); + totalAskingSize = totalAskingSize + getVolumeSizeIncludingHvSsReserve(volume, pool); } } @@ -1604,6 +1585,19 @@ public class StorageManagerImpl extends ManagerBase implements StorageManager, C return true; } + private long getVolumeSizeIncludingHvSsReserve(Volume volume, StoragePool pool) { + DataStoreProvider storeProvider = _dataStoreProviderMgr.getDataStoreProvider(pool.getStorageProviderName()); + DataStoreDriver storeDriver = storeProvider.getDataStoreDriver(); + + if (storeDriver instanceof PrimaryDataStoreDriver) { + PrimaryDataStoreDriver primaryStoreDriver = (PrimaryDataStoreDriver)storeDriver; + + return primaryStoreDriver.getVolumeSizeIncludingHypervisorSnapshotReserve(volume, pool); + } + + return volume.getSize(); + } + @Override public void createCapacityEntry(long poolId) { StoragePoolVO storage = _storagePoolDao.findById(poolId); @@ -1635,8 +1629,8 @@ public class StorageManagerImpl extends ManagerBase implements StorageManager, C } @Override - public ImageStore discoverImageStore(AddImageStoreCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { - String providerName = cmd.getProviderName(); + public ImageStore discoverImageStore(String name, String url, String providerName, Long dcId, Map details) throws IllegalArgumentException, DiscoveryException, + InvalidParameterValueException { DataStoreProvider storeProvider = _dataStoreProviderMgr.getDataStoreProvider(providerName); if (storeProvider == null) { @@ -1647,13 +1641,19 @@ public class StorageManagerImpl extends ManagerBase implements StorageManager, C providerName = storeProvider.getName(); // ignored passed provider name and use default image store provider name } - Long dcId = cmd.getZoneId(); - Map details = cmd.getDetails(); ScopeType scopeType = ScopeType.ZONE; if (dcId == null) { scopeType = ScopeType.REGION; } + if (name == null) { + name = url; + } + ImageStoreVO imageStore = _imageStoreDao.findByName(name); + if (imageStore != null) { + throw new InvalidParameterValueException("The image store with name " + name + " already exists, try creating with another name"); + } + // check if scope is supported by store provider if (!((ImageStoreProvider)storeProvider).isScopeSupported(scopeType)) { throw new InvalidParameterValueException("Image store provider " + providerName + " does not support scope " + scopeType); @@ -1686,8 +1686,8 @@ public class StorageManagerImpl extends ManagerBase implements StorageManager, C Map params = new HashMap(); params.put("zoneId", dcId); - params.put("url", cmd.getUrl()); - params.put("name", cmd.getName()); + params.put("url", url); + params.put("name", name); params.put("details", details); params.put("scope", scopeType); params.put("providerName", storeProvider.getName()); @@ -1698,8 +1698,8 @@ public class StorageManagerImpl extends ManagerBase implements StorageManager, C try { store = lifeCycle.initialize(params); } catch (Exception e) { - s_logger.debug("Failed to add data store", e); - throw new CloudRuntimeException("Failed to add data store", e); + s_logger.debug("Failed to add data store: " + e.getMessage(), e); + throw new CloudRuntimeException("Failed to add data store: " + e.getMessage(), e); } if (((ImageStoreProvider)storeProvider).needDownloadSysTemplate()) { @@ -1722,6 +1722,41 @@ public class StorageManagerImpl extends ManagerBase implements StorageManager, C return (ImageStore)_dataStoreMgr.getDataStore(store.getId(), DataStoreRole.Image); } + @Override + public ImageStore migrateToObjectStore(String name, String url, String providerName, Map details) throws IllegalArgumentException, DiscoveryException, + InvalidParameterValueException { + // check if current cloud is ready to migrate, we only support cloud with only NFS secondary storages + List imgStores = _imageStoreDao.listImageStores(); + List nfsStores = new ArrayList(); + if (imgStores != null && imgStores.size() > 0) { + for (ImageStoreVO store : imgStores) { + if (!store.getProviderName().equals(DataStoreProvider.NFS_IMAGE)) { + throw new InvalidParameterValueException("We only support migrate NFS secondary storage to use object store!"); + } else { + nfsStores.add(store); + } + } + } + // convert all NFS secondary storage to staging store + if (nfsStores != null && nfsStores.size() > 0) { + for (ImageStoreVO store : nfsStores) { + long storeId = store.getId(); + + _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), store.getDataCenterId()); + + DataStoreProvider provider = dataStoreProviderMgr.getDataStoreProvider(store.getProviderName()); + DataStoreLifeCycle lifeCycle = provider.getDataStoreLifeCycle(); + DataStore secStore = dataStoreMgr.getDataStore(storeId, DataStoreRole.Image); + lifeCycle.migrateToObjectStore(secStore); + // update store_role in template_store_ref and snapshot_store_ref to ImageCache + _templateStoreDao.updateStoreRoleToCachce(storeId); + _snapshotStoreDao.updateStoreRoleToCache(storeId); + } + } + // add object store + return discoverImageStore(name, url, providerName, null, details); + } + private void duplicateCacheStoreRecordsToRegionStore(long storeId) { _templateStoreDao.duplicateCacheRecordsOnRegionStore(storeId); _snapshotStoreDao.duplicateCacheRecordsOnRegionStore(storeId); @@ -1862,8 +1897,8 @@ public class StorageManagerImpl extends ManagerBase implements StorageManager, C try { store = lifeCycle.initialize(params); } catch (Exception e) { - s_logger.debug("Failed to add data store", e); - throw new CloudRuntimeException("Failed to add data store", e); + s_logger.debug("Failed to add data store: "+e.getMessage(), e); + throw new CloudRuntimeException("Failed to add data store: "+e.getMessage(), e); } return (ImageStore)_dataStoreMgr.getDataStore(store.getId(), DataStoreRole.ImageCache); diff --git a/server/src/com/cloud/storage/StoragePoolAutomationImpl.java b/server/src/com/cloud/storage/StoragePoolAutomationImpl.java index c76c6477418..8becd75ef26 100644 --- a/server/src/com/cloud/storage/StoragePoolAutomationImpl.java +++ b/server/src/com/cloud/storage/StoragePoolAutomationImpl.java @@ -219,7 +219,7 @@ public class StoragePoolAutomationImpl implements StoragePoolAutomation { if (restart) { - vmMgr.advanceStart(consoleProxy.getUuid(), null); + vmMgr.advanceStart(consoleProxy.getUuid(), null, null); // update work status work.setStartedAfterMaintenance(true); _storagePoolWorkDao.update(work.getId(), work); @@ -245,7 +245,7 @@ public class StoragePoolAutomationImpl implements StoragePoolAutomation { _storagePoolWorkDao.update(work.getId(), work); if (restart) { - vmMgr.advanceStart(secStrgVm.getUuid(), null); + vmMgr.advanceStart(secStrgVm.getUuid(), null, null); // update work status work.setStartedAfterMaintenance(true); _storagePoolWorkDao.update(work.getId(), work); @@ -262,7 +262,7 @@ public class StoragePoolAutomationImpl implements StoragePoolAutomation { _storagePoolWorkDao.update(work.getId(), work); if (restart) { - vmMgr.advanceStart(domR.getUuid(), null); + vmMgr.advanceStart(domR.getUuid(), null, null); // update work status work.setStartedAfterMaintenance(true); _storagePoolWorkDao.update(work.getId(), work); @@ -330,17 +330,21 @@ public class StoragePoolAutomationImpl implements StoragePoolAutomation { // proxy if (vmInstance.getType().equals(VirtualMachine.Type.ConsoleProxy)) { - ConsoleProxyVO consoleProxy = _consoleProxyDao.findById(vmInstance.getId()); - vmMgr.advanceStart(consoleProxy.getUuid(), null); + ConsoleProxyVO consoleProxy = _consoleProxyDao + .findById(vmInstance.getId()); + vmMgr.advanceStart(consoleProxy.getUuid(), null, null); // update work queue work.setStartedAfterMaintenance(true); _storagePoolWorkDao.update(work.getId(), work); } // if the instance is of type ssvm, call the ssvm manager - if (vmInstance.getType().equals(VirtualMachine.Type.SecondaryStorageVm)) { - SecondaryStorageVmVO ssVm = _secStrgDao.findById(vmInstance.getId()); - vmMgr.advanceStart(ssVm.getUuid(), null); + if (vmInstance.getType().equals( + VirtualMachine.Type.SecondaryStorageVm)) { + SecondaryStorageVmVO ssVm = _secStrgDao.findById(vmInstance + .getId()); + vmMgr.advanceStart(ssVm.getUuid(), null, null); + // update work queue work.setStartedAfterMaintenance(true); _storagePoolWorkDao.update(work.getId(), work); @@ -349,7 +353,7 @@ public class StoragePoolAutomationImpl implements StoragePoolAutomation { // if the instance is of type ssvm, call the ssvm manager if (vmInstance.getType().equals(VirtualMachine.Type.DomainRouter)) { DomainRouterVO domR = _domrDao.findById(vmInstance.getId()); - vmMgr.advanceStart(domR.getUuid(), null); + vmMgr.advanceStart(domR.getUuid(), null, null); // update work queue work.setStartedAfterMaintenance(true); _storagePoolWorkDao.update(work.getId(), work); @@ -359,7 +363,7 @@ public class StoragePoolAutomationImpl implements StoragePoolAutomation { if (vmInstance.getType().equals(VirtualMachine.Type.User)) { UserVmVO userVm = userVmDao.findById(vmInstance.getId()); - vmMgr.advanceStart(userVm.getUuid(), null); // update work queue + vmMgr.advanceStart(userVm.getUuid(), null, null); // update work queue work.setStartedAfterMaintenance(true); _storagePoolWorkDao.update(work.getId(), work); } diff --git a/server/src/com/cloud/storage/VmWorkAttachVolume.java b/server/src/com/cloud/storage/VmWorkAttachVolume.java new file mode 100644 index 00000000000..3cdfbb52a2d --- /dev/null +++ b/server/src/com/cloud/storage/VmWorkAttachVolume.java @@ -0,0 +1,40 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.storage; + +import com.cloud.vm.VmWork; + +public class VmWorkAttachVolume extends VmWork { + private static final long serialVersionUID = 553291814854451740L; + + private Long volumeId; + private Long deviceId; + + public VmWorkAttachVolume(long userId, long accountId, long vmId, String handlerName, Long volumeId, Long deviceId) { + super(userId, accountId, vmId, handlerName); + this.volumeId = volumeId; + this.deviceId = deviceId; + } + + public Long getVolumeId() { + return volumeId; + } + + public Long getDeviceId() { + return deviceId; + } +} diff --git a/server/src/com/cloud/storage/VmWorkDetachVolume.java b/server/src/com/cloud/storage/VmWorkDetachVolume.java new file mode 100644 index 00000000000..18262d254aa --- /dev/null +++ b/server/src/com/cloud/storage/VmWorkDetachVolume.java @@ -0,0 +1,34 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.storage; + +import com.cloud.vm.VmWork; + +public class VmWorkDetachVolume extends VmWork { + private static final long serialVersionUID = -8722243207385263101L; + + private Long volumeId; + + public VmWorkDetachVolume(long userId, long accountId, long vmId, String handlerName, Long volumeId) { + super(userId, accountId, vmId, handlerName); + this.volumeId = volumeId; + } + + public Long getVolumeId() { + return volumeId; + } +} diff --git a/server/src/com/cloud/storage/VmWorkMigrateVolume.java b/server/src/com/cloud/storage/VmWorkMigrateVolume.java new file mode 100644 index 00000000000..c83e02df3ba --- /dev/null +++ b/server/src/com/cloud/storage/VmWorkMigrateVolume.java @@ -0,0 +1,46 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.storage; + +import com.cloud.vm.VmWork; + +public class VmWorkMigrateVolume extends VmWork { + private static final long serialVersionUID = -565778516928408602L; + + private long volumeId; + private long destPoolId; + private boolean liveMigrate; + + public VmWorkMigrateVolume(long userId, long accountId, long vmId, String handlerName, long volumeId, long destPoolId, boolean liveMigrate) { + super(userId, accountId, vmId, handlerName); + this.volumeId = volumeId; + this.destPoolId = destPoolId; + this.liveMigrate = liveMigrate; + } + + public long getVolumeId() { + return volumeId; + } + + public long getDestPoolId() { + return destPoolId; + } + + public boolean isLiveMigrate() { + return liveMigrate; + } +} diff --git a/server/src/com/cloud/storage/VmWorkResizeVolume.java b/server/src/com/cloud/storage/VmWorkResizeVolume.java new file mode 100644 index 00000000000..3ccaecd2429 --- /dev/null +++ b/server/src/com/cloud/storage/VmWorkResizeVolume.java @@ -0,0 +1,61 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.storage; + +import com.cloud.vm.VmWork; + +public class VmWorkResizeVolume extends VmWork { + private static final long serialVersionUID = 6112366316907642498L; + + private long volumeId; + private long currentSize; + private long newSize; + private Long newServiceOfferingId; + private boolean shrinkOk; + + public VmWorkResizeVolume(long userId, long accountId, long vmId, String handlerName, + long volumeId, long currentSize, long newSize, Long newServiceOfferingId, boolean shrinkOk) { + + super(userId, accountId, vmId, handlerName); + + this.volumeId = volumeId; + this.currentSize = currentSize; + this.newSize = newSize; + this.newServiceOfferingId = newServiceOfferingId; + this.shrinkOk = shrinkOk; + } + + public long getVolumeId() { + return volumeId; + } + + public long getCurrentSize() { + return currentSize; + } + + public long getNewSize() { + return newSize; + } + + public Long getNewServiceOfferingId() { + return newServiceOfferingId; + } + + public boolean isShrinkOk() { + return shrinkOk; + } +} diff --git a/server/src/com/cloud/storage/VmWorkTakeVolumeSnapshot.java b/server/src/com/cloud/storage/VmWorkTakeVolumeSnapshot.java new file mode 100644 index 00000000000..8b238080bce --- /dev/null +++ b/server/src/com/cloud/storage/VmWorkTakeVolumeSnapshot.java @@ -0,0 +1,54 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.storage; + +import com.cloud.vm.VmWork; + +public class VmWorkTakeVolumeSnapshot extends VmWork { + + private static final long serialVersionUID = 341816293003023823L; + + private Long volumeId; + private Long policyId; + private Long snapshotId; + private boolean quiesceVm; + + public VmWorkTakeVolumeSnapshot(long userId, long accountId, long vmId, String handlerName, + Long volumeId, Long policyId, Long snapshotId, boolean quiesceVm) { + super(userId, accountId, vmId, handlerName); + this.volumeId = volumeId; + this.policyId = policyId; + this.snapshotId = snapshotId; + this.quiesceVm = quiesceVm; + } + + public Long getVolumeId() { + return volumeId; + } + + public Long getPolicyId() { + return policyId; + } + + public Long getSnapshotId() { + return snapshotId; + } + + public boolean isQuiesceVm() { + return quiesceVm; + } +} diff --git a/server/src/com/cloud/storage/VolumeApiServiceImpl.java b/server/src/com/cloud/storage/VolumeApiServiceImpl.java index 18c64ddd531..c856379b812 100644 --- a/server/src/com/cloud/storage/VolumeApiServiceImpl.java +++ b/server/src/com/cloud/storage/VolumeApiServiceImpl.java @@ -26,10 +26,8 @@ import java.util.concurrent.ExecutionException; import javax.inject.Inject; -import com.cloud.uuididentity.UUIDManager; import org.apache.log4j.Logger; -import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.command.user.volume.AttachVolumeCmd; import org.apache.cloudstack.api.command.user.volume.CreateVolumeCmd; import org.apache.cloudstack.api.command.user.volume.DetachVolumeCmd; @@ -47,6 +45,7 @@ import org.apache.cloudstack.engine.subsystem.api.storage.HostScope; import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreInfo; import org.apache.cloudstack.engine.subsystem.api.storage.Scope; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotDataFactory; +import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotService; import org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator; import org.apache.cloudstack.engine.subsystem.api.storage.TemplateDataFactory; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory; @@ -54,10 +53,17 @@ import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService.VolumeApiResult; import org.apache.cloudstack.framework.async.AsyncCallFuture; +import org.apache.cloudstack.framework.config.ConfigKey; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.framework.jobs.AsyncJob; import org.apache.cloudstack.framework.jobs.AsyncJobExecutionContext; import org.apache.cloudstack.framework.jobs.AsyncJobManager; +import org.apache.cloudstack.framework.jobs.Outcome; +import org.apache.cloudstack.framework.jobs.dao.VmWorkJobDao; +import org.apache.cloudstack.framework.jobs.impl.AsyncJobVO; +import org.apache.cloudstack.framework.jobs.impl.OutcomeImpl; +import org.apache.cloudstack.framework.jobs.impl.VmWorkJobVO; +import org.apache.cloudstack.jobs.JobInfo; import org.apache.cloudstack.storage.command.AttachAnswer; import org.apache.cloudstack.storage.command.AttachCommand; import org.apache.cloudstack.storage.command.DettachCommand; @@ -68,6 +74,7 @@ import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreDao; import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreDao; import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreVO; import org.apache.cloudstack.storage.image.datastore.ImageStoreEntity; +import org.apache.cloudstack.utils.identity.ManagementServerNode; import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; @@ -115,7 +122,6 @@ import com.cloud.storage.dao.SnapshotDao; import com.cloud.storage.dao.SnapshotPolicyDao; import com.cloud.storage.dao.StoragePoolHostDao; import com.cloud.storage.dao.StoragePoolWorkDao; -import com.cloud.storage.dao.UploadDao; import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.dao.VMTemplatePoolDao; import com.cloud.storage.dao.VolumeDao; @@ -125,18 +131,20 @@ import com.cloud.storage.secondary.SecondaryStorageVmManager; import com.cloud.storage.snapshot.SnapshotApiService; import com.cloud.storage.snapshot.SnapshotManager; import com.cloud.storage.snapshot.SnapshotScheduler; -import com.cloud.storage.upload.UploadMonitor; import com.cloud.tags.dao.ResourceTagDao; import com.cloud.template.TemplateManager; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.ResourceLimitService; +import com.cloud.user.User; import com.cloud.user.VmDiskStatisticsVO; import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.UserDao; import com.cloud.user.dao.VmDiskStatisticsDao; import com.cloud.utils.EnumUtils; import com.cloud.utils.NumbersUtil; +import com.cloud.utils.Pair; +import com.cloud.utils.Predicate; import com.cloud.utils.UriUtils; import com.cloud.utils.component.ManagerBase; import com.cloud.utils.db.DB; @@ -147,12 +155,18 @@ import com.cloud.utils.db.TransactionStatus; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.fsm.NoTransitionException; import com.cloud.utils.fsm.StateMachine2; +import com.cloud.uuididentity.UUIDManager; import com.cloud.vm.UserVmManager; import com.cloud.vm.UserVmVO; import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.VirtualMachineManager; +import com.cloud.vm.VmWork; +import com.cloud.vm.VmWorkConstants; +import com.cloud.vm.VmWorkJobHandler; +import com.cloud.vm.VmWorkJobHandlerProxy; +import com.cloud.vm.VmWorkSerializer; import com.cloud.vm.dao.ConsoleProxyDao; import com.cloud.vm.dao.DomainRouterDao; import com.cloud.vm.dao.SecondaryStorageVmDao; @@ -161,8 +175,11 @@ import com.cloud.vm.dao.VMInstanceDao; import com.cloud.vm.snapshot.VMSnapshotVO; import com.cloud.vm.snapshot.dao.VMSnapshotDao; -public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiService { +public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiService, VmWorkJobHandler { private final static Logger s_logger = Logger.getLogger(VolumeApiServiceImpl.class); + + public static final String VM_WORK_JOB_HANDLER = VolumeApiServiceImpl.class.getSimpleName(); + @Inject VolumeOrchestrationService _volumeMgr; @@ -300,9 +317,7 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic @Inject SnapshotApiService snapshotMgr; @Inject - UploadMonitor _uploadMonitor; - @Inject - UploadDao _uploadDao; + SnapshotService snapshotSrv; @Inject UUIDManager _uuidMgr; @@ -310,8 +325,21 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic protected HypervisorCapabilitiesDao _hypervisorCapabilitiesDao; @Inject StorageManager storageMgr; - private int _customDiskOfferingMinSize = 1; - private final int _customDiskOfferingMaxSize = 1024; + + @Inject + protected AsyncJobManager _jobMgr; + + @Inject + protected VmWorkJobDao _workJobDao; + + VmWorkJobHandlerProxy _jobHandlerProxy = new VmWorkJobHandlerProxy(this); + + // TODO + static final ConfigKey VmJobEnabled = new ConfigKey("Advanced", Boolean.class, "vm.job.enabled", "false", + "True to enable new VM sync model. false to use the old way", false); + static final ConfigKey VmJobCheckInterval = new ConfigKey("Advanced", Long.class, "vm.job.check.interval", "3000", + "Interval in milliseconds to check if the job is complete", false); + private long _maxVolumeSizeInGb; private final StateMachine2 _volStateMachine; @@ -381,24 +409,23 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic if (userSpecifiedName == null) { userSpecifiedName = getRandomVolumeName(); } - if ((!url.toLowerCase().endsWith("vhd")) && (!url.toLowerCase().endsWith("vhd.zip")) && (!url.toLowerCase().endsWith("vhd.bz2")) && - (!url.toLowerCase().endsWith("vhdx")) && (!url.toLowerCase().endsWith("vhdx.zip")) && - (!url.toLowerCase().endsWith("vhdx.gz")) && (!url.toLowerCase().endsWith("vhdx.bz2")) && - (!url.toLowerCase().endsWith("vhd.gz")) && (!url.toLowerCase().endsWith("qcow2")) && (!url.toLowerCase().endsWith("qcow2.zip")) && - (!url.toLowerCase().endsWith("qcow2.bz2")) && (!url.toLowerCase().endsWith("qcow2.gz")) && (!url.toLowerCase().endsWith("ova")) && - (!url.toLowerCase().endsWith("ova.zip")) && (!url.toLowerCase().endsWith("ova.bz2")) && (!url.toLowerCase().endsWith("ova.gz")) && - (!url.toLowerCase().endsWith("img")) && (!url.toLowerCase().endsWith("raw"))) { + if ((!url.toLowerCase().endsWith("vhd")) && (!url.toLowerCase().endsWith("vhd.zip")) && (!url.toLowerCase().endsWith("vhd.bz2")) && (!url.toLowerCase().endsWith("vhdx")) + && (!url.toLowerCase().endsWith("vhdx.zip")) && (!url.toLowerCase().endsWith("vhdx.gz")) && (!url.toLowerCase().endsWith("vhdx.bz2")) + && (!url.toLowerCase().endsWith("vhd.gz")) && (!url.toLowerCase().endsWith("qcow2")) && (!url.toLowerCase().endsWith("qcow2.zip")) + && (!url.toLowerCase().endsWith("qcow2.bz2")) && (!url.toLowerCase().endsWith("qcow2.gz")) && (!url.toLowerCase().endsWith("ova")) + && (!url.toLowerCase().endsWith("ova.zip")) && (!url.toLowerCase().endsWith("ova.bz2")) && (!url.toLowerCase().endsWith("ova.gz")) + && (!url.toLowerCase().endsWith("img")) && (!url.toLowerCase().endsWith("raw"))) { throw new InvalidParameterValueException("Please specify a valid " + format.toLowerCase()); } - if ((format.equalsIgnoreCase("vhd") && (!url.toLowerCase().endsWith(".vhd") && !url.toLowerCase().endsWith("vhd.zip") && !url.toLowerCase().endsWith("vhd.bz2") && !url.toLowerCase() - .endsWith("vhd.gz"))) || - (format.equalsIgnoreCase("vhdx") && (!url.toLowerCase().endsWith(".vhdx") && !url.toLowerCase().endsWith("vhdx.zip") && !url.toLowerCase().endsWith("vhdx.bz2") && !url.toLowerCase() - .endsWith("vhdx.gz"))) || - (format.equalsIgnoreCase("qcow2") && (!url.toLowerCase().endsWith(".qcow2") && !url.toLowerCase().endsWith("qcow2.zip") && - !url.toLowerCase().endsWith("qcow2.bz2") && !url.toLowerCase().endsWith("qcow2.gz"))) || - (format.equalsIgnoreCase("ova") && (!url.toLowerCase().endsWith(".ova") && !url.toLowerCase().endsWith("ova.zip") && !url.toLowerCase().endsWith("ova.bz2") && !url.toLowerCase() - .endsWith("ova.gz"))) || (format.equalsIgnoreCase("raw") && (!url.toLowerCase().endsWith(".img") && !url.toLowerCase().endsWith("raw")))) { + if ((format.equalsIgnoreCase("vhd") && (!url.toLowerCase().endsWith(".vhd") && !url.toLowerCase().endsWith("vhd.zip") && !url.toLowerCase().endsWith("vhd.bz2") && !url + .toLowerCase().endsWith("vhd.gz"))) + || (format.equalsIgnoreCase("vhdx") && (!url.toLowerCase().endsWith(".vhdx") && !url.toLowerCase().endsWith("vhdx.zip") && !url.toLowerCase().endsWith("vhdx.bz2") && !url + .toLowerCase().endsWith("vhdx.gz"))) + || (format.equalsIgnoreCase("qcow2") && (!url.toLowerCase().endsWith(".qcow2") && !url.toLowerCase().endsWith("qcow2.zip") + && !url.toLowerCase().endsWith("qcow2.bz2") && !url.toLowerCase().endsWith("qcow2.gz"))) + || (format.equalsIgnoreCase("ova") && (!url.toLowerCase().endsWith(".ova") && !url.toLowerCase().endsWith("ova.zip") && !url.toLowerCase().endsWith("ova.bz2") && !url + .toLowerCase().endsWith("ova.gz"))) || (format.equalsIgnoreCase("raw") && (!url.toLowerCase().endsWith(".img") && !url.toLowerCase().endsWith("raw")))) { throw new InvalidParameterValueException("Please specify a valid URL. URL:" + url + " is an invalid for the format " + format.toLowerCase()); } UriUtils.validateUrl(url); @@ -422,8 +449,10 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic volume.setPoolId(null); volume.setDataCenterId(zoneId); volume.setPodId(null); - volume.setAccountId(owner.getAccountId()); - volume.setDomainId(owner.getDomainId()); + // to prevent a nullpointer deref I put the system account id here when no owner is given. + // TODO Decide if this is valid or whether throwing a CloudRuntimeException is more appropriate + volume.setAccountId((owner == null) ? Account.ACCOUNT_ID_SYSTEM : owner.getAccountId()); + volume.setDomainId((owner == null) ? Domain.ROOT_DOMAIN : owner.getDomainId()); long diskOfferingId = _diskOfferingDao.findByUniqueName("Cloud.com-Custom").getId(); volume.setDiskOfferingId(diskOfferingId); // volume.setSize(size); @@ -510,9 +539,12 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic if (size == null) { throw new InvalidParameterValueException("This disk offering requires a custom size specified"); } - if ((sizeInGB < _customDiskOfferingMinSize) || (sizeInGB > _customDiskOfferingMaxSize)) { - throw new InvalidParameterValueException("Volume size: " + sizeInGB + "GB is out of allowed range. Max: " + _customDiskOfferingMaxSize + " Min:" + - _customDiskOfferingMinSize); + Long customDiskOfferingMaxSize = _volumeMgr.CustomDiskOfferingMaxSize.value(); + Long customDiskOfferingMinSize = _volumeMgr.CustomDiskOfferingMinSize.value(); + + if ((sizeInGB < customDiskOfferingMinSize) || (sizeInGB > customDiskOfferingMaxSize)) { + throw new InvalidParameterValueException("Volume size: " + sizeInGB + "GB is out of allowed range. Max: " + customDiskOfferingMaxSize + " Min:" + + customDiskOfferingMinSize); } } @@ -571,14 +603,16 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic } if (snapshotCheck.getState() != Snapshot.State.BackedUp) { - throw new InvalidParameterValueException("Snapshot id=" + snapshotId + " is not in " + Snapshot.State.BackedUp + - " state yet and can't be used for volume creation"); + throw new InvalidParameterValueException("Snapshot id=" + snapshotId + " is not in " + Snapshot.State.BackedUp + " state yet and can't be used for volume creation"); } parentVolume = _volsDao.findByIdIncludingRemoved(snapshotCheck.getVolumeId()); diskOfferingId = snapshotCheck.getDiskOfferingId(); diskOffering = _diskOfferingDao.findById(diskOfferingId); - zoneId = snapshotCheck.getDataCenterId(); + if (zoneId == null) { + // if zoneId is not provided, we default to create volume in the same zone as the snapshot zone. + zoneId = snapshotCheck.getDataCenterId(); + } size = snapshotCheck.getSize(); // ; disk offering is used for tags // purposes @@ -631,15 +665,14 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic userSpecifiedName = getRandomVolumeName(); } - VolumeVO volume = commitVolume(cmd, caller, ownerId, displayVolumeEnabled, zoneId, diskOfferingId, size, minIops, - maxIops, parentVolume, userSpecifiedName, _uuidMgr.generateUuid(Volume.class, cmd.getCustomId())); + VolumeVO volume = commitVolume(cmd, caller, ownerId, displayVolumeEnabled, zoneId, diskOfferingId, size, minIops, maxIops, parentVolume, userSpecifiedName, + _uuidMgr.generateUuid(Volume.class, cmd.getCustomId())); return volume; } private VolumeVO commitVolume(final CreateVolumeCmd cmd, final Account caller, final long ownerId, final Boolean displayVolumeEnabled, final Long zoneId, - final Long diskOfferingId, final Long size, final Long minIops, final Long maxIops, final VolumeVO parentVolume, - final String userSpecifiedName, final String uuid) { + final Long diskOfferingId, final Long size, final Long minIops, final Long maxIops, final VolumeVO parentVolume, final String userSpecifiedName, final String uuid) { return Transaction.execute(new TransactionCallback() { @Override public VolumeVO doInTransaction(TransactionStatus status) { @@ -669,7 +702,7 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic if (cmd.getSnapshotId() == null) { // for volume created from snapshot, create usage event after volume creation UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), - diskOfferingId, null, size, Volume.class.getName(), volume.getUuid()); + diskOfferingId, null, size, Volume.class.getName(), volume.getUuid()); } CallContext.current().setEventDetails("Volume Id: " + volume.getId()); @@ -734,24 +767,27 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic if (!created) { s_logger.trace("Decrementing volume resource count for account id=" + volume.getAccountId() + " as volume failed to create on the backend"); _resourceLimitMgr.decrementResourceCount(volume.getAccountId(), ResourceType.volume, cmd.getDisplayVolume()); - _resourceLimitMgr.decrementResourceCount(volume.getAccountId(), ResourceType.primary_storage, cmd.getDisplayVolume(), new Long(volume.getSize())); + _resourceLimitMgr.recalculateResourceCount(volume.getAccountId(), volume.getDomainId(), ResourceType.primary_storage.getOrdinal()); } } } - protected VolumeVO createVolumeFromSnapshot(VolumeVO volume, long snapshotId, Long vmId) - throws StorageUnavailableException { + protected VolumeVO createVolumeFromSnapshot(VolumeVO volume, long snapshotId, Long vmId) throws StorageUnavailableException { VolumeInfo createdVolume = null; SnapshotVO snapshot = _snapshotDao.findById(snapshotId); + long snapshotVolId = snapshot.getVolumeId(); UserVmVO vm = null; if (vmId != null) { vm = _userVmDao.findById(vmId); } + + // sync old snapshots to region store if necessary + createdVolume = _volumeMgr.createVolumeFromSnapshot(volume, snapshot, vm); UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, createdVolume.getAccountId(), createdVolume.getDataCenterId(), createdVolume.getId(), - createdVolume.getName(), createdVolume.getDiskOfferingId(), null, createdVolume.getSize(), Volume.class.getName(), createdVolume.getUuid()); + createdVolume.getName(), createdVolume.getDiskOfferingId(), null, createdVolume.getSize(), Volume.class.getName(), createdVolume.getUuid()); return _volsDao.findById(createdVolume.getId()); } @@ -783,8 +819,8 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic } /* Only works for KVM/Xen for now */ - if (_volsDao.getHypervisorType(volume.getId()) != HypervisorType.KVM && _volsDao.getHypervisorType(volume.getId()) != HypervisorType.XenServer && - _volsDao.getHypervisorType(volume.getId()) != HypervisorType.VMware) { + if (_volsDao.getHypervisorType(volume.getId()) != HypervisorType.KVM && _volsDao.getHypervisorType(volume.getId()) != HypervisorType.XenServer + && _volsDao.getHypervisorType(volume.getId()) != HypervisorType.VMware) { throw new InvalidParameterValueException("Cloudstack currently only supports volumes marked as KVM or XenServer hypervisor for resize"); } @@ -867,15 +903,64 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic * the actual disk size */ if (currentSize > newSize && !shrinkOk) { - throw new InvalidParameterValueException("Going from existing size of " + currentSize + " to size of " + newSize + - " would shrink the volume, need to sign off by supplying the shrinkok parameter with value of true"); + throw new InvalidParameterValueException("Going from existing size of " + currentSize + " to size of " + newSize + + " would shrink the volume, need to sign off by supplying the shrinkok parameter with value of true"); } if (!shrinkOk) { /* Check resource limit for this account on primary storage resource */ - _resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(volume.getAccountId()), ResourceType.primary_storage, volume.isDisplayVolume(), new Long(newSize - currentSize)); + _resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(volume.getAccountId()), ResourceType.primary_storage, volume.isDisplayVolume(), new Long(newSize + - currentSize)); } + if (userVm != null) { + // serialize VM operation + AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); + if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) { + // avoid re-entrance + + VmWorkJobVO placeHolder = null; + if (VmJobEnabled.value()) { + placeHolder = createPlaceHolderWork(userVm.getId()); + } + try { + return orchestrateResizeVolume(volume.getId(), currentSize, newSize, + newDiskOffering != null ? cmd.getNewDiskOfferingId() : null, shrinkOk); + } finally { + if (VmJobEnabled.value()) + _workJobDao.expunge(placeHolder.getId()); + } + + } else { + Outcome outcome = resizeVolumeThroughJobQueue(userVm.getId(), volume.getId(), currentSize, newSize, + newDiskOffering != null ? cmd.getNewDiskOfferingId() : null, shrinkOk); + + Volume vol = null; + try { + vol = outcome.get(); + } catch (InterruptedException e) { + throw new RuntimeException("Operation is interrupted", e); + } catch (java.util.concurrent.ExecutionException e) { + throw new RuntimeException("Execution excetion", e); + } + + Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); + if (jobResult != null) { + if (jobResult instanceof ConcurrentOperationException) + throw (ConcurrentOperationException)jobResult; + else if (jobResult instanceof Throwable) + throw new RuntimeException("Unexpected exception", (Throwable)jobResult); + } + return volume; + } + } + return orchestrateResizeVolume(volume.getId(), currentSize, newSize, + newDiskOffering != null ? cmd.getNewDiskOfferingId() : null, shrinkOk); + } + + private VolumeVO orchestrateResizeVolume(long volumeId, long currentSize, long newSize, Long newDiskOfferingId, boolean shrinkOk) { + VolumeVO volume = _volsDao.findById(volumeId); + UserVmVO userVm = _userVmDao.findById(volume.getInstanceId()); /* * get a list of hosts to send the commands to, try the system the * associated vm is running on first, then the last known place it ran. @@ -913,13 +998,13 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic volume = _volsDao.findById(volume.getId()); - if (newDiskOffering != null) { - volume.setDiskOfferingId(cmd.getNewDiskOfferingId()); + if (newDiskOfferingId != null) { + volume.setDiskOfferingId(newDiskOfferingId); } _volsDao.update(volume.getId(), volume); // Log usage event for volumes belonging user VM's only UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_RESIZE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), - volume.getDiskOfferingId(), volume.getTemplateId(), volume.getSize(), Volume.class.getName(), volume.getUuid()); + volume.getDiskOfferingId(), volume.getTemplateId(), volume.getSize(), Volume.class.getName(), volume.getUuid()); /* Update resource count for the account on primary storage resource */ if (!shrinkOk) { @@ -980,14 +1065,14 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic /* If volume is in primary storage, decrement primary storage count else decrement secondary storage count (in case of upload volume). */ if (volume.getFolder() != null || volume.getPath() != null || volume.getState() == Volume.State.Allocated) { - _resourceLimitMgr.decrementResourceCount(volume.getAccountId(), ResourceType.primary_storage, volume.isDisplayVolume(), new Long(volume.getSize())); + _resourceLimitMgr.recalculateResourceCount(volume.getAccountId(), volume.getDomainId(), ResourceType.primary_storage.getOrdinal()); } else { _resourceLimitMgr.recalculateResourceCount(volume.getAccountId(), volume.getDomainId(), ResourceType.secondary_storage.getOrdinal()); } // Log usage event for volumes belonging user VM's only UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_DELETE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), - Volume.class.getName(), volume.getUuid()); + Volume.class.getName(), volume.getUuid()); } } // Mark volume as removed if volume has not been created on primary or secondary @@ -1031,12 +1116,48 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic @Override public Volume attachVolumeToVM(AttachVolumeCmd command) { - Long vmId = command.getVirtualMachineId(); - Long volumeId = command.getId(); - Long deviceId = command.getDeviceId(); - return attachVolumeToVM(vmId, volumeId, deviceId); + + AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); + if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) { + // avoid re-entrance + + VmWorkJobVO placeHolder = null; + if (VmJobEnabled.value()) { + placeHolder = createPlaceHolderWork(command.getVirtualMachineId()); + } + try { + return orchestrateAttachVolumeToVM(command.getVirtualMachineId(), command.getId(), command.getDeviceId()); + } finally { + if (VmJobEnabled.value()) + _workJobDao.expunge(placeHolder.getId()); + } + + } else { + Outcome outcome = attachVolumeToVmThroughJobQueue(command.getVirtualMachineId(), command.getId(), command.getDeviceId()); + + Volume vol = null; + try { + vol = outcome.get(); + } catch (InterruptedException e) { + throw new RuntimeException("Operation is interrupted", e); + } catch (java.util.concurrent.ExecutionException e) { + throw new RuntimeException("Execution excetion", e); + } + + Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); + if (jobResult != null) { + if (jobResult instanceof ConcurrentOperationException) + throw (ConcurrentOperationException)jobResult; + else if (jobResult instanceof Throwable) + throw new RuntimeException("Unexpected exception", (Throwable)jobResult); + } + return vol; + } } + private Volume orchestrateAttachVolumeToVM(Long vmId, Long volumeId, Long deviceId) { + return attachVolumeToVM(vmId, volumeId, deviceId); + } @ActionEvent(eventType = EventTypes.EVENT_VOLUME_ATTACH, eventDescription = "attaching volume", async = true) public Volume attachVolumeToVM(Long vmId, Long volumeId, Long deviceId) { @@ -1082,8 +1203,7 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic List existingDataVolumes = _volsDao.findByInstanceAndType(vmId, Volume.Type.DATADISK); int maxDataVolumesSupported = getMaxDataVolumesSupported(vm); if (existingDataVolumes.size() >= maxDataVolumesSupported) { - throw new InvalidParameterValueException("The specified VM already has the maximum number of data disks (" + maxDataVolumesSupported + - "). Please specify another VM."); + throw new InvalidParameterValueException("The specified VM already has the maximum number of data disks (" + maxDataVolumesSupported + "). Please specify another VM."); } // Check that the VM and the volume are in the same zone @@ -1139,7 +1259,14 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic deviceId = getDeviceId(vmId, deviceId); VolumeInfo volumeOnPrimaryStorage = volume; - if (volume.getState().equals(Volume.State.Allocated) || volume.getState() == Volume.State.Uploaded) { + //don't create volume on primary storage if its being attached to the vm which Root's volume hasn't been created yet + List existingRootVolumes = _volsDao.findByInstanceAndType(vmId, Volume.Type.ROOT); + boolean rootVolumeCreatedOnPrimary = true; + if (existingRootVolumes.get(0).getState().equals(Volume.State.Allocated)) { + rootVolumeCreatedOnPrimary = false; + } + + if ((volume.getState().equals(Volume.State.Allocated) && rootVolumeCreatedOnPrimary) || volume.getState() == Volume.State.Uploaded) { try { volumeOnPrimaryStorage = _volumeMgr.createVolumeOnPrimaryStorage(vm, rootVolumeOfVm, volume, rootDiskHyperType); } catch (NoTransitionException e) { @@ -1155,15 +1282,14 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic if (moveVolumeNeeded) { PrimaryDataStoreInfo primaryStore = (PrimaryDataStoreInfo)volumeOnPrimaryStorage.getDataStore(); if (primaryStore.isLocal()) { - throw new CloudRuntimeException("Failed to attach local data volume " + volume.getName() + " to VM " + vm.getDisplayName() + - " as migration of local data volume is not allowed"); + throw new CloudRuntimeException("Failed to attach local data volume " + volume.getName() + " to VM " + vm.getDisplayName() + + " as migration of local data volume is not allowed"); } StoragePoolVO vmRootVolumePool = _storagePoolDao.findById(rootVolumeOfVm.getPoolId()); try { - volumeOnPrimaryStorage = - _volumeMgr.moveVolume(volumeOnPrimaryStorage, vmRootVolumePool.getDataCenterId(), vmRootVolumePool.getPodId(), vmRootVolumePool.getClusterId(), - dataDiskHyperType); + volumeOnPrimaryStorage = _volumeMgr.moveVolume(volumeOnPrimaryStorage, vmRootVolumePool.getDataCenterId(), vmRootVolumePool.getPodId(), + vmRootVolumePool.getClusterId(), dataDiskHyperType); } catch (ConcurrentOperationException e) { s_logger.debug("move volume failed", e); throw new CloudRuntimeException("move volume failed", e); @@ -1183,7 +1309,6 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic } _asyncMgr.updateAsyncJobAttachment(job.getId(), "volume", volumeId); - _asyncMgr.updateAsyncJobStatus(job.getId(), BaseCmd.PROGRESS_INSTANCE_CREATED, Long.toString(volumeId)); } VolumeVO newVol = _volumeDao.findById(volumeOnPrimaryStorage.getId()); @@ -1201,6 +1326,10 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic volume.setPath(path); } + if (displayVolume != null) { + volume.setDisplayVolume(displayVolume); + } + if (state != null) { try { Volume.State volumeState = Volume.State.valueOf(state); @@ -1218,7 +1347,7 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic volume.setPoolId(pool.getId()); } - if (customId != null){ + if (customId != null) { _uuidMgr.checkUuid(customId, Volume.class); volume.setUuid(customId); } @@ -1238,9 +1367,9 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic @ActionEvent(eventType = EventTypes.EVENT_VOLUME_DETACH, eventDescription = "detaching volume", async = true) public Volume detachVolumeFromVM(DetachVolumeCmd cmmd) { Account caller = CallContext.current().getCallingAccount(); - if ((cmmd.getId() == null && cmmd.getDeviceId() == null && cmmd.getVirtualMachineId() == null) || - (cmmd.getId() != null && (cmmd.getDeviceId() != null || cmmd.getVirtualMachineId() != null)) || - (cmmd.getId() == null && (cmmd.getDeviceId() == null || cmmd.getVirtualMachineId() == null))) { + if ((cmmd.getId() == null && cmmd.getDeviceId() == null && cmmd.getVirtualMachineId() == null) + || (cmmd.getId() != null && (cmmd.getDeviceId() != null || cmmd.getVirtualMachineId() != null)) + || (cmmd.getId() == null && (cmmd.getDeviceId() == null || cmmd.getVirtualMachineId() == null))) { throw new InvalidParameterValueException("Please provide either a volume id, or a tuple(device id, instance id)"); } @@ -1300,11 +1429,51 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic } _asyncMgr.updateAsyncJobAttachment(job.getId(), "volume", volumeId); - _asyncMgr.updateAsyncJobStatus(job.getId(), BaseCmd.PROGRESS_INSTANCE_CREATED, volumeId.toString()); } - String errorMsg = "Failed to detach volume: " + volume.getName() + " from VM: " + vm.getHostName(); - boolean sendCommand = (vm.getState() == State.Running); + AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); + if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) { + // avoid re-entrance + VmWorkJobVO placeHolder = null; + if (VmJobEnabled.value()) { + placeHolder = createPlaceHolderWork(vmId); + } + try { + return orchestrateDetachVolumeFromVM(vmId, volumeId); + } finally { + if (VmJobEnabled.value()) + _workJobDao.expunge(placeHolder.getId()); + } + } else { + Outcome outcome = detachVolumeFromVmThroughJobQueue(vmId, volumeId); + + Volume vol = null; + try { + vol = outcome.get(); + } catch (InterruptedException e) { + throw new RuntimeException("Operation is interrupted", e); + } catch (java.util.concurrent.ExecutionException e) { + throw new RuntimeException("Execution excetion", e); + } + + Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); + if (jobResult != null) { + if (jobResult instanceof ConcurrentOperationException) + throw (ConcurrentOperationException)jobResult; + else if (jobResult instanceof Throwable) + throw new RuntimeException("Unexpected exception", (Throwable)jobResult); + } + return vol; + } + } + + private Volume orchestrateDetachVolumeFromVM(long vmId, long volumeId) { + + Volume volume = _volumeDao.findById(volumeId); + VMInstanceVO vm = _vmInstanceDao.findById(vmId); + + String errorMsg = "Failed to detach volume " + volume.getName() + " from VM " + vm.getHostName(); + boolean sendCommand = vm.getState() == State.Running; Long hostId = vm.getHostId(); @@ -1318,11 +1487,20 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic } } + HostVO host = null; + StoragePoolVO volumePool = _storagePoolDao.findById(volume.getPoolId()); + + if (hostId != null) { + host = _hostDao.findById(hostId); + + if (host != null && host.getHypervisorType() == HypervisorType.XenServer && volumePool.isManaged()) { + sendCommand = true; + } + } + Answer answer = null; if (sendCommand) { - StoragePoolVO volumePool = _storagePoolDao.findById(volume.getPoolId()); - DataTO volTO = volFactory.getVolume(volume.getId()).getTO(); DiskTO disk = new DiskTO(volTO, volume.getDeviceId(), volume.getPath(), volume.getVolumeType()); @@ -1346,6 +1524,11 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic // Mark the volume as detached _volsDao.detachVolume(volume.getId()); + // volume.getPoolId() should be null if the VM we are attaching the disk to has never been started before + DataStore dataStore = volume.getPoolId() != null ? dataStoreMgr.getDataStore(volume.getPoolId(), DataStoreRole.Primary) : null; + + volService.disconnectVolumeFromHost(volFactory.getVolume(volume.getId()), host, dataStore); + return _volsDao.findById(volumeId); } else { @@ -1421,6 +1604,59 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic throw new InvalidParameterValueException("Migration of volume from local storage pool is not supported"); } + if (vm != null) { + // serialize VM operation + AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); + if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) { + // avoid re-entrance + + VmWorkJobVO placeHolder = null; + if (VmJobEnabled.value()) { + placeHolder = createPlaceHolderWork(vm.getId()); + } + try { + return orchestrateMigrateVolume(vol.getId(), destPool.getId(), liveMigrateVolume); + } finally { + if (VmJobEnabled.value()) + _workJobDao.expunge(placeHolder.getId()); + } + + } else { + Outcome outcome = migrateVolumeThroughJobQueue(vm.getId(), vol.getId(), destPool.getId(), liveMigrateVolume); + + try { + outcome.get(); + } catch (InterruptedException e) { + throw new RuntimeException("Operation is interrupted", e); + } catch (java.util.concurrent.ExecutionException e) { + throw new RuntimeException("Execution excetion", e); + } + + Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); + if (jobResult != null) { + if (jobResult instanceof ConcurrentOperationException) + throw (ConcurrentOperationException)jobResult; + else if (jobResult instanceof Throwable) + throw new RuntimeException("Unexpected exception", (Throwable)jobResult); + } + + // retrieve the migrated new volume from job result + if (jobResult != null && jobResult instanceof Long) { + return _entityMgr.findById(VolumeVO.class, ((Long)jobResult).longValue()); + } + return null; + } + } + + return orchestrateMigrateVolume(vol.getId(), destPool.getId(), liveMigrateVolume); + } + + private Volume orchestrateMigrateVolume(long volumeId, long destPoolId, boolean liveMigrateVolume) { + VolumeVO vol = _volsDao.findById(volumeId); + assert (vol != null); + StoragePool destPool = (StoragePool)dataStoreMgr.getDataStore(destPoolId, DataStoreRole.Primary); + assert (destPool != null); + Volume newVol = null; if (liveMigrateVolume) { newVol = liveMigrateVolume(vol, destPool); @@ -1456,14 +1692,82 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic @Override public Snapshot takeSnapshot(Long volumeId, Long policyId, Long snapshotId, Account account, boolean quiescevm) throws ResourceAllocationException { + VolumeInfo volume = volFactory.getVolume(volumeId); if (volume == null) { throw new InvalidParameterValueException("Creating snapshot failed due to volume:" + volumeId + " doesn't exist"); } if (volume.getState() != Volume.State.Ready) { - throw new InvalidParameterValueException("VolumeId: " + volumeId + " is not in " + Volume.State.Ready + " state but " + volume.getState() + - ". Cannot take snapshot."); + throw new InvalidParameterValueException("VolumeId: " + volumeId + " is not in " + Volume.State.Ready + " state but " + volume.getState() + ". Cannot take snapshot."); + } + + VMInstanceVO vm = null; + if (volume.getInstanceId() != null) + vm = _vmInstanceDao.findById(volume.getInstanceId()); + + if (vm != null) { + // serialize VM operation + AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); + if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) { + // avoid re-entrance + + VmWorkJobVO placeHolder = null; + if (VmJobEnabled.value()) { + placeHolder = createPlaceHolderWork(vm.getId()); + } + try { + return orchestrateTakeVolumeSnapshot(volumeId, policyId, snapshotId, account, quiescevm); + } finally { + if (VmJobEnabled.value()) + _workJobDao.expunge(placeHolder.getId()); + } + + } else { + Outcome outcome = takeVolumeSnapshotThroughJobQueue(vm.getId(), volumeId, policyId, snapshotId, account.getId(), quiescevm); + + try { + outcome.get(); + } catch (InterruptedException e) { + throw new RuntimeException("Operation is interrupted", e); + } catch (java.util.concurrent.ExecutionException e) { + throw new RuntimeException("Execution excetion", e); + } + + Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); + if (jobResult != null) { + if (jobResult instanceof ConcurrentOperationException) + throw (ConcurrentOperationException)jobResult; + else if (jobResult instanceof ResourceAllocationException) + throw (ResourceAllocationException)jobResult; + else if (jobResult instanceof Throwable) + throw new RuntimeException("Unexpected exception", (Throwable)jobResult); + } + + return _snapshotDao.findById(snapshotId); + } + } else { + CreateSnapshotPayload payload = new CreateSnapshotPayload(); + payload.setSnapshotId(snapshotId); + payload.setSnapshotPolicyId(policyId); + payload.setAccount(account); + payload.setQuiescevm(quiescevm); + volume.addPayload(payload); + return volService.takeSnapshot(volume); + } + } + + private Snapshot orchestrateTakeVolumeSnapshot(Long volumeId, Long policyId, Long snapshotId, Account account, boolean quiescevm) + throws ResourceAllocationException { + + VolumeInfo volume = volFactory.getVolume(volumeId); + + if (volume == null) { + throw new InvalidParameterValueException("Creating snapshot failed due to volume:" + volumeId + " doesn't exist"); + } + + if (volume.getState() != Volume.State.Ready) { + throw new InvalidParameterValueException("VolumeId: " + volumeId + " is not in " + Volume.State.Ready + " state but " + volume.getState() + ". Cannot take snapshot."); } CreateSnapshotPayload payload = new CreateSnapshotPayload(); @@ -1493,8 +1797,7 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic } if (volume.getState() != Volume.State.Ready) { - throw new InvalidParameterValueException("VolumeId: " + volumeId + " is not in " + Volume.State.Ready + " state but " + volume.getState() + - ". Cannot take snapshot."); + throw new InvalidParameterValueException("VolumeId: " + volumeId + " is not in " + Volume.State.Ready + " state but " + volume.getState() + ". Cannot take snapshot."); } if (volume.getTemplateId() != null) { @@ -1544,8 +1847,8 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic // instance is stopped if (volume.getInstanceId() != null && ApiDBUtils.findVMInstanceById(volume.getInstanceId()).getState() != State.Stopped) { s_logger.debug("Invalid state of the volume with ID: " + volumeId + ". It should be either detached or the VM should be in stopped state."); - PermissionDeniedException ex = - new PermissionDeniedException("Invalid state of the volume with specified ID. It should be either detached or the VM should be in stopped state."); + PermissionDeniedException ex = new PermissionDeniedException( + "Invalid state of the volume with specified ID. It should be either detached or the VM should be in stopped state."); ex.addProxyObject(volume.getUuid(), "volumeId"); throw ex; } @@ -1673,8 +1976,8 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic if (storeForDataStoreScope.getScopeId().equals(vmClusterId)) { return false; } - } else if (storeForDataStoreScope.getScopeType() == ScopeType.HOST && - (storeForRootStoreScope.getScopeType() == ScopeType.CLUSTER || storeForRootStoreScope.getScopeType() == ScopeType.ZONE)) { + } else if (storeForDataStoreScope.getScopeType() == ScopeType.HOST + && (storeForRootStoreScope.getScopeType() == ScopeType.CLUSTER || storeForRootStoreScope.getScopeType() == ScopeType.ZONE)) { Long hostId = _vmInstanceDao.findById(rootVolumeOfVm.getInstanceId()).getHostId(); if (storeForDataStoreScope.getScopeId().equals(hostId)) { return false; @@ -1687,26 +1990,51 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic } private VolumeVO sendAttachVolumeCommand(UserVmVO vm, VolumeVO volumeToAttach, Long deviceId) { - String errorMsg = "Failed to attach volume: " + volumeToAttach.getName() + " to VM: " + vm.getHostName(); - boolean sendCommand = (vm.getState() == State.Running); + String errorMsg = "Failed to attach volume " + volumeToAttach.getName() + " to VM " + vm.getHostName(); + boolean sendCommand = vm.getState() == State.Running; AttachAnswer answer = null; Long hostId = vm.getHostId(); + if (hostId == null) { hostId = vm.getLastHostId(); + HostVO host = _hostDao.findById(hostId); + if (host != null && host.getHypervisorType() == HypervisorType.VMware) { sendCommand = true; } } - StoragePoolVO volumeToAttachStoragePool = null; + HostVO host = null; + StoragePoolVO volumeToAttachStoragePool = _storagePoolDao.findById(volumeToAttach.getPoolId()); + + if (hostId != null) { + host = _hostDao.findById(hostId); + + if (host != null && host.getHypervisorType() == HypervisorType.XenServer && volumeToAttachStoragePool.isManaged()) { + sendCommand = true; + } + } + + // volumeToAttachStoragePool should be null if the VM we are attaching the disk to has never been started before + DataStore dataStore = volumeToAttachStoragePool != null ? dataStoreMgr.getDataStore(volumeToAttachStoragePool.getId(), DataStoreRole.Primary) : null; + + // if we don't have a host, the VM we are attaching the disk to has never been started before + if (host != null) { + try { + volService.connectVolumeToHost(volFactory.getVolume(volumeToAttach.getId()), host, dataStore); + } + catch (Exception e) { + volService.disconnectVolumeFromHost(volFactory.getVolume(volumeToAttach.getId()), host, dataStore); + + throw new CloudRuntimeException(e.getMessage()); + } + } if (sendCommand) { - volumeToAttachStoragePool = _storagePoolDao.findById(volumeToAttach.getPoolId()); - - HostVO host = _hostDao.findById(hostId); - - if (host.getHypervisorType() == HypervisorType.KVM && volumeToAttachStoragePool.isManaged() && volumeToAttach.getPath() == null) { + if (host.getHypervisorType() == HypervisorType.KVM && + volumeToAttachStoragePool.isManaged() && + volumeToAttach.getPath() == null) { volumeToAttach.setPath(volumeToAttach.get_iScsiName()); _volsDao.update(volumeToAttach.getId(), volumeToAttach); @@ -1717,9 +2045,7 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic AttachCommand cmd = new AttachCommand(disk, vm.getInstanceName()); - VolumeInfo volumeInfo = volFactory.getVolume(volumeToAttach.getId()); - DataStore dataStore = dataStoreMgr.getDataStore(volumeToAttachStoragePool.getId(), DataStoreRole.Primary); - ChapInfo chapInfo = volService.getChapInfo(volumeInfo, dataStore); + ChapInfo chapInfo = volService.getChapInfo(volFactory.getVolume(volumeToAttach.getId()), dataStore); Map details = new HashMap(); @@ -1741,6 +2067,8 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic try { answer = (AttachAnswer)_agentMgr.send(hostId, cmd); } catch (Exception e) { + volService.disconnectVolumeFromHost(volFactory.getVolume(volumeToAttach.getId()), host, dataStore); + throw new CloudRuntimeException(errorMsg + " due to: " + e.getMessage()); } } @@ -1777,6 +2105,9 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic errorMsg += "; " + details; } } + + volService.disconnectVolumeFromHost(volFactory.getVolume(volumeToAttach.getId()), host, dataStore); + throw new CloudRuntimeException(errorMsg); } } @@ -1831,8 +2162,6 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic @Override public boolean configure(String name, Map params) { - String _customDiskOfferingMinSizeStr = _configDao.getValue(Config.CustomDiskOfferingMinSize.toString()); - _customDiskOfferingMinSize = NumbersUtil.parseInt(_customDiskOfferingMinSizeStr, Integer.parseInt(Config.CustomDiskOfferingMinSize.getDefaultValue())); String maxVolumeSizeInGbString = _configDao.getValue(Config.MaxVolumeSize.toString()); _maxVolumeSizeInGb = NumbersUtil.parseLong(maxVolumeSizeInGbString, 2000); @@ -1848,4 +2177,331 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic _storagePoolAllocators = storagePoolAllocators; } + public class VmJobVolumeOutcome extends OutcomeImpl { + private long _volumeId; + + public VmJobVolumeOutcome(final AsyncJob job, final long volumeId) { + super(Volume.class, job, VmJobCheckInterval.value(), new Predicate() { + @Override + public boolean checkCondition() { + AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, job.getId()); + assert (jobVo != null); + if (jobVo == null || jobVo.getStatus() != JobInfo.Status.IN_PROGRESS) + return true; + + return false; + } + }, AsyncJob.Topics.JOB_STATE); + _volumeId = volumeId; + } + + @Override + protected Volume retrieve() { + return _volumeDao.findById(_volumeId); + } + } + + public class VmJobSnapshotOutcome extends OutcomeImpl { + private long _snapshotId; + + public VmJobSnapshotOutcome(final AsyncJob job, final long snapshotId) { + super(Snapshot.class, job, VmJobCheckInterval.value(), new Predicate() { + @Override + public boolean checkCondition() { + AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, job.getId()); + assert (jobVo != null); + if (jobVo == null || jobVo.getStatus() != JobInfo.Status.IN_PROGRESS) + return true; + + return false; + } + }, AsyncJob.Topics.JOB_STATE); + _snapshotId = snapshotId; + } + + @Override + protected Snapshot retrieve() { + return _snapshotDao.findById(_snapshotId); + } + } + + public Outcome attachVolumeToVmThroughJobQueue(final Long vmId, final Long volumeId, final Long deviceId) { + + final CallContext context = CallContext.current(); + final User callingUser = context.getCallingUser(); + final Account callingAccount = context.getCallingAccount(); + + final VMInstanceVO vm = _vmInstanceDao.findById(vmId); + + Object[] result = Transaction.execute(new TransactionCallback() { + @Override + public Object[] doInTransaction(TransactionStatus status) { + VmWorkJobVO workJob = null; + + _vmInstanceDao.lockRow(vm.getId(), true); + workJob = new VmWorkJobVO(context.getContextId()); + + workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkAttachVolume.class.getName()); + + workJob.setAccountId(callingAccount.getId()); + workJob.setUserId(callingUser.getId()); + workJob.setStep(VmWorkJobVO.Step.Starting); + workJob.setVmType(VirtualMachine.Type.Instance); + workJob.setVmInstanceId(vm.getId()); + workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId()); + + // save work context info (there are some duplications) + VmWorkAttachVolume workInfo = new VmWorkAttachVolume(callingUser.getId(), callingAccount.getId(), vm.getId(), VolumeApiServiceImpl.VM_WORK_JOB_HANDLER, volumeId, + deviceId); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + + _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId()); + + AsyncJobVO jobVo = _jobMgr.getAsyncJob(workJob.getId()); + s_logger.debug("New job " + workJob.getId() + ", result field: " + jobVo.getResult()); + + return new Object[] {workJob, new Long(workJob.getId())}; + } + }); + + final long jobId = (Long)result[1]; + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + + return new VmJobVolumeOutcome((VmWorkJobVO)result[0], + volumeId); + } + + public Outcome detachVolumeFromVmThroughJobQueue(final Long vmId, final Long volumeId) { + + final CallContext context = CallContext.current(); + final User callingUser = context.getCallingUser(); + final Account callingAccount = context.getCallingAccount(); + + final VMInstanceVO vm = _vmInstanceDao.findById(vmId); + + Object[] result = Transaction.execute(new TransactionCallback() { + @Override + public Object[] doInTransaction(TransactionStatus status) { + VmWorkJobVO workJob = null; + + _vmInstanceDao.lockRow(vm.getId(), true); + workJob = new VmWorkJobVO(context.getContextId()); + + workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkDetachVolume.class.getName()); + + workJob.setAccountId(callingAccount.getId()); + workJob.setUserId(callingUser.getId()); + workJob.setStep(VmWorkJobVO.Step.Starting); + workJob.setVmType(VirtualMachine.Type.Instance); + workJob.setVmInstanceId(vm.getId()); + workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId()); + + // save work context info (there are some duplications) + VmWorkDetachVolume workInfo = new VmWorkDetachVolume(callingUser.getId(), callingAccount.getId(), vm.getId(), VolumeApiServiceImpl.VM_WORK_JOB_HANDLER, volumeId); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + + _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId()); + + return new Object[] {workJob, new Long(workJob.getId())}; + } + }); + + final long jobId = (Long)result[1]; + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + + return new VmJobVolumeOutcome((VmWorkJobVO)result[0], + volumeId); + } + + public Outcome resizeVolumeThroughJobQueue(final Long vmId, final long volumeId, + final long currentSize, final long newSize, final Long newServiceOfferingId, final boolean shrinkOk) { + + final CallContext context = CallContext.current(); + final User callingUser = context.getCallingUser(); + final Account callingAccount = context.getCallingAccount(); + + final VMInstanceVO vm = _vmInstanceDao.findById(vmId); + + Object[] result = Transaction.execute(new TransactionCallback() { + @Override + public Object[] doInTransaction(TransactionStatus status) { + VmWorkJobVO workJob = null; + + _vmInstanceDao.lockRow(vm.getId(), true); + workJob = new VmWorkJobVO(context.getContextId()); + + workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkResizeVolume.class.getName()); + + workJob.setAccountId(callingAccount.getId()); + workJob.setUserId(callingUser.getId()); + workJob.setStep(VmWorkJobVO.Step.Starting); + workJob.setVmType(VirtualMachine.Type.Instance); + workJob.setVmInstanceId(vm.getId()); + workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId()); + + // save work context info (there are some duplications) + VmWorkResizeVolume workInfo = new VmWorkResizeVolume(callingUser.getId(), callingAccount.getId(), vm.getId(), + VolumeApiServiceImpl.VM_WORK_JOB_HANDLER, volumeId, currentSize, newSize, newServiceOfferingId, shrinkOk); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + + _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId()); + + return new Object[] {workJob, new Long(workJob.getId())}; + } + }); + + final long jobId = (Long)result[1]; + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + + return new VmJobVolumeOutcome((VmWorkJobVO)result[0], + volumeId); + } + + public Outcome migrateVolumeThroughJobQueue(final Long vmId, final long volumeId, + final long destPoolId, final boolean liveMigrate) { + + final CallContext context = CallContext.current(); + final User callingUser = context.getCallingUser(); + final Account callingAccount = context.getCallingAccount(); + + final VMInstanceVO vm = _vmInstanceDao.findById(vmId); + + Object[] result = Transaction.execute(new TransactionCallback() { + @Override + public Object[] doInTransaction(TransactionStatus status) { + VmWorkJobVO workJob = null; + + _vmInstanceDao.lockRow(vm.getId(), true); + workJob = new VmWorkJobVO(context.getContextId()); + + workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkMigrateVolume.class.getName()); + + workJob.setAccountId(callingAccount.getId()); + workJob.setUserId(callingUser.getId()); + workJob.setStep(VmWorkJobVO.Step.Starting); + workJob.setVmType(VirtualMachine.Type.Instance); + workJob.setVmInstanceId(vm.getId()); + workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId()); + + // save work context info (there are some duplications) + VmWorkMigrateVolume workInfo = new VmWorkMigrateVolume(callingUser.getId(), callingAccount.getId(), vm.getId(), + VolumeApiServiceImpl.VM_WORK_JOB_HANDLER, volumeId, destPoolId, liveMigrate); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + + _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId()); + + return new Object[] {workJob, new Long(workJob.getId())}; + } + }); + + final long jobId = (Long)result[1]; + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + + return new VmJobVolumeOutcome((VmWorkJobVO)result[0], + volumeId); + } + + public Outcome takeVolumeSnapshotThroughJobQueue(final Long vmId, final Long volumeId, + final Long policyId, final Long snapshotId, final Long accountId, final boolean quiesceVm) { + + final CallContext context = CallContext.current(); + final User callingUser = context.getCallingUser(); + final Account callingAccount = context.getCallingAccount(); + + final VMInstanceVO vm = _vmInstanceDao.findById(vmId); + + Object[] result = Transaction.execute(new TransactionCallback() { + @Override + public Object[] doInTransaction(TransactionStatus status) { + VmWorkJobVO workJob = null; + + _vmInstanceDao.lockRow(vm.getId(), true); + workJob = new VmWorkJobVO(context.getContextId()); + + workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkTakeVolumeSnapshot.class.getName()); + + workJob.setAccountId(callingAccount.getId()); + workJob.setUserId(callingUser.getId()); + workJob.setStep(VmWorkJobVO.Step.Starting); + workJob.setVmType(VirtualMachine.Type.Instance); + workJob.setVmInstanceId(vm.getId()); + workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId()); + + // save work context info (there are some duplications) + VmWorkTakeVolumeSnapshot workInfo = new VmWorkTakeVolumeSnapshot( + callingUser.getId(), accountId != null ? accountId : callingAccount.getId(), vm.getId(), + VolumeApiServiceImpl.VM_WORK_JOB_HANDLER, volumeId, policyId, snapshotId, quiesceVm); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + + _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId()); + + return new Object[] {workJob, new Long(workJob.getId())}; + } + }); + + final long jobId = (Long)result[1]; + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + + return new VmJobSnapshotOutcome((VmWorkJobVO)result[0], + snapshotId); + } + + private Pair orchestrateAttachVolumeToVM(VmWorkAttachVolume work) throws Exception { + orchestrateAttachVolumeToVM(work.getVmId(), work.getVolumeId(), work.getDeviceId()); + return new Pair(JobInfo.Status.SUCCEEDED, null); + } + + private Pair orchestrateDetachVolumeFromVM(VmWorkDetachVolume work) throws Exception { + orchestrateDetachVolumeFromVM(work.getVmId(), work.getVolumeId()); + return new Pair(JobInfo.Status.SUCCEEDED, null); + } + + private Pair orchestrateResizeVolume(VmWorkResizeVolume work) throws Exception { + orchestrateResizeVolume(work.getVolumeId(), work.getCurrentSize(), work.getNewSize(), + work.getNewServiceOfferingId(), work.isShrinkOk()); + return new Pair(JobInfo.Status.SUCCEEDED, null); + } + + private Pair orchestrateMigrateVolume(VmWorkMigrateVolume work) throws Exception { + Volume newVol = orchestrateMigrateVolume(work.getVolumeId(), work.getDestPoolId(), work.isLiveMigrate()); + return new Pair(JobInfo.Status.SUCCEEDED, + _jobMgr.marshallResultObject(new Long(newVol.getId()))); + } + + private Pair orchestrateTakeVolumeSnapshot(VmWorkTakeVolumeSnapshot work) throws Exception { + Account account = _accountDao.findById(work.getAccountId()); + orchestrateTakeVolumeSnapshot(work.getVolumeId(), work.getPolicyId(), work.getSnapshotId(), + account, work.isQuiesceVm()); + return new Pair(JobInfo.Status.SUCCEEDED, + _jobMgr.marshallResultObject(work.getSnapshotId())); + } + + @Override + public Pair handleVmWorkJob(VmWork work) throws Exception { + return _jobHandlerProxy.handleVmWorkJob(work); + } + + private VmWorkJobVO createPlaceHolderWork(long instanceId) { + VmWorkJobVO workJob = new VmWorkJobVO(""); + + workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_PLACEHOLDER); + workJob.setCmd(""); + workJob.setCmdInfo(""); + + workJob.setAccountId(0); + workJob.setUserId(0); + workJob.setStep(VmWorkJobVO.Step.Starting); + workJob.setVmType(VirtualMachine.Type.Instance); + workJob.setVmInstanceId(instanceId); + workJob.setInitMsid(ManagementServerNode.getManagementServerId()); + + _workJobDao.persist(workJob); + + return workJob; + } } diff --git a/server/src/com/cloud/storage/download/DownloadListener.java b/server/src/com/cloud/storage/download/DownloadListener.java index 2941b6e2f35..4f9a5605e33 100755 --- a/server/src/com/cloud/storage/download/DownloadListener.java +++ b/server/src/com/cloud/storage/download/DownloadListener.java @@ -122,7 +122,7 @@ public class DownloadListener implements Listener { private StatusTask _statusTask; private TimeoutTask _timeoutTask; private Date _lastUpdated = new Date(); - private String _jobId; + private String jobId; private final Map _stateMap = new HashMap(); private AsyncCompletionCallback _callback; @@ -137,7 +137,7 @@ public class DownloadListener implements Listener { private VolumeService _volumeSrv; // TODO: this constructor should be the one used for template only, remove other template constructor later - public DownloadListener(EndPoint ssAgent, DataStore store, DataObject object, Timer _timer, DownloadMonitorImpl downloadMonitor, DownloadCommand cmd, + public DownloadListener(EndPoint ssAgent, DataStore store, DataObject object, Timer timer, DownloadMonitorImpl downloadMonitor, DownloadCommand cmd, AsyncCompletionCallback callback) { _ssAgent = ssAgent; this.object = object; @@ -145,7 +145,7 @@ public class DownloadListener implements Listener { _cmd = cmd; initStateMachine(); _currState = getState(Status.NOT_DOWNLOADED.toString()); - this._timer = _timer; + this._timer = timer; _timeoutTask = new TimeoutTask(this); this._timer.schedule(_timeoutTask, 3 * STATUS_POLL_INTERVAL); _callback = callback; @@ -306,8 +306,8 @@ public class DownloadListener implements Listener { } } - public void setCommand(DownloadCommand _cmd) { - this._cmd = _cmd; + public void setCommand(DownloadCommand cmd) { + this._cmd = cmd; } public DownloadCommand getCommand() { @@ -318,12 +318,12 @@ public class DownloadListener implements Listener { transition(DownloadEvent.ABANDON_DOWNLOAD, null); } - public void setJobId(String _jobId) { - this._jobId = _jobId; + public void setJobId(String jobId) { + this.jobId = jobId; } public String getJobId() { - return _jobId; + return jobId; } public void scheduleStatusCheck(RequestType request) { diff --git a/server/src/com/cloud/storage/download/DownloadMonitorImpl.java b/server/src/com/cloud/storage/download/DownloadMonitorImpl.java index d9003334f6c..33278afafb5 100755 --- a/server/src/com/cloud/storage/download/DownloadMonitorImpl.java +++ b/server/src/com/cloud/storage/download/DownloadMonitorImpl.java @@ -56,7 +56,6 @@ import com.cloud.agent.api.storage.Proxy; import com.cloud.configuration.Config; import com.cloud.storage.RegisterVolumePayload; import com.cloud.storage.Storage.ImageFormat; -import com.cloud.storage.VMTemplateStorageResourceAssoc; import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; import com.cloud.storage.Volume; import com.cloud.storage.dao.VMTemplateDao; diff --git a/server/src/com/cloud/storage/listener/SnapshotStateListener.java b/server/src/com/cloud/storage/listener/SnapshotStateListener.java index 649aeff4256..45f0c5d7f52 100644 --- a/server/src/com/cloud/storage/listener/SnapshotStateListener.java +++ b/server/src/com/cloud/storage/listener/SnapshotStateListener.java @@ -29,7 +29,6 @@ import org.apache.cloudstack.framework.events.EventBus; import org.apache.cloudstack.framework.events.EventBusException; import com.cloud.event.EventCategory; -import com.cloud.server.ManagementServer; import com.cloud.server.ManagementService; import com.cloud.storage.Snapshot; import com.cloud.storage.Snapshot.Event; @@ -40,7 +39,7 @@ import com.cloud.utils.fsm.StateListener; public class SnapshotStateListener implements StateListener { - protected static EventBus _eventBus = null; + protected static EventBus s_eventBus = null; private static final Logger s_logger = Logger.getLogger(VolumeStateListener.class); @@ -63,7 +62,7 @@ public class SnapshotStateListener implements StateListener pools = _poolDao.listBy(host.getDataCenterId(), host.getPodId(), host.getClusterId(), ScopeType.CLUSTER); List zoneStoragePoolsByTags = _poolDao.findZoneWideStoragePoolsByTags(host.getDataCenterId(), null); List zoneStoragePoolsByHypervisor = _poolDao.findZoneWideStoragePoolsByHypervisor(host.getDataCenterId(), scCmd.getHypervisorType()); diff --git a/server/src/com/cloud/storage/listener/VolumeStateListener.java b/server/src/com/cloud/storage/listener/VolumeStateListener.java index cd78d4ec600..1ab2755117c 100644 --- a/server/src/com/cloud/storage/listener/VolumeStateListener.java +++ b/server/src/com/cloud/storage/listener/VolumeStateListener.java @@ -29,7 +29,6 @@ import org.apache.cloudstack.framework.events.EventBus; import org.apache.cloudstack.framework.events.EventBusException; import com.cloud.event.EventCategory; -import com.cloud.server.ManagementServer; import com.cloud.server.ManagementService; import com.cloud.storage.Volume; import com.cloud.storage.Volume.Event; @@ -39,7 +38,7 @@ import com.cloud.utils.fsm.StateListener; public class VolumeStateListener implements StateListener { - protected static EventBus _eventBus = null; + protected static EventBus s_eventBus = null; private static final Logger s_logger = Logger.getLogger(VolumeStateListener.class); @@ -62,7 +61,7 @@ public class VolumeStateListener implements StateListener private void pubishOnEventBus(String event, String status, Volume vo, State oldState, State newState) { try { - _eventBus = ComponentContext.getComponent(EventBus.class); + s_eventBus = ComponentContext.getComponent(EventBus.class); } catch (NoSuchBeanDefinitionException nbe) { return; // no provider is configured to provide events bus, so just return } @@ -82,7 +81,7 @@ public class VolumeStateListener implements StateListener eventMsg.setDescription(eventDescription); try { - _eventBus.publish(eventMsg); + s_eventBus.publish(eventMsg); } catch (EventBusException e) { s_logger.warn("Failed to state change event on the the event bus."); } diff --git a/server/src/com/cloud/storage/resource/DummySecondaryStorageResource.java b/server/src/com/cloud/storage/resource/DummySecondaryStorageResource.java index 583ad9b8def..ce01a69aa0a 100644 --- a/server/src/com/cloud/storage/resource/DummySecondaryStorageResource.java +++ b/server/src/com/cloud/storage/resource/DummySecondaryStorageResource.java @@ -159,8 +159,8 @@ public class DummySecondaryStorageResource extends ServerResourceBase implements return true; } - public void setUseServiceVm(boolean _useServiceVm) { - this._useServiceVm = _useServiceVm; + public void setUseServiceVm(boolean useServiceVm) { + this._useServiceVm = useServiceVm; } public boolean useServiceVm() { diff --git a/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java b/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java index 5c7557f8865..a5d3d4c2dcf 100755 --- a/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java +++ b/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java @@ -30,18 +30,19 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; -import org.apache.log4j.Logger; - +import org.apache.cloudstack.config.ApiServiceConfiguration; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; import org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; +import org.apache.cloudstack.framework.security.keystore.KeystoreManager; import org.apache.cloudstack.storage.datastore.db.ImageStoreDao; import org.apache.cloudstack.storage.datastore.db.ImageStoreVO; import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreDao; import org.apache.cloudstack.utils.identity.ManagementServerNode; +import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; @@ -50,7 +51,6 @@ import com.cloud.agent.api.RebootCommand; import com.cloud.agent.api.SecStorageFirewallCfgCommand; import com.cloud.agent.api.SecStorageSetupAnswer; import com.cloud.agent.api.SecStorageSetupCommand; -import com.cloud.agent.api.SecStorageSetupCommand.Certificates; import com.cloud.agent.api.SecStorageVMSetupCommand; import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupSecondaryStorageCommand; @@ -81,7 +81,6 @@ import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.info.RunningHostCountInfo; import com.cloud.info.RunningHostInfoAgregator; import com.cloud.info.RunningHostInfoAgregator.ZoneHostInfo; -import com.cloud.keystore.KeystoreManager; import com.cloud.network.Network; import com.cloud.network.NetworkModel; import com.cloud.network.Networks.TrafficType; @@ -92,7 +91,6 @@ import com.cloud.network.dao.NetworkVO; import com.cloud.network.rules.RulesManager; import com.cloud.offering.NetworkOffering; import com.cloud.offering.ServiceOffering; -import com.cloud.offerings.NetworkOfferingVO; import com.cloud.offerings.dao.NetworkOfferingDao; import com.cloud.resource.ResourceManager; import com.cloud.resource.ResourceStateAdapter; @@ -168,7 +166,7 @@ public class SecondaryStorageManagerImpl extends ManagerBase implements Secondar private static final int STARTUP_DELAY = 60000; // 60 seconds - private int _mgmt_port = 8250; + private int _mgmtPort = 8250; private List _ssVmAllocators; @@ -259,7 +257,7 @@ public class SecondaryStorageManagerImpl extends ManagerBase implements Secondar public SecondaryStorageVmVO startSecStorageVm(long secStorageVmId) { try { SecondaryStorageVmVO secStorageVm = _secStorageVmDao.findById(secStorageVmId); - _itMgr.advanceStart(secStorageVm.getUuid(), null); + _itMgr.advanceStart(secStorageVm.getUuid(), null, null); return _secStorageVmDao.findById(secStorageVm.getId()); } catch (StorageUnavailableException e) { s_logger.warn("Exception while trying to start secondary storage vm", e); @@ -305,7 +303,7 @@ public class SecondaryStorageManagerImpl extends ManagerBase implements Secondar if (!_useSSlCopy) { setupCmd = new SecStorageSetupCommand(ssStore.getTO(), secUrl, null); } else { - Certificates certs = _keystoreMgr.getCertificates(ConsoleProxyManager.CERTIFICATE_NAME); + KeystoreManager.Certificates certs = _keystoreMgr.getCertificates(ConsoleProxyManager.CERTIFICATE_NAME); setupCmd = new SecStorageSetupCommand(ssStore.getTO(), secUrl, certs); } @@ -825,7 +823,7 @@ public class SecondaryStorageManagerImpl extends ManagerBase implements Secondar Map agentMgrConfigs = _configDao.getConfiguration("AgentManager", params); value = agentMgrConfigs.get("port"); - _mgmt_port = NumbersUtil.parseInt(value, 8250); + _mgmtPort = NumbersUtil.parseInt(value, 8250); _listener = new SecondaryStorageListener(this, _agentMgr); _agentMgr.registerForHostEvents(_listener, true, false, true); @@ -1016,8 +1014,8 @@ public class SecondaryStorageManagerImpl extends ManagerBase implements Secondar StringBuilder buf = profile.getBootArgsBuilder(); buf.append(" template=domP type=secstorage"); - buf.append(" host=").append(ClusterManager.ManagementHostIPAdr.value()); - buf.append(" port=").append(_mgmt_port); + buf.append(" host=").append(ApiServiceConfiguration.ManagementHostIPAdr.value()); + buf.append(" port=").append(_mgmtPort); buf.append(" name=").append(profile.getVirtualMachine().getHostName()); buf.append(" zone=").append(dest.getDataCenter().getId()); @@ -1142,6 +1140,11 @@ public class SecondaryStorageManagerImpl extends ManagerBase implements Secondar controlNic = managementNic; } + // verify ssh access on management nic for system vm running on HyperV + if(profile.getHypervisorType() == HypervisorType.Hyperv) { + controlNic = managementNic; + } + CheckSshCommand check = new CheckSshCommand(profile.getInstanceName(), controlNic.getIp4Address(), 3922); cmds.addCommand("checkSsh", check); @@ -1381,6 +1384,6 @@ public class SecondaryStorageManagerImpl extends ManagerBase implements Secondar @Inject public void setSecondaryStorageVmAllocators(List ssVmAllocators) { - this._ssVmAllocators = ssVmAllocators; + _ssVmAllocators = ssVmAllocators; } } diff --git a/server/src/com/cloud/storage/secondary/SecondaryStorageVmManager.java b/server/src/com/cloud/storage/secondary/SecondaryStorageVmManager.java index a1af95c3ff2..3b32c851f0a 100755 --- a/server/src/com/cloud/storage/secondary/SecondaryStorageVmManager.java +++ b/server/src/com/cloud/storage/secondary/SecondaryStorageVmManager.java @@ -27,7 +27,7 @@ import com.cloud.vm.SecondaryStorageVmVO; public interface SecondaryStorageVmManager extends Manager { - public static final int DEFAULT_SS_VM_RAMSIZE = 256; // 256M + public static final int DEFAULT_SS_VM_RAMSIZE = 512; // 512M public static final int DEFAULT_SS_VM_CPUMHZ = 500; // 500 MHz public static final int DEFAULT_SS_VM_MTUSIZE = 1500; public static final int DEFAULT_SS_VM_CAPACITY = 50; // max command execution session per SSVM diff --git a/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java b/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java index ef89fe21c9e..a9eae7db1d5 100755 --- a/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java +++ b/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java @@ -322,16 +322,10 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager, UsageEventUtils.publishUsageEvent(EventTypes.EVENT_SNAPSHOT_CREATE, snapshot.getAccountId(), snapshot.getDataCenterId(), snapshotId, snapshot.getName(), null, null, volume.getSize(), snapshot.getClass().getName(), snapshot.getUuid()); } - _resourceLimitMgr.incrementResourceCount(snapshotOwner.getId(), ResourceType.snapshot); } catch (Exception e) { s_logger.debug("Failed to create snapshot", e); - if (backup) { - _resourceLimitMgr.decrementResourceCount(snapshotOwner.getId(), ResourceType.secondary_storage, new Long(volume.getSize())); - } else { - _resourceLimitMgr.decrementResourceCount(snapshotOwner.getId(), ResourceType.primary_storage, new Long(volume.getSize())); - } throw new CloudRuntimeException("Failed to create snapshot", e); } @@ -427,6 +421,7 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager, s_logger.error("Unable to find snaphot strategy to handle snapshot with id '" + snapshotId + "'"); return false; } + SnapshotDataStoreVO snapshotStoreRef = _snapshotStoreDao.findBySnapshot(snapshotId, DataStoreRole.Image); try { boolean result = snapshotStrategy.deleteSnapshot(snapshotId); @@ -435,8 +430,10 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager, UsageEventUtils.publishUsageEvent(EventTypes.EVENT_SNAPSHOT_DELETE, snapshotCheck.getAccountId(), snapshotCheck.getDataCenterId(), snapshotId, snapshotCheck.getName(), null, null, 0L, snapshotCheck.getClass().getName(), snapshotCheck.getUuid()); } - _resourceLimitMgr.decrementResourceCount(snapshotCheck.getAccountId(), ResourceType.snapshot); - _resourceLimitMgr.decrementResourceCount(snapshotCheck.getAccountId(), ResourceType.secondary_storage, new Long(snapshotCheck.getSize())); + if (snapshotCheck.getState() != Snapshot.State.Error && snapshotCheck.getState() != Snapshot.State.Destroyed) + _resourceLimitMgr.decrementResourceCount(snapshotCheck.getAccountId(), ResourceType.snapshot); + if (snapshotCheck.getState() == Snapshot.State.BackedUp) + _resourceLimitMgr.decrementResourceCount(snapshotCheck.getAccountId(), ResourceType.secondary_storage, new Long(snapshotStoreRef.getSize())); } return result; } catch (Exception e) { @@ -621,11 +618,12 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager, s_logger.error("Unable to find snaphot strategy to handle snapshot with id '" + snapshot.getId() + "'"); continue; } + SnapshotDataStoreVO snapshotStoreRef = _snapshotStoreDao.findBySnapshot(snapshot.getId(), DataStoreRole.Image); if (snapshotStrategy.deleteSnapshot(snapshot.getId())) { if (snapshot.getRecurringType() == Type.MANUAL) { _resourceLimitMgr.decrementResourceCount(accountId, ResourceType.snapshot); - _resourceLimitMgr.decrementResourceCount(accountId, ResourceType.secondary_storage, new Long(snapshot.getSize())); + _resourceLimitMgr.decrementResourceCount(accountId, ResourceType.secondary_storage, new Long(snapshotStoreRef.getSize())); } // Log event after successful deletion @@ -915,7 +913,7 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager, if (userVm.getHypervisorType() == HypervisorType.VMware || userVm.getHypervisorType() == HypervisorType.KVM) { List activeSnapshots = _snapshotDao.listByInstanceId(volume.getInstanceId(), Snapshot.State.Creating, Snapshot.State.CreatedOnPrimary, Snapshot.State.BackingUp); - if (activeSnapshots.size() > 1) { + if (activeSnapshots.size() > 0) { throw new CloudRuntimeException("There is other active snapshot tasks on the instance to which the volume is attached, please try again later"); } } @@ -953,17 +951,16 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager, UsageEventUtils.publishUsageEvent(EventTypes.EVENT_SNAPSHOT_CREATE, snapshot.getAccountId(), snapshot.getDataCenterId(), snapshotId, snapshot.getName(), null, null, volume.getSize(), snapshot.getClass().getName(), snapshot.getUuid()); - _resourceLimitMgr.incrementResourceCount(snapshotOwner.getId(), ResourceType.snapshot); + SnapshotDataStoreVO snapshotStoreRef = _snapshotStoreDao.findBySnapshot(snapshotId, DataStoreRole.Image); + // Correct the resource count of snapshot in case of delta snapshots. + _resourceLimitMgr.decrementResourceCount(snapshotOwner.getId(), ResourceType.secondary_storage, new Long(volume.getSize() - snapshotStoreRef.getSize())); } catch (Exception e) { s_logger.debug("post process snapshot failed", e); } } catch (Exception e) { s_logger.debug("Failed to create snapshot", e); - if (backup) { - _resourceLimitMgr.decrementResourceCount(snapshotOwner.getId(), ResourceType.secondary_storage, new Long(volume.getSize())); - } else { - _resourceLimitMgr.decrementResourceCount(snapshotOwner.getId(), ResourceType.primary_storage, new Long(volume.getSize())); - } + _resourceLimitMgr.decrementResourceCount(snapshotOwner.getId(), ResourceType.snapshot); + _resourceLimitMgr.decrementResourceCount(snapshotOwner.getId(), ResourceType.secondary_storage, new Long(volume.getSize())); throw new CloudRuntimeException("Failed to create snapshot", e); } return snapshot; @@ -1068,17 +1065,14 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager, try { _resourceLimitMgr.checkResourceLimit(owner, ResourceType.snapshot); - if (backup) { - _resourceLimitMgr.checkResourceLimit(owner, ResourceType.secondary_storage, new Long(volume.getSize())); - } else { - _resourceLimitMgr.checkResourceLimit(owner, ResourceType.primary_storage, new Long(volume.getSize())); - } + _resourceLimitMgr.checkResourceLimit(owner, ResourceType.secondary_storage, new Long(volume.getSize())); } catch (ResourceAllocationException e) { if (snapshotType != Type.MANUAL) { String msg = "Snapshot resource limit exceeded for account id : " + owner.getId() + ". Failed to create recurring snapshots"; s_logger.warn(msg); - _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_UPDATE_RESOURCE_COUNT, 0L, 0L, msg, "Snapshot resource limit exceeded for account id : " + owner.getId() + - ". Failed to create recurring snapshots; please use updateResourceLimit to increase the limit"); + _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_UPDATE_RESOURCE_COUNT, 0L, 0L, msg, + "Snapshot resource limit exceeded for account id : " + owner.getId() + + ". Failed to create recurring snapshots; please use updateResourceLimit to increase the limit"); } throw e; } @@ -1110,11 +1104,8 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager, if (snapshot == null) { throw new CloudRuntimeException("Failed to create snapshot for volume: " + volume.getId()); } - if (backup) { - _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.secondary_storage, new Long(volume.getSize())); - } else { - _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.primary_storage, new Long(volume.getSize())); - } + _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.snapshot); + _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.secondary_storage, new Long(volume.getSize())); return snapshot; } diff --git a/server/src/com/cloud/storage/snapshot/SnapshotSchedulerImpl.java b/server/src/com/cloud/storage/snapshot/SnapshotSchedulerImpl.java index 78e78b63bf5..315905953a6 100644 --- a/server/src/com/cloud/storage/snapshot/SnapshotSchedulerImpl.java +++ b/server/src/com/cloud/storage/snapshot/SnapshotSchedulerImpl.java @@ -93,13 +93,13 @@ public class SnapshotSchedulerImpl extends ManagerBase implements SnapshotSchedu private TestClock _testTimerTask; public AsyncJobDispatcher getAsyncJobDispatcher() { - return _asyncDispatcher; + return _asyncDispatcher; } - + public void setAsyncJobDispatcher(AsyncJobDispatcher dispatcher) { - _asyncDispatcher = dispatcher; + _asyncDispatcher = dispatcher; } - + private Date getNextScheduledTime(long policyId, Date currentTimestamp) { SnapshotPolicyVO policy = _snapshotPolicyDao.findById(policyId); Date nextTimestamp = null; diff --git a/server/src/com/cloud/storage/upload/UploadListener.java b/server/src/com/cloud/storage/upload/UploadListener.java index 1fa89468b85..f6ad815d007 100755 --- a/server/src/com/cloud/storage/upload/UploadListener.java +++ b/server/src/com/cloud/storage/upload/UploadListener.java @@ -166,7 +166,7 @@ public class UploadListener implements Listener { private final Map stateMap = new HashMap(); private Long uploadId; - public UploadListener(DataStore host, Timer _timer, UploadDao uploadDao, UploadVO uploadObj, UploadMonitorImpl uploadMonitor, UploadCommand cmd, Long accountId, + public UploadListener(DataStore host, Timer timerInput, UploadDao uploadDao, UploadVO uploadObj, UploadMonitorImpl uploadMonitor, UploadCommand cmd, Long accountId, String typeName, Type type, long eventId, long asyncJobId, AsyncJobManager asyncMgr) { sserver = host; this.uploadDao = uploadDao; @@ -178,7 +178,7 @@ public class UploadListener implements Listener { this.type = type; initStateMachine(); currState = getState(Status.NOT_UPLOADED.toString()); - timer = _timer; + timer = timerInput; timeoutTask = new TimeoutTask(this); timer.schedule(timeoutTask, 3 * STATUS_POLL_INTERVAL); this.eventId = eventId; @@ -215,12 +215,12 @@ public class UploadListener implements Listener { return false; } - public void setCommand(UploadCommand _cmd) { - cmd = _cmd; + public void setCommand(UploadCommand cmd) { + this.cmd = cmd; } - public void setJobId(String _jobId) { - jobId = _jobId; + public void setJobId(String jobId) { + this.jobId = jobId; } public String getJobId() { diff --git a/server/src/com/cloud/storage/upload/UploadMonitorImpl.java b/server/src/com/cloud/storage/upload/UploadMonitorImpl.java index 991f35f7c69..6f1f5e90c4e 100755 --- a/server/src/com/cloud/storage/upload/UploadMonitorImpl.java +++ b/server/src/com/cloud/storage/upload/UploadMonitorImpl.java @@ -269,7 +269,7 @@ public class UploadMonitorImpl extends ManagerBase implements UploadMonitor { CreateEntityDownloadURLCommand cmd = new CreateEntityDownloadURLCommand(((ImageStoreEntity)store).getMountPoint(), path, uuid, null); Answer ans = ep.sendMessage(cmd); if (ans == null || !ans.getResult()) { - errorString = "Unable to create a link for " + type + " id:" + template.getId() + "," + ans.getDetails(); + errorString = "Unable to create a link for " + type + " id:" + template.getId() + "," + (ans == null ? "" : ans.getDetails()); s_logger.error(errorString); throw new CloudRuntimeException(errorString); } @@ -325,7 +325,7 @@ public class UploadMonitorImpl extends ManagerBase implements UploadMonitor { CreateEntityDownloadURLCommand cmd = new CreateEntityDownloadURLCommand(((ImageStoreEntity)secStore).getMountPoint(), path, uuid, null); Answer ans = ep.sendMessage(cmd); if (ans == null || !ans.getResult()) { - errorString = "Unable to create a link for " + type + " id:" + entityId + "," + ans.getDetails(); + errorString = "Unable to create a link for " + type + " id:" + entityId + "," + (ans == null ? "" : ans.getDetails()); s_logger.warn(errorString); throw new CloudRuntimeException(errorString); } diff --git a/server/src/com/cloud/tags/TaggedResourceManagerImpl.java b/server/src/com/cloud/tags/TaggedResourceManagerImpl.java index 6b52a97c07c..555a8452786 100644 --- a/server/src/com/cloud/tags/TaggedResourceManagerImpl.java +++ b/server/src/com/cloud/tags/TaggedResourceManagerImpl.java @@ -25,65 +25,102 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; import org.apache.cloudstack.context.CallContext; -import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; +import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; import org.apache.log4j.Logger; -import org.springframework.stereotype.Component; import com.cloud.api.query.dao.ResourceTagJoinDao; -import com.cloud.dc.dao.DataCenterDao; +import com.cloud.dc.DataCenterVO; import com.cloud.domain.Domain; +import com.cloud.domain.PartOf; import com.cloud.event.ActionEvent; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.PermissionDeniedException; -import com.cloud.network.dao.FirewallRulesDao; -import com.cloud.network.dao.IPAddressDao; -import com.cloud.network.dao.LoadBalancerDao; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.RemoteAccessVpnDao; -import com.cloud.network.rules.dao.PortForwardingRulesDao; -import com.cloud.network.security.dao.SecurityGroupDao; -import com.cloud.network.vpc.NetworkACLItemDao; -import com.cloud.network.vpc.dao.NetworkACLDao; -import com.cloud.network.vpc.dao.StaticRouteDao; -import com.cloud.network.vpc.dao.VpcDao; -import com.cloud.network.vpc.dao.VpcGatewayDao; -import com.cloud.projects.dao.ProjectDao; +import com.cloud.network.as.AutoScaleVmProfileVO; +import com.cloud.network.dao.IPAddressVO; +import com.cloud.network.dao.LoadBalancerVO; +import com.cloud.network.dao.NetworkVO; +import com.cloud.network.dao.RemoteAccessVpnVO; +import com.cloud.network.dao.Site2SiteCustomerGatewayVO; +import com.cloud.network.dao.Site2SiteVpnConnectionVO; +import com.cloud.network.dao.Site2SiteVpnGatewayVO; +import com.cloud.network.rules.FirewallRuleVO; +import com.cloud.network.rules.PortForwardingRuleVO; +import com.cloud.network.security.SecurityGroupVO; +import com.cloud.network.vpc.NetworkACLItemVO; +import com.cloud.network.vpc.NetworkACLVO; +import com.cloud.network.vpc.StaticRouteVO; +import com.cloud.network.vpc.VpcVO; +import com.cloud.projects.ProjectVO; import com.cloud.server.ResourceTag; import com.cloud.server.ResourceTag.ResourceObjectType; import com.cloud.server.TaggedResourceService; -import com.cloud.service.dao.ServiceOfferingDao; -import com.cloud.storage.dao.SnapshotDao; -import com.cloud.storage.dao.VMTemplateDao; -import com.cloud.storage.dao.VolumeDao; +import com.cloud.service.ServiceOfferingVO; +import com.cloud.storage.DiskOfferingVO; +import com.cloud.storage.SnapshotVO; +import com.cloud.storage.VMTemplateVO; +import com.cloud.storage.VolumeVO; import com.cloud.tags.dao.ResourceTagDao; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.DomainManager; +import com.cloud.user.OwnedBy; +import com.cloud.user.UserVO; import com.cloud.utils.Pair; import com.cloud.utils.component.ManagerBase; import com.cloud.utils.db.DB; -import com.cloud.utils.db.DbUtil; -import com.cloud.utils.db.GenericDao; +import com.cloud.utils.db.EntityManager; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; import com.cloud.utils.db.TransactionCallbackNoReturn; import com.cloud.utils.db.TransactionStatus; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.uuididentity.dao.IdentityDao; -import com.cloud.vm.dao.NicDao; -import com.cloud.vm.dao.UserVmDao; -import com.cloud.vm.snapshot.dao.VMSnapshotDao; +import com.cloud.vm.NicVO; +import com.cloud.vm.UserVmVO; +import com.cloud.vm.snapshot.VMSnapshotVO; -@Component @Local(value = {TaggedResourceService.class}) public class TaggedResourceManagerImpl extends ManagerBase implements TaggedResourceService { public static final Logger s_logger = Logger.getLogger(TaggedResourceManagerImpl.class); - private static Map> _daoMap = new HashMap>(); + private static final Map> s_typeMap = new HashMap>(); + static { + s_typeMap.put(ResourceObjectType.UserVm, UserVmVO.class); + s_typeMap.put(ResourceObjectType.Volume, VolumeVO.class); + s_typeMap.put(ResourceObjectType.Template, VMTemplateVO.class); + s_typeMap.put(ResourceObjectType.ISO, VMTemplateVO.class); + s_typeMap.put(ResourceObjectType.Snapshot, SnapshotVO.class); + s_typeMap.put(ResourceObjectType.Network, NetworkVO.class); + s_typeMap.put(ResourceObjectType.LoadBalancer, LoadBalancerVO.class); + s_typeMap.put(ResourceObjectType.PortForwardingRule, PortForwardingRuleVO.class); + s_typeMap.put(ResourceObjectType.FirewallRule, FirewallRuleVO.class); + s_typeMap.put(ResourceObjectType.SecurityGroup, SecurityGroupVO.class); + s_typeMap.put(ResourceObjectType.PublicIpAddress, IPAddressVO.class); + s_typeMap.put(ResourceObjectType.Project, ProjectVO.class); + s_typeMap.put(ResourceObjectType.Vpc, VpcVO.class); + s_typeMap.put(ResourceObjectType.Nic, NicVO.class); + s_typeMap.put(ResourceObjectType.NetworkACL, NetworkACLVO.class); + s_typeMap.put(ResourceObjectType.StaticRoute, StaticRouteVO.class); + s_typeMap.put(ResourceObjectType.VMSnapshot, VMSnapshotVO.class); + s_typeMap.put(ResourceObjectType.RemoteAccessVpn, RemoteAccessVpnVO.class); + s_typeMap.put(ResourceObjectType.Zone, DataCenterVO.class); + s_typeMap.put(ResourceObjectType.ServiceOffering, ServiceOfferingVO.class); + s_typeMap.put(ResourceObjectType.Storage, StoragePoolVO.class); + s_typeMap.put(ResourceObjectType.PrivateGateway, RemoteAccessVpnVO.class); + s_typeMap.put(ResourceObjectType.NetworkACLList, NetworkACLItemVO.class); + s_typeMap.put(ResourceObjectType.VpnGateway, Site2SiteVpnGatewayVO.class); + s_typeMap.put(ResourceObjectType.CustomerGateway, Site2SiteCustomerGatewayVO.class); + s_typeMap.put(ResourceObjectType.VpnConnection, Site2SiteVpnConnectionVO.class); + s_typeMap.put(ResourceObjectType.User, UserVO.class); + s_typeMap.put(ResourceObjectType.DiskOffering, DiskOfferingVO.class); + s_typeMap.put(ResourceObjectType.AutoScaleVmProfile, AutoScaleVmProfileVO.class); + } + @Inject + EntityManager _entityMgr; @Inject AccountManager _accountMgr; @Inject @@ -91,80 +128,11 @@ public class TaggedResourceManagerImpl extends ManagerBase implements TaggedReso @Inject ResourceTagJoinDao _resourceTagJoinDao; @Inject - IdentityDao _identityDao; - @Inject DomainManager _domainMgr; - @Inject - UserVmDao _userVmDao; - @Inject - VolumeDao _volumeDao; - @Inject - VMTemplateDao _templateDao; - @Inject - SnapshotDao _snapshotDao; - @Inject - NetworkDao _networkDao; - @Inject - LoadBalancerDao _lbDao; - @Inject - PortForwardingRulesDao _pfDao; - @Inject - FirewallRulesDao _firewallDao; - @Inject - SecurityGroupDao _securityGroupDao; - @Inject - RemoteAccessVpnDao _vpnDao; - @Inject - IPAddressDao _publicIpDao; - @Inject - ProjectDao _projectDao; - @Inject - VpcDao _vpcDao; - @Inject - StaticRouteDao _staticRouteDao; - @Inject - VMSnapshotDao _vmSnapshotDao; - @Inject - NicDao _nicDao; - @Inject - NetworkACLItemDao _networkACLItemDao; - @Inject - DataCenterDao _dataCenterDao; - @Inject - ServiceOfferingDao _serviceOffDao; - @Inject - PrimaryDataStoreDao _storagePoolDao; - @Inject - VpcGatewayDao _vpcGatewayDao; - @Inject - NetworkACLDao _networkACLListDao; + @Override public boolean configure(String name, Map params) throws ConfigurationException { - _daoMap.put(ResourceObjectType.UserVm, _userVmDao); - _daoMap.put(ResourceObjectType.Volume, _volumeDao); - _daoMap.put(ResourceObjectType.Template, _templateDao); - _daoMap.put(ResourceObjectType.ISO, _templateDao); - _daoMap.put(ResourceObjectType.Snapshot, _snapshotDao); - _daoMap.put(ResourceObjectType.Network, _networkDao); - _daoMap.put(ResourceObjectType.LoadBalancer, _lbDao); - _daoMap.put(ResourceObjectType.PortForwardingRule, _pfDao); - _daoMap.put(ResourceObjectType.FirewallRule, _firewallDao); - _daoMap.put(ResourceObjectType.SecurityGroup, _securityGroupDao); - _daoMap.put(ResourceObjectType.PublicIpAddress, _publicIpDao); - _daoMap.put(ResourceObjectType.Project, _projectDao); - _daoMap.put(ResourceObjectType.Vpc, _vpcDao); - _daoMap.put(ResourceObjectType.Nic, _nicDao); - _daoMap.put(ResourceObjectType.NetworkACL, _networkACLItemDao); - _daoMap.put(ResourceObjectType.StaticRoute, _staticRouteDao); - _daoMap.put(ResourceObjectType.VMSnapshot, _vmSnapshotDao); - _daoMap.put(ResourceObjectType.RemoteAccessVpn, _vpnDao); - _daoMap.put(ResourceObjectType.Zone, _dataCenterDao); - _daoMap.put(ResourceObjectType.ServiceOffering, _serviceOffDao); - _daoMap.put(ResourceObjectType.Storage, _storagePoolDao); - _daoMap.put(ResourceObjectType.PrivateGateway, _vpcGatewayDao); - _daoMap.put(ResourceObjectType.NetworkACLList, _networkACLListDao); - return true; } @@ -180,59 +148,31 @@ public class TaggedResourceManagerImpl extends ManagerBase implements TaggedReso @Override public long getResourceId(String resourceId, ResourceObjectType resourceType) { - GenericDao dao = _daoMap.get(resourceType); - if (dao == null) { - throw new CloudRuntimeException("Dao is not loaded for the resource type " + resourceType); + Class clazz = s_typeMap.get(resourceType); + Object entity = _entityMgr.findByUuid(clazz, resourceId); + if (entity != null) { + return ((InternalIdentity)entity).getId(); } - Class claz = DbUtil.getEntityBeanType(dao); - - Long identityId = null; - - while (claz != null && claz != Object.class) { - try { - String tableName = DbUtil.getTableName(claz); - if (tableName == null) { - throw new InvalidParameterValueException("Unable to find resource of type " + resourceType + " in the database"); - } - identityId = _identityDao.getIdentityId(tableName, resourceId); - if (identityId != null) { - break; - } - } catch (Exception ex) { - //do nothing here, it might mean uuid field is missing and we have to search further - } - claz = claz.getSuperclass(); + entity = _entityMgr.findById(clazz, resourceId); + if (entity != null) { + return ((InternalIdentity)entity).getId(); } - - if (identityId == null) { - throw new InvalidParameterValueException("Unable to find resource by id " + resourceId + " and type " + resourceType); - } - return identityId; + throw new InvalidParameterValueException("Unable to find resource by id " + resourceId + " and type " + resourceType); } private Pair getAccountDomain(long resourceId, ResourceObjectType resourceType) { + Class clazz = s_typeMap.get(resourceType); - Pair pair = null; - GenericDao dao = _daoMap.get(resourceType); - Class claz = DbUtil.getEntityBeanType(dao); - while (claz != null && claz != Object.class) { - try { - String tableName = DbUtil.getTableName(claz); - if (tableName == null) { - throw new InvalidParameterValueException("Unable to find resource of type " + resourceType + " in the database"); - } - pair = _identityDao.getAccountDomainInfo(tableName, resourceId, resourceType); - if (pair.first() != null || pair.second() != null) { - break; - } - } catch (Exception ex) { - //do nothing here, it might mean uuid field is missing and we have to search further - } - claz = claz.getSuperclass(); + Object entity = _entityMgr.findById(clazz, resourceId); + Long accountId = null; + Long domainId = null; + if (entity instanceof OwnedBy) { + accountId = ((OwnedBy)entity).getAccountId(); } - Long accountId = pair.first(); - Long domainId = pair.second(); + if (entity instanceof PartOf) { + domainId = ((PartOf)entity).getDomainId(); + } if (accountId == null) { accountId = Account.ACCOUNT_ID_SYSTEM; @@ -294,8 +234,7 @@ public class TaggedResourceManagerImpl extends ManagerBase implements TaggedReso throw new InvalidParameterValueException("Value for the key " + key + " is either null or empty"); } - ResourceTagVO resourceTag = - new ResourceTagVO(key, value, accountDomainPair.first(), accountDomainPair.second(), id, resourceType, customer, resourceUuid); + ResourceTagVO resourceTag = new ResourceTagVO(key, value, accountDomainPair.first(), accountDomainPair.second(), id, resourceType, customer, resourceUuid); resourceTag = _resourceTagDao.persist(resourceTag); resourceTags.add(resourceTag); } @@ -308,32 +247,14 @@ public class TaggedResourceManagerImpl extends ManagerBase implements TaggedReso @Override public String getUuid(String resourceId, ResourceObjectType resourceType) { - GenericDao dao = _daoMap.get(resourceType); - Class claz = DbUtil.getEntityBeanType(dao); + Class clazz = s_typeMap.get(resourceType); - String identiyUUId = null; - - while (claz != null && claz != Object.class) { - try { - String tableName = DbUtil.getTableName(claz); - if (tableName == null) { - throw new InvalidParameterValueException("Unable to find resource of type " + resourceType + " in the database"); - } - - claz = claz.getSuperclass(); - if (claz == Object.class) { - identiyUUId = _identityDao.getIdentityUuid(tableName, resourceId); - } - } catch (Exception ex) { - //do nothing here, it might mean uuid field is missing and we have to search further - } + Object entity = _entityMgr.findById(clazz, resourceId); + if (entity != null && entity instanceof Identity) { + return ((Identity)entity).getUuid(); } - if (identiyUUId == null) { - return resourceId; - } - - return identiyUUId; + return resourceId; } @Override diff --git a/server/src/com/cloud/template/HypervisorTemplateAdapter.java b/server/src/com/cloud/template/HypervisorTemplateAdapter.java index 542e675d127..25e79db2bbe 100755 --- a/server/src/com/cloud/template/HypervisorTemplateAdapter.java +++ b/server/src/com/cloud/template/HypervisorTemplateAdapter.java @@ -151,20 +151,54 @@ public class HypervisorTemplateAdapter extends TemplateAdapterBase { (!url.toLowerCase().endsWith("qcow2.bz2")) && (!url.toLowerCase().endsWith("qcow2.gz")) && (!url.toLowerCase().endsWith("ova")) && (!url.toLowerCase().endsWith("ova.zip")) && (!url.toLowerCase().endsWith("ova.bz2")) && (!url.toLowerCase().endsWith("ova.gz")) && (!url.toLowerCase().endsWith("tar")) && (!url.toLowerCase().endsWith("tar.zip")) && (!url.toLowerCase().endsWith("tar.bz2")) && - (!url.toLowerCase().endsWith("tar.gz")) && (!url.toLowerCase().endsWith("img")) && (!url.toLowerCase().endsWith("raw"))) { + (!url.toLowerCase().endsWith("tar.gz")) && (!url.toLowerCase().endsWith("vmdk")) && (!url.toLowerCase().endsWith("vmdk.gz")) && + (!url.toLowerCase().endsWith("vmdk.zip")) && (!url.toLowerCase().endsWith("vmdk.bz2")) && (!url.toLowerCase().endsWith("img")) && + (!url.toLowerCase().endsWith("img.gz")) && (!url.toLowerCase().endsWith("img.zip")) && (!url.toLowerCase().endsWith("img.bz2")) && + (!url.toLowerCase().endsWith("raw")) && (!url.toLowerCase().endsWith("raw.gz")) && (!url.toLowerCase().endsWith("raw.bz2")) && + (!url.toLowerCase().endsWith("raw.zip"))) { throw new InvalidParameterValueException("Please specify a valid " + format.toLowerCase()); } - if ((format.equalsIgnoreCase("vhd") && (!url.toLowerCase().endsWith("vhd") && !url.toLowerCase().endsWith("vhd.zip") && !url.toLowerCase().endsWith("vhd.bz2") && !url.toLowerCase() - .endsWith("vhd.gz"))) || - (format.equalsIgnoreCase("vhdx") && (!url.toLowerCase().endsWith("vhdx") && !url.toLowerCase().endsWith("vhdx.zip") && !url.toLowerCase().endsWith("vhdx.bz2") && !url.toLowerCase() - .endsWith("vhdx.gz"))) || - (format.equalsIgnoreCase("qcow2") && (!url.toLowerCase().endsWith("qcow2") && !url.toLowerCase().endsWith("qcow2.zip") && - !url.toLowerCase().endsWith("qcow2.bz2") && !url.toLowerCase().endsWith("qcow2.gz"))) || - (format.equalsIgnoreCase("ova") && (!url.toLowerCase().endsWith("ova") && !url.toLowerCase().endsWith("ova.zip") && !url.toLowerCase().endsWith("ova.bz2") && !url.toLowerCase() - .endsWith("ova.gz"))) || - (format.equalsIgnoreCase("tar") && (!url.toLowerCase().endsWith("tar") && !url.toLowerCase().endsWith("tar.zip") && !url.toLowerCase().endsWith("tar.bz2") && !url.toLowerCase() - .endsWith("tar.gz"))) || (format.equalsIgnoreCase("raw") && (!url.toLowerCase().endsWith("img") && !url.toLowerCase().endsWith("raw")))) { + if ((format.equalsIgnoreCase("vhd") + && (!url.toLowerCase().endsWith("vhd") + && !url.toLowerCase().endsWith("vhd.zip") + && !url.toLowerCase().endsWith("vhd.bz2") + && !url.toLowerCase().endsWith("vhd.gz"))) + || (format.equalsIgnoreCase("vhdx") + && (!url.toLowerCase().endsWith("vhdx") + && !url.toLowerCase().endsWith("vhdx.zip") + && !url.toLowerCase().endsWith("vhdx.bz2") + && !url.toLowerCase().endsWith("vhdx.gz"))) + || (format.equalsIgnoreCase("qcow2") + && (!url.toLowerCase().endsWith("qcow2") + && !url.toLowerCase().endsWith("qcow2.zip") + && !url.toLowerCase().endsWith("qcow2.bz2") + && !url.toLowerCase().endsWith("qcow2.gz"))) + || (format.equalsIgnoreCase("ova") + && (!url.toLowerCase().endsWith("ova") + && !url.toLowerCase().endsWith("ova.zip") + && !url.toLowerCase().endsWith("ova.bz2") + && !url.toLowerCase().endsWith("ova.gz"))) + || (format.equalsIgnoreCase("tar") + && (!url.toLowerCase().endsWith("tar") + && !url.toLowerCase().endsWith("tar.zip") + && !url.toLowerCase().endsWith("tar.bz2") + && !url.toLowerCase().endsWith("tar.gz"))) + || (format.equalsIgnoreCase("raw") + && (!url.toLowerCase().endsWith("img") + && !url.toLowerCase().endsWith("img.zip") + && !url.toLowerCase().endsWith("img.bz2") + && !url.toLowerCase().endsWith("img.gz") + && !url.toLowerCase().endsWith("raw") + && !url.toLowerCase().endsWith("raw.bz2") + && !url.toLowerCase().endsWith("raw.zip") + && !url.toLowerCase().endsWith("raw.gz"))) + || (format.equalsIgnoreCase("vmdk") + && (!url.toLowerCase().endsWith("vmdk") + && !url.toLowerCase().endsWith("vmdk.zip") + && !url.toLowerCase().endsWith("vmdk.bz2") + && !url.toLowerCase().endsWith("vmdk.gz"))) + ) { throw new InvalidParameterValueException("Please specify a valid URL. URL:" + url + " is an invalid for the format " + format.toLowerCase()); } diff --git a/server/src/com/cloud/template/TemplateAdapterBase.java b/server/src/com/cloud/template/TemplateAdapterBase.java index 59aab3b64b7..e3999122b53 100755 --- a/server/src/com/cloud/template/TemplateAdapterBase.java +++ b/server/src/com/cloud/template/TemplateAdapterBase.java @@ -176,8 +176,14 @@ public abstract class TemplateAdapterBase extends AdapterBase implements Templat } boolean isAdmin = _accountDao.findById(templateOwner.getId()).getType() == Account.ACCOUNT_TYPE_ADMIN; + boolean isRegionStore = false; + List stores = _imgStoreDao.findRegionImageStores(); + if (stores != null && stores.size() > 0) { + isRegionStore = true; + } - if (!isAdmin && zoneId == null) { + if (!isAdmin && zoneId == null && !isRegionStore ) { + // domain admin and user should also be able to register template on a region store throw new InvalidParameterValueException("Please specify a valid zone Id."); } diff --git a/server/src/com/cloud/template/TemplateManagerImpl.java b/server/src/com/cloud/template/TemplateManagerImpl.java index f545d2c6fb5..56232d27609 100755 --- a/server/src/com/cloud/template/TemplateManagerImpl.java +++ b/server/src/com/cloud/template/TemplateManagerImpl.java @@ -19,9 +19,9 @@ package com.cloud.template; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Date; +import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.HashMap; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; @@ -136,7 +136,6 @@ import com.cloud.storage.StoragePoolHostVO; import com.cloud.storage.StoragePoolStatus; import com.cloud.storage.TemplateProfile; import com.cloud.storage.Upload; -import com.cloud.storage.VMTemplateDetailVO; import com.cloud.storage.VMTemplateHostVO; import com.cloud.storage.VMTemplateStoragePoolVO; import com.cloud.storage.VMTemplateStorageResourceAssoc; @@ -426,7 +425,7 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager, if (isISO) { desc = Upload.Type.ISO.toString(); } - eventId = eventId == null ? 0 : eventId; + eventId = (eventId == null ? 0 : eventId); if (!_accountMgr.isRootAdmin(caller.getType()) && _disableExtraction) { throw new PermissionDeniedException("Extraction has been disabled by admin"); @@ -690,38 +689,47 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager, Account caller = CallContext.current().getCallingAccount(); // Verify parameters - if (sourceZoneId.equals(destZoneId)) { - throw new InvalidParameterValueException("Please specify different source and destination zones."); - } - - DataCenterVO sourceZone = _dcDao.findById(sourceZoneId); - if (sourceZone == null) { - throw new InvalidParameterValueException("Please specify a valid source zone."); - } - - DataCenterVO dstZone = _dcDao.findById(destZoneId); - if (dstZone == null) { - throw new InvalidParameterValueException("Please specify a valid destination zone."); - } - VMTemplateVO template = _tmpltDao.findById(templateId); if (template == null || template.getRemoved() != null) { throw new InvalidParameterValueException("Unable to find template with id"); } - DataStore srcSecStore = getImageStore(sourceZoneId, templateId); + DataStore srcSecStore = null; + if (sourceZoneId != null) { + // template is on zone-wide secondary storage + srcSecStore = getImageStore(sourceZoneId, templateId); + } else { + // template is on region store + srcSecStore = getImageStore(templateId); + } + if (srcSecStore == null) { - throw new InvalidParameterValueException("There is no template " + templateId + " in zone " + sourceZoneId); + throw new InvalidParameterValueException("There is no template " + templateId + " ready on image store."); } if (template.isCrossZones()) { - //TODO: we may need UI still enable CopyTemplate in case of cross zone template to trigger sync to region store. // sync template from cache store to region store if it is not there, for cases where we are going to migrate existing NFS to S3. _tmpltSvr.syncTemplateToRegionStore(templateId, srcSecStore); s_logger.debug("Template " + templateId + " is cross-zone, don't need to copy"); return template; } + if (sourceZoneId != null) { + if (sourceZoneId.equals(destZoneId)) { + throw new InvalidParameterValueException("Please specify different source and destination zones."); + } + + DataCenterVO sourceZone = _dcDao.findById(sourceZoneId); + if (sourceZone == null) { + throw new InvalidParameterValueException("Please specify a valid source zone."); + } + } + + DataCenterVO dstZone = _dcDao.findById(destZoneId); + if (dstZone == null) { + throw new InvalidParameterValueException("Please specify a valid destination zone."); + } + DataStore dstSecStore = getImageStore(destZoneId, templateId); if (dstSecStore != null) { s_logger.debug("There is template " + templateId + " in secondary storage " + dstSecStore.getName() + " in zone " + destZoneId + " , don't need to copy"); @@ -1268,12 +1276,12 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager, updatedTemplate.setFeatured(isFeatured.booleanValue()); } - if(isExtractable != null){ + if (isExtractable != null) { // Only Root admins allowed to change it for templates - if(!template.getFormat().equals(ImageFormat.ISO) && caller.getType() != Account.ACCOUNT_TYPE_ADMIN){ + if (!template.getFormat().equals(ImageFormat.ISO) && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { throw new InvalidParameterValueException("Only ROOT admins are allowed to modify this attribute."); - }else{ - // For Isos normal user can change it, as their are no derivatives. + } else { + // For Isos normal user can change it, as their are no derivatives. updatedTemplate.setExtractable(isExtractable.booleanValue()); } } @@ -1387,8 +1395,14 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager, throw new CloudRuntimeException("Failed to create template" + result.getResult()); } - VMTemplateZoneVO templateZone = new VMTemplateZoneVO(zoneId, templateId, new Date()); - _tmpltZoneDao.persist(templateZone); + // create entries in template_zone_ref table + if (_dataStoreMgr.isRegionStore(store)) { + // template created on region store + _tmpltSvr.associateTemplateToZone(templateId, null); + } else { + VMTemplateZoneVO templateZone = new VMTemplateZoneVO(zoneId, templateId, new Date()); + _tmpltZoneDao.persist(templateZone); + } privateTemplate = _tmpltDao.findById(templateId); if (snapshotId != null) { @@ -1629,20 +1643,20 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager, // Increment the number of templates if (template != null) { Map details = new HashMap(); - if ( volume != null ) { + if (volume != null) { Long vmId = volume.getInstanceId(); - if ( vmId != null ) { - UserVmVO userVm = _userVmDao.findById(vmId); + if (vmId != null) { + UserVmVO userVm = _userVmDao.findById(vmId); if (userVm != null) { _userVmDao.loadDetails(userVm); details.putAll(userVm.getDetails()); } } } - if(cmd.getDetails() != null) { + if (cmd.getDetails() != null) { details.putAll(cmd.getDetails()); } - if( !details.isEmpty()) { + if (!details.isEmpty()) { privateTemplate.setDetails(details); _tmpltDao.saveDetails(privateTemplate); } @@ -1693,11 +1707,28 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager, return null; } + // get the region wide image store where a template is READY on, + // just pick one is enough. + @Override + public DataStore getImageStore(long tmpltId) { + TemplateDataStoreVO tmpltStore = _tmplStoreDao.findReadyByTemplate(tmpltId, DataStoreRole.Image); + if (tmpltStore != null) { + return _dataStoreMgr.getDataStore(tmpltStore.getDataStoreId(), DataStoreRole.Image); + } + + return null; + } + @Override public Long getTemplateSize(long templateId, long zoneId) { TemplateDataStoreVO templateStoreRef = _tmplStoreDao.findByTemplateZoneDownloadStatus(templateId, zoneId, VMTemplateStorageResourceAssoc.Status.DOWNLOADED); if (templateStoreRef == null) { - throw new CloudRuntimeException("Template " + templateId + " has not been completely downloaded to zone " + zoneId); + // check if it is ready on image cache stores + templateStoreRef = _tmplStoreDao.findByTemplateZoneStagingDownloadStatus(templateId, zoneId, + VMTemplateStorageResourceAssoc.Status.DOWNLOADED); + if (templateStoreRef == null) { + throw new CloudRuntimeException("Template " + templateId + " has not been completely downloaded to zone " + zoneId); + } } return templateStoreRef.getSize(); @@ -1754,7 +1785,7 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager, } // Don't allow to modify system template - if (id == Long.valueOf(1)) { + if (Long.valueOf(1).equals(id)) { InvalidParameterValueException ex = new InvalidParameterValueException("Unable to update template/iso of specified id"); ex.addProxyObject(String.valueOf(id), "templateId"); throw ex; diff --git a/server/src/com/cloud/test/IPRangeConfig.java b/server/src/com/cloud/test/IPRangeConfig.java index f4619955f4f..1d564714087 100755 --- a/server/src/com/cloud/test/IPRangeConfig.java +++ b/server/src/com/cloud/test/IPRangeConfig.java @@ -69,7 +69,7 @@ public class IPRangeConfig { long zoneId = PodZoneConfig.getZoneId(zone); result = changeRange(op, "public", -1, zoneId, startIP, endIP, null, -1); - result.replaceAll("
", "/n"); + result = result.replaceAll("
", "/n"); System.out.println(result); } else if (type.equals("private")) { if (args.length != 5 && args.length != 6) { @@ -92,7 +92,7 @@ public class IPRangeConfig { long podId = PodZoneConfig.getPodId(pod, zone); long zoneId = PodZoneConfig.getZoneId(zone); result = changeRange(op, "private", podId, zoneId, startIP, endIP, null, -1); - result.replaceAll("
", "/n"); + result = result.replaceAll("
", "/n"); System.out.println(result); } else { printError(usage()); @@ -569,31 +569,6 @@ public class IPRangeConfig { "Unable to start DB connection to read guest cidr network. Please contact Cloud Support."); } -// public static String getGuestIpNetwork() { -// return DatabaseConfig.getDatabaseValueString("SELECT * FROM `cloud`.`configuration` WHERE name = \"guest.ip.network\"", "value", -// "Unable to start DB connection to read guest IP network. Please contact Cloud Support."); -// } -// -// public static String getGuestNetmask() { -// return DatabaseConfig.getDatabaseValueString("SELECT * FROM `cloud`.`configuration` WHERE name = \"guest.netmask\"", "value", -// "Unable to start DB connection to read guest netmask. Please contact Cloud Support."); -// } - -// public static String getGuestSubnet() { -// String guestIpNetwork = getGuestIpNetwork(); -// String guestNetmask = getGuestNetmask(); -// -// if (guestIpNetwork == null || guestIpNetwork.isEmpty()) printError("Please enter a valid guest IP network address."); -// if (guestNetmask == null || guestNetmask.isEmpty()) printError("Please enter a valid guest IP network netmask"); -// -// return NetUtils.getSubNet(guestIpNetwork, guestNetmask); -// } - -// public static long getGuestCidrSize() { -// String guestNetmask = getGuestNetmask(); -// return NetUtils.getCidrSize(guestNetmask); -// } - public static boolean validCIDR(final String cidr) { if (cidr == null || cidr.isEmpty()) { return false; diff --git a/server/src/com/cloud/user/AccountManagerImpl.java b/server/src/com/cloud/user/AccountManagerImpl.java index fa441ae65dd..186cfb2afa2 100755 --- a/server/src/com/cloud/user/AccountManagerImpl.java +++ b/server/src/com/cloud/user/AccountManagerImpl.java @@ -21,6 +21,7 @@ import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; @@ -37,8 +38,6 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; -import org.apache.commons.codec.binary.Base64; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.ControlledEntity; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.acl.SecurityChecker; @@ -112,6 +111,7 @@ import com.cloud.projects.ProjectVO; import com.cloud.projects.dao.ProjectAccountDao; import com.cloud.projects.dao.ProjectDao; import com.cloud.server.auth.UserAuthenticator; +import com.cloud.server.auth.UserAuthenticator.ActionOnFailedAuthentication; import com.cloud.storage.VMTemplateVO; import com.cloud.storage.Volume; import com.cloud.storage.VolumeApiService; @@ -156,7 +156,7 @@ import com.cloud.vm.dao.InstanceGroupDao; import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.VMInstanceDao; -@Local(value = { AccountManager.class, AccountService.class }) +@Local(value = {AccountManager.class, AccountService.class}) public class AccountManagerImpl extends ManagerBase implements AccountManager, Manager { public static final Logger s_logger = Logger.getLogger(AccountManagerImpl.class); @@ -345,7 +345,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M @Override public boolean isAdmin(short accountType) { return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) || - (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN)); + (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN)); } @Override @@ -381,7 +381,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M @Override public void checkAccess(Account caller, AccessType accessType, boolean sameOwner, ControlledEntity... entities) { - + //check for the same owner Long ownerId = null; ControlledEntity prevEntity = null; @@ -395,7 +395,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M } prevEntity = entity; } - } + } } if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || isRootAdmin(caller.getType())) { @@ -416,7 +416,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M domainId = account != null ? account.getDomainId() : -1; } if (entity.getAccountId() != -1 && domainId != -1 && !(entity instanceof VirtualMachineTemplate) && - !(accessType != null && accessType == AccessType.UseNetwork) && !(entity instanceof AffinityGroup)) { + !(accessType != null && accessType == AccessType.UseNetwork) && !(entity instanceof AffinityGroup)) { List toBeChecked = domains.get(entity.getDomainId()); // for templates, we don't have to do cross domains check if (toBeChecked == null) { @@ -680,7 +680,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M ReservationContext context = new ReservationContextImpl(null, null, getActiveUser(callerUserId), caller); - if (!_networkMgr.destroyNetwork(network.getId(), context)) { + if (!_networkMgr.destroyNetwork(network.getId(), context, false)) { s_logger.warn("Unable to destroy network " + network + " as a part of account id=" + accountId + " cleanup."); accountCleanupNeeded = true; networksDeleted = false; @@ -751,11 +751,14 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M // release account specific acquired portable IP's. Since all the portable IP's must have been already // disassociated with VPC/guest network (due to deletion), so just mark portable IP as free. - List portableIpsToRelease = _ipAddressDao.listByAccount(accountId); - for (IpAddress ip : portableIpsToRelease) { - s_logger.debug("Releasing portable ip " + ip + " as a part of account id=" + accountId + " cleanup"); - _ipAddrMgr.releasePortableIpAddress(ip.getId()); + List ipsToRelease = _ipAddressDao.listByAccount(accountId); + for (IpAddress ip : ipsToRelease) { + if (ip.isPortable()) { + s_logger.debug("Releasing portable ip " + ip + " as a part of account id=" + accountId + " cleanup"); + _ipAddrMgr.releasePortableIpAddress(ip.getId()); + } } + // release dedication if any List dedicatedResources = _dedicatedDao.listByAccountId(accountId); if (dedicatedResources != null && !dedicatedResources.isEmpty()) { @@ -864,12 +867,13 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M @Override @DB @ActionEvents({ - @ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_CREATE, eventDescription = "creating Account"), - @ActionEvent(eventType = EventTypes.EVENT_USER_CREATE, eventDescription = "creating User") + @ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_CREATE, eventDescription = "creating Account"), + @ActionEvent(eventType = EventTypes.EVENT_USER_CREATE, eventDescription = "creating User") }) - public UserAccount createUserAccount(final String userName, final String password, final String firstName, final String lastName, final String email, final String timezone, String accountName, - final short accountType, - Long domainId, final String networkDomain, final Map details, String accountUUID, final String userUUID) { + public UserAccount createUserAccount(final String userName, final String password, final String firstName, final String lastName, final String email, + final String timezone, String accountName, + final short accountType, + Long domainId, final String networkDomain, final Map details, String accountUUID, final String userUUID) { if (accountName == null) { accountName = userName; @@ -906,8 +910,8 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M if (networkDomain != null) { if (!NetUtils.verifyDomainName(networkDomain)) { throw new InvalidParameterValueException( - "Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " - + "and the hyphen ('-'); can't start or end with \"-\""); + "Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " + + "and the hyphen ('-'); can't start or end with \"-\""); } } @@ -950,7 +954,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M @Override @ActionEvent(eventType = EventTypes.EVENT_USER_CREATE, eventDescription = "creating User") public UserVO createUser(String userName, String password, String firstName, String lastName, String email, String timeZone, String accountName, Long domainId, - String userUUID) { + String userUUID) { // default domain to ROOT if not specified if (domainId == null) { @@ -1265,7 +1269,8 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M @Override @ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_DELETE, eventDescription = "deleting account", async = true) // This method deletes the account - public boolean deleteUserAccount(long accountId) { + public + boolean deleteUserAccount(long accountId) { CallContext ctx = CallContext.current(); long callerUserId = ctx.getCallingUserId(); @@ -1356,7 +1361,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) { throw new InvalidParameterValueException("Unable to find active account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + - domainId); + domainId); } if (account.getId() == Account.ACCOUNT_ID_SYSTEM) { @@ -1445,14 +1450,14 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M // update // itself throw new InvalidParameterValueException("There already exists an account with the name:" + newAccountName + " in the domain:" + domainId + - " with existing account id:" + duplicateAcccount.getId()); + " with existing account id:" + duplicateAcccount.getId()); } if (networkDomain != null && !networkDomain.isEmpty()) { if (!NetUtils.verifyDomainName(networkDomain)) { throw new InvalidParameterValueException( - "Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " - + "and the hyphen ('-'); can't start or end with \"-\""); + "Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " + + "and the hyphen ('-'); can't start or end with \"-\""); } } @@ -1690,18 +1695,18 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M // Account type to role type translation switch (accountType) { - case Account.ACCOUNT_TYPE_ADMIN: - roleType = RoleType.Admin; - break; - case Account.ACCOUNT_TYPE_DOMAIN_ADMIN: - roleType = RoleType.DomainAdmin; - break; - case Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN: - roleType = RoleType.ResourceAdmin; - break; - case Account.ACCOUNT_TYPE_NORMAL: - roleType = RoleType.User; - break; + case Account.ACCOUNT_TYPE_ADMIN: + roleType = RoleType.Admin; + break; + case Account.ACCOUNT_TYPE_DOMAIN_ADMIN: + roleType = RoleType.DomainAdmin; + break; + case Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN: + roleType = RoleType.ResourceAdmin; + break; + case Account.ACCOUNT_TYPE_NORMAL: + roleType = RoleType.User; + break; } return roleType; } @@ -1731,7 +1736,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M @Override @DB public AccountVO createAccount(final String accountName, final short accountType, final Long domainId, final String networkDomain, final Map details, - final String uuid) { + final String uuid) { // Validate domain Domain domain = _domainMgr.getDomain(domainId); if (domain == null) { @@ -1754,8 +1759,8 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M if (networkDomain != null) { if (!NetUtils.verifyDomainName(networkDomain)) { throw new InvalidParameterValueException( - "Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " - + "and the hyphen ('-'); can't start or end with \"-\""); + "Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " + + "and the hyphen ('-'); can't start or end with \"-\""); } } @@ -1860,7 +1865,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M List parameterNames = new ArrayList(); for (Object paramNameObj : requestParameters.keySet()) { - parameterNames.add((String) paramNameObj); // put the name in a list that we'll sort later + parameterNames.add((String)paramNameObj); // put the name in a list that we'll sort later } Collections.sort(parameterNames); @@ -1868,7 +1873,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M try { for (String paramName : parameterNames) { // parameters come as name/value pairs in the form String/String[] - String paramValue = ((String[]) requestParameters.get(paramName))[0]; + String paramValue = ((String[])requestParameters.get(paramName))[0]; if ("signature".equalsIgnoreCase(paramName)) { signature = paramValue; @@ -1941,10 +1946,10 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M } if (NetUtils.isValidIp(loginIpAddress)) { ActionEventUtils.onActionEvent(user.getId(), user.getAccountId(), user.getDomainId(), EventTypes.EVENT_USER_LOGIN, "user has logged in from IP Address " + - loginIpAddress); + loginIpAddress); } else { ActionEventUtils.onActionEvent(user.getId(), user.getAccountId(), user.getDomainId(), EventTypes.EVENT_USER_LOGIN, - "user has logged in. The IP Address cannot be determined"); + "user has logged in. The IP Address cannot be determined"); } return user; } else { @@ -1961,13 +1966,19 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M } boolean authenticated = false; + HashSet actionsOnFailedAuthenticaion = new HashSet(); for (UserAuthenticator authenticator : _userAuthenticators) { - if (authenticator.authenticate(username, password, domainId, requestParameters)) { + Pair result = authenticator.authenticate(username, password, domainId, requestParameters); + if (result.first()) { authenticated = true; break; + } else if (result.second() != null) { + actionsOnFailedAuthenticaion.add(result.second()); } } + boolean updateIncorrectLoginCount = actionsOnFailedAuthenticaion.contains(ActionOnFailedAuthentication.INCREMENT_INCORRECT_LOGIN_ATTEMPT_COUNT); + if (authenticated) { UserAccount userAccount = _userAccountDao.getUserAccount(username, domainId); if (userAccount == null) { @@ -1982,7 +1993,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M } if (!userAccount.getState().equalsIgnoreCase(Account.State.enabled.toString()) || - !userAccount.getAccountState().equalsIgnoreCase(Account.State.enabled.toString())) { + !userAccount.getAccountState().equalsIgnoreCase(Account.State.enabled.toString())) { if (s_logger.isInfoEnabled()) { s_logger.info("User " + username + " in domain " + domainName + " is disabled/locked (or account is disabled/locked)"); } @@ -2005,12 +2016,14 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M if (!isInternalAccount(userAccount.getType())) { // Internal accounts are not disabled int attemptsMade = userAccount.getLoginAttempts() + 1; - if (attemptsMade < _allowedLoginAttempts) { - updateLoginAttempts(userAccount.getId(), attemptsMade, false); - s_logger.warn("Login attempt failed. You have " + (_allowedLoginAttempts - attemptsMade) + " attempt(s) remaining"); - } else { - updateLoginAttempts(userAccount.getId(), _allowedLoginAttempts, true); - s_logger.warn("User " + userAccount.getUsername() + " has been disabled due to multiple failed login attempts." + " Please contact admin."); + if (updateIncorrectLoginCount) { + if (attemptsMade < _allowedLoginAttempts) { + updateLoginAttempts(userAccount.getId(), attemptsMade, false); + s_logger.warn("Login attempt failed. You have " + (_allowedLoginAttempts - attemptsMade) + " attempt(s) remaining"); + } else { + updateLoginAttempts(userAccount.getId(), _allowedLoginAttempts, true); + s_logger.warn("User " + userAccount.getUsername() + " has been disabled due to multiple failed login attempts." + " Please contact admin."); + } } } } else { @@ -2114,14 +2127,14 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M @Override public void buildACLSearchBuilder(SearchBuilder sb, Long domainId, boolean isRecursive, List permittedAccounts, - ListProjectResourcesCriteria listProjectResourcesCriteria) { + ListProjectResourcesCriteria listProjectResourcesCriteria) { if (sb.entity() instanceof IPAddressVO) { - sb.and("accountIdIN", ((IPAddressVO) sb.entity()).getAllocatedToAccountId(), SearchCriteria.Op.IN); - sb.and("domainId", ((IPAddressVO) sb.entity()).getAllocatedInDomainId(), SearchCriteria.Op.EQ); + sb.and("accountIdIN", ((IPAddressVO)sb.entity()).getAllocatedToAccountId(), SearchCriteria.Op.IN); + sb.and("domainId", ((IPAddressVO)sb.entity()).getAllocatedInDomainId(), SearchCriteria.Op.EQ); } else if (sb.entity() instanceof ProjectInvitationVO) { - sb.and("accountIdIN", ((ProjectInvitationVO) sb.entity()).getForAccountId(), SearchCriteria.Op.IN); - sb.and("domainId", ((ProjectInvitationVO) sb.entity()).getInDomainId(), SearchCriteria.Op.EQ); + sb.and("accountIdIN", ((ProjectInvitationVO)sb.entity()).getForAccountId(), SearchCriteria.Op.IN); + sb.and("domainId", ((ProjectInvitationVO)sb.entity()).getInDomainId(), SearchCriteria.Op.EQ); } else { sb.and("accountIdIN", sb.entity().getAccountId(), SearchCriteria.Op.IN); sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); @@ -2133,9 +2146,9 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); if (sb.entity() instanceof IPAddressVO) { - sb.join("domainSearch", domainSearch, ((IPAddressVO) sb.entity()).getAllocatedInDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); + sb.join("domainSearch", domainSearch, ((IPAddressVO)sb.entity()).getAllocatedInDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); } else if (sb.entity() instanceof ProjectInvitationVO) { - sb.join("domainSearch", domainSearch, ((ProjectInvitationVO) sb.entity()).getInDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); + sb.join("domainSearch", domainSearch, ((ProjectInvitationVO)sb.entity()).getInDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); } else { sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); } @@ -2150,9 +2163,9 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M } if (sb.entity() instanceof IPAddressVO) { - sb.join("accountSearch", accountSearch, ((IPAddressVO) sb.entity()).getAllocatedToAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); + sb.join("accountSearch", accountSearch, ((IPAddressVO)sb.entity()).getAllocatedToAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); } else if (sb.entity() instanceof ProjectInvitationVO) { - sb.join("accountSearch", accountSearch, ((ProjectInvitationVO) sb.entity()).getForAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); + sb.join("accountSearch", accountSearch, ((ProjectInvitationVO)sb.entity()).getForAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); } else { sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); } @@ -2161,7 +2174,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M @Override public void buildACLSearchCriteria(SearchCriteria sc, Long domainId, boolean isRecursive, List permittedAccounts, - ListProjectResourcesCriteria listProjectResourcesCriteria) { + ListProjectResourcesCriteria listProjectResourcesCriteria) { if (listProjectResourcesCriteria != null) { sc.setJoinParameters("accountSearch", "type", Account.ACCOUNT_TYPE_PROJECT); @@ -2181,8 +2194,8 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M @Override public void buildACLSearchParameters(Account caller, Long id, String accountName, Long projectId, List - permittedAccounts, Ternary domainIdRecursiveListProject, - boolean listAll, boolean forProjectInvitation) { + permittedAccounts, Ternary domainIdRecursiveListProject, + boolean listAll, boolean forProjectInvitation) { Long domainId = domainIdRecursiveListProject.first(); if (domainId != null) { Domain domain = _domainDao.findById(domainId); @@ -2268,7 +2281,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M @Override public void buildACLViewSearchBuilder(SearchBuilder sb, Long domainId, boolean isRecursive, List permittedAccounts, - ListProjectResourcesCriteria listProjectResourcesCriteria) { + ListProjectResourcesCriteria listProjectResourcesCriteria) { sb.and("accountIdIN", sb.entity().getAccountId(), SearchCriteria.Op.IN); sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); @@ -2291,7 +2304,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M @Override public void buildACLViewSearchCriteria(SearchCriteria sc, Long domainId, boolean isRecursive, List permittedAccounts, - ListProjectResourcesCriteria listProjectResourcesCriteria) { + ListProjectResourcesCriteria listProjectResourcesCriteria) { if (listProjectResourcesCriteria != null) { sc.setParameters("accountType", Account.ACCOUNT_TYPE_PROJECT); diff --git a/server/src/com/cloud/user/DomainManagerImpl.java b/server/src/com/cloud/user/DomainManagerImpl.java index 89a918ee68e..b2a478ef096 100644 --- a/server/src/com/cloud/user/DomainManagerImpl.java +++ b/server/src/com/cloud/user/DomainManagerImpl.java @@ -395,8 +395,7 @@ public class DomainManagerImpl extends ManagerBase implements DomainManager, Dom ReservationContext context = new ReservationContextImpl(null, null, _accountMgr.getActiveUser(ctx.getCallingUserId()), ctx.getCallingAccount()); for (Long networkId : networkIds) { s_logger.debug("Deleting network id=" + networkId + " as a part of domain id=" + domainId + " cleanup"); - - if (!_networkMgr.destroyNetwork(networkId, context)) { + if (!_networkMgr.destroyNetwork(networkId, context, false)) { s_logger.warn("Unable to destroy network id=" + networkId + " as a part of domain id=" + domainId + " cleanup."); networksDeleted = false; } else { diff --git a/server/src/com/cloud/uuididentity/UUIDManager.java b/server/src/com/cloud/uuididentity/UUIDManager.java index 6bef87a1cde..ecf238c9e09 100644 --- a/server/src/com/cloud/uuididentity/UUIDManager.java +++ b/server/src/com/cloud/uuididentity/UUIDManager.java @@ -16,7 +16,6 @@ // under the License. package com.cloud.uuididentity; -import org.apache.cloudstack.api.Identity; public interface UUIDManager { diff --git a/server/src/com/cloud/uuididentity/UUIDManagerImpl.java b/server/src/com/cloud/uuididentity/UUIDManagerImpl.java index 852b2dcaf7d..09ba3d1c18f 100644 --- a/server/src/com/cloud/uuididentity/UUIDManagerImpl.java +++ b/server/src/com/cloud/uuididentity/UUIDManagerImpl.java @@ -16,84 +16,82 @@ // under the License. package com.cloud.uuididentity; +import java.util.UUID; + +import javax.ejb.Local; +import javax.inject.Inject; + +import org.apache.cloudstack.context.CallContext; + import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.PermissionDeniedException; -import com.cloud.storage.Volume; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.utils.db.EntityManager; import com.cloud.utils.exception.CloudRuntimeException; -import org.apache.cloudstack.acl.ControlledEntity; -import org.apache.cloudstack.api.Identity; -import org.apache.cloudstack.context.CallContext; -import javax.ejb.Local; -import javax.inject.Inject; -import java.util.UUID; - -@Local(value = { UUIDManager.class }) +@Local(value = {UUIDManager.class}) public class UUIDManagerImpl implements UUIDManager { - @Inject EntityManager _entityMgr; @Inject AccountManager _accountMgr; //TODO - Make this configurable. - private final int UUID_RETRY = 3; - + private static final int UUID_RETRY = 3; @Override - public void checkUuid(String uuid, Class entityType){ + public void checkUuid(String uuid, Class entityType) { - if(uuid == null) return; + if (uuid == null) + return; Account caller = CallContext.current().getCallingAccount(); // Only admin and system allowed to do this - if ( !(caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getType())) ) { + if (!(caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getType()))) { throw new PermissionDeniedException("Please check your permissions, you are not allowed to create/update custom id"); } // check format - if(!IsUuidFormat(uuid)) + if (!IsUuidFormat(uuid)) throw new InvalidParameterValueException("UUID: " + uuid + " doesn't follow the UUID format"); // check unique - if(!IsUuidUnique(entityType, uuid)) + if (!IsUuidUnique(entityType, uuid)) throw new InvalidParameterValueException("UUID: " + uuid + " already exists so can't create/update with custom id"); } - public boolean IsUuidFormat(String uuid){ + public boolean IsUuidFormat(String uuid) { // Match against UUID regex to check if input is uuid string boolean isUuid = uuid.matches("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"); return isUuid; } - public boolean IsUuidUnique(Class entityType, String uuid){ + public boolean IsUuidUnique(Class entityType, String uuid) { T obj = _entityMgr.findByUuid(entityType, uuid); - if(obj != null) + if (obj != null) return false; else return true; } @Override - public String generateUuid(Class entityType, String customId){ + public String generateUuid(Class entityType, String customId) { - if(customId == null){ // if no customid is passed then generate it. + if (customId == null) { // if no customid is passed then generate it. int retry = UUID_RETRY; while (retry-- != 0) { // there might be collision so retry String uuid = UUID.randomUUID().toString(); - if(IsUuidUnique(entityType, uuid)) + if (IsUuidUnique(entityType, uuid)) return uuid; } throw new CloudRuntimeException("Unable to generate a unique uuid, please try again"); - }else { + } else { checkUuid(customId, entityType); return customId; } diff --git a/server/src/com/cloud/uuididentity/dao/IdentityDaoImpl.java b/server/src/com/cloud/uuididentity/dao/IdentityDaoImpl.java deleted file mode 100644 index c5d2c434b0b..00000000000 --- a/server/src/com/cloud/uuididentity/dao/IdentityDaoImpl.java +++ /dev/null @@ -1,241 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.uuididentity.dao; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -import javax.ejb.Local; - -import org.apache.log4j.Logger; -import org.springframework.stereotype.Component; - -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.server.ResourceTag.ResourceObjectType; -import com.cloud.utils.Pair; -import com.cloud.utils.db.DB; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.TransactionLegacy; - -@Component -@Local(value = {IdentityDao.class}) -public class IdentityDaoImpl extends GenericDaoBase implements IdentityDao { - private static final Logger s_logger = Logger.getLogger(IdentityDaoImpl.class); - - public IdentityDaoImpl() { - } - - @Override - @DB - public Long getIdentityId(String tableName, String identityString) { - assert (tableName != null); - assert (identityString != null); - - PreparedStatement pstmt = null; - TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB); - try { - try { - try { - pstmt = txn.prepareAutoCloseStatement(String.format("SELECT uuid FROM `%s`", tableName)); - pstmt.executeQuery(); - } catch (SQLException e) { - throw new InvalidParameterValueException("uuid field doesn't exist in table " + tableName); - } - - pstmt = txn.prepareAutoCloseStatement(String.format("SELECT id FROM `%s` WHERE id=? OR uuid=?", tableName) - - // TODO : after graceful period, use following line turn on more secure check - // String.format("SELECT id FROM %s WHERE (id=? AND uuid IS NULL) OR uuid=?", mapper.entityTableName()) - ); - - long id = 0; - try { - // TODO : use regular expression to determine - id = Long.parseLong(identityString); - } catch (NumberFormatException e) { - // this could happen when it is a uuid string, so catch and ignore it - } - - pstmt.setLong(1, id); - pstmt.setString(2, identityString); - - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) { - return rs.getLong(1); - } else { - if (id == -1L) - return id; - - throw new InvalidParameterValueException("Object " + tableName + "(uuid: " + identityString + ") does not exist."); - } - } catch (SQLException e) { - s_logger.error("Unexpected exception ", e); - } - } finally { - txn.close(); - } - return null; - } - - @DB - @Override - public Pair getAccountDomainInfo(String tableName, Long identityId, ResourceObjectType resourceType) { - assert (tableName != null); - - PreparedStatement pstmt = null; - TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB); - try { - Long domainId = null; - Long accountId = null; - //get domainId - try { - pstmt = txn.prepareAutoCloseStatement(String.format("SELECT domain_id FROM `%s` WHERE id=?", tableName)); - pstmt.setLong(1, identityId); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) { - if (rs.getLong(1) != 0) { - domainId = rs.getLong(1); - } - } - } catch (SQLException e) { - } - - //get accountId - try { - String account = "account_id"; - if (resourceType == ResourceObjectType.Project) { - account = "project_account_id"; - } - pstmt = txn.prepareAutoCloseStatement(String.format("SELECT " + account + " FROM `%s` WHERE id=?", tableName)); - pstmt.setLong(1, identityId); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) { - if (rs.getLong(1) != 0) { - accountId = rs.getLong(1); - } - } - } catch (SQLException e) { - } - return new Pair(accountId, domainId); - } finally { - txn.close(); - } - } - - @DB - @Override - public String getIdentityUuid(String tableName, String identityString) { - assert (tableName != null); - assert (identityString != null); - - PreparedStatement pstmt = null; - TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB); - try { - try { - pstmt = txn.prepareAutoCloseStatement(String.format("SELECT uuid FROM `%s` WHERE id=? OR uuid=?", tableName) - // String.format("SELECT uuid FROM %s WHERE (id=? AND uuid IS NULL) OR uuid=?", tableName) - ); - - long id = 0; - try { - // TODO : use regular expression to determine - id = Long.parseLong(identityString); - } catch (NumberFormatException e) { - // this could happen when it is a uuid string, so catch and ignore it - } - - pstmt.setLong(1, id); - pstmt.setString(2, identityString); - - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) { - String uuid = rs.getString(1); - if (uuid != null && !uuid.isEmpty()) - return uuid; - return identityString; - } - } catch (SQLException e) { - s_logger.error("Unexpected exception ", e); - } - } finally { - txn.close(); - } - - return identityString; - } - - @Override - @DB - public void initializeDefaultUuid(String tableName) { - assert (tableName != null); - List l = getNullUuidRecords(tableName); - - TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB); - try { - try { - txn.start(); - for (Long id : l) { - setInitialUuid(tableName, id); - } - txn.commit(); - } catch (SQLException e) { - txn.rollback(); - s_logger.error("Unexpected exception ", e); - } - } finally { - txn.close(); - } - } - - @DB - List getNullUuidRecords(String tableName) { - List l = new ArrayList(); - - PreparedStatement pstmt = null; - TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB); - try { - try { - pstmt = txn.prepareAutoCloseStatement(String.format("SELECT id FROM `%s` WHERE uuid IS NULL", tableName)); - - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) { - l.add(rs.getLong(1)); - } - } catch (SQLException e) { - s_logger.error("Unexpected exception ", e); - } - } finally { - txn.close(); - } - return l; - } - - @DB - void setInitialUuid(String tableName, long id) throws SQLException { - TransactionLegacy txn = TransactionLegacy.currentTxn(); - - PreparedStatement pstmtUpdate = null; - pstmtUpdate = txn.prepareAutoCloseStatement(String.format("UPDATE `%s` SET uuid=? WHERE id=?", tableName)); - - pstmtUpdate.setString(1, String.valueOf(id)); - pstmtUpdate.setLong(2, id); - pstmtUpdate.executeUpdate(); - } -} diff --git a/server/src/com/cloud/vm/SystemVmLoadScanner.java b/server/src/com/cloud/vm/SystemVmLoadScanner.java index 28c900d9d7a..97f9dcdaab4 100644 --- a/server/src/com/cloud/vm/SystemVmLoadScanner.java +++ b/server/src/com/cloud/vm/SystemVmLoadScanner.java @@ -44,7 +44,7 @@ public class SystemVmLoadScanner { private final SystemVmLoadScanHandler _scanHandler; private final ScheduledExecutorService _capacityScanScheduler; private final GlobalLock _capacityScanLock; - + public SystemVmLoadScanner(SystemVmLoadScanHandler scanHandler) { _scanHandler = scanHandler; _capacityScanScheduler = Executors.newScheduledThreadPool(1, new NamedThreadFactory(scanHandler.getScanHandlerName())); @@ -71,15 +71,15 @@ public class SystemVmLoadScanner { @Override protected void runInContext() { - try { - CallContext callContext = CallContext.current(); - assert(callContext != null); - - AsyncJobExecutionContext.registerPseudoExecutionContext( - callContext.getCallingAccountId(), callContext.getCallingUserId()); - + try { + CallContext callContext = CallContext.current(); + assert (callContext != null); + + AsyncJobExecutionContext.registerPseudoExecutionContext( + callContext.getCallingAccountId(), callContext.getCallingUserId()); + reallyRun(); - + AsyncJobExecutionContext.unregister(); } catch (Throwable e) { s_logger.warn("Unexpected exception " + e.getMessage(), e); diff --git a/server/src/com/cloud/vm/UserVmManager.java b/server/src/com/cloud/vm/UserVmManager.java index da60f330abd..950e7e37094 100755 --- a/server/src/com/cloud/vm/UserVmManager.java +++ b/server/src/com/cloud/vm/UserVmManager.java @@ -46,7 +46,7 @@ import com.cloud.utils.Pair; public interface UserVmManager extends UserVmService { static final String EnableDynamicallyScaleVmCK = "enable.dynamic.scale.vm"; static final ConfigKey EnableDynamicallyScaleVm = new ConfigKey("Advanced", Boolean.class, EnableDynamicallyScaleVmCK, "false", - "Enables/Diables dynamically scaling a vm", true, ConfigKey.Scope.Zone); + "Enables/Disables dynamically scaling a vm", true, ConfigKey.Scope.Zone); static final int MAX_USER_DATA_LENGTH_BYTES = 2048; @@ -110,7 +110,8 @@ public interface UserVmManager extends UserVmService { Pair> startVirtualMachine(long vmId, Long hostId, Map additionalParams) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; - boolean upgradeVirtualMachine(Long id, Long serviceOfferingId, Map customParameters) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, + boolean upgradeVirtualMachine(Long id, Long serviceOfferingId, Map customParameters) throws ResourceUnavailableException, + ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException; boolean setupVmForPvlan(boolean add, Long hostId, NicProfile nic); @@ -118,7 +119,7 @@ public interface UserVmManager extends UserVmService { void collectVmDiskStatistics(UserVmVO userVm); UserVm updateVirtualMachine(long id, String displayName, String group, Boolean ha, Boolean isDisplayVmEnabled, Long osTypeId, String userData, - Boolean isDynamicallyScalable, HTTPMethod httpMethod, String customId) throws ResourceUnavailableException, InsufficientCapacityException; + Boolean isDynamicallyScalable, HTTPMethod httpMethod, String customId) throws ResourceUnavailableException, InsufficientCapacityException; //the validateCustomParameters, save and remove CustomOfferingDetils functions can be removed from the interface once we can //find a common place for all the scaling and upgrading code of both user and systemvms. diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java index fa45cc8ed90..1dcaf798a5d 100755 --- a/server/src/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/com/cloud/vm/UserVmManagerImpl.java @@ -34,10 +34,6 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; -import com.cloud.event.UsageEventVO; -import com.cloud.uuididentity.UUIDManager; -import com.cloud.capacity.Capacity; -import com.cloud.exception.InsufficientServerCapacityException; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; @@ -86,8 +82,6 @@ import org.apache.cloudstack.managed.context.ManagedContextRunnable; import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; import org.apache.cloudstack.storage.to.TemplateObjectTO; -import org.apache.commons.codec.binary.Base64; -import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; @@ -107,6 +101,7 @@ import com.cloud.alert.AlertManager; import com.cloud.api.ApiDBUtils; import com.cloud.api.query.dao.UserVmJoinDao; import com.cloud.api.query.vo.UserVmJoinVO; +import com.cloud.capacity.Capacity; import com.cloud.capacity.CapacityManager; import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationManager; @@ -130,6 +125,7 @@ import com.cloud.domain.dao.DomainDao; import com.cloud.event.ActionEvent; import com.cloud.event.EventTypes; import com.cloud.event.UsageEventUtils; +import com.cloud.event.UsageEventVO; import com.cloud.event.dao.UsageEventDao; import com.cloud.exception.AgentUnavailableException; import com.cloud.exception.CloudException; @@ -261,6 +257,7 @@ import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.ExecutionException; import com.cloud.utils.fsm.NoTransitionException; import com.cloud.utils.net.NetUtils; +import com.cloud.uuididentity.UUIDManager; import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.dao.InstanceGroupDao; import com.cloud.vm.dao.InstanceGroupVMMapDao; @@ -374,6 +371,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir @Inject protected NicDao _nicDao; @Inject + protected ServiceOfferingDao _offerringDao; + @Inject protected VpcDao _vpcDao; @Inject protected RulesManager _rulesMgr; @@ -460,7 +459,6 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir protected boolean _dailyOrHourly = false; private int capacityReleaseInterval; - protected String _name; protected String _instance; protected String _zone; protected boolean _instanceNameFlag; @@ -468,9 +466,9 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir @Inject ConfigurationDao _configDao; - private final int MAX_VM_NAME_LEN = 80; - private final int MAX_HTTP_GET_LENGTH = 2 * MAX_USER_DATA_LENGTH_BYTES; - private final int MAX_HTTP_POST_LENGTH = 16 * MAX_USER_DATA_LENGTH_BYTES; + private static final int MAX_VM_NAME_LEN = 80; + private static final int MAX_HTTP_GET_LENGTH = 2 * MAX_USER_DATA_LENGTH_BYTES; + private static final int MAX_HTTP_POST_LENGTH = 16 * MAX_USER_DATA_LENGTH_BYTES; @Inject protected OrchestrationService _orchSrvc; @@ -488,22 +486,22 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir return _vmDao.listByHostId(hostId); } - protected void resourceLimitCheck(Account owner, Long cpu, Long memory) throws ResourceAllocationException { - _resourceLimitMgr.checkResourceLimit(owner, ResourceType.user_vm); - _resourceLimitMgr.checkResourceLimit(owner, ResourceType.cpu, cpu); - _resourceLimitMgr.checkResourceLimit(owner, ResourceType.memory, memory); + protected void resourceLimitCheck(Account owner, Boolean displayVm, Long cpu, Long memory) throws ResourceAllocationException { + _resourceLimitMgr.checkResourceLimit(owner, ResourceType.user_vm, displayVm); + _resourceLimitMgr.checkResourceLimit(owner, ResourceType.cpu, displayVm, cpu); + _resourceLimitMgr.checkResourceLimit(owner, ResourceType.memory, displayVm, memory); } - protected void resourceCountIncrement(long accountId, Long cpu, Long memory) { - _resourceLimitMgr.incrementResourceCount(accountId, ResourceType.user_vm); - _resourceLimitMgr.incrementResourceCount(accountId, ResourceType.cpu, cpu); - _resourceLimitMgr.incrementResourceCount(accountId, ResourceType.memory, memory); + protected void resourceCountIncrement(long accountId, Boolean displayVm, Long cpu, Long memory) { + _resourceLimitMgr.incrementResourceCount(accountId, ResourceType.user_vm, displayVm); + _resourceLimitMgr.incrementResourceCount(accountId, ResourceType.cpu, displayVm, cpu); + _resourceLimitMgr.incrementResourceCount(accountId, ResourceType.memory, displayVm, memory); } - protected void resourceCountDecrement(long accountId, Long cpu, Long memory) { - _resourceLimitMgr.decrementResourceCount(accountId, ResourceType.user_vm); - _resourceLimitMgr.decrementResourceCount(accountId, ResourceType.cpu, cpu); - _resourceLimitMgr.decrementResourceCount(accountId, ResourceType.memory, memory); + protected void resourceCountDecrement(long accountId, Boolean displayVm, Long cpu, Long memory) { + _resourceLimitMgr.decrementResourceCount(accountId, ResourceType.user_vm, displayVm); + _resourceLimitMgr.decrementResourceCount(accountId, ResourceType.cpu, displayVm, cpu); + _resourceLimitMgr.decrementResourceCount(accountId, ResourceType.memory, displayVm, memory); } @Override @@ -563,8 +561,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } Network defaultNetwork = _networkDao.findById(defaultNic.getNetworkId()); - NicProfile defaultNicProfile = - new NicProfile(defaultNic, defaultNetwork, null, null, null, _networkModel.isSecurityGroupSupportedInNetwork(defaultNetwork), + NicProfile defaultNicProfile = new NicProfile(defaultNic, defaultNetwork, null, null, null, _networkModel.isSecurityGroupSupportedInNetwork(defaultNetwork), _networkModel.getNetworkTag(template.getHypervisorType(), defaultNetwork)); VirtualMachineProfile vmProfile = new VirtualMachineProfileImpl(vmInstance); vmProfile.setParameter(VirtualMachineProfile.Param.VmPassword, password); @@ -632,8 +629,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir SSHKeyPairVO s = _sshKeyPairDao.findByName(owner.getAccountId(), owner.getDomainId(), cmd.getName()); if (s == null) { - throw new InvalidParameterValueException("A key pair with name '" + cmd.getName() + "' does not exist for account " + owner.getAccountName() + - " in specified domain id"); + throw new InvalidParameterValueException("A key pair with name '" + cmd.getName() + "' does not exist for account " + owner.getAccountName() + + " in specified domain id"); } _accountMgr.checkAccess(caller, null, true, userVm); @@ -659,7 +656,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir return userVm; } - private boolean resetVMSSHKeyInternal(Long vmId, String SSHPublicKey, String password) throws ResourceUnavailableException, InsufficientCapacityException { + private boolean resetVMSSHKeyInternal(Long vmId, String sshPublicKey, String password) throws ResourceUnavailableException, InsufficientCapacityException { Long userId = CallContext.current().getCallingUserId(); VMInstanceVO vmInstance = _vmDao.findById(vmId); @@ -671,9 +668,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } Network defaultNetwork = _networkDao.findById(defaultNic.getNetworkId()); - NicProfile defaultNicProfile = - new NicProfile(defaultNic, defaultNetwork, null, null, null, _networkModel.isSecurityGroupSupportedInNetwork(defaultNetwork), _networkModel.getNetworkTag( - template.getHypervisorType(), defaultNetwork)); + NicProfile defaultNicProfile = new NicProfile(defaultNic, defaultNetwork, null, null, null, _networkModel.isSecurityGroupSupportedInNetwork(defaultNetwork), + _networkModel.getNetworkTag(template.getHypervisorType(), defaultNetwork)); VirtualMachineProfile vmProfile = new VirtualMachineProfileImpl(vmInstance); @@ -685,7 +681,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir if (element == null) { throw new CloudRuntimeException("Can't find network element for " + Service.UserData.getName() + " provider needed for SSH Key reset"); } - boolean result = element.saveSSHKey(defaultNetwork, defaultNicProfile, vmProfile, SSHPublicKey); + boolean result = element.saveSSHKey(defaultNetwork, defaultNicProfile, vmProfile, sshPublicKey); // Need to reboot the virtual machine so that the password gets redownloaded from the DomR, and reset on the VM if (!result) { @@ -762,8 +758,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir * TODO: cleanup eventually - Refactored API call */ // This method will be deprecated as we use ScaleVMCmd for both stopped VMs and running VMs - public - UserVm upgradeVirtualMachine(UpgradeVMCmd cmd) throws ResourceAllocationException { + public UserVm upgradeVirtualMachine(UpgradeVMCmd cmd) throws ResourceAllocationException { Long vmId = cmd.getId(); Long svcOffId = cmd.getServiceOfferingId(); Account caller = CallContext.current().getCallingAccount(); @@ -773,19 +768,19 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId); if (vmInstance == null) { throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); - }else if (!(vmInstance.getState().equals(State.Stopped))) { - throw new InvalidParameterValueException("Unable to upgrade virtual machine " + vmInstance.toString() + " " + " in state " + vmInstance.getState() + - "; make sure the virtual machine is stopped"); + } else if (!(vmInstance.getState().equals(State.Stopped))) { + throw new InvalidParameterValueException("Unable to upgrade virtual machine " + vmInstance.toString() + " " + " in state " + vmInstance.getState() + + "; make sure the virtual machine is stopped"); } _accountMgr.checkAccess(caller, null, true, vmInstance); // Check resource limits for CPU and Memory. - Map customParameters = cmd.getCustomParameters(); + Map customParameters = cmd.getDetails(); ServiceOfferingVO newServiceOffering = _offeringDao.findById(svcOffId); if (newServiceOffering.isDynamic()) { newServiceOffering.setDynamicFlag(true); - validateCustomParameters(newServiceOffering, cmd.getCustomParameters()); + validateCustomParameters(newServiceOffering, cmd.getDetails()); newServiceOffering = _offeringDao.getcomputeOffering(newServiceOffering, customParameters); } ServiceOfferingVO currentServiceOffering = _offeringDao.findByIdIncludingRemoved(vmInstance.getId(), vmInstance.getServiceOfferingId()); @@ -824,7 +819,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir saveCustomOfferingDetails(vmId, newServiceOffering); } if (currentServiceOffering.isDynamic() && !newServiceOffering.isDynamic()) { - removeCustomOfferingDetails(vmId); + removeCustomOfferingDetails(vmId); } // Increment or decrement CPU and Memory count accordingly. @@ -839,30 +834,33 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir _resourceLimitMgr.decrementResourceCount(caller.getAccountId(), ResourceType.memory, new Long(currentMemory - newMemory)); } - generateUsageEvent(newServiceOffering, cmd.getCustomParameters(), _vmDao.findById(vmId), EventTypes.EVENT_VM_UPGRADE); + // Generate usage event for VM upgrade + generateUsageEvent(newServiceOffering, cmd.getDetails(), _vmDao.findById(vmId), EventTypes.EVENT_VM_UPGRADE); return _vmDao.findById(vmInstance.getId()); } @Override public void validateCustomParameters(ServiceOfferingVO serviceOffering, Map customParameters) { - if (customParameters.size() !=0 ) { + if (customParameters.size() != 0) { if (serviceOffering.getCpu() == null) { String cpuNumber = customParameters.get(UsageEventVO.DynamicParameters.cpuNumber.name()); if ((cpuNumber == null) || (NumbersUtil.parseInt(cpuNumber, -1) <= 0 || NumbersUtil.parseInt(cpuNumber, -1) > 2147483647)) { throw new InvalidParameterValueException("Invalid cpu cores value, specify a value between 1 and 2147483647"); } } else if (customParameters.containsKey(UsageEventVO.DynamicParameters.cpuNumber.name())) { - throw new InvalidParameterValueException("The cpu cores of this offering id:"+serviceOffering.getId()+" is not customizable. This is predefined in the template."); + throw new InvalidParameterValueException("The cpu cores of this offering id:" + serviceOffering.getId() + + " is not customizable. This is predefined in the template."); } if (serviceOffering.getSpeed() == null) { String cpuSpeed = customParameters.get(UsageEventVO.DynamicParameters.cpuSpeed.name()); - if ((cpuSpeed == null) || (NumbersUtil.parseInt(cpuSpeed, -1) <= 0 || NumbersUtil.parseInt(cpuSpeed, -1) > 2147483647 )) { + if ((cpuSpeed == null) || (NumbersUtil.parseInt(cpuSpeed, -1) <= 0 || NumbersUtil.parseInt(cpuSpeed, -1) > 2147483647)) { throw new InvalidParameterValueException("Invalid cpu speed value, specify a value between 1 and 2147483647"); } } else if (customParameters.containsKey(UsageEventVO.DynamicParameters.cpuSpeed.name())) { - throw new InvalidParameterValueException("The cpu speed of this offering id:"+serviceOffering.getId()+" is not customizable. This is predefined in the template."); + throw new InvalidParameterValueException("The cpu speed of this offering id:" + serviceOffering.getId() + + " is not customizable. This is predefined in the template."); } if (serviceOffering.getRamSize() == null) { @@ -870,8 +868,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir if (memory == null || (NumbersUtil.parseInt(memory, -1) < 32 || NumbersUtil.parseInt(memory, -1) > 2147483647)) { throw new InvalidParameterValueException("Invalid memory value, specify a value between 32 and 2147483647 MB"); } - } else if (customParameters.containsKey(UsageEventVO.DynamicParameters.memory.name())){ - throw new InvalidParameterValueException("The memory of this offering id:"+serviceOffering.getId()+" is not customizable. This is predefined in the template."); + } else if (customParameters.containsKey(UsageEventVO.DynamicParameters.memory.name())) { + throw new InvalidParameterValueException("The memory of this offering id:" + serviceOffering.getId() + " is not customizable. This is predefined in the template."); } } else { throw new InvalidParameterValueException("Need to specify custom parameter values cpu, cpu speed and memory when using custom offering"); @@ -967,10 +965,14 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir if (network == null) { throw new InvalidParameterValueException("unable to find a network with id " + networkId); } - if (!(network.getGuestType() == Network.GuestType.Shared && network.getAclType() == ACLType.Domain) && - !(network.getAclType() == ACLType.Account && network.getAccountId() == vmInstance.getAccountId())) { - throw new InvalidParameterValueException("only shared network or isolated network with the same account_id can be added to vmId: " + vmId); + + if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { + if (!(network.getGuestType() == Network.GuestType.Shared && network.getAclType() == ACLType.Domain) + && !(network.getAclType() == ACLType.Account && network.getAccountId() == vmInstance.getAccountId())) { + throw new InvalidParameterValueException("only shared network or isolated network with the same account_id can be added to vmId: " + vmId); + } } + List allNics = _nicDao.listByVmId(vmInstance.getId()); for (NicVO nic : allNics) { if (nic.getNetworkId() == network.getId()) @@ -1144,8 +1146,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir if (existing == null) { s_logger.warn("Failed to update default nic, no nic profile found for existing default network"); - throw new CloudRuntimeException( - "Failed to find a nic profile for the existing default network. This is bad and probably means some sort of configuration corruption"); + throw new CloudRuntimeException("Failed to find a nic profile for the existing default network. This is bad and probably means some sort of configuration corruption"); } Network oldDefaultNetwork = null; @@ -1190,45 +1191,44 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir String nicIdString = Long.toString(nic.getId()); long newNetworkOfferingId = network.getNetworkOfferingId(); UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_REMOVE, vmInstance.getAccountId(), vmInstance.getDataCenterId(), vmInstance.getId(), - oldNicIdString, oldNetworkOfferingId, null, 1L, VirtualMachine.class.getName(), vmInstance.getUuid()); + oldNicIdString, oldNetworkOfferingId, null, 1L, VirtualMachine.class.getName(), vmInstance.getUuid()); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_ASSIGN, vmInstance.getAccountId(), vmInstance.getDataCenterId(), vmInstance.getId(), nicIdString, + newNetworkOfferingId, null, 1L, VirtualMachine.class.getName(), vmInstance.getUuid()); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_REMOVE, vmInstance.getAccountId(), vmInstance.getDataCenterId(), vmInstance.getId(), nicIdString, + newNetworkOfferingId, null, 0L, VirtualMachine.class.getName(), vmInstance.getUuid()); UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_ASSIGN, vmInstance.getAccountId(), vmInstance.getDataCenterId(), vmInstance.getId(), - nicIdString, newNetworkOfferingId, null, 1L, VirtualMachine.class.getName(), vmInstance.getUuid()); - UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_REMOVE, vmInstance.getAccountId(), vmInstance.getDataCenterId(), vmInstance.getId(), - nicIdString, newNetworkOfferingId, null, 0L, VirtualMachine.class.getName(), vmInstance.getUuid()); - UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_ASSIGN, vmInstance.getAccountId(), vmInstance.getDataCenterId(), vmInstance.getId(), - oldNicIdString, oldNetworkOfferingId, null, 0L, VirtualMachine.class.getName(), vmInstance.getUuid()); + oldNicIdString, oldNetworkOfferingId, null, 0L, VirtualMachine.class.getName(), vmInstance.getUuid()); return _vmDao.findById(vmInstance.getId()); } - throw new CloudRuntimeException("something strange happened, new default network(" + newdefault.getId() + ") is not null, and is not equal to the network(" + - nic.getNetworkId() + ") of the chosen nic"); + throw new CloudRuntimeException("something strange happened, new default network(" + newdefault.getId() + ") is not null, and is not equal to the network(" + + nic.getNetworkId() + ") of the chosen nic"); } @Override @ActionEvent(eventType = EventTypes.EVENT_VM_UPGRADE, eventDescription = "Upgrading VM", async = true) public UserVm upgradeVirtualMachine(ScaleVMCmd cmd) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, - VirtualMachineMigrationException { + VirtualMachineMigrationException { Long vmId = cmd.getId(); Long newServiceOfferingId = cmd.getServiceOfferingId(); CallContext.current().setEventDetails("Vm Id: " + vmId); - boolean result = upgradeVirtualMachine(vmId, newServiceOfferingId,cmd.getCustomParameters()); - if(result){ + boolean result = upgradeVirtualMachine(vmId, newServiceOfferingId, cmd.getDetails()); + if (result) { UserVmVO vmInstance = _vmDao.findById(vmId); if (vmInstance.getState().equals(State.Stopped)) { // Generate usage event for VM upgrade - generateUsageEvent(_serviceOfferingDao.findById(newServiceOfferingId), cmd.getCustomParameters(), vmInstance, EventTypes.EVENT_VM_UPGRADE); + generateUsageEvent(_offeringDao.findById(newServiceOfferingId), cmd.getDetails(), _vmDao.findById(vmId), EventTypes.EVENT_VM_UPGRADE); } if (vmInstance.getState().equals(State.Running)) { // Generate usage event for Dynamic scaling of VM - generateUsageEvent(_serviceOfferingDao.findById(newServiceOfferingId),cmd.getCustomParameters(), vmInstance, EventTypes.EVENT_VM_UPGRADE); + generateUsageEvent(_offeringDao.findById(newServiceOfferingId), cmd.getDetails(), _vmDao.findById(vmId), EventTypes.EVENT_VM_UPGRADE); } return vmInstance; } else { throw new CloudRuntimeException("Failed to scale the VM"); } - } @Override @@ -1267,7 +1267,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } @Override - public boolean upgradeVirtualMachine(Long vmId, Long newServiceOfferingId, Map customParameters) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException{ + public boolean upgradeVirtualMachine(Long vmId, Long newServiceOfferingId, Map customParameters) throws ResourceUnavailableException, + ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException { // Verify input parameters VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId); @@ -1276,13 +1277,14 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir upgradeStoppedVirtualMachine(vmId, newServiceOfferingId, customParameters); return true; } - if(vmInstance.getState().equals(State.Running)){ + if (vmInstance.getState().equals(State.Running)) { return upgradeRunningVirtualMachine(vmId, newServiceOfferingId, customParameters); } return false; } - private boolean upgradeRunningVirtualMachine(Long vmId, Long newServiceOfferingId, Map customParameters) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException{ + private boolean upgradeRunningVirtualMachine(Long vmId, Long newServiceOfferingId, Map customParameters) throws ResourceUnavailableException, + ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException { Account caller = CallContext.current().getCallingAccount(); VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId); @@ -1293,7 +1295,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir _accountMgr.checkAccess(caller, null, true, vmInstance); //Check if its a scale "up" - ServiceOfferingVO newServiceOffering = (ServiceOfferingVO) _offeringDao.findById(newServiceOfferingId); + ServiceOfferingVO newServiceOffering = _offeringDao.findById(newServiceOfferingId); if (newServiceOffering.isDynamic()) { newServiceOffering.setDynamicFlag(true); validateCustomParameters(newServiceOffering, customParameters); @@ -1311,14 +1313,13 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir int currentMemory = currentServiceOffering.getRamSize(); int currentSpeed = currentServiceOffering.getSpeed(); int memoryDiff = newMemory - currentMemory; - int cpuDiff = newCpu*newSpeed - currentCpu*currentSpeed; + int cpuDiff = newCpu * newSpeed - currentCpu * currentSpeed; // Don't allow to scale when (Any of the new values less than current values) OR (All current and new values are same) - if ((newSpeed < currentSpeed || newMemory < currentMemory || newCpu < currentCpu) || - (newSpeed == currentSpeed && newMemory == currentMemory && newCpu == currentCpu)) { - throw new InvalidParameterValueException("Only scaling up the vm is supported, new service offering(speed=" + newSpeed + ",cpu=" + newCpu + ",memory=," + - newMemory + ")" + " should have at least one value(cpu/ram) greater than old value and no resource value less than older(speed=" + currentSpeed + - ",cpu=" + currentCpu + ",memory=," + currentMemory + ")"); + if ((newSpeed < currentSpeed || newMemory < currentMemory || newCpu < currentCpu) || (newSpeed == currentSpeed && newMemory == currentMemory && newCpu == currentCpu)) { + throw new InvalidParameterValueException("Only scaling up the vm is supported, new service offering(speed=" + newSpeed + ",cpu=" + newCpu + ",memory=," + newMemory + + ")" + " should have at least one value(cpu/ram) greater than old value and no resource value less than older(speed=" + currentSpeed + ",cpu=" + currentCpu + + ",memory=," + currentMemory + ")"); } // Check resource limits @@ -1348,7 +1349,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir // Check disable threshold for cluster is not crossed HostVO host = _hostDao.findById(vmInstance.getHostId()); - if(_capacityMgr.checkIfClusterCrossesThreshold(host.getClusterId(), cpuDiff, memoryDiff)){ + if (_capacityMgr.checkIfClusterCrossesThreshold(host.getClusterId(), cpuDiff, memoryDiff)) { throw new CloudRuntimeException("Unable to scale vm: " + vmInstance.getUuid() + " due to insufficient resources"); } @@ -1362,15 +1363,15 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } if (memoryDiff > 0) { - _resourceLimitMgr.incrementResourceCount(caller.getAccountId(), ResourceType.memory, new Long (memoryDiff)); + _resourceLimitMgr.incrementResourceCount(caller.getAccountId(), ResourceType.memory, new Long(memoryDiff)); } // #1 Check existing host has capacity - if( !excludes.shouldAvoid(ApiDBUtils.findHostById(vmInstance.getHostId())) ){ + if (!excludes.shouldAvoid(ApiDBUtils.findHostById(vmInstance.getHostId()))) { existingHostHasCapacity = _capacityMgr.checkIfHostHasCpuCapability(vmInstance.getHostId(), newCpu, newSpeed) - && _capacityMgr.checkIfHostHasCapacity(vmInstance.getHostId(), cpuDiff, - (memoryDiff) * 1024L * 1024L, false, _capacityMgr.getClusterOverProvisioningFactor(host.getClusterId(), Capacity.CAPACITY_TYPE_CPU), - _capacityMgr.getClusterOverProvisioningFactor(host.getClusterId(), Capacity.CAPACITY_TYPE_MEMORY), false); + && _capacityMgr.checkIfHostHasCapacity(vmInstance.getHostId(), cpuDiff, (memoryDiff) * 1024L * 1024L, false, + _capacityMgr.getClusterOverProvisioningFactor(host.getClusterId(), Capacity.CAPACITY_TYPE_CPU), + _capacityMgr.getClusterOverProvisioningFactor(host.getClusterId(), Capacity.CAPACITY_TYPE_MEMORY), false); excludes.addHost(vmInstance.getHostId()); } @@ -1404,7 +1405,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir if (!success) { _itMgr.upgradeVmDb(vmId, currentServiceOffering.getId()); // rollback if (newServiceOffering.isDynamic()) { - removeCustomOfferingDetails(vmId); + removeCustomOfferingDetails(vmId); } // Decrement CPU and Memory count accordingly. if (newCpu > currentCpu) { @@ -1412,7 +1413,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } if (memoryDiff > 0) { - _resourceLimitMgr.decrementResourceCount(caller.getAccountId(), ResourceType.memory, new Long (memoryDiff)); + _resourceLimitMgr.decrementResourceCount(caller.getAccountId(), ResourceType.memory, new Long(memoryDiff)); } } } @@ -1428,7 +1429,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir details.put(UsageEventVO.DynamicParameters.cpuNumber.name(), serviceOffering.getCpu().toString()); details.put(UsageEventVO.DynamicParameters.cpuSpeed.name(), serviceOffering.getSpeed().toString()); details.put(UsageEventVO.DynamicParameters.memory.name(), serviceOffering.getRamSize().toString()); - List detailList = new ArrayList(); + List detailList = new ArrayList(); for (String key : details.keySet()) { UserVmDetailVO detailVO = new UserVmDetailVO(vmId, key, details.get(key)); detailList.add(detailVO); @@ -1437,12 +1438,12 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } @Override - public void removeCustomOfferingDetails(long vmId){ + public void removeCustomOfferingDetails(long vmId) { Map details = _uservmDetailsDao.listDetailsKeyPairs(vmId); details.remove(UsageEventVO.DynamicParameters.cpuNumber.name()); details.remove(UsageEventVO.DynamicParameters.cpuSpeed.name()); details.remove(UsageEventVO.DynamicParameters.memory.name()); - List detailList = new ArrayList(); + List detailList = new ArrayList(); for (String key : details.keySet()) { UserVmDetailVO detailVO = new UserVmDetailVO(vmId, key, details.get(key)); detailList.add(detailVO); @@ -1536,7 +1537,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir // First check that the maximum number of UserVMs, CPU and Memory limit for the given // accountId will not be exceeded - resourceLimitCheck(account, new Long(serviceOffering.getCpu()), new Long(serviceOffering.getRamSize())); + resourceLimitCheck(account, vm.isDisplayVm(), new Long(serviceOffering.getCpu()), new Long(serviceOffering.getRamSize())); _haMgr.cancelDestroy(vm, vm.getHostId()); @@ -1563,13 +1564,13 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir offeringId = offering.getId(); } } - UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), - volume.getName(), offeringId, templateId, volume.getSize(), Volume.class.getName(), volume.getUuid()); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), + offeringId, templateId, volume.getSize(), Volume.class.getName(), volume.getUuid()); } } //Update Resource Count for the given account - resourceCountIncrement(account.getId(), new Long(serviceOffering.getCpu()), new Long(serviceOffering.getRamSize())); + resourceCountIncrement(account.getId(), vm.isDisplayVm(), new Long(serviceOffering.getCpu()), new Long(serviceOffering.getRamSize())); } }); @@ -1616,7 +1617,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir _itMgr.registerGuru(VirtualMachine.Type.User, this); - VirtualMachine.State.getStateMachine().registerListener(new UserVmStateListener(_usageEventDao, _networkDao, _nicDao)); + VirtualMachine.State.getStateMachine().registerListener(new UserVmStateListener(_usageEventDao, _networkDao, _nicDao, _offeringDao)); String value = _configDao.getValue(Config.SetVmInternalNameUsingDisplayName.key()); _instanceNameFlag = (value == null) ? false : Boolean.parseBoolean(value); @@ -1661,7 +1662,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir // Update Resource count if (vm.getAccountId() != Account.ACCOUNT_ID_SYSTEM && !rootVol.isEmpty()) { _resourceLimitMgr.decrementResourceCount(vm.getAccountId(), ResourceType.volume); - _resourceLimitMgr.decrementResourceCount(vm.getAccountId(), ResourceType.primary_storage, new Long(rootVol.get(0).getSize())); + _resourceLimitMgr.recalculateResourceCount(vm.getAccountId(), vm.getDomainId(), ResourceType.primary_storage.getOrdinal()); } // Only if vm is not expunged already, cleanup it's resources @@ -1780,7 +1781,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir ServiceOfferingVO offering = _serviceOfferingDao.findById(vm.getId(), vm.getServiceOfferingId()); // Update Resource Count for the given account - resourceCountDecrement(vm.getAccountId(), new Long(offering.getCpu()), new Long(offering.getRamSize())); + resourceCountDecrement(vm.getAccountId(), vm.isDisplayVm(), new Long(offering.getCpu()), new Long(offering.getRamSize())); } } } @@ -1844,10 +1845,15 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, vmInstance); - if (isDisplayVmEnabled != null) { + //If the flag is specified and is changed + if (isDisplayVmEnabled != null && isDisplayVmEnabled != vmInstance.isDisplayVm()) { if (!_accountMgr.isRootAdmin(caller.getType())) { throw new PermissionDeniedException("Cannot update parameter displayvm, only admin permitted "); } + ServiceOffering offering = _serviceOfferingDao.findByIdIncludingRemoved(vmInstance.getServiceOfferingId()); + _resourceLimitMgr.changeResourceCount(vmInstance.getAccountId(), ResourceType.user_vm, isDisplayVmEnabled); + _resourceLimitMgr.changeResourceCount(vmInstance.getAccountId(), ResourceType.cpu, isDisplayVmEnabled, new Long(offering.getCpu())); + _resourceLimitMgr.changeResourceCount(vmInstance.getAccountId(), ResourceType.memory, isDisplayVmEnabled, new Long(offering.getRamSize())); } return updateVirtualMachine(id, displayName, group, ha, isDisplayVmEnabled, osTypeId, userData, isDynamicallyScalable, cmd.getHttpMethod(), cmd.getCustomId()); @@ -1855,7 +1861,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir @Override public UserVm updateVirtualMachine(long id, String displayName, String group, Boolean ha, Boolean isDisplayVmEnabled, Long osTypeId, String userData, - Boolean isDynamicallyScalable, HTTPMethod httpMethod, String customId) throws ResourceUnavailableException, InsufficientCapacityException { + Boolean isDynamicallyScalable, HTTPMethod httpMethod, String customId) throws ResourceUnavailableException, InsufficientCapacityException { UserVmVO vm = _vmDao.findById(id); if (vm == null) { throw new CloudRuntimeException("Unable to find virual machine with id " + id); @@ -1937,8 +1943,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir for (Nic nic : nics) { Network network = _networkDao.findById(nic.getNetworkId()); - NicProfile nicProfile = - new NicProfile(nic, network, null, null, null, _networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag( + NicProfile nicProfile = new NicProfile(nic, network, null, null, null, _networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag( template.getHypervisorType(), network)); VirtualMachineProfile vmProfile = new VirtualMachineProfileImpl(vm); @@ -1958,8 +1963,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir @Override @ActionEvent(eventType = EventTypes.EVENT_VM_START, eventDescription = "starting Vm", async = true) - public UserVm startVirtualMachine(StartVMCmd cmd) throws ExecutionException, ConcurrentOperationException, ResourceUnavailableException, - InsufficientCapacityException { + public UserVm startVirtualMachine(StartVMCmd cmd) throws ExecutionException, ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { return startVirtualMachine(cmd.getId(), cmd.getHostId(), null).first(); } @@ -2203,11 +2207,11 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir @Override @ActionEvent(eventType = EventTypes.EVENT_VM_CREATE, eventDescription = "deploying Vm", create = true) - public UserVm createBasicSecurityGroupVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, - List securityGroupIdList, Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, - HTTPMethod httpmethod, String userData, String sshKeyPair, Map requestedIps, IpAddresses defaultIps, Boolean displayVm, String keyboard, - List affinityGroupIdList, Map customParametes, String customId) throws InsufficientCapacityException, - ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException { + public UserVm createBasicSecurityGroupVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List securityGroupIdList, + Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, HTTPMethod httpmethod, + String userData, String sshKeyPair, Map requestedIps, IpAddresses defaultIps, Boolean displayVm, String keyboard, List affinityGroupIdList, + Map customParametes, String customId) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, + StorageUnavailableException, ResourceAllocationException { Account caller = CallContext.current().getCallingAccount(); List networkList = new ArrayList(); @@ -2242,26 +2246,25 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir if (s_logger.isDebugEnabled()) { s_logger.debug("Couldn't find default security group for the account " + owner + " so creating a new one"); } - defaultGroup = - _securityGroupMgr.createSecurityGroup(SecurityGroupManager.DEFAULT_GROUP_NAME, SecurityGroupManager.DEFAULT_GROUP_DESCRIPTION, + defaultGroup = _securityGroupMgr.createSecurityGroup(SecurityGroupManager.DEFAULT_GROUP_NAME, SecurityGroupManager.DEFAULT_GROUP_DESCRIPTION, owner.getDomainId(), owner.getId(), owner.getAccountName()); securityGroupIdList.add(defaultGroup.getId()); } } } - return createVirtualMachine(zone, serviceOffering, template, hostName, displayName, owner, diskOfferingId, diskSize, networkList, securityGroupIdList, group, - httpmethod, userData, sshKeyPair, hypervisor, caller, requestedIps, defaultIps, displayVm, keyboard, affinityGroupIdList, customParametes, customId); + return createVirtualMachine(zone, serviceOffering, template, hostName, displayName, owner, diskOfferingId, diskSize, networkList, securityGroupIdList, group, httpmethod, + userData, sshKeyPair, hypervisor, caller, requestedIps, defaultIps, displayVm, keyboard, affinityGroupIdList, customParametes, customId); } @Override @ActionEvent(eventType = EventTypes.EVENT_VM_CREATE, eventDescription = "deploying Vm", create = true) public UserVm createAdvancedSecurityGroupVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List networkIdList, - List securityGroupIdList, Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, - HTTPMethod httpmethod, String userData, String sshKeyPair, Map requestedIps, IpAddresses defaultIps, Boolean displayVm, String keyboard, - List affinityGroupIdList, Map customParameters, String customId) throws InsufficientCapacityException, - ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException { + List securityGroupIdList, Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, + HTTPMethod httpmethod, String userData, String sshKeyPair, Map requestedIps, IpAddresses defaultIps, Boolean displayVm, String keyboard, + List affinityGroupIdList, Map customParameters, String customId) throws InsufficientCapacityException, ConcurrentOperationException, + ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException { Account caller = CallContext.current().getCallingAccount(); List networkList = new ArrayList(); @@ -2350,25 +2353,24 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir if (s_logger.isDebugEnabled()) { s_logger.debug("Couldn't find default security group for the account " + owner + " so creating a new one"); } - defaultGroup = - _securityGroupMgr.createSecurityGroup(SecurityGroupManager.DEFAULT_GROUP_NAME, SecurityGroupManager.DEFAULT_GROUP_DESCRIPTION, + defaultGroup = _securityGroupMgr.createSecurityGroup(SecurityGroupManager.DEFAULT_GROUP_NAME, SecurityGroupManager.DEFAULT_GROUP_DESCRIPTION, owner.getDomainId(), owner.getId(), owner.getAccountName()); securityGroupIdList.add(defaultGroup.getId()); } } } - return createVirtualMachine(zone, serviceOffering, template, hostName, displayName, owner, diskOfferingId, diskSize, networkList, securityGroupIdList, group, - httpmethod, userData, sshKeyPair, hypervisor, caller, requestedIps, defaultIps, displayVm, keyboard, affinityGroupIdList, customParameters, customId); + return createVirtualMachine(zone, serviceOffering, template, hostName, displayName, owner, diskOfferingId, diskSize, networkList, securityGroupIdList, group, httpmethod, + userData, sshKeyPair, hypervisor, caller, requestedIps, defaultIps, displayVm, keyboard, affinityGroupIdList, customParameters, customId); } @Override @ActionEvent(eventType = EventTypes.EVENT_VM_CREATE, eventDescription = "deploying Vm", create = true) - public UserVm createAdvancedVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List networkIdList, - Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, HTTPMethod httpmethod, - String userData, String sshKeyPair, Map requestedIps, IpAddresses defaultIps, Boolean displayvm, String keyboard, - List affinityGroupIdList, Map customParametrs, String customId) throws InsufficientCapacityException, - ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException { + public UserVm createAdvancedVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List networkIdList, Account owner, + String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, HTTPMethod httpmethod, String userData, + String sshKeyPair, Map requestedIps, IpAddresses defaultIps, Boolean displayvm, String keyboard, List affinityGroupIdList, + Map customParametrs, String customId) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, + StorageUnavailableException, ResourceAllocationException { Account caller = CallContext.current().getCallingAccount(); List networkList = new ArrayList(); @@ -2390,27 +2392,24 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir List requiredOfferings = _networkOfferingDao.listByAvailability(Availability.Required, false); if (requiredOfferings.size() < 1) { - throw new InvalidParameterValueException("Unable to find network offering with availability=" + Availability.Required + - " to automatically create the network as a part of vm creation"); + throw new InvalidParameterValueException("Unable to find network offering with availability=" + Availability.Required + + " to automatically create the network as a part of vm creation"); } if (requiredOfferings.get(0).getState() == NetworkOffering.State.Enabled) { // get Virtual networks List virtualNetworks = _networkModel.listNetworksForAccount(owner.getId(), zone.getId(), Network.GuestType.Isolated); if (virtualNetworks.isEmpty()) { - long physicalNetworkId = - _networkModel.findPhysicalNetworkId(zone.getId(), requiredOfferings.get(0).getTags(), requiredOfferings.get(0).getTrafficType()); + long physicalNetworkId = _networkModel.findPhysicalNetworkId(zone.getId(), requiredOfferings.get(0).getTags(), requiredOfferings.get(0).getTrafficType()); // Validate physical network PhysicalNetwork physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId); if (physicalNetwork == null) { - throw new InvalidParameterValueException("Unable to find physical network with id: " + physicalNetworkId + " and tag: " + - requiredOfferings.get(0).getTags()); + throw new InvalidParameterValueException("Unable to find physical network with id: " + physicalNetworkId + " and tag: " + + requiredOfferings.get(0).getTags()); } - s_logger.debug("Creating network for account " + owner + " from the network offering id=" + requiredOfferings.get(0).getId() + - " as a part of deployVM process"); - Network newNetwork = - _networkMgr.createGuestNetwork(requiredOfferings.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", null, - null, null, null, owner, null, physicalNetwork, zone.getId(), ACLType.Account, null, null, null, null, true, null); + s_logger.debug("Creating network for account " + owner + " from the network offering id=" + requiredOfferings.get(0).getId() + " as a part of deployVM process"); + Network newNetwork = _networkMgr.createGuestNetwork(requiredOfferings.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", + null, null, null, null, owner, null, physicalNetwork, zone.getId(), ACLType.Account, null, null, null, null, true, null); defaultNetwork = _networkDao.findById(newNetwork.getId()); } else if (virtualNetworks.size() > 1) { throw new InvalidParameterValueException("More than 1 default Isolated networks are found for account " + owner + "; please specify networkIds"); @@ -2418,8 +2417,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir defaultNetwork = _networkDao.findById(virtualNetworks.get(0).getId()); } } else { - throw new InvalidParameterValueException("Required network offering id=" + requiredOfferings.get(0).getId() + " is not in " + - NetworkOffering.State.Enabled); + throw new InvalidParameterValueException("Required network offering id=" + requiredOfferings.get(0).getId() + " is not in " + NetworkOffering.State.Enabled); } networkList.add(defaultNetwork); @@ -2434,8 +2432,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir // Only ISOs, XenServer, KVM, and VmWare template types are // supported for vpc networks if (template.getFormat() != ImageFormat.ISO && !vpcSupportedHTypes.contains(template.getHypervisorType())) { - throw new InvalidParameterValueException("Can't create vm from template with hypervisor " + template.getHypervisorType() + " in vpc network " + - network); + throw new InvalidParameterValueException("Can't create vm from template with hypervisor " + template.getHypervisorType() + " in vpc network " + network); } else if (template.getFormat() == ImageFormat.ISO && !vpcSupportedHTypes.contains(hypervisor)) { // Only XenServer, KVM, and VMware hypervisors are supported // for vpc networks @@ -2455,23 +2452,23 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } } - return createVirtualMachine(zone, serviceOffering, template, hostName, displayName, owner, diskOfferingId, diskSize, networkList, null, group, httpmethod, - userData, sshKeyPair, hypervisor, caller, requestedIps, defaultIps, displayvm, keyboard, affinityGroupIdList, customParametrs, customId); + return createVirtualMachine(zone, serviceOffering, template, hostName, displayName, owner, diskOfferingId, diskSize, networkList, null, group, httpmethod, userData, + sshKeyPair, hypervisor, caller, requestedIps, defaultIps, displayvm, keyboard, affinityGroupIdList, customParametrs, customId); } public void checkNameForRFCCompliance(String name) { if (!NetUtils.verifyDomainNameLabel(name, true)) { throw new InvalidParameterValueException("Invalid name. Vm name can contain ASCII letters 'a' through 'z', the digits '0' through '9', " - + "and the hyphen ('-'), must be between 1 and 63 characters long, and can't start or end with \"-\" and can't start with digit"); + + "and the hyphen ('-'), must be between 1 and 63 characters long, and can't start or end with \"-\" and can't start with digit"); } } @DB - protected UserVm createVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate tmplt, String hostName, String displayName, - Account owner, Long diskOfferingId, Long diskSize, List networkList, List securityGroupIdList, String group, HTTPMethod httpmethod, - String userData, String sshKeyPair, HypervisorType hypervisor, Account caller, Map requestedIps, IpAddresses defaultIps, - Boolean isDisplayVmEnabled, String keyboard, List affinityGroupIdList, Map customParameters, String customId) - throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException, StorageUnavailableException, ResourceAllocationException { + protected UserVm createVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate tmplt, String hostName, String displayName, Account owner, + Long diskOfferingId, Long diskSize, List networkList, List securityGroupIdList, String group, HTTPMethod httpmethod, String userData, + String sshKeyPair, HypervisorType hypervisor, Account caller, Map requestedIps, IpAddresses defaultIps, Boolean isDisplayVmEnabled, String keyboard, + List affinityGroupIdList, Map customParameters, String customId) throws InsufficientCapacityException, ResourceUnavailableException, + ConcurrentOperationException, StorageUnavailableException, ResourceAllocationException { _accountMgr.checkAccess(caller, null, true, owner); @@ -2519,9 +2516,21 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir size = tmp; } if (diskOfferingId != null) { + DiskOfferingVO diskOffering = _diskOfferingDao.findById(diskOfferingId); + if (diskOffering != null && diskOffering.isCustomized()) { + if (diskSize == null) { + throw new InvalidParameterValueException("This disk offering requires a custom size specified"); + } + Long customDiskOfferingMaxSize = volumeMgr.CustomDiskOfferingMaxSize.value(); + Long customDiskOfferingMinSize = volumeMgr.CustomDiskOfferingMinSize.value(); + if ((diskSize < customDiskOfferingMinSize) || (diskSize > customDiskOfferingMaxSize)) { + throw new InvalidParameterValueException("VM Creation failed. Volume size: " + diskSize + "GB is out of allowed range. Max: " + customDiskOfferingMaxSize + + " Min:" + customDiskOfferingMinSize); + } + } size += _diskOfferingDao.findById(diskOfferingId).getDiskSize(); } - resourceLimitCheck(owner, new Long(offering.getCpu()), new Long(offering.getRamSize())); + resourceLimitCheck(owner, isDisplayVmEnabled, new Long(offering.getCpu()), new Long(offering.getRamSize())); _resourceLimitMgr.checkResourceLimit(owner, ResourceType.volume, (isIso || diskOfferingId == null ? 1 : 2)); _resourceLimitMgr.checkResourceLimit(owner, ResourceType.primary_storage, size); @@ -2546,8 +2555,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir if (ag == null) { throw new InvalidParameterValueException("Unable to find affinity group " + ag); } else if (!_affinityGroupService.isAffinityGroupProcessorAvailable(ag.getType())) { - throw new InvalidParameterValueException("Affinity group type is not supported for group: " + ag + " ,type: " + ag.getType() + - " , Please try again after removing the affinity group"); + throw new InvalidParameterValueException("Affinity group type is not supported for group: " + ag + " ,type: " + ag.getType() + + " , Please try again after removing the affinity group"); } else { // verify permissions if (ag.getAclType() == ACLType.Domain) { @@ -2627,10 +2636,15 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir if (network.getDataCenterId() != zone.getId()) { throw new InvalidParameterValueException("Network id=" + network.getId() + " doesn't belong to zone " + zone.getId()); } - if (!(network.getGuestType() == Network.GuestType.Shared && network.getAclType() == ACLType.Domain) && - !(network.getAclType() == ACLType.Account && network.getAccountId() == accountId)) { - throw new InvalidParameterValueException("only shared network or isolated network with the same account_id can be added to vm"); + + //relax the check if the caller is admin account + if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { + if (!(network.getGuestType() == Network.GuestType.Shared && network.getAclType() == ACLType.Domain) + && !(network.getAclType() == ACLType.Account && network.getAccountId() == accountId)) { + throw new InvalidParameterValueException("only shared network or isolated network with the same account_id can be added to vm"); + } } + IpAddresses requestedIpPair = null; if (requestedIps != null && !requestedIps.isEmpty()) { requestedIpPair = requestedIps.get(network.getId()); @@ -2689,7 +2703,6 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir long id = _vmDao.getNextInSequence(Long.class, "id"); - if (hostName != null) { // Check is hostName is RFC compliant checkNameForRFCCompliance(hostName); @@ -2745,8 +2758,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir List hostNames = _vmInstanceDao.listDistinctHostNames(ntwkId); // * verify that there are no duplicates if (hostNames.contains(hostName)) { - throw new InvalidParameterValueException("The vm with hostName " + hostName + " already exists in the network domain: " + ntwkDomain.getKey() + - "; network=" + _networkModel.getNetwork(ntwkId)); + throw new InvalidParameterValueException("The vm with hostName " + hostName + " already exists in the network domain: " + ntwkDomain.getKey() + "; network=" + + _networkModel.getNetwork(ntwkId)); } } } @@ -2758,8 +2771,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir hypervisorType = template.getHypervisorType(); } - UserVmVO vm = - commitUserVm(zone, template, hostName, displayName, owner, diskOfferingId, diskSize, userData, hypervisor, caller, isDisplayVmEnabled, keyboard, accountId, + UserVmVO vm = commitUserVm(zone, template, hostName, displayName, owner, diskOfferingId, diskSize, userData, hypervisor, caller, isDisplayVmEnabled, keyboard, accountId, offering, isIso, sshPublicKey, networkNicMap, id, instanceName, uuidName, hypervisorType, customParameters); // Assign instance to the group @@ -2788,16 +2800,15 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } private UserVmVO commitUserVm(final DataCenter zone, final VirtualMachineTemplate template, final String hostName, final String displayName, final Account owner, - final Long diskOfferingId, final Long diskSize, final String userData, final HypervisorType hypervisor, final Account caller, final Boolean isDisplayVmEnabled, - final String keyboard, final long accountId, final ServiceOfferingVO offering, final boolean isIso, final String sshPublicKey, - final LinkedHashMap networkNicMap, final long id, final String instanceName, final String uuidName, final HypervisorType hypervisorType, - final Map customParameters) throws InsufficientCapacityException { + final Long diskOfferingId, final Long diskSize, final String userData, final HypervisorType hypervisor, final Account caller, final Boolean isDisplayVmEnabled, + final String keyboard, final long accountId, final ServiceOfferingVO offering, final boolean isIso, final String sshPublicKey, + final LinkedHashMap networkNicMap, final long id, final String instanceName, final String uuidName, final HypervisorType hypervisorType, + final Map customParameters) throws InsufficientCapacityException { return Transaction.execute(new TransactionCallbackWithException() { @Override public UserVmVO doInTransaction(TransactionStatus status) throws InsufficientCapacityException { - UserVmVO vm = - new UserVmVO(id, instanceName, displayName, template.getId(), hypervisorType, template.getGuestOSId(), offering.getOfferHA(), - offering.getLimitCpuUse(), owner.getDomainId(), owner.getId(), offering.getId(), userData, hostName, diskOfferingId); + UserVmVO vm = new UserVmVO(id, instanceName, displayName, template.getId(), hypervisorType, template.getGuestOSId(), offering.getOfferHA(), offering + .getLimitCpuUse(), owner.getDomainId(), owner.getId(), offering.getId(), userData, hostName, diskOfferingId); vm.setUuid(uuidName); vm.setDynamicallyScalable(template.isDynamicallyScalable()); if (sshPublicKey != null) { @@ -2812,7 +2823,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } Long rootDiskSize = null; if (customParameters.containsKey("rootdisksize")) { - if (NumbersUtil.parseLong(customParameters.get("rootdisksize"), -1) <=0) { + if (NumbersUtil.parseLong(customParameters.get("rootdisksize"), -1) <= 0) { throw new InvalidParameterValueException("rootdisk size should be a non zero number."); } rootDiskSize = Long.parseLong(customParameters.get("rootDisksize")); @@ -2880,12 +2891,11 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir if (isIso) { _orchSrvc.createVirtualMachineFromScratch(vm.getUuid(), Long.toString(owner.getAccountId()), vm.getIsoId().toString(), hostName, displayName, - hypervisor.name(), guestOSCategory.getName(), offering.getCpu(), offering.getSpeed(), offering.getRamSize(), diskSize, computeTags, rootDiskTags, - networkNicMap, plan); + hypervisor.name(), guestOSCategory.getName(), offering.getCpu(), offering.getSpeed(), offering.getRamSize(), diskSize, computeTags, rootDiskTags, + networkNicMap, plan); } else { - _orchSrvc.createVirtualMachine(vm.getUuid(), Long.toString(owner.getAccountId()), Long.toString(template.getId()), hostName, displayName, - hypervisor.name(), offering.getCpu(), offering.getSpeed(), offering.getRamSize(), diskSize, computeTags, rootDiskTags, networkNicMap, plan, - rootDiskSize); + _orchSrvc.createVirtualMachine(vm.getUuid(), Long.toString(owner.getAccountId()), Long.toString(template.getId()), hostName, displayName, hypervisor.name(), + offering.getCpu(), offering.getSpeed(), offering.getRamSize(), diskSize, computeTags, rootDiskTags, networkNicMap, plan, rootDiskSize); } if (s_logger.isDebugEnabled()) { @@ -2894,32 +2904,27 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir CallContext.current().setEventDetails("Vm Id: " + vm.getId()); if (!offering.isDynamic()) { - UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_CREATE, accountId, zone.getId(), vm.getId(), - vm.getHostName(), offering.getId(), template.getId(), hypervisorType.toString(), - VirtualMachine.class.getName(), vm.getUuid()); - } - else { - UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_CREATE, accountId, zone.getId(), vm.getId(), vm.getHostName(), offering.getId(), - template.getId(), hypervisorType.toString(), VirtualMachine.class.getName(), vm.getUuid(), customParameters); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_CREATE, accountId, zone.getId(), vm.getId(), vm.getHostName(), offering.getId(), template.getId(), + hypervisorType.toString(), VirtualMachine.class.getName(), vm.getUuid()); + } else { + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_CREATE, accountId, zone.getId(), vm.getId(), vm.getHostName(), offering.getId(), template.getId(), + hypervisorType.toString(), VirtualMachine.class.getName(), vm.getUuid(), customParameters); } //Update Resource Count for the given account - resourceCountIncrement(accountId, new Long(offering.getCpu()), new Long(offering.getRamSize())); + resourceCountIncrement(accountId, isDisplayVmEnabled, new Long(offering.getCpu()), new Long(offering.getRamSize())); return vm; } }); } - private void generateUsageEvent(ServiceOfferingVO serviceOffering, Map customParameters, UserVmVO vm, String eventType){ + private void generateUsageEvent(ServiceOfferingVO serviceOffering, Map customParameters, UserVmVO vm, String eventType) { if (!serviceOffering.isDynamic()) { - UsageEventUtils.publishUsageEvent(eventType, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), - vm.getHostName(), serviceOffering.getId(), vm.getTemplateId(), vm.getHypervisorType().toString(), - VirtualMachine.class.getName(), vm.getUuid()); - } - else { - UsageEventUtils.publishUsageEvent(eventType, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), - vm.getHostName(), serviceOffering.getId(), vm.getTemplateId(), vm.getHypervisorType().toString(), - VirtualMachine.class.getName(), vm.getUuid(), customParameters); + UsageEventUtils.publishUsageEvent(eventType, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), vm.getHostName(), serviceOffering.getId(), vm.getTemplateId(), vm + .getHypervisorType().toString(), VirtualMachine.class.getName(), vm.getUuid()); + } else { + UsageEventUtils.publishUsageEvent(eventType, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), vm.getHostName(), serviceOffering.getId(), vm.getTemplateId(), vm + .getHypervisorType().toString(), VirtualMachine.class.getName(), vm.getUuid(), customParameters); } } @@ -2961,11 +2966,12 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } protected UserVm startVirtualMachine(DeployVMCmd cmd, Map additonalParams) throws ResourceUnavailableException, - InsufficientCapacityException, ConcurrentOperationException { + InsufficientCapacityException, ConcurrentOperationException { long vmId = cmd.getEntityId(); Long hostId = cmd.getHostId(); UserVmVO vm = _vmDao.findById(vmId); + CallContext.current().putContextParameter(VirtualMachine.class, vm.getUuid()); Pair> vmParamPair = null; try { @@ -3063,6 +3069,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir if (network.getTrafficType() == TrafficType.Guest || network.getTrafficType() == TrafficType.Public) { userVm.setPrivateIpAddress(nic.getIp4Address()); userVm.setPrivateMacAddress(nic.getMacAddress()); + _vmDao.update(userVm.getId(), userVm); } } @@ -3115,7 +3122,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir NetworkVO network = _networkDao.findById(nic.getNetworkId()); long isDefault = (nic.isDefaultNic()) ? 1 : 0; UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_ASSIGN, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), Long.toString(nic.getId()), - network.getNetworkOfferingId(), null, isDefault, VirtualMachine.class.getName(), vm.getUuid()); + network.getNetworkOfferingId(), null, isDefault, VirtualMachine.class.getName(), vm.getUuid()); if (network.getTrafficType() == TrafficType.Guest) { originalIp = nic.getIp4Address(); guestNic = nic; @@ -3220,8 +3227,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir assert (offering.getAssociatePublicIP() == true) : "User VM should not have system owned public IP associated with it when offering configured not to associate public IP."; _rulesMgr.disableStaticNat(ip.getId(), ctx.getCallingAccount(), ctx.getCallingUserId(), true); } catch (Exception ex) { - s_logger.warn("Failed to disable static nat and release system ip " + ip + " as a part of vm " + profile.getVirtualMachine() + " stop due to exception ", - ex); + s_logger.warn("Failed to disable static nat and release system ip " + ip + " as a part of vm " + profile.getVirtualMachine() + " stop due to exception ", ex); } } @@ -3242,9 +3248,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } @Override - public Pair> - startVirtualMachine(long vmId, Long hostId, Map additionalParams) throws ConcurrentOperationException, - ResourceUnavailableException, InsufficientCapacityException { + public Pair> startVirtualMachine(long vmId, Long hostId, Map additionalParams) + throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { // Input validation Account callerAccount = CallContext.current().getCallingAccount(); UserVO callerUser = _userDao.findById(CallContext.current().getCallingUserId()); @@ -3284,8 +3289,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } // check if vm is security group enabled - if (_securityGroupMgr.isVmSecurityGroupEnabled(vmId) && _securityGroupMgr.getSecurityGroupsForVm(vmId).isEmpty() && - !_securityGroupMgr.isVmMappedToDefaultSecurityGroup(vmId) && _networkModel.canAddDefaultSecurityGroup()) { + if (_securityGroupMgr.isVmSecurityGroupEnabled(vmId) && _securityGroupMgr.getSecurityGroupsForVm(vmId).isEmpty() + && !_securityGroupMgr.isVmMappedToDefaultSecurityGroup(vmId) && _networkModel.canAddDefaultSecurityGroup()) { // if vm is not mapped to security group, create a mapping if (s_logger.isDebugEnabled()) { s_logger.debug("Vm " + vm + " is security group enabled, but not mapped to default security group; creating the mapping automatically"); @@ -3364,12 +3369,10 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } @Override - - public UserVm destroyVm(long vmId) throws ResourceUnavailableException, - ConcurrentOperationException { - // Account caller = CallContext.current().getCallingAccount(); - // Long userId = CallContext.current().getCallingUserId(); - Long userId = 2L; + public UserVm destroyVm(long vmId) throws ResourceUnavailableException, ConcurrentOperationException { + // Account caller = CallContext.current().getCallingAccount(); + // Long userId = CallContext.current().getCallingUserId(); + Long userId = 2L; // Verify input parameters UserVmVO vm = _vmDao.findById(vmId); @@ -3383,8 +3386,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir return vm; } - - // _accountMgr.checkAccess(caller, null, true, vm); + // _accountMgr.checkAccess(caller, null, true, vm); User userCaller = _userDao.findById(userId); boolean status; @@ -3405,7 +3407,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir for (VolumeVO volume : volumes) { if (volume.getVolumeType().equals(Volume.Type.ROOT)) { UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_DELETE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), - Volume.class.getName(), volume.getUuid()); + Volume.class.getName(), volume.getUuid()); } } @@ -3414,7 +3416,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir ServiceOfferingVO offering = _serviceOfferingDao.findByIdIncludingRemoved(vm.getId(), vm.getServiceOfferingId()); //Update Resource Count for the given account - resourceCountDecrement(vm.getAccountId(), new Long(offering.getCpu()), new Long(offering.getRamSize())); + resourceCountDecrement(vm.getAccountId(), vm.isDisplayVm(), new Long(offering.getCpu()), new Long(offering.getRamSize())); } return _vmDao.findById(vmId); } else { @@ -3445,8 +3447,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } if (diskStatsAnswer != null) { if (!diskStatsAnswer.getResult()) { - s_logger.warn("Error while collecting disk stats vm: " + userVm.getHostName() + " from host: " + host.getName() + "; details: " + - diskStatsAnswer.getDetails()); + s_logger.warn("Error while collecting disk stats vm: " + userVm.getHostName() + " from host: " + host.getName() + "; details: " + diskStatsAnswer.getDetails()); return; } try { @@ -3468,8 +3469,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir if ((volumes == null) || (volumes.size() == 0)) break; VolumeVO volume = volumes.get(0); - VmDiskStatisticsVO previousVmDiskStats = - _vmDiskStatsDao.findBy(userVm.getAccountId(), userVm.getDataCenterId(), userVm.getId(), volume.getId()); + VmDiskStatisticsVO previousVmDiskStats = _vmDiskStatsDao.findBy(userVm.getAccountId(), userVm.getDataCenterId(), userVm.getId(), volume.getId()); VmDiskStatisticsVO vmDiskStat_lock = _vmDiskStatsDao.lock(userVm.getAccountId(), userVm.getDataCenterId(), userVm.getId(), volume.getId()); if ((vmDiskStat.getIORead() == 0) && (vmDiskStat.getIOWrite() == 0) && (vmDiskStat.getBytesRead() == 0) && (vmDiskStat.getBytesWrite() == 0)) { @@ -3478,52 +3478,50 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } if (vmDiskStat_lock == null) { - s_logger.warn("unable to find vm disk stats from host for account: " + userVm.getAccountId() + " with vmId: " + userVm.getId() + - " and volumeId:" + volume.getId()); + s_logger.warn("unable to find vm disk stats from host for account: " + userVm.getAccountId() + " with vmId: " + userVm.getId() + " and volumeId:" + + volume.getId()); continue; } - if (previousVmDiskStats != null && - ((previousVmDiskStats.getCurrentIORead() != vmDiskStat_lock.getCurrentIORead()) || ((previousVmDiskStats.getCurrentIOWrite() != vmDiskStat_lock.getCurrentIOWrite()) || - (previousVmDiskStats.getCurrentBytesRead() != vmDiskStat_lock.getCurrentBytesRead()) || (previousVmDiskStats.getCurrentBytesWrite() != vmDiskStat_lock.getCurrentBytesWrite())))) { - s_logger.debug("vm disk stats changed from the time GetVmDiskStatsCommand was sent. " + "Ignoring current answer. Host: " + - host.getName() + " . VM: " + vmDiskStat.getVmName() + " IO Read: " + vmDiskStat.getIORead() + " IO Write: " + - vmDiskStat.getIOWrite() + " Bytes Read: " + vmDiskStat.getBytesRead() + " Bytes Write: " + vmDiskStat.getBytesWrite()); + if (previousVmDiskStats != null + && ((previousVmDiskStats.getCurrentIORead() != vmDiskStat_lock.getCurrentIORead()) || ((previousVmDiskStats.getCurrentIOWrite() != vmDiskStat_lock + .getCurrentIOWrite()) || (previousVmDiskStats.getCurrentBytesRead() != vmDiskStat_lock.getCurrentBytesRead()) || (previousVmDiskStats + .getCurrentBytesWrite() != vmDiskStat_lock.getCurrentBytesWrite())))) { + s_logger.debug("vm disk stats changed from the time GetVmDiskStatsCommand was sent. " + "Ignoring current answer. Host: " + host.getName() + + " . VM: " + vmDiskStat.getVmName() + " IO Read: " + vmDiskStat.getIORead() + " IO Write: " + vmDiskStat.getIOWrite() + " Bytes Read: " + + vmDiskStat.getBytesRead() + " Bytes Write: " + vmDiskStat.getBytesWrite()); continue; } if (vmDiskStat_lock.getCurrentIORead() > vmDiskStat.getIORead()) { if (s_logger.isDebugEnabled()) { - s_logger.debug("Read # of IO that's less than the last one. " + "Assuming something went wrong and persisting it. Host: " + - host.getName() + " . VM: " + vmDiskStat.getVmName() + " Reported: " + vmDiskStat.getIORead() + " Stored: " + - vmDiskStat_lock.getCurrentIORead()); + s_logger.debug("Read # of IO that's less than the last one. " + "Assuming something went wrong and persisting it. Host: " + host.getName() + + " . VM: " + vmDiskStat.getVmName() + " Reported: " + vmDiskStat.getIORead() + " Stored: " + vmDiskStat_lock.getCurrentIORead()); } vmDiskStat_lock.setNetIORead(vmDiskStat_lock.getNetIORead() + vmDiskStat_lock.getCurrentIORead()); } vmDiskStat_lock.setCurrentIORead(vmDiskStat.getIORead()); if (vmDiskStat_lock.getCurrentIOWrite() > vmDiskStat.getIOWrite()) { if (s_logger.isDebugEnabled()) { - s_logger.debug("Write # of IO that's less than the last one. " + "Assuming something went wrong and persisting it. Host: " + - host.getName() + " . VM: " + vmDiskStat.getVmName() + " Reported: " + vmDiskStat.getIOWrite() + " Stored: " + - vmDiskStat_lock.getCurrentIOWrite()); + s_logger.debug("Write # of IO that's less than the last one. " + "Assuming something went wrong and persisting it. Host: " + host.getName() + + " . VM: " + vmDiskStat.getVmName() + " Reported: " + vmDiskStat.getIOWrite() + " Stored: " + vmDiskStat_lock.getCurrentIOWrite()); } vmDiskStat_lock.setNetIOWrite(vmDiskStat_lock.getNetIOWrite() + vmDiskStat_lock.getCurrentIOWrite()); } vmDiskStat_lock.setCurrentIOWrite(vmDiskStat.getIOWrite()); if (vmDiskStat_lock.getCurrentBytesRead() > vmDiskStat.getBytesRead()) { if (s_logger.isDebugEnabled()) { - s_logger.debug("Read # of Bytes that's less than the last one. " + "Assuming something went wrong and persisting it. Host: " + - host.getName() + " . VM: " + vmDiskStat.getVmName() + " Reported: " + vmDiskStat.getBytesRead() + " Stored: " + - vmDiskStat_lock.getCurrentBytesRead()); + s_logger.debug("Read # of Bytes that's less than the last one. " + "Assuming something went wrong and persisting it. Host: " + host.getName() + + " . VM: " + vmDiskStat.getVmName() + " Reported: " + vmDiskStat.getBytesRead() + " Stored: " + vmDiskStat_lock.getCurrentBytesRead()); } vmDiskStat_lock.setNetBytesRead(vmDiskStat_lock.getNetBytesRead() + vmDiskStat_lock.getCurrentBytesRead()); } vmDiskStat_lock.setCurrentBytesRead(vmDiskStat.getBytesRead()); if (vmDiskStat_lock.getCurrentBytesWrite() > vmDiskStat.getBytesWrite()) { if (s_logger.isDebugEnabled()) { - s_logger.debug("Write # of Bytes that's less than the last one. " + "Assuming something went wrong and persisting it. Host: " + - host.getName() + " . VM: " + vmDiskStat.getVmName() + " Reported: " + vmDiskStat.getBytesWrite() + " Stored: " + - vmDiskStat_lock.getCurrentBytesWrite()); + s_logger.debug("Write # of Bytes that's less than the last one. " + "Assuming something went wrong and persisting it. Host: " + host.getName() + + " . VM: " + vmDiskStat.getVmName() + " Reported: " + vmDiskStat.getBytesWrite() + " Stored: " + + vmDiskStat_lock.getCurrentBytesWrite()); } vmDiskStat_lock.setNetBytesWrite(vmDiskStat_lock.getNetBytesWrite() + vmDiskStat_lock.getCurrentBytesWrite()); } @@ -3587,8 +3585,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } @Override - public Pair, Integer> searchForUserVMs(Criteria c, Account caller, Long domainId, boolean isRecursive, List permittedAccounts, - boolean listAll, ListProjectResourcesCriteria listProjectResourcesCriteria, Map tags) { + public Pair, Integer> searchForUserVMs(Criteria c, Account caller, Long domainId, boolean isRecursive, List permittedAccounts, boolean listAll, + ListProjectResourcesCriteria listProjectResourcesCriteria, Map tags) { Filter searchFilter = new Filter(UserVmJoinVO.class, c.getOrderBy(), c.getAscending(), c.getOffset(), c.getLimit()); //first search distinct vm id by using query criteria and pagination @@ -3778,7 +3776,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir @Override public UserVm createVirtualMachine(DeployVMCmd cmd) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException, - StorageUnavailableException, ResourceAllocationException { + StorageUnavailableException, ResourceAllocationException { // TODO Auto-generated method stub return null; } @@ -3821,8 +3819,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir HypervisorType destHypervisorType = _clusterDao.findById(destPool.getClusterId()).getHypervisorType(); if (vm.getHypervisorType() != destHypervisorType) { - throw new InvalidParameterValueException("hypervisor is not compatible: dest: " + destHypervisorType.toString() + ", vm: " + - vm.getHypervisorType().toString()); + throw new InvalidParameterValueException("hypervisor is not compatible: dest: " + destHypervisorType.toString() + ", vm: " + vm.getHypervisorType().toString()); } _itMgr.storageMigration(vm.getUuid(), destPool); return _vmDao.findById(vm.getId()); @@ -3849,8 +3846,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir @Override @ActionEvent(eventType = EventTypes.EVENT_VM_MIGRATE, eventDescription = "migrating VM", async = true) - public VirtualMachine migrateVirtualMachine(Long vmId, Host destinationHost) throws ResourceUnavailableException, ConcurrentOperationException, - ManagementServerException, VirtualMachineMigrationException { + public VirtualMachine migrateVirtualMachine(Long vmId, Host destinationHost) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, + VirtualMachineMigrationException { // access check - only root admin can migrate VM Account caller = CallContext.current().getCallingAccount(); if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { @@ -3873,18 +3870,13 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir ex.addProxyObject(vm.getUuid(), "vmId"); throw ex; } - if (!vm.getHypervisorType().equals(HypervisorType.XenServer) - && !vm.getHypervisorType().equals(HypervisorType.VMware) - && !vm.getHypervisorType().equals(HypervisorType.KVM) - && !vm.getHypervisorType().equals(HypervisorType.Ovm) - && !vm.getHypervisorType().equals(HypervisorType.Hyperv) + if (!vm.getHypervisorType().equals(HypervisorType.XenServer) && !vm.getHypervisorType().equals(HypervisorType.VMware) && !vm.getHypervisorType().equals(HypervisorType.KVM) + && !vm.getHypervisorType().equals(HypervisorType.Ovm) && !vm.getHypervisorType().equals(HypervisorType.Hyperv) && !vm.getHypervisorType().equals(HypervisorType.Simulator)) { if (s_logger.isDebugEnabled()) { - s_logger.debug(vm - + " is not XenServer/VMware/KVM/Ovm/Hyperv, cannot migrate this VM."); + s_logger.debug(vm + " is not XenServer/VMware/KVM/Ovm/Hyperv, cannot migrate this VM."); } - throw new InvalidParameterValueException( - "Unsupported Hypervisor Type for VM migration, we support XenServer/VMware/KVM/Ovm/Hyperv only"); + throw new InvalidParameterValueException("Unsupported Hypervisor Type for VM migration, we support XenServer/VMware/KVM/Ovm/Hyperv only"); } if (isVMUsingLocalStorage(vm)) { @@ -3902,8 +3894,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir // check if host is UP if (destinationHost.getState() != com.cloud.host.Status.Up || destinationHost.getResourceState() != ResourceState.Enabled) { - throw new InvalidParameterValueException("Cannot migrate VM, destination host is not in correct state, has status: " + destinationHost.getState() + - ", state: " + destinationHost.getResourceState()); + throw new InvalidParameterValueException("Cannot migrate VM, destination host is not in correct state, has status: " + destinationHost.getState() + ", state: " + + destinationHost.getResourceState()); } if (vm.getType() != VirtualMachine.Type.User) { @@ -3929,11 +3921,11 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir HostVO destinationHostVO = _hostDao.findById(destinationHost.getId()); if (_capacityMgr.checkIfHostReachMaxGuestLimit(destinationHostVO)) { if (s_logger.isDebugEnabled()) { - s_logger.debug("Host name: " + destinationHost.getName() + ", hostId: " + destinationHost.getId() + - " already has max Running VMs(count includes system VMs), cannot migrate to this host"); + s_logger.debug("Host name: " + destinationHost.getName() + ", hostId: " + destinationHost.getId() + + " already has max Running VMs(count includes system VMs), cannot migrate to this host"); } - throw new VirtualMachineMigrationException("Destination host, hostId: " + destinationHost.getId() + - " already has max Running VMs(count includes system VMs), cannot migrate to this host"); + throw new VirtualMachineMigrationException("Destination host, hostId: " + destinationHost.getId() + + " already has max Running VMs(count includes system VMs), cannot migrate to this host"); } UserVmVO uservm = _vmDao.findById(vmId); @@ -4012,17 +4004,15 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir //if hosts are dedicated to different account/domains, raise an alert if (srcExplDedicated && destExplDedicated) { - if ((accountOfDedicatedHost(srcHost) != null) && (accountOfDedicatedHost(srcHost) != accountOfDedicatedHost(destHost))) { - String msg = - "VM is being migrated from host " + srcHost.getName() + " explicitly dedicated to account " + accountOfDedicatedHost(srcHost) + " to host " + - destHost.getName() + " explicitly dedicated to account " + accountOfDedicatedHost(destHost); + if (!((accountOfDedicatedHost(srcHost) == null) || (accountOfDedicatedHost(srcHost).equals(accountOfDedicatedHost(destHost))))) { + String msg = "VM is being migrated from host " + srcHost.getName() + " explicitly dedicated to account " + accountOfDedicatedHost(srcHost) + " to host " + + destHost.getName() + " explicitly dedicated to account " + accountOfDedicatedHost(destHost); _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_USERVM, vm.getDataCenterId(), vm.getPodIdToDeployIn(), msg, msg); s_logger.warn(msg); } - if ((domainOfDedicatedHost(srcHost) != null) && (domainOfDedicatedHost(srcHost) != domainOfDedicatedHost(destHost))) { - String msg = - "VM is being migrated from host " + srcHost.getName() + " explicitly dedicated to domain " + domainOfDedicatedHost(srcHost) + " to host " + - destHost.getName() + " explicitly dedicated to domain " + domainOfDedicatedHost(destHost); + if (!((domainOfDedicatedHost(srcHost) == null) || (domainOfDedicatedHost(srcHost).equals(domainOfDedicatedHost(destHost))))) { + String msg = "VM is being migrated from host " + srcHost.getName() + " explicitly dedicated to domain " + domainOfDedicatedHost(srcHost) + " to host " + + destHost.getName() + " explicitly dedicated to domain " + domainOfDedicatedHost(destHost); _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_USERVM, vm.getDataCenterId(), vm.getPodIdToDeployIn(), msg, msg); s_logger.warn(msg); } @@ -4046,9 +4036,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir if (!isServiceOfferingUsingPlannerInPreferredMode(vm.getServiceOfferingId())) { //Check if all vms on destination host are created using strict implicit mode if (!checkIfAllVmsCreatedInStrictMode(accountOfVm, vmsOnDest)) { - msg = - "VM of account " + accountOfVm + " with strict implicit deployment planner being migrated to host " + destHost.getName() + - " not having all vms strict implicitly dedicated to account " + accountOfVm; + msg = "VM of account " + accountOfVm + " with strict implicit deployment planner being migrated to host " + destHost.getName() + + " not having all vms strict implicitly dedicated to account " + accountOfVm; } } else { //If vm is deployed using preferred implicit planner, check if all vms on destination host must be @@ -4056,9 +4045,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir for (VMInstanceVO vmsDest : vmsOnDest) { ServiceOfferingVO destPlanner = _offeringDao.findById(vm.getId(), vmsDest.getServiceOfferingId()); if (!((destPlanner.getDeploymentPlanner() != null && destPlanner.getDeploymentPlanner().equals("ImplicitDedicationPlanner")) && vmsDest.getAccountId() == accountOfVm)) { - msg = - "VM of account " + accountOfVm + " with preffered implicit deployment planner being migrated to host " + destHost.getName() + - " not having all vms implicitly dedicated to account " + accountOfVm; + msg = "VM of account " + accountOfVm + " with preffered implicit deployment planner being migrated to host " + destHost.getName() + + " not having all vms implicitly dedicated to account " + accountOfVm; } } } @@ -4136,8 +4124,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir createdByImplicitStrict = false; break; } else if (isServiceOfferingUsingPlannerInPreferredMode(vm.getServiceOfferingId()) || vm.getAccountId() != accountId) { - s_logger.info("Host " + vm.getHostId() + " found to be running a vm created by an implicit planner" + - " in preferred mode, or running vms of other account"); + s_logger.info("Host " + vm.getHostId() + " found to be running a vm created by an implicit planner" + " in preferred mode, or running vms of other account"); createdByImplicitStrict = false; break; } @@ -4165,7 +4152,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir @Override @ActionEvent(eventType = EventTypes.EVENT_VM_MIGRATE, eventDescription = "migrating VM", async = true) public VirtualMachine migrateVirtualMachineWithVolume(Long vmId, Host destinationHost, Map volumeToPool) throws ResourceUnavailableException, - ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException { + ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException { // Access check - only root administrator can migrate VM. Account caller = CallContext.current().getCallingAccount(); if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { @@ -4189,9 +4176,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir throw ex; } - if (!vm.getHypervisorType().equals(HypervisorType.XenServer) && !vm.getHypervisorType().equals(HypervisorType.VMware) && - !vm.getHypervisorType().equals(HypervisorType.KVM) && !vm.getHypervisorType().equals(HypervisorType.Ovm) && - !vm.getHypervisorType().equals(HypervisorType.Simulator)) { + if (!vm.getHypervisorType().equals(HypervisorType.XenServer) && !vm.getHypervisorType().equals(HypervisorType.VMware) && !vm.getHypervisorType().equals(HypervisorType.KVM) + && !vm.getHypervisorType().equals(HypervisorType.Ovm) && !vm.getHypervisorType().equals(HypervisorType.Simulator)) { throw new InvalidParameterValueException("Unsupported hypervisor type for vm migration, we support" + " XenServer/VMware/KVM only"); } @@ -4199,27 +4185,25 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir Host srcHost = _resourceMgr.getHost(srcHostId); // Check if src and destination hosts are valid and migrating to same host if (destinationHost.getId() == srcHostId) { - throw new InvalidParameterValueException("Cannot migrate VM, VM is already present on this host, please" - + " specify valid destination host to migrate the VM"); + throw new InvalidParameterValueException("Cannot migrate VM, VM is already present on this host, please" + " specify valid destination host to migrate the VM"); } // Check if the source and destination hosts are of the same type and support storage motion. if (!(srcHost.getHypervisorType().equals(destinationHost.getHypervisorType()) && srcHost.getHypervisorVersion().equals(destinationHost.getHypervisorVersion()))) { - throw new CloudRuntimeException("The source and destination hosts are not of the same type and version. " + "Source hypervisor type and version: " + - srcHost.getHypervisorType().toString() + " " + srcHost.getHypervisorVersion() + ", Destination hypervisor type and version: " + - destinationHost.getHypervisorType().toString() + " " + destinationHost.getHypervisorVersion()); + throw new CloudRuntimeException("The source and destination hosts are not of the same type and version. " + "Source hypervisor type and version: " + + srcHost.getHypervisorType().toString() + " " + srcHost.getHypervisorVersion() + ", Destination hypervisor type and version: " + + destinationHost.getHypervisorType().toString() + " " + destinationHost.getHypervisorVersion()); } HypervisorCapabilitiesVO capabilities = _hypervisorCapabilitiesDao.findByHypervisorTypeAndVersion(srcHost.getHypervisorType(), srcHost.getHypervisorVersion()); if (!capabilities.isStorageMotionSupported()) { - throw new CloudRuntimeException("Migration with storage isn't supported on hypervisor " + srcHost.getHypervisorType() + " of version " + - srcHost.getHypervisorVersion()); + throw new CloudRuntimeException("Migration with storage isn't supported on hypervisor " + srcHost.getHypervisorType() + " of version " + srcHost.getHypervisorVersion()); } // Check if destination host is up. if (destinationHost.getState() != com.cloud.host.Status.Up || destinationHost.getResourceState() != ResourceState.Enabled) { - throw new CloudRuntimeException("Cannot migrate VM, destination host is not in correct state, has " + "status: " + destinationHost.getState() + ", state: " + - destinationHost.getResourceState()); + throw new CloudRuntimeException("Cannot migrate VM, destination host is not in correct state, has " + "status: " + destinationHost.getState() + ", state: " + + destinationHost.getResourceState()); } List vmVolumes = _volsDao.findUsableVolumesForInstance(vm.getId()); @@ -4228,8 +4212,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir if (volumeToPool.isEmpty()) { // If the destination host is in the same cluster and volumes do not have to be migrated across pools // then fail the call. migrateVirtualMachine api should have been used. - throw new InvalidParameterValueException("Migration of the vm " + vm + "from host " + srcHost + " to destination host " + destinationHost + - " doesn't involve migrating the volumes."); + throw new InvalidParameterValueException("Migration of the vm " + vm + "from host " + srcHost + " to destination host " + destinationHost + + " doesn't involve migrating the volumes."); } } @@ -4245,8 +4229,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } else { // Verify the volume given belongs to the vm. if (!vmVolumes.contains(volume)) { - throw new InvalidParameterValueException("There volume " + volume + " doesn't belong to " + "the virtual machine " + vm + - " that has to be migrated"); + throw new InvalidParameterValueException("There volume " + volume + " doesn't belong to " + "the virtual machine " + vm + " that has to be migrated"); } volToPoolObjectMap.put(volume, pool); } @@ -4263,8 +4246,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir // Check max guest vm limit for the destinationHost. HostVO destinationHostVO = _hostDao.findById(destinationHost.getId()); if (_capacityMgr.checkIfHostReachMaxGuestLimit(destinationHostVO)) { - throw new VirtualMachineMigrationException("Host name: " + destinationHost.getName() + ", hostId: " + destinationHost.getId() + - " already has max running vms (count includes system VMs). Cannot" + " migrate to this host"); + throw new VirtualMachineMigrationException("Host name: " + destinationHost.getName() + ", hostId: " + destinationHost.getId() + + " already has max running vms (count includes system VMs). Cannot" + " migrate to this host"); } checkHostsDedication(vm, srcHostId, destinationHost.getId()); @@ -4276,8 +4259,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir @DB @Override @ActionEvent(eventType = EventTypes.EVENT_VM_MOVE, eventDescription = "move VM to another user", async = false) - public UserVm moveVMToUser(final AssignVMCmd cmd) throws ResourceAllocationException, ConcurrentOperationException, ResourceUnavailableException, - InsufficientCapacityException { + public UserVm moveVMToUser(final AssignVMCmd cmd) throws ResourceAllocationException, ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { // VERIFICATIONS and VALIDATIONS // VV 1: verify the two users @@ -4365,7 +4347,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir removeInstanceFromInstanceGroup(cmd.getVmId()); // VV 2: check if account/domain is with in resource limits to create a new vm - resourceLimitCheck(newAccount, new Long(offering.getCpu()), new Long(offering.getRamSize())); + resourceLimitCheck(newAccount, vm.isDisplayVm(), new Long(offering.getCpu()), new Long(offering.getRamSize())); // VV 3: check if volumes and primary storage space are with in resource limits _resourceLimitMgr.checkResourceLimit(newAccount, ResourceType.volume, _volsDao.findByInstance(cmd.getVmId()).size()); @@ -4390,11 +4372,11 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir @Override public void doInTransactionWithoutResult(TransactionStatus status) { //generate destroy vm event for usage - UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_DESTROY, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), vm.getHostName(), - vm.getServiceOfferingId(), vm.getTemplateId(), vm.getHypervisorType().toString(), VirtualMachine.class.getName(), vm.getUuid()); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_DESTROY, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), vm.getHostName(), vm.getServiceOfferingId(), + vm.getTemplateId(), vm.getHypervisorType().toString(), VirtualMachine.class.getName(), vm.getUuid()); // update resource counts for old account - resourceCountDecrement(oldAccount.getAccountId(), new Long(offering.getCpu()), new Long(offering.getRamSize())); + resourceCountDecrement(oldAccount.getAccountId(), vm.isDisplayVm(), new Long(offering.getCpu()), new Long(offering.getRamSize())); // OWNERSHIP STEP 1: update the vm owner vm.setAccountId(newAccount.getAccountId()); @@ -4404,7 +4386,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir // OS 2: update volume for (VolumeVO volume : volumes) { UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_DELETE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), - Volume.class.getName(), volume.getUuid()); + Volume.class.getName(), volume.getUuid()); _resourceLimitMgr.decrementResourceCount(oldAccount.getAccountId(), ResourceType.volume); _resourceLimitMgr.decrementResourceCount(oldAccount.getAccountId(), ResourceType.primary_storage, new Long(volume.getSize())); volume.setAccountId(newAccount.getAccountId()); @@ -4413,7 +4395,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir _resourceLimitMgr.incrementResourceCount(newAccount.getAccountId(), ResourceType.volume); _resourceLimitMgr.incrementResourceCount(newAccount.getAccountId(), ResourceType.primary_storage, new Long(volume.getSize())); UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), - volume.getDiskOfferingId(), volume.getTemplateId(), volume.getSize(), Volume.class.getName(), volume.getUuid()); + volume.getDiskOfferingId(), volume.getTemplateId(), volume.getSize(), Volume.class.getName(), volume.getUuid()); //snapshots: mark these removed in db List snapshots = _snapshotDao.listByVolumeIdIncludingRemoved(volume.getId()); for (SnapshotVO snapshot : snapshots) { @@ -4422,11 +4404,11 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } //update resource count of new account - resourceCountIncrement(newAccount.getAccountId(), new Long(offering.getCpu()), new Long(offering.getRamSize())); + resourceCountIncrement(newAccount.getAccountId(), vm.isDisplayVm(), new Long(offering.getCpu()), new Long(offering.getRamSize())); //generate usage events to account for this change - UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_CREATE, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), vm.getHostName(), - vm.getServiceOfferingId(), vm.getTemplateId(), vm.getHypervisorType().toString(), VirtualMachine.class.getName(), vm.getUuid()); + UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_CREATE, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), vm.getHostName(), vm.getServiceOfferingId(), + vm.getTemplateId(), vm.getHypervisorType().toString(), VirtualMachine.class.getName(), vm.getUuid()); } }); @@ -4488,8 +4470,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir if (s_logger.isDebugEnabled()) { s_logger.debug("Couldn't find default security group for the account " + newAccount + " so creating a new one"); } - defaultGroup = - _securityGroupMgr.createSecurityGroup(SecurityGroupManager.DEFAULT_GROUP_NAME, SecurityGroupManager.DEFAULT_GROUP_DESCRIPTION, + defaultGroup = _securityGroupMgr.createSecurityGroup(SecurityGroupManager.DEFAULT_GROUP_NAME, SecurityGroupManager.DEFAULT_GROUP_DESCRIPTION, newAccount.getDomainId(), newAccount.getId(), newAccount.getAccountName()); securityGroupIdList.add(defaultGroup.getId()); } @@ -4535,8 +4516,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir // don't allow to use system networks NetworkOffering networkOffering = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId()); if (networkOffering.isSystemOnly()) { - InvalidParameterValueException ex = - new InvalidParameterValueException("Specified Network id is system only and can't be used for vm deployment"); + InvalidParameterValueException ex = new InvalidParameterValueException("Specified Network id is system only and can't be used for vm deployment"); ex.addProxyObject(network.getUuid(), "networkId"); throw ex; } @@ -4546,27 +4526,26 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir NetworkVO defaultNetwork = null; List requiredOfferings = _networkOfferingDao.listByAvailability(Availability.Required, false); if (requiredOfferings.size() < 1) { - throw new InvalidParameterValueException("Unable to find network offering with availability=" + Availability.Required + - " to automatically create the network as a part of vm creation"); + throw new InvalidParameterValueException("Unable to find network offering with availability=" + Availability.Required + + " to automatically create the network as a part of vm creation"); } if (requiredOfferings.get(0).getState() == NetworkOffering.State.Enabled) { // get Virtual networks List virtualNetworks = _networkModel.listNetworksForAccount(newAccount.getId(), zone.getId(), Network.GuestType.Isolated); if (virtualNetworks.isEmpty()) { - long physicalNetworkId = - _networkModel.findPhysicalNetworkId(zone.getId(), requiredOfferings.get(0).getTags(), requiredOfferings.get(0).getTrafficType()); + long physicalNetworkId = _networkModel.findPhysicalNetworkId(zone.getId(), requiredOfferings.get(0).getTags(), requiredOfferings.get(0) + .getTrafficType()); // Validate physical network PhysicalNetwork physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId); if (physicalNetwork == null) { - throw new InvalidParameterValueException("Unable to find physical network with id: " + physicalNetworkId + " and tag: " + - requiredOfferings.get(0).getTags()); + throw new InvalidParameterValueException("Unable to find physical network with id: " + physicalNetworkId + " and tag: " + + requiredOfferings.get(0).getTags()); } - s_logger.debug("Creating network for account " + newAccount + " from the network offering id=" + requiredOfferings.get(0).getId() + - " as a part of deployVM process"); - Network newNetwork = - _networkMgr.createGuestNetwork(requiredOfferings.get(0).getId(), newAccount.getAccountName() + "-network", newAccount.getAccountName() + - "-network", null, null, null, null, newAccount, null, physicalNetwork, zone.getId(), ACLType.Account, null, null, null, null, true, - null); + s_logger.debug("Creating network for account " + newAccount + " from the network offering id=" + requiredOfferings.get(0).getId() + + " as a part of deployVM process"); + Network newNetwork = _networkMgr.createGuestNetwork(requiredOfferings.get(0).getId(), newAccount.getAccountName() + "-network", + newAccount.getAccountName() + "-network", null, null, null, null, newAccount, null, physicalNetwork, zone.getId(), ACLType.Account, null, null, + null, null, true, null); // if the network offering has persistent set to true, implement the network if (requiredOfferings.get(0).getIsPersistent()) { DeployDestination dest = new DeployDestination(zone, null, null, null); @@ -4581,10 +4560,9 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } newNetwork = implementedNetwork.second(); } catch (Exception ex) { - s_logger.warn("Failed to implement network " + newNetwork + " elements and" + - " resources as a part of network provision for persistent network due to ", ex); - CloudRuntimeException e = - new CloudRuntimeException("Failed to implement network" + s_logger.warn("Failed to implement network " + newNetwork + " elements and" + + " resources as a part of network provision for persistent network due to ", ex); + CloudRuntimeException e = new CloudRuntimeException("Failed to implement network" + " (with specified id) elements and resources as a part of network provision"); e.addProxyObject(newNetwork.getUuid(), "networkId"); throw e; @@ -4592,14 +4570,13 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir } defaultNetwork = _networkDao.findById(newNetwork.getId()); } else if (virtualNetworks.size() > 1) { - throw new InvalidParameterValueException("More than 1 default Isolated networks are found " + "for account " + newAccount + - "; please specify networkIds"); + throw new InvalidParameterValueException("More than 1 default Isolated networks are found " + "for account " + newAccount + + "; please specify networkIds"); } else { defaultNetwork = _networkDao.findById(virtualNetworks.get(0).getId()); } } else { - throw new InvalidParameterValueException("Required network offering id=" + requiredOfferings.get(0).getId() + " is not in " + - NetworkOffering.State.Enabled); + throw new InvalidParameterValueException("Required network offering id=" + requiredOfferings.get(0).getId() + " is not in " + NetworkOffering.State.Enabled); } applicableNetworks.add(defaultNetwork); @@ -4830,4 +4807,16 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir public ConfigKey[] getConfigKeys() { return new ConfigKey[] {EnableDynamicallyScaleVm}; } + + @Override + public String getVmUserData(long vmId) { + UserVmVO vm = _vmDao.findById(vmId); + if (vm == null) { + throw new InvalidParameterValueException("Unable to find virual machine with id " + vmId); + } + + //check permissions + _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, vm); + return vm.getUserData(); + } } diff --git a/server/src/com/cloud/vm/UserVmStateListener.java b/server/src/com/cloud/vm/UserVmStateListener.java index 9f5f51dc06f..2f6be6cbbcf 100644 --- a/server/src/com/cloud/vm/UserVmStateListener.java +++ b/server/src/com/cloud/vm/UserVmStateListener.java @@ -24,6 +24,7 @@ import java.util.Map; import javax.inject.Inject; +import com.cloud.server.ManagementService; import org.apache.log4j.Logger; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -32,11 +33,12 @@ import org.apache.cloudstack.framework.events.EventBus; import com.cloud.event.EventCategory; import com.cloud.event.EventTypes; import com.cloud.event.UsageEventUtils; +import com.cloud.event.UsageEventVO; import com.cloud.event.dao.UsageEventDao; import com.cloud.network.dao.NetworkDao; import com.cloud.network.dao.NetworkVO; -import com.cloud.server.ManagementServer; -import com.cloud.server.ManagementService; +import com.cloud.service.ServiceOfferingVO; +import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.utils.component.ComponentContext; import com.cloud.utils.fsm.StateListener; import com.cloud.vm.VirtualMachine.Event; @@ -45,20 +47,19 @@ import com.cloud.vm.dao.NicDao; public class UserVmStateListener implements StateListener { - @Inject - protected UsageEventDao _usageEventDao; - @Inject - protected NetworkDao _networkDao; - @Inject - protected NicDao _nicDao; + @Inject protected UsageEventDao _usageEventDao; + @Inject protected NetworkDao _networkDao; + @Inject protected NicDao _nicDao; + @Inject protected ServiceOfferingDao _offeringDao; private static final Logger s_logger = Logger.getLogger(UserVmStateListener.class); - protected static EventBus _eventBus = null; + protected static EventBus s_eventBus = null; - public UserVmStateListener(UsageEventDao usageEventDao, NetworkDao networkDao, NicDao nicDao) { + public UserVmStateListener(UsageEventDao usageEventDao, NetworkDao networkDao, NicDao nicDao, ServiceOfferingDao offeringDao) { this._usageEventDao = usageEventDao; this._networkDao = networkDao; this._nicDao = nicDao; + this._offeringDao = offeringDao; } @Override @@ -80,14 +81,11 @@ public class UserVmStateListener implements StateListener nics = _nicDao.listByVmId(vo.getId()); for (NicVO nic : nics) { NetworkVO network = _networkDao.findById(nic.getNetworkId()); @@ -95,16 +93,33 @@ public class UserVmStateListener implements StateListener customParameters = new HashMap(); + customParameters.put(UsageEventVO.DynamicParameters.cpuNumber.name(), serviceOffering.getCpu().toString()); + customParameters.put(UsageEventVO.DynamicParameters.cpuSpeed.name(), serviceOffering.getSpeed().toString()); + customParameters.put(UsageEventVO.DynamicParameters.memory.name(), serviceOffering.getRamSize().toString()); + UsageEventUtils.publishUsageEvent(eventType, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), + vm.getHostName(), serviceOffering.getId(), vm.getTemplateId(), vm.getHypervisorType().toString(), + VirtualMachine.class.getName(), vm.getUuid(), customParameters); + } + } + private void pubishOnEventBus(String event, String status, VirtualMachine vo, VirtualMachine.State oldState, VirtualMachine.State newState) { try { - _eventBus = ComponentContext.getComponent(EventBus.class); + s_eventBus = ComponentContext.getComponent(EventBus.class); } catch (NoSuchBeanDefinitionException nbe) { return; // no provider is configured to provide events bus, so just return } @@ -124,7 +139,7 @@ public class UserVmStateListener implements StateListener VmJobEnabled = new ConfigKey("Advanced", + Boolean.class, "vm.job.enabled", "false", + "True to enable new VM sync model. false to use the old way", false); + static final ConfigKey VmJobCheckInterval = new ConfigKey("Advanced", + Long.class, "vm.job.check.interval", "3000", + "Interval in milliseconds to check if the job is complete", false); + @Override public boolean configure(String name, Map params) throws ConfigurationException { _name = name; @@ -182,8 +218,8 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana if (state == null) { VMSnapshot.State[] status = - {VMSnapshot.State.Ready, VMSnapshot.State.Creating, VMSnapshot.State.Allocated, VMSnapshot.State.Error, VMSnapshot.State.Expunging, - VMSnapshot.State.Reverting}; + {VMSnapshot.State.Ready, VMSnapshot.State.Creating, VMSnapshot.State.Allocated, VMSnapshot.State.Error, VMSnapshot.State.Expunging, + VMSnapshot.State.Reverting}; sc.setParameters("status", (Object[])status); } else { sc.setParameters("state", state); @@ -249,7 +285,7 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana throw new InvalidParameterValueException("Creating vm snapshot failed due to VM:" + vmId + " is not in the running or Stopped state"); } - if (snapshotMemory && userVmVo.getState() == VirtualMachine.State.Stopped) { + if(snapshotMemory && userVmVo.getState() == VirtualMachine.State.Stopped){ throw new InvalidParameterValueException("Can not snapshot memory when VM is in stopped state"); } @@ -327,6 +363,56 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana if (vmSnapshot == null) { throw new CloudRuntimeException("VM snapshot id: " + vmSnapshotId + " can not be found"); } + + // serialize VM operation + AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); + if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) { + // avoid re-entrance + VmWorkJobVO placeHolder = null; + if (VmJobEnabled.value()) { + placeHolder = createPlaceHolderWork(vmId); + } + try { + return orchestrateCreateVMSnapshot(vmId, vmSnapshotId, quiescevm); + } finally { + if (VmJobEnabled.value()) + _workJobDao.expunge(placeHolder.getId()); + } + + } else { + Outcome outcome = createVMSnapshotThroughJobQueue(vmId, vmSnapshotId, quiescevm); + + VMSnapshot result = null; + try { + result = outcome.get(); + } catch (InterruptedException e) { + throw new RuntimeException("Operation is interrupted", e); + } catch (java.util.concurrent.ExecutionException e) { + throw new RuntimeException("Execution excetion", e); + } + + Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); + if (jobResult != null) { + if (jobResult instanceof ConcurrentOperationException) + throw (ConcurrentOperationException)jobResult; + else if (jobResult instanceof Throwable) + throw new RuntimeException("Unexpected exception", (Throwable)jobResult); + } + + return result; + } + } + + private VMSnapshot orchestrateCreateVMSnapshot(Long vmId, Long vmSnapshotId, Boolean quiescevm) { + UserVmVO userVm = _userVMDao.findById(vmId); + if (userVm == null) { + throw new InvalidParameterValueException("Create vm to snapshot failed due to vm: " + vmId + " is not found"); + } + VMSnapshotVO vmSnapshot = _vmSnapshotDao.findById(vmSnapshotId); + if (vmSnapshot == null) { + throw new CloudRuntimeException("VM snapshot id: " + vmSnapshotId + " can not be found"); + } + VMSnapshotOptions options = new VMSnapshotOptions(quiescevm); vmSnapshot.setOptions(options); try { @@ -376,6 +462,71 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana throw new InvalidParameterValueException("There is other active vm snapshot tasks on the instance, please try again later"); } + // serialize VM operation + AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); + if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) { + // avoid re-entrance + VmWorkJobVO placeHolder = null; + if (VmJobEnabled.value()) { + placeHolder = createPlaceHolderWork(vmSnapshot.getVmId()); + } + try { + return orchestrateDeleteVMSnapshot(vmSnapshotId); + } finally { + if (VmJobEnabled.value()) + _workJobDao.expunge(placeHolder.getId()); + } + } else { + Outcome outcome = deleteVMSnapshotThroughJobQueue(vmSnapshot.getVmId(), vmSnapshotId); + + VMSnapshot result = null; + try { + result = outcome.get(); + } catch (InterruptedException e) { + throw new RuntimeException("Operation is interrupted", e); + } catch (java.util.concurrent.ExecutionException e) { + throw new RuntimeException("Execution excetion", e); + } + + Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); + if (jobResult != null) { + if (jobResult instanceof ConcurrentOperationException) + throw (ConcurrentOperationException)jobResult; + else if (jobResult instanceof Throwable) + throw new RuntimeException("Unexpected exception", (Throwable)jobResult); + } + + if (jobResult instanceof Boolean) + return ((Boolean)jobResult).booleanValue(); + + return false; + } + } + + private boolean orchestrateDeleteVMSnapshot(Long vmSnapshotId) { + Account caller = getCaller(); + + VMSnapshotVO vmSnapshot = _vmSnapshotDao.findById(vmSnapshotId); + if (vmSnapshot == null) { + throw new InvalidParameterValueException("unable to find the vm snapshot with id " + vmSnapshotId); + } + + _accountMgr.checkAccess(caller, null, true, vmSnapshot); + + // check VM snapshot states, only allow to delete vm snapshots in created and error state + if (VMSnapshot.State.Ready != vmSnapshot.getState() && VMSnapshot.State.Expunging != vmSnapshot.getState() && VMSnapshot.State.Error != vmSnapshot.getState()) { + throw new InvalidParameterValueException("Can't delete the vm snapshotshot " + vmSnapshotId + " due to it is not in Created or Error, or Expunging State"); + } + + // check if there are other active VM snapshot tasks + if (hasActiveVMSnapshotTasks(vmSnapshot.getVmId())) { + List expungingSnapshots = _vmSnapshotDao.listByInstanceId(vmSnapshot.getVmId(), VMSnapshot.State.Expunging); + if (expungingSnapshots.size() > 0 && expungingSnapshots.get(0).getId() == vmSnapshot.getId()) + s_logger.debug("Target VM snapshot already in expunging state, go on deleting it: " + vmSnapshot.getDisplayName()); + else + throw new InvalidParameterValueException("There is other active vm snapshot tasks on the instance, please try again later"); + } + if (vmSnapshot.getState() == VMSnapshot.State.Allocated) { return _vmSnapshotDao.remove(vmSnapshot.getId()); } else { @@ -413,6 +564,88 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana Account caller = getCaller(); _accountMgr.checkAccess(caller, null, true, vmSnapshotVo); + // VM should be in running or stopped states + if (userVm.getState() != VirtualMachine.State.Running + && userVm.getState() != VirtualMachine.State.Stopped) { + throw new InvalidParameterValueException( + "VM Snapshot reverting failed due to vm is not in the state of Running or Stopped."); + } + + // if snapshot is not created, error out + if (vmSnapshotVo.getState() != VMSnapshot.State.Ready) { + throw new InvalidParameterValueException( + "VM Snapshot reverting failed due to vm snapshot is not in the state of Created."); + } + + // serialize VM operation + AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); + if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) { + // avoid re-entrance + + VmWorkJobVO placeHolder = null; + if (VmJobEnabled.value()) { + placeHolder = createPlaceHolderWork(vmSnapshotVo.getVmId()); + } + try { + return orchestrateRevertToVMSnapshot(vmSnapshotId); + } finally { + if (VmJobEnabled.value()) + _workJobDao.expunge(placeHolder.getId()); + } + + } else { + Outcome outcome = revertToVMSnapshotThroughJobQueue(vmSnapshotVo.getVmId(), vmSnapshotId); + + VMSnapshot result = null; + try { + result = outcome.get(); + } catch (InterruptedException e) { + throw new RuntimeException("Operation is interrupted", e); + } catch (java.util.concurrent.ExecutionException e) { + throw new RuntimeException("Execution excetion", e); + } + + Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); + if (jobResult != null) { + if (jobResult instanceof ConcurrentOperationException) + throw (ConcurrentOperationException)jobResult; + else if (jobResult instanceof InsufficientCapacityException) + throw (InsufficientCapacityException)jobResult; + else if (jobResult instanceof ResourceUnavailableException) + throw (ResourceUnavailableException)jobResult; + else if (jobResult instanceof Throwable) + throw new RuntimeException("Unexpected exception", (Throwable)jobResult); + } + + return userVm; + } + } + + private UserVm orchestrateRevertToVMSnapshot(Long vmSnapshotId) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException { + + // check if VM snapshot exists in DB + VMSnapshotVO vmSnapshotVo = _vmSnapshotDao.findById(vmSnapshotId); + if (vmSnapshotVo == null) { + throw new InvalidParameterValueException( + "unable to find the vm snapshot with id " + vmSnapshotId); + } + Long vmId = vmSnapshotVo.getVmId(); + UserVmVO userVm = _userVMDao.findById(vmId); + // check if VM exists + if (userVm == null) { + throw new InvalidParameterValueException("Revert vm to snapshot: " + + vmSnapshotId + " failed due to vm: " + vmId + + " is not found"); + } + + // check if there are other active VM snapshot tasks + if (hasActiveVMSnapshotTasks(vmId)) { + throw new InvalidParameterValueException("There is other active vm snapshot tasks on the instance, please try again later"); + } + + Account caller = getCaller(); + _accountMgr.checkAccess(caller, null, true, vmSnapshotVo); + // VM should be in running or stopped states if (userVm.getState() != VirtualMachine.State.Running && userVm.getState() != VirtualMachine.State.Stopped) { throw new InvalidParameterValueException("VM Snapshot reverting failed due to vm is not in the state of Running or Stopped."); @@ -429,7 +662,7 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana // start or stop VM first, if revert from stopped state to running state, or from running to stopped if (userVm.getState() == VirtualMachine.State.Stopped && vmSnapshotVo.getType() == VMSnapshot.Type.DiskAndMemory) { try { - _itMgr.advanceStart(userVm.getUuid(), new HashMap()); + _itMgr.advanceStart(userVm.getUuid(), new HashMap(), null); vm = _userVMDao.findById(userVm.getId()); hostId = vm.getHostId(); } catch (Exception e) { @@ -481,6 +714,48 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana @Override public boolean deleteAllVMSnapshots(long vmId, VMSnapshot.Type type) { + // serialize VM operation + AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext(); + if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) { + // avoid re-entrance + VmWorkJobVO placeHolder = null; + if (VmJobEnabled.value()) { + placeHolder = createPlaceHolderWork(vmId); + } + try { + return orchestrateDeleteAllVMSnapshots(vmId, type); + } finally { + if (VmJobEnabled.value()) + _workJobDao.expunge(placeHolder.getId()); + } + + } else { + Outcome outcome = deleteAllVMSnapshotsThroughJobQueue(vmId, type); + + try { + outcome.get(); + } catch (InterruptedException e) { + throw new RuntimeException("Operation is interrupted", e); + } catch (java.util.concurrent.ExecutionException e) { + throw new RuntimeException("Execution excetion", e); + } + + Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob()); + if (jobResult != null) { + if (jobResult instanceof ConcurrentOperationException) + throw (ConcurrentOperationException)jobResult; + else if (jobResult instanceof Throwable) + throw new RuntimeException("Unexpected exception", (Throwable)jobResult); + } + + if (jobResult instanceof Boolean) + return (Boolean)jobResult; + + return false; + } + } + + private boolean orchestrateDeleteAllVMSnapshots(long vmId, VMSnapshot.Type type) { boolean result = true; List listVmSnapshots = _vmSnapshotDao.findByVm(vmId); if (listVmSnapshots == null || listVmSnapshots.isEmpty()) { @@ -501,14 +776,13 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana @Override public boolean syncVMSnapshot(VMInstanceVO vm, Long hostId) { - try { + try{ UserVmVO userVm = _userVMDao.findById(vm.getId()); if (userVm == null) return false; - List vmSnapshotsInExpungingStates = - _vmSnapshotDao.listByInstanceId(vm.getId(), VMSnapshot.State.Expunging, VMSnapshot.State.Reverting, VMSnapshot.State.Creating); + List vmSnapshotsInExpungingStates = _vmSnapshotDao.listByInstanceId(vm.getId(), VMSnapshot.State.Expunging, VMSnapshot.State.Reverting, VMSnapshot.State.Creating); for (VMSnapshotVO vmSnapshotVO : vmSnapshotsInExpungingStates) { VMSnapshotStrategy strategy = findVMSnapshotStrategy(vmSnapshotVO); if (vmSnapshotVO.getState() == VMSnapshot.State.Expunging) { @@ -529,4 +803,273 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana return false; } + public class VmJobVMSnapshotOutcome extends OutcomeImpl { + private long _vmSnapshotId; + + public VmJobVMSnapshotOutcome(final AsyncJob job, final long vmSnapshotId) { + super(VMSnapshot.class, job, VmJobCheckInterval.value(), new Predicate() { + @Override + public boolean checkCondition() { + AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, job.getId()); + assert (jobVo != null); + if (jobVo == null || jobVo.getStatus() != JobInfo.Status.IN_PROGRESS) + return true; + + return false; + } + }, AsyncJob.Topics.JOB_STATE); + _vmSnapshotId = vmSnapshotId; + } + + @Override + protected VMSnapshot retrieve() { + return _vmSnapshotDao.findById(_vmSnapshotId); + } + } + + public class VmJobVirtualMachineOutcome extends OutcomeImpl { + long vmId; + + public VmJobVirtualMachineOutcome(final AsyncJob job, final long vmId) { + super(VirtualMachine.class, job, VmJobCheckInterval.value(), new Predicate() { + @Override + public boolean checkCondition() { + AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, job.getId()); + assert (jobVo != null); + if (jobVo == null || jobVo.getStatus() != JobInfo.Status.IN_PROGRESS) + return true; + + return false; + } + }, AsyncJob.Topics.JOB_STATE); + } + + @Override + protected VirtualMachine retrieve() { + return _vmInstanceDao.findById(vmId); + } + } + + public Outcome createVMSnapshotThroughJobQueue(final Long vmId, final Long vmSnapshotId, final boolean quiesceVm) { + + final CallContext context = CallContext.current(); + final User callingUser = context.getCallingUser(); + final Account callingAccount = context.getCallingAccount(); + + final VMInstanceVO vm = _vmInstanceDao.findById(vmId); + + Object[] result = Transaction.execute(new TransactionCallback() { + @Override + public Object[] doInTransaction(TransactionStatus status) { + VmWorkJobVO workJob = null; + + _vmInstanceDao.lockRow(vm.getId(), true); + workJob = new VmWorkJobVO(context.getContextId()); + + workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkCreateVMSnapshot.class.getName()); + + workJob.setAccountId(callingAccount.getId()); + workJob.setUserId(callingUser.getId()); + workJob.setStep(VmWorkJobVO.Step.Starting); + workJob.setVmType(VirtualMachine.Type.Instance); + workJob.setVmInstanceId(vm.getId()); + workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId()); + + // save work context info (there are some duplications) + VmWorkCreateVMSnapshot workInfo = new VmWorkCreateVMSnapshot(callingUser.getId(), callingAccount.getId(), vm.getId(), + VMSnapshotManagerImpl.VM_WORK_JOB_HANDLER, vmSnapshotId, quiesceVm); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + + _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId()); + + return new Object[] {workJob, new Long(workJob.getId())}; + } + }); + + final long jobId = (Long)result[1]; + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + + return new VmJobVMSnapshotOutcome((VmWorkJobVO)result[0], + vmSnapshotId); + } + + public Outcome deleteVMSnapshotThroughJobQueue(final Long vmId, final Long vmSnapshotId) { + + final CallContext context = CallContext.current(); + final User callingUser = context.getCallingUser(); + final Account callingAccount = context.getCallingAccount(); + + final VMInstanceVO vm = _vmInstanceDao.findById(vmId); + + Object[] result = Transaction.execute(new TransactionCallback() { + @Override + public Object[] doInTransaction(TransactionStatus status) { + VmWorkJobVO workJob = null; + + _vmInstanceDao.lockRow(vm.getId(), true); + workJob = new VmWorkJobVO(context.getContextId()); + + workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkDeleteVMSnapshot.class.getName()); + + workJob.setAccountId(callingAccount.getId()); + workJob.setUserId(callingUser.getId()); + workJob.setStep(VmWorkJobVO.Step.Starting); + workJob.setVmType(VirtualMachine.Type.Instance); + workJob.setVmInstanceId(vm.getId()); + workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId()); + + // save work context info (there are some duplications) + VmWorkDeleteVMSnapshot workInfo = new VmWorkDeleteVMSnapshot(callingUser.getId(), callingAccount.getId(), vm.getId(), + VMSnapshotManagerImpl.VM_WORK_JOB_HANDLER, vmSnapshotId); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + + _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId()); + + return new Object[] {workJob, new Long(workJob.getId())}; + } + }); + + final long jobId = (Long)result[1]; + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + + return new VmJobVMSnapshotOutcome((VmWorkJobVO)result[0], + vmSnapshotId); + } + + public Outcome revertToVMSnapshotThroughJobQueue(final Long vmId, final Long vmSnapshotId) { + + final CallContext context = CallContext.current(); + final User callingUser = context.getCallingUser(); + final Account callingAccount = context.getCallingAccount(); + + final VMInstanceVO vm = _vmInstanceDao.findById(vmId); + + Object[] result = Transaction.execute(new TransactionCallback() { + @Override + public Object[] doInTransaction(TransactionStatus status) { + VmWorkJobVO workJob = null; + + _vmInstanceDao.lockRow(vm.getId(), true); + workJob = new VmWorkJobVO(context.getContextId()); + + workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkRevertToVMSnapshot.class.getName()); + + workJob.setAccountId(callingAccount.getId()); + workJob.setUserId(callingUser.getId()); + workJob.setStep(VmWorkJobVO.Step.Starting); + workJob.setVmType(VirtualMachine.Type.Instance); + workJob.setVmInstanceId(vm.getId()); + workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId()); + + // save work context info (there are some duplications) + VmWorkRevertToVMSnapshot workInfo = new VmWorkRevertToVMSnapshot(callingUser.getId(), callingAccount.getId(), vm.getId(), + VMSnapshotManagerImpl.VM_WORK_JOB_HANDLER, vmSnapshotId); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + + _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId()); + + return new Object[] {workJob, new Long(workJob.getId())}; + } + }); + + final long jobId = (Long)result[1]; + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + + return new VmJobVMSnapshotOutcome((VmWorkJobVO)result[0], + vmSnapshotId); + } + + public Outcome deleteAllVMSnapshotsThroughJobQueue(final Long vmId, final VMSnapshot.Type type) { + + final CallContext context = CallContext.current(); + final User callingUser = context.getCallingUser(); + final Account callingAccount = context.getCallingAccount(); + + final VMInstanceVO vm = _vmInstanceDao.findById(vmId); + + Object[] result = Transaction.execute(new TransactionCallback() { + @Override + public Object[] doInTransaction(TransactionStatus status) { + VmWorkJobVO workJob = null; + + _vmInstanceDao.lockRow(vm.getId(), true); + workJob = new VmWorkJobVO(context.getContextId()); + + workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER); + workJob.setCmd(VmWorkDeleteAllVMSnapshots.class.getName()); + + workJob.setAccountId(callingAccount.getId()); + workJob.setUserId(callingUser.getId()); + workJob.setStep(VmWorkJobVO.Step.Starting); + workJob.setVmType(VirtualMachine.Type.Instance); + workJob.setVmInstanceId(vm.getId()); + workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId()); + + // save work context info (there are some duplications) + VmWorkDeleteAllVMSnapshots workInfo = new VmWorkDeleteAllVMSnapshots(callingUser.getId(), callingAccount.getId(), vm.getId(), + VMSnapshotManagerImpl.VM_WORK_JOB_HANDLER, type); + workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo)); + + _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId()); + + return new Object[] {workJob, new Long(workJob.getId())}; + } + }); + + final long jobId = (Long)result[1]; + AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId); + + return new VmJobVirtualMachineOutcome((VmWorkJobVO)result[0], + vmId); + } + + public Pair orchestrateCreateVMSnapshot(VmWorkCreateVMSnapshot work) throws Exception { + VMSnapshot snapshot = orchestrateCreateVMSnapshot(work.getVmId(), work.getVmSnapshotId(), work.isQuiesceVm()); + return new Pair(JobInfo.Status.SUCCEEDED, + _jobMgr.marshallResultObject(new Long(snapshot.getId()))); + } + + public Pair orchestrateDeleteVMSnapshot(VmWorkDeleteVMSnapshot work) { + boolean result = orchestrateDeleteVMSnapshot(work.getVmSnapshotId()); + return new Pair(JobInfo.Status.SUCCEEDED, + _jobMgr.marshallResultObject(new Boolean(result))); + } + + public Pair orchestrateRevertToVMSnapshot(VmWorkRevertToVMSnapshot work) throws Exception { + orchestrateRevertToVMSnapshot(work.getVmSnapshotId()); + return new Pair(JobInfo.Status.SUCCEEDED, null); + } + + public Pair orchestrateDeleteAllVMSnapshots(VmWorkDeleteAllVMSnapshots work) { + boolean result = orchestrateDeleteAllVMSnapshots(work.getVmId(), work.getSnapshotType()); + return new Pair(JobInfo.Status.SUCCEEDED, + _jobMgr.marshallResultObject(new Boolean(result))); + } + + @Override + public Pair handleVmWorkJob(VmWork work) throws Exception { + return _jobHandlerProxy.handleVmWorkJob(work); + } + + private VmWorkJobVO createPlaceHolderWork(long instanceId) { + VmWorkJobVO workJob = new VmWorkJobVO(""); + + workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_PLACEHOLDER); + workJob.setCmd(""); + workJob.setCmdInfo(""); + + workJob.setAccountId(0); + workJob.setUserId(0); + workJob.setStep(VmWorkJobVO.Step.Starting); + workJob.setVmType(VirtualMachine.Type.Instance); + workJob.setVmInstanceId(instanceId); + workJob.setInitMsid(ManagementServerNode.getManagementServerId()); + + _workJobDao.persist(workJob); + + return workJob; + } } diff --git a/server/src/com/cloud/uuididentity/dao/IdentityDao.java b/server/src/com/cloud/vm/snapshot/VmWorkCreateVMSnapshot.java similarity index 55% rename from server/src/com/cloud/uuididentity/dao/IdentityDao.java rename to server/src/com/cloud/vm/snapshot/VmWorkCreateVMSnapshot.java index a0978fac17c..33718029303 100644 --- a/server/src/com/cloud/uuididentity/dao/IdentityDao.java +++ b/server/src/com/cloud/vm/snapshot/VmWorkCreateVMSnapshot.java @@ -14,25 +14,28 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. +package com.cloud.vm.snapshot; -package com.cloud.uuididentity.dao; +import com.cloud.vm.VmWork; -import com.cloud.server.ResourceTag.ResourceObjectType; -import com.cloud.utils.Pair; -import com.cloud.utils.db.GenericDao; +public class VmWorkCreateVMSnapshot extends VmWork { + private static final long serialVersionUID = 124386202146049838L; -public interface IdentityDao extends GenericDao { - Long getIdentityId(String tableName, String identityString); + private Long vmSnapshotId; + private boolean quiesceVm; - String getIdentityUuid(String tableName, String identityString); + public VmWorkCreateVMSnapshot(long userId, long accountId, long vmId, String handlerName, Long vmSnapshotId, boolean quiesceVm) { + super(userId, accountId, vmId, handlerName); - void initializeDefaultUuid(String tableName); + this.vmSnapshotId = vmSnapshotId; + this.quiesceVm = quiesceVm; + } - /** - * @param tableName - * @param identityId - * @param resourceType TODO - * @return - */ - Pair getAccountDomainInfo(String tableName, Long identityId, ResourceObjectType resourceType); + public Long getVmSnapshotId() { + return vmSnapshotId; + } + + public boolean isQuiesceVm() { + return quiesceVm; + } } diff --git a/server/src/com/cloud/vm/snapshot/VmWorkDeleteAllVMSnapshots.java b/server/src/com/cloud/vm/snapshot/VmWorkDeleteAllVMSnapshots.java new file mode 100644 index 00000000000..ce20dfc984d --- /dev/null +++ b/server/src/com/cloud/vm/snapshot/VmWorkDeleteAllVMSnapshots.java @@ -0,0 +1,35 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.vm.snapshot; + +import com.cloud.vm.VmWork; + +public class VmWorkDeleteAllVMSnapshots extends VmWork { + private static final long serialVersionUID = -6010083039865471888L; + + private VMSnapshot.Type type; + + public VmWorkDeleteAllVMSnapshots(long userId, long accountId, long vmId, String handlerName, VMSnapshot.Type type) { + super(userId, accountId, vmId, handlerName); + + this.type = type; + } + + public VMSnapshot.Type getSnapshotType() { + return type; + } +} diff --git a/server/src/com/cloud/vm/snapshot/VmWorkDeleteVMSnapshot.java b/server/src/com/cloud/vm/snapshot/VmWorkDeleteVMSnapshot.java new file mode 100644 index 00000000000..1a80e39406d --- /dev/null +++ b/server/src/com/cloud/vm/snapshot/VmWorkDeleteVMSnapshot.java @@ -0,0 +1,35 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.vm.snapshot; + +import com.cloud.vm.VmWork; + +public class VmWorkDeleteVMSnapshot extends VmWork { + private static final long serialVersionUID = 7168101866614517508L; + + private Long vmSnapshotId; + + public VmWorkDeleteVMSnapshot(long userId, long accountId, long vmId, String handlerName, Long vmSnapshotId) { + super(userId, accountId, vmId, handlerName); + + this.vmSnapshotId = vmSnapshotId; + } + + public Long getVmSnapshotId() { + return vmSnapshotId; + } +} diff --git a/server/src/com/cloud/vm/snapshot/VmWorkRevertToVMSnapshot.java b/server/src/com/cloud/vm/snapshot/VmWorkRevertToVMSnapshot.java new file mode 100644 index 00000000000..f7beee5c4e5 --- /dev/null +++ b/server/src/com/cloud/vm/snapshot/VmWorkRevertToVMSnapshot.java @@ -0,0 +1,35 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.vm.snapshot; + +import com.cloud.vm.VmWork; + +public class VmWorkRevertToVMSnapshot extends VmWork { + private static final long serialVersionUID = -3406543280278986843L; + + private Long vmSnapshotId; + + public VmWorkRevertToVMSnapshot(long userId, long accountId, long vmId, String handlerName, Long vmSnapshotId) { + super(userId, accountId, vmId, handlerName); + + this.vmSnapshotId = vmSnapshotId; + } + + public Long getVmSnapshotId() { + return vmSnapshotId; + } +} diff --git a/server/src/org/apache/cloudstack/network/lb/CertServiceImpl.java b/server/src/org/apache/cloudstack/network/lb/CertServiceImpl.java index ae3d17939de..dd536fec552 100644 --- a/server/src/org/apache/cloudstack/network/lb/CertServiceImpl.java +++ b/server/src/org/apache/cloudstack/network/lb/CertServiceImpl.java @@ -238,27 +238,27 @@ public class CertServiceImpl implements CertService { return certResponseList; } - private void validate(String _cert, String _key, String _password, String _chain) { + private void validate(String certInput, String keyInput, String password, String chainInput) { Certificate cert; PrivateKey key; List chain = null; try { - cert = parseCertificate(_cert); - key = parsePrivateKey(_key, _password); + cert = parseCertificate(certInput); + key = parsePrivateKey(keyInput, password); - if (_chain != null) { - chain = parseChain(_chain); + if (chainInput != null) { + chain = parseChain(chainInput); } } catch (IOException e) { throw new IllegalArgumentException("Parsing certificate/key failed: " + e.getMessage(), e); } - validateCert(cert, _chain != null ? true : false); + validateCert(cert, chainInput != null ? true : false); validateKeys(cert.getPublicKey(), key); - if (_chain != null) + if (chainInput != null) validateChain(chain, cert); } @@ -289,7 +289,7 @@ public class CertServiceImpl implements CertService { return response; } - private void validateCert(Certificate cert, boolean chain_present) { + private void validateCert(Certificate cert, boolean chainPresent) { if (!(cert instanceof X509Certificate)) throw new IllegalArgumentException("Invalid certificate format. Expected X509 certificate"); @@ -300,7 +300,7 @@ public class CertServiceImpl implements CertService { throw new IllegalArgumentException("Certificate expired or not valid", e); } - if (!chain_present) { + if (!chainPresent) { PublicKey pubKey = cert.getPublicKey(); try { cert.verify(pubKey); @@ -482,7 +482,7 @@ public class CertServiceImpl implements CertService { public static class KeyPassword implements PasswordFinder { - boolean password_requested = false; + boolean passwordRequested = false; char[] password; KeyPassword(char[] word) { @@ -491,12 +491,12 @@ public class CertServiceImpl implements CertService { @Override public char[] getPassword() { - password_requested = true; + passwordRequested = true; return password; } public boolean getPasswordRequested() { - return password_requested; + return passwordRequested; } } } \ No newline at end of file diff --git a/server/test/async-job-component.xml b/server/test/async-job-component.xml index 55f47cc5b50..6c7a6e004dd 100644 --- a/server/test/async-job-component.xml +++ b/server/test/async-job-component.xml @@ -1,204 +1,191 @@ - - + + - - - - - - - 50 - -1 - - - - - 50 - -1 - - - 50 - -1 - - - - - - - 50 - -1 - routing - - - 5000 - 300 - - - - - 50 - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + 50 + -1 + + + + + 50 + -1 + + + 50 + -1 + + + + + + + 50 + -1 + routing + + + 5000 + 300 + + + + + 50 + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - 2 - - - 2 - - - - - + + + - - - + + + + + + + + 2 + + + 2 + + + + + - - - - - - - - - - - - - - - - - - - - - - - - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/server/test/com/cloud/capacity/CapacityManagerTest.java b/server/test/com/cloud/capacity/CapacityManagerTest.java index b6cae6be9c9..686089b9e34 100644 --- a/server/test/com/cloud/capacity/CapacityManagerTest.java +++ b/server/test/com/cloud/capacity/CapacityManagerTest.java @@ -39,11 +39,11 @@ public class CapacityManagerTest { ClusterDetailsDao ClusterDetailsDao = mock(com.cloud.dc.ClusterDetailsDao.class); CapacityManagerImpl capMgr; private ServiceOfferingVO svo = mock(ServiceOfferingVO.class); - private CapacityVO cvo_cpu = mock(CapacityVO.class); - private CapacityVO cvo_ram = mock(CapacityVO.class); + private CapacityVO cvoCpu = mock(CapacityVO.class); + private CapacityVO cvoRam = mock(CapacityVO.class); private VirtualMachine vm = mock(VirtualMachine.class); - private ClusterDetailsVO cluster_detail_cpu = mock(ClusterDetailsVO.class); - private ClusterDetailsVO cluster_detail_ram = mock(ClusterDetailsVO.class); + private ClusterDetailsVO clusterDetailCpu = mock(ClusterDetailsVO.class); + private ClusterDetailsVO clusterDetailRam = mock(ClusterDetailsVO.class); public CapacityManagerImpl setUp() { CapacityManagerImpl capMgr = new CapacityManagerImpl(); @@ -59,18 +59,18 @@ public class CapacityManagerTest { when(vm.getHostId()).thenReturn(1l); when(vm.getServiceOfferingId()).thenReturn(2l); when(SOfferingDao.findById(anyLong(), anyLong())).thenReturn(svo); - when(CDao.findByHostIdType(anyLong(), eq(Capacity.CAPACITY_TYPE_CPU))).thenReturn(cvo_cpu); - when(CDao.findByHostIdType(anyLong(), eq(Capacity.CAPACITY_TYPE_MEMORY))).thenReturn(cvo_ram); - when(cvo_cpu.getUsedCapacity()).thenReturn(500l); - when(cvo_cpu.getTotalCapacity()).thenReturn(2000l); - when(cvo_ram.getUsedCapacity()).thenReturn(3000l); - when(cvo_ram.getTotalCapacity()).thenReturn((long)1024 * 1024 * 1024); + when(CDao.findByHostIdType(anyLong(), eq(Capacity.CAPACITY_TYPE_CPU))).thenReturn(cvoCpu); + when(CDao.findByHostIdType(anyLong(), eq(Capacity.CAPACITY_TYPE_MEMORY))).thenReturn(cvoRam); + when(cvoCpu.getUsedCapacity()).thenReturn(500l); + when(cvoCpu.getTotalCapacity()).thenReturn(2000l); + when(cvoRam.getUsedCapacity()).thenReturn(3000l); + when(cvoRam.getTotalCapacity()).thenReturn((long)1024 * 1024 * 1024); when(svo.getCpu()).thenReturn(500); when(svo.getRamSize()).thenReturn(512); - when(cvo_cpu.getReservedCapacity()).thenReturn(0l); - when(cvo_ram.getReservedCapacity()).thenReturn(0l); - when(cluster_detail_ram.getValue()).thenReturn("1.5"); - when(cluster_detail_cpu.getValue()).thenReturn("2"); + when(cvoCpu.getReservedCapacity()).thenReturn(0l); + when(cvoRam.getReservedCapacity()).thenReturn(0l); + when(clusterDetailRam.getValue()).thenReturn("1.5"); + when(clusterDetailCpu.getValue()).thenReturn("2"); when(CDao.update(anyLong(), isA(CapacityVO.class))).thenReturn(true); boolean hasCapacity = capMgr.checkIfHostHasCapacity(1l, 500, 1024 * 1024 * 1024, false, 2, 2, false); Assert.assertTrue(hasCapacity); diff --git a/server/test/com/cloud/network/DedicateGuestVlanRangesTest.java b/server/test/com/cloud/network/DedicateGuestVlanRangesTest.java index 176891b198e..1615b849866 100644 --- a/server/test/com/cloud/network/DedicateGuestVlanRangesTest.java +++ b/server/test/com/cloud/network/DedicateGuestVlanRangesTest.java @@ -93,7 +93,7 @@ public class DedicateGuestVlanRangesTest { networkService._accountDao = _accountDao; networkService._projectMgr = _projectMgr; networkService._physicalNetworkDao = _physicalNetworkDao; - networkService._datacneter_vnet = _dataCenterVnetDao; + networkService._datacneterVnet = _dataCenterVnetDao; networkService._accountGuestVlanMapDao = _accountGuestVlanMapDao; Account account = new AccountVO("testaccount", 1, "networkdomain", (short)0, UUID.randomUUID().toString()); @@ -194,18 +194,18 @@ public class DedicateGuestVlanRangesTest { when(networkService._physicalNetworkDao.findById(anyLong())).thenReturn(physicalNetwork); - when(networkService._datacneter_vnet.listAllocatedVnetsInRange(anyLong(), anyLong(), anyInt(), anyInt())).thenReturn(null); + when(networkService._datacneterVnet.listAllocatedVnetsInRange(anyLong(), anyLong(), anyInt(), anyInt())).thenReturn(null); when(networkService._accountGuestVlanMapDao.listAccountGuestVlanMapsByPhysicalNetwork(anyLong())).thenReturn(null); when(networkService._accountGuestVlanMapDao.persist(any(AccountGuestVlanMapVO.class))).thenReturn(accountGuestVlanMapVO); - when(networkService._datacneter_vnet.update(anyLong(), any(DataCenterVnetVO.class))).thenReturn(true); + when(networkService._datacneterVnet.update(anyLong(), any(DataCenterVnetVO.class))).thenReturn(true); List dataCenterVnetList = new ArrayList(); DataCenterVnetVO dataCenterVnetVO = new DataCenterVnetVO("2-5", 1L, 1L); dataCenterVnetList.add(dataCenterVnetVO); - when(networkService._datacneter_vnet.findVnet(anyLong(), anyString())).thenReturn(dataCenterVnetList); + when(networkService._datacneterVnet.findVnet(anyLong(), anyString())).thenReturn(dataCenterVnetList); try { GuestVlan result = networkService.dedicateGuestVlanRange(dedicateGuestVlanRangesCmd); @@ -274,7 +274,7 @@ public class DedicateGuestVlanRangesTest { DataCenterVnetVO dataCenter = new DataCenterVnetVO("2-5", 1L, 1L); dataCenter.setAccountId(1L); dataCenterList.add(dataCenter); - when(networkService._datacneter_vnet.listAllocatedVnetsInRange(anyLong(), anyLong(), anyInt(), anyInt())).thenReturn(dataCenterList); + when(networkService._datacneterVnet.listAllocatedVnetsInRange(anyLong(), anyLong(), anyInt(), anyInt())).thenReturn(dataCenterList); try { networkService.dedicateGuestVlanRange(dedicateGuestVlanRangesCmd); @@ -297,7 +297,7 @@ public class DedicateGuestVlanRangesTest { when(networkService._physicalNetworkDao.findById(anyLong())).thenReturn(physicalNetwork); - when(networkService._datacneter_vnet.listAllocatedVnetsInRange(anyLong(), anyLong(), anyInt(), anyInt())).thenReturn(null); + when(networkService._datacneterVnet.listAllocatedVnetsInRange(anyLong(), anyLong(), anyInt(), anyInt())).thenReturn(null); List guestVlanMaps = new ArrayList(); AccountGuestVlanMapVO accountGuestVlanMap = new AccountGuestVlanMapVO(1L, 1L); @@ -326,7 +326,7 @@ public class DedicateGuestVlanRangesTest { when(networkService._physicalNetworkDao.findById(anyLong())).thenReturn(physicalNetwork); - when(networkService._datacneter_vnet.listAllocatedVnetsInRange(anyLong(), anyLong(), anyInt(), anyInt())).thenReturn(null); + when(networkService._datacneterVnet.listAllocatedVnetsInRange(anyLong(), anyLong(), anyInt(), anyInt())).thenReturn(null); List guestVlanMaps = new ArrayList(); AccountGuestVlanMapVO accountGuestVlanMap = new AccountGuestVlanMapVO(2L, 1L); @@ -348,7 +348,7 @@ public class DedicateGuestVlanRangesTest { AccountGuestVlanMapVO accountGuestVlanMap = new AccountGuestVlanMapVO(1L, 1L); when(networkService._accountGuestVlanMapDao.findById(anyLong())).thenReturn(accountGuestVlanMap); - doNothing().when(networkService._datacneter_vnet).releaseDedicatedGuestVlans(anyLong()); + doNothing().when(networkService._datacneterVnet).releaseDedicatedGuestVlans(anyLong()); when(networkService._accountGuestVlanMapDao.remove(anyLong())).thenReturn(true); try { diff --git a/server/test/com/cloud/network/MockFirewallManagerImpl.java b/server/test/com/cloud/network/MockFirewallManagerImpl.java index d3d11f1ab4f..3fbbcdf65a6 100644 --- a/server/test/com/cloud/network/MockFirewallManagerImpl.java +++ b/server/test/com/cloud/network/MockFirewallManagerImpl.java @@ -167,7 +167,7 @@ public class MockFirewallManagerImpl extends ManagerBase implements FirewallMana } @Override - public boolean applyIngressFirewallRules(long Ipid, Account caller) throws ResourceUnavailableException { + public boolean applyIngressFirewallRules(long ipId, Account caller) throws ResourceUnavailableException { // TODO Auto-generated method stub return false; } diff --git a/server/test/com/cloud/network/MockNetworkModelImpl.java b/server/test/com/cloud/network/MockNetworkModelImpl.java index 6ae6ae8beef..6c9e597b9f3 100644 --- a/server/test/com/cloud/network/MockNetworkModelImpl.java +++ b/server/test/com/cloud/network/MockNetworkModelImpl.java @@ -92,6 +92,15 @@ public class MockNetworkModelImpl extends ManagerBase implements NetworkModel { return null; } + /* (non-Javadoc) + * @see com.cloud.network.NetworkModel#listPublicIpsAssignedToGuestNtwk(long, long, java.lang.Boolean) + */ + @Override + public List listPublicIpsAssignedToGuestNtwk(long associatedNetworkId, Boolean sourceNat) { + // TODO Auto-generated method stub + return null; + } + /* (non-Javadoc) * @see com.cloud.network.NetworkModel#getSystemAccountNetworkOfferings(java.lang.String[]) */ diff --git a/server/test/com/cloud/network/UpdatePhysicalNetworkTest.java b/server/test/com/cloud/network/UpdatePhysicalNetworkTest.java index 2608371db53..022181e2217 100644 --- a/server/test/com/cloud/network/UpdatePhysicalNetworkTest.java +++ b/server/test/com/cloud/network/UpdatePhysicalNetworkTest.java @@ -38,7 +38,7 @@ import com.cloud.utils.db.TransactionLegacy; public class UpdatePhysicalNetworkTest { private PhysicalNetworkDao _physicalNetworkDao = mock(PhysicalNetworkDao.class); - private DataCenterVnetDao _DatacenterVnetDao = mock(DataCenterVnetDao.class); + private DataCenterVnetDao _datacenterVnetDao = mock(DataCenterVnetDao.class); private DataCenterDao _datacenterDao = mock(DataCenterDao.class); private DataCenterVO datacentervo = mock(DataCenterVO.class); private PhysicalNetworkVO physicalNetworkVO = mock(PhysicalNetworkVO.class); @@ -49,7 +49,7 @@ public class UpdatePhysicalNetworkTest { NetworkServiceImpl networkService = new NetworkServiceImpl(); networkService._dcDao = _datacenterDao; networkService._physicalNetworkDao = _physicalNetworkDao; - networkService._datacneter_vnet = _DatacenterVnetDao; + networkService._datacneterVnet = _datacenterVnetDao; return networkService; } @@ -61,7 +61,7 @@ public class UpdatePhysicalNetworkTest { when(_physicalNetworkDao.findById(anyLong())).thenReturn(physicalNetworkVO); when(_datacenterDao.findById(anyLong())).thenReturn(datacentervo); when(_physicalNetworkDao.update(anyLong(), any(physicalNetworkVO.getClass()))).thenReturn(true); - when(_DatacenterVnetDao.listVnetsByPhysicalNetworkAndDataCenter(anyLong(), anyLong())).thenReturn(existingRange); + when(_datacenterVnetDao.listVnetsByPhysicalNetworkAndDataCenter(anyLong(), anyLong())).thenReturn(existingRange); networkService.updatePhysicalNetwork(1l, null, null, "524-524,525-530", null); txn.close("updatePhysicalNetworkTest"); verify(physicalNetworkVO).setVnet(argumentCaptor.capture()); diff --git a/server/test/com/cloud/network/security/SecurityGroupManagerTestConfiguration.java b/server/test/com/cloud/network/security/SecurityGroupManagerTestConfiguration.java index 81aacdd5b07..a5940cd779a 100644 --- a/server/test/com/cloud/network/security/SecurityGroupManagerTestConfiguration.java +++ b/server/test/com/cloud/network/security/SecurityGroupManagerTestConfiguration.java @@ -71,12 +71,12 @@ import com.cloud.vm.dao.VMInstanceDaoImpl; @Configuration @ComponentScan(basePackageClasses = {SecurityGroupRulesDaoImpl.class, UserVmDaoImpl.class, AccountDaoImpl.class, ConfigurationDaoImpl.class, - SecurityGroupWorkDaoImpl.class, VmRulesetLogDaoImpl.class, VMInstanceDaoImpl.class, DomainDaoImpl.class, UsageEventDaoImpl.class, - ResourceTagsDaoImpl.class, HostDaoImpl.class, HostDetailsDaoImpl.class, HostTagsDaoImpl.class, ClusterDaoImpl.class, HostPodDaoImpl.class, - DataCenterDaoImpl.class, DataCenterIpAddressDaoImpl.class, HostTransferMapDaoImpl.class, SecurityGroupManagerImpl2.class, SecurityGroupDaoImpl.class, - SecurityGroupVMMapDaoImpl.class, UserVmDetailsDaoImpl.class, DataCenterIpAddressDaoImpl.class, DataCenterLinkLocalIpAddressDaoImpl.class, - DataCenterVnetDaoImpl.class, PodVlanDaoImpl.class, DataCenterDetailsDaoImpl.class, SecurityGroupRuleDaoImpl.class, NicDaoImpl.class, - SecurityGroupJoinDaoImpl.class}, + SecurityGroupWorkDaoImpl.class, VmRulesetLogDaoImpl.class, VMInstanceDaoImpl.class, DomainDaoImpl.class, UsageEventDaoImpl.class, + ResourceTagsDaoImpl.class, HostDaoImpl.class, HostDetailsDaoImpl.class, HostTagsDaoImpl.class, ClusterDaoImpl.class, HostPodDaoImpl.class, + DataCenterDaoImpl.class, DataCenterIpAddressDaoImpl.class, HostTransferMapDaoImpl.class, SecurityGroupManagerImpl2.class, SecurityGroupDaoImpl.class, + SecurityGroupVMMapDaoImpl.class, UserVmDetailsDaoImpl.class, DataCenterIpAddressDaoImpl.class, DataCenterLinkLocalIpAddressDaoImpl.class, + DataCenterVnetDaoImpl.class, PodVlanDaoImpl.class, DataCenterDetailsDaoImpl.class, SecurityGroupRuleDaoImpl.class, NicDaoImpl.class, + SecurityGroupJoinDaoImpl.class}, includeFilters = {@Filter(value = Library.class, type = FilterType.CUSTOM)}, useDefaultFilters = false) public class SecurityGroupManagerTestConfiguration { diff --git a/server/test/com/cloud/resource/MockResourceManagerImpl.java b/server/test/com/cloud/resource/MockResourceManagerImpl.java index 70f88b3bd50..5599e8c42b9 100644 --- a/server/test/com/cloud/resource/MockResourceManagerImpl.java +++ b/server/test/com/cloud/resource/MockResourceManagerImpl.java @@ -308,6 +308,15 @@ public class MockResourceManagerImpl extends ManagerBase implements ResourceMana return false; } + /* (non-Javadoc) + * @see com.cloud.resource.ResourceManager#maintain(long) + */ + @Override + public boolean checkAndMaintain(long hostId) { + // TODO Auto-generated method stub + return false; + } + /* (non-Javadoc) * @see com.cloud.resource.ResourceManager#deleteHost(long, boolean, boolean) */ diff --git a/server/test/com/cloud/snapshot/SnapshotDaoTestConfiguration.java b/server/test/com/cloud/snapshot/SnapshotDaoTestConfiguration.java index ffb97b885af..1d6cf4cf5f0 100644 --- a/server/test/com/cloud/snapshot/SnapshotDaoTestConfiguration.java +++ b/server/test/com/cloud/snapshot/SnapshotDaoTestConfiguration.java @@ -43,7 +43,7 @@ import com.cloud.vm.dao.VMInstanceDaoImpl; @Configuration @ComponentScan(basePackageClasses = {SnapshotDaoImpl.class, ResourceTagsDaoImpl.class, VMInstanceDaoImpl.class, VolumeDaoImpl.class, NicDaoImpl.class, HostDaoImpl.class, - HostDetailsDaoImpl.class, HostTagsDaoImpl.class, HostTransferMapDaoImpl.class, ClusterDaoImpl.class, HostPodDaoImpl.class}, + HostDetailsDaoImpl.class, HostTagsDaoImpl.class, HostTransferMapDaoImpl.class, ClusterDaoImpl.class, HostPodDaoImpl.class}, includeFilters = {@Filter(value = SnapshotDaoTestConfiguration.Library.class, type = FilterType.CUSTOM)}, useDefaultFilters = false) public class SnapshotDaoTestConfiguration { diff --git a/server/test/com/cloud/vm/DeploymentPlanningManagerImplTest.java b/server/test/com/cloud/vm/DeploymentPlanningManagerImplTest.java index 0d82ff22c15..751a3bdd43f 100644 --- a/server/test/com/cloud/vm/DeploymentPlanningManagerImplTest.java +++ b/server/test/com/cloud/vm/DeploymentPlanningManagerImplTest.java @@ -168,7 +168,7 @@ public class DeploymentPlanningManagerImplTest { DataCenterDeployment plan = new DataCenterDeployment(dataCenterId); Mockito.when(avoids.shouldAvoid((DataCenterVO)Matchers.anyObject())).thenReturn(true); - DeployDestination dest = _dpm.planDeployment(vmProfile, plan, avoids); + DeployDestination dest = _dpm.planDeployment(vmProfile, plan, avoids, null); assertNull("DataCenter is in avoid set, destination should be null! ", dest); } @@ -183,7 +183,7 @@ public class DeploymentPlanningManagerImplTest { Mockito.when(avoids.shouldAvoid((DataCenterVO)Matchers.anyObject())).thenReturn(false); Mockito.when(_planner.canHandle(vmProfile, plan, avoids)).thenReturn(false); - DeployDestination dest = _dpm.planDeployment(vmProfile, plan, avoids); + DeployDestination dest = _dpm.planDeployment(vmProfile, plan, avoids, null); assertNull("Planner cannot handle, destination should be null! ", dest); } @@ -199,7 +199,7 @@ public class DeploymentPlanningManagerImplTest { Mockito.when(_planner.canHandle(vmProfile, plan, avoids)).thenReturn(true); Mockito.when(((DeploymentClusterPlanner)_planner).orderClusters(vmProfile, plan, avoids)).thenReturn(null); - DeployDestination dest = _dpm.planDeployment(vmProfile, plan, avoids); + DeployDestination dest = _dpm.planDeployment(vmProfile, plan, avoids, null); assertNull("Planner cannot handle, destination should be null! ", dest); } diff --git a/server/test/com/cloud/vm/snapshot/VMSnapshotManagerTest.java b/server/test/com/cloud/vm/snapshot/VMSnapshotManagerTest.java index 352dbeacae4..9d5c2b42ea9 100644 --- a/server/test/com/cloud/vm/snapshot/VMSnapshotManagerTest.java +++ b/server/test/com/cloud/vm/snapshot/VMSnapshotManagerTest.java @@ -106,7 +106,7 @@ public class VMSnapshotManagerTest { HypervisorCapabilitiesDao _hypervisorCapabilitiesDao; int _vmSnapshotMax = 10; - private static long TEST_VM_ID = 3L; + private static final long TEST_VM_ID = 3L; @Mock UserVmVO vmMock; @Mock diff --git a/server/test/com/cloud/vpc/MockNetworkManagerImpl.java b/server/test/com/cloud/vpc/MockNetworkManagerImpl.java index 56ba66aebfc..226788370e6 100644 --- a/server/test/com/cloud/vpc/MockNetworkManagerImpl.java +++ b/server/test/com/cloud/vpc/MockNetworkManagerImpl.java @@ -194,7 +194,7 @@ public class MockNetworkManagerImpl extends ManagerBase implements NetworkOrches * @see com.cloud.network.NetworkService#searchForNetworks(com.cloud.api.commands.ListNetworksCmd) */ @Override - public List searchForNetworks(ListNetworksCmd cmd) { + public Pair, Integer> searchForNetworks(ListNetworksCmd cmd) { // TODO Auto-generated method stub return null; } @@ -203,7 +203,7 @@ public class MockNetworkManagerImpl extends ManagerBase implements NetworkOrches * @see com.cloud.network.NetworkService#deleteNetwork(long) */ @Override - public boolean deleteNetwork(long networkId) { + public boolean deleteNetwork(long networkId, boolean forced) { // TODO Auto-generated method stub return false; } @@ -404,10 +404,10 @@ public class MockNetworkManagerImpl extends ManagerBase implements NetworkOrches } /* (non-Javadoc) - * @see com.cloud.network.NetworkService#addTrafficTypeToPhysicalNetwork(java.lang.Long, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) + * @see com.cloud.network.NetworkService#addTrafficTypeToPhysicalNetwork(java.lang.Long, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ @Override - public PhysicalNetworkTrafficType addTrafficTypeToPhysicalNetwork(Long physicalNetworkId, String trafficType, String xenLabel, String kvmLabel, String vmwareLabel, + public PhysicalNetworkTrafficType addTrafficTypeToPhysicalNetwork(Long physicalNetworkId, String trafficType, String isolationMethod, String xenLabel, String kvmLabel, String vmwareLabel, String simulatorLabel, String vlan, String hypervLabel) { // TODO Auto-generated method stub return null; @@ -597,7 +597,7 @@ public class MockNetworkManagerImpl extends ManagerBase implements NetworkOrches * @see com.cloud.network.NetworkManager#destroyNetwork(long, com.cloud.vm.ReservationContext) */ @Override - public boolean destroyNetwork(long networkId, ReservationContext context) { + public boolean destroyNetwork(long networkId, ReservationContext context, boolean forced) { // TODO Auto-generated method stub return false; } @@ -791,7 +791,7 @@ public class MockNetworkManagerImpl extends ManagerBase implements NetworkOrches } @Override - public NicSecondaryIp allocateSecondaryGuestIP(Account account, long zoneId, Long nicId, Long networkId, String ipaddress) { + public NicSecondaryIp allocateSecondaryGuestIP(long nicId, String ipaddress) { // TODO Auto-generated method stub return null; } @@ -803,7 +803,7 @@ public class MockNetworkManagerImpl extends ManagerBase implements NetworkOrches } @Override - public List listVmNics(Long vmId, Long nicId) { + public List listVmNics(long vmId, Long nicId, Long networkId) { // TODO Auto-generated method stub return null; } @@ -835,6 +835,11 @@ public class MockNetworkManagerImpl extends ManagerBase implements NetworkOrches //To change body of implemented methods use File | Settings | File Templates. } + @Override + public boolean resourceCountNeedsUpdate(NetworkOffering ntwkOff, ACLType aclType) { + return false; //To change body of implemented methods use File | Settings | File Templates. + } + @Override public void prepareNicForMigration(VirtualMachineProfile vm, DeployDestination dest) { // TODO Auto-generated method stub diff --git a/server/test/com/cloud/vpc/MockNetworkModelImpl.java b/server/test/com/cloud/vpc/MockNetworkModelImpl.java index e0583d8d317..67ab8e875cb 100644 --- a/server/test/com/cloud/vpc/MockNetworkModelImpl.java +++ b/server/test/com/cloud/vpc/MockNetworkModelImpl.java @@ -103,6 +103,16 @@ public class MockNetworkModelImpl extends ManagerBase implements NetworkModel { return null; } + /* (non-Javadoc) + * @see com.cloud.network.NetworkModel#listPublicIpsAssignedToGuestNtwk(long, long, java.lang.Boolean) + */ + @Override + public List listPublicIpsAssignedToGuestNtwk(long associatedNetworkId, Boolean sourceNat) { + + // TODO Auto-generated method stub + return null; + } + /* (non-Javadoc) * @see com.cloud.network.NetworkModel#getSystemAccountNetworkOfferings(java.lang.String[]) */ diff --git a/server/test/com/cloud/vpc/MockResourceLimitManagerImpl.java b/server/test/com/cloud/vpc/MockResourceLimitManagerImpl.java index aec82fd5db1..be49abde0b1 100644 --- a/server/test/com/cloud/vpc/MockResourceLimitManagerImpl.java +++ b/server/test/com/cloud/vpc/MockResourceLimitManagerImpl.java @@ -22,7 +22,6 @@ import java.util.Map; import javax.ejb.Local; import javax.naming.ConfigurationException; -import com.cloud.configuration.Resource; import org.springframework.stereotype.Component; import com.cloud.configuration.Resource.ResourceType; diff --git a/server/test/com/cloud/vpc/MockVpcVirtualNetworkApplianceManager.java b/server/test/com/cloud/vpc/MockVpcVirtualNetworkApplianceManager.java index dbb2cc90df5..4802cfff93b 100644 --- a/server/test/com/cloud/vpc/MockVpcVirtualNetworkApplianceManager.java +++ b/server/test/com/cloud/vpc/MockVpcVirtualNetworkApplianceManager.java @@ -79,7 +79,7 @@ public class MockVpcVirtualNetworkApplianceManager extends ManagerBase implement } @Override - public boolean saveSSHPublicKeyToRouter(Network network, NicProfile nic, VirtualMachineProfile profile, List routers, String SSHPublicKey) + public boolean saveSSHPublicKeyToRouter(Network network, NicProfile nic, VirtualMachineProfile profile, List routers, String sshPublicKey) throws ResourceUnavailableException { return false; //To change body of implemented methods use File | Settings | File Templates. } diff --git a/server/test/com/cloud/vpc/NetworkACLManagerTest.java b/server/test/com/cloud/vpc/NetworkACLManagerTest.java index 3e1220d4f97..629afa3873f 100644 --- a/server/test/com/cloud/vpc/NetworkACLManagerTest.java +++ b/server/test/com/cloud/vpc/NetworkACLManagerTest.java @@ -24,7 +24,6 @@ import javax.inject.Inject; import junit.framework.TestCase; -import org.apache.log4j.Logger; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -58,7 +57,11 @@ import com.cloud.network.vpc.NetworkACLItemVO; import com.cloud.network.vpc.NetworkACLManager; import com.cloud.network.vpc.NetworkACLManagerImpl; import com.cloud.network.vpc.NetworkACLVO; +import com.cloud.network.vpc.PrivateGateway; +import com.cloud.network.vpc.VpcGateway; +import com.cloud.network.vpc.VpcGatewayVO; import com.cloud.network.vpc.VpcManager; +import com.cloud.network.vpc.VpcService; import com.cloud.network.vpc.dao.NetworkACLDao; import com.cloud.network.vpc.dao.VpcGatewayDao; import com.cloud.tags.dao.ResourceTagDao; @@ -94,12 +97,14 @@ public class NetworkACLManagerTest extends TestCase { NetworkModel _networkModel; @Inject List _networkAclElements; + @Inject + VpcService _vpcSvc; + @Inject + VpcGatewayDao _vpcGatewayDao; private NetworkACLVO acl; private NetworkACLItemVO aclItem; - private static final Logger s_logger = Logger.getLogger(NetworkACLManagerTest.class); - @Override @Before public void setUp() { @@ -125,6 +130,7 @@ public class NetworkACLManagerTest extends TestCase { } @Test + @SuppressWarnings("unchecked") public void testApplyACL() throws Exception { NetworkVO network = Mockito.mock(NetworkVO.class); Mockito.when(_networkDao.findById(Matchers.anyLong())).thenReturn(network); @@ -134,6 +140,84 @@ public class NetworkACLManagerTest extends TestCase { assertTrue(_aclMgr.applyACLToNetwork(1L)); } + @Test + public void testApplyNetworkACL() throws Exception { + driveTestApplyNetworkACL(true, true, true); + driveTestApplyNetworkACL(false, false, true); + driveTestApplyNetworkACL(false, true, false); + } + + @SuppressWarnings("unchecked") + public void driveTestApplyNetworkACL(boolean result, boolean applyNetworkACLs, boolean applyACLToPrivateGw) throws Exception { + // In order to test ONLY our scope method, we mock the others + NetworkACLManager aclManager = Mockito.spy(_aclMgr); + + // Prepare + // Reset mocked objects to reuse + Mockito.reset(_networkACLItemDao); + + // Make sure it is handled + long aclId = 1L; + NetworkVO network = Mockito.mock(NetworkVO.class); + List networks = new ArrayList(); + networks.add(network); + Mockito.when(_networkDao.listByAclId(Matchers.anyLong())) + .thenReturn(networks); + Mockito.when(_networkDao.findById(Matchers.anyLong())).thenReturn(network); + Mockito.when(_networkModel.isProviderSupportServiceInNetwork(Matchers.anyLong(), + Matchers.any(Network.Service.class), Matchers.any(Network.Provider.class))) + .thenReturn(true); + Mockito.when(_networkAclElements.get(0).applyNetworkACLs(Matchers.any(Network.class), + Matchers.anyList())).thenReturn(applyNetworkACLs); + + // Make sure it applies ACL to private gateway + List vpcGateways = new ArrayList(); + VpcGatewayVO vpcGateway = Mockito.mock(VpcGatewayVO.class); + PrivateGateway privateGateway = Mockito.mock(PrivateGateway.class); + Mockito.when(_vpcSvc.getVpcPrivateGateway(Mockito.anyLong())).thenReturn(privateGateway); + vpcGateways.add(vpcGateway); + Mockito.when(_vpcGatewayDao.listByAclIdAndType(aclId, VpcGateway.Type.Private)) + .thenReturn(vpcGateways); + + // Create 4 rules to test all 4 scenarios: only revoke should + // be deleted, only add should update + List rules = new ArrayList(); + NetworkACLItemVO ruleActive = Mockito.mock(NetworkACLItemVO.class); + NetworkACLItemVO ruleStaged = Mockito.mock(NetworkACLItemVO.class); + NetworkACLItemVO rule2Revoke = Mockito.mock(NetworkACLItemVO.class); + NetworkACLItemVO rule2Add = Mockito.mock(NetworkACLItemVO.class); + Mockito.when(ruleActive.getState()).thenReturn(NetworkACLItem.State.Active); + Mockito.when(ruleStaged.getState()).thenReturn(NetworkACLItem.State.Staged); + Mockito.when(rule2Add.getState()).thenReturn(NetworkACLItem.State.Add); + Mockito.when(rule2Revoke.getState()).thenReturn(NetworkACLItem.State.Revoke); + rules.add(ruleActive); + rules.add(ruleStaged); + rules.add(rule2Add); + rules.add(rule2Revoke); + + long revokeId = 8; + Mockito.when(rule2Revoke.getId()).thenReturn(revokeId); + + long addId = 9; + Mockito.when(rule2Add.getId()).thenReturn(addId); + Mockito.when(_networkACLItemDao.findById(addId)).thenReturn(rule2Add); + + Mockito.when(_networkACLItemDao.listByACL(aclId)) + .thenReturn(rules); + // Mock methods to avoid + Mockito.doReturn(applyACLToPrivateGw).when(aclManager).applyACLToPrivateGw(privateGateway); + + // Execute + assertEquals("Result was not congruent with applyNetworkACLs and applyACLToPrivateGw", result, aclManager.applyNetworkACL(aclId)); + + // Assert if conditions met, network ACL was applied + int timesProcessingDone = (applyNetworkACLs && applyACLToPrivateGw) ? 1 : 0; + Mockito.verify(_networkACLItemDao, Mockito.times(timesProcessingDone)).remove(revokeId); + Mockito.verify(rule2Add, Mockito.times(timesProcessingDone)).setState(NetworkACLItem.State.Active); + Mockito.verify(_networkACLItemDao, Mockito.times(timesProcessingDone)).update(addId, rule2Add); + } + + @Test public void testRevokeACLItem() throws Exception { Mockito.when(_networkACLItemDao.findById(Matchers.anyLong())).thenReturn(aclItem); @@ -220,6 +304,11 @@ public class NetworkACLManagerTest extends TestCase { return Mockito.mock(VpcGatewayDao.class); } + @Bean + public VpcService vpcService() { + return Mockito.mock(VpcService.class); + } + public static class Library implements TypeFilter { @Override public boolean match(MetadataReader mdr, MetadataReaderFactory arg1) throws IOException { diff --git a/server/test/com/cloud/vpc/NetworkACLServiceTest.java b/server/test/com/cloud/vpc/NetworkACLServiceTest.java index aeed99b5092..786789fec77 100644 --- a/server/test/com/cloud/vpc/NetworkACLServiceTest.java +++ b/server/test/com/cloud/vpc/NetworkACLServiceTest.java @@ -20,7 +20,6 @@ import java.util.UUID; import javax.inject.Inject; -import com.cloud.network.vpc.dao.VpcDao; import junit.framework.TestCase; import org.apache.log4j.Logger; @@ -58,8 +57,10 @@ import com.cloud.network.vpc.NetworkACLServiceImpl; import com.cloud.network.vpc.NetworkACLVO; import com.cloud.network.vpc.Vpc; import com.cloud.network.vpc.VpcManager; +import com.cloud.network.vpc.VpcService; import com.cloud.network.vpc.VpcVO; import com.cloud.network.vpc.dao.NetworkACLDao; +import com.cloud.network.vpc.dao.VpcDao; import com.cloud.network.vpc.dao.VpcGatewayDao; import com.cloud.tags.dao.ResourceTagDao; import com.cloud.user.Account; @@ -89,6 +90,8 @@ public class NetworkACLServiceTest extends TestCase { EntityManager _entityMgr; @Inject VpcDao _vpcDao; + @Inject + VpcService _vpcSrv; private CreateNetworkACLCmd createACLItemCmd; private NetworkACLVO acl; @@ -185,7 +188,9 @@ public class NetworkACLServiceTest extends TestCase { @Test public void testDeleteACLItem() throws Exception { Mockito.when(_networkACLItemDao.findById(Matchers.anyLong())).thenReturn(aclItem); + Mockito.when(_networkAclMgr.getNetworkACL(Matchers.anyLong())).thenReturn(acl); Mockito.when(_networkAclMgr.revokeNetworkACLItem(Matchers.anyLong())).thenReturn(true); + Mockito.when(_entityMgr.findById(Mockito.eq(Vpc.class), Mockito.anyLong())).thenReturn(new VpcVO()); assertTrue(_aclService.revokeNetworkACLItem(1L)); } @@ -250,10 +255,15 @@ public class NetworkACLServiceTest extends TestCase { } @Bean - public VpcDao vpcDao () { + public VpcDao vpcDao() { return Mockito.mock(VpcDao.class); } + @Bean + public VpcService vpcService() { + return Mockito.mock(VpcService.class); + } + public static class Library implements TypeFilter { @Override public boolean match(MetadataReader mdr, MetadataReaderFactory arg1) throws IOException { diff --git a/server/test/com/cloud/vpc/VpcTestConfiguration.java b/server/test/com/cloud/vpc/VpcTestConfiguration.java index 94e92128b9d..8777698db86 100644 --- a/server/test/com/cloud/vpc/VpcTestConfiguration.java +++ b/server/test/com/cloud/vpc/VpcTestConfiguration.java @@ -108,20 +108,20 @@ import com.cloud.vpc.dao.MockVpcOfferingServiceMapDaoImpl; @Configuration @ComponentScan(basePackageClasses = {VpcManagerImpl.class, NetworkElement.class, VpcOfferingDao.class, ConfigurationDaoImpl.class, IPAddressDaoImpl.class, - DomainRouterDaoImpl.class, VpcGatewayDaoImpl.class, PrivateIpDaoImpl.class, StaticRouteDaoImpl.class, PhysicalNetworkDaoImpl.class, - ResourceTagsDaoImpl.class, FirewallRulesDaoImpl.class, VlanDaoImpl.class, AccountDaoImpl.class, ResourceCountDaoImpl.class, - Site2SiteVpnGatewayDaoImpl.class, PodVlanMapDaoImpl.class, AccountVlanMapDaoImpl.class, HostDaoImpl.class, HostDetailsDaoImpl.class, - HostTagsDaoImpl.class, HostTransferMapDaoImpl.class, ClusterDaoImpl.class, HostPodDaoImpl.class, RouterNetworkDaoImpl.class, - UserStatisticsDaoImpl.class, PhysicalNetworkTrafficTypeDaoImpl.class, FirewallRulesCidrsDaoImpl.class, ResourceLimitManagerImpl.class, - ResourceLimitDaoImpl.class, ResourceCountDaoImpl.class, DomainDaoImpl.class, UserVmDaoImpl.class, UserVmDetailsDaoImpl.class, NicDaoImpl.class, - SnapshotDaoImpl.class, VMInstanceDaoImpl.class, VolumeDaoImpl.class, UserIpv6AddressDaoImpl.class, NicSecondaryIpDaoImpl.class, - VpcServiceMapDaoImpl.class, ServiceOfferingDaoImpl.class, VMTemplateHostDaoImpl.class, MockVpcDaoImpl.class, VMTemplateDaoImpl.class, - VMTemplateZoneDaoImpl.class, VMTemplateDetailsDaoImpl.class, DataCenterDaoImpl.class, DataCenterIpAddressDaoImpl.class, - DataCenterLinkLocalIpAddressDaoImpl.class, DataCenterVnetDaoImpl.class, PodVlanDaoImpl.class, DataCenterDetailsDaoImpl.class, - MockNetworkManagerImpl.class, MockVpcVirtualNetworkApplianceManager.class, EntityManagerImpl.class, LoadBalancerDaoImpl.class, - FirewallRulesCidrsDaoImpl.class, VirtualRouterProviderDaoImpl.class, ProjectDaoImpl.class, ProjectAccountDaoImpl.class, MockVpcOfferingDaoImpl.class, - MockConfigurationManagerImpl.class, MockNetworkOfferingServiceMapDaoImpl.class, MockNetworkServiceMapDaoImpl.class, - MockVpcOfferingServiceMapDaoImpl.class, MockNetworkOfferingDaoImpl.class, MockNetworkModelImpl.class, Ipv6AddressManagerImpl.class}, + DomainRouterDaoImpl.class, VpcGatewayDaoImpl.class, PrivateIpDaoImpl.class, StaticRouteDaoImpl.class, PhysicalNetworkDaoImpl.class, + ResourceTagsDaoImpl.class, FirewallRulesDaoImpl.class, VlanDaoImpl.class, AccountDaoImpl.class, ResourceCountDaoImpl.class, + Site2SiteVpnGatewayDaoImpl.class, PodVlanMapDaoImpl.class, AccountVlanMapDaoImpl.class, HostDaoImpl.class, HostDetailsDaoImpl.class, + HostTagsDaoImpl.class, HostTransferMapDaoImpl.class, ClusterDaoImpl.class, HostPodDaoImpl.class, RouterNetworkDaoImpl.class, + UserStatisticsDaoImpl.class, PhysicalNetworkTrafficTypeDaoImpl.class, FirewallRulesCidrsDaoImpl.class, ResourceLimitManagerImpl.class, + ResourceLimitDaoImpl.class, ResourceCountDaoImpl.class, DomainDaoImpl.class, UserVmDaoImpl.class, UserVmDetailsDaoImpl.class, NicDaoImpl.class, + SnapshotDaoImpl.class, VMInstanceDaoImpl.class, VolumeDaoImpl.class, UserIpv6AddressDaoImpl.class, NicSecondaryIpDaoImpl.class, + VpcServiceMapDaoImpl.class, ServiceOfferingDaoImpl.class, VMTemplateHostDaoImpl.class, MockVpcDaoImpl.class, VMTemplateDaoImpl.class, + VMTemplateZoneDaoImpl.class, VMTemplateDetailsDaoImpl.class, DataCenterDaoImpl.class, DataCenterIpAddressDaoImpl.class, + DataCenterLinkLocalIpAddressDaoImpl.class, DataCenterVnetDaoImpl.class, PodVlanDaoImpl.class, DataCenterDetailsDaoImpl.class, + MockNetworkManagerImpl.class, MockVpcVirtualNetworkApplianceManager.class, EntityManagerImpl.class, LoadBalancerDaoImpl.class, + FirewallRulesCidrsDaoImpl.class, VirtualRouterProviderDaoImpl.class, ProjectDaoImpl.class, ProjectAccountDaoImpl.class, MockVpcOfferingDaoImpl.class, + MockConfigurationManagerImpl.class, MockNetworkOfferingServiceMapDaoImpl.class, MockNetworkServiceMapDaoImpl.class, + MockVpcOfferingServiceMapDaoImpl.class, MockNetworkOfferingDaoImpl.class, MockNetworkModelImpl.class, Ipv6AddressManagerImpl.class}, includeFilters = {@Filter(value = VpcTestConfiguration.VpcLibrary.class, type = FilterType.CUSTOM)}, useDefaultFilters = false) public class VpcTestConfiguration { diff --git a/server/test/org/apache/cloudstack/networkoffering/ChildTestConfiguration.java b/server/test/org/apache/cloudstack/networkoffering/ChildTestConfiguration.java index 6d93f84e17d..58d02fa1c1d 100644 --- a/server/test/org/apache/cloudstack/networkoffering/ChildTestConfiguration.java +++ b/server/test/org/apache/cloudstack/networkoffering/ChildTestConfiguration.java @@ -122,15 +122,15 @@ import com.cloud.vm.dao.VMInstanceDaoImpl; @Configuration @ComponentScan(basePackageClasses = {AccountVlanMapDaoImpl.class, VolumeDaoImpl.class, HostPodDaoImpl.class, DomainDaoImpl.class, ServiceOfferingDaoImpl.class, - ServiceOfferingDetailsDaoImpl.class, VlanDaoImpl.class, IPAddressDaoImpl.class, ResourceTagsDaoImpl.class, AccountDaoImpl.class, - InstanceGroupDaoImpl.class, UserAccountJoinDaoImpl.class, CapacityDaoImpl.class, SnapshotDaoImpl.class, HostDaoImpl.class, VMInstanceDaoImpl.class, - HostTransferMapDaoImpl.class, PortForwardingRulesDaoImpl.class, PrivateIpDaoImpl.class, UsageEventDaoImpl.class, PodVlanMapDaoImpl.class, - DiskOfferingDaoImpl.class, DataCenterDaoImpl.class, DataCenterIpAddressDaoImpl.class, DataCenterVnetDaoImpl.class, PodVlanDaoImpl.class, - DataCenterDetailsDaoImpl.class, NicSecondaryIpDaoImpl.class, UserIpv6AddressDaoImpl.class, UserDaoImpl.class, NicDaoImpl.class, - NetworkDomainDaoImpl.class, HostDetailsDaoImpl.class, HostTagsDaoImpl.class, ClusterDaoImpl.class, FirewallRulesDaoImpl.class, - FirewallRulesCidrsDaoImpl.class, PhysicalNetworkDaoImpl.class, PhysicalNetworkTrafficTypeDaoImpl.class, PhysicalNetworkServiceProviderDaoImpl.class, - LoadBalancerDaoImpl.class, NetworkServiceMapDaoImpl.class, PrimaryDataStoreDaoImpl.class, StoragePoolDetailsDaoImpl.class, - PortableIpRangeDaoImpl.class, RegionDaoImpl.class, PortableIpDaoImpl.class, AccountGuestVlanMapDaoImpl.class}, + ServiceOfferingDetailsDaoImpl.class, VlanDaoImpl.class, IPAddressDaoImpl.class, ResourceTagsDaoImpl.class, AccountDaoImpl.class, + InstanceGroupDaoImpl.class, UserAccountJoinDaoImpl.class, CapacityDaoImpl.class, SnapshotDaoImpl.class, HostDaoImpl.class, VMInstanceDaoImpl.class, + HostTransferMapDaoImpl.class, PortForwardingRulesDaoImpl.class, PrivateIpDaoImpl.class, UsageEventDaoImpl.class, PodVlanMapDaoImpl.class, + DiskOfferingDaoImpl.class, DataCenterDaoImpl.class, DataCenterIpAddressDaoImpl.class, DataCenterVnetDaoImpl.class, PodVlanDaoImpl.class, + DataCenterDetailsDaoImpl.class, NicSecondaryIpDaoImpl.class, UserIpv6AddressDaoImpl.class, UserDaoImpl.class, NicDaoImpl.class, + NetworkDomainDaoImpl.class, HostDetailsDaoImpl.class, HostTagsDaoImpl.class, ClusterDaoImpl.class, FirewallRulesDaoImpl.class, + FirewallRulesCidrsDaoImpl.class, PhysicalNetworkDaoImpl.class, PhysicalNetworkTrafficTypeDaoImpl.class, PhysicalNetworkServiceProviderDaoImpl.class, + LoadBalancerDaoImpl.class, NetworkServiceMapDaoImpl.class, PrimaryDataStoreDaoImpl.class, StoragePoolDetailsDaoImpl.class, + PortableIpRangeDaoImpl.class, RegionDaoImpl.class, PortableIpDaoImpl.class, AccountGuestVlanMapDaoImpl.class}, includeFilters = {@Filter(value = ChildTestConfiguration.Library.class, type = FilterType.CUSTOM)}, useDefaultFilters = false) public class ChildTestConfiguration { diff --git a/server/test/resources/SecurityGroupManagerTestContext.xml b/server/test/resources/SecurityGroupManagerTestContext.xml index 7ff2976dd6b..3b9a7525948 100644 --- a/server/test/resources/SecurityGroupManagerTestContext.xml +++ b/server/test/resources/SecurityGroupManagerTestContext.xml @@ -1,19 +1,19 @@ - - diff --git a/services/console-proxy-rdp/rdpconsole/README.txt b/services/console-proxy-rdp/rdpconsole/README.txt old mode 100644 new mode 100755 index 15029d43287..546746c22fa --- a/services/console-proxy-rdp/rdpconsole/README.txt +++ b/services/console-proxy-rdp/rdpconsole/README.txt @@ -14,28 +14,38 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -This project contains code for basic VNC and RDP clients. +This project contains code for basic VNC, RDP, and HyperV (RDP) clients. -VNC client can be invoked using following command: +Usage: + java common.Client vnc|rdp|hyperv OPTIONS - mvn exec:java -Dexec.mainClass="common.Client" -Dexec.args="vnc 192.168.0.101 5901 password" +Common options: + --help|-h Show this help text. + --debug-link|-DL Print debugging messages when packets are trasnferred via links. + --debug-element|-DE Print debugging messages when packets are received or sended by elements. + --debug-pipeline|-DP Print debugging messages in pipelines. + --host|-n|--host-name VALUE Name or IP address of host to connect to. Required. + --width|-W VALUE Width of canvas. Default value is "1024". + --height|-H VALUE Height of canvas. Default value is "768". -where - * vnc - name of protcol; - * 192.168.0.101 - IP of VNC server; - * 5901 - port of VNC server screen (5900+display number); - * password - VNC server password. +VNC options: + --port|-p VALUE Port of VNC display server to connect to. Calculate as 5900 + display number, e.g. 5900 for display #0, 5901 for display #1, and so on. Default value is "5901". + --password|-P VALUE Password to use. Required. +RDP options: + --ssl-implementation|-j jre|apr|bco Select SSL engine to use: JRE standard implementation, Apache Portable Runtime native library, BonuncyCastle.org implementation. Default value is "apr". + --port|-p VALUE Port of RDP server to connect to. Default value is "3389". + --domain|-D VALUE NTLM domain to login into. Default value is "Workgroup". + --user|-U VALUE User name to use. Default value is "Administrator". + --password|-P VALUE Password to use. If omitted, then login screen will be shown. -RDP client can be invoked using following command: - - mvn exec:java -Dexec.mainClass="common.Client" -Dexec.args="rdp 192.168.0.101 3389 Administrator" - -where - * rdp - name of protcol; - * 192.168.0.101 - IP of RDP server; - * 3389 - port of RDP server; - * Administrator - user name for loging dialog. +HyperV options: + --ssl-implementation|-j jre|apr|bco Select SSL engine to use: JRE standard implementation, Apache Portable Runtime native library, BonuncyCastle.org implementation. Default value is "apr". + --port|-p VALUE Port of HyperV server to connect to. Default value is "2179". + --instance|-i VALUE HyperV instance ID to use. Required. + --domain|-D VALUE NTLM domain to login into. Default value is "Workgroup". + --user|-U VALUE User name to use. Default value is "Administrator". + --password|-P VALUE Password to use. Required. Limitations of VNC client: diff --git a/services/console-proxy-rdp/rdpconsole/pom.xml b/services/console-proxy-rdp/rdpconsole/pom.xml old mode 100644 new mode 100755 index d25329aa238..05585a1027a --- a/services/console-proxy-rdp/rdpconsole/pom.xml +++ b/services/console-proxy-rdp/rdpconsole/pom.xml @@ -61,11 +61,17 @@ 3.8.1 test
+ org.apache.tomcat.embed tomcat-embed-core 7.0.30 - test + + + + org.bouncycastle + bcprov-jdk16 diff --git a/services/console-proxy-rdp/rdpconsole/rdp-config.bat b/services/console-proxy-rdp/rdpconsole/rdp-config.bat old mode 100644 new mode 100755 index e9510144426..f19b00da958 --- a/services/console-proxy-rdp/rdpconsole/rdp-config.bat +++ b/services/console-proxy-rdp/rdpconsole/rdp-config.bat @@ -16,7 +16,7 @@ rem specific language governing permissions and limitations rem under the License. rem -rem Configure and start RDP service. +rem Configure and start RDP service. Run this script on RDP server. rem rem Turn off firewall diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/AwtKeyEventSource.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/AwtKeyEventSource.java old mode 100644 new mode 100755 diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/AwtMouseEventSource.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/AwtMouseEventSource.java old mode 100644 new mode 100755 diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/BitmapOrder.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/BitmapOrder.java old mode 100644 new mode 100755 index 3a25c8f1cfb..8d643311699 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/common/BitmapOrder.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/common/BitmapOrder.java @@ -40,7 +40,8 @@ public class BitmapOrder extends Order { @Override public String toString() { final int maxLen = 10; - return String.format("BitmapUpdateOrder [rectangles=%s]", rectangles != null ? Arrays.asList(rectangles).subList(0, Math.min(rectangles.length, maxLen)) : null); + return String.format("BitmapUpdateOrder [rectangles=%s]", rectangles != null ? Arrays.asList(rectangles).subList(0, Math.min(rectangles.length, maxLen)) + : null); } } diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/BitmapRectangle.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/BitmapRectangle.java old mode 100644 new mode 100755 index 08dcbf69da7..1685114b2a0 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/common/BitmapRectangle.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/common/BitmapRectangle.java @@ -65,8 +65,10 @@ public class BitmapRectangle { @Override public String toString() { - return String.format("BitmapUpdateRectangle [x=%s, y=%s, width=%s, height=%s, bitsPerPixel=%s, bitmapDataStream=%s]", x, y, width, height, colorDepth, - bitmapDataStream); + return String + .format( + "BitmapUpdateRectangle [x=%s, y=%s, width=%s, height=%s, bitsPerPixel=%s, bitmapDataStream=%s]", + x, y, width, height, colorDepth, bitmapDataStream); } } diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/BufferedImageCanvas.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/BufferedImageCanvas.java old mode 100644 new mode 100755 index 2418de3832f..9cb523137ec --- a/services/console-proxy-rdp/rdpconsole/src/main/java/common/BufferedImageCanvas.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/common/BufferedImageCanvas.java @@ -30,7 +30,7 @@ public class BufferedImageCanvas extends Canvas { private static final long serialVersionUID = 1L; // Offline screen buffer - private BufferedImage offlineImage; + protected BufferedImage offlineImage; // Cached Graphics2D object for offline screen buffer private Graphics2D graphics; @@ -49,7 +49,7 @@ public class BufferedImageCanvas extends Canvas { } public void setCanvasSize(int width, int height) { - this.offlineImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + offlineImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); graphics = offlineImage.createGraphics(); setSize(offlineImage.getWidth(), offlineImage.getHeight()); @@ -76,4 +76,8 @@ public class BufferedImageCanvas extends Canvas { return graphics; } + public void updateFrameBuffer(int x, int y, int w, int h) { + //this method will be used to mark the dirty tiles + } + } diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/BufferedImageCopyRectAdapter.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/BufferedImageCopyRectAdapter.java old mode 100644 new mode 100755 index 28bf640cfbd..804cab71096 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/common/BufferedImageCopyRectAdapter.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/common/BufferedImageCopyRectAdapter.java @@ -81,23 +81,23 @@ public class BufferedImageCopyRectAdapter extends BaseElement { Element renderer = new BufferedImageCopyRectAdapter("renderer", canvas); int[] pixelsBeforeCopy = new int[] { - // 0 - 1, 2, 3, 4, - // 1 - 5, 6, 7, 8, - // 2 - 9, 10, 11, 12, - // 3 - 13, 14, 15, 16}; + // 0 + 1, 2, 3, 4, + // 1 + 5, 6, 7, 8, + // 2 + 9, 10, 11, 12, + // 3 + 13, 14, 15, 16}; int[] pixelsAfterCopy = new int[] { - // 0 - 11, 12, 3, 4, - // 1 - 15, 16, 7, 8, - // 2 - 9, 10, 11, 12, - // 3 - 13, 14, 15, 16}; + // 0 + 11, 12, 3, 4, + // 1 + 15, 16, 7, 8, + // 2 + 9, 10, 11, 12, + // 3 + 13, 14, 15, 16}; // Initalize image int[] data = ((DataBufferInt)canvas.getOfflineImage().getRaster().getDataBuffer()).getData(); diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/BufferedImagePixelsAdapter.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/BufferedImagePixelsAdapter.java old mode 100644 new mode 100755 index e93df3e7add..396bdd47b4c --- a/services/console-proxy-rdp/rdpconsole/src/main/java/common/BufferedImagePixelsAdapter.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/common/BufferedImagePixelsAdapter.java @@ -82,32 +82,32 @@ public class BufferedImagePixelsAdapter extends BaseElement { switch (dataBuf.getDataType()) { - case DataBuffer.TYPE_INT: { + case DataBuffer.TYPE_INT: { - // Convert array of bytes to array of int's - int[] intArray = buf.toIntLEArray(); + // Convert array of bytes to array of int's + int[] intArray = buf.toIntLEArray(); - // We chose RGB888 model, so Raster will use DataBufferInt type - DataBufferInt dataBuffer = (DataBufferInt)dataBuf; + // We chose RGB888 model, so Raster will use DataBufferInt type + DataBufferInt dataBuffer = (DataBufferInt)dataBuf; - int imageWidth = image.getWidth(); - int imageHeight = image.getHeight(); + int imageWidth = image.getWidth(); + int imageHeight = image.getHeight(); - // Paint rectangle directly on buffer, line by line - int[] imageBuffer = dataBuffer.getData(); + // Paint rectangle directly on buffer, line by line + int[] imageBuffer = dataBuffer.getData(); - for (int srcLine = 0, dstLine = y; srcLine < rectHeight && dstLine < imageHeight; srcLine++, dstLine++) { - try { - System.arraycopy(intArray, srcLine * rectWidth, imageBuffer, x + dstLine * imageWidth, rectWidth); - } catch (IndexOutOfBoundsException e) { - } + for (int srcLine = 0, dstLine = y; srcLine < rectHeight && dstLine < imageHeight; srcLine++, dstLine++) { + try { + System.arraycopy(intArray, srcLine * rectWidth, imageBuffer, x + dstLine * imageWidth, rectWidth); + } catch (IndexOutOfBoundsException e) { } - break; } + break; + } - default: - throw new RuntimeException("Unsupported data buffer in buffered image: expected data buffer of type int (DataBufferInt). Actual data buffer type: " + - dataBuf.getClass().getSimpleName()); + default: + throw new RuntimeException("Unsupported data buffer in buffered image: expected data buffer of type int (DataBufferInt). Actual data buffer type: " + + dataBuf.getClass().getSimpleName()); } // Request update of repainted area @@ -123,13 +123,11 @@ public class BufferedImagePixelsAdapter extends BaseElement { Element renderer = new BufferedImagePixelsAdapter("renderer", canvas); - byte[] pixels = - new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, - 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; + byte[] pixels = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, + 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; - int[] pixelsLE = - new int[] {0x04030201, 0x08070605, 0x0c0b0a09, 0x100f0e0d, 0x04030201, 0x08070605, 0x0c0b0a09, 0x100f0e0d, 0x04030201, 0x08070605, 0x0c0b0a09, 0x100f0e0d, - 0x04030201, 0x08070605, 0x0c0b0a09, 0x100f0e0d}; + int[] pixelsLE = new int[] {0x04030201, 0x08070605, 0x0c0b0a09, 0x100f0e0d, 0x04030201, 0x08070605, 0x0c0b0a09, 0x100f0e0d, 0x04030201, 0x08070605, + 0x0c0b0a09, 0x100f0e0d, 0x04030201, 0x08070605, 0x0c0b0a09, 0x100f0e0d}; ByteBuffer buf = new ByteBuffer(pixels); buf.putMetadata(TARGET_X, 0); diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/Client.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/Client.java old mode 100644 new mode 100755 index b6dc4a26023..688693bfd10 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/common/Client.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/common/Client.java @@ -22,46 +22,216 @@ import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.net.InetSocketAddress; +import java.util.Arrays; import rdpclient.RdpClient; import streamer.Element; import streamer.Pipeline; import streamer.PipelineImpl; import streamer.SocketWrapper; +import streamer.SocketWrapperImpl; +import streamer.apr.AprSocketWrapperImpl; +import streamer.bco.BcoSocketWrapperImpl; +import streamer.ssl.SSLState; import vncclient.VncClient; +import common.opt.IntOption; +import common.opt.Option; +import common.opt.OptionParser; +import common.opt.StringEnumerationOption; +import common.opt.StringOption; public class Client { + enum Protocol { + NONE, VNC, RDP, HYPERV + } + + // Common options + private Option help = new Option() { + { + name = "--help"; + alias = "-h"; + description = "Show this help text."; + } + }; + private Option debugLink = new Option() { + { + name = "--debug-link"; + alias = "-DL"; + description = "Print debugging messages when packets are trasnferred via links."; + } + }; + private Option debugElement = new Option() { + { + name = "--debug-element"; + alias = "-DE"; + description = "Print debugging messages when packets are received or sended by elements."; + } + }; + private Option debugPipeline = new Option() { + { + name = "--debug-pipeline"; + alias = "-DP"; + description = "Print debugging messages in pipelines."; + } + }; + + private StringOption hostName = new StringOption() { + { + name = "--host"; + alias = "-n"; + aliases = new String[] {"--host-name"}; + required = true; + description = "Name or IP address of host to connect to."; + } + }; + private IntOption canvasWidth = new IntOption() { + { + name = "--width"; + alias = "-W"; + value = 1024; + description = "Width of canvas."; + } + }; + + private IntOption canvasHeight = new IntOption() { + { + name = "--height"; + alias = "-H"; + value = 768; + description = "Height of canvas."; + } + }; + + // Protocol specific options + + private IntOption vncPort = new IntOption() { + { + name = "--port"; + alias = "-p"; + value = 5901; + description = "Port of VNC display server to connect to. Calculate as 5900 + display number, e.g. 5900 for display #0, 5901 for display #1, and so on."; + } + }; + + private IntOption rdpPort = new IntOption() { + { + name = "--port"; + alias = "-p"; + value = 3389; + description = "Port of RDP server to connect to."; + } + }; + + private IntOption hyperVPort = new IntOption() { + { + name = "--port"; + alias = "-p"; + value = 2179; + description = "Port of HyperV server to connect to."; + } + }; + + private StringOption password = new StringOption() { + { + name = "--password"; + alias = "-P"; + required = true; + description = "Password to use."; + } + }; + + private StringOption rdpPassword = new StringOption() { + { + name = "--password"; + alias = "-P"; + required = false; + description = "Password to use. If omitted, then login screen will be shown."; + } + }; + + private StringOption userName = new StringOption() { + { + name = "--user"; + alias = "-U"; + value = "Administrator"; + description = "User name to use."; + } + }; + + private StringOption domain = new StringOption() { + { + name = "--domain"; + alias = "-D"; + value = "Workgroup"; + description = "NTLM domain to login into."; + } + }; + + private StringOption hyperVInstanceId = new StringOption() { + { + name = "--instance"; + alias = "-i"; + required = true; + description = "HyperV instance ID to use."; + } + }; + private StringEnumerationOption sslImplementation = new StringEnumerationOption() { + { + name = "--ssl-implementation"; + alias = "-j"; + value = "apr"; + choices = new String[] {"jre", "apr", "bco"}; + description = "Select SSL engine to use: JRE standard implementation, Apache Portable Runtime native library, BonuncyCastle.org implementation."; + } + }; + + private final Option[] commonOptions = new Option[] {help, debugLink, debugElement, debugPipeline, hostName, canvasWidth, canvasHeight}; + private final Option[] vncOptions = new Option[] {vncPort, password}; + private final Option[] rdpOptions = new Option[] {sslImplementation, rdpPort, domain, userName, rdpPassword}; + private final Option[] hyperVOptions = new Option[] {sslImplementation, hyperVPort, hyperVInstanceId, domain, userName, password}; + private static Frame frame; private static SocketWrapper socket; private static ScrollPane scroller; private static ScreenDescription screen; private static BufferedImageCanvas canvas; - public static void main(String args[]) { - // System.setProperty("streamer.Link.debug", "true"); - // System.setProperty("streamer.Element.debug", "true"); - // System.setProperty("streamer.Pipeline.debug", "true"); + private void help() { + System.out.println("Usage: \n java common.Client vnc|rdp|hyperv OPTIONS\n"); + System.out.println(Option.toHelp("Common options", commonOptions)); + System.out.println(Option.toHelp("VNC options", vncOptions)); + System.out.println(Option.toHelp("RDP options", rdpOptions)); + System.out.println(Option.toHelp("HyperV options", hyperVOptions)); + } + + public void runClient(String[] args) { try { - if (args.length < 4) { - System.out.println("Usage: \n java common.Client vnc IP PORT PASSWORD\n java common.Client rdp IP PORT username\n"); - System.exit(0); - } - String connectionType = args[0]; - String hostname = args[1]; - int port = Integer.parseInt(args[2]); - String userNameOrPassword = args[3]; + Protocol protocol = parseOptions(args); + if (protocol == Protocol.NONE) + return; - // Create address from arguments - InetSocketAddress address = new InetSocketAddress(hostname, port); + System.setProperty("streamer.Link.debug", "" + debugLink.used); + System.setProperty("streamer.Element.debug", "" + debugElement.used); + System.setProperty("streamer.Pipeline.debug", "" + debugPipeline.used); + + SSLState sslState = new SSLState(); // Create socket wrapper - socket = new SocketWrapper("socket"); + if ("jre".equals(sslImplementation.value)) { + socket = new SocketWrapperImpl("socket", sslState); + } else if ("apr".equals(sslImplementation.value)) { + socket = new AprSocketWrapperImpl("socket", sslState); + } else if ("bco".equals(sslImplementation.value)) { + socket = new BcoSocketWrapperImpl("socket", sslState); + } else { + throw new RuntimeException("Unexpected option value: \"" + sslImplementation.value + "\". " + sslImplementation.help()); + } screen = new ScreenDescription(); - canvas = new BufferedImageCanvas(1024, 768); + canvas = new BufferedImageCanvas(canvasWidth.value, canvasHeight.value); screen.addSizeChangeListener(new SizeChangeListener() { @Override public void sizeChanged(int width, int height) { @@ -74,13 +244,24 @@ public class Client { }); // Assemble pipeline + InetSocketAddress address; Element main; - if ("vnc".equals(connectionType)) { - main = new VncClient("client", userNameOrPassword, screen, canvas); - } else if ("rdp".equals(connectionType)) { - main = new RdpClient("client", userNameOrPassword, screen, canvas); - } else { - throw new RuntimeException("Unknown connection type. Expected value: \"vnc\" or \"rdp\", actual value: \"" + connectionType + "\"."); + switch (protocol) { + case VNC: + address = new InetSocketAddress(hostName.value, vncPort.value); + main = new VncClient("client", password.value, screen, canvas); + break; + case RDP: + address = new InetSocketAddress(hostName.value, rdpPort.value); + main = new RdpClient("client", hostName.value, domain.value, userName.value, rdpPassword.value, null, screen, canvas, sslState); + break; + case HYPERV: + address = new InetSocketAddress(hostName.value, hyperVPort.value); + main = new RdpClient("client", hostName.value, domain.value, userName.value, password.value, hyperVInstanceId.value, screen, canvas, sslState); + break; + default: + address = null; + main = null; } Pipeline pipeline = new PipelineImpl("Client"); @@ -89,7 +270,7 @@ public class Client { pipeline.validate(); - frame = createVncClientMainWindow(canvas, "VNC", new WindowAdapter() { + frame = createVncClientMainWindow(canvas, protocol.toString() + " " + hostName.value, new WindowAdapter() { @Override public void windowClosing(WindowEvent evt) { shutdown(); @@ -108,6 +289,41 @@ public class Client { } } + private Protocol parseOptions(String[] args) { + String protocolName = (args.length > 0) ? args[0] : ""; + Protocol protocol = Protocol.NONE; + + Option[] options; + if (protocolName.equals("vnc")) { + protocol = Protocol.VNC; + options = join(commonOptions, vncOptions); + } else if (protocolName.equals("rdp")) { + protocol = Protocol.RDP; + options = join(commonOptions, rdpOptions); + } else if (protocolName.equals("hyperv")) { + protocol = Protocol.HYPERV; + options = join(commonOptions, hyperVOptions); + } else { + help(); + return Protocol.NONE; + } + + // Parse all options for given protocol + String[] arguments = OptionParser.parseOptions(args, 1, options); + + if (arguments.length > 0) { + System.err.println("[Client] ERROR: Arguments are not allowed here. Check command syntax. Extra arguments: \"" + Arrays.toString(arguments) + "\"."); + help(); + return Protocol.NONE; + } + + if (help.used) { + help(); + return Protocol.NONE; + } + return protocol; + } + protected static void shutdown() { if (frame != null) { frame.setVisible(false); @@ -135,4 +351,25 @@ public class Client { return frame; } + /** + * Join two arrays with options and return new array. + */ + private Option[] join(Option[] a1, Option[] a2) { + // Extend first array + Option[] result = Arrays.copyOf(a1, a1.length + a2.length); + + // Append second array to first + for (int i = 0, p = a1.length; i < a2.length; i++, p++) + result[p] = a2[i]; + + return result; + } + + public static void main(String args[]) { + // *DEBUG*/System.setProperty("javax.net.debug", "ssl"); + // * DEBUG */System.setProperty("javax.net.debug", "ssl:record:packet"); + + new Client().runClient(args); + } + } diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/CopyRectOrder.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/CopyRectOrder.java old mode 100644 new mode 100755 diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/KeyOrder.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/KeyOrder.java old mode 100644 new mode 100755 diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/MouseOrder.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/MouseOrder.java old mode 100644 new mode 100755 diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/OrderType.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/OrderType.java old mode 100644 new mode 100755 diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/ScreenDescription.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/ScreenDescription.java old mode 100644 new mode 100755 index a9155e8dee0..1c33a63cb61 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/common/ScreenDescription.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/common/ScreenDescription.java @@ -56,12 +56,12 @@ public class ScreenDescription { * Store information about server pixel format. */ public void setPixelFormat(int bitsPerPixel, int depth, boolean bigEndianFlag, boolean trueColorFlag, int redMax, int greenMax, int blueMax, int redShift, - int greenShift, int blueShift) { + int greenShift, int blueShift) { - this.bytesPerPixel = (bitsPerPixel + 7) / 8; + bytesPerPixel = (bitsPerPixel + 7) / 8; this.bitsPerPixel = bitsPerPixel; - this.colorDepth = depth; + colorDepth = depth; this.bigEndianFlag = bigEndianFlag; this.trueColorFlag = trueColorFlag; @@ -79,23 +79,23 @@ public class ScreenDescription { public void setPixelFormatRGBTrueColor(int bitsPerPixel) { switch (bitsPerPixel) { - case 8: - setPixelFormat(8, 8, false, false, -1, -1, -1, -1, -1, -1); - break; - case 15: - setPixelFormat(16, 15, false, true, 31, 31, 31, 0, 5, 10); - break; - case 16: - setPixelFormat(16, 16, false, true, 31, 63, 31, 0, 5, 11); - break; - case 24: - setPixelFormat(24, 24, false, true, 255, 255, 255, 0, 8, 16); - break; - case 32: - setPixelFormat(32, 24, false, true, 255, 255, 255, 0, 8, 16); - break; - default: - throw new RuntimeException("Unknown color depth."); + case 8: + setPixelFormat(8, 8, false, false, -1, -1, -1, -1, -1, -1); + break; + case 15: + setPixelFormat(16, 15, false, true, 31, 31, 31, 0, 5, 10); + break; + case 16: + setPixelFormat(16, 16, false, true, 31, 63, 31, 0, 5, 11); + break; + case 24: + setPixelFormat(24, 24, false, true, 255, 255, 255, 0, 8, 16); + break; + case 32: + setPixelFormat(32, 24, false, true, 255, 255, 255, 0, 8, 16); + break; + default: + throw new RuntimeException("Unknown color depth."); } } @@ -107,8 +107,8 @@ public class ScreenDescription { if (height <= 0 || width <= 0) throw new RuntimeException("Incorrect framebuffer size: " + width + "x" + height + "."); - this.framebufferWidth = width; - this.framebufferHeight = height; + framebufferWidth = width; + framebufferHeight = height; callSizeChangeListeners(width, height); } @@ -145,16 +145,16 @@ public class ScreenDescription { } public boolean isRGB888_32_LE() { - return (colorDepth == 24 && bitsPerPixel == 32 && redShift == 0 && greenShift == 8 && blueShift == 16 && redMax == 255 && greenMax == 255 && blueMax == 255 && - !bigEndianFlag && trueColorFlag); + return (colorDepth == 24 && bitsPerPixel == 32 && redShift == 0 && greenShift == 8 && blueShift == 16 && redMax == 255 && greenMax == 255 && blueMax == 255 + && !bigEndianFlag && trueColorFlag); } @Override public String toString() { - return "ScreenDescription [framebufferWidth=" + framebufferWidth + ", framebufferHeight=" + framebufferHeight + ", desktopName=" + desktopName + - ", bytesPerPixel=" + bytesPerPixel + ", depth=" + colorDepth + ", bitsPerPixel=" + bitsPerPixel + ", redShift=" + redShift + ", greenShift=" + greenShift + - ", blueShift=" + blueShift + ", redMax=" + redMax + ", greenMax=" + greenMax + ", blueMax=" + blueMax + ", bigEndianFlag=" + bigEndianFlag + - ", trueColorFlag=" + trueColorFlag + "]"; + return "ScreenDescription [framebufferWidth=" + framebufferWidth + ", framebufferHeight=" + framebufferHeight + ", desktopName=" + desktopName + + ", bytesPerPixel=" + bytesPerPixel + ", depth=" + colorDepth + ", bitsPerPixel=" + bitsPerPixel + ", redShift=" + redShift + ", greenShift=" + greenShift + + ", blueShift=" + blueShift + ", redMax=" + redMax + ", greenMax=" + greenMax + ", blueMax=" + blueMax + ", bigEndianFlag=" + bigEndianFlag + + ", trueColorFlag=" + trueColorFlag + "]"; } public void addSizeChangeListener(SizeChangeListener sizeChangeListener) { diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/SizeChangeListener.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/SizeChangeListener.java old mode 100644 new mode 100755 diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/AwtBellAdapter.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/adapter/AwtBellAdapter.java old mode 100644 new mode 100755 similarity index 92% rename from services/console-proxy-rdp/rdpconsole/src/main/java/common/AwtBellAdapter.java rename to services/console-proxy-rdp/rdpconsole/src/main/java/common/adapter/AwtBellAdapter.java index 5970abb21a9..c25b07f19c6 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/common/AwtBellAdapter.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/common/adapter/AwtBellAdapter.java @@ -14,17 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package common; +package common.adapter; import java.awt.Toolkit; import streamer.BaseElement; import streamer.ByteBuffer; import streamer.Element; -import streamer.FakeSource; import streamer.Link; import streamer.Pipeline; import streamer.PipelineImpl; +import streamer.debug.FakeSource; public class AwtBellAdapter extends BaseElement { @@ -61,9 +61,9 @@ public class AwtBellAdapter extends BaseElement { Element source = new FakeSource("source") { { - this.incommingBufLength = 0; - this.delay = 1000; - this.numBuffers = 3; + incommingBufLength = 0; + delay = 1000; + numBuffers = 3; } }; diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/AwtCanvasAdapter.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/adapter/AwtCanvasAdapter.java old mode 100644 new mode 100755 similarity index 61% rename from services/console-proxy-rdp/rdpconsole/src/main/java/common/AwtCanvasAdapter.java rename to services/console-proxy-rdp/rdpconsole/src/main/java/common/adapter/AwtCanvasAdapter.java index 8adee499cb6..f3a73d70dbd --- a/services/console-proxy-rdp/rdpconsole/src/main/java/common/AwtCanvasAdapter.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/common/adapter/AwtCanvasAdapter.java @@ -14,13 +14,13 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package common; +package common.adapter; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.awt.image.WritableRaster; -import rdpclient.ServerBitmapUpdate; +import rdpclient.rdp.ServerBitmapUpdate; import streamer.BaseElement; import streamer.ByteBuffer; import streamer.Element; @@ -28,6 +28,12 @@ import streamer.Link; import streamer.Order; import streamer.Pipeline; import streamer.PipelineImpl; +import common.BitmapOrder; +import common.BitmapRectangle; +import common.BufferedImageCanvas; +import common.CopyRectOrder; +import common.OrderType; +import common.ScreenDescription; public class AwtCanvasAdapter extends BaseElement { @@ -54,30 +60,31 @@ public class AwtCanvasAdapter extends BaseElement { Order order = buf.getOrder(); switch ((OrderType)order.type) { - case BITMAP_UPDATE: - handleBitmap((BitmapOrder)order, buf); - break; + case BITMAP_UPDATE: + handleBitmap((BitmapOrder)order, buf); + break; - case COPY_RECT: - handleCopyRect((CopyRectOrder)order, buf); - break; + case COPY_RECT: + handleCopyRect((CopyRectOrder)order, buf); + break; - default: - throw new RuntimeException("Order is not implemented: " + buf + "."); - // break; + default: + throw new RuntimeException("Order is not implemented: " + buf + "."); + // break; } buf.unref(); } private void handleCopyRect(CopyRectOrder order, ByteBuffer buf) { - // TODO Auto-generated method stub // Copy image canvas.getOfflineGraphics().copyArea(order.srcX, order.srcY, order.width, order.height, order.x - order.srcX, order.y - order.srcY); // Request update of repainted area + canvas.updateFrameBuffer(order.x, order.y, order.width, order.height); canvas.repaint(order.x, order.y, order.width, order.height); + } private void handleBitmap(BitmapOrder order, ByteBuffer buf) { @@ -98,39 +105,40 @@ public class AwtCanvasAdapter extends BaseElement { BufferedImage rectImage; switch (rectangle.colorDepth) { - case 8: { - rectImage = new BufferedImage(bufferWidth, height, BufferedImage.TYPE_BYTE_INDEXED, screen.colorMap); - WritableRaster raster = rectImage.getRaster(); - raster.setDataElements(0, 0, bufferWidth, bufferHeight, rectangle.bitmapDataStream.toByteArray()); - break; - } - case 15: { - rectImage = new BufferedImage(bufferWidth, height, BufferedImage.TYPE_USHORT_555_RGB); - WritableRaster raster = rectImage.getRaster(); - raster.setDataElements(0, 0, bufferWidth, bufferHeight, rectangle.bitmapDataStream.toShortArray()); - break; - } - case 16: { - rectImage = new BufferedImage(bufferWidth, height, BufferedImage.TYPE_USHORT_565_RGB); - WritableRaster raster = rectImage.getRaster(); - raster.setDataElements(0, 0, bufferWidth, bufferHeight, rectangle.bitmapDataStream.toShortArray()); - break; - } - case 24: - case 32: { - rectImage = new BufferedImage(bufferWidth, height, BufferedImage.TYPE_INT_RGB); - WritableRaster raster = rectImage.getRaster(); - raster.setDataElements(0, 0, bufferWidth, bufferHeight, rectangle.bitmapDataStream.toIntLEArray()); - break; - } - default: - throw new RuntimeException("Unsupported color depth: " + rectangle.colorDepth + "."); + case 8: { + rectImage = new BufferedImage(bufferWidth, height, BufferedImage.TYPE_BYTE_INDEXED, screen.colorMap); + WritableRaster raster = rectImage.getRaster(); + raster.setDataElements(0, 0, bufferWidth, bufferHeight, rectangle.bitmapDataStream.toByteArray()); + break; + } + case 15: { + rectImage = new BufferedImage(bufferWidth, height, BufferedImage.TYPE_USHORT_555_RGB); + WritableRaster raster = rectImage.getRaster(); + raster.setDataElements(0, 0, bufferWidth, bufferHeight, rectangle.bitmapDataStream.toShortArray()); + break; + } + case 16: { + rectImage = new BufferedImage(bufferWidth, height, BufferedImage.TYPE_USHORT_565_RGB); + WritableRaster raster = rectImage.getRaster(); + raster.setDataElements(0, 0, bufferWidth, bufferHeight, rectangle.bitmapDataStream.toShortArray()); + break; + } + case 24: + case 32: { + rectImage = new BufferedImage(bufferWidth, height, BufferedImage.TYPE_INT_RGB); + WritableRaster raster = rectImage.getRaster(); + raster.setDataElements(0, 0, bufferWidth, bufferHeight, rectangle.bitmapDataStream.toIntLEArray()); + break; + } + default: + throw new RuntimeException("Unsupported color depth: " + rectangle.colorDepth + "."); } g.setClip(x, y, width, height); g.drawImage(rectImage, x, y, null); // Request update of repainted area + canvas.updateFrameBuffer(x, y, width, height); canvas.repaint(x, y, width, height); } @@ -143,9 +151,8 @@ public class AwtCanvasAdapter extends BaseElement { // System.setProperty("streamer.Link.debug", "true"); // System.setProperty("streamer.Element.debug", "true"); // System.setProperty("streamer.Pipeline.debug", "true"); - ByteBuffer packet = - new ByteBuffer(new byte[] {0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x10, 0x00, 0x01, 0x00, 0x10, 0x00, 0x01, 0x04, 0x0a, - 0x00, 0x0c, (byte)0x84, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}); + ByteBuffer packet = new ByteBuffer(new byte[] {0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x10, 0x00, 0x01, 0x00, 0x10, 0x00, + 0x01, 0x04, 0x0a, 0x00, 0x0c, (byte)0x84, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}); Pipeline pipeline = new PipelineImpl("test"); diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/AwtClipboardAdapter.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/adapter/AwtClipboardAdapter.java old mode 100644 new mode 100755 similarity index 88% rename from services/console-proxy-rdp/rdpconsole/src/main/java/common/AwtClipboardAdapter.java rename to services/console-proxy-rdp/rdpconsole/src/main/java/common/adapter/AwtClipboardAdapter.java index 75dc1b91122..cc7f33071e3 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/common/AwtClipboardAdapter.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/common/adapter/AwtClipboardAdapter.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package common; +package common.adapter; import java.awt.Toolkit; import java.awt.datatransfer.StringSelection; @@ -22,10 +22,11 @@ import java.awt.datatransfer.StringSelection; import streamer.BaseElement; import streamer.ByteBuffer; import streamer.Link; -import vncclient.VncMessageHandler; public class AwtClipboardAdapter extends BaseElement { + public static final String CLIPBOARD_CONTENT = "content"; + public AwtClipboardAdapter(String id) { super(id); declarePads(); @@ -43,14 +44,14 @@ public class AwtClipboardAdapter extends BaseElement { if (buf == null) return; - String content = (String)buf.getMetadata(VncMessageHandler.CLIPBOARD_CONTENT); + String content = (String)buf.getMetadata(CLIPBOARD_CONTENT); StringSelection contents = new StringSelection(content); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(contents, null); } @Override public String toString() { - return "Clipboard(" + id + ")"; + return "ClipboardAdapter(" + id + ")"; } } diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/asn1/Any.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/asn1/Any.java new file mode 100755 index 00000000000..2ef7c69d457 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/common/asn1/Any.java @@ -0,0 +1,78 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package common.asn1; + +import streamer.ByteBuffer; + +/** + * Any type. Don't forget to set type. + */ +public class Any extends Tag { + + /** + * Raw bytes of any value. + */ + public ByteBuffer value; + + public Any(String name) { + super(name); + } + + @Override + public boolean isValueSet() { + return value != null; + } + + @Override + public long calculateLengthOfValuePayload() { + return value.length; + } + + @Override + public void writeTagValuePayload(ByteBuffer buf) { + buf.writeBytes(value); + } + + @Override + public void readTagValue(ByteBuffer buf, BerType typeAndFlags) { + long length = buf.readBerLength(); + + value = buf.readBytes((int)length); + } + + @Override + public Tag deepCopy(String suffix) { + return new Any(name + suffix).copyFrom(this); + } + + @Override + public Tag copyFrom(Tag tag) { + super.copyFrom(tag); + tagType = tag.tagType; + value = new ByteBuffer(((Any)tag).value.toByteArray()); + return this; + } + + @Override + public boolean isTypeValid(BerType typeAndFlags, boolean explicit) { + if (explicit) + return typeAndFlags.tagClass == tagClass && typeAndFlags.constructed && typeAndFlags.typeOrTagNumber == tagNumber; + else + return true; + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/asn1/Asn1Constants.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/asn1/Asn1Constants.java new file mode 100755 index 00000000000..6dacd60272b --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/common/asn1/Asn1Constants.java @@ -0,0 +1,83 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package common.asn1; + +public interface Asn1Constants { + + /** + * Universal class type. + */ + public static final int UNIVERSAL_CLASS = 0x00; + + /** + * Application class type. + */ + public static final int APPLICATION_CLASS = 0x40; + + public static final int CONTEXT_CLASS = 0x80; + + public static final int PRIVATE_CLASS = 0xC0; + + /** + * Constructed type. + */ + public static final int CONSTRUCTED = 0x20; + + /** + * Mask to extract class. + */ + public static final int CLASS_MASK = 0xC0; + + /** + * Mask to extract type. + */ + public static final int TYPE_MASK = 0x1F; + + public static final int EOF = 0x00; + public static final int BOOLEAN = 0x01; + /** + * Integer primitive. + */ + public static final int INTEGER = 0x02; + public static final int BIT_STRING = 0x03; + /** + * Octet string primitive. + */ + public static final int OCTET_STRING = 0x04; + public static final int NULL = 0x05; + public static final int OBJECT_ID = 0x06; + public static final int REAL = 0x09; + public static final int ENUMERATED = 0x0A; + /** + * Sequence primitive. + */ + public static final int SEQUENCE = 0x10; + public static final int SET = 0x11; + public static final int NUMERIC_STRING = 0x12; + public static final int PRINTABLE_STRING = 0x13; + public static final int TELETEX_STRING = 0x14; + public static final int VIDEOTEXT_STRING = 0x15; + public static final int IA5_STRING = 0x16; + public static final int UTCTIME = 0x17; + public static final int GENERAL_TIME = 0x18; + public static final int GRAPHIC_STRING = 0x19; + public static final int VISIBLE_STRING = 0x1A; + public static final int GENERAL_STRING = 0x1B; + + public static final int EXTENDED_TYPE = 0x1F; + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/asn1/Asn1Integer.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/asn1/Asn1Integer.java new file mode 100755 index 00000000000..678e04eb131 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/common/asn1/Asn1Integer.java @@ -0,0 +1,116 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package common.asn1; + +import streamer.ByteBuffer; + +/** + * Variable length integer. + */ +public class Asn1Integer extends Tag { + + public Long value = null; + + public Asn1Integer(String name) { + super(name); + tagType = INTEGER; + } + + @Override + public void readTagValue(ByteBuffer buf, BerType typeAndFlags) { + // Type is already read by parent parser + + long length = buf.readBerLength(); + if (length > 8) + throw new RuntimeException("[" + this + "] ERROR: Integer value is too long: " + length + " bytes. Cannot handle integers more than 8 bytes long. Data: " + + buf + "."); + + value = buf.readSignedVarInt((int)length); + } + + @Override + public Tag deepCopy(String suffix) { + return new Asn1Integer(name + suffix).copyFrom(this); + } + + @Override + public Tag copyFrom(Tag tag) { + super.copyFrom(tag); + value = ((Asn1Integer)tag).value; + return this; + } + + @Override + public String toString() { + return super.toString() + "= " + value; + } + + @Override + public long calculateLengthOfValuePayload() { + if (value <= 0xff) + return 1; + if (value <= 0xffFF) + return 2; + if (value <= 0xffFFff) + return 3; + if (value <= 0xffFFffFFL) + return 4; + if (value <= 0xffFFffFFffL) + return 5; + if (value <= 0xffFFffFFffFFL) + return 6; + if (value <= 0xffFFffFFffFFffL) + return 7; + + return 8; + } + + @Override + public void writeTagValuePayload(ByteBuffer buf) { + long value = this.value.longValue(); + + if (value < 0xff) { + buf.writeByte((int)value); + } else if (value <= 0xffFF) { + buf.writeShort((int)value); + } else if (value <= 0xffFFff) { + buf.writeByte((int)(value >> 16)); + buf.writeShort((int)value); + } else if (value <= 0xffFFffFFL) { + buf.writeInt((int)value); + } else if (value <= 0xffFFffFFffL) { + buf.writeByte((int)(value >> 32)); + buf.writeInt((int)value); + } else if (value <= 0xffFFffFFffFFL) { + buf.writeShort((int)(value >> 32)); + buf.writeInt((int)value); + } else if (value <= 0xffFFffFFffFFffL) { + buf.writeByte((int)(value >> (32 + 16))); + buf.writeShort((int)(value >> 32)); + buf.writeInt((int)value); + } else { + buf.writeInt((int)(value >> 32)); + buf.writeInt((int)value); + } + } + + @Override + public boolean isValueSet() { + return value != null; + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/asn1/BerType.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/asn1/BerType.java new file mode 100755 index 00000000000..8e53f249568 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/common/asn1/BerType.java @@ -0,0 +1,40 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package common.asn1; + +public class BerType { + + public int tagClass; + public boolean constructed; + public int typeOrTagNumber; + + public BerType() { + } + + public BerType(int tagClass, boolean constructed, int typeOrTagNumber) { + this.tagClass = tagClass; + this.constructed = constructed; + this.typeOrTagNumber = typeOrTagNumber; + } + + @Override + public String toString() { + return "BerType [tagClass=" + Tag.tagClassToString(tagClass) + ", constructed=" + constructed + ", type or tag number=" + + Tag.tagTypeOrNumberToString(tagClass, typeOrTagNumber) + "]"; + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/asn1/BitString.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/asn1/BitString.java new file mode 100755 index 00000000000..3323c727744 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/common/asn1/BitString.java @@ -0,0 +1,67 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package common.asn1; + +import streamer.ByteBuffer; + +public class BitString extends Tag { + + /** + * Bit string value. + */ + public ByteBuffer value; + + public BitString(String name) { + super(name); + tagType = BIT_STRING; + } + + @Override + public boolean isValueSet() { + return value != null; + } + + @Override + public long calculateLengthOfValuePayload() { + return value.length; + } + + @Override + public void writeTagValuePayload(ByteBuffer buf) { + buf.writeBytes(value); + } + + @Override + public void readTagValue(ByteBuffer buf, BerType typeAndFlags) { + long length = buf.readBerLength(); + + value = buf.readBytes((int)length); + } + + @Override + public Tag deepCopy(String suffix) { + return new BitString(name + suffix).copyFrom(this); + } + + @Override + public Tag copyFrom(Tag tag) { + super.copyFrom(tag); + value = new ByteBuffer(((BitString)tag).value.toByteArray()); + return this; + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/asn1/ObjectID.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/asn1/ObjectID.java new file mode 100755 index 00000000000..c112cd0b992 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/common/asn1/ObjectID.java @@ -0,0 +1,67 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package common.asn1; + +import streamer.ByteBuffer; + +public class ObjectID extends Tag { + + /** + * Raw bytes of encoded OID. + */ + public ByteBuffer value; + + public ObjectID(String name) { + super(name); + tagType = OBJECT_ID; + } + + @Override + public boolean isValueSet() { + return value != null; + } + + @Override + public long calculateLengthOfValuePayload() { + return value.length; + } + + @Override + public void writeTagValuePayload(ByteBuffer buf) { + buf.writeBytes(value); + } + + @Override + public void readTagValue(ByteBuffer buf, BerType typeAndFlags) { + long length = buf.readBerLength(); + + value = buf.readBytes((int)length); + } + + @Override + public Tag deepCopy(String suffix) { + return new ObjectID(name + suffix).copyFrom(this); + } + + @Override + public Tag copyFrom(Tag tag) { + super.copyFrom(tag); + value = new ByteBuffer(((ObjectID)tag).value.toByteArray()); + return this; + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/asn1/OctetString.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/asn1/OctetString.java new file mode 100755 index 00000000000..3da9c849166 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/common/asn1/OctetString.java @@ -0,0 +1,80 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package common.asn1; + +import streamer.ByteBuffer; + +public class OctetString extends Tag { + + public ByteBuffer value = null; + + public OctetString(String name) { + super(name); + tagType = OCTET_STRING; + } + + @Override + public void readTagValue(ByteBuffer buf, BerType typeAndFlags) { + // Type is already read by parent parser + + long length = buf.readBerLength(); + + if (length > buf.length) + throw new RuntimeException("BER octet string is too long: " + length + " bytes. Data: " + buf + "."); + + value = buf.readBytes((int)length); + } + + @Override + public Tag deepCopy(String suffix) { + return new OctetString(name + suffix).copyFrom(this); + } + + @Override + public Tag copyFrom(Tag tag) { + super.copyFrom(tag); + value = ((OctetString)tag).value; + return this; + } + + @Override + public String toString() { + return super.toString() + "= " + value; + } + + @Override + public long calculateLengthOfValuePayload() { + if (value != null) + return value.length; + else + return 0; + } + + @Override + public void writeTagValuePayload(ByteBuffer buf) { + if (value != null) + buf.writeBytes(value); + else + return; + } + + @Override + public boolean isValueSet() { + return value != null; + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/asn1/Sequence.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/asn1/Sequence.java new file mode 100755 index 00000000000..6fa23f8baab --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/common/asn1/Sequence.java @@ -0,0 +1,143 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package common.asn1; + +import java.util.Arrays; + +import streamer.ByteBuffer; + +/** + * One or more elements of different types. + * + * Only prefixed tags are supported. + */ +public class Sequence extends Tag { + + public Tag[] tags; + + public Sequence(String name) { + super(name); + tagType = SEQUENCE; + // Sequence and SequenceOf are always encoded as constructed + constructed = true; + } + + @Override + public long calculateLengthOfValuePayload() { + long sum = 0; + + for (Tag tag : tags) { + long tagLength = tag.calculateFullLength(); + sum += tagLength; + } + + return sum; + } + + @Override + public void writeTagValuePayload(ByteBuffer buf) { + // Write tags + for (Tag tag : tags) { + tag.writeTag(buf); + } + } + + @Override + public void readTagValue(ByteBuffer buf, BerType typeAndFlags) { + // Type is already read by parent parser + + long length = buf.readBerLength(); + if (length > buf.remainderLength()) + throw new RuntimeException("BER sequence is too long: " + length + " bytes, while buffer remainder length is " + buf.remainderLength() + ". Data: " + buf + + "."); + + ByteBuffer value = buf.readBytes((int)length); + parseContent(value); + + value.unref(); + } + + protected void parseContent(ByteBuffer buf) { + for (int i = 0; buf.remainderLength() > 0 && i < tags.length; i++) { + BerType typeAndFlags = readBerType(buf); + + // If current tag does not match data in buffer + if (!tags[i].isTypeValid(typeAndFlags)) { + + // If tag is required, then throw exception + if (!tags[i].optional) { + throw new RuntimeException("[" + this + "] ERROR: Required tag is missed: " + tags[i] + ". Unexected tag type: " + typeAndFlags + ". Data: " + buf + + "."); + } else { + // One or more tags are omitted, so skip them + for (; i < tags.length; i++) { + if (tags[i].isTypeValid(typeAndFlags)) { + break; + } + } + + if (i >= tags.length || !tags[i].isTypeValid(typeAndFlags)) { + throw new RuntimeException("[" + this + "] ERROR: No more tags to read or skip, but some data still left in buffer. Unexected tag type: " + + typeAndFlags + ". Data: " + buf + "."); + } + } + } + + tags[i].readTag(buf, typeAndFlags); + } + + } + + @Override + public boolean isTypeValid(BerType typeAndFlags, boolean explicit) { + if (explicit) + return typeAndFlags.tagClass == tagClass && typeAndFlags.constructed && typeAndFlags.typeOrTagNumber == tagNumber; + else + // Sequences are always encoded as "constructed" in BER. + return typeAndFlags.tagClass == UNIVERSAL_CLASS && typeAndFlags.constructed && typeAndFlags.typeOrTagNumber == SEQUENCE; + } + + @Override + public Tag deepCopy(String suffix) { + return new Sequence(name + suffix).copyFrom(this); + } + + @Override + public Tag copyFrom(Tag tag) { + super.copyFrom(tag); + + if (tags.length != ((Sequence)tag).tags.length) + throw new RuntimeException("Incompatible sequences. This: " + this + ", another: " + tag + "."); + + for (int i = 0; i < tags.length; i++) { + tags[i].copyFrom(((Sequence)tag).tags[i]); + } + + return this; + } + + @Override + public String toString() { + return super.toString() + "{" + Arrays.toString(tags) + " }"; + } + + @Override + public boolean isValueSet() { + return tags != null; + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/asn1/SequenceOf.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/asn1/SequenceOf.java new file mode 100755 index 00000000000..f288991c259 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/common/asn1/SequenceOf.java @@ -0,0 +1,82 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package common.asn1; + +import java.util.ArrayList; + +import streamer.ByteBuffer; + +/** + * Zero or more elements of same type (array). + */ +public class SequenceOf extends Sequence { + + /** + * Type of this array. + */ + public Tag type; + + /* Values are stored in tags[] variable inherited from Sequence. */ + + public SequenceOf(String name) { + super(name); + } + + @Override + protected void parseContent(ByteBuffer buf) { + ArrayList tagList = new ArrayList(); + + for (int index = 0; buf.remainderLength() > 0; index++) { + // End of array is marked with two zero bytes (0x00 0x00) + if (buf.peekUnsignedByte(0) == 0x00 && buf.peekUnsignedByte(1) == 0x00) { + break; + } + + Tag tag = type.deepCopy(index); + + tag.readTag(buf); + tagList.add(tag); + } + + tags = tagList.toArray(new Tag[tagList.size()]); + } + + @Override + public Tag deepCopy(String suffix) { + return new SequenceOf(name + suffix).copyFrom(this); + } + + @Override + public Tag copyFrom(Tag tag) { + super.copyFrom(tag); + // We can create shallow copy of type, because it will not be modified + type = ((SequenceOf)tag).type; + + tags = new Tag[((Sequence)tag).tags.length]; + for (int i = 0; i < tags.length; i++) { + tags[i] = ((Sequence)tag).tags[i].deepCopy(""); + } + + return this; + } + + @Override + public String toString() { + return super.toString() + ": " + type; + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/asn1/Tag.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/asn1/Tag.java new file mode 100755 index 00000000000..80ece43db74 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/common/asn1/Tag.java @@ -0,0 +1,462 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package common.asn1; + +import streamer.ByteBuffer; + +public abstract class Tag implements Asn1Constants { + + /** + * Name of this tag, for debugging purposes. + */ + public String name = ""; + + /** + * Is this tag required or optional, for explicit tags only. + */ + public boolean optional = false; + + /** + * Tag primitive (e.g. implicit boolean), or constructed (e.g. sequence, or + * explicit boolean). + */ + public boolean constructed = false; + + /** + * Class of tag, when it is explicit. + */ + public int tagClass = UNIVERSAL_CLASS; + + /** + * Tag number (e.g. index in sequence), when tag is explicit. + */ + public int tagNumber = -1; + + /** + * Tag type (e.g. INDER), when tag is implicit. + */ + public int tagType = -1; + + /** + * If tag is explicit, then it is prefixed with tag number, so it can be + * optional or used in unordered set. + */ + public boolean explicit = false; + + public Tag(String name) { + this.name = name; + } + + /** + * Write tag value, with or without prefix. + */ + public void writeTag(ByteBuffer buf) { + + if (!isMustBeWritten()) + return; + + // Write prefix, when necessary + if (explicit) { + + // Write tag prefix, always constructed + BerType berTagPrefix = new BerType(tagClass, true, tagNumber); + writeBerType(buf, berTagPrefix); + + // Write tag prefix length + buf.writeBerLength(calculateLength()); + + // Write tag value + writeTagValue(buf); + } else { + // If implicit, just write tag value + writeTagValue(buf); + } + } + + /** + * Must return true when value of this tag is set or tag is required, so it + * can be written, false otherwise. + */ + public boolean isMustBeWritten() { + return !optional || isValueSet(); + } + + /** + * Must return true when value of this tag is set or tag is required, so it + * can be written, false otherwise. + */ + public abstract boolean isValueSet(); + + /** + * Calculate full length of tag, including type (or prefix, when explicit). + */ + public long calculateFullLength() { + if (!isMustBeWritten()) + return 0; + + // Length of value, including type + long length = calculateLength(); + + if (!explicit) { + // Length of tag type and it length + length += calculateLengthOfTagTypeOrTagNumber(tagType) + calculateLengthOfLength(length); + } else { + // Length of tag prefix and it length + length += calculateLengthOfTagTypeOrTagNumber(tagNumber) + calculateLengthOfLength(length); + } + + return length; + } + + /** + * Calculate length of tag, including type when explicit, but without length + * of prefix (or type, when implicit). + */ + public long calculateLength() { + if (!isMustBeWritten()) + return 0; + + // Length of value + long length = calculateLengthOfValuePayload(); + + if (explicit) { + // Length of tag type and it length + length += calculateLengthOfTagTypeOrTagNumber(tagType) + calculateLengthOfLength(length); + } + + return length; + } + + /** + * Calculate length of BER length. + */ + public int calculateLengthOfLength(long length) { + if (length < 0) + throw new RuntimeException("[" + this + "] ERROR: Length of tag cannot be less than zero: " + length + "."); + + if (length <= 0x7f) + return 1; + if (length <= 0xff) + return 2; + if (length <= 0xffFF) + return 3; + if (length <= 0xffFFff) + return 4; + if (length <= 0xffFFffFFL) + return 5; + if (length <= 0xffFFffFFffL) + return 6; + if (length <= 0xffFFffFFffFFL) + return 7; + if (length <= 0xffFFffFFffFFffL) + return 8; + + return 9; + } + + /** + * Calculate length of type to tag number. Values less than 31 are encoded + * using lower 5 bits of first byte of tag. Values larger than 31 are + * indicated by lower 5 bits set to 1 (0x1F, 31), and next bytes are contain + * value in network order, where topmost bit of byte (0x80) indicates is value + * contains more bytes, i.e. last byte of sequence has this bit set to 0. + */ + public int calculateLengthOfTagTypeOrTagNumber(int tagType) { + if (tagType >= EXTENDED_TYPE) + throw new RuntimeException("Multibyte tag types are not supported yet."); + + return 1; + } + + /** + * Calculate length of payload only, without tag prefix, tag type, and + * lengths. + * + * @return + */ + public abstract long calculateLengthOfValuePayload(); + + /** + * Write tag value only, without prefix. + */ + public void writeTagValue(ByteBuffer buf) { + + // Write type + BerType valueType = new BerType(UNIVERSAL_CLASS, constructed, tagType); + writeBerType(buf, valueType); + + // Write length + long lengthOfPayload = calculateLengthOfValuePayload(); + buf.writeBerLength(lengthOfPayload); + + // Store cursor to check is calculated length matches length of actual bytes + // written + int storedCursor = buf.cursor; + + // Write value + writeTagValuePayload(buf); + + // Check is calculated length matches length of actual bytes written, to catch errors early + int actualLength = buf.cursor - storedCursor; + if (actualLength != lengthOfPayload) + throw new RuntimeException("[" + this + "] ERROR: Unexpected length of data in buffer. Expected " + lengthOfPayload + " of bytes of payload, but " + + actualLength + " bytes are written instead. Data: " + buf + "."); + } + + /** + * Write tag value only, without prefix, tag type, and length. + */ + public abstract void writeTagValuePayload(ByteBuffer buf); + + /** + * Read required tag, i.e. we are 100% sure that byte buffer will contain this + * tag, or exception will be thrown otherwise. + * + * @param buf + * buffer with tag data + */ + public void readTag(ByteBuffer buf) { + BerType typeAndFlags = readBerType(buf); + + // * DEBUG */System.out.println("Tag, read " + typeAndFlags); + + if (!isTypeValid(typeAndFlags)) + throw new RuntimeException("[" + this + "] Unexpected type: " + typeAndFlags + "."); + + readTag(buf, typeAndFlags); + } + + /** + * Read tag when it type is already read. + */ + public void readTag(ByteBuffer buf, BerType typeAndFlags) { + + if (explicit) { + long length = buf.readBerLength(); + + if (length > buf.length) + throw new RuntimeException("BER value is too long: " + length + " bytes. Data: " + buf + "."); + + ByteBuffer value = buf.readBytes((int)length); + + readTagValue(value); + + value.unref(); + } else { + + readTagValue(buf, typeAndFlags); + } + } + + /** + * Read tag value only, i.e. it prefix is already read. + */ + public void readTagValue(ByteBuffer value) { + BerType typeAndFlags = readBerType(value); + + // * DEBUG */System.out.println("Tag, read value " + typeAndFlags); + + if (!isTypeValid(typeAndFlags, false)) + throw new RuntimeException("[" + this + "] Unexpected type: " + typeAndFlags + "."); + + readTagValue(value, typeAndFlags); + } + + /** + * Check are tag type and flags valid for this tag. + */ + public final boolean isTypeValid(BerType typeAndFlags) { + return isTypeValid(typeAndFlags, explicit); + } + + /** + * Check are tag type and flags valid for this tag with or without tag prefix. + * + * @param explicit + * if true, then value is wrapped in tag prefix + */ + public boolean isTypeValid(BerType typeAndFlags, boolean explicit) { + if (explicit) + return typeAndFlags.tagClass == tagClass && typeAndFlags.constructed && typeAndFlags.typeOrTagNumber == tagNumber; + else + return typeAndFlags.tagClass == UNIVERSAL_CLASS && !typeAndFlags.constructed && typeAndFlags.typeOrTagNumber == tagType; + } + + @Override + public String toString() { + return " \nTag [name=" + + name + + + ((constructed) ? ", constructed=" + constructed : "") + + + (", tagType=" + tagTypeOrNumberToString(UNIVERSAL_CLASS, tagType)) + + + ((explicit) ? ", explicit=" + explicit + ", optional=" + optional + ", tagClass=" + tagClassToString(tagClass) + ", tagNumber=" + + tagTypeOrNumberToString(tagClass, tagNumber) : "") + "]"; + } + + public static final String tagTypeOrNumberToString(int tagClass, int tagTypeOrNumber) { + switch (tagClass) { + case UNIVERSAL_CLASS: + switch (tagTypeOrNumber) { + case EOF: + return "EOF"; + case BOOLEAN: + return "BOOLEAN"; + case INTEGER: + return "INTEGER"; + case BIT_STRING: + return "BIT_STRING"; + case OCTET_STRING: + return "OCTET_STRING"; + case NULL: + return "NULL"; + case OBJECT_ID: + return "OBJECT_ID"; + case REAL: + return "REAL"; + case ENUMERATED: + return "ENUMERATED"; + case SEQUENCE: + return "SEQUENCE"; + case SET: + return "SET"; + case NUMERIC_STRING: + return "NUMERIC_STRING"; + case PRINTABLE_STRING: + return "PRINTABLE_STRING"; + case TELETEX_STRING: + return "TELETEX_STRING"; + case VIDEOTEXT_STRING: + return "VIDEOTEXT_STRING"; + case IA5_STRING: + return "IA5_STRING"; + case UTCTIME: + return "UTCTIME"; + case GENERAL_TIME: + return "GENERAL_TIME"; + case GRAPHIC_STRING: + return "GRAPHIC_STRING"; + case VISIBLE_STRING: + return "VISIBLE_STRING"; + case GENERAL_STRING: + return "GENERAL_STRING"; + case EXTENDED_TYPE: + return "EXTENDED_TYPE (multibyte)"; + default: + return "UNKNOWN(" + tagTypeOrNumber + ")"; + + } + + default: + return "[" + tagTypeOrNumber + "]"; + } + } + + public static final String tagClassToString(int tagClass) { + switch (tagClass) { + case UNIVERSAL_CLASS: + return "UNIVERSAL"; + case CONTEXT_CLASS: + return "CONTEXT"; + case APPLICATION_CLASS: + return "APPLICATION"; + case PRIVATE_CLASS: + return "PRIVATE"; + default: + return "UNKNOWN"; + } + } + + /** + * Read BER tag type. + */ + public BerType readBerType(ByteBuffer buf) { + int typeAndFlags = buf.readUnsignedByte(); + + int tagClass = typeAndFlags & CLASS_MASK; + + boolean constructed = (typeAndFlags & CONSTRUCTED) != 0; + + int type = typeAndFlags & TYPE_MASK; + if (type == EXTENDED_TYPE) + throw new RuntimeException("Extended tag types/numbers (31+) are not supported yet."); + + return new BerType(tagClass, constructed, type); + } + + /** + * Write BER tag type. + */ + public void writeBerType(ByteBuffer buf, BerType berType) { + + if (berType.typeOrTagNumber >= EXTENDED_TYPE || berType.typeOrTagNumber < 0) + throw new RuntimeException("Extended tag types/numbers (31+) are not supported yet: " + berType + "."); + + if ((berType.tagClass & CLASS_MASK) != berType.tagClass) + throw new RuntimeException("Value of BER tag class is out of range: " + berType.tagClass + ". Expected values: " + UNIVERSAL_CLASS + ", " + CONTEXT_CLASS + + ", " + APPLICATION_CLASS + ", " + PRIVATE_CLASS + "."); + + int typeAndFlags = berType.tagClass | ((berType.constructed) ? CONSTRUCTED : 0) | berType.typeOrTagNumber; + + buf.writeByte(typeAndFlags); + } + + /** + * Read tag value only, i.e. it prefix is already read, when value type is + * already read. + * + * @param buf + * buffer with tag data + */ + public abstract void readTagValue(ByteBuffer buf, BerType typeAndFlags); + + /** + * Create deep copy of this tag with given suffix appended to name. + * + * @param suffix + * suffix to add to tag name, or empty string + * @return deep copy of this tag + */ + public abstract Tag deepCopy(String suffix); + + /** + * Create deep copy of this tag for array or set. + * + * @param index + * index of element in array or set + * @return deep copy of this tag + */ + public Tag deepCopy(int index) { + return deepCopy("[" + index + "]"); + } + + /** + * Copy tag values from an other tag, except name. + * + * @return this + */ + public Tag copyFrom(Tag tag) { + constructed = tag.constructed; + explicit = tag.explicit; + optional = tag.optional; + tagClass = tag.tagClass; + tagNumber = tag.tagNumber; + return this; + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/opt/IncrementalOption.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/opt/IncrementalOption.java new file mode 100755 index 00000000000..eb24d11671a --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/common/opt/IncrementalOption.java @@ -0,0 +1,28 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package common.opt; + +public class IncrementalOption extends Option { + int value = 0; + + @Override + public int parse(int position, String[] args) { + value++; + return super.parse(position, args); + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/opt/IntOption.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/opt/IntOption.java new file mode 100755 index 00000000000..87e732a82f4 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/common/opt/IntOption.java @@ -0,0 +1,41 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package common.opt; + +public class IntOption extends Option { + public int value = 0; + + @Override + public int parse(int position, String[] args) { + if (position + 1 >= args.length) + throw new NoArgumentForOptionException("Cannot find required argument for option \"" + args[position] + "\"."); + + value = Integer.parseInt(args[position + 1]); + return super.parse(position, args) + 1; + } + + @Override + public String help() { + StringBuilder help = new StringBuilder(); + help.append(join("|", name, alias, aliases)).append(" VALUE\t").append(description); + if (required) + help.append(" Required."); + else if (value != 0) + help.append(" Default value is \"").append("" + value).append("\"."); + return help.toString(); + } +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/opt/NoArgumentForOptionException.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/opt/NoArgumentForOptionException.java new file mode 100755 index 00000000000..a074672c489 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/common/opt/NoArgumentForOptionException.java @@ -0,0 +1,26 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package common.opt; + +public class NoArgumentForOptionException extends RuntimeException { + public NoArgumentForOptionException(String message) { + super(message); + } + + private static final long serialVersionUID = 1L; + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/opt/Option.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/opt/Option.java new file mode 100755 index 00000000000..e69d3f39304 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/common/opt/Option.java @@ -0,0 +1,102 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package common.opt; + +public class Option { + + public String name = ""; + public String alias = null; + public String aliases[] = null; + + public String description = ""; + public boolean used = false; + public boolean required = false; + + /** + * Parse option value, if any. + * + * @param position + * position of this option in list of arguments + * @param args + * command line arguments + * @return how many arguments are consumed, at least 1 + */ + public int parse(int position, String args[]) { + used = true; + return 1; + } + + @Override + public String toString() { + return help(); + } + + /** + * Return help string for this option. Example: + * + *
+     *   --foo|-f    Foo option.
+     * 
+ */ + public String help() { + return join("|", name, alias, aliases) + "\t" + description + ((required) ? " Required." : ""); + } + + /** + * Return string like "--foo|-f|--another-foo-alias". + */ + protected String join(String delim, String name, String alias, String aliases[]) { + + // Option name is mandatory + StringBuilder sb = new StringBuilder(name.length()); + sb.append(name); + + // Alias is optional + if (alias != null && alias.length() > 0) { + sb.append(delim).append(alias); + } + + // Other aliases are optional too + if (aliases != null) { + for (String s : aliases) { + if (s != null && s.length() > 0) { + sb.append(delim).append(s); + } + } + } + + return sb.toString(); + } + + /** + * Return description of options in format suitable for help and usage text. + * + * @param header + * header string to print before list of options + * @param options + * list of options to print + */ + public static String toHelp(String header, Option[] options) { + StringBuffer sb = new StringBuffer(); + sb.append(header).append(":\n"); + for (Option option : options) { + sb.append(" ").append(option.help()).append('\n'); + } + return sb.toString(); + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/opt/OptionParser.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/opt/OptionParser.java new file mode 100755 index 00000000000..11c42fec6c6 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/common/opt/OptionParser.java @@ -0,0 +1,147 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package common.opt; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +/** + * Simple parser of GNU-like options. + */ +public class OptionParser { + + public static Option helpOption() { + return new Option() { + { + name = "--help"; + alias = "-h"; + } + }; + } + + /** + * Parse options, capture values and return rest of arguments. + * + * @param args + * command line arguments to parse + * @param startFrom + * number of first argument to start parsing from + * @param options + * options to fill with values + * @return rest of command line after first non-option or "--" separator + */ + public static String[] parseOptions(String args[], int startFrom, Option options[]) { + // Convert array of options into map, where key is option name or alias + Map optionMap = new HashMap(options.length); + for (Option option : options) { + optionMap.put(option.name, option); + + if (option.alias != null) + optionMap.put(option.alias, option); + + if (option.aliases != null) { + for (String alias : option.aliases) + optionMap.put(alias, option); + } + } + + // Parse arguments + int position = startFrom; + while (position < args.length) { + // Double dash means end of options + String optionName = args[position]; + if (optionName.equals("--")) { + position++; + break; + } + + Option option = optionMap.get(optionName); + + // If option is not found, then this is argument, unless is starts with + // dash + if (option == null) + if (!optionName.startsWith("-")) + break; + else + throw new UnknownOptionException("Option \"" + optionName + + "\" is unknown. If this is not an option, then use \"--\" to separate options and arguments. Known options: " + optionMap.keySet().toString()); + + position += option.parse(position, args); + } + + // Check is required options are used on command line + for (Option option : options) { + if (option.required && !option.used) + throw new OptionRequiredException("Option \"" + option.name + "\" is required."); + } + + // Return rest of arguments, which are left after options + return (position < args.length) ? Arrays.copyOfRange(args, position, args.length) : new String[] {}; + } + + /* Example. */ + public static void main(String args[]) { + if (args.length == 0) + args = new String[] {"--help", "--foo", "fooval", "--bar", "123", "-v", "--verbose", "-v", "-a", "a1", "-aa", "a2", "-aaa", "a3", "rest", "of", + "arguments"}; + + StringOption foo = new StringOption() { + { + name = "--foo"; + alias = "-f"; + value = "fooDefault"; + } + }; + + IntOption bar = new IntOption() { + { + name = "--bar"; + alias = "-b"; + value = 123; + } + }; + + IncrementalOption verbose = new IncrementalOption() { + { + name = "--verbose"; + alias = "-v"; + } + }; + + StringArrayOption array = new StringArrayOption() { + { + name = "--array"; + alias = "-a"; + aliases = new String[] {"-aa", "-aaa"}; + } + }; + + String arguments[] = OptionParser.parseOptions(args, 0, new Option[] {helpOption(), foo, bar, verbose, array}); + + assertTrue(foo.value.equals("fooval")); + assertTrue(bar.value == 123); + assertTrue(verbose.value == 3); + assertTrue(Arrays.equals(array.value, new String[] {"a1", "a2", "a3"})); + assertTrue(Arrays.equals(arguments, new String[] {"rest", "of", "arguments"})); + } + + public static void assertTrue(boolean result) { + if (!result) + throw new AssertionError(); + } +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/opt/OptionRequiredException.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/opt/OptionRequiredException.java new file mode 100755 index 00000000000..b39762793a5 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/common/opt/OptionRequiredException.java @@ -0,0 +1,26 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package common.opt; + +public class OptionRequiredException extends RuntimeException { + public OptionRequiredException(String message) { + super(message); + } + + private static final long serialVersionUID = 1L; + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/opt/StringArrayOption.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/opt/StringArrayOption.java new file mode 100755 index 00000000000..b2f3c308695 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/common/opt/StringArrayOption.java @@ -0,0 +1,38 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package common.opt; + +import java.util.Arrays; + +public class StringArrayOption extends Option { + public String value[] = null; + + @Override + public int parse(int position, String[] args) { + if (position + 1 >= args.length) + throw new NoArgumentForOptionException("Cannot find required argument for option \"" + args[position] + "\"."); + + // Append value to end of array of values + if (value == null) { + value = new String[] {args[position + 1]}; + } else { + value = Arrays.copyOf(value, value.length + 1); + value[value.length - 1] = args[position + 1]; + } + return super.parse(position, args) + 1; + } +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/opt/StringEnumerationOption.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/opt/StringEnumerationOption.java new file mode 100755 index 00000000000..f59952ed473 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/common/opt/StringEnumerationOption.java @@ -0,0 +1,72 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package common.opt; + +public class StringEnumerationOption extends Option { + public String value = ""; + public String choices[] = new String[] {}; + + @Override + public int parse(int position, String[] args) { + if (position + 1 >= args.length) + throw new NoArgumentForOptionException("Cannot find required argument for option \"" + args[position] + "\"."); + + value = args[position + 1]; + + for (String s : choices) { + if (value.equals(s)) + return super.parse(position, args) + 1; + } + + throw new NoArgumentForOptionException("Unexpected argument for option \"" + args[position] + "\": \"" + value + "\". Expected argument: " + + join("|", choices) + "."); + } + + @Override + public String help() { + StringBuilder help = new StringBuilder(); + help.append(join("|", name, alias, aliases)).append(" ").append(join("|", choices)).append("\t").append(description); + if (required) + help.append(" Required."); + else if (value != null && value.length() > 0) + help.append(" Default value is \"").append(value).append("\"."); + return help.toString(); + } + + /** + * Join strings in array into one large string. + */ + protected String join(String delim, String values[]) { + StringBuilder sb = new StringBuilder(); + if (values != null) { + boolean first = true; + for (String s : values) { + if (s != null && s.length() > 0) { + if (first) + first = false; + else + sb.append(delim); + + sb.append(s); + } + } + } + + return sb.toString(); + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/opt/StringOption.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/opt/StringOption.java new file mode 100755 index 00000000000..ec9c82c3da8 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/common/opt/StringOption.java @@ -0,0 +1,41 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package common.opt; + +public class StringOption extends Option { + public String value = ""; + + @Override + public int parse(int position, String[] args) { + if (position + 1 >= args.length) + throw new NoArgumentForOptionException("Cannot find required argument for option \"" + args[position] + "\"."); + + value = args[position + 1]; + return super.parse(position, args) + 1; + } + + @Override + public String help() { + StringBuilder help = new StringBuilder(); + help.append(join("|", name, alias, aliases)).append(" VALUE\t").append(description); + if (required) + help.append(" Required."); + else if (value != null && value.length() > 0) + help.append(" Default value is \"").append(value).append("\"."); + return help.toString(); + } +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/common/opt/UnknownOptionException.java b/services/console-proxy-rdp/rdpconsole/src/main/java/common/opt/UnknownOptionException.java new file mode 100755 index 00000000000..58cce7327b9 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/common/opt/UnknownOptionException.java @@ -0,0 +1,27 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package common.opt; + +public class UnknownOptionException extends RuntimeException { + + public UnknownOptionException(String message) { + super(message); + } + + private static final long serialVersionUID = 1L; + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/AwtRdpKeyboardAdapter.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/AwtRdpKeyboardAdapter.java deleted file mode 100644 index 06449f6f874..00000000000 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/AwtRdpKeyboardAdapter.java +++ /dev/null @@ -1,350 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package rdpclient; - -import java.awt.event.KeyEvent; - -import streamer.BaseElement; -import streamer.ByteBuffer; -import streamer.Link; -import common.KeyOrder; - -public class AwtRdpKeyboardAdapter extends BaseElement { - - /** - * Absence of this flag indicates a key-down event, while its presence - * indicates a key-release event. - */ - public static final int FASTPATH_INPUT_KBDFLAGS_RELEASE = 0x01; - - /** - * Keystroke message contains an extended scancode. For enhanced 101-key and - * 102-key keyboards, extended keys include the right ALT and right CTRL keys - * on the main section of the keyboard; the INS, DEL, HOME, END, PAGE UP, PAGE - * DOWN and ARROW keys in the clusters to the left of the numeric keypad; and - * the Divide ("/") and ENTER keys in the numeric keypad. - */ - public static final int FASTPATH_INPUT_KBDFLAGS_EXTENDED = 0x02; - - public static final int FASTPATH_INPUT_EVENT_SCANCODE = 0; - - public AwtRdpKeyboardAdapter(String id) { - super(id); - } - - @Override - public void handleData(ByteBuffer buf, Link link) { - if (verbose) - System.out.println("[" + this + "] INFO: Data received: " + buf + "."); - - KeyOrder order = (KeyOrder)buf.getOrder(); - buf.unref(); - - ByteBuffer outBuf = new ByteBuffer(2, true); - - int scanCode = map_en_us(order.event); - - // eventHeader (1 byte): An 8-bit, unsigned integer. The format of this - // field is the same as the eventHeader byte field described in section - // 2.2.8.1.2.2. The eventCode bitfield (3 bits in size) MUST be set to - // FASTPATH_INPUT_EVENT_SCANCODE (0). The eventFlags bitfield (5 bits in - // size) contains flags describing the keyboard event. - outBuf.writeByte((scanCode >> 8) | (FASTPATH_INPUT_EVENT_SCANCODE << 5) | ((order.pressed) ? 0 : FASTPATH_INPUT_KBDFLAGS_RELEASE)); - - // keyCode (1 byte): An 8-bit, unsigned integer. The scancode of the key - // which triggered the event. - outBuf.writeByte(scanCode); - - // Push buffer to one pad only, so it can be modified without copying of - // data - pushDataToPad(STDOUT, outBuf); - } - - /** - * Return key scan code (in lower byte) and extended flags (in second byte). - */ - private int map_en_us(KeyEvent event) { - // Also set extended key flag when necessary. - // For enhanced 101-key and 102-key keyboards, extended keys include the - // right ALT and right CTRL keys on the main section of the keyboard; the - // INS, DEL, HOME, END, PAGE UP, PAGE DOWN and ARROW keys in the clusters to - // the left of the numeric keypad; and the Divide ("/") and ENTER keys in - // the numeric keypad. - - switch (event.getKeyCode()) { - // Functional keys - case KeyEvent.VK_ESCAPE: - return 1; - case KeyEvent.VK_F1: - return 59; - case KeyEvent.VK_F2: - return 60; - case KeyEvent.VK_F3: - return 61; - case KeyEvent.VK_F4: - return 62; - case KeyEvent.VK_F5: - return 63; - case KeyEvent.VK_F6: - return 64; - case KeyEvent.VK_F7: - return 65; - case KeyEvent.VK_F8: - return 66; - case KeyEvent.VK_F9: - return 67; - case KeyEvent.VK_F10: - return 68; - case KeyEvent.VK_F11: - return 87; - case KeyEvent.VK_F12: - return 88; - - // Row #1 - case KeyEvent.VK_BACK_QUOTE: - return 41; - case KeyEvent.VK_1: - return 2; - case KeyEvent.VK_2: - return 3; - case KeyEvent.VK_3: - return 4; - case KeyEvent.VK_4: - return 5; - case KeyEvent.VK_5: - return 6; - case KeyEvent.VK_6: - return 7; - case KeyEvent.VK_7: - return 8; - case KeyEvent.VK_8: - return 9; - case KeyEvent.VK_9: - return 10; - case KeyEvent.VK_0: - return 11; - case KeyEvent.VK_MINUS: - return 12; - case KeyEvent.VK_EQUALS: - return 13; - case KeyEvent.VK_BACK_SPACE: - return 14; - - // Row #2 - case KeyEvent.VK_TAB: - return 15; - case KeyEvent.VK_Q: - return 16; - case KeyEvent.VK_W: - return 17; - case KeyEvent.VK_E: - return 18; - case KeyEvent.VK_R: - return 19; - case KeyEvent.VK_T: - return 20; - case KeyEvent.VK_Y: - return 21; - case KeyEvent.VK_U: - return 22; - case KeyEvent.VK_I: - return 23; - case KeyEvent.VK_O: - return 24; - case KeyEvent.VK_P: - return 25; - case KeyEvent.VK_OPEN_BRACKET: - return 26; - case KeyEvent.VK_CLOSE_BRACKET: - return 27; - case KeyEvent.VK_ENTER: - switch (event.getKeyLocation()) { - default: - case KeyEvent.KEY_LOCATION_STANDARD: - return 28; - case KeyEvent.KEY_LOCATION_NUMPAD: - return (FASTPATH_INPUT_KBDFLAGS_EXTENDED << 8) | 28; - } - - // Row #3 - case KeyEvent.VK_CAPS_LOCK: - return 58; - case KeyEvent.VK_A: - return 30; - case KeyEvent.VK_S: - return 31; - case KeyEvent.VK_D: - return 32; - case KeyEvent.VK_F: - return 33; - case KeyEvent.VK_G: - return 34; - case KeyEvent.VK_H: - return 35; - case KeyEvent.VK_J: - return 36; - case KeyEvent.VK_K: - return 37; - case KeyEvent.VK_L: - return 38; - case KeyEvent.VK_SEMICOLON: - return 39; - case KeyEvent.VK_QUOTE: - return 40; - - // Row #4 - case KeyEvent.VK_SHIFT: - switch (event.getKeyLocation()) { - default: - case KeyEvent.KEY_LOCATION_LEFT: - return 42; - case KeyEvent.KEY_LOCATION_RIGHT: - return 54; - } - case KeyEvent.VK_BACK_SLASH: - return 43; - case KeyEvent.VK_Z: - return 44; - case KeyEvent.VK_X: - return 45; - case KeyEvent.VK_C: - return 46; - case KeyEvent.VK_V: - return 47; - case KeyEvent.VK_B: - return 48; - case KeyEvent.VK_N: - return 49; - case KeyEvent.VK_M: - return 50; - case KeyEvent.VK_COMMA: - return 51; - case KeyEvent.VK_PERIOD: - return 52; - case KeyEvent.VK_SLASH: - return 53; - - // - // Bottom row - case KeyEvent.VK_CONTROL: - switch (event.getKeyLocation()) { - default: - case KeyEvent.KEY_LOCATION_LEFT: - return 29; - case KeyEvent.KEY_LOCATION_RIGHT: - return (FASTPATH_INPUT_KBDFLAGS_EXTENDED << 8) | 29; - } - case KeyEvent.VK_WINDOWS: - switch (event.getKeyLocation()) { - default: - case KeyEvent.KEY_LOCATION_LEFT: - return 91; - case KeyEvent.KEY_LOCATION_RIGHT: - return 92; - } - case KeyEvent.VK_ALT: - switch (event.getKeyLocation()) { - default: - case KeyEvent.KEY_LOCATION_LEFT: - return 56; - case KeyEvent.KEY_LOCATION_RIGHT: - return (FASTPATH_INPUT_KBDFLAGS_EXTENDED << 8) | 56; - } - case KeyEvent.VK_ALT_GRAPH: - return (FASTPATH_INPUT_KBDFLAGS_EXTENDED << 8) | 56; - - case KeyEvent.VK_SPACE: - return 57; - - case KeyEvent.VK_CONTEXT_MENU: - return 93; - - // - // Special keys - case KeyEvent.VK_PRINTSCREEN: - return 55; - case KeyEvent.VK_SCROLL_LOCK: - return 70; - case KeyEvent.VK_PAUSE: - return 29; - - // Text navigation keys - case KeyEvent.VK_INSERT: - return (FASTPATH_INPUT_KBDFLAGS_EXTENDED << 8) | 82; - case KeyEvent.VK_HOME: - return (FASTPATH_INPUT_KBDFLAGS_EXTENDED << 8) | 71; - case KeyEvent.VK_PAGE_UP: - return (FASTPATH_INPUT_KBDFLAGS_EXTENDED << 8) | 73; - case KeyEvent.VK_DELETE: - return (FASTPATH_INPUT_KBDFLAGS_EXTENDED << 8) | 83; - case KeyEvent.VK_END: - return (FASTPATH_INPUT_KBDFLAGS_EXTENDED << 8) | 79; - case KeyEvent.VK_PAGE_DOWN: - return (FASTPATH_INPUT_KBDFLAGS_EXTENDED << 8) | 81; - - // Cursor keys - case KeyEvent.VK_UP: - return (FASTPATH_INPUT_KBDFLAGS_EXTENDED << 8) | 72; - case KeyEvent.VK_LEFT: - return (FASTPATH_INPUT_KBDFLAGS_EXTENDED << 8) | 75; - case KeyEvent.VK_DOWN: - return (FASTPATH_INPUT_KBDFLAGS_EXTENDED << 8) | 80; - case KeyEvent.VK_RIGHT: - return (FASTPATH_INPUT_KBDFLAGS_EXTENDED << 8) | 77; - - // Keypad - case KeyEvent.VK_NUM_LOCK: - return 69; - case KeyEvent.VK_DIVIDE: - return (FASTPATH_INPUT_KBDFLAGS_EXTENDED << 8) | 53; - case KeyEvent.VK_MULTIPLY: - return 55; - case KeyEvent.VK_SUBTRACT: - return 74; - case KeyEvent.VK_ADD: - return 78; - - case KeyEvent.VK_NUMPAD7: - return 71; - case KeyEvent.VK_NUMPAD8: - return 72; - case KeyEvent.VK_NUMPAD9: - return 73; - case KeyEvent.VK_NUMPAD4: - return 75; - case KeyEvent.VK_NUMPAD5: - return 76; - case KeyEvent.VK_NUMPAD6: - return 77; - case KeyEvent.VK_NUMPAD1: - return 79; - case KeyEvent.VK_NUMPAD2: - return 80; - case KeyEvent.VK_NUMPAD3: - return 81; - case KeyEvent.VK_NUMPAD0: - return 82; - case KeyEvent.VK_DECIMAL: - return 83; - - default: - System.err.println("Key is not mapped: " + event + "."); - return 57; // Space - } - } - -} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientConfirmActivePDU.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientConfirmActivePDU.java deleted file mode 100644 index d757e8e7950..00000000000 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientConfirmActivePDU.java +++ /dev/null @@ -1,1129 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package rdpclient; - -import streamer.BaseElement; -import streamer.ByteBuffer; -import streamer.Element; -import streamer.Link; -import streamer.MockSink; -import streamer.MockSource; -import streamer.Pipeline; -import streamer.PipelineImpl; -import common.ScreenDescription; - -/** - * @see http://msdn.microsoft.com/en-us/library/cc240488.aspx - */ -public class ClientConfirmActivePDU extends BaseElement { - - public static final String SOURCE_DESC = "MSTSC"; - - public static final int CAPSTYPE_BITMAP = 0x2; - - protected int numberCapabilities; - - protected RdpState state; - protected ScreenDescription screen; - - protected boolean desktopResize = false; - protected int prefferedBitsPerPixel = 16; - - public ClientConfirmActivePDU(String id, ScreenDescription screen, RdpState state) { - super(id); - this.state = state; - this.screen = screen; - } - - @Override - public void handleData(ByteBuffer aBuf, Link link) { - - // Body - ByteBuffer buf = new ByteBuffer(1024, true); - numberCapabilities = 0; - writeCapabilities(buf); - buf.trimAtCursor(); - - // Header - ByteBuffer header = createMCSHeader(buf); - - // Length of source descriptor, including NULL character (LE) - header.writeShortLE(SOURCE_DESC.length() + 1); - - // Length of combined capabilities + 4 bytes (number of capabilities and - // padding) (LE) - header.writeShortLE(buf.length + 4); - - header.writeString(SOURCE_DESC, RdpConstants.CHARSET_8); - header.writeByte(0); - - // Number of capabilities - header.writeShortLE(numberCapabilities); - - // Padding 2 bytes - header.writeShortLE(0); - - header.trimAtCursor(); - - // Prepend header to capabilities - buf.prepend(header); - - // Trim buffer to actual length of data written - buf.length = buf.cursor; - - pushDataToPad(STDOUT, buf); - - sendOtherRequredPackets(); - - } - - private ByteBuffer createMCSHeader(ByteBuffer buf) { - ByteBuffer header = new ByteBuffer(100); - // MCS Send Data Request - header.writeByte(0x64); - - // Initiator: 1004 (1001+3) - header.writeShort(3); - - // Channel ID: 1003 (I/O channel) - header.writeShort(1003); - - // Data priority: high (0x40), segmentation: begin (0x20) | end (0x10) - header.writeByte(0x70); - - int length = buf.length + 26; - - // User data length: (variable length field, LE) - header.writeVariableShort(length); - - // Total length: (LE) - header.writeShortLE(length); - - // PDU type: Confirm Active PDU (0x3), TS_PROTOCOL_VERSION (0x10) (LE) - header.writeShortLE(0x13); - - // PDU source: 1004 (LE) - header.writeShortLE(1004); - - // Share ID, e.g. 0x000103ea (LE) - header.writeIntLE((int)state.serverShareId); - - // Originator ID: 1002 (LE) - header.writeShortLE(1002); - return header; - } - - private void sendOtherRequredPackets() { - // Send sequence in bulk - - sendSynchronizePDU(); - sendControlPDUActionCooperate(); - sendControlPDUActionRequestControl(); - // sendBitmapCachePersistentListPDU(); - sendFontListPDU(); - } - - private void sendFontListPDU() { - { - int length = 1024; // Large enough - ByteBuffer buf = new ByteBuffer(length, true); - - /* @formatter:off */ - buf.writeBytes(new byte[] { - // MCS Send Data Request - (byte)0x64, - // Initiator: 1004 (1001+3) - (byte)0x00, (byte)0x03, - // Channel ID: 1003 (I/O channel) - (byte)0x03, (byte)0xeb, - // Data priority: high (0x40), segmentation: begin (0x20) | end (0x10) - (byte)0x70, - // User data length: 26 bytes (0x1a, variable length field) - (byte)0x80, (byte)0x1a, - - // Total length: 26 bytes (0x1a, LE) - (byte)0x1a, (byte)0x00, - // PDU type: PDUTYPE_DATAPDU (0x7), PDU version: 1 (0x0010) (LE) - (byte)0x17, (byte)0x00, - // PDU source: 1004 (LE) - (byte)0xec, (byte)0x03, - }); - // Share ID, 4 bytes (LE) - buf.writeIntLE((int)state.serverShareId); - - buf.writeBytes(new byte[] { - // Padding 1 byte - (byte)0x00, - // Stream ID: STREAM_LOW (1) - (byte)0x01, - // uncompressedLength : 12 bytes (LE) - (byte)0x0c, (byte)0x00, - - // pduType2: PDUTYPE2_FONTLIST (39) - (byte)0x27, - // generalCompressedType: 0 - (byte)0x00, - // generalCompressedLength: 0 (LE) - (byte)0x00, (byte)0x00, - - // numberEntries (should be set to zero): 0 (LE) - (byte)0x00, (byte)0x00, - // totalNumEntries (should be set to zero): 0 (LE) - (byte)0x00, (byte)0x00, - // listFlags (should be set to 0x3): 0x0003 (LE), FONTLIST_LAST(0x2) | FONTLIST_FIRST(0x1) - (byte)0x03, (byte)0x00, - // entrySize: 50 bytes (0x0032, LE) - (byte)0x32, (byte)0x00, - }); - /* @formatter:on */ - - // Trim buffer to actual length of data written - buf.trimAtCursor(); - - pushDataToPad(STDOUT, buf); - } - } - - private void sendControlPDUActionRequestControl() { - int length = 1024; // Large enough - ByteBuffer buf = new ByteBuffer(length, true); - - /* @formatter:off */ - buf.writeBytes(new byte[] { - // MCS Send Data Request - (byte)0x64, - // Initiator: 1004 (1001+3) - (byte)0x00, (byte)0x03, - // Channel ID: 1003 (I/O channel) - (byte)0x03, (byte)0xeb, - // Data priority: high (0x40), segmentation: begin (0x20) | end (0x10) - (byte)0x70, - // User data length: 26 bytes (0x1a, variable length field) - (byte)0x80, (byte)0x1a, - - // Total length: 26 bytes (0x1a, LE) - (byte)0x1a, (byte)0x00, - // PDU type: PDUTYPE_DATAPDU (0x7), PDU version: 1 (0x0010) (LE) - (byte)0x17, (byte)0x00, - // PDU source: 1004 (LE) - (byte)0xec, (byte)0x03, - }); - // Share ID, 4 bytes (LE) - buf.writeIntLE((int)state.serverShareId); - - buf.writeBytes(new byte[] { - // Padding 1 byte - (byte)0x00, - // Stream ID: STREAM_LOW (1) - (byte)0x01, - // uncompressedLength : 12 bytes (LE) - (byte)0x0c, (byte)0x00, - // pduType2: PDUTYPE2_CONTROL (20) - (byte)0x14, - // generalCompressedType: 0 - (byte)0x00, - // generalCompressedLength: 0 (LE) - (byte)0x00, (byte)0x00, - - // action: CTRLACTION_REQUEST_CONTROL (1) (LE) - (byte)0x01, (byte)0x00, - // grantId: 0 (LE) - (byte)0x00, (byte)0x00, - // controlId: 0 (LE) - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - }); - /* @formatter:on */ - - // Trim buffer to actual length of data written - buf.trimAtCursor(); - - pushDataToPad(STDOUT, buf); - } - - private void sendControlPDUActionCooperate() { - int length = 1024; // Large enough - ByteBuffer buf = new ByteBuffer(length, true); - - /* @formatter:off */ - buf.writeBytes(new byte[] { - // MCS Send Data Request - (byte)0x64, - // Initiator: 1004 (1001+3) - (byte)0x00, (byte)0x03, - // Channel ID: 1003 (I/O channel) - (byte)0x03, (byte)0xeb, - // Data priority: high (0x40), segmentation: begin (0x20) | end (0x10) - (byte)0x70, - // User data length: 26 bytes (0x1a, variable length field) - (byte)0x80, (byte)0x1a, - - // Total length: 26 bytes (0x1a, LE) - (byte)0x1a,(byte)0x00, - // PDU type: PDUTYPE_DATAPDU (0x7), PDU version: 1 (0x0010) (LE) - (byte)0x17, (byte)0x00, - // PDU source: 1004 (LE) - (byte)0xec, (byte)0x03, - }); - // Share ID, 4 bytes (LE) - buf.writeIntLE((int)state.serverShareId); - - buf.writeBytes(new byte[] { - // Padding 1 byte - (byte)0x00, - // Stream ID: STREAM_LOW (1) - (byte)0x01, - // uncompressedLength : 12 bytes (LE) - (byte)0x0c, (byte)0x00, - // pduType2: PDUTYPE2_CONTROL (20) - (byte)0x14, - // generalCompressedType: 0 - (byte)0x00, - // generalCompressedLength: 0 (LE?) - (byte)0x00, (byte)0x00, - // action: CTRLACTION_COOPERATE (4) (LE) - (byte)0x04, (byte)0x00, - // grantId: 0 (LE) - (byte)0x00, (byte)0x00, - // controlId: 0 - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - }); - /* @formatter:on */ - - buf.trimAtCursor(); - - pushDataToPad(STDOUT, buf); - } - - private void sendSynchronizePDU() { - - ByteBuffer buf = new ByteBuffer(1024, true); - /* @formatter:off */ - buf.writeBytes(new byte[] { - // MCS send data request - (byte)0x64, - // Initiator: 1004 (1001+3) - (byte)0x00, (byte)0x03, - // Channel ID: 1003 (I/O Channel) - (byte)0x03, (byte)0xeb, - // Data priority: high (0x40), segmentation: begin (0x20) | end (0x10) - (byte)0x70, - // Data length: 22 bytes (0x16, variable length field) - (byte)0x80, (byte)0x16, - - // RDP: total length: 22 bytes (LE) - (byte)0x16, (byte)0x00, - - // PDU type: PDUTYPE_DATAPDU (0x7), TS_PROTOCOL_VERSION (0x10) (LE) - (byte)0x17, (byte)0x00, - - // PDU source: 1007 (LE) - (byte)0xec, (byte)0x03, - }); - // Share ID, 4 bytes (LE) - buf.writeIntLE((int)state.serverShareId); - - buf.writeBytes(new byte[] { - // Padding: 1 byte - (byte)0x00, - // Stream ID: STREAM_LOW (1) - (byte)0x01, - // uncompressedLength : 8 bytes (LE) - (byte)0x08, (byte)0x00, - // pduType2 = PDUTYPE2_SYNCHRONIZE (31) - (byte)0x1f, - // generalCompressedType: 0 - (byte)0x00, - // generalCompressedLength: 0 (LE?) - (byte)0x00, (byte)0x00, - // messageType: SYNCMSGTYPE_SYNC (1) (LE) - (byte)0x01, (byte)0x00, - // targetUser: 0x03ea - (byte)0xea, (byte)0x03, - }); - /* @formatter:on */ - buf.trimAtCursor(); - pushDataToPad(STDOUT, buf); - } - - private void writeCapabilities(ByteBuffer buf) { - writeGeneralCS(buf); - - writeBitmapCS(buf); - - writeOrderCS(buf); - - writeBitmapCache2CS(buf); - - writeColorTableCacheCS(buf); - - writeWindowActivationCS(buf); - - writeControlCS(buf); - - writePointerCS(buf); - - writeShareCS(buf); - - writeInputCS(buf); - - writeBrushCS(buf); - - writeSoundCS(buf); - - writeFontCS(buf); - - writeOffscreenBitmapCS(buf); - - writeGlyphCacheCS(buf); - } - - private void writeBrushCS(ByteBuffer buf) { - numberCapabilities++; - buf.writeBytes(new byte[] { - // - // Brush Capability Set (8 bytes), see - // http://msdn.microsoft.com/en-us/library/cc240564.aspx - (byte)0x0f, (byte)0x00, // capability set type: CAPSTYPE_BRUSH (15, - // LE) - (byte)0x08, (byte)0x00, // length of capability set: 8 bytes (LE) - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // brushSupportLevel: - // BRUSH_DEFAULT - // (0x0, LE) - - }); - } - - private void writeInputCS(ByteBuffer buf) { - numberCapabilities++; - buf.writeBytes(new byte[] { - // - // Input Capability Set (88 bytes), see - // http://msdn.microsoft.com/en-us/library/cc240563.aspx - (byte)0x0d, - (byte)0x00, // capability set type: CAPSTYPE_INPUT (13, LE) - (byte)0x58, - (byte)0x00, // length of capability set: 88 bytes (LE) - (byte)0x35, - (byte)0x00, // inputFlags: 0x0035 (LE), INPUT_FLAG_FASTPATH_INPUT2 - // (0x20), INPUT_FLAG_VKPACKET (0x10), INPUT_FLAG_MOUSEX - // (0x4), INPUT_FLAG_SCANCODES (0x1) - (byte)0x00, - (byte)0x00, // Padding 2 bytes - (byte)0x09, - (byte)0x04, - (byte)0x00, - (byte)0x00, // keyboardLayout: "US" keyboard layout (0x000409, LE) - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, // keyboardType: unknown (LE) - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, // keyboardSubType: unknown (LE) - (byte)0x00, - (byte)0x00, - (byte)0x00, - (byte)0x00, // keyboardFunctionKey: unknown (LE) - // imeFileName: "", (64 bytes, including trailing NULL characters, UCS2) - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - - }); - } - - private void writeShareCS(ByteBuffer buf) { - numberCapabilities++; - buf.writeBytes(new byte[] { - // - // Share Capability Set (8 bytes), see - // http://msdn.microsoft.com/en-us/library/cc240570.aspx - (byte)0x09, (byte)0x00, // capability set type: CAPSTYPE_SHARE (9, LE) - (byte)0x08, (byte)0x00, // length of capability set: 8 bytes (LE) - (byte)0x00, (byte)0x00, // nodeID (must be set to 0 by client): 0 (LE) - (byte)0x00, (byte)0x00, // Padding 2 bytes (LE) - - }); - } - - private void writePointerCS(ByteBuffer buf) { - numberCapabilities++; - buf.writeBytes(new byte[] { - // - // Pointer Capability Set (10 bytes), see - // http://msdn.microsoft.com/en-us/library/cc240562.aspx - (byte)0x08, (byte)0x00, // capability set type: CAPSTYPE_POINTER (8, - // LE) - (byte)0x0a, (byte)0x00, // length of capability set: 10 bytes (LE) - (byte)0x00, (byte)0x00, // colorPointerFlag: FALSE (LE) - (byte)0x00, (byte)0x00, // colorPointerCacheSize: 0 (LE) - (byte)0x14, (byte)0x00, // pointerCacheSize: 20 (LE) - - }); - } - - private void writeControlCS(ByteBuffer buf) { - numberCapabilities++; - buf.writeBytes(new byte[] { - // - // Control Capability Set (12 bytes), see - // http://msdn.microsoft.com/en-us/library/cc240568.aspx - (byte)0x05, (byte)0x00, // capability set type: CAPSTYPE_ACTIVATION - // (7) - (byte)0x0c, (byte)0x00, // length of capability set: 12 bytes (LE) - (byte)0x00, (byte)0x00, // controlFlags (should be set to 0): 0 (LE) - (byte)0x00, (byte)0x00, // remoteDetachFlag (should be set to 0): 0 - // (LE) - (byte)0x02, (byte)0x00, // controlInterest (should be set to - // CONTROLPRIORITY_NEVER): - // CONTROLPRIORITY_NEVER (2) (LE) - (byte)0x02, (byte)0x00, // detachInterest (should be set to - // CONTROLPRIORITY_NEVER): - // CONTROLPRIORITY_NEVER (2) (LE) - - }); - } - - private void writeWindowActivationCS(ByteBuffer buf) { - numberCapabilities++; - buf.writeBytes(new byte[] { - // - // Window Activation Capability Set (12 bytes), see - // http://msdn.microsoft.com/en-us/library/cc240569.aspx - (byte)0x07, (byte)0x00, // capability set type: CAPSTYPE_ACTIVATION - // (7) (LE) - (byte)0x0c, (byte)0x00, // length of capability set: 12 bytes (LE) - (byte)0x00, (byte)0x00, // helpKeyFlag (should be set to FALSE (0)): - // FALSE (0, LE) - (byte)0x00, (byte)0x00, // helpKeyIndexFlag (should be set to FALSE - // (0)): FALSE (0, LE) - (byte)0x00, (byte)0x00, // helpExtendedKeyFlag (should be set to FALSE - // (0)): FALSE (0, LE) - (byte)0x00, (byte)0x00, // windowManagerKeyFlag (should be set to - // FALSE (0)): FALSE (0, LE) - - }); - } - - private void writeColorTableCacheCS(ByteBuffer buf) { - numberCapabilities++; - buf.writeBytes(new byte[] { - - // - // Color Table Cache Capability Set (8 bytes), see - // http://msdn.microsoft.com/en-us/library/cc241564.aspx - (byte)0x0a, (byte)0x00, // capability set type: CAPSTYPE_COLORCACHE - // (10) (LE) - (byte)0x08, (byte)0x00, // length of capability set: 8 bytes (LE) - (byte)0x06, (byte)0x00, // Color table cache size (must be ignored - // during capability exchange and is assumed - // to be 0x0006): 6 (LE) - (byte)0x00, (byte)0x00, // Padding 2 bytes - - }); - } - - private void writeBitmapCache2CS(ByteBuffer buf) { - numberCapabilities++; - buf.writeBytes(new byte[] { - // - // Bitmap Cache Rev. 2 Capability Set (40 bytes), see - // http://msdn.microsoft.com/en-us/library/cc240560.aspx - (byte)0x13, (byte)0x00, // capability set type: - // CAPSTYPE_BITMAPCACHE_REV2 (19) (LE) - (byte)0x28, (byte)0x00, // length of capability set: 40 bytes (LE) - (byte)0x00, (byte)0x00, // Cache flags: 0 (LE) - (byte)0x00, // Padding 1 byte - (byte)0x00, // Number of cell caches: 0 - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Bitmap cache0 - // cell info: 0 (LE) - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Bitmap cache1 - // cell info: 0 (LE) - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Bitmap cache2 - // cell info: 0 (LE) - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Bitmap cache3 - // cell info: 0 (LE) - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Bitmap cache4 - // cell info: 0 (LE) - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Padding 12 bytes - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Padding - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Padding - }); - } - - private void writeGeneralCS(ByteBuffer buf) { - numberCapabilities++; - buf.writeBytes(new byte[] { - // Capabilities, see - // http://msdn.microsoft.com/en-us/library/cc240486.aspx - - // - // General capability set (24 bytes), see - // http://msdn.microsoft.com/en-us/library/cc240549.aspx - (byte)0x01, (byte)0x00, // capability set type: CAPSTYPE_GENERAL (1) - // (LE) - (byte)0x18, (byte)0x00, // length of capability set: 24 bytes (LE) - (byte)0x01, (byte)0x00, // TS_OSMAJORTYPE_WINDOWS (1) (LE) - (byte)0x03, (byte)0x00, // TS_OSMINORTYPE_WINDOWS_NT (3) (LE) - (byte)0x00, (byte)0x02, // TS_CAPS_PROTOCOLVERSION (0x0200) (LE) - (byte)0x00, (byte)0x00, // Padding 2 bytes - (byte)0x00, (byte)0x00, // generalCompressionTypes: 0 (LE) - - // Extra flags: 0x040d (LE) - // FastPathOutput: (...............1) Advertiser supports fast-path - // output - // ShadowCompression: (..............0.) Advertiser NOT supports shadow - // compression - // LongLengthCredentials: (.............1..) Advertiser supports - // long-length credentials for the user name, password, or domain name - // SessionAutoreconnection: (............1...) Advertiser supports - // session auto-reconnection - // ImprovedEncryptionChecksum: (...........0....) Client and server NOT - // support improved encryption checksum - // Reserved1: (......00000.....) - // CompressedBitMapDataFlag: (.....1..........) No 8-UINT8 header is - // present for compressed bitmap data - // Reserved2: (00000...........) - (byte)0x0d, (byte)0x04, - - (byte)0x00, (byte)0x00, // updateCapabilityFlag: 0 (LE) - (byte)0x00, (byte)0x00, // remoteUnshareFlag: 0 (LE) - (byte)0x00, (byte)0x00, // generalCompressionLevel: 0 (LE) - (byte)0x00, // refreshRectSupport: FALSE (0) - (byte)0x00, // suppressOutputSupport: FALSE (0) - - }); - } - - private void writeBitmapCS(ByteBuffer buf) { - // Bitmap capability set (28 bytes), see - // http://msdn.microsoft.com/en-us/library/cc240554.aspx - - numberCapabilities++; - - // Capability set type: CAPSTYPE_BITMAP (2) (LE) - buf.writeShortLE(CAPSTYPE_BITMAP); - - // Length of capability set: 28 bytes (LE) - buf.writeShortLE(28); - - // preferredBitsPerPixel: 16 bpp (LE) - buf.writeShortLE(prefferedBitsPerPixel); - - // receive1BitPerPixel (ignored and SHOULD be set to TRUE (0x1)): TRUE (0x1) (LE) - buf.writeShortLE(1); - - // receive4BitsPerPixel (ignored and SHOULD be set to TRUE (0x1)): TRUE (0x1) (LE) - buf.writeShortLE(1); - - // receive8BitsPerPixel (ignored and SHOULD be set to TRUE (0x1)): TRUE (0x1) (LE) - buf.writeShortLE(1); - - // Desktop width and height (LE) - buf.writeShortLE(screen.getFramebufferWidth()); - buf.writeShortLE(screen.getFramebufferHeight()); - - // Padding 2 bytes - buf.writeShortLE(0); - - // desktopResizeFlag (LE) - buf.writeShortLE((desktopResize) ? 1 : 0); - - buf.writeBytes(new byte[] {(byte)0x01, (byte)0x00, // bitmapCompressionFlag (must be set to TRUE - // (0x1)): TRUE (0x1) (LE) - (byte)0x00, // highColorFlags (field is ignored and SHOULD be set to - // zero): 0 - (byte)0x01, // drawingFlags: 0x1 TODO: padding, why 0x1 ??? - (byte)0x01, (byte)0x00, // multipleRectangleSupport: TRUE (LE) - (byte)0x00, (byte)0x00, // Padding 2 bytes - - }); - } - - private void writeOrderCS(ByteBuffer buf) { - numberCapabilities++; - buf.writeBytes(new byte[] { - // - // Order Capability Set (88 bytes), see - // http://msdn.microsoft.com/en-us/library/cc240556.aspx - (byte)0x03, - (byte)0x00, // capability set type: CAPSTYPE_ORDER (3) (LE) - (byte)0x58, - (byte)0x00, // length of capability set: 88 bytes (LE) - // terminalDescriptor = "" (16 bytes, UCS2) - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // pad4octetsA - (byte)0x01, (byte)0x00, // desktopSaveXGranularity (ignored): 1 (LE) - (byte)0x14, (byte)0x00, // desktopSaveYGranularity (ignored): 20 (LE) - (byte)0x00, (byte)0x00, // pad2octetsA (ignored) - (byte)0x01, (byte)0x00, // maximumOrderLevel: ORD_LEVEL_1_ORDERS (1) - (byte)0x00, (byte)0x00, // number of fonts (ignored): 0 - (byte)0x4a, (byte)0x00, // orderFlags = 0x004a (LE), - // SOLIDPATTERNBRUSHONLY (0x40), - // ZEROBOUNDSDELTASSUPPORT (0x8, MUST), - // NEGOTIATEORDERSUPPORT (0x2, MUST) - // Order support: 32 bytes (no primary drawing orders are supported, so - // this array MUST be initialized to all zeros, use 0x01 for TRUE). - (byte)0x00, // TS_NEG_DSTBLT_INDEX: FALSE - (byte)0x00, // TS_NEG_PATBLT_INDEX: FALSE - (byte)0x00, // TS_NEG_SCRBLT_INDEX: FALSE - (byte)0x00, // TS_NEG_MEMBLT_INDEX: FALSE - (byte)0x00, // TS_NEG_MEM3BLT_INDEX: FALSE - (byte)0x00, // TS_NEG_ATEXTOUT_INDEX: FALSE - (byte)0x00, // TS_NEG_AEXTTEXTOUT_INDEX: FALSE - (byte)0x00, // TS_NEG_DRAWNINEGRID_INDEX: FALSE - (byte)0x00, // TS_NEG_LINETO_INDEX: FALSE - (byte)0x00, // TS_NEG_MULTI_DRAWNINEGRID_INDEX: FALSE - (byte)0x00, // TS_NEG_OPAQUERECT_INDEX: FALSE - (byte)0x00, // TS_NEG_SAVEBITMAP_INDEX: FALSE - (byte)0x00, // TS_NEG_WTEXTOUT_INDEX: FALSE - (byte)0x00, // TS_NEG_MEMBLT_R2_INDEX: FALSE - (byte)0x00, // TS_NEG_MEM3BLT_R2_INDEX: FALSE - (byte)0x00, // TS_NEG_MULTIDSTBLT_INDEX: FALSE - (byte)0x00, // TS_NEG_MULTIPATBLT_INDEX: FALSE - (byte)0x00, // TS_NEG_MULTISCRBLT_INDEX: FALSE - (byte)0x00, // TS_NEG_MULTIOPAQUERECT_INDEX: FALSE - (byte)0x00, // TS_NEG_FAST_INDEX_INDEX: FALSE - (byte)0x00, // TS_NEG_POLYGON_SC_INDEX: FALSE - (byte)0x00, // TS_NEG_POLYGON_CB_INDEX: FALSE - (byte)0x00, // TS_NEG_POLYLINE_INDEX: TRUE - (byte)0x00, // Unused: 0 - (byte)0x00, // TS_NEG_FAST_GLYPH_INDEX: FALSE - (byte)0x00, // TS_NEG_ELLIPSE_SC_INDEX: FALSE - (byte)0x00, // TS_NEG_ELLIPSE_CB_INDEX: FALSE - (byte)0x00, // TS_NEG_INDEX_INDEX: FALSE - (byte)0x00, // TS_NEG_WEXTTEXTOUT_INDEX: FALSE - (byte)0x00, // TS_NEG_WLONGTEXTOUT_INDEX: FALSE - (byte)0x00, // TS_NEG_WLONGEXTTEXTOUT_INDEX: FALSE - (byte)0x00, // Unused: 0 - (byte)0x00, (byte)0x00, // Text flags (ignored): 0 (LE) - (byte)0x00, (byte)0x00, // Order support extra flags: 0 (LE) - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Padding 4 bytes - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Desktop save size - // (ignored): 0 - // (assumed to be - // 230400 bytes - // (480*480, - // 0x38400, LE)) - (byte)0x00, (byte)0x00, // Padding 2 bytes - (byte)0x00, (byte)0x00, // Padding 2 bytes - (byte)0xe4, (byte)0x04, // Text ANSI Code Page: 1252, ANSI - Latin I - // (0x04e4, LE) - (byte)0x00, (byte)0x00, // Padding 2 bytes - - }); - } - - private void writeSoundCS(ByteBuffer buf) { - numberCapabilities++; - buf.writeBytes(new byte[] { - // - // Sound Capability Set (8 bytes), see - // http://msdn.microsoft.com/en-us/library/cc240552.aspx - (byte)0x0c, (byte)0x00, // capability set type: CAPSTYPE_SOUND (12, - // LE) - (byte)0x08, (byte)0x00, // length of capability set: 8 bytes (LE) - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // soundFlags: - // 0x0000 (LE) // - // SOUND_FLAG_BEEPS - // (0x1) - - }); - } - - private void writeFontCS(ByteBuffer buf) { - numberCapabilities++; - buf.writeBytes(new byte[] { - // - // Font Capability Set (8 bytes), see - // http://msdn.microsoft.com/en-us/library/cc240571.aspx - (byte)0x0e, (byte)0x00, (byte)0x08, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, - - }); - } - - private void writeOffscreenBitmapCS(ByteBuffer buf) { - numberCapabilities++; - buf.writeBytes(new byte[] { - // - // Offscreen Bitmap Cache Capability Set (12 bytes), see - // http://msdn.microsoft.com/en-us/library/cc240550.aspx - (byte)0x11, (byte)0x00, // capability set type: - // CAPSTYPE_OFFSCREENCACHE (17, LE) - (byte)0x0c, (byte)0x00, // length of capability set: 12 bytes (LE) - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // offscreenSupportLevel: - // FALSE (LE) - (byte)0x00, (byte)0x00, // offscreenCacheSize: 0 (LE) - (byte)0x00, (byte)0x00, // offscreenCacheEntries: 0 (LE) - - }); - } - - private void writeGlyphCacheCS(ByteBuffer buf) { - numberCapabilities++; - buf.writeBytes(new byte[] { - // - // Glyph Cache Capability Set (52 bytes), see - // http://msdn.microsoft.com/en-us/library/cc240565.aspx - (byte)0x10, (byte)0x00, // capability set type: - // CAPSTYPE_OFFSCREENCACHE (16, LE) - (byte)0x34, (byte)0x00, // length of capability set: 52 bytes (LE) - // Glyph Cache (40 bytes) - (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) - (byte)0x04, (byte)0x00, // CacheMaximumCellSize: 4 (LE) - (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) - (byte)0x04, (byte)0x00, // CacheMaximumCellSize: 4 (LE) - (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) - (byte)0x08, (byte)0x00, // CacheMaximumCellSize: 4 (LE) - (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) - (byte)0x08, (byte)0x00, // CacheMaximumCellSize: 4 (LE) - (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) - (byte)0x10, (byte)0x00, // CacheMaximumCellSize: 4 (LE) - (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) - (byte)0x20, (byte)0x00, // CacheMaximumCellSize: 4 (LE) - (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) - (byte)0x40, (byte)0x00, // CacheMaximumCellSize: 4 (LE) - (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) - (byte)0x80, (byte)0x00, // CacheMaximumCellSize: 4 (LE) - (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) - (byte)0x00, (byte)0x01, // CacheMaximumCellSize: 4 (LE) - (byte)0x40, (byte)0x00, // CacheEntries: 64 (LE) - (byte)0x00, (byte)0x08, // CacheMaximumCellSize: 2048 (LE) - // FragCache - (byte)0x00, (byte)0x01, // CacheEntries: 256 (LE) - (byte)0x00, (byte)0x01, // CacheMaximumCellSize: 256 (LE) - // - (byte)0x00, (byte)0x00, // GlyphSupportLevel: GLYPH_SUPPORT_NONE (0x0, - // LE) - (byte)0x00, (byte)0x00, // Padding 2 bytes - }); - } - - /** - * Example. - */ - public static void main(String args[]) { - // System.setProperty("streamer.Link.debug", "true"); - System.setProperty("streamer.Element.debug", "true"); - // System.setProperty("streamer.Pipeline.debug", "true"); - - /* @formatter:off */ - byte[] packet = new byte[] { - // MCS Send Data Request - (byte)0x64, - - // Initiator: 1004 (1001+3) - (byte)0x00, (byte)0x03, - - // Channel ID: 1003 (I/O channel) - (byte)0x03, (byte)0xeb, - - // Data priority: high (0x40), segmentation: begin (0x20) | end (0x10) - (byte)0x70, - - // User data length: 432 bytes (0x1b0, variable length field) - (byte)0x81, (byte)0xb0, - - // Total length: 432 bytes (0x1b0, LE) - (byte)0xb0, (byte)0x01, - - // PDU type: Confirm Active PDU (0x3), TS_PROTOCOL_VERSION (0x10) (LE) - (byte)0x13, (byte)0x00, - - // PDU source: 1004 (LE) - (byte)0xec, (byte)0x03, - - // Share ID: 0x000103ea (LE) - (byte)0xea, (byte)0x03, (byte)0x01, (byte)0x00, - - // Originator ID: 1002 (LE) - (byte)0xea, (byte)0x03, - - // Length of source descriptor: 6 bytes (including NULL character) (LE) - (byte)0x06, (byte)0x00, - - // Length of combined capabilities: 410 bytes (LE) - (byte)0x9a, (byte)0x01, - - // Source descriptor: "MSTSC" ??? - (byte)0x4d, (byte)0x53, (byte)0x54, (byte)0x53, (byte)0x43, (byte)0x00, - - // Number of capabilities: 15 (LE) - (byte)0x0f, (byte)0x00, - - // Padding 2 bytes - (byte)0x00, (byte)0x00, - - // Capabilities, see http://msdn.microsoft.com/en-us/library/cc240486.aspx - - // - // General capability set (24 bytes), see http://msdn.microsoft.com/en-us/library/cc240549.aspx - (byte)0x01, (byte)0x00, // capability set type: CAPSTYPE_GENERAL (1) (LE) - (byte)0x18, (byte)0x00, // length of capability set: 24 bytes (LE) - (byte)0x01, (byte)0x00, // TS_OSMAJORTYPE_WINDOWS (1) (LE) - (byte)0x03, (byte)0x00, // TS_OSMINORTYPE_WINDOWS_NT (3) (LE) - (byte)0x00, (byte)0x02, // TS_CAPS_PROTOCOLVERSION (0x0200) (LE) - (byte)0x00, (byte)0x00, // Padding 2 bytes - (byte)0x00, (byte)0x00, // generalCompressionTypes: 0 (LE) - - // Extra flags: 0x040d (LE) -// FastPathOutput: (...............1) Advertiser supports fast-path output -// ShadowCompression: (..............0.) Advertiser NOT supports shadow compression -// LongLengthCredentials: (.............1..) Advertiser supports long-length credentials for the user name, password, or domain name -// SessionAutoreconnection: (............1...) Advertiser supports session auto-reconnection -// ImprovedEncryptionChecksum: (...........0....) Client and server NOT support improved encryption checksum -// Reserved1: (......00000.....) -// CompressedBitMapDataFlag: (.....1..........) No 8-UINT8 header is present for compressed bitmap data -// Reserved2: (00000...........) - (byte)0x0d, (byte)0x04, - - (byte)0x00, (byte)0x00, // updateCapabilityFlag: 0 (LE) - (byte)0x00, (byte)0x00, // remoteUnshareFlag: 0 (LE) - (byte)0x00, (byte)0x00, // generalCompressionLevel: 0 (LE) - (byte)0x00, // refreshRectSupport: FALSE (0) - (byte)0x00, // suppressOutputSupport: FALSE (0) - - // - // Bitmap capability set (28 bytes), see http://msdn.microsoft.com/en-us/library/cc240554.aspx - (byte)0x02, (byte)0x00, // capability set type: CAPSTYPE_BITMAP (2) (LE) - (byte)0x1c, (byte)0x00, // length of capability set: 28 bytes (LE) - (byte)0x10, (byte)0x00, // preferredBitsPerPixel: 16 bpp (LE) - (byte)0x01, (byte)0x00, // receive1BitPerPixel (ignored and SHOULD be set to TRUE (0x1)): TRUE (0x1) (LE) - (byte)0x01, (byte)0x00, // receive4BitsPerPixel (ignored and SHOULD be set to TRUE (0x1)): TRUE (0x1) (LE) - (byte)0x01, (byte)0x00, // receive8BitsPerPixel (ignored and SHOULD be set to TRUE (0x1)): TRUE (0x1) (LE) - (byte)0x00, (byte)0x04, // desktopWidth = 1024 pixels (LE) - (byte)0x00, (byte)0x03, // desktopHeight = 768 pixels (LE) - (byte)0x00, (byte)0x00, // Padding 2 bytes - (byte)0x00, (byte)0x00, // desktopResizeFlag: FALSE (0x0) (LE) - (byte)0x01, (byte)0x00, // bitmapCompressionFlag (must be set to TRUE (0x1)): TRUE (0x1) (LE) - (byte)0x00, // highColorFlags (field is ignored and SHOULD be set to zero): 0 - (byte)0x01, // drawingFlags: 0x1 TODO: padding, why 0x1 ??? - (byte)0x01, (byte)0x00, // multipleRectangleSupport: TRUE (LE) - (byte)0x00, (byte)0x00, // Padding 2 bytes - - // - // Order Capability Set (88 bytes), see http://msdn.microsoft.com/en-us/library/cc240556.aspx - (byte)0x03, (byte)0x00, // capability set type: CAPSTYPE_ORDER (3) (LE) - (byte)0x58, (byte)0x00, // length of capability set: 88 bytes (LE) - // terminalDescriptor = "" (16 bytes, UCS2) - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // pad4octetsA - (byte)0x01, (byte)0x00, // desktopSaveXGranularity (ignored): 1 (LE) - (byte)0x14, (byte)0x00, // desktopSaveYGranularity (ignored): 20 (LE) - (byte)0x00, (byte)0x00, // pad2octetsA (ignored) - (byte)0x01, (byte)0x00, // maximumOrderLevel: ORD_LEVEL_1_ORDERS (1) - (byte)0x00, (byte)0x00, // number of fonts (ignored): 0 - (byte)0x4a, (byte)0x00, // orderFlags = 0x004a (LE), SOLIDPATTERNBRUSHONLY (0x40), ZEROBOUNDSDELTASSUPPORT (0x8, MUST), NEGOTIATEORDERSUPPORT (0x2, MUST) - // Order support: 32 bytes (no primary drawing orders are supported, so this array MUST be initialized to all zeros, use 0x01 for TRUE). - (byte)0x00, // TS_NEG_DSTBLT_INDEX: FALSE - (byte)0x00, // TS_NEG_PATBLT_INDEX: FALSE - (byte)0x00, // TS_NEG_SCRBLT_INDEX: FALSE - (byte)0x00, // TS_NEG_MEMBLT_INDEX: FALSE - (byte)0x00, // TS_NEG_MEM3BLT_INDEX: FALSE - (byte)0x00, // TS_NEG_ATEXTOUT_INDEX: FALSE - (byte)0x00, // TS_NEG_AEXTTEXTOUT_INDEX: FALSE - (byte)0x00, // TS_NEG_DRAWNINEGRID_INDEX: FALSE - (byte)0x00, // TS_NEG_LINETO_INDEX: FALSE - (byte)0x00, // TS_NEG_MULTI_DRAWNINEGRID_INDEX: FALSE - (byte)0x00, // TS_NEG_OPAQUERECT_INDEX: FALSE - (byte)0x00, // TS_NEG_SAVEBITMAP_INDEX: FALSE - (byte)0x00, // TS_NEG_WTEXTOUT_INDEX: FALSE - (byte)0x00, // TS_NEG_MEMBLT_R2_INDEX: FALSE - (byte)0x00, // TS_NEG_MEM3BLT_R2_INDEX: FALSE - (byte)0x00, // TS_NEG_MULTIDSTBLT_INDEX: FALSE - (byte)0x00, // TS_NEG_MULTIPATBLT_INDEX: FALSE - (byte)0x00, // TS_NEG_MULTISCRBLT_INDEX: FALSE - (byte)0x00, // TS_NEG_MULTIOPAQUERECT_INDEX: FALSE - (byte)0x00, // TS_NEG_FAST_INDEX_INDEX: FALSE - (byte)0x00, // TS_NEG_POLYGON_SC_INDEX: FALSE - (byte)0x00, // TS_NEG_POLYGON_CB_INDEX: FALSE - (byte)0x00, // TS_NEG_POLYLINE_INDEX: TRUE - (byte)0x00, // Unused: 0 - (byte)0x00, // TS_NEG_FAST_GLYPH_INDEX: FALSE - (byte)0x00, // TS_NEG_ELLIPSE_SC_INDEX: FALSE - (byte)0x00, // TS_NEG_ELLIPSE_CB_INDEX: FALSE - (byte)0x00, // TS_NEG_INDEX_INDEX: FALSE - (byte)0x00, // TS_NEG_WEXTTEXTOUT_INDEX: FALSE - (byte)0x00, // TS_NEG_WLONGTEXTOUT_INDEX: FALSE - (byte)0x00, // TS_NEG_WLONGEXTTEXTOUT_INDEX: FALSE - (byte)0x00, // Unused: 0 - (byte)0x00, (byte)0x00, // Text flags (ignored): 0 (LE) - (byte)0x00, (byte)0x00, // Order support extra flags: 0 (LE) - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Padding 4 bytes - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Desktop save size (ignored): 0 (assumed to be 230400 bytes (480*480, 0x38400, LE)) - (byte)0x00, (byte)0x00, // Padding 2 bytes - (byte)0x00, (byte)0x00, // Padding 2 bytes - (byte)0xe4, (byte)0x04, // Text ANSI Code Page: 1252, ANSI - Latin I (0x04e4, LE) - (byte)0x00, (byte)0x00, // Padding 2 bytes - - // - // Bitmap Cache Rev. 2 Capability Set (40 bytes), see http://msdn.microsoft.com/en-us/library/cc240560.aspx - (byte)0x13, (byte)0x00, // capability set type: CAPSTYPE_BITMAPCACHE_REV2 (19) (LE) - (byte)0x28, (byte)0x00, // length of capability set: 40 bytes (LE) - (byte)0x00, (byte)0x00, // Cache flags: 0 (LE) - (byte)0x00, // Padding 1 byte - (byte)0x00, // Number of cell caches: 0 - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Bitmap cache0 cell info: 0 (LE) - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Bitmap cache1 cell info: 0 (LE) - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Bitmap cache2 cell info: 0 (LE) - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Bitmap cache3 cell info: 0 (LE) - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Bitmap cache4 cell info: 0 (LE) - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Padding 12 bytes - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Padding - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Padding - - // - // Color Table Cache Capability Set (8 bytes), see http://msdn.microsoft.com/en-us/library/cc241564.aspx - (byte)0x0a, (byte)0x00, // capability set type: CAPSTYPE_COLORCACHE (10) (LE) - (byte)0x08, (byte)0x00, // length of capability set: 8 bytes (LE) - (byte)0x06, (byte)0x00, // Color table cache size (must be ignored during capability exchange and is assumed to be 0x0006): 6 (LE) - (byte)0x00, (byte)0x00, // Padding 2 bytes - - // - // Window Activation Capability Set (12 bytes), see http://msdn.microsoft.com/en-us/library/cc240569.aspx - (byte)0x07, (byte)0x00, // capability set type: CAPSTYPE_ACTIVATION (7) (LE) - (byte)0x0c, (byte)0x00, // length of capability set: 12 bytes (LE) - (byte)0x00, (byte)0x00, // helpKeyFlag (should be set to FALSE (0)): FALSE (0, LE) - (byte)0x00, (byte)0x00, // helpKeyIndexFlag (should be set to FALSE (0)): FALSE (0, LE) - (byte)0x00, (byte)0x00, // helpExtendedKeyFlag (should be set to FALSE (0)): FALSE (0, LE) - (byte)0x00, (byte)0x00, // windowManagerKeyFlag (should be set to FALSE (0)): FALSE (0, LE) - - // - // Control Capability Set (12 bytes), see http://msdn.microsoft.com/en-us/library/cc240568.aspx - (byte)0x05, (byte)0x00, // capability set type: CAPSTYPE_ACTIVATION (7) - (byte)0x0c, (byte)0x00, // length of capability set: 12 bytes (LE) - (byte)0x00, (byte)0x00, // controlFlags (should be set to 0): 0 (LE) - (byte)0x00, (byte)0x00, // remoteDetachFlag (should be set to 0): 0 (LE) - (byte)0x02, (byte)0x00, // controlInterest (should be set to CONTROLPRIORITY_NEVER): CONTROLPRIORITY_NEVER (2) (LE) - (byte)0x02, (byte)0x00, // detachInterest (should be set to CONTROLPRIORITY_NEVER): CONTROLPRIORITY_NEVER (2) (LE) - - // - // Pointer Capability Set (10 bytes), see http://msdn.microsoft.com/en-us/library/cc240562.aspx - (byte)0x08, (byte)0x00, // capability set type: CAPSTYPE_POINTER (8, LE) - (byte)0x0a, (byte)0x00, // length of capability set: 10 bytes (LE) - (byte)0x00, (byte)0x00, // colorPointerFlag: FALSE (LE) - (byte)0x00, (byte)0x00, // colorPointerCacheSize: 0 (LE) - (byte)0x14, (byte)0x00, // pointerCacheSize: 20 (LE) - - // - // Share Capability Set (8 bytes), see http://msdn.microsoft.com/en-us/library/cc240570.aspx - (byte)0x09, (byte)0x00, // capability set type: CAPSTYPE_SHARE (9, LE) - (byte)0x08, (byte)0x00, // length of capability set: 8 bytes (LE) - (byte)0x00, (byte)0x00, // nodeID (must be set to 0 by client): 0 (LE) - (byte)0x00, (byte)0x00, // Padding 2 bytes (LE) - - // - // Input Capability Set (88 bytes), see http://msdn.microsoft.com/en-us/library/cc240563.aspx - (byte)0x0d, (byte)0x00, // capability set type: CAPSTYPE_INPUT (13, LE) - (byte)0x58, (byte)0x00, // length of capability set: 88 bytes (LE) - (byte)0x35, (byte)0x00, // inputFlags: 0x0035 (LE), INPUT_FLAG_FASTPATH_INPUT2 (0x20), INPUT_FLAG_VKPACKET (0x10), INPUT_FLAG_MOUSEX (0x4), INPUT_FLAG_SCANCODES (0x1) - (byte)0x00, (byte)0x00, // Padding 2 bytes - (byte)0x09, (byte)0x04, (byte)0x00, (byte)0x00, // keyboardLayout: "US" keyboard layout (0x000409, LE) - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // keyboardType: unknown (LE) - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // keyboardSubType: unknown (LE) - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // keyboardFunctionKey: unknown (LE) - // imeFileName: "", (64 bytes, including trailing NULL characters, UCS2) - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - - // - // Brush Capability Set (8 bytes), see http://msdn.microsoft.com/en-us/library/cc240564.aspx - (byte)0x0f, (byte)0x00, // capability set type: CAPSTYPE_BRUSH (15, LE) - (byte)0x08, (byte)0x00, // length of capability set: 8 bytes (LE) - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // brushSupportLevel: BRUSH_DEFAULT (0x0, LE) - - // - // Sound Capability Set (8 bytes), see http://msdn.microsoft.com/en-us/library/cc240552.aspx - (byte)0x0c, (byte)0x00, // capability set type: CAPSTYPE_SOUND (12, LE) - (byte)0x08, (byte)0x00, // length of capability set: 8 bytes (LE) - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // soundFlags: 0x0000 (LE) // SOUND_FLAG_BEEPS (0x1) - - // - // Font Capability Set (8 bytes), see http://msdn.microsoft.com/en-us/library/cc240571.aspx - (byte)0x0e, (byte)0x00, - (byte)0x08, (byte)0x00, - (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, - - // - // Offscreen Bitmap Cache Capability Set (12 bytes), see http://msdn.microsoft.com/en-us/library/cc240550.aspx - (byte)0x11, (byte)0x00, // capability set type: CAPSTYPE_OFFSCREENCACHE (17, LE) - (byte)0x0c, (byte)0x00, // length of capability set: 12 bytes (LE) - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // offscreenSupportLevel: FALSE (LE) - (byte)0x00, (byte)0x00, // offscreenCacheSize: 0 (LE) - (byte)0x00, (byte)0x00, // offscreenCacheEntries: 0 (LE) - - // - // Glyph Cache Capability Set (52 bytes), see http://msdn.microsoft.com/en-us/library/cc240565.aspx - (byte)0x10, (byte)0x00, // capability set type: CAPSTYPE_OFFSCREENCACHE (16, LE) - (byte)0x34, (byte)0x00, // length of capability set: 52 bytes (LE) - // Glyph Cache (40 bytes) - (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) - (byte)0x04, (byte)0x00, // CacheMaximumCellSize: 4 (LE) - (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) - (byte)0x04, (byte)0x00, // CacheMaximumCellSize: 4 (LE) - (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) - (byte)0x08, (byte)0x00, // CacheMaximumCellSize: 4 (LE) - (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) - (byte)0x08, (byte)0x00, // CacheMaximumCellSize: 4 (LE) - (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) - (byte)0x10, (byte)0x00, // CacheMaximumCellSize: 4 (LE) - (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) - (byte)0x20, (byte)0x00, // CacheMaximumCellSize: 4 (LE) - (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) - (byte)0x40, (byte)0x00, // CacheMaximumCellSize: 4 (LE) - (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) - (byte)0x80, (byte)0x00, // CacheMaximumCellSize: 4 (LE) - (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) - (byte)0x00, (byte)0x01, // CacheMaximumCellSize: 4 (LE) - (byte)0x40, (byte)0x00, // CacheEntries: 64 (LE) - (byte)0x00, (byte)0x08, // CacheMaximumCellSize: 2048 (LE) - // FragCache - (byte)0x00, (byte)0x01, // CacheEntries: 256 (LE) - (byte)0x00, (byte)0x01, // CacheMaximumCellSize: 256 (LE) - // - (byte)0x00, (byte)0x00, // GlyphSupportLevel: GLYPH_SUPPORT_NONE (0x0, LE) - (byte)0x00, (byte)0x00, // Padding 2 bytes - }; - /* @formatter:on */ - - RdpState rdpState = new RdpState(); - ScreenDescription screenDescription = new ScreenDescription(); - screenDescription.setFramebufferSize(1024, 768); - - rdpState.serverShareId = 0x000103ea; - - MockSource source = new MockSource("source", ByteBuffer.convertByteArraysToByteBuffers(new byte[] {})); - Element confirm_active = new ClientConfirmActivePDU("confirm_active", screenDescription, rdpState); - Element sink = new MockSink("sink", ByteBuffer.convertByteArraysToByteBuffers(packet)); - - Pipeline pipeline = new PipelineImpl("test"); - pipeline.add(source, confirm_active, sink); - pipeline.link("source", "confirm_active", "sink"); - pipeline.runMainLoop("source", STDOUT, false, false); - } - -} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientInfoPDU.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientInfoPDU.java deleted file mode 100644 index 12692840906..00000000000 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientInfoPDU.java +++ /dev/null @@ -1,455 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package rdpclient; - -import streamer.ByteBuffer; -import streamer.Element; -import streamer.Link; -import streamer.MockSink; -import streamer.MockSource; -import streamer.OneTimeSwitch; -import streamer.Pipeline; -import streamer.PipelineImpl; - -/** - * @see http://msdn.microsoft.com/en-us/library/cc240475.aspx - */ -public class ClientInfoPDU extends OneTimeSwitch { - - public static final int INFO_MOUSE = 0x1; - public static final int INFO_DISABLECTRLALTDEL = 0x2; - public static final int INFO_UNICODE = 0x10; - - public static final int INFO_MAXIMIZESHELL = 0x20; - public static final int INFO_LOGONNOTIFY = 0x40; - public static final int INFO_ENABLEWINDOWSKEY = 0x100; - public static final int INFO_MOUSE_HAS_WHEEL = 0x00020000; - public static final int INFO_NOAUDIOPLAYBACK = 0x00080000; - - public static final int PERF_DISABLE_WALLPAPER = 0x1; - public static final int PERF_DISABLE_FULLWINDOWDRAG = 0x2; - public static final int PERF_DISABLE_MENUANIMATIONS = 0x4; - - protected byte[] userName = "".getBytes(RdpConstants.CHARSET_16); - protected byte[] password = "".getBytes(RdpConstants.CHARSET_16); // No effect - protected byte[] alternateShell = "".getBytes(RdpConstants.CHARSET_16); - protected byte[] domain = "".getBytes(RdpConstants.CHARSET_16); - protected byte[] workingDir = "".getBytes(RdpConstants.CHARSET_16); - protected byte[] clientAddress = "192.168.0.100".getBytes(RdpConstants.CHARSET_16); - protected byte[] clientDir = "C:\\Windows\\System32\\mstscax.dll".getBytes(RdpConstants.CHARSET_16); - - protected String standardTimeZoneName = "EET, Standard Time"; - protected String daylightTimeZoneName = "EET, Summer Time"; - protected int standardTimeZoneBias = 0; /* in minutes */ - protected int daylightTimeZoneBias = 60; /* in minutes */ - - public ClientInfoPDU(String id, String userName) { - super(id); - this.userName = userName.getBytes(RdpConstants.CHARSET_16); - } - - @Override - protected void handleOneTimeData(ByteBuffer buf, Link link) { - if (buf == null) - return; - - throw new RuntimeException("Unexpected packet: " + buf + "."); - } - - @Override - protected void onStart() { - super.onStart(); - - // Length of packet - ByteBuffer buf = new ByteBuffer(1024, true); - - // MCS Send Data Request PDU - buf.writeByte(0x64); - - // Initiator: 0x03 + 1001 = 1004 - buf.writeShort(3); - - // Channel ID: 1003 - buf.writeShort(1003); - - // Data priority: high, segmentation: begin | end (0x40 | 0x20 | 0x10 = 0x70) - buf.writeByte(0x70); - - // User data length: (variable length field) - int length = 224 + userName.length + password.length + alternateShell.length + domain.length + workingDir.length + clientAddress.length + clientDir.length; - buf.writeShort(length | 0x8000); - - // Flags: SEC_INFO_PKT (0x4000) - buf.writeShort(0x4000); - - // TS_SECURITY_HEADER::flagsHi - ignored - buf.writeShort(0x0000); - - // Codepage: 0 (UNKNOWN, LE) (use 0x04090409 (1033,1033) for EN_US) - buf.writeIntLE(0x0000); - - // Flags - buf.writeIntLE(INFO_MOUSE | INFO_DISABLECTRLALTDEL | INFO_UNICODE | INFO_MAXIMIZESHELL | INFO_LOGONNOTIFY | INFO_ENABLEWINDOWSKEY | INFO_MOUSE_HAS_WHEEL | - INFO_NOAUDIOPLAYBACK); - - // - // Lengths - // - - // cbDomain length: 0 bytes (LE) (NOT including size of mandatory NULL terminator) - buf.writeShortLE(domain.length); - - // cbUserName length: 16 bytes (0x10, LE) (NOT including size of mandatory NULL terminator) - buf.writeShortLE(userName.length); - - // cbPassword length: (LE) (NOT including size of mandatory NULL terminator) - buf.writeShortLE(password.length); - - // cbAlternateShell: (LE) (NOT including size of mandatory NULL terminator) - buf.writeShortLE(alternateShell.length); - - // cbWorkingDir: (LE) (NOT including size of mandatory NULL terminator) - buf.writeShortLE(workingDir.length); - - // - // Values - // - - // Domain: (UCS2), see cbDomain - buf.writeBytes(domain); - buf.writeShort(0); - - // User name: (UCS2), see cbUserName - buf.writeBytes(userName); - buf.writeShort(0); - - // Password: (UCS2), see cbPassword - buf.writeBytes(password); - buf.writeShort(0); - - // Alternate shell: (UCS2), see cbAlternateShell - buf.writeBytes(alternateShell); - buf.writeShort(0); - - // Working directory: (UCS2), see cbWorkingDir - buf.writeBytes(workingDir); - buf.writeShort(0); - - // Client address family: 2 (AF_INET, LE) - buf.writeShortLE(2); - - // cbClientAddress: ( LE) (including the size of the mandatory NULL terminator) - buf.writeShortLE(clientAddress.length + 2); - - // Client address: (UCS2) - buf.writeBytes(clientAddress); - buf.writeShort(0); - - // cbClientDir: 64 bytes (0x40, LE) (including the size of the mandatory NULL terminator) - buf.writeShortLE(clientDir.length + 2); - - // Client directory: (UCS2) - buf.writeBytes(clientDir); - buf.writeShort(0); - - // - // Client time zone: - // - - // Bias: 0 minutes (LE) - buf.writeIntLE(0); - - // Standard name: "EET, Standard Time" (fixed string: 64 bytes, UCS2) - buf.writeFixedString(62, standardTimeZoneName, RdpConstants.CHARSET_16); - buf.writeShort(0); - - // Standard date - buf.writeBytes(new byte[] { - // wYear: 0 (LE) - (byte)0x00, (byte)0x00, - // wMonth: unknown (LE) - (byte)0x00, (byte)0x00, - // wDayOfWeek: Sunday (LE) - (byte)0x00, (byte)0x00, - // wDay: unknown (LE) - (byte)0x00, (byte)0x00, - // wHour: 0 (LE) - (byte)0x00, (byte)0x00, - // wMinute: 0 (LE) - (byte)0x00, (byte)0x00, - // wSecond: 0 (LE) - (byte)0x00, (byte)0x00, - // wMilliseconds: 0 - (byte)0x00, (byte)0x00, - - }); - - // StandardBias: 0 minutes (LE) - buf.writeIntLE(standardTimeZoneBias); - - // Daylight name: "EET, Summer Time" (fixed string: 64 bytes, UCS2) - buf.writeFixedString(62, daylightTimeZoneName, RdpConstants.CHARSET_16); - buf.writeShort(0); - - // Daylight date - buf.writeBytes(new byte[] { - // wYear: 0 (LE) - (byte)0x00, (byte)0x00, - // wMonth: unknown (LE) - (byte)0x00, (byte)0x00, - // wDayOfWeek: Sunday (LE) - (byte)0x00, (byte)0x00, - // wDay: unknown (LE) - (byte)0x00, (byte)0x00, - // wHour: 0 (LE) - (byte)0x00, (byte)0x00, - // wMinute: 0 (LE) - (byte)0x00, (byte)0x00, - // wSecond: 0 (LE) - (byte)0x00, (byte)0x00, - // wMilliseconds: 0 - (byte)0x00, (byte)0x00, - - }); - - // Daylight bias: 60 minutes (LE) - buf.writeIntLE(daylightTimeZoneBias); - - // Client session ID: 0x00000000 (LE) - buf.writeIntLE(0); - - // Performance flags: 0x7 (LE) = PERF_DISABLE_WALLPAPER (0x1), PERF_DISABLE_FULLWINDOWDRAG (0x2), PERF_DISABLE_MENUANIMATIONS (0x4) - buf.writeIntLE(PERF_DISABLE_WALLPAPER | PERF_DISABLE_FULLWINDOWDRAG | PERF_DISABLE_MENUANIMATIONS); - - // cbAutoReconnectCookie: 0 bytes (LE) - buf.writeShortLE(0); - - // Trim buffer to actual length of data written - buf.length = buf.cursor; - - pushDataToOTOut(buf); - - switchOff(); - } - - /** - * Example. - */ - public static void main(String args[]) { - // System.setProperty("streamer.Link.debug", "true"); - System.setProperty("streamer.Element.debug", "true"); - // System.setProperty("streamer.Pipeline.debug", "true"); - - /* @formatter:off */ - byte[] packet = new byte[] { - - // TPKT - (byte) 0x03, (byte) 0x00, - - // TPKT length: 343 bytes - (byte) 0x01, (byte) 0x57, - - // X224 Data PDU - (byte) 0x02, (byte) 0xf0, (byte) 0x80, - - - // MCS Send Data Request PDU - (byte) 0x64, - - // Initiator: 0x03 + 1001 = 1004 - (byte) 0x00, (byte) 0x03, - - // Channel ID: 1003 (IO Channel) - (byte) 0x03, (byte) 0xeb, - - // Data priority: high, segmentation: begin | end (0x40 | 0x20 | 0x10 = 0x70) - (byte) 0x70, - - // User data length: 328 (0x148) bytes, variable length field - (byte) 0x81, (byte) 0x48, - - // Flags: SEC_INFO_PKT (0x4000) - (byte) 0x40, (byte) 0x00, - - // TS_SECURITY_HEADER::flagsHi - ignored - (byte) 0x00, (byte) 0x00, - - // Codepage: 0 (UNKNOWN, LE) (use 0x04090409 (1033,1033) for EN_US) - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - - // Flags: 0xa0173 (LE), INFO_MOUSE (0x1), INFO_DISABLECTRLALTDEL (0x2), INFO_UNICODE (0x10), - // INFO_MAXIMIZESHELL (0x20), INFO_LOGONNOTIFY (0x40), INFO_ENABLEWINDOWSKEY (0x100), - // INFO_MOUSE_HAS_WHEEL (0x00020000), INFO_NOAUDIOPLAYBACK (0x00080000), - (byte) 0x73, (byte) 0x01, (byte) 0x0a, (byte) 0x00, - - // Lengths - - // cbDomain length: 0 bytes (LE) (NOT including size of mandatory NULL terminator) - (byte) 0x00, (byte) 0x00, - - // cbUserName length: 16 bytes (0x10, LE) (NOT including size of mandatory NULL terminator) - (byte) 0x10, (byte) 0x00, - - // cbPassword length: 0 bytes (LE) (NOT including size of mandatory NULL terminator) - (byte) 0x00, (byte) 0x00, - - // cbAlternateShell: 0 bytes (LE) (NOT including size of mandatory NULL terminator) - (byte) 0x00, (byte) 0x00, - - // cbWorkingDir: 0 bytes (LE) (NOT including size of mandatory NULL terminator) - (byte) 0x00, (byte) 0x00, - - // Values - - // Domain: "" (UCS2), see cbDomain - (byte) 0x00, (byte) 0x00, - - // User name: "vlisivka" (UCS2), see cbUserName - (byte) 0x76, (byte) 0x00, (byte) 0x6c, (byte) 0x00, (byte) 0x69, (byte) 0x00, (byte) 0x73, (byte) 0x00, - (byte) 0x69, (byte) 0x00, (byte) 0x76, (byte) 0x00, (byte) 0x6b, (byte) 0x00, (byte) 0x61, (byte) 0x00, - (byte) 0x00, (byte) 0x00, - - // Password: "" (UCS2), see cbPassword - (byte) 0x00, (byte) 0x00, - - // Alternate shell: "" (UCS2), see cbAlternateShell - (byte) 0x00, (byte) 0x00, - - // Working directory: "" (UCS2), see cbWorkingDir - (byte) 0x00, (byte) 0x00, - - // Client address family: 2 (AF_INET, LE) - (byte) 0x02, (byte) 0x00, - - // cbClientAddress = 28 bytes (0x1c, LE) (including the size of the mandatory NULL terminator) - (byte) 0x1c, (byte) 0x00, - - // Client address: "192.168.0.100" (UCS2) - (byte) 0x31, (byte) 0x00, (byte) 0x39, (byte) 0x00, (byte) 0x32, (byte) 0x00, (byte) 0x2e, (byte) 0x00, - (byte) 0x31, (byte) 0x00, (byte) 0x36, (byte) 0x00, (byte) 0x38, (byte) 0x00, (byte) 0x2e, (byte) 0x00, - (byte) 0x30, (byte) 0x00, (byte) 0x2e, (byte) 0x00, (byte) 0x31, (byte) 0x00, (byte) 0x30, (byte) 0x00, - (byte) 0x30, (byte) 0x00, (byte) 0x00, (byte) 0x00, - - // cbClientDir: 64 bytes (0x40, LE) (including the size of the mandatory NULL terminator) - (byte) 0x40, (byte) 0x00, - - // Client directory: "C:\Windows\System32\mstscax.dll" (UCS2) - (byte) 0x43, (byte) 0x00, (byte) 0x3a, (byte) 0x00, (byte) 0x5c, (byte) 0x00, (byte) 0x57, (byte) 0x00, - (byte) 0x69, (byte) 0x00, (byte) 0x6e, (byte) 0x00, (byte) 0x64, (byte) 0x00, (byte) 0x6f, (byte) 0x00, - (byte) 0x77, (byte) 0x00, (byte) 0x73, (byte) 0x00, (byte) 0x5c, (byte) 0x00, (byte) 0x53, (byte) 0x00, - (byte) 0x79, (byte) 0x00, (byte) 0x73, (byte) 0x00, (byte) 0x74, (byte) 0x00, (byte) 0x65, (byte) 0x00, - (byte) 0x6d, (byte) 0x00, (byte) 0x33, (byte) 0x00, (byte) 0x32, (byte) 0x00, (byte) 0x5c, (byte) 0x00, - (byte) 0x6d, (byte) 0x00, (byte) 0x73, (byte) 0x00, (byte) 0x74, (byte) 0x00, (byte) 0x73, (byte) 0x00, - (byte) 0x63, (byte) 0x00, (byte) 0x61, (byte) 0x00, (byte) 0x78, (byte) 0x00, (byte) 0x2e, (byte) 0x00, - (byte) 0x64, (byte) 0x00, (byte) 0x6c, (byte) 0x00, (byte) 0x6c, (byte) 0x00, (byte) 0x00, (byte) 0x00, - - // - // Client time zone: - - // Bias: 0 minutes (LE) - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - - // Standard name: "EET, Standard Time" (fixed string: 64 bytes, UCS2) - (byte) 0x45, (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x54, (byte) 0x00, (byte) 0x2c, (byte) 0x00, - (byte) 0x20, (byte) 0x00, (byte) 0x53, (byte) 0x00, (byte) 0x74, (byte) 0x00, (byte) 0x61, (byte) 0x00, - (byte) 0x6e, (byte) 0x00, (byte) 0x64, (byte) 0x00, (byte) 0x61, (byte) 0x00, (byte) 0x72, (byte) 0x00, - (byte) 0x64, (byte) 0x00, (byte) 0x20, (byte) 0x00, (byte) 0x54, (byte) 0x00, (byte) 0x69, (byte) 0x00, - (byte) 0x6d, (byte) 0x00, (byte) 0x65, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - - // - // Standard date - // wYear: 0 (LE) - (byte) 0x00, (byte) 0x00, - // wMonth: unknown (LE) - (byte) 0x00, (byte) 0x00, - // wDayOfWeek: Sunday (LE) - (byte) 0x00, (byte) 0x00, - // wDay: unknown (LE) - (byte) 0x00, (byte) 0x00, - // wHour: 0 (LE) - (byte) 0x00, (byte) 0x00, - // wMinute: 0 (LE) - (byte) 0x00, (byte) 0x00, - // wSecond: 0 (LE) - (byte) 0x00, (byte) 0x00, - // wMilliseconds: 0 - (byte) 0x00, (byte) 0x00, - - // StandardBias: 0 minutes (LE) - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - - // Daylight name: "EET, Summer Time" (fixed string: 64 bytes, UCS2) - (byte) 0x45, (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x54, (byte) 0x00, (byte) 0x2c, (byte) 0x00, - (byte) 0x20, (byte) 0x00, (byte) 0x53, (byte) 0x00, (byte) 0x75, (byte) 0x00, (byte) 0x6d, (byte) 0x00, - (byte) 0x6d, (byte) 0x00, (byte) 0x65, (byte) 0x00, (byte) 0x72, (byte) 0x00, (byte) 0x20, (byte) 0x00, - (byte) 0x54, (byte) 0x00, (byte) 0x69, (byte) 0x00, (byte) 0x6d, (byte) 0x00, (byte) 0x65, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - - // Daylight date - // wYear: 0 (LE) - (byte) 0x00, (byte) 0x00, - // wMonth: unknown (LE) - (byte) 0x00, (byte) 0x00, - // wDayOfWeek: Sunday (LE) - (byte) 0x00, (byte) 0x00, - // wDay: unknown (LE) - (byte) 0x00, (byte) 0x00, - // wHour: 0 (LE) - (byte) 0x00, (byte) 0x00, - // wMinute: 0 (LE) - (byte) 0x00, (byte) 0x00, - // wSecond: 0 (LE) - (byte) 0x00, (byte) 0x00, - // wMilliseconds: 0 - (byte) 0x00, (byte) 0x00, - - // Daylight bias: 60 minutes (LE) - (byte) 0x3c, (byte) 0x00, (byte) 0x00, (byte) 0x00, - - - // Client session ID: 0x00000000 (LE) - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - - // Performance flags: 0x7 (LE) = PERF_DISABLE_WALLPAPER (0x1), PERF_DISABLE_FULLWINDOWDRAG (0x2), PERF_DISABLE_MENUANIMATIONS (0x4) - (byte) 0x07, (byte) 0x00, (byte) 0x00, (byte) 0x00, - - // cbAutoReconnectCookie: 0 bytes (LE) - (byte) 0x00, (byte) 0x00, - }; - /* @formatter:on */ - - MockSource source = new MockSource("source", ByteBuffer.convertByteArraysToByteBuffers(new byte[] {1, 2, 3})); - Element todo = new ClientInfoPDU("client_info", "vlisivka"); - Element x224 = new ClientX224DataPdu("x224"); - Element tpkt = new ClientTpkt("tpkt"); - Element sink = new MockSink("sink", ByteBuffer.convertByteArraysToByteBuffers(packet)); - Element mainSink = new MockSink("mainSink", ByteBuffer.convertByteArraysToByteBuffers(new byte[] {1, 2, 3})); - - Pipeline pipeline = new PipelineImpl("test"); - pipeline.add(source, todo, x224, tpkt, sink, mainSink); - pipeline.link("source", "client_info", "mainSink"); - pipeline.link("client_info >" + OTOUT, "x224", "tpkt", "sink"); - pipeline.runMainLoop("source", STDOUT, false, false); - } - -} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientMCSConnectInitial.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientMCSConnectInitial.java deleted file mode 100644 index e910c10fcea..00000000000 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientMCSConnectInitial.java +++ /dev/null @@ -1,669 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package rdpclient; - -import streamer.ByteBuffer; -import streamer.Element; -import streamer.Link; -import streamer.MockSink; -import streamer.MockSource; -import streamer.OneTimeSwitch; -import streamer.Pipeline; -import streamer.PipelineImpl; - -public class ClientMCSConnectInitial extends OneTimeSwitch { - - public ClientMCSConnectInitial(String id) { - super(id); - } - - @Override - protected void handleOneTimeData(ByteBuffer buf, Link link) { - if (buf == null) - return; - - throw new RuntimeException("Unexpected packet: " + buf + "."); - } - - @Override - protected void onStart() { - super.onStart(); - - int length = 1024; // Large enough - ByteBuffer buf = new ByteBuffer(length, true); - - /* @formatter:off */ - buf.writeBytes(new byte[] { -// - T125: MCSConnect Initial -// - MCSConnectInitial: Identifier=Generic Conference Control (0.0.20.124.0.1), ConnectPDULength=254 -// - ConnectInitialHeader: - (byte)0x7F, (byte)0x65, -// - AsnId: Application Constructed Tag (101) -// - HighTag: -// Class: (01......) Application (1) -// Type: (..1.....) Constructed -// TagNumber: (...11111) -// TagValueEnd: 101 (0x65) - (byte)0x82, (byte)0x01, (byte)0x6C, -// - AsnLen: Length = 364, LengthOfLength = 2 -// LengthType: LengthOfLength = 2 -// Length: 364 bytes - (byte)0x04, (byte)0x01, (byte)0x01, -// - CallingDomainSelector: 0x1 -// - AsnOctetStringHeader: -// - AsnId: OctetString type (Universal 4) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..0.....) Primitive -// TagValue: (...00100) 4 -// - AsnLen: Length = 1, LengthOfLength = 0 -// Length: 1 bytes, LengthOfLength = 0 -// OctetStream: 0x1 - (byte)0x04, (byte)0x01, (byte)0x01, -// - CalledDomainSelector: 0x1 -// - AsnOctetStringHeader: -// - AsnId: OctetString type (Universal 4) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..0.....) Primitive -// TagValue: (...00100) 4 -// - AsnLen: Length = 1, LengthOfLength = 0 -// Length: 1 bytes, LengthOfLength = 0 -// OctetStream: 0x1 - (byte)0x01, (byte)0x01, (byte)0xFF, -// - UpwardFlag: True -// - AsnBooleanHeader: -// - AsnId: Boolean type (Universal 1) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..0.....) Primitive -// TagValue: (...00001) 1 -// - AsnLen: Length = 1, LengthOfLength = 0 -// Length: 1 bytes, LengthOfLength = 0 -// Tf: 255 (0xFF) - -// -// - TargetParameters: Length = 26, LengthOfLength = 0 - (byte)0x30, (byte)0x1A, -// - DomainParametersHeader: 0x1 -// - AsnId: Sequence and SequenceOf types (Universal 16) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..1.....) Constructed -// TagValue: (...10000) 16 -// - AsnLen: Length = 26, LengthOfLength = 0 -// Length: 26 bytes, LengthOfLength = 0 - (byte)0x02, (byte)0x01, (byte)0x22, -// - ChannelIds: 34 -// - AsnIntegerHeader: -// - AsnId: Integer type (Universal 2) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..0.....) Primitive -// TagValue: (...00010) 2 -// - AsnLen: Length = 1, LengthOfLength = 0 -// Length: 1 bytes, LengthOfLength = 0 -// AsnInt: 34 (0x22) - (byte)0x02, (byte)0x01, (byte)0x02, -// - UserIDs: 2 -// - AsnIntegerHeader: -// - AsnId: Integer type (Universal 2) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..0.....) Primitive -// TagValue: (...00010) 2 -// - AsnLen: Length = 1, LengthOfLength = 0 -// Length: 1 bytes, LengthOfLength = 0 -// AsnInt: 2 (0x2) - (byte)0x02, (byte)0x01, (byte)0x00, -// - TokenIds: 0 -// - AsnIntegerHeader: -// - AsnId: Integer type (Universal 2) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..0.....) Primitive -// TagValue: (...00010) 2 -// - AsnLen: Length = 1, LengthOfLength = 0 -// Length: 1 bytes, LengthOfLength = 0 -// AsnInt: 0 (0x0) - (byte)0x02, (byte)0x01, (byte)0x01, -// - NumPriorities: 1 -// - AsnIntegerHeader: -// - AsnId: Integer type (Universal 2) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..0.....) Primitive -// TagValue: (...00010) 2 -// - AsnLen: Length = 1, LengthOfLength = 0 -// Length: 1 bytes, LengthOfLength = 0 -// AsnInt: 1 (0x1) - (byte)0x02, (byte)0x01, (byte)0x00, -// - MinThroughput: 0 -// - AsnIntegerHeader: -// - AsnId: Integer type (Universal 2) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..0.....) Primitive -// TagValue: (...00010) 2 -// - AsnLen: Length = 1, LengthOfLength = 0 -// Length: 1 bytes, LengthOfLength = 0 -// AsnInt: 0 (0x0) - (byte)0x02, (byte)0x01, (byte)0x01, -// - Height: 1 -// - AsnIntegerHeader: -// - AsnId: Integer type (Universal 2) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..0.....) Primitive -// TagValue: (...00010) 2 -// - AsnLen: Length = 1, LengthOfLength = 0 -// Length: 1 bytes, LengthOfLength = 0 -// AsnInt: 1 (0x1) - (byte)0x02, (byte)0x03, (byte)0x00, (byte)0xFF, (byte)0xFF, -// - MCSPDUsize: 65535 -// - AsnIntegerHeader: -// - AsnId: Integer type (Universal 2) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..0.....) Primitive -// TagValue: (...00010) 2 -// - AsnLen: Length = 3, LengthOfLength = 0 -// Length: 3 bytes, LengthOfLength = 0 -// AsnInt: 65535 (0xFFFF) - (byte)0x02, (byte)0x01, (byte)0x02, -// - protocolVersion: 2 -// - AsnIntegerHeader: -// - AsnId: Integer type (Universal 2) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..0.....) Primitive -// TagValue: (...00010) 2 -// - AsnLen: Length = 1, LengthOfLength = 0 -// Length: 1 bytes, LengthOfLength = 0 -// AsnInt: 2 (0x2) - -// -// - MinimumParameters: Length = 25, LengthOfLength = 0 - (byte)0x30, (byte)0x19, -// - DomainParametersHeader: 0x1 -// - AsnId: Sequence and SequenceOf types (Universal 16) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..1.....) Constructed -// TagValue: (...10000) 16 -// - AsnLen: Length = 25, LengthOfLength = 0 -// Length: 25 bytes, LengthOfLength = 0 - (byte)0x02, (byte)0x01, (byte)0x01, -// - ChannelIds: 1 -// - AsnIntegerHeader: -// - AsnId: Integer type (Universal 2) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..0.....) Primitive -// TagValue: (...00010) 2 -// - AsnLen: Length = 1, LengthOfLength = 0 -// Length: 1 bytes, LengthOfLength = 0 -// AsnInt: 1 (0x1) - (byte)0x02, (byte)0x01, (byte)0x01, -// - UserIDs: 1 -// - AsnIntegerHeader: -// - AsnId: Integer type (Universal 2) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..0.....) Primitive -// TagValue: (...00010) 2 -// - AsnLen: Length = 1, LengthOfLength = 0 -// Length: 1 bytes, LengthOfLength = 0 -// AsnInt: 1 (0x1) - (byte)0x02, (byte)0x01, (byte)0x01, -// - TokenIds: 1 -// - AsnIntegerHeader: -// - AsnId: Integer type (Universal 2) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..0.....) Primitive -// TagValue: (...00010) 2 -// - AsnLen: Length = 1, LengthOfLength = 0 -// Length: 1 bytes, LengthOfLength = 0 -// AsnInt: 1 (0x1) - (byte)0x02, (byte)0x01, (byte)0x01, -// - NumPriorities: 1 -// - AsnIntegerHeader: -// - AsnId: Integer type (Universal 2) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..0.....) Primitive -// TagValue: (...00010) 2 -// - AsnLen: Length = 1, LengthOfLength = 0 -// Length: 1 bytes, LengthOfLength = 0 -// AsnInt: 1 (0x1) - (byte)0x02, (byte)0x01, (byte)0x00, -// - MinThroughput: 0 -// - AsnIntegerHeader: -// - AsnId: Integer type (Universal 2) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..0.....) Primitive -// TagValue: (...00010) 2 -// - AsnLen: Length = 1, LengthOfLength = 0 -// Length: 1 bytes, LengthOfLength = 0 -// AsnInt: 0 (0x0) - (byte)0x02, (byte)0x01, (byte)0x01, -// - Height: 1 -// - AsnIntegerHeader: -// - AsnId: Integer type (Universal 2) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..0.....) Primitive -// TagValue: (...00010) 2 -// - AsnLen: Length = 1, LengthOfLength = 0 -// Length: 1 bytes, LengthOfLength = 0 -// AsnInt: 1 (0x1) - (byte)0x02, (byte)0x02, (byte)0x04, (byte)0x20, -// - MCSPDUsize: 1056 -// - AsnIntegerHeader: -// - AsnId: Integer type (Universal 2) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..0.....) Primitive -// TagValue: (...00010) 2 -// - AsnLen: Length = 2, LengthOfLength = 0 -// Length: 2 bytes, LengthOfLength = 0 -// AsnInt: 1056 (0x420) - (byte)0x02, (byte)0x01, (byte)0x02, -// - protocolVersion: 2 -// - AsnIntegerHeader: -// - AsnId: Integer type (Universal 2) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..0.....) Primitive -// TagValue: (...00010) 2 -// - AsnLen: Length = 1, LengthOfLength = 0 -// Length: 1 bytes, LengthOfLength = 0 -// AsnInt: 2 (0x2) -// - MaximumParameters: Length = 31, LengthOfLength = 0 -// - DomainParametersHeader: 0x1 - (byte)0x30, (byte)0x1F, -// - AsnId: Sequence and SequenceOf types (Universal 16) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..1.....) Constructed -// TagValue: (...10000) 16 -// - AsnLen: Length = 31, LengthOfLength = 0 -// Length: 31 bytes, LengthOfLength = 0 - (byte)0x02, (byte)0x03, (byte)0x00, (byte)0xFF, (byte)0xFF, -// - ChannelIds: 65535 -// - AsnIntegerHeader: -// - AsnId: Integer type (Universal 2) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..0.....) Primitive -// TagValue: (...00010) 2 -// - AsnLen: Length = 3, LengthOfLength = 0 -// Length: 3 bytes, LengthOfLength = 0 -// AsnInt: 65535 (0xFFFF) - (byte)0x02, (byte)0x02, (byte)0xFC, (byte)0x17, -// - UserIDs: 64535 -// - AsnIntegerHeader: -// - AsnId: Integer type (Universal 2) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..0.....) Primitive -// TagValue: (...00010) 2 -// - AsnLen: Length = 2, LengthOfLength = 0 -// Length: 2 bytes, LengthOfLength = 0 -// AsnInt: 64535 (0xFC17) - (byte)0x02, (byte)0x03, (byte)0x00, (byte)0xFF, (byte)0xFF, -// - TokenIds: 65535 -// - AsnIntegerHeader: -// - AsnId: Integer type (Universal 2) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..0.....) Primitive -// TagValue: (...00010) 2 -// - AsnLen: Length = 3, LengthOfLength = 0 -// Length: 3 bytes, LengthOfLength = 0 -// AsnInt: 65535 (0xFFFF) - (byte)0x02, (byte)0x01, (byte)0x01, -// - NumPriorities: 1 -// - AsnIntegerHeader: -// - AsnId: Integer type (Universal 2) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..0.....) Primitive -// TagValue: (...00010) 2 -// - AsnLen: Length = 1, LengthOfLength = 0 -// Length: 1 bytes, LengthOfLength = 0 -// AsnInt: 1 (0x1) - (byte)0x02, (byte)0x01, (byte)0x00, -// - MinThroughput: 0 -// - AsnIntegerHeader: -// - AsnId: Integer type (Universal 2) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..0.....) Primitive -// TagValue: (...00010) 2 -// - AsnLen: Length = 1, LengthOfLength = 0 -// Length: 1 bytes, LengthOfLength = 0 -// AsnInt: 0 (0x0) - (byte)0x02, (byte)0x01, (byte)0x01, -// - Height: 1 -// - AsnIntegerHeader: -// - AsnId: Integer type (Universal 2) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..0.....) Primitive -// TagValue: (...00010) 2 -// - AsnLen: Length = 1, LengthOfLength = 0 -// Length: 1 bytes, LengthOfLength = 0 -// AsnInt: 1 (0x1) - (byte)0x02, (byte)0x03, (byte)0x00, (byte)0xFF, (byte)0xFF, -// - MCSPDUsize: 65535 -// - AsnIntegerHeader: -// - AsnId: Integer type (Universal 2) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..0.....) Primitive -// TagValue: (...00010) 2 -// - AsnLen: Length = 3, LengthOfLength = 0 -// Length: 3 bytes, LengthOfLength = 0 -// AsnInt: 65535 (0xFFFF) - (byte)0x02, (byte)0x01, (byte)0x02, -// - protocolVersion: 2 -// - AsnIntegerHeader: -// - AsnId: Integer type (Universal 2) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..0.....) Primitive -// TagValue: (...00010) 2 -// - AsnLen: Length = 1, LengthOfLength = 0 -// Length: 1 bytes, LengthOfLength = 0 -// AsnInt: 2 (0x2) -// - UserData: Identifier=Generic Conference Contro (0.0.20.124.0.1), ConnectPDULength=254 -// - UserDataHeader: - (byte)0x04, (byte)0x82, (byte)0x01, (byte)0x07, -// - AsnId: OctetString type (Universal 4) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..0.....) Primitive -// TagValue: (...00100) 4 -// - AsnLen: Length = 263, LengthOfLength = 2 -// LengthType: LengthOfLength = 2 -// Length: 263 bytes - (byte)0x00, (byte)0x05, (byte)0x00, (byte)0x14, (byte)0x7C, (byte)0x00, (byte)0x01, -// - AsnBerObjectIdentifier: Generic Conference Contro (0.0.20.124.0.1) -// - AsnObjectIdentifierHeader: -// - AsnId: Reserved for use by the encoding rules (Universal 0) -// - LowTag: -// Class: (00......) Universal (0) -// Type: (..0.....) Primitive -// TagValue: (...00000) 0 -// - AsnLen: Length = 5, LengthOfLength = 0 -// Length: 5 bytes, LengthOfLength = 0 -// First: 0 (0x0) -// Final: 20 (0x14) -// Final: 124 (0x7C) -// Final: 0 (0x0) -// Final: 1 (0x1) - (byte)0x80, (byte)0xFE, -// - ConnectPDULength: 254 -// Align: No Padding -// Length: 254 - (byte)0x00, (byte)0x08, (byte)0x00, (byte)0x10, -// - ConnectGCCPDU: conferenceCreateRequest -// ExtensionBit: 0 (0x0) -// - ChoiceValue: conferenceCreateRequest -// Value: (000.....) 0x0 -// - conferenceCreateRequest: -// ExtensionBit: 0 (0x0) -// convenerPasswordPresent: 0 (0x0) -// passwordPresent: 0 (0x0) -// conductorPrivilegesPresent: 0 (0x0) -// conductedPrivilegesPresent: 0 (0x0) -// nonConductedPrivilegesPresent: 0 (0x0) -// conferenceDescriptionPresent: 0 (0x0) -// callerIdentifierPresent: 0 (0x0) -// userDataPresent: 1 (0x1) -// - conferenceName: -// ExtensionBit: 0 (0x0) -// textPresent: 0 (0x0) -// - numeric: 1 -// - SimpleNumericString: 1 -// - NumericString: 1 -// - Align: No Padding -// Padding1: (0.......) 0x0 -// - Length: 1 -// Value: (00000000) 0x0 -// - Restrictedstr: 1 -// FourBits: (0001....) 0x1 -// - lockedConference: False -// Value: False 0....... -// - listedConference: False -// Value: False 0....... -// - conductibleConference: False -// Value: False 0....... -// - TerminationMethod: automatic -// ExtensionBit: 0 (0x0) -// - RootIndex: 0 -// Value: (0.......) 0x0 -// - userData: - (byte)0x00, (byte)0x01, -// - Size: 1 -// - Align: No Padding -// Padding7: (0000000.) 0x0 -// Length: 1 -// - UserData: 0x44756361 - (byte)0xC0, (byte)0x00, (byte)0x44, (byte)0x75, (byte)0x63, (byte)0x61, -// valuePresent: 1 (0x1) -// - key: h221NonStandard "Duca" -// - ChoiceValue: h221NonStandard -// Value: (1.......) 0x1 -// - h221NonStandard: -// - H221NonStandardIdentifier: length: 4 -// - ConstrainedLength: 4 -// Value: (00000000) 0x0 -// - Align: No Padding -// Padding6: (000000..) 0x0 -// Value: Binary Large Object (4 Bytes) "Duca" -// - ClientMcsConnectInitialPdu: - (byte)0x80, (byte)0xF0, -// - RDPGCCUserDataRequestLength: 240 -// Align: No Padding -// Length: 240 -// - TsUd: CS_CORE - (byte)0x01, (byte)0xC0, (byte)0xD8, (byte)0x00, -// - TsUdHeader: Type = CS_CORE, Length = 216 -// Type: CS_CORE -// Length: 216 (0xD8) -// - TsUdCsCore: - (byte)0x04, (byte)0x00, (byte)0x08, (byte)0x00, -// Version: RDP 5.0, 5.1, 5.2, 6.0, 6.1, and 7.0 - (byte)0x00, (byte)0x04, -// DesktopWidth: 1024 (0x400) - (byte)0x00, (byte)0x03, -// DesktopHeight: 768 (0x300) - (byte)0x01, (byte)0xCA, -// ColorDepth: 8 bpp - (byte)0x03, (byte)0xAA, -// SASSequence: 0xaa03, SHOULD be set to RNS_UD_SAS_DEL(0xAA03) - (byte)0x09, (byte)0x04, (byte)0x00, (byte)0x00, -// KeyboardLayout: Language: English, Location: United States - (byte)0x28, (byte)0x0A, (byte)0x00, (byte)0x00, -// ClientBuild: 2600 (0xA28) - (byte)0x61, (byte)0x00, (byte)0x70, (byte)0x00, (byte)0x6F, (byte)0x00, (byte)0x6C, (byte)0x00, (byte)0x6C, (byte)0x00, (byte)0x6F, (byte)0x00, (byte)0x33, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, -// ClientName: apollo3 - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, -// KeyboardType: Undefined value: 0 - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, -// KeyboardSubType: 0 (0x0) - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, -// KeyboardFunctionKey: 0 (0x0) - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, -// ImeFileName: - (byte)0x01, (byte)0xCA, -// PostBeta2ColorDepth: 8 bpp - (byte)0x01, (byte)0x00, -// ClientProductId: 0x1, SHOULD be set to initialized to 1 - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, -// SerialNumber: 0x0, SHOULD be set to 0 - (byte)0x10, (byte)0x00, -// HighColorDepth: 16-bit 565 RGB - (byte)0x07, (byte)0x00, -// - SupportedColorDepth: 7 (0x7) -// Support24BPP: (...............1) Support 24BPP -// Support16BPP: (..............1.) Support 16BPP -// Support15BPP: (.............1..) Support 15BPP -// Support32BPP: (............0...) Not Support 32BPP -// Reserved: (000000000000....) - (byte)0x01, (byte)0x00, -// - EarlyCapabilityFlags: 1 (0x1) -// SupportSetErrorPdu: (...............1) Indicates that the client supports the Set Error Info PDU -// Want32BppSession: (..............0.) Client is not requesting 32BPP session -// SupportStatusInfoPdu: (.............0..) Client not supports the Server Status Info PDU -// StrongAsymmetricKeys: (............0...) Not support asymmetric keys larger than 512-bits -// Unused: (...........0....) -// ValidConnection: (..........0.....) Not Indicates ConnectionType field contains valid data -// SupportMonitorLayoutPdu: (.........0......) Not Indicates that the client supports the Monitor Layout PDU -// Unused2: (000000000.......) - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, -// ClientDigProductId: -(byte)0x00, -// connectionType: invalid connection type -(byte)0x00, -// pad1octet: 0 (0x0) -(byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, -// ServerSelectedProtocols: TLS 1.0 -// -// - TsUd: CS_CLUSTER -// - TsUdHeader: Type = CS_CLUSTER, Length = 12 -(byte)0x04, (byte)0xC0, -// Type: CS_CLUSTER -(byte)0x0C, (byte)0x00, -// Length: 12 (0xC) -(byte)0x0D, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, -// - TsUdCsCluster: -// - Flags: 13 (0xD) -// RedirectedSupported: (...............................1) Support Redirected -// SessionIDFieldValid: (..............................0.) SessionID Field not Valid -// SupportedVersion: (..........................0011..) REDIRECTION_VERSION4 -// RedirectedSmartcard: (.........................0......) Not Logon with Smartcard -// Unused: (0000000000000000000000000.......) -// RedirectedSessionID: 0 (0x0) -// -// - TsUd: CS_SECURITY -// - TsUdHeader: Type = CS_SECURITY, Length = 12 -(byte)0x02, (byte)0xC0, -// Type: CS_SECURITY -(byte)0x0C, (byte)0x00, -// Length: 12 (0xC) -// -// - TsUdCsSec: -(byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, -// - EncryptionMethod: -// Support40Bit: (...............................0) Not Support -// Support128Bit: (..............................0.) Not Support 128-bit -// Reserved1: (.............................0..) -// Support56Bit: (............................0...) Not Support 56-bit -// SupportFIPS: (...........................0....) Not Support FIPS Compliant -// Reserved2: (000000000000000000000000000.....) -(byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, -// - ExtEncryptionMethod: -// Support40Bit: (...............................0) Not Support -// Support128Bit: (..............................0.) Not Support 128-bit -// Reserved1: (.............................0..) -// Support56Bit: (............................0...) Not Support 56-bit -// SupportFIPS: (...........................0....) Not Support FIPS Compliant -// Reserved2: (000000000000000000000000000.....) - }); - /* @formatter:on */ - - buf.length = buf.cursor; - - pushDataToOTOut(buf); - - switchOff(); - } - - /** - * Example. - * - * @see http://msdn.microsoft.com/en-us/library/cc240836.aspx - */ - public static void main(String args[]) { - // System.setProperty("streamer.Link.debug", "true"); - System.setProperty("streamer.Element.debug", "true"); - // System.setProperty("streamer.Pipeline.debug", "true"); - - /* @formatter:off */ - byte[] packet = new byte[] { - // TPKT: TPKT version = 3 - (byte) 0x03, (byte) 0x00, - // TPKT: Packet length: 378 bytes - (byte) 0x01, (byte) 0x78, - - // X.224: Length indicator = 2 - (byte) 0x02, - // X.224: Type: Data TPDU - (byte) 0xf0, - // X.224: EOT - (byte) 0x80, - - // Captured packet - (byte)0x7f, (byte)0x65, (byte)0x82, (byte)0x01, (byte)0x6c, (byte)0x04, (byte)0x01, (byte)0x01, (byte)0x04, - (byte)0x01, (byte)0x01, (byte)0x01, (byte)0x01, (byte)0xff, (byte)0x30, (byte)0x1a, (byte)0x02, (byte)0x01, (byte)0x22, (byte)0x02, (byte)0x01, (byte)0x02, (byte)0x02, (byte)0x01, (byte)0x00, - (byte)0x02, (byte)0x01, (byte)0x01, (byte)0x02, (byte)0x01, (byte)0x00, (byte)0x02, (byte)0x01, (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x00, (byte)0xff, (byte)0xff, (byte)0x02, (byte)0x01, - (byte)0x02, (byte)0x30, (byte)0x19, (byte)0x02, (byte)0x01, (byte)0x01, (byte)0x02, (byte)0x01, (byte)0x01, (byte)0x02, (byte)0x01, (byte)0x01, (byte)0x02, (byte)0x01, (byte)0x01, (byte)0x02, - (byte)0x01, (byte)0x00, (byte)0x02, (byte)0x01, (byte)0x01, (byte)0x02, (byte)0x02, (byte)0x04, (byte)0x20, (byte)0x02, (byte)0x01, (byte)0x02, (byte)0x30, (byte)0x1f, (byte)0x02, (byte)0x03, - (byte)0x00, (byte)0xff, (byte)0xff, (byte)0x02, (byte)0x02, (byte)0xfc, (byte)0x17, (byte)0x02, (byte)0x03, (byte)0x00, (byte)0xff, (byte)0xff, (byte)0x02, (byte)0x01, (byte)0x01, (byte)0x02, - (byte)0x01, (byte)0x00, (byte)0x02, (byte)0x01, (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x00, (byte)0xff, (byte)0xff, (byte)0x02, (byte)0x01, (byte)0x02, (byte)0x04, (byte)0x82, (byte)0x01, - (byte)0x07, (byte)0x00, (byte)0x05, (byte)0x00, (byte)0x14, (byte)0x7c, (byte)0x00, (byte)0x01, (byte)0x80, (byte)0xfe, (byte)0x00, (byte)0x08, (byte)0x00, (byte)0x10, (byte)0x00, (byte)0x01, - (byte)0xc0, (byte)0x00, (byte)0x44, (byte)0x75, (byte)0x63, (byte)0x61, (byte)0x80, (byte)0xf0, (byte)0x01, (byte)0xc0, (byte)0xd8, (byte)0x00, (byte)0x04, (byte)0x00, (byte)0x08, (byte)0x00, - (byte)0x00, (byte)0x04, (byte)0x00, (byte)0x03, (byte)0x01, (byte)0xca, (byte)0x03, (byte)0xaa, (byte)0x09, (byte)0x04, (byte)0x00, (byte)0x00, (byte)0x28, (byte)0x0a, (byte)0x00, (byte)0x00, - (byte)0x61, (byte)0x00, (byte)0x70, (byte)0x00, (byte)0x6f, (byte)0x00, (byte)0x6c, (byte)0x00, (byte)0x6c, (byte)0x00, (byte)0x6f, (byte)0x00, (byte)0x33, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x01, (byte)0xca, (byte)0x01, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x10, (byte)0x00, (byte)0x07, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x04, (byte)0xc0, (byte)0x0c, (byte)0x00, (byte)0x0d, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x02, (byte)0xc0, (byte)0x0c, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - }; - /* @formatter:on */ - - MockSource source = new MockSource("source", ByteBuffer.convertByteArraysToByteBuffers(new byte[] {1, 2, 3})); - Element todo = new ClientMCSConnectInitial("ClientMCSConnectInitial"); - Element x224 = new ClientX224DataPdu("x224"); - Element tpkt = new ClientTpkt("tpkt"); - - Element sink = new MockSink("sink", ByteBuffer.convertByteArraysToByteBuffers(packet)); - - Element mainSink = new MockSink("mainSink", ByteBuffer.convertByteArraysToByteBuffers(new byte[] {1, 2, 3})); - - Pipeline pipeline = new PipelineImpl("test"); - pipeline.add(source, todo, x224, tpkt, sink, mainSink); - pipeline.link("source", "ClientMCSConnectInitial", "mainSink"); - pipeline.link("ClientMCSConnectInitial >" + OTOUT, "x224", "tpkt", "sink"); - pipeline.runMainLoop("source", STDOUT, false, false); - } - -} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientPacketSniffer.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientPacketSniffer.java deleted file mode 100644 index ce517d2acea..00000000000 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientPacketSniffer.java +++ /dev/null @@ -1,49 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package rdpclient; - -/** - * Try to determine packet content by it header fingerprint. - */ -public class ClientPacketSniffer extends PacketSniffer { - - private static final Pair[] clientRegexps = new Pair[] { -// @formatter:off - new Pair("Client FastPath input", "04"), - new Pair("Client X224ConnectionRequest", "03 00 XX XX 27 E0"), - new Pair("Client ConnectionRequest", "03 00 XX XX XX E0"), - new Pair("Client MCConnectInitial", "03 00 XX XX 02 F0 80 7F 65"), - new Pair("Client ErectDomainRequest", "03 00 XX XX 02 F0 80 04"), - new Pair("Client AttachUserRequest", "03 00 XX XX 02 F0 80 28"), - new Pair("Client ChannelJoinRequest", "03 00 XX XX 02 F0 80 38"), - new Pair("Client Info", "03 00 XX XX 02 F0 80 64 00 03 03 EB 70 XX XX XX XX 00 00"), - new Pair("Client ConfirmActivePDU", "03 00 XX XX 02 F0 80 64 00 03 03 EB 70 XX XX XX XX 13 00"), - new Pair("Client SynchronizePDU", "03 00 XX XX 02 F0 80 64 00 03 03 EB 70 XX XX XX XX 17 00 EC 03 EA 03 XX 00 XX XX XX XX 1F"), - new Pair("Client ControlPDU", "03 00 XX XX 02 F0 80 64 00 03 03 EB 70 XX XX XX XX 17 00 EC 03 EA 03 XX 00 XX XX XX XX 14"), - new Pair("Client FontListPDU", "03 00 XX XX 02 F0 80 64 00 03 03 EB 70 XX XX XX XX 17 00 EC 03 EA 03 XX 00 XX XX XX XX 27"), - new Pair("Client BitmapCachePersistentList","03 00 XX XX 02 F0 80 64 00 03 03 EB 70 XX XX XX XX 17 00 EC 03 EA 03 XX XX XX XX XX XX 2b"), -// new Pair("Client TPKT Unknown packet", "03"), -// new Pair("Client UNKNOWN PACKET (ERROR)", ".*"), - // @formatter:on - - }; - - public ClientPacketSniffer(String id) { - super(id, clientRegexps); - } - -} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/RLEBitmapDecompression.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/RLEBitmapDecompression.java deleted file mode 100644 index cd3a5ed8af2..00000000000 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/RLEBitmapDecompression.java +++ /dev/null @@ -1,985 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package rdpclient; - -import streamer.AssertingByteBuffer; -import streamer.ByteBuffer; - -/** - * Based on code example from MSDN, @see - * http://msdn.microsoft.com/en-us/library/dd240593.aspx . - */ -public class RLEBitmapDecompression { - - public static final int g_MaskRegularRunLength = 0x1F; - public static final int g_MaskLiteRunLength = 0x0F; - - public static final int g_MaskSpecialFgBg1 = 0x03; - public static final int g_MaskSpecialFgBg2 = 0x05; - - public static final int REGULAR_BG_RUN = 0x00; - public static final int REGULAR_FG_RUN = 0x01; - public static final int REGULAR_FGBG_IMAGE = 0x02; - public static final int REGULAR_COLOR_RUN = 0x03; - public static final int REGULAR_COLOR_IMAGE = 0x04; - - public static final int LITE_SET_FG_FG_RUN = 0x0C; - public static final int LITE_SET_FG_FGBG_IMAGE = 0x0D; - public static final int LITE_DITHERED_RUN = 0x0E; - - public static final int MEGA_MEGA_BG_RUN = 0xF0; - public static final int MEGA_MEGA_FG_RUN = 0xF1; - public static final int MEGA_MEGA_FGBG_IMAGE = 0xF2; - public static final int MEGA_MEGA_COLOR_RUN = 0xF3; - public static final int MEGA_MEGA_COLOR_IMAGE = 0xF4; - public static final int MEGA_MEGA_SET_FG_RUN = 0xF6; - public static final int MEGA_MEGA_SET_FGBG_IMAGE = 0xF7; - public static final int MEGA_MEGA_DITHERED_RUN = 0xF8; - - public static final int SPECIAL_FGBG_1 = 0xF9; - public static final int SPECIAL_FGBG_2 = 0xFA; - - public static final int SPECIAL_WHITE = 0xFD; - public static final int SPECIAL_BLACK = 0xFE; - - /** - * Writes a pixel to the specified buffer and advance cursor by bpp. - * - * @param bpp - * bytes per pixel - */ - private static void writePixel(int bpp, ByteBuffer destBuf, int pixel) { - switch (bpp) { - case 1: - destBuf.writeByte(pixel); - break; - case 2: - destBuf.writeShortLE(pixel); - break; - case 3: - destBuf.writeByte(pixel); - destBuf.writeShortLE(pixel >> 8); - break; - case 4: - destBuf.writeIntLE(pixel); - break; - default: - throw new RuntimeException("Unsupported color depth."); - } - } - - /** - * Reads a pixel from the specified buffer at given offset without changing of - * cursor. - * - * @param bpp - * bytes per pixel - * @param offset - * -rowDelta (i.e. (-width*bpp)) - */ - private static int peekPixel(int bpp, ByteBuffer destBuf, int offset) { - if (offset >= 0 || (-offset) > destBuf.cursor) - throw new RuntimeException("Incorrect value for offset: offset in destination buffer must point to pixel in previous row."); - - // Adjust cursor to point to pixel in previous row - int oldCursor = destBuf.cursor; - destBuf.cursor += offset; - - int pixel; - switch (bpp) { - case 1: - pixel = destBuf.readUnsignedByte(); - break; - case 2: - pixel = destBuf.readUnsignedShortLE(); - break; - case 3: - pixel = destBuf.readUnsignedByte() | (destBuf.readUnsignedShortLE() >> 8); - break; - case 4: - pixel = destBuf.readSignedIntLE(); - break; - default: - throw new RuntimeException("Unsupported color depth."); - } - destBuf.cursor = oldCursor; - - return pixel; - } - - /** - * Reads a pixel from the specified buffer and advance cursor by bpp value. - * - * @param bpp - * bytes per pixel - */ - private static int readPixel(int bpp, ByteBuffer srcBuf) { - int pixel; - switch (bpp) { - case 1: - pixel = srcBuf.readUnsignedByte(); - break; - case 2: - pixel = srcBuf.readUnsignedShortLE(); - break; - case 3: - pixel = srcBuf.readUnsignedByte() | (srcBuf.readUnsignedShortLE() >> 8); - break; - case 4: - pixel = srcBuf.readSignedIntLE(); - break; - default: - throw new RuntimeException("Unsupported color depth."); - } - - return pixel; - } - - /** - * Returns the size of a pixel in bytes. - */ - private static int getPixelSize(int colorDepth) { - switch (colorDepth) { - case 8: - return 1; - case 15: - case 16: - return 2; - case 24: - return 3; - default: - throw new RuntimeException("Unsupported pixel color depth: " + colorDepth + " bpp."); - } - } - - /** - * Reads the supplied order header & extracts the compression order code ID. - */ - private static int extractCodeId(int orderHeader) { - // Taken from FreeRDP code, bitmap.c - switch (orderHeader) { - case MEGA_MEGA_BG_RUN: - case MEGA_MEGA_FG_RUN: - case MEGA_MEGA_SET_FG_RUN: - case MEGA_MEGA_DITHERED_RUN: - case MEGA_MEGA_COLOR_RUN: - case MEGA_MEGA_FGBG_IMAGE: - case MEGA_MEGA_SET_FGBG_IMAGE: - case MEGA_MEGA_COLOR_IMAGE: - case SPECIAL_FGBG_1: - case SPECIAL_FGBG_2: - case SPECIAL_WHITE: - case SPECIAL_BLACK: - return orderHeader; - } - - int code = orderHeader >> 5; - switch (code) { - case REGULAR_BG_RUN: - case REGULAR_FG_RUN: - case REGULAR_COLOR_RUN: - case REGULAR_FGBG_IMAGE: - case REGULAR_COLOR_IMAGE: - return code; - } - - return orderHeader >> 4; - } - - /** - * Returns a black pixel. - */ - private static int getColorBlack() { - return 0x000000; - } - - /** - * Returns a white pixel. - */ - private static int getColorWhite(int colorDepth) { - if (colorDepth == 8) { - // - // Palette entry #255 holds white. - // - return 0xFF; - } else if (colorDepth == 15) { - // - // 5 bits per RGB component: - // 0111 1111 1111 1111 (binary) - // - return 0x7FFF; - } else if (colorDepth == 16) { - // - // 5 bits for red, 6 bits for green, 5 bits for green: - // 1111 1111 1111 1111 (binary) - // - return 0xFFFF; - } else if (colorDepth == 24) { - // - // 8 bits per RGB component: - // 1111 1111 1111 1111 1111 1111 (binary) - // - return 0xFFFFFF; - } else - throw new RuntimeException("Unsupported color depth."); - } - - /** - * Extract the run length of a compression order. - */ - private static int extractRunLength(int code, int orderHeader, ByteBuffer srcBuf) { - switch (code) { - case REGULAR_FGBG_IMAGE: { - int runLength = orderHeader & g_MaskRegularRunLength; - if (runLength == 0) - runLength = srcBuf.readUnsignedByte() + 1; - else - runLength = runLength * 8; - return runLength; - } - case LITE_SET_FG_FGBG_IMAGE: { - int runLength = orderHeader & g_MaskLiteRunLength; - if (runLength == 0) - runLength = srcBuf.readUnsignedByte() + 1; - else - runLength = runLength * 8; - return runLength; - } - case REGULAR_BG_RUN: - case REGULAR_COLOR_IMAGE: - case REGULAR_COLOR_RUN: - case REGULAR_FG_RUN: { - int runLength = orderHeader & g_MaskRegularRunLength; - if (runLength == 0) - // An extended (MEGA) run. - runLength = srcBuf.readUnsignedByte() + 32; - return runLength; - } - case LITE_DITHERED_RUN: - case LITE_SET_FG_FG_RUN: { - int runLength = orderHeader & g_MaskLiteRunLength; - if (runLength == 0) - // An extended (MEGA) run. - runLength = srcBuf.readUnsignedByte() + 16; - return runLength; - } - case MEGA_MEGA_BG_RUN: - case MEGA_MEGA_COLOR_IMAGE: - case MEGA_MEGA_COLOR_RUN: - case MEGA_MEGA_DITHERED_RUN: - case MEGA_MEGA_FG_RUN: - case MEGA_MEGA_FGBG_IMAGE: - case MEGA_MEGA_SET_FG_RUN: - case MEGA_MEGA_SET_FGBG_IMAGE: { - return srcBuf.readUnsignedShortLE(); - } - default: - return 0; - } - - } - - /** - * Write a foreground/background image to a destination buffer. - */ - private static void writeFgBgImage(int bpp, ByteBuffer destBuf, int rowDelta, int bitmask, int fgPel, int cBits) { - for (; cBits > 0; cBits--, bitmask >>= 1) { - int xorPixel = peekPixel(bpp, destBuf, -rowDelta); - writePixel(bpp, destBuf, ((bitmask & 0x1) > 0) ? xorPixel ^ fgPel : xorPixel); - } - } - - /** - * Write a foreground/background image to a destination buffer for the first - * line of compressed data. - */ - private static void writeFirstLineFgBgImage(int bpp, ByteBuffer destBuf, int bitmask, int fgPel, int cBits) { - for (; cBits > 0; cBits--, bitmask >>= 1) { - writePixel(bpp, destBuf, ((bitmask & 0x1) > 0) ? fgPel : getColorBlack()); - } - } - - /** - * Decompress a RLE compressed bitmap and flip decompressed image. - * - * @param srcBuf - * source buffer containing compressed bitmap - * @param imageWidth - * width of destination image in pixels - * @param imageHeight - * height of destination image in pixels - * @param colorDepth - * bits per pixel - * @return destination image buffer - */ - public static ByteBuffer rleDecompress(ByteBuffer srcBuf, int imageWidth, int imageHeight, int colorDepth) { - int bpp = getPixelSize(colorDepth); - - // Decompress image - ByteBuffer destBuf = new ByteBuffer(new byte[imageWidth * imageHeight * bpp]); - rleDecompress(srcBuf, destBuf, imageWidth, imageHeight, colorDepth); - - // Flip image - return flipRawImage(destBuf, imageWidth, imageHeight, bpp); - } - - /** - * Decompress a RLE compressed bitmap. - * - * @param srcBuf - * source buffer containing compressed bitmap - * @param destBuf - * destination buffer - * @param imageWidth - * width of destination image in pixels - * @param imageHeight - * height of destination image in pixels - * @param colorDepth - * bits per pixel - */ - protected static void rleDecompress(final ByteBuffer srcBuf, final ByteBuffer destBuf, final int imageWidth, final int imageHeight, final int colorDepth) { - final int bpp = getPixelSize(colorDepth); - final int rowDelta = imageWidth * bpp; - final int whitePixel = getColorWhite(colorDepth); - final int blackPixel = getColorBlack(); - - int fgPel = whitePixel; - boolean insertFgPel = false; - boolean firstLine = true; - - if (destBuf.length != imageWidth * imageHeight * bpp) - throw new RuntimeException("Incorrect size of destination buffer. Expected size (imageWidth*imageHeight*bpp): " + (imageWidth * imageHeight * bpp) + - ", actual size: " + destBuf.length + "."); - - while (srcBuf.cursor < srcBuf.length) { - // Watch out for the end of the first scanline in destination buffer. - if (firstLine) { - if (destBuf.cursor >= rowDelta) { - firstLine = false; - insertFgPel = false; - } - } - - // Extract the compression order code ID from the compression - // order header. - int orderHeader = srcBuf.readUnsignedByte(); - int code = extractCodeId(orderHeader); - - // Handle Background Run Orders. - if (code == REGULAR_BG_RUN | code == MEGA_MEGA_BG_RUN) { - int runLength = extractRunLength(code, orderHeader, srcBuf); - - if (firstLine) { - if (insertFgPel) { - writePixel(bpp, destBuf, fgPel); - runLength--; - } - - for (; runLength > 0; runLength--) - writePixel(bpp, destBuf, blackPixel); - - } else { - if (insertFgPel) { - writePixel(bpp, destBuf, peekPixel(bpp, destBuf, -rowDelta) ^ fgPel); - runLength--; - } - - // Copy pixels from previous row of destination image - for (; runLength > 0; runLength--) - writePixel(bpp, destBuf, peekPixel(bpp, destBuf, -rowDelta)); - } - - // - // A follow-on background run order will need a - // foreground pel inserted. - // - insertFgPel = true; - continue; - } - - // - // For any of the other run-types a follow-on background run - // order does not need a foreground pel inserted. - // - insertFgPel = false; - - // - // Handle Foreground Run Orders. - // - if (code == REGULAR_FG_RUN | code == MEGA_MEGA_FG_RUN | code == LITE_SET_FG_FG_RUN | code == MEGA_MEGA_SET_FG_RUN) { - int runLength = extractRunLength(code, orderHeader, srcBuf); - - if (code == LITE_SET_FG_FG_RUN | code == MEGA_MEGA_SET_FG_RUN) - fgPel = readPixel(bpp, srcBuf); - - if (firstLine) { - for (; runLength > 0; runLength--) { - writePixel(bpp, destBuf, fgPel); - } - } else { - for (; runLength > 0; runLength--) { - writePixel(bpp, destBuf, peekPixel(bpp, destBuf, -rowDelta) ^ fgPel); - } - } - - continue; - } - - // - // Handle Dithered Run Orders. - // - if (code == LITE_DITHERED_RUN | code == MEGA_MEGA_DITHERED_RUN) { - int runLength = extractRunLength(code, orderHeader, srcBuf); - - int pixelA = readPixel(bpp, srcBuf); - int pixelB = readPixel(bpp, srcBuf); - - for (; runLength > 0; runLength--) { - writePixel(bpp, destBuf, pixelA); - writePixel(bpp, destBuf, pixelB); - } - - continue; - } - - // - // Handle Color Run Orders. - // - if (code == REGULAR_COLOR_RUN | code == MEGA_MEGA_COLOR_RUN) { - int runLength = extractRunLength(code, orderHeader, srcBuf); - - int pixelA = readPixel(bpp, srcBuf); - - for (; runLength > 0; runLength--) - writePixel(bpp, destBuf, pixelA); - - continue; - } - - // - // Handle Foreground/Background Image Orders. - // - if (code == REGULAR_FGBG_IMAGE | code == MEGA_MEGA_FGBG_IMAGE | code == LITE_SET_FG_FGBG_IMAGE | code == MEGA_MEGA_SET_FGBG_IMAGE) { - int runLength = extractRunLength(code, orderHeader, srcBuf); - - if (code == LITE_SET_FG_FGBG_IMAGE | code == MEGA_MEGA_SET_FGBG_IMAGE) { - fgPel = readPixel(bpp, srcBuf); - } - - for (; runLength > 8; runLength -= 8) { - int bitmask = srcBuf.readUnsignedByte(); - - if (firstLine) - writeFirstLineFgBgImage(bpp, destBuf, bitmask, fgPel, 8); - else - writeFgBgImage(bpp, destBuf, rowDelta, bitmask, fgPel, 8); - } - - if (runLength > 0) { - int bitmask = srcBuf.readUnsignedByte(); - - if (firstLine) - writeFirstLineFgBgImage(bpp, destBuf, bitmask, fgPel, runLength); - else - writeFgBgImage(bpp, destBuf, rowDelta, bitmask, fgPel, runLength); - } - - continue; - } - - // - // Handle Color Image Orders. - // - if (code == REGULAR_COLOR_IMAGE | code == MEGA_MEGA_COLOR_IMAGE) { - int runLength = extractRunLength(code, orderHeader, srcBuf); - - /* DEBUG */ - // Copy bytes from source to destination using writeByte(readByte()) - // for (int byteCount = runLength * bpp; byteCount > 0; byteCount--) { - // destBuf.writeByte(srcBuf.readUnsignedByte()); - // } - /* DEBUG */ - - // Copy bytes from source to destination directly using arraycopy() - int lengthInBytes = runLength * bpp; - System.arraycopy(srcBuf.data, srcBuf.offset + srcBuf.cursor, destBuf.data, destBuf.offset + destBuf.cursor, lengthInBytes); - srcBuf.cursor += lengthInBytes; - destBuf.cursor += lengthInBytes; - - continue; - } - - // - // Handle Special Order 1. - // - if (code == SPECIAL_FGBG_1) { - if (firstLine) - writeFirstLineFgBgImage(bpp, destBuf, g_MaskSpecialFgBg1, fgPel, 8); - else - writeFgBgImage(bpp, destBuf, rowDelta, g_MaskSpecialFgBg1, fgPel, 8); - - continue; - } - - // - // Handle Special Order 2. - // - if (code == SPECIAL_FGBG_2) { - if (firstLine) - writeFirstLineFgBgImage(bpp, destBuf, g_MaskSpecialFgBg2, fgPel, 8); - else - writeFgBgImage(bpp, destBuf, rowDelta, g_MaskSpecialFgBg2, fgPel, 8); - - continue; - } - - // - // Handle White Order. - // - if (code == SPECIAL_WHITE) { - writePixel(bpp, destBuf, whitePixel); - - continue; - } - - // - // Handle Black Order. - // - if (code == SPECIAL_BLACK) { - writePixel(bpp, destBuf, blackPixel); - - continue; - } - - throw new RuntimeException("Unknown code: " + code + "."); - } - } - - /** - * Flip image in vertical direction. - */ - public static ByteBuffer flipRawImage(ByteBuffer src, int width, int height, int bpp) { - if (width * height * bpp != src.length) - throw new RuntimeException("Incorrect size of buffer. Expected size (imageWidth*imageHeight*bpp): " + (width * height * bpp) + ", actual size: " + - src.length + "."); - ByteBuffer dest = new ByteBuffer(new byte[src.length]); - - int scanLine = width * bpp; - - for (int i = 0; i < height; i++) { - // Copy one row - System.arraycopy(src.data, (height - i - 1) * scanLine, dest.data, i * scanLine, scanLine); - } - - return dest; - - } - - /** - * Example. - */ - public static void main(String args[]) { - - if (true) { - // 16x1@8bpp, all black - int width = 16, height = 1, depth = 8, bpp = depth / 8; - ByteBuffer src = new ByteBuffer(new byte[] {0x10}); - ByteBuffer dest = new AssertingByteBuffer(new byte[width * height * bpp]); - rleDecompress(src, dest, width, height, depth); - } - - if (true) { - // 16x1@16bpp, all black - int width = 16, height = 1, depth = 16, bpp = depth / 8; - ByteBuffer src = new ByteBuffer(new byte[] {0x0c, (byte)0x84, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}); - ByteBuffer dest = new AssertingByteBuffer(new byte[width * height * bpp]); - rleDecompress(src, dest, width, height, depth); - } - - if (true) { - // 32x32@8 - int width = 32, height = 32, depth = 8, bpp = depth / 8; - - ByteBuffer src = - new ByteBuffer(new byte[] {(byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x80, (byte)0x00, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, - (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0xec, (byte)0x6c, (byte)0x0e, (byte)0x0e, (byte)0x44, (byte)0x0e, - (byte)0x0e, (byte)0x0e, (byte)0x13, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, - (byte)0x06, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0xe4, (byte)0x04, (byte)0x06, (byte)0x8e, (byte)0x60, (byte)0x0e, (byte)0x60, (byte)0x8c, - (byte)0xb4, (byte)0xb5, (byte)0xdc, (byte)0xdc, (byte)0xbb, (byte)0xb4, (byte)0x8c, (byte)0x66, (byte)0x0b, (byte)0x6c, (byte)0xe4, (byte)0x04, - (byte)0x06, (byte)0x02, (byte)0x8b, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0xf8, (byte)0x0e, (byte)0x66, - (byte)0xb4, (byte)0xdc, (byte)0x68, (byte)0xe2, (byte)0x97, (byte)0xdd, (byte)0xb4, (byte)0xa7, (byte)0x16, (byte)0x06, (byte)0x06, (byte)0x06, - (byte)0xed, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x06, - (byte)0x0b, (byte)0xae, (byte)0xdc, (byte)0xe9, (byte)0x6a, (byte)0xdc, (byte)0x96, (byte)0xe9, (byte)0xe9, (byte)0xb4, (byte)0x0e, (byte)0x00, - (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x06, - (byte)0x0e, (byte)0xae, (byte)0xdc, (byte)0xdb, (byte)0xdb, (byte)0xd0, (byte)0x09, (byte)0x07, (byte)0xcf, (byte)0x03, (byte)0x95, (byte)0xdb, - (byte)0xdb, (byte)0xdc, (byte)0xb4, (byte)0x66, (byte)0x6c, (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x04, - (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x0b, (byte)0xae, (byte)0xdb, (byte)0xd4, (byte)0xd5, (byte)0x6c, (byte)0xdb, (byte)0x80, (byte)0xaf, - (byte)0xd5, (byte)0xd4, (byte)0xdb, (byte)0xb4, (byte)0x66, (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0xed, - (byte)0x06, (byte)0xed, (byte)0x66, (byte)0xae, (byte)0xd5, (byte)0xad, (byte)0xd4, (byte)0xd4, (byte)0xd5, (byte)0xd5, (byte)0xd5, (byte)0xdb, - (byte)0xb4, (byte)0xb4, (byte)0xb4, (byte)0xb4, (byte)0xb4, (byte)0xd5, (byte)0xd5, (byte)0xd5, (byte)0xd4, (byte)0xd4, (byte)0xad, (byte)0xd5, - (byte)0xb4, (byte)0x0e, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x60, (byte)0xa7, (byte)0xb4, - (byte)0xad, (byte)0xad, (byte)0xad, (byte)0xb3, (byte)0xb3, (byte)0xd4, (byte)0xd4, (byte)0xb3, (byte)0x8c, (byte)0xb6, (byte)0x07, (byte)0xb6, - (byte)0x8c, (byte)0xb3, (byte)0xd4, (byte)0xb3, (byte)0xb3, (byte)0xad, (byte)0xad, (byte)0xad, (byte)0xb4, (byte)0xad, (byte)0x66, (byte)0x00, - (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x06, (byte)0x66, (byte)0xae, (byte)0xad, (byte)0x8b, (byte)0xad, (byte)0xad, (byte)0xad, - (byte)0xad, (byte)0xad, (byte)0xb3, (byte)0xad, (byte)0xb5, (byte)0x07, (byte)0x07, (byte)0x07, (byte)0xf0, (byte)0x8b, (byte)0xad, (byte)0xad, - (byte)0xad, (byte)0xad, (byte)0xad, (byte)0x8b, (byte)0xa7, (byte)0xae, (byte)0xa7, (byte)0x6c, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x04, - (byte)0x6c, (byte)0xa7, (byte)0xad, (byte)0xa7, (byte)0xa7, (byte)0x8b, (byte)0xad, (byte)0xad, (byte)0xad, (byte)0xad, (byte)0xad, (byte)0xad, - (byte)0xb5, (byte)0xbd, (byte)0xbd, (byte)0xbd, (byte)0xbd, (byte)0xf0, (byte)0x8b, (byte)0x8b, (byte)0xad, (byte)0x8b, (byte)0x8b, (byte)0xa7, - (byte)0xa7, (byte)0xc8, (byte)0xc8, (byte)0x60, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x66, (byte)0xc8, (byte)0xa7, (byte)0x66, - (byte)0xa7, (byte)0xa7, (byte)0x8b, (byte)0x8b, (byte)0x8b, (byte)0x8b, (byte)0xad, (byte)0x8b, (byte)0x92, (byte)0xf1, (byte)0xf1, (byte)0xf1, - (byte)0xf1, (byte)0xf2, (byte)0x07, (byte)0xa7, (byte)0xa7, (byte)0x8b, (byte)0xa7, (byte)0xa7, (byte)0x66, (byte)0x66, (byte)0xc8, (byte)0x66, - (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x60, (byte)0xa7, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0xa7, (byte)0xa7, (byte)0xa7, - (byte)0xa7, (byte)0x8b, (byte)0x8b, (byte)0x8b, (byte)0xa7, (byte)0xb6, (byte)0xf3, (byte)0xf3, (byte)0xf3, (byte)0xf3, (byte)0xf3, (byte)0x07, - (byte)0x66, (byte)0xa7, (byte)0xa7, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0xa7, (byte)0xa7, (byte)0x6c, (byte)0x00, (byte)0x00, (byte)0x6c, - (byte)0x04, (byte)0xa7, (byte)0x60, (byte)0x6b, (byte)0x66, (byte)0x99, (byte)0xb6, (byte)0xf5, (byte)0xf5, (byte)0xf5, (byte)0xf5, (byte)0xf5, - (byte)0xef, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0xa7, (byte)0x66, (byte)0x00, (byte)0x00, (byte)0x60, - (byte)0xa7, (byte)0x66, (byte)0x60, (byte)0x66, (byte)0x66, (byte)0x8c, (byte)0xf1, (byte)0x6e, (byte)0xff, (byte)0x85, (byte)0xbd, (byte)0x66, - (byte)0x66, (byte)0x66, (byte)0x60, (byte)0x05, (byte)0x87, (byte)0x13, (byte)0x04, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0xf4, - (byte)0x70, (byte)0xff, (byte)0x84, (byte)0xbd, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x05, (byte)0x85, (byte)0x0b, (byte)0xa7, (byte)0xb5, - (byte)0xae, (byte)0x8c, (byte)0xd0, (byte)0x13, (byte)0xc1, (byte)0x01, (byte)0x00, (byte)0x08, (byte)0x8e, (byte)0x8c, (byte)0xae, (byte)0xb5, - (byte)0xae, (byte)0x66, (byte)0x00, (byte)0x00, (byte)0x6c, (byte)0xae, (byte)0xbc, (byte)0xb5, (byte)0xb5, (byte)0xae, (byte)0xb5, (byte)0xd0, - (byte)0x0e, (byte)0x0c, (byte)0x01, (byte)0x00, (byte)0x90, (byte)0xf2, (byte)0xae, (byte)0xae, (byte)0xb5, (byte)0xb5, (byte)0xbc, (byte)0xb5, - (byte)0x66, (byte)0x00, (byte)0x00, (byte)0x04, (byte)0xae, (byte)0x0a, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0x68, (byte)0xae, (byte)0x82, - (byte)0x8c, (byte)0x0a, (byte)0x05, (byte)0x8c, (byte)0xf2, (byte)0xae, (byte)0xae, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xbc, (byte)0xb5, - (byte)0x6c, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x05, (byte)0x81, (byte)0xd0, (byte)0x06, (byte)0x9a, (byte)0x8c, (byte)0x0a, (byte)0xff, - (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xf2, (byte)0xae, (byte)0xae, (byte)0xd0, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0x0a, - (byte)0xb5, (byte)0x6c, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x8b, (byte)0x0a, (byte)0xbc, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0x06, - (byte)0x9b, (byte)0xb6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xf2, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xb5, - (byte)0xb5, (byte)0xb5, (byte)0xb6, (byte)0x0a, (byte)0x8c, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x6c, (byte)0xb5, (byte)0x0a, - (byte)0xb6, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0x05, (byte)0x80, (byte)0x7d, (byte)0xbc, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, - (byte)0xf2, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb6, (byte)0x0a, (byte)0x0a, (byte)0x8b, (byte)0x06, - (byte)0x00, (byte)0x00, (byte)0x04, (byte)0x06, (byte)0x87, (byte)0x0a, (byte)0xbc, (byte)0xb6, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xd0, - (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xb6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xf2, (byte)0xd0, (byte)0xae, (byte)0xd0, (byte)0xb5, - (byte)0xb5, (byte)0xb5, (byte)0xb6, (byte)0xbc, (byte)0x1a, (byte)0xb5, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0xed, (byte)0x06, - (byte)0x6e, (byte)0xb5, (byte)0x0a, (byte)0xbc, (byte)0xb6, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xd0, (byte)0xd0, (byte)0xd0, (byte)0xb5, - (byte)0xf4, (byte)0xff, (byte)0xf2, (byte)0xd0, (byte)0xd0, (byte)0xd0, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb6, (byte)0xbc, (byte)0x0a, - (byte)0x0a, (byte)0x8b, (byte)0x06, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x04, (byte)0x8b, (byte)0xbc, (byte)0x1a, - (byte)0x0a, (byte)0xb6, (byte)0xb6, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xd0, (byte)0xb5, (byte)0xb5, (byte)0xb5, - (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb6, (byte)0xb6, (byte)0x0a, (byte)0xde, (byte)0x0a, (byte)0xa7, (byte)0x06, (byte)0x00, (byte)0x06, - (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x8b, (byte)0xbc, (byte)0xf2, (byte)0x0a, (byte)0xb6, (byte)0xb6, - (byte)0xb6, (byte)0xb6, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb6, (byte)0xb6, (byte)0xb6, (byte)0xb6, - (byte)0x0a, (byte)0xf2, (byte)0x1a, (byte)0x8c, (byte)0xec, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x04, (byte)0x06, - (byte)0x04, (byte)0x06, (byte)0x04, (byte)0xa7, (byte)0xbc, (byte)0x1a, (byte)0x0a, (byte)0x0a, (byte)0x6a, (byte)0xb6, (byte)0x96, (byte)0x0a, - (byte)0x0a, (byte)0xf2, (byte)0x0a, (byte)0x87, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x06, - (byte)0x06, (byte)0xed, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x8c, (byte)0xb6, (byte)0xf4, (byte)0xf2, (byte)0xd0, (byte)0x09, (byte)0xbc, - (byte)0x87, (byte)0x03, (byte)0x80, (byte)0x2c, (byte)0xde, (byte)0xf4, (byte)0x0a, (byte)0x8b, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, - (byte)0xed, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x06, (byte)0x04, (byte)0x6c, - (byte)0x87, (byte)0x0a, (byte)0xf4, (byte)0xf4, (byte)0xf2, (byte)0xde, (byte)0xbd, (byte)0xbd, (byte)0xde, (byte)0xf2, (byte)0xf4, (byte)0xf4, - (byte)0x0a, (byte)0xd0, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x06, (byte)0x00, (byte)0x00, - (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x6c, (byte)0x8c, (byte)0xb5, - (byte)0xbc, (byte)0x0a, (byte)0xde, (byte)0xf2, (byte)0xbd, (byte)0x0a, (byte)0xb5, (byte)0x8c, (byte)0x6c, (byte)0x06, (byte)0xed, (byte)0x06, - (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0xe6, (byte)0x04, (byte)0x06, (byte)0x86, - (byte)0x04, (byte)0x6c, (byte)0x04, (byte)0x8b, (byte)0x04, (byte)0x6c, (byte)0xe6, (byte)0x04, (byte)0x06, (byte)0x82, (byte)0x00, (byte)0x00 - - }); - - ByteBuffer flippedImage = - new ByteBuffer(new byte[] {(byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, - (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x6c, (byte)0x04, (byte)0x8b, (byte)0x04, (byte)0x6c, (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, - (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x06, - (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x6c, (byte)0x8c, (byte)0xb5, (byte)0xbc, (byte)0x0a, - (byte)0xde, (byte)0xf2, (byte)0xbd, (byte)0x0a, (byte)0xb5, (byte)0x8c, (byte)0x6c, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x06, - (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x06, - (byte)0x04, (byte)0x6c, (byte)0x87, (byte)0x0a, (byte)0xf4, (byte)0xf4, (byte)0xf2, (byte)0xde, (byte)0xbd, (byte)0xbd, (byte)0xde, (byte)0xf2, - (byte)0xf4, (byte)0xf4, (byte)0x0a, (byte)0xd0, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x06, - (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x8c, (byte)0xb6, (byte)0xf4, (byte)0xf2, - (byte)0x0a, (byte)0x0a, (byte)0x0a, (byte)0xb6, (byte)0xb6, (byte)0xb6, (byte)0xb6, (byte)0x0a, (byte)0x0a, (byte)0x0a, (byte)0xde, (byte)0xf4, - (byte)0x0a, (byte)0x8b, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x04, (byte)0x06, - (byte)0x04, (byte)0x06, (byte)0x04, (byte)0xa7, (byte)0xbc, (byte)0x1a, (byte)0x0a, (byte)0x0a, (byte)0xb6, (byte)0xb6, (byte)0xb6, (byte)0xb6, - (byte)0xb6, (byte)0xb6, (byte)0xb6, (byte)0xb6, (byte)0xb6, (byte)0xb6, (byte)0x0a, (byte)0x0a, (byte)0xf2, (byte)0x0a, (byte)0x87, (byte)0x06, - (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x8b, (byte)0xbc, - (byte)0xf2, (byte)0x0a, (byte)0xb6, (byte)0xb6, (byte)0xb6, (byte)0xb6, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb5, - (byte)0xb6, (byte)0xb6, (byte)0xb6, (byte)0xb6, (byte)0x0a, (byte)0xf2, (byte)0x1a, (byte)0x8c, (byte)0xec, (byte)0x06, (byte)0x06, (byte)0x06, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x04, (byte)0x8b, (byte)0xbc, (byte)0x1a, (byte)0x0a, (byte)0xb6, (byte)0xb6, (byte)0xb5, - (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xd0, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb6, - (byte)0xb6, (byte)0x0a, (byte)0xde, (byte)0x0a, (byte)0xa7, (byte)0x06, (byte)0x00, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0xed, (byte)0x06, - (byte)0x6e, (byte)0xb5, (byte)0x0a, (byte)0xbc, (byte)0xb6, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xd0, (byte)0xd0, (byte)0xd0, (byte)0xb5, - (byte)0xf4, (byte)0xff, (byte)0xf2, (byte)0xd0, (byte)0xd0, (byte)0xd0, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb6, (byte)0xbc, (byte)0x0a, - (byte)0x0a, (byte)0x8b, (byte)0x06, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x04, (byte)0x06, (byte)0x87, (byte)0x0a, (byte)0xbc, (byte)0xb6, - (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xd0, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xb6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xf2, - (byte)0xd0, (byte)0xae, (byte)0xd0, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb6, (byte)0xbc, (byte)0x1a, (byte)0xb5, (byte)0x04, (byte)0x06, - (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x6c, (byte)0xb5, (byte)0x0a, (byte)0xb6, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xae, (byte)0xae, - (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xbc, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xf2, (byte)0xae, (byte)0xae, (byte)0xae, - (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb6, (byte)0x0a, (byte)0x0a, (byte)0x8b, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x8b, - (byte)0x0a, (byte)0xbc, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xb6, - (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xf2, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xb5, (byte)0xb5, (byte)0xb5, - (byte)0xb6, (byte)0x0a, (byte)0x8c, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0xae, (byte)0x0a, (byte)0xb5, (byte)0xb5, (byte)0xb5, - (byte)0xd0, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0x8c, (byte)0x0a, (byte)0xff, (byte)0xff, (byte)0xff, - (byte)0xff, (byte)0xff, (byte)0xf2, (byte)0xae, (byte)0xae, (byte)0xd0, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0x0a, (byte)0xb5, (byte)0x6c, - (byte)0x00, (byte)0x00, (byte)0x04, (byte)0xae, (byte)0x0a, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xae, - (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0x8c, (byte)0x0a, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xf2, - (byte)0xae, (byte)0xae, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xbc, (byte)0xb5, (byte)0x6c, (byte)0x00, (byte)0x00, (byte)0x6c, (byte)0xae, - (byte)0xbc, (byte)0xb5, (byte)0xb5, (byte)0xae, (byte)0xb5, (byte)0xf3, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, - (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xf2, (byte)0xae, (byte)0xae, (byte)0xb5, - (byte)0xb5, (byte)0xbc, (byte)0xb5, (byte)0x66, (byte)0x00, (byte)0x00, (byte)0x0b, (byte)0xa7, (byte)0xb5, (byte)0xae, (byte)0x8c, (byte)0xa7, - (byte)0xf4, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, - (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xbd, (byte)0xa7, (byte)0x8c, (byte)0xae, (byte)0xb5, (byte)0xae, (byte)0x66, - (byte)0x00, (byte)0x00, (byte)0x13, (byte)0x04, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0xf4, (byte)0xff, (byte)0xff, (byte)0xff, - (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, - (byte)0xff, (byte)0xbd, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0xa7, (byte)0x66, (byte)0x00, (byte)0x00, (byte)0x60, (byte)0xa7, - (byte)0x66, (byte)0x60, (byte)0x66, (byte)0x66, (byte)0x8c, (byte)0xf1, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, - (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xbd, (byte)0x66, (byte)0x66, (byte)0x66, - (byte)0x60, (byte)0x66, (byte)0xa7, (byte)0x66, (byte)0x00, (byte)0x00, (byte)0x6c, (byte)0x04, (byte)0xa7, (byte)0x60, (byte)0x66, (byte)0x66, - (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0xb6, (byte)0xf5, (byte)0xf5, - (byte)0xf5, (byte)0xf5, (byte)0xf5, (byte)0xef, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0xa7, (byte)0x66, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x60, (byte)0xa7, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0xa7, (byte)0xa7, (byte)0xa7, (byte)0xa7, - (byte)0x8b, (byte)0x8b, (byte)0x8b, (byte)0xa7, (byte)0xb6, (byte)0xf3, (byte)0xf3, (byte)0xf3, (byte)0xf3, (byte)0xf3, (byte)0x07, (byte)0x66, - (byte)0xa7, (byte)0xa7, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0xa7, (byte)0xa7, (byte)0x6c, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x66, - (byte)0xc8, (byte)0xa7, (byte)0x66, (byte)0xa7, (byte)0xa7, (byte)0x8b, (byte)0x8b, (byte)0x8b, (byte)0x8b, (byte)0xad, (byte)0x8b, (byte)0x92, - (byte)0xf1, (byte)0xf1, (byte)0xf1, (byte)0xf1, (byte)0xf2, (byte)0x07, (byte)0xa7, (byte)0xa7, (byte)0x8b, (byte)0xa7, (byte)0xa7, (byte)0x66, - (byte)0x66, (byte)0xc8, (byte)0x66, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x04, (byte)0x6c, (byte)0xa7, (byte)0xad, (byte)0xa7, (byte)0xa7, - (byte)0x8b, (byte)0xad, (byte)0xad, (byte)0xad, (byte)0xad, (byte)0xad, (byte)0xad, (byte)0xb5, (byte)0xbd, (byte)0xbd, (byte)0xbd, (byte)0xbd, - (byte)0xf0, (byte)0x8b, (byte)0x8b, (byte)0xad, (byte)0x8b, (byte)0x8b, (byte)0xa7, (byte)0xa7, (byte)0xc8, (byte)0xc8, (byte)0x60, (byte)0x06, - (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x06, (byte)0x66, (byte)0xae, (byte)0xad, (byte)0x8b, (byte)0xad, (byte)0xad, (byte)0xad, (byte)0xad, - (byte)0xad, (byte)0xb3, (byte)0xad, (byte)0xb5, (byte)0x07, (byte)0x07, (byte)0x07, (byte)0xf0, (byte)0x8b, (byte)0xad, (byte)0xad, (byte)0xad, - (byte)0xad, (byte)0xad, (byte)0x8b, (byte)0xa7, (byte)0xae, (byte)0xa7, (byte)0x6c, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x06, - (byte)0x60, (byte)0xa7, (byte)0xb4, (byte)0xad, (byte)0xad, (byte)0xad, (byte)0xb3, (byte)0xb3, (byte)0xd4, (byte)0xd4, (byte)0xb3, (byte)0x8c, - (byte)0xb6, (byte)0x07, (byte)0xb6, (byte)0x8c, (byte)0xb3, (byte)0xd4, (byte)0xb3, (byte)0xb3, (byte)0xad, (byte)0xad, (byte)0xad, (byte)0xb4, - (byte)0xad, (byte)0x66, (byte)0x00, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0xed, (byte)0x06, (byte)0xed, (byte)0x66, (byte)0xae, (byte)0xd5, - (byte)0xad, (byte)0xd4, (byte)0xd4, (byte)0xd5, (byte)0xd5, (byte)0xd5, (byte)0xdb, (byte)0xb4, (byte)0xb4, (byte)0xb4, (byte)0xb4, (byte)0xb4, - (byte)0xd5, (byte)0xd5, (byte)0xd5, (byte)0xd4, (byte)0xd4, (byte)0xad, (byte)0xd5, (byte)0xb4, (byte)0x0e, (byte)0x06, (byte)0x06, (byte)0x06, - (byte)0x00, (byte)0x00, (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x0b, (byte)0xae, (byte)0xdb, (byte)0xd4, (byte)0xd5, (byte)0xdb, - (byte)0xdb, (byte)0xdb, (byte)0xdb, (byte)0xdb, (byte)0xdb, (byte)0xdb, (byte)0xdb, (byte)0xdb, (byte)0xdb, (byte)0xdb, (byte)0xdb, (byte)0xd5, - (byte)0xd4, (byte)0xdb, (byte)0xb4, (byte)0x66, (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x06, - (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x0e, (byte)0xae, (byte)0xdc, (byte)0xdb, (byte)0xdb, (byte)0xdb, (byte)0xdb, (byte)0xdb, (byte)0xdb, - (byte)0xdc, (byte)0xdc, (byte)0xdb, (byte)0xdb, (byte)0xdb, (byte)0xdb, (byte)0xdb, (byte)0xdb, (byte)0xdc, (byte)0xb4, (byte)0x66, (byte)0x6c, - (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x06, - (byte)0x0b, (byte)0xae, (byte)0xdc, (byte)0xe9, (byte)0xdc, (byte)0xdc, (byte)0xdc, (byte)0xdc, (byte)0xdc, (byte)0xdc, (byte)0xdc, (byte)0xdc, - (byte)0xdc, (byte)0xdc, (byte)0xe9, (byte)0xe9, (byte)0xb4, (byte)0x0e, (byte)0x00, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x06, - (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0xf8, (byte)0x0e, (byte)0x66, (byte)0xb4, - (byte)0xdc, (byte)0xe2, (byte)0xe2, (byte)0xe2, (byte)0xe2, (byte)0xe2, (byte)0xe2, (byte)0xe2, (byte)0xe2, (byte)0xdd, (byte)0xb4, (byte)0xa7, - (byte)0x16, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x04, (byte)0x06, - (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x60, (byte)0x0e, (byte)0x60, (byte)0x8c, (byte)0xb4, (byte)0xb5, - (byte)0xdc, (byte)0xdc, (byte)0xbb, (byte)0xb4, (byte)0x8c, (byte)0x66, (byte)0x0b, (byte)0x6c, (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, - (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x06, - (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0xec, (byte)0x6c, (byte)0x0e, (byte)0x0e, (byte)0x44, (byte)0x0e, (byte)0x0e, (byte)0x0e, - (byte)0x13, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x06, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00}); - ByteBuffer dest = new AssertingByteBuffer(flipRawImage(flippedImage, width, height, bpp).data); - - rleDecompress(src, dest, width, height, depth); - - } - - if (true) { - // 32x32@16 - int width = 32, height = 32, depth = 16; - - ByteBuffer src = - new ByteBuffer(new byte[] {(byte)0x85, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x06, (byte)0x8b, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, - (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x06, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0x16, - (byte)0x69, (byte)0x99, (byte)0xd6, (byte)0x06, (byte)0x69, (byte)0x99, (byte)0xd6, (byte)0x04, (byte)0xcc, (byte)0x89, (byte)0x52, (byte)0x03, - (byte)0x6e, (byte)0xff, (byte)0xff, (byte)0x02, (byte)0x6e, (byte)0x08, (byte)0x42, (byte)0x01, (byte)0x70, (byte)0x08, (byte)0x42, (byte)0x71, - (byte)0xff, (byte)0xff, (byte)0xce, (byte)0x18, (byte)0xc6, (byte)0x01, (byte)0x81, (byte)0x08, (byte)0x42, (byte)0xce, (byte)0x66, (byte)0x29, - (byte)0x02, (byte)0xcd, (byte)0x89, (byte)0x52, (byte)0x03, (byte)0x88, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, - (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xd8, (byte)0x99, - (byte)0xd6, (byte)0x03, (byte)0xf8, (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xf0, (byte)0x66, (byte)0x99, (byte)0xd6, - (byte)0x05, (byte)0x6a, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0xc4, (byte)0xcc, (byte)0x89, (byte)0x52, (byte)0x03, (byte)0x6e, (byte)0xff, - (byte)0xff, (byte)0x02, (byte)0x6e, (byte)0x08, (byte)0x42, (byte)0x01, (byte)0x70, (byte)0x08, (byte)0x42, (byte)0x71, (byte)0xff, (byte)0xff, - (byte)0xce, (byte)0x18, (byte)0xc6, (byte)0x01, (byte)0x81, (byte)0x08, (byte)0x42, (byte)0xce, (byte)0x66, (byte)0x29, (byte)0x02, (byte)0xcd, - (byte)0x89, (byte)0x52, (byte)0x03, (byte)0x00, (byte)0x04, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xc3, (byte)0x80, (byte)0x61, (byte)0x00, - (byte)0xa5, (byte)0x80, (byte)0x40, (byte)0xec, (byte)0x52, (byte)0x00, (byte)0x5a, (byte)0x00, (byte)0x2d, (byte)0x00, (byte)0x24, (byte)0x00, - (byte)0x12, (byte)0x00, (byte)0x24, (byte)0x00, (byte)0x12, (byte)0x00, (byte)0x5a, (byte)0x00, (byte)0x2d, (byte)0x00, (byte)0xa5, (byte)0x80, - (byte)0x52, (byte)0x00, (byte)0xc3, (byte)0x80, (byte)0x61, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xcc, (byte)0x89, - (byte)0x52, (byte)0x03, (byte)0x6e, (byte)0xff, (byte)0xff, (byte)0x02, (byte)0xcb, (byte)0x18, (byte)0xc6, (byte)0x84, (byte)0x08, (byte)0x42, - (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0xff, (byte)0xff,}); - - ByteBuffer dest = - new AssertingByteBuffer(new byte[] {(byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, - (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, - (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, - (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x10, - (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, - (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x99, - (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, - (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, - (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x08, (byte)0x42, (byte)0x08, - (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, - (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, - (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0xff, (byte)0xff, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, - (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, - (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, - (byte)0x42, (byte)0x08, (byte)0x42, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, - (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, - (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, - (byte)0xff, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, - (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, - (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, - (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, - (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, - (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, - (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, - (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, - (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, - (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, - (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, - (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, - (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, - (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, - (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, - (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, - (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, - (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, - (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, - (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, - (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, - (byte)0x42, (byte)0xff, (byte)0xff, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, - (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, - (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0xff, - (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, - (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, - (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x10, (byte)0x84, (byte)0x10, - (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, - (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, - (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, - (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, - (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, - (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, - (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, - (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, - (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, - (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, - (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, - (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, - (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, - (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, - (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, - (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, - (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, - (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, - (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, - (byte)0xff, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, - (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, - (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0xff, (byte)0xff,}); - - rleDecompress(src, dest, width, height, depth); - - } - } -} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/RdpClient.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/RdpClient.java old mode 100644 new mode 100755 index 825964f6a2d..a3db165c2fa --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/RdpClient.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/RdpClient.java @@ -16,27 +16,87 @@ // under the License. package rdpclient; +import java.net.InetAddress; +import java.net.UnknownHostException; + +import rdpclient.adapter.AwtRdpKeyboardAdapter; +import rdpclient.adapter.AwtRdpMouseAdapter; +import rdpclient.hyperv.ClientPreConnectionBlob; +import rdpclient.ntlmssp.ClientNtlmsspNegotiate; +import rdpclient.ntlmssp.ClientNtlmsspPubKeyAuth; +import rdpclient.ntlmssp.ClientNtlmsspUserCredentials; +import rdpclient.ntlmssp.NtlmState; +import rdpclient.ntlmssp.ServerNtlmsspChallenge; +import rdpclient.ntlmssp.ServerNtlmsspPubKeyPlus1; +import rdpclient.rdp.ClientConfirmActivePDU; +import rdpclient.rdp.ClientFastPathPDU; +import rdpclient.rdp.ClientInfoPDU; +import rdpclient.rdp.ClientMCSAttachUserRequest; +import rdpclient.rdp.ClientMCSChannelJoinRequestServerMCSChannelConfirmPDUs; +import rdpclient.rdp.ClientMCSConnectInitial; +import rdpclient.rdp.ClientMCSErectDomainRequest; +import rdpclient.rdp.ClientTpkt; +import rdpclient.rdp.ClientX224ConnectionRequestPDU; +import rdpclient.rdp.ClientX224DataPDU; +import rdpclient.rdp.RdpConstants; +import rdpclient.rdp.RdpState; +import rdpclient.rdp.ServerBitmapUpdate; +import rdpclient.rdp.ServerDemandActivePDU; +import rdpclient.rdp.ServerFastPath; +import rdpclient.rdp.ServerIOChannelRouter; +import rdpclient.rdp.ServerLicenseErrorPDUValidClient; +import rdpclient.rdp.ServerMCSAttachUserConfirmPDU; +import rdpclient.rdp.ServerMCSConnectResponse; +import rdpclient.rdp.ServerMCSPDU; +import rdpclient.rdp.ServerPaletteUpdate; +import rdpclient.rdp.ServerX224ConnectionConfirmPDU; +import rdpclient.rdp.ServerX224DataPdu; import streamer.PipelineImpl; import streamer.Queue; -import common.AwtCanvasAdapter; +import streamer.ssl.SSLState; +import streamer.ssl.UpgradeSocketToSSL; import common.AwtKeyEventSource; import common.AwtMouseEventSource; import common.BufferedImageCanvas; import common.ScreenDescription; +import common.adapter.AwtCanvasAdapter; public class RdpClient extends PipelineImpl { + AwtMouseEventSource mouseEventSource = null; + AwtKeyEventSource keyEventSource = null; + /** * Name of last OneTimePacket in handshake sequence. */ private static final String HANDSHAKE_END = "server_valid_client"; - public RdpClient(String id, String userName, ScreenDescription screen, BufferedImageCanvas canvas) { + /** + * Create new RDP or HyperV cli + * + * @param id + * id of this element + * @param userName + * user name + * @param password + * password + * @param pcb + * pre-connection blob for HyperV server or null/empty string to + * disable. Usually, HyperV VM ID, e.g. + * "39418F90-6D03-468E-B796-91C60DD6653A". + * @param screen + * screen description to fill + * @param canvas + * canvas to draw on + * @param sslState + */ + public RdpClient(String id, String serverHostName, String domain, String userName, String password, String pcb, ScreenDescription screen, + BufferedImageCanvas canvas, SSLState sslState) { super(id); - assembleRDPPipeline(userName, screen, canvas); + assembleRDPPipeline(serverHostName, domain, userName, password, pcb, screen, canvas, sslState); } -// /* DEBUG */ + // /* DEBUG */ // @Override // protected HashMap initElementMap(String id) { // HashMap map = new HashMap(); @@ -45,72 +105,195 @@ public class RdpClient extends PipelineImpl { // return map; // } - private void assembleRDPPipeline(String userName, ScreenDescription screen, BufferedImageCanvas canvas) { + /** + * Assemble connection sequence and main pipeline. + * + * Connection sequence for RDP w/o NLA: cookie(TPKT) SSL x224(TPKT) + * main(FastPath). + * + * Connection sequence for RDP w NLA: cookie(TPKT) SSL credssp x224(TPKT) + * main(FastPath). + * + * Connection sequence for HyperV w NLA: pcb SSL credssp cookie(TPKT) + * x224(TPKT) main(FastPath). + */ + protected void assembleRDPPipeline(String serverHostName, String domain, String userName, String password, String pcb, ScreenDescription screen, + BufferedImageCanvas canvas, SSLState sslState) { + // If preconnection blob with VM ID is specified, then we are connecting to + // HyperV server + boolean hyperv = (pcb != null && !pcb.isEmpty()); + // HyperV server requires NLA (CredSSP/SPNEGO/NTLMSSP) to connect, because + // it cannot display login screen + boolean credssp = hyperv || (password != null && !password.isEmpty()); + + String workstation; + try { + workstation = InetAddress.getLocalHost().getHostName(); + } catch (UnknownHostException e) { + workstation = "workstation"; + } + // // Handshake chain // RdpState state = new RdpState(); - int[] channelsToJoin = new int[] {RdpConstants.CHANNEL_RDPRDR, RdpConstants.CHANNEL_IO}; + NtlmState ntlmState = new NtlmState(); + + int[] channelsToJoin = new int[] {RdpConstants.CHANNEL_IO, + // RdpConstants.CHANNEL_RDPRDR, // RDPRDR channel is not used in current + // version + + // RdpConstants .CHANNEL_CLIPRDR // Clipboard channel is refused to join :-/ + }; // Add elements - add( + // If pre-connection blob is specified, then add element to send it as + // first packet + if (hyperv) { + add(new ClientPreConnectionBlob("pcb", pcb)); + } - new ClientX224ConnectionRequestPDU("client_connection_req", userName), new ServerX224ConnectionConfirmPDU("server_connection_conf"), + // If password is specified, then use CredSSP/NTLM (NTLMSSP) + int protocol = RdpConstants.RDP_NEG_REQ_PROTOCOL_SSL; + if (credssp) { + protocol = RdpConstants.RDP_NEG_REQ_PROTOCOL_HYBRID; - new UpgradeSocketToSSL("upgrade_to_ssl"), + add( + new ClientNtlmsspNegotiate("client_ntlmssp_nego", ntlmState), - new ClientMCSConnectInitial("client_initial_conference_create"), new ServerMCSConnectResponse("server_initial_conference_create"), + new ServerNtlmsspChallenge("server_ntlmssp_challenge", ntlmState), - new ClientMCSErectDomainRequest("client_erect_domain"), + new ClientNtlmsspPubKeyAuth("client_ntlmssp_auth", ntlmState, sslState, serverHostName, domain, workstation, userName, password), - new ClientMCSAttachUserRequest("client_atach_user"), new ServerMCSAttachUserConfirmPDU("server_atach_user_confirm", state), + new ServerNtlmsspPubKeyPlus1("server_ntlmssp_confirm", ntlmState), - new ClientMCSChannelJoinRequest_ServerMCSChannelConfirmPDUs("client_channel_join_rdprdr", channelsToJoin, state), + new ClientNtlmsspUserCredentials("client_ntlmssp_finish", ntlmState) - new ClientInfoPDU("client_info_req", userName), + ); + } - new ServerLicenseErrorPDUValidClient("server_valid_client"), + add(new ClientX224ConnectionRequestPDU("client_connection_req", userName, protocol), new ServerX224ConnectionConfirmPDU("server_connection_conf"), + new UpgradeSocketToSSL("upgrade_to_ssl"), - new ServerFastPath("server_fastpath"), + new ClientMCSConnectInitial("client_initial_conference_create"), new ServerMCSConnectResponse("server_initial_conference_create"), - new ServerTpkt("server_tpkt"), + new ClientMCSErectDomainRequest("client_erect_domain"), - new ServerX224DataPdu("server_x224_data"), + new ClientMCSAttachUserRequest("client_atach_user"), new ServerMCSAttachUserConfirmPDU("server_atach_user_confirm", state), - // These TPKT and X224 wrappers are connected directly to OUT for handshake - // sequence - new ClientTpkt("client_tpkt_ot"), + new ClientMCSChannelJoinRequestServerMCSChannelConfirmPDUs("client_channel_join_rdprdr", channelsToJoin, state), - new ClientX224DataPdu("client_x224_data_ot") + new ClientInfoPDU("client_info_req", userName), - ); + new ServerLicenseErrorPDUValidClient("server_valid_client"), - // Handshake sequence (via SlowPath) - link("IN", + new ServerFastPath("server_fastpath"), - "server_fastpath >tpkt", "server_tpkt", + // new ServerTpkt("server_tpkt"), - "client_connection_req", "server_connection_conf", + new ServerX224DataPdu("server_x224_data"), - "upgrade_to_ssl", + // These TPKT and X224 wrappers are connected directly to OUT for + // handshake sequence + new ClientTpkt("client_tpkt_ot"), - "client_initial_conference_create", "server_initial_conference_create", + new ClientX224DataPDU("client_x224_data_ot") - "client_erect_domain", + ); - "server_x224_data", + // If HyperV VM ID is set, then insert element which will send VM ID as + // first packet of connection, before other packets + if (hyperv) { - "client_atach_user", "server_atach_user_confirm", + // HyperV: pcb SSL credssp cookie x224 main. - "client_channel_join_rdprdr", + link("IN", - "client_info_req", + // Pre Connection Blob + "pcb", - "server_valid_client" + // Main (will be used after connection seq) or tpkt (to X224) + "server_fastpath >tpkt", - ); + // SSL + "upgrade_to_ssl", + + // CredSSP + "client_ntlmssp_nego", "server_ntlmssp_challenge", "client_ntlmssp_auth", "server_ntlmssp_confirm", "client_ntlmssp_finish", + + // Cookie + "client_connection_req", "server_connection_conf", + + // X224 + "client_initial_conference_create"); + + for (String element : new String[] {"pcb", "client_ntlmssp_nego", "server_ntlmssp_challenge", "client_ntlmssp_auth", "server_ntlmssp_confirm", + "client_ntlmssp_finish"}) { + link(element + " >otout", element + "< OUT"); + + } + + } else { + + // RDP: cookie SSL (credssp) x224 main. + + link("IN", + + // Main or tpkt + "server_fastpath >tpkt", + + // Cookie + "client_connection_req", "server_connection_conf", + + // SSL + "upgrade_to_ssl"); + + if (credssp) { + // SSL + link("upgrade_to_ssl", + + // CredSSP + "client_ntlmssp_nego", "server_ntlmssp_challenge", "client_ntlmssp_auth", "server_ntlmssp_confirm", "client_ntlmssp_finish", + + // X224 + "client_initial_conference_create"); + + for (String element : new String[] {"client_ntlmssp_nego", "server_ntlmssp_challenge", "client_ntlmssp_auth", "server_ntlmssp_confirm", + "client_ntlmssp_finish"}) { + link(element + " >otout", element + "< OUT"); + + } + + } else { + + link( + // SSL + "upgrade_to_ssl", + + // X224 + "client_initial_conference_create"); + } + } + + link( + // X224 + "client_initial_conference_create", "server_initial_conference_create", + + "client_erect_domain", + + "server_x224_data", + + "client_atach_user", "server_atach_user_confirm", + + "client_channel_join_rdprdr", + + "client_info_req", + + "server_valid_client" + + ); // Chain for direct handshake responses (without involving of queue) link("client_x224_data_ot", "client_tpkt_ot", "client_tpkt_ot< OUT"); @@ -122,8 +305,7 @@ public class RdpClient extends PipelineImpl { } // Connect one time outputs to client X224 input - String x224_peers[] = - new String[] {"client_initial_conference_create", "server_initial_conference_create", "client_erect_domain", "client_atach_user", + String x224_peers[] = new String[] {"client_initial_conference_create", "server_initial_conference_create", "client_erect_domain", "client_atach_user", "server_atach_user_confirm", "client_channel_join_rdprdr", "client_info_req", "server_valid_client"}; for (String element : x224_peers) { link(element + " >otout", element + "< client_x224_data_ot"); @@ -134,13 +316,13 @@ public class RdpClient extends PipelineImpl { // add( - // To transfer packets between input threads and output thread. - new Queue("queue"), + // To transfer packets between input threads and output thread. + new Queue("queue"), - // Slow path: MultiChannel Support - new ServerMCSPDU("server_mcs") + // Slow path: MultiChannel Support + new ServerMCSPDU("server_mcs") - ); + ); // Last element of handshake sequence will wake up queue and and socket // output pull loop, which will switch links, between socket output and @@ -154,8 +336,8 @@ public class RdpClient extends PipelineImpl { // Main network // - AwtMouseEventSource mouseEventSource = new AwtMouseEventSource("mouse"); - AwtKeyEventSource keyEventSource = new AwtKeyEventSource("keyboard"); + mouseEventSource = new AwtMouseEventSource("mouse"); + keyEventSource = new AwtKeyEventSource("keyboard"); // Subscribe packet sender to various events canvas.addMouseListener(mouseEventSource); @@ -165,38 +347,38 @@ public class RdpClient extends PipelineImpl { // Add elements add( - new ServerChannel1003Router("server_channel_1003", state), + new ServerIOChannelRouter("server_io_channel", state), - new ServerDemandActivePDU("server_demand_active", screen, state), + new ServerDemandActivePDU("server_demand_active", screen, state), - new ClientConfirmActivePDU("client_confirm_active", screen, state), + new ClientConfirmActivePDU("client_confirm_active", screen, state), - new ServerBitmapUpdate("server_bitmap_update"), + new ServerBitmapUpdate("server_bitmap_update"), - new AwtCanvasAdapter("canvas_adapter", canvas, screen), + new AwtCanvasAdapter("canvas_adapter", canvas, screen), - new ServerPaletteUpdate("server_palette", screen), + new ServerPaletteUpdate("server_palette", screen), - keyEventSource, new AwtRdpKeyboardAdapter("keyboard_adapter"), + keyEventSource, new AwtRdpKeyboardAdapter("keyboard_adapter"), - mouseEventSource, new AwtRdpMouseAdapter("mouse_adapter"), + mouseEventSource, new AwtRdpMouseAdapter("mouse_adapter"), - // These FastPath, TPKT, and X224 wrappers are connected to queue - new ClientTpkt("client_tpkt_queue"), + // These FastPath, TPKT, and X224 wrappers are connected to queue + new ClientTpkt("client_tpkt_queue"), - new ClientX224DataPdu("client_x224_data_queue"), + new ClientX224DataPDU("client_x224_data_queue"), - new ClientFastPathPDU("client_fastpath_queue")); + new ClientFastPathPDU("client_fastpath_queue")); // Server packet handlers - link("server_mcs >channel_1003", "server_channel_1003"); + link("server_mcs >channel_1003", "server_io_channel"); link("server_fastpath >bitmap", "fastpath< server_bitmap_update", "server_bitmap_update< canvas_adapter"); - link("server_channel_1003 >bitmap", "slowpath< server_bitmap_update"); + link("server_io_channel >bitmap", "slowpath< server_bitmap_update"); link("server_fastpath >palette", "fastpath< server_palette"); - link("server_channel_1003 >palette", "slowpath< server_palette"); + link("server_io_channel >palette", "slowpath< server_palette"); - link("server_channel_1003 >demand_active", "slowpath< server_demand_active"); + link("server_io_channel >demand_active", "slowpath< server_demand_active"); // link("server_demand_active >confirm_active", "client_confirm_active", // "confirm_active< client_channel_1003"); link("server_demand_active >confirm_active", "client_confirm_active", "confirm_active< client_x224_data_queue"); @@ -211,4 +393,12 @@ public class RdpClient extends PipelineImpl { link("client_x224_data_queue", "client_tpkt_queue", "client_tpkt_queue< queue"); } + + public AwtMouseEventSource getMouseEventSource() { + return mouseEventSource; + } + + public AwtKeyEventSource getKeyEventSource() { + return keyEventSource; + } } diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerChannel1003Router.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerChannel1003Router.java deleted file mode 100644 index 1526edf3a6b..00000000000 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerChannel1003Router.java +++ /dev/null @@ -1,533 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package rdpclient; - -import streamer.BaseElement; -import streamer.ByteBuffer; -import streamer.Element; -import streamer.Link; -import streamer.MockSink; -import streamer.MockSource; -import streamer.Pipeline; -import streamer.PipelineImpl; - -public class ServerChannel1003Router extends BaseElement { - - /** - * Demand Active PDU. - */ - public static final int PDUTYPE_DEMANDACTIVEPDU = 0x1; - - /** - * Confirm Active PDU. - */ - public static final int PDUTYPE_CONFIRMACTIVEPDU = 0x3; - - /** - * Deactivate All PDU. - */ - public static final int PDUTYPE_DEACTIVATEALLPDU = 0x6; - - /** - * Data PDU (actual type is revealed by the pduType2 field in the Share Data - * Header). - */ - public static final int PDUTYPE_DATAPDU = 0x7; - - /** - * Enhanced Security Server Redirection PDU. - */ - public static final int PDUTYPE_SERVER_REDIR_PKT = 0xA; - - protected RdpState state; - - public ServerChannel1003Router(String id, RdpState state) { - super(id); - this.state = state; - } - - /** - * @see http://msdn.microsoft.com/en-us/library/cc240576.aspx - */ - @Override - public void handleData(ByteBuffer buf, Link link) { - if (verbose) - System.out.println("[" + this + "] INFO: Data received: " + buf + "."); - - int length = buf.readUnsignedShortLE(); - if (buf.length != length) { - // It is ServerErrorAlert-ValidClient - // Ignore it - //throw new RuntimeException("[" + this + "] ERROR: Incorrect PDU length: " + length + ", data: " + buf + "."); - } - - int type = buf.readUnsignedShortLE() & 0xf; - - // int sourceId = buf.readUnsignedShortLE(); - buf.skipBytes(2); - - switch (type) { - case PDUTYPE_DEMANDACTIVEPDU: - pushDataToPad("demand_active", buf); - break; - case PDUTYPE_CONFIRMACTIVEPDU: - throw new RuntimeException("Unexpected client CONFIRM ACTIVE PDU. Data: " + buf + "."); - case PDUTYPE_DEACTIVATEALLPDU: - // pushDataToPad("deactivate_all", buf); - /* ignore */buf.unref(); - break; - case PDUTYPE_DATAPDU: - handleDataPdu(buf); - break; - case PDUTYPE_SERVER_REDIR_PKT: - // pushDataToPad("server_redir", buf); - /* ignore */buf.unref(); - break; - default: - throw new RuntimeException("[" + this + "] ERROR: Unknown PDU type: " + type + ", data: " + buf + "."); - } - - } - - /** - * Graphics Update PDU. - */ - public static final int PDUTYPE2_UPDATE = 0x02; - - /** - * Control PDU. - */ - public static final int PDUTYPE2_CONTROL = 0x14; - - /** - * Pointer Update PDU. - */ - public static final int PDUTYPE2_POINTER = 0x1B; - - /** - * Input Event PDU. - */ - public static final int PDUTYPE2_INPUT = 0x1C; - - /** - * Synchronize PDU. - */ - public static final int PDUTYPE2_SYNCHRONIZE = 0x1F; - - /** - * Refresh Rect PDU. - */ - public static final int PDUTYPE2_REFRESH_RECT = 0x21; - - /** - * Play Sound PDU. - */ - public static final int PDUTYPE2_PLAY_SOUND = 0x22; - - /** - * Suppress Output PDU. - */ - public static final int PDUTYPE2_SUPPRESS_OUTPUT = 0x23; - - /** - * Shutdown Request PDU. - */ - public static final int PDUTYPE2_SHUTDOWN_REQUEST = 0x24; - - /** - * Shutdown Request Denied PDU. - */ - public static final int PDUTYPE2_SHUTDOWN_DENIED = 0x25; - - /** - * Save Session Info PDU. - */ - public static final int PDUTYPE2_SAVE_SESSION_INFO = 0x26; - - /** - * Font List PDU. - */ - public static final int PDUTYPE2_FONTLIST = 0x27; - - /** - * Font Map PDU. - */ - public static final int PDUTYPE2_FONTMAP = 0x28; - - /** - * Set Keyboard Indicators PDU. - */ - public static final int PDUTYPE2_SET_KEYBOARD_INDICATORS = 0x29; - - /** - * Persistent Key List PDU. - */ - public static final int PDUTYPE2_BITMAPCACHE_PERSISTENT_LIST = 0x2B; - - /** - * Bitmap Cache Error PDU. - */ - public static final int PDUTYPE2_BITMAPCACHE_ERROR_PDU = 0x2C; - - /** - * Set Keyboard IME Status PDU. - */ - public static final int PDUTYPE2_SET_KEYBOARD_IME_STATUS = 0x2D; - - /** - * Offscreen Bitmap Cache Error PDU. - */ - public static final int PDUTYPE2_OFFSCRCACHE_ERROR_PDU = 0x2E; - - /** - * Set Error Info PDU. - */ - public static final int PDUTYPE2_SET_ERROR_INFO_PDU = 0x2F; - - /** - * DrawNineGrid Cache Error PDU. - */ - public static final int PDUTYPE2_DRAWNINEGRID_ERROR_PDU = 0x30; - - /** - * GDI+ Error PDU. - */ - public static final int PDUTYPE2_DRAWGDIPLUS_ERROR_PDU = 0x31; - - /** - * Auto-Reconnect Status PDU. - */ - public static final int PDUTYPE2_ARC_STATUS_PDU = 0x32; - - /** - * Status Info PDU. - */ - public static final int PDUTYPE2_STATUS_INFO_PDU = 0x36; - - /** - * Monitor Layout PDU. - */ - public static final int PDUTYPE2_MONITOR_LAYOUT_PDU = 0x37; - - /** - * Indicates an Orders Update. - */ - public static final int UPDATETYPE_ORDERS = 0x0000; - - /** - * Indicates a Bitmap Graphics Update. - */ - public static final int UPDATETYPE_BITMAP = 0x0001; - - /** - * Indicates a Palette Update. - */ - public static final int UPDATETYPE_PALETTE = 0x0002; - - /** - * Indicates a Synchronize Update. - */ - public static final int UPDATETYPE_SYNCHRONIZE = 0x0003; - - /** - * @see http://msdn.microsoft.com/en-us/library/cc240577.aspx - */ - protected void handleDataPdu(ByteBuffer buf) { - - // (4 bytes): A 32-bit, unsigned integer. Share identifier for the packet. - long shareId = buf.readUnsignedIntLE(); - if (shareId != state.serverShareId) - throw new RuntimeException("Unexpected share ID: " + shareId + "."); -// buf.skipBytes(4); - - // Padding. - buf.skipBytes(1); - - // (1 byte): An 8-bit, unsigned integer. The stream identifier for the - // packet. - // int streamId = buf.readUnsignedByte(); - buf.skipBytes(1); - - // (2 bytes): A 16-bit, unsigned integer. The uncompressed length of the - // packet in bytes. - int uncompressedLength = buf.readUnsignedShortLE(); - - // (1 byte): An 8-bit, unsigned integer. The type of Data PDU. - int type2 = buf.readUnsignedByte(); - - // (1 byte): An 8-bit, unsigned integer. The compression type and flags - // specifying the data following the Share Data Header - int compressedType = buf.readUnsignedByte(); - if (compressedType != 0) - throw new RuntimeException("Compression of protocol packets is not supported. Data: " + buf + "."); - - // (2 bytes): A 16-bit, unsigned integer. The compressed length of the - // packet in bytes. - int compressedLength = buf.readUnsignedShortLE(); - if (compressedLength != 0) - throw new RuntimeException("Compression of protocol packets is not supported. Data: " + buf + "."); - - ByteBuffer data = buf.readBytes(uncompressedLength - 18); - buf.unref(); - - switch (type2) { - - case PDUTYPE2_UPDATE: { - - // (2 bytes): A 16-bit, unsigned integer. Type of the graphics update. - int updateType = data.readUnsignedShortLE(); - ByteBuffer data2 = data.readBytes(data.length - data.cursor); - data.unref(); - - switch (updateType) { - case UPDATETYPE_ORDERS: - pushDataToPad("orders", data2); - break; - case UPDATETYPE_BITMAP: - pushDataToPad("bitmap", data2); - break; - case UPDATETYPE_PALETTE: - pushDataToPad("palette", data2); - break; - case UPDATETYPE_SYNCHRONIZE: - // Ignore - data2.unref(); - break; - } - - break; - } - case PDUTYPE2_CONTROL: - if (verbose) - System.out.println("[" + this + "] INFO: Packet PDUTYPE2_CONTROL ignored."); - // Ignore - data.unref(); - break; - case PDUTYPE2_POINTER: - if (verbose) - System.out.println("[" + this + "] INFO: Packet PDUTYPE2_POINTER ignored."); - // Ignore - data.unref(); - break; - case PDUTYPE2_INPUT: - if (verbose) - System.out.println("[" + this + "] INFO: Packet PDUTYPE2_INPUT ignored."); - // Ignore - data.unref(); - break; - case PDUTYPE2_SYNCHRONIZE: - if (verbose) - System.out.println("[" + this + "] INFO: Packet PDUTYPE2_SYNCHRONIZE ignored."); - // Ignore - data.unref(); - break; - case PDUTYPE2_REFRESH_RECT: - if (verbose) - System.out.println("[" + this + "] INFO: Packet PDUTYPE2_REFRESH_RECT ignored."); - // Ignore - data.unref(); - break; - case PDUTYPE2_PLAY_SOUND: - if (verbose) - System.out.println("[" + this + "] INFO: Packet PDUTYPE2_PLAY_SOUND ignored."); - // Ignore - data.unref(); - break; - case PDUTYPE2_SUPPRESS_OUTPUT: - if (verbose) - System.out.println("[" + this + "] INFO: Packet PDUTYPE2_SUPPRESS_OUTPUT ignored."); - // Ignore - data.unref(); - break; - case PDUTYPE2_SHUTDOWN_REQUEST: - if (verbose) - System.out.println("[" + this + "] INFO: Packet PDUTYPE2_SHUTDOWN_REQUEST ignored."); - // Ignore - data.unref(); - break; - case PDUTYPE2_SHUTDOWN_DENIED: - if (verbose) - System.out.println("[" + this + "] INFO: Packet PDUTYPE2_SHUTDOWN_DENIED ignored."); - // Ignore - data.unref(); - break; - case PDUTYPE2_SAVE_SESSION_INFO: - if (verbose) - System.out.println("[" + this + "] INFO: Packet PDUTYPE2_SAVE_SESSION_INFO ignored."); - // Ignore - data.unref(); - break; - case PDUTYPE2_FONTLIST: - if (verbose) - System.out.println("[" + this + "] INFO: Packet PDUTYPE2_FONTLIST ignored."); - // Ignore - data.unref(); - break; - case PDUTYPE2_FONTMAP: - if (verbose) - System.out.println("[" + this + "] INFO: Packet PDUTYPE2_FONTMAP ignored."); - // Ignore - data.unref(); - break; - case PDUTYPE2_SET_KEYBOARD_INDICATORS: - if (verbose) - System.out.println("[" + this + "] INFO: Packet PDUTYPE2_SET_KEYBOARD_INDICATORS ignored."); - // Ignore - data.unref(); - break; - case PDUTYPE2_BITMAPCACHE_PERSISTENT_LIST: - if (verbose) - System.out.println("[" + this + "] INFO: Packet PDUTYPE2_BITMAPCACHE_PERSISTENT_LIST ignored."); - // Ignore - data.unref(); - break; - case PDUTYPE2_BITMAPCACHE_ERROR_PDU: - if (verbose) - System.out.println("[" + this + "] INFO: Packet PDUTYPE2_BITMAPCACHE_ERROR_PDU ignored."); - // Ignore - data.unref(); - break; - case PDUTYPE2_SET_KEYBOARD_IME_STATUS: - if (verbose) - System.out.println("[" + this + "] INFO: Packet PDUTYPE2_SET_KEYBOARD_IME_STATUS ignored."); - // Ignore - data.unref(); - break; - case PDUTYPE2_OFFSCRCACHE_ERROR_PDU: - if (verbose) - System.out.println("[" + this + "] INFO: Packet PDUTYPE2_OFFSCRCACHE_ERROR_PDU ignored."); - // Ignore - data.unref(); - break; - case PDUTYPE2_SET_ERROR_INFO_PDU: - if (verbose) - System.out.println("[" + this + "] INFO: Packet PDUTYPE2_SET_ERROR_INFO_PDU ignored."); - // Ignore - data.unref(); - break; - case PDUTYPE2_DRAWNINEGRID_ERROR_PDU: - if (verbose) - System.out.println("[" + this + "] INFO: Packet PDUTYPE2_DRAWNINEGRID_ERROR_PDU ignored."); - // Ignore - data.unref(); - break; - case PDUTYPE2_DRAWGDIPLUS_ERROR_PDU: - if (verbose) - System.out.println("[" + this + "] INFO: Packet PDUTYPE2_DRAWGDIPLUS_ERROR_PDU ignored."); - // Ignore - data.unref(); - break; - case PDUTYPE2_ARC_STATUS_PDU: - if (verbose) - System.out.println("[" + this + "] INFO: Packet PDUTYPE2_ARC_STATUS_PDU ignored."); - // Ignore - data.unref(); - break; - case PDUTYPE2_STATUS_INFO_PDU: - if (verbose) - System.out.println("[" + this + "] INFO: Packet PDUTYPE2_STATUS_INFO_PDU ignored."); - // Ignore - data.unref(); - break; - case PDUTYPE2_MONITOR_LAYOUT_PDU: - if (verbose) - System.out.println("[" + this + "] INFO: Packet PDUTYPE2_MONITOR_LAYOUT_PDU ignored."); - // Ignore - data.unref(); - break; - - default: - throw new RuntimeException("Unknow data PDU type: " + type2 + ", data: " + buf + "."); - } - } - - /** - * Example. - * - */ - public static void main(String args[]) { - // System.setProperty("streamer.Link.debug", "true"); - System.setProperty("streamer.Element.debug", "true"); - // System.setProperty("streamer.Pipeline.debug", "true"); - - byte[] packet = new byte[] { - // TPKT - (byte)0x03, (byte)0x00, // TPKT Header: TPKT version = 3 - (byte)0x00, (byte)0x1B, // TPKT length: 27 bytes - - // X224 - (byte)0x02, // X224 Length: 2 bytes - (byte)0xF0, // X224 Type: Data - (byte)0x80, // X224 EOT - - // MCS - // Type: send data indication: 26 (0x1a, top 6 bits) - (byte)0x68, // ?? - - (byte)0x00, (byte)0x01, // User ID: 1002 (1001+1) - (byte)0x03, (byte)0xEB, // Channel ID: 1003 - (byte)0x70, // Data priority: high, segmentation: begin|end - (byte)0x0D, // Payload length: 13 bytes - - // Deactivate all PDU - (byte)0x0D, (byte)0x00, // Length: 13 bytes (LE) - - // - PDUType: (0x16, LE) - // Type: (............0110) TS_PDUTYPE_DEACTIVATEALLPDU - // ProtocolVersion: (000000000001....) 1 - (byte)0x16, (byte)0x00, - - (byte)0xEA, (byte)0x03, // PDU source: 1002 (LE) - (byte)0xEA, (byte)0x03, (byte)0x01, (byte)0x00, // ShareID = 66538 - - (byte)0x01, (byte)0x00, // Length if source descriptor: 1 (LE) - (byte)0x00, // Source descriptor (should be set to 0): 0 - }; - - MockSource source = new MockSource("source", ByteBuffer.convertByteArraysToByteBuffers(packet)); - RdpState rdpState = new RdpState() { - { - serverShareId = 66538; - } - }; - Element channel1003 = new ServerChannel1003Router("channel_1003", rdpState); - Element mcs = new ServerMCSPDU("mcs"); - Element tpkt = new ServerTpkt("tpkt"); - Element x224 = new ServerX224DataPdu("x224"); - Element sink = new MockSink("sink", ByteBuffer.convertByteArraysToByteBuffers(new byte[] { - // Deactivate all PDU - (byte)0x0D, (byte)0x00, // Length: 13 bytes (LE) - - // - PDUType: 22 (0x16, LE) - // Type: (............0110) TS_PDUTYPE_DEACTIVATEALLPDU - // ProtocolVersion: (000000000001....) 1 - (byte)0x16, (byte)0x00, - - (byte)0xEA, (byte)0x03, // PDU source: 1002 (LE) - (byte)0xEA, (byte)0x03, (byte)0x01, (byte)0x00, // ShareID = 66538 - - (byte)0x01, (byte)0x00, // Length if source descriptor: 1 (LE) - (byte)0x00, // Source descriptor (should be set to 0): 0 - })); - - Pipeline pipeline = new PipelineImpl("test"); - pipeline.add(source, tpkt, x224, mcs, channel1003, sink); - pipeline.link("source", "tpkt", "x224", "mcs >channel_1003", "channel_1003 >deactivate_all", "sink"); - pipeline.runMainLoop("source", STDOUT, false, false); - } - -} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerDemandActivePDU.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerDemandActivePDU.java deleted file mode 100644 index 9605b85311d..00000000000 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerDemandActivePDU.java +++ /dev/null @@ -1,660 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package rdpclient; - -import streamer.BaseElement; -import streamer.ByteBuffer; -import streamer.Element; -import streamer.FakeSink; -import streamer.Link; -import streamer.MockSource; -import streamer.Order; -import streamer.Pipeline; -import streamer.PipelineImpl; -import common.ScreenDescription; - -/** - * @see http://msdn.microsoft.com/en-us/library/cc240669.aspx - * @see http://msdn.microsoft.com/en-us/library/cc240484.aspx - */ -public class ServerDemandActivePDU extends BaseElement { - - /** - * Demand Active PDU. - */ - public static final int PDUTYPE_DEMANDACTIVEPDU = 0x1; - - protected RdpState state; - protected ScreenDescription screen; - - public ServerDemandActivePDU(String id, ScreenDescription screen, RdpState state) { - super(id); - this.state = state; - this.screen = screen; - } - - @Override - public void handleData(ByteBuffer buf, Link link) { - if (verbose) - System.out.println("[" + this + "] INFO: Data received: " + buf + "."); - - // Total length of packet - int length = buf.readSignedShortLE(); // Ignore - if (buf.length != length) - throw new RuntimeException("Incorrect length of packet. Length: " + length + ", data: " + buf + "."); - - int type = buf.readSignedShortLE() & 0xf; - if (type != PDUTYPE_DEMANDACTIVEPDU) - throw new RuntimeException("Unknown PDU type. Expected type: Demand Active PDU (0x1), actual tyoe: " + type + ", data: " + buf + "."); - - // TS_SHARECONTROLHEADER::pduSource = 0x03ea (1002) - int pduSource = buf.readSignedShortLE(); - if (pduSource != 1002) - throw new RuntimeException("Unexepcted source of demand active PDU. Expected source: 1002, actual source: " + pduSource + "."); - - // (4 bytes): A 32-bit, unsigned integer. The share identifier for the - // packet (see [T128] section 8.4.2 for more information regarding share - // IDs). - long shareId = buf.readUnsignedIntLE(); - state.serverShareId = shareId; - - // Ignore rest of server data because it is not used by this client. - // (2 bytes): A 16-bit, unsigned integer. The size in bytes of the - // sourceDescriptor field. - int lengthSourceDescriptor = buf.readUnsignedShortLE(); - - // (2 bytes): A 16-bit, unsigned integer. The combined size in bytes of the - // numberCapabilities, pad2Octets, and capabilitySets fields. - int lengthCombinedCapabilities = buf.readUnsignedShortLE(); - - // (variable): A variable-length array of bytes containing a source - // descriptor, - // ByteBuffer sourceDescriptor = buf.readBytes(lengthSourceDescriptor); - buf.skipBytes(lengthSourceDescriptor); - - // (variable): An array of Capability Set (section 2.2.1.13.1.1.1) - // structures. The number of capability sets is specified by the - // numberCapabilities field. - handleCapabiltySets(buf.readBytes(lengthCombinedCapabilities)); - - // (4 bytes): A 32-bit, unsigned integer. The session identifier. This field - // is ignored by the client. - buf.skipBytes(4); - - /* DEBUG */buf.assertThatBufferIsFullyRead(); - - buf.unref(); - - sendHandshakePackets(); - } - - /** - * General Capability Set - */ - public static final int CAPSTYPE_GENERAL = 0x0001; - /** - * Bitmap Capability Set - */ - public static final int CAPSTYPE_BITMAP = 0x0002; - /** - * Order Capability Set - */ - public static final int CAPSTYPE_ORDER = 0x0003; - /** - * Revision 1 Bitmap Cache Capability Set - */ - public static final int CAPSTYPE_BITMAPCACHE = 0x0004; - /** - * Control Capability Set - */ - public static final int CAPSTYPE_CONTROL = 0x0005; - /** - * Window Activation Capability Set - */ - public static final int CAPSTYPE_ACTIVATION = 0x0007; - /** - * Pointer Capability Set - */ - public static final int CAPSTYPE_POINTER = 0x0008; - /** - * Share Capability Set - */ - public static final int CAPSTYPE_SHARE = 0x0009; - /** - * Color Table Cache Capability Set - */ - public static final int CAPSTYPE_COLORCACHE = 0x000A; - /** - * Sound Capability Set - */ - public static final int CAPSTYPE_SOUND = 0x000C; - /** - * Input Capability Set - */ - public static final int CAPSTYPE_INPUT = 0x000D; - /** - * Font Capability Set - */ - public static final int CAPSTYPE_FONT = 0x000E; - /** - * Brush Capability Set - */ - public static final int CAPSTYPE_BRUSH = 0x000F; - /** - * Glyph Cache Capability Set - */ - public static final int CAPSTYPE_GLYPHCACHE = 0x0010; - /** - * Offscreen Bitmap Cache Capability Set - */ - public static final int CAPSTYPE_OFFSCREENCACHE = 0x0011; - /** - * Bitmap Cache Host Support Capability Set - */ - public static final int CAPSTYPE_BITMAPCACHE_HOSTSUPPORT = 0x0012; - /** - * Revision 2 Bitmap Cache Capability Set - */ - public static final int CAPSTYPE_BITMAPCACHE_REV2 = 0x0013; - /** - * Virtual Channel Capability Set - */ - public static final int CAPSTYPE_VIRTUALCHANNEL = 0x0014; - /** - * DrawNineGrid Cache Capability Set - */ - public static final int CAPSTYPE_DRAWNINEGRIDCACHE = 0x0015; - /** - * Draw GDI+ Cache Capability Set - */ - public static final int CAPSTYPE_DRAWGDIPLUS = 0x0016; - /** - * Remote Programs Capability Set - */ - public static final int CAPSTYPE_RAIL = 0x0017; - /** - * Window List Capability Set - */ - public static final int CAPSTYPE_WINDOW = 0x0018; - /** - * Desktop Composition Extension Capability Set - */ - public static final int CAPSETTYPE_COMPDESK = 0x0019; - /** - * Multifragment Update Capability Set - */ - public static final int CAPSETTYPE_MULTIFRAGMENTUPDATE = 0x001A; - /** - * Large Pointer Capability Set - */ - public static final int CAPSETTYPE_LARGE_POINTER = 0x001B; - /** - * Surface Commands Capability Set - */ - public static final int CAPSETTYPE_SURFACE_COMMANDS = 0x001C; - /** - * Bitmap Codecs Capability Set - */ - public static final int CAPSETTYPE_BITMAP_CODECS = 0x001D; - /** - * Frame Acknowledge Capability Set - */ - public static final int CAPSSETTYPE_FRAME_ACKNOWLEDGE = 0x001E; - - /** - * @see http://msdn.microsoft.com/en-us/library/cc240486.aspx - */ - protected void handleCapabiltySets(ByteBuffer buf) { - // (2 bytes): A 16-bit, unsigned integer. The number of capability sets - // included in the Demand Active PDU. - int numberCapabilities = buf.readSignedShortLE(); - - // (2 bytes): Padding. - buf.skipBytes(2); - - for (int i = 0; i < numberCapabilities; i++) { - // (2 bytes): A 16-bit, unsigned integer. The type identifier of the - // capability set. - int capabilitySetType = buf.readUnsignedShortLE(); - - // (2 bytes): A 16-bit, unsigned integer. The length in bytes of the - // capability data, including the size of the capabilitySetType and - // lengthCapability fields. - int lengthCapability = buf.readUnsignedShortLE(); - - // (variable): Capability set data which conforms to the structure of the - // type given by the capabilitySetType field. - ByteBuffer capabilityData = buf.readBytes(lengthCapability - 4); - - switch (capabilitySetType) { - case CAPSTYPE_GENERAL: - break; - case CAPSTYPE_BITMAP: - handleBitmapCapabilities(capabilityData); - break; - case CAPSTYPE_ORDER: - break; - case CAPSTYPE_BITMAPCACHE: - break; - case CAPSTYPE_CONTROL: - break; - case CAPSTYPE_ACTIVATION: - break; - case CAPSTYPE_POINTER: - break; - case CAPSTYPE_SHARE: - break; - case CAPSTYPE_COLORCACHE: - break; - case CAPSTYPE_SOUND: - break; - case CAPSTYPE_INPUT: - break; - case CAPSTYPE_FONT: - break; - case CAPSTYPE_BRUSH: - break; - case CAPSTYPE_GLYPHCACHE: - break; - case CAPSTYPE_OFFSCREENCACHE: - break; - case CAPSTYPE_BITMAPCACHE_HOSTSUPPORT: - break; - case CAPSTYPE_BITMAPCACHE_REV2: - break; - case CAPSTYPE_VIRTUALCHANNEL: - break; - case CAPSTYPE_DRAWNINEGRIDCACHE: - break; - case CAPSTYPE_DRAWGDIPLUS: - break; - case CAPSTYPE_RAIL: - break; - case CAPSTYPE_WINDOW: - break; - case CAPSETTYPE_COMPDESK: - break; - case CAPSETTYPE_MULTIFRAGMENTUPDATE: - break; - case CAPSETTYPE_LARGE_POINTER: - break; - case CAPSETTYPE_SURFACE_COMMANDS: - break; - case CAPSETTYPE_BITMAP_CODECS: - break; - case CAPSSETTYPE_FRAME_ACKNOWLEDGE: - break; - default: - // Ignore - break; - } - - capabilityData.unref(); - } - - // TODO - - buf.unref(); - } - - /** - * @see http://msdn.microsoft.com/en-us/library/cc240554.aspx - */ - protected void handleBitmapCapabilities(ByteBuffer buf) { - - // (2 bytes): A 16-bit, unsigned integer. The server MUST set this field to - // the color depth of the session, while the client SHOULD set this field to - // the color depth requested in the Client Core Data (section 2.2.1.3.2). - int preferredBitsPerPixel = buf.readUnsignedShortLE(); - screen.setPixelFormatRGBTrueColor(preferredBitsPerPixel); - - // receive1BitPerPixel (2 bytes): A 16-bit, unsigned integer. Indicates - // whether the client can receive 1 bpp. This field is ignored and SHOULD be - // set to TRUE (0x0001). - buf.skipBytes(2); - - // receive4BitsPerPixel(2 bytes): A 16-bit, unsigned integer. Indicates - // whether the client can receive 4 bpp. This field is ignored and SHOULD be - // set to TRUE (0x0001). - buf.skipBytes(2); - - // receive8BitsPerPixel (2 bytes): A 16-bit, unsigned integer. Indicates - // whether the client can receive 8 bpp. This field is ignored and SHOULD be - // set to TRUE (0x0001). - buf.skipBytes(2); - - // (2 bytes): A 16-bit, unsigned integer. The width of the desktop in the - // session. - int desktopWidth = buf.readUnsignedShortLE(); - - // (2 bytes): A 16-bit, unsigned integer. The height of the desktop in the - // session. - int desktopHeight = buf.readUnsignedShortLE(); - - screen.setFramebufferSize(desktopWidth, desktopHeight); - - // pad2octets (2 bytes): A 16-bit, unsigned integer. Padding. Values in this - // field MUST be ignored. - - // desktopResizeFlag (2 bytes): A 16-bit, unsigned integer. Indicates - // whether resizing the desktop by using a Deactivation-Reactivation - // Sequence is supported. - - // bitmapCompressionFlag (2 bytes): A 16-bit, unsigned integer. Indicates - // whether bitmap compression is supported. This field MUST be set to TRUE - // (0x0001) because support for compressed bitmaps is required for a - // connection to proceed. - - // highColorFlags (1 byte): An 8-bit, unsigned integer. Client support for - // 16 bpp color modes. This field is ignored and SHOULD be set to zero. - - // drawingFlags (1 byte): An 8-bit, unsigned integer. Flags describing - // support for 32 bpp bitmaps. - - // multipleRectangleSupport (2 bytes): A 16-bit, unsigned integer. Indicates - // whether the use of multiple bitmap rectangles is supported in the Bitmap - // Update (section 2.2.9.1.1.3.1.2). This field MUST be set to TRUE (0x0001) - // because multiple rectangle support is required for a connection to - // proceed. - - // pad2octetsB (2 bytes): A 16-bit, unsigned integer. Padding. Values in - // this field MUST be ignored. - } - - /** - * Send all client requests in one hop, to simplify logic. - */ - protected void sendHandshakePackets() { - // Send reactivation sequence in bulk - pushDataToPad("confirm_active", new ByteBuffer((Order)null)); - } - - /** - * Example. - * - */ - public static void main(String args[]) { - // System.setProperty("streamer.Link.debug", "true"); - System.setProperty("streamer.Element.debug", "true"); - // System.setProperty("streamer.Pipeline.debug", "true"); - - /* @formatter:off */ - byte[] packet = new byte[] { - 0x67, 0x01, // TS_SHARECONTROLHEADER::totalLength = 0x0167 = 359 bytes - 0x11, 0x00, // TS_SHARECONTROLHEADER::pduType = 0x0011 0x0011 = 0x0010 | 0x0001 = TS_PROTOCOL_VERSION | PDUTYPE_DEMANDACTIVEPDU - - (byte) 0xea, 0x03, // TS_SHARECONTROLHEADER::pduSource = 0x03ea (1002) - - (byte) 0xea, 0x03, 0x01, 0x00, // TS_DEMAND_ACTIVE_PDU::shareId - 0x04, 0x00, // TS_DEMAND_ACTIVE_PDU::lengthSourceDescriptor = 4 bytes - 0x51, 0x01, // TS_DEMAND_ACTIVE_PDU::lengthCombinedCapabilities = 0x151 = 337 bytes - - 0x52, 0x44, 0x50, 0x00, // TS_DEMAND_ACTIVE_PDU::sourceDescriptor = "RDP" - - 0x0d, 0x00, // TS_DEMAND_ACTIVE_PDU::numberCapabilities = 13 - 0x00, 0x00, // TS_DEMAND_ACTIVE_PDU::pad2octets - - // Share Capability Set (8 bytes) - // 0x09, 0x00, 0x08, 0x00, (byte) 0xea, 0x03, (byte) 0xdc, (byte) 0xe2, - // - 0x09, 0x00, // TS_SHARE_CAPABILITYSET::capabilitySetType = CAPSTYPE_SHARE (9) - 0x08, 0x00, // TS_SHARE_CAPABILITYSET::lengthCapability = 8 bytes - (byte) 0xea, 0x03, // TS_SHARE_CAPABILITYSET::nodeID = 0x03ea (1002) - (byte) 0xdc, (byte) 0xe2, // TS_SHARE_CAPABILITYSET::pad2octets - - // General Capability Set (24 bytes) - // 0x01, 0x00, 0x18, 0x00, 0x01, 0x00, 0x03, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x1d, 0x04, - // 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, - // - 0x01, 0x00, // TS_GENERAL_CAPABILITYSET::capabilitySetType = CAPSTYPE_GENERAL (1) - 0x18, 0x00, // TS_GENERAL_CAPABILITYSET::lengthCapability = 24 bytes - - 0x01, 0x00, // TS_GENERAL_CAPABILITYSET::osMajorType = TS_OSMAJORTYPE_WINDOWS (1) - 0x03, 0x00, // TS_GENERAL_CAPABILITYSET::osMinorType = TS_OSMINORTYPE_WINDOWS_NT (3) - 0x00, 0x02, // TS_GENERAL_CAPABILITYSET::protocolVersion = TS_CAPS_PROTOCOLVERSION (0x0200) - 0x00, 0x00, // TS_GENERAL_CAPABILITYSET::pad2octetsA - 0x00, 0x00, // TS_GENERAL_CAPABILITYSET::generalCompressionTypes = 0 - 0x1d, 0x04, // TS_GENERAL_CAPABILITYSET::extraFlags = 0x041d = 0x0400 | 0x0010 | 0x0008 | 0x0004 | 0x0001 = NO_BITMAP_COMPRESSION_HDR | ENC_SALTED_CHECKSUM | AUTORECONNECT_SUPPORTED | LONG_CREDENTIALS_SUPPORTED | FASTPATH_OUTPUT_SUPPORTED - - 0x00, 0x00, // TS_GENERAL_CAPABILITYSET::updateCapabilityFlag = 0 - 0x00, 0x00, // TS_GENERAL_CAPABILITYSET::remoteUnshareFlag = 0 - 0x00, 0x00, // TS_GENERAL_CAPABILITYSET::generalCompressionLevel = 0 - 0x01, // TS_GENERAL_CAPABILITYSET::refreshRectSupport = TRUE - 0x01, // TS_GENERAL_CAPABILITYSET::suppressOutputSupport = TRUE - - // Virtual Channel Capability Set (8 bytes) - // 0x14, 0x00, 0x08, 0x00, 0x02, 0x00, 0x00, 0x00, - // - 0x14, 0x00, // TS_VIRTUALCHANNEL_CAPABILITYSET::capabilitySetType = CAPSTYPE_VIRTUALCHANNEL (20) - 0x08, 0x00, // TS_VIRTUALCHANNEL_CAPABILITYSET::lengthCapability = 8 bytes - - 0x02, 0x00, 0x00, 0x00, // TS_VIRTUALCHANNEL_CAPABILITYSET::vccaps1 = 0x00000002 = VCCAPS_COMPR_CS_8K - - // DrawGdiPlus Capability Set (40 bytes) - // 0x16, 0x00, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, (byte) 0xf6, 0x13, (byte) 0xf3, 0x01, 0x00, 0x00, 0x00, - // 0x01, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, (byte) 0x9c, (byte) 0xf6, 0x13, (byte) 0xf3, 0x61, (byte) 0xa6, (byte) 0x82, (byte) 0x80, - // 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, (byte) 0x91, (byte) 0xbf, - // - 0x16, 0x00, // TS_DRAW_GDIPLUS_CAPABILITYSET::capabilitySetType = CAPSTYPE_DRAWGDIPLUS (22) - 0x28, 0x00, // TS_DRAW_GDIPLUS_CAPABILITYSET::lengthCapability = 40 bytes - - 0x00, 0x00, 0x00, 0x00, // TS_DRAW_GDIPLUS_CAPABILITYSET::drawGdiplusSupportLevel = TS_DRAW_GDIPLUS_DEFAULT (0) - 0x70, (byte) 0xf6, 0x13, (byte) 0xf3, // TS_DRAW_GDIPLUS_CAPABILITYSET::GdipVersion (not initialized by server) - 0x01, 0x00, 0x00, 0x00, // TS_DRAW_GDIPLUS_CAPABILITYSET::drawGdiplusCacheLevel = TS_DRAW_GDIPLUS_CACHE_LEVEL_ONE (1) - - 0x01, 0x00, // TS_GDIPLUS_CACHE_ENTRIES::GdipGraphicsCacheEntries (not initialized by server) - 0x00, 0x00, // TS_GDIPLUS_CACHE_ENTRIES::GdipObjectBrushCacheEntries (not initialized by server) - 0x18, 0x00, // TS_GDIPLUS_CACHE_ENTRIES::GdipObjectPenCacheEntries (not initialized by server) - 0x00, 0x00, // TS_GDIPLUS_CACHE_ENTRIES::GdipObjectImageCacheEntries (not initialized by server) - (byte) 0x9c, (byte) 0xf6, // TS_GDIPLUS_CACHE_ENTRIES::GdipObjectImageAttributesCacheEntries (not initialized by server) - - 0x13, (byte) 0xf3, // TS_GDIPLUS_CACHE_CHUNK_SIZE::GdipGraphicsCacheChunkSize (not initialized by server) - 0x61, (byte) 0xa6, // TS_GDIPLUS_CACHE_CHUNK_SIZE::GdipObjectBrushCacheChunkSize (not initialized by server) - (byte) 0x82, (byte) 0x80, // TS_GDIPLUS_CACHE_CHUNK_SIZE::GdipObjectPenCacheChunkSize (not initialized by server) - 0x00, 0x00, // TS_GDIPLUS_CACHE_CHUNK_SIZE::GdipObjectImageAttributesCacheChunkSize (not initialized by server) - - 0x00, 0x00, // TS_GDIPLUS_IMAGE_CACHE_PROPERTIES::GdipObjectImageCacheChunkSize (not initialized by server) - 0x00, 0x50, // TS_GDIPLUS_IMAGE_CACHE_PROPERTIES::GdipObjectImageCacheTotalSize (not initialized by server) - (byte) 0x91, (byte) 0xbf, // TS_GDIPLUS_IMAGE_CACHE_PROPERTIES::GdipObjectImageCacheMaxSize (not initialized by server) - - // Font Capability Set (4 bytes) - // 0x0e, 0x00, 0x04, 0x00, - // - // Due to a bug, the TS_FONT_CAPABILITYSET capability set size is incorrectly set to 4 bytes (it must be 8 bytes). As a result of this bug, the fontSupportFlags and pad2octets fields are missing. - 0x0e, 0x00, // TS_FONT_CAPABILITYSET::capabilitySetType = CAPSTYPE_FONT (14) - 0x04, 0x00, // TS_FONT_CAPABILITYSET::lengthCapability = 4 bytes - - - // Bitmap Capability Set (28 bytes) - // 0x02, 0x00, 0x1c, 0x00, 0x18, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x04, - // 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, - // - 0x02, 0x00, // TS_BITMAP_CAPABILITYSET::capabilitySetType = CAPSTYPE_BITMAP (2) - 0x1c, 0x00, // TS_BITMAP_CAPABILITYSET::lengthCapability = 28 bytes - - 0x18, 0x00, // TS_BITMAP_CAPABILITYSET::preferredBitsPerPixel = 24 bpp - 0x01, 0x00, // TS_BITMAP_CAPABILITYSET::receive1BitPerPixel = TRUE - 0x01, 0x00, // TS_BITMAP_CAPABILITYSET::receive4BitsPerPixel = TRUE - 0x01, 0x00, // TS_BITMAP_CAPABILITYSET::receive8BitsPerPixel = TRUE - 0x00, 0x05, // TS_BITMAP_CAPABILITYSET::desktopWidth = 1280 pixels - 0x00, 0x04, // TS_BITMAP_CAPABILITYSET::desktopHeight = 1024 pixels - 0x00, 0x00, // TS_BITMAP_CAPABILITYSET::pad2octets - 0x01, 0x00, // TS_BITMAP_CAPABILITYSET::desktopResizeFlag = TRUE - 0x01, 0x00, // TS_BITMAP_CAPABILITYSET::bitmapCompressionFlag = TRUE - 0x00, // TS_BITMAP_CAPABILITYSET::highColorFlags = 0 - 0x00, // TS_BITMAP_CAPABILITYSET::pad1octet - 0x01, 0x00, // TS_BITMAP_CAPABILITYSET::multipleRectangleSupport = TRUE - 0x00, 0x00, // TS_BITMAP_CAPABILITYSET::pad2octetsB - - // Order Capability Set (88 bytes) - // 0x03, 0x00, 0x58, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - // 0x00, 0x00, 0x00, 0x00, 0x40, 0x42, 0x0f, 0x00, 0x01, 0x00, 0x14, 0x00, 0x00, 0x00, 0x01, 0x00, - // 0x00, 0x00, 0x22, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, - // 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x01, 0x01, 0x01, 0x01, - // 0x00, 0x00, 0x00, 0x00, (byte) 0xa1, 0x06, 0x00, 0x00, 0x40, 0x42, 0x0f, 0x00, 0x40, 0x42, 0x0f, 0x00, - // 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - // - 0x03, 0x00, // TS_ORDER_CAPABILITYSET::capabilitySetType = CAPSTYPE_ORDER (3) - 0x58, 0x00, // TS_ORDER_CAPABILITYSET::lengthCapability = 88 bytes - - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // TS_ORDER_CAPABILITYSET::terminalDescriptor = "" - 0x40, 0x42, 0x0f, 0x00, // TS_ORDER_CAPABILITYSET::pad4octetsA - - 0x01, 0x00, // TS_ORDER_CAPABILITYSET::desktopSaveXGranularity = 1 - 0x14, 0x00, // TS_ORDER_CAPABILITYSET::desktopSaveYGranularity = 20 - 0x00, 0x00, // TS_ORDER_CAPABILITYSET::pad2octetsA - 0x01, 0x00, // TS_ORDER_CAPABILITYSET::maximumOrderLevel = ORD_LEVEL_1_ORDERS (1) - 0x00, 0x00, // TS_ORDER_CAPABILITYSET::numberFonts = 0 - - 0x22, 0x00, // TS_ORDER_CAPABILITYSET::orderFlags = 0x0022 = 0x0020 | 0x0002 = COLORINDEXSUPPORT | NEGOTIATEORDERSUPPORT - - 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_DSTBLT_INDEX] = TRUE - 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_PATBLT_INDEX] = TRUE - 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_SCRBLT_INDEX] = TRUE - 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_MEMBLT_INDEX] = TRUE - 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_MEM3BLT_INDEX] = TRUE - 0x00, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_ATEXTOUT_INDEX] = FALSE - 0x00, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_AEXTTEXTOUT_INDEX] = FALSE - 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_DRAWNINEGRID_INDEX] = TRUE - 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_LINETO_INDEX] = TRUE - 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_MULTI_DRAWNINEGRID_INDEX] = TRUE - 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_OPAQUERECT_INDEX] = TRUE - 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_SAVEBITMAP_INDEX] = TRUE - 0x00, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_WTEXTOUT_INDEX] = FALSE - 0x00, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_MEMBLT_R2_INDEX] = FALSE - 0x00, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_MEM3BLT_R2_INDEX] = FALSE - 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_MULTIDSTBLT_INDEX] = TRUE - 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_MULTIPATBLT_INDEX] = TRUE - 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_MULTISCRBLT_INDEX] = TRUE - 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_MULTIOPAQUERECT_INDEX] = TRUE - 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_FAST_INDEX_INDEX] = TRUE - 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_POLYGON_SC_INDEX] = TRUE - 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_POLYGON_CB_INDEX] = TRUE - 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_POLYLINE_INDEX] = TRUE - 0x00, // TS_ORDER_CAPABILITYSET::orderSupport[23] = 0 - 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_FAST_GLYPH_INDEX] = TRUE - 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_ELLIPSE_SC_INDEX] = TRUE - 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_ELLIPSE_CB_INDEX] = TRUE - 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_INDEX_INDEX] = TRUE - 0x00, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_WEXTTEXTOUT_INDEX] = FALSE - 0x00, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_WLONGTEXTOUT_INDEX] = FALSE - 0x00, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_WLONGEXTTEXTOUT_INDEX] = FALSE - 0x00, // TS_ORDER_CAPABILITYSET::orderSupport[24] = 0 - - (byte) 0xa1, 0x06, // TS_ORDER_CAPABILITYSET::textFlags = 0x06a1 - - 0x00, 0x00, // TS_ORDER_CAPABILITYSET::pad2octetsB - 0x40, 0x42, 0x0f, 0x00, // TS_ORDER_CAPABILITYSET::pad4octetsB - - 0x40, 0x42, 0x0f, 0x00, // TS_ORDER_CAPABILITYSET::desktopSaveSize = 0xf4240 = 1000000 - 0x01, 0x00, // TS_ORDER_CAPABILITYSET::pad2octetsC - 0x00, 0x00, // TS_ORDER_CAPABILITYSET::pad2octetsD - 0x00, 0x00, // TS_ORDER_CAPABILITYSET::textANSICodePage - 0x00, 0x00, // TS_ORDER_CAPABILITYSET::pad2octetsE - - // Color Table Cache Capability Set (8 bytes) - // 0x0a, 0x00, 0x08, 0x00, 0x06, 0x00, 0x00, 0x00, - // - 0x0a, 0x00, // TS_COLORTABLECACHE_CAPABILITYSET::capabilitySetType = CAPSTYPE_COLORCACHE (10) - 0x08, 0x00, // TS_COLORTABLECACHE_CAPABILITYSET::lengthCapability = 8 bytes - - 0x06, 0x00, // TS_COLORTABLECACHE_CAPABILITYSET::colorTableCacheSize = 6 - 0x00, 0x00, // TS_COLORTABLECACHE_CAPABILITYSET::pad2octets - - // Bitmap Cache Host Support Capability Set (8 bytes) - // 0x12, 0x00, 0x08, 0x00, 0x01, 0x00, 0x00, 0x00, - // - 0x12, 0x00, // TS_BITMAPCACHE_CAPABILITYSET_HOSTSUPPORT::capabilitySetType = CAPSTYPE_BITMAPCACHE_HOSTSUPPORT (18) - 0x08, 0x00, // TS_BITMAPCACHE_CAPABILITYSET_HOSTSUPPORT::lengthCapability = 8 bytes - - 0x01, // TS_BITMAPCACHE_CAPABILITYSET_HOSTSUPPORT::CacheVersion = 1 (corresponds to rev. 2 capabilities) - 0x00, // TS_BITMAPCACHE_CAPABILITYSET_HOSTSUPPORT::Pad1 - 0x00, 0x00, // TS_BITMAPCACHE_CAPABILITYSET_HOSTSUPPORT::Pad2 - - // Pointer Capability Set (10 bytes) - // 0x08, 0x00, 0x0a, 0x00, 0x01, 0x00, 0x19, 0x00, 0x19, 0x00, - // - 0x08, 0x00, // TS_POINTER_CAPABILITYSET::capabilitySetType = CAPSTYPE_POINTER (8) - 0x0a, 0x00, // TS_POINTER_CAPABILITYSET::lengthCapability = 10 bytes - - 0x01, 0x00, // TS_POINTER_CAPABILITYSET::colorPointerFlag = TRUE - 0x19, 0x00, // TS_POINTER_CAPABILITYSET::colorPointerCacheSize = 25 - 0x19, 0x00, // TS_POINTER_CAPABILITYSET::pointerCacheSize = 25 - - // Input Capability Set (88 bytes) - // 0x0d, 0x00, 0x58, 0x00, 0x35, 0x00, 0x00, 0x00, (byte) 0xa1, 0x06, 0x00, 0x00, 0x40, 0x42, 0x0f, 0x00, - // 0x0c, (byte) 0xf6, 0x13, (byte) 0xf3, (byte) 0x93, 0x5a, 0x37, (byte) 0xf3, 0x00, (byte) 0x90, 0x30, (byte) 0xe1, 0x34, 0x1c, 0x38, (byte) 0xf3, - // 0x40, (byte) 0xf6, 0x13, (byte) 0xf3, 0x04, 0x00, 0x00, 0x00, 0x4c, 0x54, (byte) 0xdc, (byte) 0xe2, 0x08, 0x50, (byte) 0xdc, (byte) 0xe2, - // 0x01, 0x00, 0x00, 0x00, 0x08, 0x50, (byte) 0xdc, (byte) 0xe2, 0x00, 0x00, 0x00, 0x00, 0x38, (byte) 0xf6, 0x13, (byte) 0xf3, - // 0x2e, 0x05, 0x38, (byte) 0xf3, 0x08, 0x50, (byte) 0xdc, (byte) 0xe2, 0x2c, (byte) 0xf6, 0x13, (byte) 0xf3, 0x00, 0x00, 0x00, 0x00, - // 0x08, 0x00, 0x0a, 0x00, 0x01, 0x00, 0x19, 0x00, - // - 0x0d, 0x00, // TS_INPUT_CAPABILITYSET::capabilitySetType = CAPSTYPE_INPUT (13) - 0x58, 0x00, // TS_INPUT_CAPABILITYSET::lengthCapability = 88 bytes - - 0x35, 0x00, // TS_INPUT_CAPABILITYSET::inputFlags = 0x0035 = 0x0020 | 0x0010 | 0x0004 | 0x0001 = INPUT_FLAG_FASTPATH_INPUT2 | INPUT_FLAG_VKPACKET | INPUT_FLAG_MOUSEX | INPUT_FLAG_SCANCODES - - 0x00, 0x00, // TS_INPUT_CAPABILITYSET::pad2octetsA - (byte) 0xa1, 0x06, 0x00, 0x00, // TS_INPUT_CAPABILITYSET::keyboardLayout (not initialized by server) - 0x40, 0x42, 0x0f, 0x00, // TS_INPUT_CAPABILITYSET::keyboardType (not initialized by server) - 0x0c, (byte) 0xf6, 0x13, (byte) 0xf3, // TS_INPUT_CAPABILITYSET::keyboardSubType (not initialized by server) - (byte) 0x93, 0x5a, 0x37, (byte) 0xf3, // TS_INPUT_CAPABILITYSET::keyboardFunctionKey (not initialized by server) - - // TS_INPUT_CAPABILITYSET::imeFileName (not initialized by server) - 0x00, (byte) 0x90, 0x30, (byte) 0xe1, 0x34, 0x1c, 0x38, (byte) 0xf3, 0x40, (byte) 0xf6, 0x13, (byte) 0xf3, 0x04, 0x00, 0x00, 0x00, - 0x4c, 0x54, (byte) 0xdc, (byte) 0xe2, 0x08, 0x50, (byte) 0xdc, (byte) 0xe2, 0x01, 0x00, 0x00, 0x00, 0x08, 0x50, (byte) 0xdc, (byte) 0xe2, - 0x00, 0x00, 0x00, 0x00, 0x38, (byte) 0xf6, 0x13, (byte) 0xf3, 0x2e, 0x05, 0x38, (byte) 0xf3, 0x08, 0x50, (byte) 0xdc, (byte) 0xe2, - 0x2c, (byte) 0xf6, 0x13, (byte) 0xf3, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x0a, 0x00, 0x01, 0x00, 0x19, 0x00, - - // RAIL Capability Set (8 bytes) - // 0x17, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, - // - 0x17, 0x00, // TS_RAIL_CAPABILITYSET::capabilitySetType = CAPSTYPE_RAIL (23) - 0x08, 0x00, // TS_RAIL_CAPABILITYSET::lengthCapability = 8 bytes - - 0x00, 0x00, 0x00, 0x00, // TS_RAIL_CAPABILITYSET::railSupportLevel = TS_RAIL_LEVEL_DEFAULT (0) - - // Windowing Capability Set (11 bytes) - // 0x18, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - // - 0x18, 0x00, // TS_WINDOW_CAPABILITYSET::capabilitySetType = CAPSTYPE_WINDOW (24) - 0x0b, 0x00, // TS_WINDOW_CAPABILITYSET::lengthCapability = 11 bytes - - 0x00, 0x00, 0x00, 0x00, // TS_WINDOW_CAPABILITYSET::wndSupportLevel = TS_WINDOW_LEVEL_DEFAULT (0) - 0x00, // TS_WINDOW_CAPABILITYSET::nIconCaches = 0 - 0x00, 0x00, // TS_WINDOW_CAPABILITYSET::nIconCacheEntries = 0 - - // Remainder of Demand Active PDU: - - 0x00, 0x00, 0x00, 0x00, // TS_DEMAND_ACTIVE_PDU::sessionId = 0 - }; - /* @formatter:on */ - - RdpState rdpState = new RdpState(); - ScreenDescription screenDescription = new ScreenDescription(); - - MockSource source = new MockSource("source", ByteBuffer.convertByteArraysToByteBuffers(packet)); - Element demandActive = new ServerDemandActivePDU("demand_active", screenDescription, rdpState); - Element sink = new FakeSink("sink"); - - Pipeline pipeline = new PipelineImpl("test"); - pipeline.add(source, demandActive, sink); - pipeline.link("source", "demand_active", "sink"); - pipeline.runMainLoop("source", STDOUT, false, false); - } - -} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerFastPath.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerFastPath.java deleted file mode 100644 index 1d7ddc29224..00000000000 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerFastPath.java +++ /dev/null @@ -1,258 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package rdpclient; - -import streamer.BaseElement; -import streamer.ByteBuffer; -import streamer.Link; - -/** - * @see http://msdn.microsoft.com/en-us/library/cc240621.aspx - */ -public class ServerFastPath extends BaseElement { - - /** - * TPKT protocol version (first byte). - */ - public static final int PROTOCOL_TPKT = 3; - - /** - * Fast path protocol version (first two bits of first byte). - */ - public static final int PROTOCOL_FASTPATH = 0; - - /** - * TPKT packets will be pushed to that pad. - */ - public static final String TPKT_PAD = "tpkt"; - - private static final String ORDERS_PAD = "orders"; - private static final String BITMAP_PAD = "bitmap"; - private static final String PALETTE_PAD = "palette"; - - /** - * Indicates that packet contains 8 byte secure checksum at top of packet. Top - * two bits of first byte. - */ - public static final int FASTPATH_OUTPUT_SECURE_CHECKSUM = 1; - - /** - * Indicates that packet contains 8 byte secure checksum at top of packet and - * packet content is encrypted. Top two bits of first byte. - */ - public static final int FASTPATH_OUTPUT_ENCRYPTED = 2; - - public static final int FASTPATH_UPDATETYPE_ORDERS = 0; - public static final int FASTPATH_UPDATETYPE_BITMAP = 1; - public static final int FASTPATH_UPDATETYPE_PALETTE = 2; - public static final int FASTPATH_UPDATETYPE_SYNCHRONIZE = 3; - public static final int FASTPATH_UPDATETYPE_SURFCMDS = 4; - public static final int FASTPATH_UPDATETYPE_PTR_NULL = 5; - public static final int FASTPATH_UPDATETYPE_PTR_DEFAULT = 6; - public static final int FASTPATH_UPDATETYPE_PTR_POSITION = 8; - public static final int FASTPATH_UPDATETYPE_COLOR = 9; - public static final int FASTPATH_UPDATETYPE_CACHED = 0xa; - public static final int FASTPATH_UPDATETYPE_POINTER = 0xb; - - public static final int FASTPATH_FRAGMENT_SINGLE = 0; - public static final int FASTPATH_FRAGMENT_LAST = 1; - public static final int FASTPATH_FRAGMENT_FIRST = 2; - public static final int FASTPATH_FRAGMENT_NEXT = 3; - - public static final int FASTPATH_OUTPUT_COMPRESSION_USED = 2; - - public ServerFastPath(String id) { - super(id); - } - - @Override - public void handleData(ByteBuffer buf, Link link) { - if (buf == null) - return; - - if (verbose) - System.out.println("[" + this + "] INFO: Data received: " + buf + "."); - - //* DEBUG */System.out.println(buf.toHexString(buf.length)); - - // We need at 4 bytes to read packet type (TPKT or FastPath) and packet - // length - if (!cap(buf, 4, UNLIMITED, link, false)) - return; - - int typeAndFlags = buf.readUnsignedByte(); - - if (typeAndFlags == PROTOCOL_TPKT) { - // - // TPKT - // - - // Reserved - buf.skipBytes(1); - - // Read TPKT length - int length = buf.readUnsignedShort(); - - if (!cap(buf, length, length, link, false)) - // Wait for full packet to arrive - return; - - pushDataToPad(TPKT_PAD, buf); - - // TPKT is handled - return; - } - - // - // FastPath - // - // Number of bytes in updateData field (including header (1+1 or 2 - // bytes)) - int length = buf.readVariableUnsignedShort(); - - // Length is the size of payload, so we need to calculate from cursor - if (!cap(buf, length, length, link, false)) - // Wait for full packet to arrive - return; - - int type = typeAndFlags & 0x3; - int securityFlags = (typeAndFlags >> 6) & 0x3; - - // Assertions - { - if (type != PROTOCOL_FASTPATH) - throw new RuntimeException("Unknown protocol. Expected protocol: 0 (FastPath). Actual protocol: " + type + ", data: " + buf + "."); - - switch (securityFlags) { - case FASTPATH_OUTPUT_SECURE_CHECKSUM: - // TODO - throw new RuntimeException("Secure checksum is not supported in FastPath packets."); - case FASTPATH_OUTPUT_ENCRYPTED: - // TODO - throw new RuntimeException("Encryption is not supported in FastPath packets."); - } - } - - // TODO: optional FIPS information, when FIPS is selected - // TODO: optional data signature (checksum), when checksum or FIPS is - // selected - - // Array of FastPath update fields - while (buf.cursor < buf.length) { - - int updateHeader = buf.readUnsignedByte(); - - int size = buf.readUnsignedShortLE(); - - int updateCode = updateHeader & 0xf; - int fragmentation = (updateHeader >> 4) & 0x3; - int compression = (updateHeader >> 6) & 0x3; - - if (verbose) - System.out.println("[" + this + "] INFO: FastPath update received. UpdateCode: " + updateCode + ", fragmentation: " + fragmentation + ", compression: " + - compression + ", size: " + size + "."); - - ByteBuffer data = buf.readBytes(size); - buf.putMetadata("fragmentation", fragmentation); - buf.putMetadata("compression", compression); - - switch (updateCode) { - - case FASTPATH_UPDATETYPE_ORDERS: - if (verbose) - System.out.println("[" + this + "] INFO: FASTPATH_UPDATETYPE_ORDERS."); - pushDataToPad(ORDERS_PAD, data); - break; - - case FASTPATH_UPDATETYPE_BITMAP: - if (verbose) - System.out.println("[" + this + "] INFO: FASTPATH_UPDATETYPE_BITMAP."); - pushDataToPad(BITMAP_PAD, data); - break; - - case FASTPATH_UPDATETYPE_PALETTE: - if (verbose) - System.out.println("[" + this + "] INFO: FASTPATH_UPDATETYPE_PALETTE."); - pushDataToPad(PALETTE_PAD, data); - break; - - case FASTPATH_UPDATETYPE_SYNCHRONIZE: - // @see http://msdn.microsoft.com/en-us/library/cc240625.aspx - if (verbose) - System.out.println("[" + this + "] INFO: FASTPATH_UPDATETYPE_SYNCHRONIZE."); - - data.unref(); - - if (size != 0) - throw new RuntimeException("Size of FastPath synchronize packet must be 0. UpdateCode: " + updateCode + ", fragmentation: " + fragmentation + - ", compression: " + compression + ", size: " + size + ", data: " + data + "."); - break; - - case FASTPATH_UPDATETYPE_SURFCMDS: - if (verbose) - System.out.println("[" + this + "] INFO: FASTPATH_UPDATETYPE_SURFCMDS."); - - break; - - case FASTPATH_UPDATETYPE_PTR_NULL: - if (verbose) - System.out.println("[" + this + "] INFO: FASTPATH_UPDATETYPE_PTR_NULL."); - - break; - - case FASTPATH_UPDATETYPE_PTR_DEFAULT: - if (verbose) - System.out.println("[" + this + "] INFO: FASTPATH_UPDATETYPE_PTR_DEFAULT."); - - break; - - case FASTPATH_UPDATETYPE_PTR_POSITION: - if (verbose) - System.out.println("[" + this + "] INFO: FASTPATH_UPDATETYPE_PTR_POSITION."); - - break; - - case FASTPATH_UPDATETYPE_COLOR: - if (verbose) - System.out.println("[" + this + "] INFO: FASTPATH_UPDATETYPE_COLOR."); - - break; - - case FASTPATH_UPDATETYPE_CACHED: - if (verbose) - System.out.println("[" + this + "] INFO: FASTPATH_UPDATETYPE_CACHED."); - - break; - - case FASTPATH_UPDATETYPE_POINTER: - if (verbose) - System.out.println("[" + this + "] INFO: FASTPATH_UPDATETYPE_POINTER."); - - break; - - default: - throw new RuntimeException("Unknown FastPath update. UpdateCode: " + updateCode + ", fragmentation: " + fragmentation + ", compression: " + - compression + ", size: " + size + ", data: " + data + "."); - - } - - } - - buf.unref(); - } - -} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerMCSPDU.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerMCSPDU.java deleted file mode 100644 index d9e4f425901..00000000000 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerMCSPDU.java +++ /dev/null @@ -1,149 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package rdpclient; - -import streamer.BaseElement; -import streamer.ByteBuffer; -import streamer.Element; -import streamer.Link; -import streamer.MockSink; -import streamer.MockSource; -import streamer.Pipeline; -import streamer.PipelineImpl; - -public class ServerMCSPDU extends BaseElement { - - public ServerMCSPDU(String id) { - super(id); - } - - @Override - public void handleData(ByteBuffer buf, Link link) { - if (verbose) - System.out.println("[" + this + "] INFO: Data received: " + buf + "."); - - byte headerByte = buf.readSignedByte(); - int type = headerByte >> 2; - - switch (type) { - // Expected type: send data indication: 26 (0x1a, top 6 bits, or 0x68) - case 0x1a: { - // int userId = buf.readUnsignedShort() + 1001; // User ID: 1002 (1001+1) - buf.skipBytes(2); // Ignore user ID - - int channelId = buf.readUnsignedShort(); // Channel ID: 1003 - - int flags = buf.readSignedByte(); - if ((flags & 0x30) != 0x30) - throw new RuntimeException("Fragmented MCS packets are not supported."); - - int payloadLength = buf.readVariableUnsignedShort(); - - ByteBuffer data = buf.readBytes(payloadLength); - - buf.unref(); - - pushDataToPad("channel_" + channelId, data); - break; - } - - case 0x8: { - // Disconnection sequence. - buf.unref(); - break; - } - - default: - throw new RuntimeException("Unsupported MCS packet type: " + type + "(" + headerByte + "), data: " + buf + "."); - } - - } - - /** - * Example. - * - */ - public static void main(String args[]) { - // System.setProperty("streamer.Link.debug", "true"); - // System.setProperty("streamer.Element.debug", "true"); - // System.setProperty("streamer.Pipeline.debug", "true"); - - byte[] packet = new byte[] { - // TPKT - (byte)0x03, (byte)0x00, // TPKT Header: TPKT version = 3 - (byte)0x00, (byte)0x1B, // TPKT length: 27 bytes - - // X224 - (byte)0x02, // X224 Length: 2 bytes - (byte)0xF0, // X224 Type: Data - (byte)0x80, // X224 EOT - - // MCS - // Type: send data indication: 26 (0x1a, top 6 bits) - (byte)0x68, // ?? - - (byte)0x00, (byte)0x01, // User ID: 1002 (1001+1) - (byte)0x03, (byte)0xEB, // Channel ID: 1003 - (byte)0x70, // Data priority: high, segmentation: begin|end - (byte)0x0D, // Payload length: 13 bytes - - // Deactivate all PDU - (byte)0x0D, (byte)0x00, // Length: 13 bytes (LE) - - // - PDUType: 22 (0x16, LE) - // Type: (............0110) TS_PDUTYPE_DEACTIVATEALLPDU - // ProtocolVersion: (000000000001....) 1 - (byte)0x16, (byte)0x00, - - (byte)0xEA, (byte)0x03, // PDU source: 1002 (LE) - (byte)0xEA, (byte)0x03, (byte)0x01, (byte)0x00, // ShareID = 66538 - - (byte)0x01, (byte)0x00, // Length if source descriptor: 1 (LE) - (byte)0x00, // Source descriptor (should be set to 0): 0 - }; - - MockSource source = new MockSource("source", ByteBuffer.convertByteArraysToByteBuffers(packet)); - Element mcs = new ServerMCSPDU("mcs") { - { - verbose = true; - } - }; - Element tpkt = new ServerTpkt("tpkt"); - Element x224 = new ServerX224DataPdu("x224"); - Element sink = new MockSink("sink", ByteBuffer.convertByteArraysToByteBuffers(new byte[] { - // Deactivate all PDU - (byte)0x0D, (byte)0x00, // Length: 13 bytes (LE) - - // - PDUType: 22 (0x16, LE) - // Type: (............0110) TS_PDUTYPE_DEACTIVATEALLPDU - // ProtocolVersion: (000000000001....) 1 - (byte)0x16, (byte)0x00, - - (byte)0xEA, (byte)0x03, // PDU source: 1002 (LE) - (byte)0xEA, (byte)0x03, (byte)0x01, (byte)0x00, // ShareID = 66538 - - (byte)0x01, (byte)0x00, // Length if source descriptor: 1 (LE) - (byte)0x00, // Source descriptor (should be set to 0): 0 - })); - - Pipeline pipeline = new PipelineImpl("test"); - pipeline.add(source, tpkt, x224, mcs, sink); - pipeline.link("source", "tpkt", "x224", "mcs >channel_1003", "sink"); - pipeline.runMainLoop("source", STDOUT, false, false); - } - -} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerPacketSniffer.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerPacketSniffer.java deleted file mode 100644 index 290c1bcf9e7..00000000000 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerPacketSniffer.java +++ /dev/null @@ -1,50 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package rdpclient; - -/** - * Try to determine packet content by it header fingerprint. - */ -public class ServerPacketSniffer extends PacketSniffer { - - private static final Pair[] serverRegexps = new Pair[] { -// @formatter:off - new Pair("Server FastPath update", "04"), - new Pair("Server X224ConnectionRequest", "03 00 XX XX 0E D0"), - new Pair("Server MCSConnectResponse", "03 00 XX XX 02 F0 80 7F 66 5A"), - new Pair("Server AttachUserConfirm", "03 00 XX XX 02 F0 80 2E"), - new Pair("Server ChannelJoinConfirm", "03 00 XX XX 02 F0 80 3E"), - new Pair("Server ErrorAlert", "03 00 XX XX 02 F0 80 68 00 01 03 EB 70 14 80 00"), - new Pair("Server DemandActivePDU", "03 00 XX XX 02 F0 80 68 00 01 03 EB 70 XX XX XX XX 11"), - new Pair("Server ControlPDU", "03 00 XX XX 02 F0 80 68 00 01 03 EB 70 XX XX XX 17 00 EA 03 EA 03 XX 00 XX XX XX XX 14"), - new Pair("Server SynchronizePDU", "03 00 XX XX 02 F0 80 68 00 01 03 EB 70 XX XX XX 17 00 EA 03 EA 03 XX 00 XX XX XX XX 1F"), - new Pair("Server FontMapPDU", "03 00 XX XX 02 F0 80 68 00 01 03 EB 70 XX XX XX 17 00 EA 03 EA 03 XX 00 XX XX XX XX 28"), - new Pair("Server SET_ERROR_INFO_PDU", "03 00 XX XX 02 F0 80 68 00 01 03 EB 30 XX XX XX 17 00 00 00 EA 03 XX 00 XX XX XX XX 2F"), - new Pair("Server DeactivateAllPDU", "03 00 XX XX 02 F0 80 68 00 01 03 EB 70 XX XX XX 16 00"), - new Pair("Server CloseConnection", "03 00 00 09 02 F0 80 21 80"), - -// new Pair("Server TPKT unknown packet", "03"), -// new Pair("Server FastPath update with flags or continuation", ".*"), - // @formatter:on - - }; - - public ServerPacketSniffer(String id) { - super(id, serverRegexps); - } - -} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/adapter/AwtRdpKeyboardAdapter.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/adapter/AwtRdpKeyboardAdapter.java new file mode 100755 index 00000000000..2d1e8fca6c3 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/adapter/AwtRdpKeyboardAdapter.java @@ -0,0 +1,350 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.adapter; + +import java.awt.event.KeyEvent; + +import streamer.BaseElement; +import streamer.ByteBuffer; +import streamer.Link; +import common.KeyOrder; + +public class AwtRdpKeyboardAdapter extends BaseElement { + + /** + * Absence of this flag indicates a key-down event, while its presence + * indicates a key-release event. + */ + public static final int FASTPATH_INPUT_KBDFLAGS_RELEASE = 0x01; + + /** + * Keystroke message contains an extended scancode. For enhanced 101-key and + * 102-key keyboards, extended keys include the right ALT and right CTRL keys + * on the main section of the keyboard; the INS, DEL, HOME, END, PAGE UP, PAGE + * DOWN and ARROW keys in the clusters to the left of the numeric keypad; and + * the Divide ("/") and ENTER keys in the numeric keypad. + */ + public static final int FASTPATH_INPUT_KBDFLAGS_EXTENDED = 0x02; + + public static final int FASTPATH_INPUT_EVENT_SCANCODE = 0; + + public AwtRdpKeyboardAdapter(String id) { + super(id); + } + + @Override + public void handleData(ByteBuffer buf, Link link) { + if (verbose) + System.out.println("[" + this + "] INFO: Data received: " + buf + "."); + + KeyOrder order = (KeyOrder)buf.getOrder(); + buf.unref(); + + ByteBuffer outBuf = new ByteBuffer(2, true); + + int scanCode = map_en_us(order.event); + + // eventHeader (1 byte): An 8-bit, unsigned integer. The format of this + // field is the same as the eventHeader byte field described in section + // 2.2.8.1.2.2. The eventCode bitfield (3 bits in size) MUST be set to + // FASTPATH_INPUT_EVENT_SCANCODE (0). The eventFlags bitfield (5 bits in + // size) contains flags describing the keyboard event. + outBuf.writeByte((scanCode >> 8) | (FASTPATH_INPUT_EVENT_SCANCODE << 5) | ((order.pressed) ? 0 : FASTPATH_INPUT_KBDFLAGS_RELEASE)); + + // keyCode (1 byte): An 8-bit, unsigned integer. The scancode of the key + // which triggered the event. + outBuf.writeByte(scanCode); + + // Push buffer to one pad only, so it can be modified without copying of + // data + pushDataToPad(STDOUT, outBuf); + } + + /** + * Return key scan code (in lower byte) and extended flags (in second byte). + */ + private int map_en_us(KeyEvent event) { + // Also set extended key flag when necessary. + // For enhanced 101-key and 102-key keyboards, extended keys include the + // right ALT and right CTRL keys on the main section of the keyboard; the + // INS, DEL, HOME, END, PAGE UP, PAGE DOWN and ARROW keys in the clusters to + // the left of the numeric keypad; and the Divide ("/") and ENTER keys in + // the numeric keypad. + + switch (event.getKeyCode()) { + // Functional keys + case KeyEvent.VK_ESCAPE: + return 1; + case KeyEvent.VK_F1: + return 59; + case KeyEvent.VK_F2: + return 60; + case KeyEvent.VK_F3: + return 61; + case KeyEvent.VK_F4: + return 62; + case KeyEvent.VK_F5: + return 63; + case KeyEvent.VK_F6: + return 64; + case KeyEvent.VK_F7: + return 65; + case KeyEvent.VK_F8: + return 66; + case KeyEvent.VK_F9: + return 67; + case KeyEvent.VK_F10: + return 68; + case KeyEvent.VK_F11: + return 87; + case KeyEvent.VK_F12: + return 88; + + // Row #1 + case KeyEvent.VK_BACK_QUOTE: + return 41; + case KeyEvent.VK_1: + return 2; + case KeyEvent.VK_2: + return 3; + case KeyEvent.VK_3: + return 4; + case KeyEvent.VK_4: + return 5; + case KeyEvent.VK_5: + return 6; + case KeyEvent.VK_6: + return 7; + case KeyEvent.VK_7: + return 8; + case KeyEvent.VK_8: + return 9; + case KeyEvent.VK_9: + return 10; + case KeyEvent.VK_0: + return 11; + case KeyEvent.VK_MINUS: + return 12; + case KeyEvent.VK_EQUALS: + return 13; + case KeyEvent.VK_BACK_SPACE: + return 14; + + // Row #2 + case KeyEvent.VK_TAB: + return 15; + case KeyEvent.VK_Q: + return 16; + case KeyEvent.VK_W: + return 17; + case KeyEvent.VK_E: + return 18; + case KeyEvent.VK_R: + return 19; + case KeyEvent.VK_T: + return 20; + case KeyEvent.VK_Y: + return 21; + case KeyEvent.VK_U: + return 22; + case KeyEvent.VK_I: + return 23; + case KeyEvent.VK_O: + return 24; + case KeyEvent.VK_P: + return 25; + case KeyEvent.VK_OPEN_BRACKET: + return 26; + case KeyEvent.VK_CLOSE_BRACKET: + return 27; + case KeyEvent.VK_ENTER: + switch (event.getKeyLocation()) { + default: + case KeyEvent.KEY_LOCATION_STANDARD: + return 28; + case KeyEvent.KEY_LOCATION_NUMPAD: + return (FASTPATH_INPUT_KBDFLAGS_EXTENDED << 8) | 28; + } + + // Row #3 + case KeyEvent.VK_CAPS_LOCK: + return 58; + case KeyEvent.VK_A: + return 30; + case KeyEvent.VK_S: + return 31; + case KeyEvent.VK_D: + return 32; + case KeyEvent.VK_F: + return 33; + case KeyEvent.VK_G: + return 34; + case KeyEvent.VK_H: + return 35; + case KeyEvent.VK_J: + return 36; + case KeyEvent.VK_K: + return 37; + case KeyEvent.VK_L: + return 38; + case KeyEvent.VK_SEMICOLON: + return 39; + case KeyEvent.VK_QUOTE: + return 40; + + // Row #4 + case KeyEvent.VK_SHIFT: + switch (event.getKeyLocation()) { + default: + case KeyEvent.KEY_LOCATION_LEFT: + return 42; + case KeyEvent.KEY_LOCATION_RIGHT: + return 54; + } + case KeyEvent.VK_BACK_SLASH: + return 43; + case KeyEvent.VK_Z: + return 44; + case KeyEvent.VK_X: + return 45; + case KeyEvent.VK_C: + return 46; + case KeyEvent.VK_V: + return 47; + case KeyEvent.VK_B: + return 48; + case KeyEvent.VK_N: + return 49; + case KeyEvent.VK_M: + return 50; + case KeyEvent.VK_COMMA: + return 51; + case KeyEvent.VK_PERIOD: + return 52; + case KeyEvent.VK_SLASH: + return 53; + + // + // Bottom row + case KeyEvent.VK_CONTROL: + switch (event.getKeyLocation()) { + default: + case KeyEvent.KEY_LOCATION_LEFT: + return 29; + case KeyEvent.KEY_LOCATION_RIGHT: + return (FASTPATH_INPUT_KBDFLAGS_EXTENDED << 8) | 29; + } + case KeyEvent.VK_WINDOWS: + switch (event.getKeyLocation()) { + default: + case KeyEvent.KEY_LOCATION_LEFT: + return 91; + case KeyEvent.KEY_LOCATION_RIGHT: + return 92; + } + case KeyEvent.VK_ALT: + switch (event.getKeyLocation()) { + default: + case KeyEvent.KEY_LOCATION_LEFT: + return 56; + case KeyEvent.KEY_LOCATION_RIGHT: + return (FASTPATH_INPUT_KBDFLAGS_EXTENDED << 8) | 56; + } + case KeyEvent.VK_ALT_GRAPH: + return (FASTPATH_INPUT_KBDFLAGS_EXTENDED << 8) | 56; + + case KeyEvent.VK_SPACE: + return 57; + + case KeyEvent.VK_CONTEXT_MENU: + return 93; + + // + // Special keys + case KeyEvent.VK_PRINTSCREEN: + return 55; + case KeyEvent.VK_SCROLL_LOCK: + return 70; + case KeyEvent.VK_PAUSE: + return 29; + + // Text navigation keys + case KeyEvent.VK_INSERT: + return (FASTPATH_INPUT_KBDFLAGS_EXTENDED << 8) | 82; + case KeyEvent.VK_HOME: + return (FASTPATH_INPUT_KBDFLAGS_EXTENDED << 8) | 71; + case KeyEvent.VK_PAGE_UP: + return (FASTPATH_INPUT_KBDFLAGS_EXTENDED << 8) | 73; + case KeyEvent.VK_DELETE: + return (FASTPATH_INPUT_KBDFLAGS_EXTENDED << 8) | 83; + case KeyEvent.VK_END: + return (FASTPATH_INPUT_KBDFLAGS_EXTENDED << 8) | 79; + case KeyEvent.VK_PAGE_DOWN: + return (FASTPATH_INPUT_KBDFLAGS_EXTENDED << 8) | 81; + + // Cursor keys + case KeyEvent.VK_UP: + return (FASTPATH_INPUT_KBDFLAGS_EXTENDED << 8) | 72; + case KeyEvent.VK_LEFT: + return (FASTPATH_INPUT_KBDFLAGS_EXTENDED << 8) | 75; + case KeyEvent.VK_DOWN: + return (FASTPATH_INPUT_KBDFLAGS_EXTENDED << 8) | 80; + case KeyEvent.VK_RIGHT: + return (FASTPATH_INPUT_KBDFLAGS_EXTENDED << 8) | 77; + + // Keypad + case KeyEvent.VK_NUM_LOCK: + return 69; + case KeyEvent.VK_DIVIDE: + return (FASTPATH_INPUT_KBDFLAGS_EXTENDED << 8) | 53; + case KeyEvent.VK_MULTIPLY: + return 55; + case KeyEvent.VK_SUBTRACT: + return 74; + case KeyEvent.VK_ADD: + return 78; + + case KeyEvent.VK_NUMPAD7: + return 71; + case KeyEvent.VK_NUMPAD8: + return 72; + case KeyEvent.VK_NUMPAD9: + return 73; + case KeyEvent.VK_NUMPAD4: + return 75; + case KeyEvent.VK_NUMPAD5: + return 76; + case KeyEvent.VK_NUMPAD6: + return 77; + case KeyEvent.VK_NUMPAD1: + return 79; + case KeyEvent.VK_NUMPAD2: + return 80; + case KeyEvent.VK_NUMPAD3: + return 81; + case KeyEvent.VK_NUMPAD0: + return 82; + case KeyEvent.VK_DECIMAL: + return 83; + + default: + System.err.println("Key is not mapped: " + event + "."); + return event.getKeyCode(); + } + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/AwtRdpMouseAdapter.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/adapter/AwtRdpMouseAdapter.java old mode 100644 new mode 100755 similarity index 91% rename from services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/AwtRdpMouseAdapter.java rename to services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/adapter/AwtRdpMouseAdapter.java index bb7c5867a22..6b347aac832 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/AwtRdpMouseAdapter.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/adapter/AwtRdpMouseAdapter.java @@ -14,10 +14,9 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package rdpclient; +package rdpclient.adapter; import java.awt.event.InputEvent; -import java.awt.event.MouseEvent; import streamer.BaseElement; import streamer.ByteBuffer; @@ -28,58 +27,58 @@ import common.MouseOrder; * @see http://msdn.microsoft.com/en-us/library/cc240594.aspx */ public class AwtRdpMouseAdapter extends BaseElement { - public static int FASTPATH_INPUT_EVENT_MOUSE = 0x01; + public final static int FASTPATH_INPUT_EVENT_MOUSE = 0x01; /** * Event is a mouse wheel rotation. The only valid flags in a wheel rotation * event are PTRFLAGS_WHEEL_NEGATIVE and the WheelRotationMask; all other * pointer flags are ignored. */ - public static int PTRFLAGS_WHEEL = 0x0200; + public final static int PTRFLAGS_WHEEL = 0x0200; /** * Wheel rotation value (contained in the WheelRotationMask bit field) is * negative and MUST be sign-extended before injection at the server. */ - public static int PTRFLAGS_WHEEL_NEGATIVE = 0x0100; + public final static int PTRFLAGS_WHEEL_NEGATIVE = 0x0100; /** * Bit field describing the number of rotation units the mouse wheel was * rotated. The value is negative if the PTRFLAGS_WHEEL_NEGATIVE flag is set. */ - public static int WHEEL_ROTATION_MASK = 0x01FF; + public final static int WHEEL_ROTATION_MASK = 0x01FF; /** * Indicates that the mouse position MUST be updated to the location specified * by the xPos and yPos fields. */ - public static int PTRFLAGS_MOVE = 0x0800; + public final static int PTRFLAGS_MOVE = 0x0800; /** * Indicates that a click event has occurred at the position specified by the * xPos and yPos fields. The button flags indicate which button has been * clicked and at least one of these flags MUST be set. */ - public static int PTRFLAGS_DOWN = 0x8000; + public final static int PTRFLAGS_DOWN = 0x8000; /** * Mouse button 1 (left button) was clicked or released. If the PTRFLAGS_DOWN * flag is set, then the button was clicked, otherwise it was released. */ - public static int PTRFLAGS_BUTTON1 = 0x1000; + public final static int PTRFLAGS_BUTTON1 = 0x1000; /** * Mouse button 2 (right button) was clicked or released. If the PTRFLAGS_DOWN * flag is set, then the button was clicked, otherwise it was released. */ - public static int PTRFLAGS_BUTTON2 = 0x2000; + public final static int PTRFLAGS_BUTTON2 = 0x2000; /** * Mouse button 3 (middle button or wheel) was clicked or released. If the * PTRFLAGS_DOWN flag is set, then the button was clicked, otherwise it was * released. */ - public static int PTRFLAGS_BUTTON3 = 0x4000; + public final static int PTRFLAGS_BUTTON3 = 0x4000; public AwtRdpMouseAdapter(String id) { super(id); diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/clip/ClipboardDataFormat.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/clip/ClipboardDataFormat.java new file mode 100755 index 00000000000..3a165360933 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/clip/ClipboardDataFormat.java @@ -0,0 +1,143 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.clip; + +import java.util.Map; + +import rdpclient.rdp.RdpConstants; +import streamer.ByteBuffer; + +public class ClipboardDataFormat { + + public static final String HTML_FORMAT = "HTML Format"; + public static final String RTF_AS_TEXT = "RTF As Text"; + public static final String RICH_TEXT_FORMAT_WITHOUT_OBJECTS = "Rich Text Format Without Objects"; + public static final String RICH_TEXT_FORMAT = "Rich Text Format"; + + public static final int CB_FORMAT_TEXT = 0x0001; + public static final int CB_FORMAT_UNICODETEXT = 0x000D; + + /** + * Supported clipboard data formats in order of preference. + */ + public static final Object[] supportedTextBasedFormats = new Object[] { + // ID's + CB_FORMAT_UNICODETEXT, CB_FORMAT_TEXT, + + // Names + HTML_FORMAT, + + // RTF_AS_TEXT, + // RICH_TEXT_FORMAT_WITHOUT_OBJECTS, + // RICH_TEXT_FORMAT, + + }; + + public final int id; + public final String name; + + public ClipboardDataFormat(int id, String name) { + super(); + this.id = id; + this.name = name; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + id; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ClipboardDataFormat other = (ClipboardDataFormat)obj; + if (id != other.id) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + + @Override + public String toString() { + return "ClipboardDataFormat [id=" + id + ", name=\"" + name + "\"" + ((id == CB_FORMAT_UNICODETEXT) ? " (Unicode text)" : "") + + ((id == CB_FORMAT_TEXT) ? " (text)" : "") + "]"; + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + /** + * Parse response of supported format and return it as string. + */ + public String parseServerResponseAsString(ByteBuffer buf) { + switch (id) { + case CB_FORMAT_UNICODETEXT: + return buf.readVariableWideString(RdpConstants.CHARSET_16); + case CB_FORMAT_TEXT: + return buf.readVariableString(RdpConstants.CHARSET_8); + } + + if (name == null || name.length() == 0) + return null; + + if (HTML_FORMAT.equals(name)) + return buf.readVariableString(RdpConstants.CHARSET_8); // TODO: verify + + // if (RTF_AS_TEXT.equals(name)) + // return buf.readVariableString(RdpConstants.CHARSET_8); // TODO: verify + // + // if (RICH_TEXT_FORMAT_WITHOUT_OBJECTS.equals(name)) + // return buf.readVariableString(RdpConstants.CHARSET_8); // TODO: verify + // + // if (RICH_TEXT_FORMAT.equals(name)) + // return buf.readVariableString(RdpConstants.CHARSET_8); // TODO: verify + + return null; + } + + /** + * Find first (richest) text-based data format. + * + * @return text-based data format or null, when not found + */ + public static ClipboardDataFormat findBestTextFormat(Map serverClipboardDataFormats) { + for (Object formatKey : ClipboardDataFormat.supportedTextBasedFormats) + if (serverClipboardDataFormats.containsKey(formatKey)) + return serverClipboardDataFormats.get(formatKey); + + return null; + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/clip/ClipboardState.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/clip/ClipboardState.java new file mode 100755 index 00000000000..9c465b54110 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/clip/ClipboardState.java @@ -0,0 +1,70 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.clip; + +import java.util.HashMap; +import java.util.Map; + +public class ClipboardState { + + /** + * The Long Format Name variant of the Format List PDU is supported for + * exchanging updated format names. If this flag is not set, the Short Format + * Name variant MUST be used. If this flag is set by both protocol endpoints, + * then the Long Format Name variant MUST be used. + */ + public boolean serverUseLongFormatNames = false; + public final boolean clientUseLongFormatNames = false; + + /** + * File copy and paste using stream-based operations are supported using the + * File Contents Request PDU and File Contents Response PDU. + */ + public boolean serverStreamFileClipEnabled = false; + public final boolean clientStreamFileClipEnabled = false; + + /** + * Indicates that any description of files to copy and paste MUST NOT include + * the source path of the files. + */ + public boolean serverFileClipNoFilePaths = false; + public final boolean clientFileClipNoFilePaths = false; + + /** + * Locking and unlocking of File Stream data on the clipboard is supported + * using the Lock Clipboard Data PDU and Unlock Clipboard Data PDU. + */ + public boolean serverCanLockClipdata = false; + public final boolean clientCanLockClipdata = false; + + /** + * The Monitor Ready PDU is sent from the server to the client to indicate + * that the server is initialized and ready. + */ + public boolean serverReady = false; + + /** + * Set of data formats, which are supported by server for paste operation. + */ + public Map serverClipboardDataFormats = new HashMap(0); + + /** + * Server sends clipboard data in requested format. + */ + public ClipboardDataFormat serverRequestedFormat; + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/clip/ServerClipRdrChannelRouter.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/clip/ServerClipRdrChannelRouter.java new file mode 100755 index 00000000000..32381247ff8 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/clip/ServerClipRdrChannelRouter.java @@ -0,0 +1,193 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.clip; + +import streamer.BaseElement; +import streamer.ByteBuffer; +import streamer.Link; + +public class ServerClipRdrChannelRouter extends BaseElement { + + /** + * Key for ASCII names message flag in payload metadata. Value is Boolean. + */ + public static final String ASCII_NAMES = "ascii_names"; + + /** + * Key for success/fail message flag in payload metadata. Value is Boolean. + */ + public static final String SUCCESS = "success"; + + /** + * Monitor Ready PDU + */ + public static final int CB_MONITOR_READY = 0x0001; + + /** + * Format List PDU + */ + public static final int CB_FORMAT_LIST = 0x0002; + + /** + * Format List Response PDU + */ + public static final int CB_FORMAT_LIST_RESPONSE = 0x0003; + + /** + * Format Data Request PDU + */ + public static final int CB_FORMAT_DATA_REQUEST = 0x0004; + + /** + * Format Data Response PDU + */ + public static final int CB_FORMAT_DATA_RESPONSE = 0x0005; + + /** + * Temporary Directory PDU + */ + public static final int CB_TEMP_DIRECTORY = 0x0006; + + /** + * Clipboard Capabilities PDU + */ + public static final int CB_CLIP_CAPS = 0x0007; + + /** + * File Contents Request PDU + */ + public static final int CB_FILECONTENTS_REQUEST = 0x0008; + + /** + * File Contents Response PDU + */ + public static final int CB_FILECONTENTS_RESPONSE = 0x0009; + + /** + * Lock Clipboard Data PDU + */ + public static final int CB_LOCK_CLIPDATA = 0x000A; + + /** + * Unlock Clipboard Data PDU + */ + public static final int CB_UNLOCK_CLIPDATA = 0x000B; + + /** + * Used by the Format List Response PDU, Format Data Response PDU, and File + * Contents Response PDU to indicate that the associated request Format List + * PDU, Format Data Request PDU, and File Contents Request PDU were processed + * successfully. + */ + public static final int CB_RESPONSE_OK = 0x0001; + + /** + * Used by the Format List Response PDU, Format Data Response PDU, and File + * Contents Response PDU to indicate that the associated Format List PDU, + * Format Data Request PDU, and File Contents Request PDU were not processed + * successfully. + */ + public static final int CB_RESPONSE_FAIL = 0x0002; + + /** + * Used by the Short Format Name variant of the Format List Response PDU to + * indicate the format names are in ASCII 8. + */ + public static final int CB_ASCII_NAMES = 0x0004; + + public ServerClipRdrChannelRouter(String id) { + super(id); + } + + @Override + public void handleData(ByteBuffer buf, Link link) { + if (verbose) + System.out.println("[" + this + "] INFO: Data received: " + buf + "."); + + // Parse PDU header + // Example: 07 00 -> CLIPRDR_HEADER::msgType = CB_CLIP_CAPS (7) + int msgType = buf.readUnsignedShortLE(); + + // Example: 00 00 -> CLIPRDR_HEADER::msgFlags = 0 + int msgFlags = buf.readUnsignedShortLE(); + + // Example: 10 00 00 00 -> CLIPRDR_HEADER::dataLen = 0x10 = 16 bytes + long dataLenLong = buf.readSignedIntLE(); + if (dataLenLong > 4 * 1024 * 1024) + throw new RuntimeException("Clipboard packet is too long. Expected length: less than 4MiB. Actual length: " + dataLenLong + "."); + int dataLen = (int)dataLenLong; + + ByteBuffer payload = buf.readBytes(dataLen); + + // Parse message flags and store them in the payload metadata + if ((msgFlags & CB_RESPONSE_OK) == CB_RESPONSE_OK) + payload.putMetadata("success", true); + if ((msgFlags & CB_RESPONSE_FAIL) == CB_RESPONSE_FAIL) + payload.putMetadata(SUCCESS, false); + if ((msgFlags & CB_ASCII_NAMES) == CB_ASCII_NAMES) + payload.putMetadata(ASCII_NAMES, true); + + // Push PDU to appropriate handler + switch (msgType) { + case CB_MONITOR_READY: + pushDataToPad("monitor_ready", payload); + break; + case CB_FORMAT_LIST: + pushDataToPad("format_list", payload); + break; + case CB_FORMAT_LIST_RESPONSE: + pushDataToPad("format_list_response", payload); + break; + case CB_FORMAT_DATA_REQUEST: + pushDataToPad("format_data_request", payload); + break; + case CB_FORMAT_DATA_RESPONSE: + pushDataToPad("format_data_response", payload); + break; + case CB_TEMP_DIRECTORY: + throw new RuntimeException("[" + this + "] ERROR: Unexpected clipboard temporary directory PDU received from server. Data: " + buf + "."); + case CB_CLIP_CAPS: + pushDataToPad("clipboard_capabilities", payload); + break; + case CB_FILECONTENTS_REQUEST: + pushDataToPad("filecontent_request", payload); + break; + case CB_FILECONTENTS_RESPONSE: + pushDataToPad("filecontent_response", payload); + break; + case CB_LOCK_CLIPDATA: + pushDataToPad("lock_clipdata", payload); + break; + case CB_UNLOCK_CLIPDATA: + pushDataToPad("unlock_clipdata", payload); + break; + default: + throw new RuntimeException("[" + this + "] ERROR: Unknown clipboard PDU message type: " + msgType + "."); + } + + buf.unref(); + + } + + /** + * Example. + */ + public static void main(String args[]) { + // TODO + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/clip/ServerClipboardCapabilitiesPDU.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/clip/ServerClipboardCapabilitiesPDU.java new file mode 100755 index 00000000000..68278e87d16 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/clip/ServerClipboardCapabilitiesPDU.java @@ -0,0 +1,180 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.clip; + +import streamer.BaseElement; +import streamer.ByteBuffer; +import streamer.Element; +import streamer.Link; +import streamer.Pipeline; +import streamer.PipelineImpl; +import streamer.debug.MockSink; +import streamer.debug.MockSource; + +public class ServerClipboardCapabilitiesPDU extends BaseElement { + + /** + * General capability set. + */ + public static final int CB_CAPSTYPE_GENERAL = 0x1; + + /** + * The Long Format Name variant of the Format List PDU is supported for + * exchanging updated format names. If this flag is not set, the Short Format + * Name variant MUST be used. If this flag is set by both protocol endpoints, + * then the Long Format Name variant MUST be used. + */ + public static final int CB_USE_LONG_FORMAT_NAMES = 0x00000002; + + /** + * File copy and paste using stream-based operations are supported using the + * File Contents Request PDU and File Contents Response PDU. + */ + public static final int CB_STREAM_FILECLIP_ENABLED = 0x00000004; + + /** + * Indicates that any description of files to copy and paste MUST NOT include + * the source path of the files. + */ + public static final int CB_FILECLIP_NO_FILE_PATHS = 0x00000008; + + /** + * Locking and unlocking of File Stream data on the clipboard is supported + * using the Lock Clipboard Data PDU and Unlock Clipboard Data PDU. + */ + public static final int CB_CAN_LOCK_CLIPDATA = 0x00000010; + + protected ClipboardState state; + + public ServerClipboardCapabilitiesPDU(String id, ClipboardState state) { + super(id); + this.state = state; + } + + @Override + public void handleData(ByteBuffer buf, Link link) { + if (verbose) + System.out.println("[" + this + "] INFO: Data received: " + buf + "."); + + // 0x01, 0x00, // CLIPRDR_CAPS::cCapabilitiesSets = 1 + int cCapabilitiesSets = buf.readUnsignedShortLE(); + + // 0x00, 0x00, // CLIPRDR_CAPS::pad1 + buf.skipBytes(2); + + // Parse all capability sets + for (int capabilitySet = 0; capabilitySet < cCapabilitiesSets; capabilitySet++) { + // 0x01, 0x00, // CLIPRDR_CAPS_SET::capabilitySetType = + // CB_CAPSTYPE_GENERAL (1) + int capabilitySetType = buf.readUnsignedShortLE(); + + // 0x0c, 0x00, // CLIPRDR_CAPS_SET::lengthCapability = 0x0c = 12 bytes + int lengthCapability = buf.readUnsignedShortLE(); + + // parse capability set + switch (capabilitySetType) { + case CB_CAPSTYPE_GENERAL: + parseGeneralCapabilitySet(buf.readBytes(lengthCapability - 4)); + break; + default: + // Ignore + // throw new RuntimeException("Unknown capability set type: " + + // capabilitySetType + ". Expected value: CB_CAPSTYPE_GENERAL (1)."); + } + } + + buf.unref(); + } + + protected void parseGeneralCapabilitySet(ByteBuffer buf) { + // 0x02, 0x00, 0x00, 0x00, // CLIPRDR_GENERAL_CAPABILITY::version = + // CB_CAPS_VERSION_2 (2) + // long version = buf.readUnsignedIntLE(); + buf.skipBytes(4); + + // 0x0e, 0x00, 0x00, 0x00, // CLIPRDR_GENERAL_CAPABILITY::capabilityFlags + // = 0x0000000e = 0x02 |0x04 |0x08 = CB_USE_LONG_FORMAT_NAMES | + // CB_STREAM_FILECLIP_ENABLED | CB_FILECLIP_NO_FILE_PATHS + int flags = buf.readSignedIntLE(); + + if ((flags & CB_USE_LONG_FORMAT_NAMES) == CB_USE_LONG_FORMAT_NAMES) { + state.serverUseLongFormatNames = true; + if (verbose) + System.out.println("[" + this + "] INFO: Server can use long format names for clipboard data."); + } + + if ((flags & CB_STREAM_FILECLIP_ENABLED) == CB_STREAM_FILECLIP_ENABLED) { + state.serverStreamFileClipEnabled = true; + if (verbose) + System.out.println("[" + this + "] INFO: Server supports stream based file clipboard operations."); + } + + if ((flags & CB_FILECLIP_NO_FILE_PATHS) == CB_FILECLIP_NO_FILE_PATHS) { + state.serverFileClipNoFilePaths = true; + if (verbose) + System.out.println("[" + this + + "] INFO: Server Indicates that any description of files to copy and paste MUST NOT include the source path of the files."); + } + + if ((flags & CB_CAN_LOCK_CLIPDATA) == CB_CAN_LOCK_CLIPDATA) { + state.serverCanLockClipdata = true; + if (verbose) + System.out.println("[" + this + "] INFO: Server can lock and unlock file streams on the clipboard."); + } + + } + + /** + * Example. + */ + public static void main(String[] args) { + // System.setProperty("streamer.Link.debug", "true"); + System.setProperty("streamer.Element.debug", "true"); + // System.setProperty("streamer.Pipeline.debug", "true"); + + /* @formatter:off */ + byte[] packet = new byte[] { + 0x07, 0x00, // CLIPRDR_HEADER::msgType = CB_CLIP_CAPS (7) + 0x00, 0x00, // CLIPRDR_HEADER::msgFlags = 0 + 0x10, 0x00, 0x00, 0x00, // CLIPRDR_HEADER::dataLen = 0x10 = 16 bytes + 0x01, 0x00, // CLIPRDR_CAPS::cCapabilitiesSets = 1 + 0x00, 0x00, // CLIPRDR_CAPS::pad1 + 0x01, 0x00, // CLIPRDR_CAPS_SET::capabilitySetType = CB_CAPSTYPE_GENERAL (1) + 0x0c, 0x00, // CLIPRDR_CAPS_SET::lengthCapability = 0x0c = 12 bytes + 0x02, 0x00, 0x00, 0x00, // CLIPRDR_GENERAL_CAPABILITY::version = CB_CAPS_VERSION_2 (2) + 0x0e, 0x00, 0x00, 0x00, // CLIPRDR_GENERAL_CAPABILITY::capabilityFlags = 0x0000000e = 0x02 |0x04 |0x08 = CB_USE_LONG_FORMAT_NAMES | CB_STREAM_FILECLIP_ENABLED | CB_FILECLIP_NO_FILE_PATHS + }; + /* @formatter:on */ + + MockSource source = new MockSource("source", ByteBuffer.convertByteArraysToByteBuffers(packet)); + Element router = new ServerClipRdrChannelRouter("router"); + ClipboardState state = new ClipboardState(); + Element clip_cap = new ServerClipboardCapabilitiesPDU("clip_cap", state); + Element sink = new MockSink("sink", new ByteBuffer[] {}); + + Pipeline pipeline = new PipelineImpl("test"); + pipeline.add(source, router, clip_cap, sink); + pipeline.link("source", "router >clipboard_capabilities", "clip_cap", "sink"); + pipeline.runMainLoop("source", STDOUT, false, false); + + // Check state + if (!state.serverUseLongFormatNames || !state.serverStreamFileClipEnabled || !state.serverFileClipNoFilePaths || state.serverCanLockClipdata) + throw new RuntimeException("Server clipboard capabilities packet parsed incorrectly."); + + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/clip/ServerFormatDataResponsePDU.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/clip/ServerFormatDataResponsePDU.java new file mode 100755 index 00000000000..99f9eda2d2b --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/clip/ServerFormatDataResponsePDU.java @@ -0,0 +1,97 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.clip; + +import streamer.BaseElement; +import streamer.ByteBuffer; +import streamer.Element; +import streamer.Link; +import streamer.Pipeline; +import streamer.PipelineImpl; +import streamer.debug.MockSink; +import streamer.debug.MockSource; +import common.adapter.AwtClipboardAdapter; + +public class ServerFormatDataResponsePDU extends BaseElement { + + public static final String SERVER_CLIPBOARD_ADAPTER_PAD = "clipboard"; + + protected ClipboardState state; + + public ServerFormatDataResponsePDU(String id, ClipboardState state) { + super(id); + this.state = state; + } + + @Override + public void handleData(ByteBuffer buf, Link link) { + if (verbose) + System.out.println("[" + this + "] INFO: Data received: " + buf + "."); + + parseData(buf); + + buf.unref(); + } + + protected void parseData(ByteBuffer buf) { + + String content = state.serverRequestedFormat.parseServerResponseAsString(buf); + + // Send response to clipboard adapter + ByteBuffer outBuf = new ByteBuffer(0); + outBuf.putMetadata(AwtClipboardAdapter.CLIPBOARD_CONTENT, content); + + pushDataToPad(SERVER_CLIPBOARD_ADAPTER_PAD, outBuf); + } + + /** + * Example. + */ + public static void main(String[] args) { + // System.setProperty("streamer.Link.debug", "true"); + System.setProperty("streamer.Element.debug", "true"); + // System.setProperty("streamer.Pipeline.debug", "true"); + + /* @formatter:off */ + byte[] packet = new byte[] { + 0x05, 0x00, // CLIPRDR_HEADER::msgType = CB_FORMAT_DATA_RESPONSE (5) + 0x01, 0x00, // CLIPRDR_HEADER::msgFlags = 0x0001 = CB_RESPONSE_OK + 0x18, 0x00, 0x00, 0x00, // CLIPRDR_HEADER::dataLen = 0x18 = 24 bytes + + 0x68, 0x00, 0x65, 0x00, 0x6c, 0x00, 0x6c, 0x00, 0x6f, 0x00, 0x20, 0x00, 0x77, 0x00, 0x6f, 0x00, + 0x72, 0x00, 0x6c, 0x00, 0x64, 0x00, 0x00, 0x00, // CLIPRDR_FORMAT_DATA_RESPONSE::requestedFormatData: "hello world" + }; + /* @formatter:on */ + + MockSource source = new MockSource("source", ByteBuffer.convertByteArraysToByteBuffers(packet)); + Element router = new ServerClipRdrChannelRouter("router"); + ClipboardState state = new ClipboardState(); + state.serverRequestedFormat = new ClipboardDataFormat(ClipboardDataFormat.CB_FORMAT_UNICODETEXT, ""); + Element format_data_response = new ServerFormatDataResponsePDU("format_data_response", state); + + ByteBuffer clipboardAdapterPacket = new ByteBuffer(0); + clipboardAdapterPacket.putMetadata(AwtClipboardAdapter.CLIPBOARD_CONTENT, "hello world"); + Element sink = new MockSink("sink", new ByteBuffer[] {clipboardAdapterPacket}); + + Pipeline pipeline = new PipelineImpl("test"); + pipeline.add(source, router, format_data_response, sink); + pipeline.link("source", "router >format_data_response", "format_data_response >clipboard", "sink"); + pipeline.runMainLoop("source", STDOUT, false, false); + + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/clip/ServerFormatListPDU.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/clip/ServerFormatListPDU.java new file mode 100755 index 00000000000..776f4516b52 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/clip/ServerFormatListPDU.java @@ -0,0 +1,237 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.clip; + +import java.util.HashMap; +import java.util.Map; + +import rdpclient.rdp.RdpConstants; +import streamer.BaseElement; +import streamer.ByteBuffer; +import streamer.Element; +import streamer.Link; +import streamer.Pipeline; +import streamer.PipelineImpl; +import streamer.debug.MockSink; +import streamer.debug.MockSource; + +public class ServerFormatListPDU extends BaseElement { + + protected ClipboardState state; + + public ServerFormatListPDU(String id, ClipboardState state) { + super(id); + this.state = state; + } + + @Override + public void handleData(ByteBuffer buf, Link link) { + if (verbose) + System.out.println("[" + this + "] INFO: Data received: " + buf + "."); + + parseFormatNames(buf); + buf.unref(); + + // Automatically send request for text-based data to insert it into local + // clipboard + ClipboardDataFormat textFormat = ClipboardDataFormat.findBestTextFormat(state.serverClipboardDataFormats); + if (textFormat != null) { + // Send response: OK + sendFormatListParseResponse(true); + // Request data + sendFormatDataRequest(textFormat); + } else { + // Send response: FAIL, we are not interested in this data + sendFormatListParseResponse(false); + } + } + + /** + * The Format Data Request PDU is sent by the recipient of the Format List + * PDU. It is used to request the data for one of the formats that was listed + * in the Format List PDU. + */ + protected void sendFormatDataRequest(ClipboardDataFormat textFormat) { + + if (verbose) + System.out.println("[" + this + "] INFO: Sending request for data in following format: " + textFormat + "."); + + // Store data format to parse server response later + state.serverRequestedFormat = textFormat; + + ByteBuffer buf = new ByteBuffer(12, true); + + // Type + buf.writeShortLE(ServerClipRdrChannelRouter.CB_FORMAT_DATA_REQUEST); + // Message flags + buf.writeShortLE(0); + // Length + buf.writeIntLE(4); + + // ID of chosen format + buf.writeIntLE(textFormat.id); + + buf.trimAtCursor(); + + pushDataToPad(STDOUT, buf); + } + + /** + * The Format List Response PDU is sent as a reply to the Format List PDU. It + * is used to indicate whether processing of the Format List PDU was + * successful. + * + * @param b + */ + protected void sendFormatListParseResponse(boolean ok) { + ByteBuffer buf = new ByteBuffer(8, true); + + // Type + buf.writeShortLE(ServerClipRdrChannelRouter.CB_FORMAT_LIST_RESPONSE); + // Message flags + buf.writeShortLE((ok) ? ServerClipRdrChannelRouter.CB_RESPONSE_OK : ServerClipRdrChannelRouter.CB_RESPONSE_FAIL); + // Length + buf.writeIntLE(0); + + buf.trimAtCursor(); + + pushDataToPad(STDOUT, buf); + } + + protected void parseFormatNames(ByteBuffer buf) { + + // Set will not be modified after creation, so there is no need to make it + // synchronous. + Map formats = new HashMap(); + + while (buf.cursor < buf.length) { + int id = buf.readSignedIntLE(); + + String name; + if (state.serverUseLongFormatNames) { + // Long format names in Unicode + name = buf.readVariableWideString(RdpConstants.CHARSET_16); + } else { + Boolean asciiNames = (Boolean)buf.getMetadata(ServerClipRdrChannelRouter.ASCII_NAMES); + + if (asciiNames != null && asciiNames) { + // Short format names in ASCII + name = buf.readString(32, RdpConstants.CHARSET_8); + } else { + // Short format names in Unicode + name = buf.readString(32, RdpConstants.CHARSET_16); + } + + } + + // Store format in map by both ID and name (if name is not empty) + formats.put(id, new ClipboardDataFormat(id, name)); + if (name.length() > 0) + formats.put(name, new ClipboardDataFormat(id, name)); + } + + if (verbose) + System.out.println("Server supports following formats for clipboard data: " + formats.values().toString() + "."); + + state.serverClipboardDataFormats = formats; + } + + /** + * Example. + */ + public static void main(String[] args) { + // System.setProperty("streamer.Link.debug", "true"); + System.setProperty("streamer.Element.debug", "true"); + // System.setProperty("streamer.Pipeline.debug", "true"); + + /* @formatter:off */ + byte[] packet = new byte[] { + 0x02, 0x00, // CLIPRDR_HEADER::msgType = CB_FORMAT_LIST (2) + 0x00, 0x00, // CLIPRDR_HEADER::msgFlags = 0 + (byte) 0xe0, 0x00, 0x00, 0x00, // CLIPRDR_HEADER::dataLen = 0xe0 = 224 bytes + + (byte) 0x8a, (byte) 0xc0, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatId = 0xc08a = 49290 + 0x52, 0x00, 0x69, 0x00, 0x63, 0x00, 0x68, 0x00, 0x20, 0x00, 0x54, 0x00, 0x65, 0x00, 0x78, 0x00, 0x74, 0x00, 0x20, 0x00, 0x46, 0x00, 0x6f, 0x00, 0x72, 0x00, 0x6d, 0x00, 0x61, 0x00, 0x74, 0x00, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatName = "Rich Text Format" + + 0x45, (byte) 0xc1, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatId = 0xc145 = 49477 + 0x52, 0x00, 0x69, 0x00, 0x63, 0x00, 0x68, 0x00, 0x20, 0x00, 0x54, 0x00, 0x65, 0x00, 0x78, 0x00, + 0x74, 0x00, 0x20, 0x00, 0x46, 0x00, 0x6f, 0x00, 0x72, 0x00, 0x6d, 0x00, 0x61, 0x00, 0x74, 0x00, + 0x20, 0x00, 0x57, 0x00, 0x69, 0x00, 0x74, 0x00, 0x68, 0x00, 0x6f, 0x00, 0x75, 0x00, 0x74, 0x00, + 0x20, 0x00, 0x4f, 0x00, 0x62, 0x00, 0x6a, 0x00, 0x65, 0x00, 0x63, 0x00, 0x74, 0x00, 0x73, 0x00, + 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatName = "Rich Text Format Without Objects" + + 0x43, (byte) 0xc1, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatId = 0xc143 = 49475 + 0x52, 0x00, 0x54, 0x00, 0x46, 0x00, 0x20, 0x00, 0x41, 0x00, 0x73, 0x00, 0x20, 0x00, 0x54, 0x00, + 0x65, 0x00, 0x78, 0x00, 0x74, 0x00, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatName = "RTF As Text" + + 0x01, 0x00, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatId = 1 + 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatName = "" + + 0x0d, 0x00, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatId = 0x0d = 13 + 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatName = "" + + 0x04, (byte) 0xc0, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatId = 0xc004 = 49156 + 0x4e, 0x00, 0x61, 0x00, 0x74, 0x00, 0x69, 0x00, 0x76, 0x00, 0x65, 0x00, 0x00, 0x00, // "Native" + + 0x0e, (byte) 0xc0, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatId = 0xc00e = 49166 + 0x4f, 0x00, 0x62, 0x00, 0x6a, 0x00, 0x65, 0x00, 0x63, 0x00, 0x74, 0x00, 0x20, 0x00, 0x44, 0x00, + 0x65, 0x00, 0x73, 0x00, 0x63, 0x00, 0x72, 0x00, 0x69, 0x00, 0x70, 0x00, 0x74, 0x00, 0x6f, 0x00, + 0x72, 0x00, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatName = "Object Descriptor" + + 0x03, 0x00, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatId = 3 + 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatName = "" + + 0x10, 0x00, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatId = 16 + 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatName = "" + + 0x07, 0x00, 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatId = 7 + 0x00, 0x00, // CLIPRDR_LONG_FORMAT_NAME::formatName = "" + }; + /* @formatter:on */ + + MockSource source = new MockSource("source", ByteBuffer.convertByteArraysToByteBuffers(packet)); + Element router = new ServerClipRdrChannelRouter("router"); + ClipboardState state = new ClipboardState(); + state.serverUseLongFormatNames = true; + Element format_list = new ServerFormatListPDU("format_list", state); + + Element sink = new MockSink("sink", ByteBuffer.convertByteArraysToByteBuffers(new byte[] { + // Format List Response PDU + 0x03, 0x00, // CLIPRDR_HEADER::msgType = CB_FORMAT_LIST_RESPONSE (3) + 0x01, 0x00, // CLIPRDR_HEADER::msgFlags = 0x0001 = CB_RESPONSE_OK + 0x00, 0x00, 0x00, 0x00, // CLIPRDR_HEADER::dataLen = 0 bytes + }, new byte[] { + // Format Data Request PDU + 0x04, 0x00, // CLIPRDR_HEADER::msgType = CB_FORMAT_DATA_REQUEST (4) + 0x00, 0x00, // CLIPRDR_HEADER::msgFlags = 0 + 0x04, 0x00, 0x00, 0x00, // CLIPRDR_HEADER::dataLen = 4 bytes + 0x0d, 0x00, 0x00, 0x00, // CLIPRDR_FORMAT_DATA_REQUEST::requestedFormatId + // = 0x0d + })); + + Pipeline pipeline = new PipelineImpl("test"); + pipeline.add(source, router, format_list, sink); + pipeline.link("source", "router >format_list", "format_list", "sink"); + pipeline.runMainLoop("source", STDOUT, false, false); + + // Check state + if (!(state.serverClipboardDataFormats.containsKey(49475) && state.serverClipboardDataFormats.containsKey("Rich Text Format"))) + throw new RuntimeException("Server format list packet parsed incorrectly."); + + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/clip/ServerMonitorReadyPDU.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/clip/ServerMonitorReadyPDU.java new file mode 100755 index 00000000000..bbc356e1432 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/clip/ServerMonitorReadyPDU.java @@ -0,0 +1,85 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.clip; + +import streamer.BaseElement; +import streamer.ByteBuffer; +import streamer.Element; +import streamer.Link; +import streamer.Pipeline; +import streamer.PipelineImpl; +import streamer.debug.MockSink; +import streamer.debug.MockSource; + +public class ServerMonitorReadyPDU extends BaseElement { + + protected ClipboardState state; + + public ServerMonitorReadyPDU(String id, ClipboardState state) { + super(id); + this.state = state; + } + + // 0x01, 0x00, // CLIPRDR_HEADER::msgType = CB_MONITOR_READY (1) + // 0x00, 0x00, // CLIPRDR_HEADER::msgFlags = 0 + // 0x00, 0x00, 0x00, 0x00, // CLIPRDR_HEADER::dataLen = 0 bytes + + @Override + public void handleData(ByteBuffer buf, Link link) { + if (verbose) + System.out.println("[" + this + "] INFO: Data received: " + buf + "."); + + state.serverReady = true; + + buf.unref(); + + } + + /** + * Example. + */ + public static void main(String[] args) { + // System.setProperty("streamer.Link.debug", "true"); + System.setProperty("streamer.Element.debug", "true"); + // System.setProperty("streamer.Pipeline.debug", "true"); + + /* @formatter:off */ + byte[] packet = new byte[] { + 0x01, 0x00, // CLIPRDR_HEADER::msgType = CB_MONITOR_READY (1) + 0x00, 0x00, // CLIPRDR_HEADER::msgFlags = 0 + 0x00, 0x00, 0x00, 0x00, // CLIPRDR_HEADER::dataLen = 0 bytes + }; + /* @formatter:on */ + + MockSource source = new MockSource("source", ByteBuffer.convertByteArraysToByteBuffers(packet)); + Element router = new ServerClipRdrChannelRouter("router"); + ClipboardState state = new ClipboardState(); + Element monitor_ready = new ServerMonitorReadyPDU("monitor_ready", state); + Element sink = new MockSink("sink", new ByteBuffer[] {}); + + Pipeline pipeline = new PipelineImpl("test"); + pipeline.add(source, router, monitor_ready, sink); + pipeline.link("source", "router >monitor_ready", "monitor_ready", "sink"); + pipeline.runMainLoop("source", STDOUT, false, false); + + // Check state + if (!state.serverReady) + throw new RuntimeException("Server monitor ready packet parsed incorrectly."); + + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/debug/ClientPacketSniffer.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/debug/ClientPacketSniffer.java new file mode 100755 index 00000000000..203fde415c2 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/debug/ClientPacketSniffer.java @@ -0,0 +1,51 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.debug; + +/** + * Try to determine packet content by it header fingerprint. + */ +public class ClientPacketSniffer extends PacketSniffer { + + private static final Pair[] clientRegexps = new Pair[] { +// @formatter:off + new Pair("Client FastPath input", "04"), + new Pair("Client X224ConnectionRequest", "03 00 XX XX 27 E0"), + new Pair("Client ConnectionRequest", "03 00 XX XX XX E0"), + new Pair("Client MCConnectInitial", "03 00 XX XX 02 F0 80 7F 65"), + new Pair("Client ErectDomainRequest", "03 00 XX XX 02 F0 80 04"), + new Pair("Client AttachUserRequest", "03 00 XX XX 02 F0 80 28"), + new Pair("Client ChannelJoinRequest", "03 00 XX XX 02 F0 80 38"), + new Pair("Client Info", "03 00 XX XX 02 F0 80 64 00 03 03 EB 70 XX XX XX XX 00 00"), + new Pair("Client ConfirmActivePDU", "03 00 XX XX 02 F0 80 64 00 03 03 EB 70 XX XX XX XX 13 00"), + new Pair("Client SynchronizePDU", "03 00 XX XX 02 F0 80 64 00 03 03 EB 70 XX XX XX XX 17 00 EC 03 EA 03 XX 00 XX XX XX XX 1F"), + new Pair("Client ControlPDU", "03 00 XX XX 02 F0 80 64 00 03 03 EB 70 XX XX XX XX 17 00 EC 03 EA 03 XX 00 XX XX XX XX 14"), + new Pair("Client FontListPDU", "03 00 XX XX 02 F0 80 64 00 03 03 EB 70 XX XX XX XX 17 00 EC 03 EA 03 XX 00 XX XX XX XX 27"), + new Pair("Client BitmapCachePersistentList","03 00 XX XX 02 F0 80 64 00 03 03 EB 70 XX XX XX XX 17 00 EC 03 EA 03 XX XX XX XX XX XX 2b"), + new Pair("Client CredSSP", "30"), + new Pair("Client HyperV PreConnection Blob","5E"), + new Pair("Client a TPKT packet", "03"), + new Pair("Client a Fast Path packet", "00"), + // @formatter:on + + }; + + public ClientPacketSniffer(String id) { + super(id, clientRegexps); + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/PacketSniffer.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/debug/PacketSniffer.java old mode 100644 new mode 100755 similarity index 98% rename from services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/PacketSniffer.java rename to services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/debug/PacketSniffer.java index 12fa8e33720..efbe6890902 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/PacketSniffer.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/debug/PacketSniffer.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package rdpclient; +package rdpclient.debug; import java.util.regex.Pattern; diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/debug/ServerPacketSniffer.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/debug/ServerPacketSniffer.java new file mode 100755 index 00000000000..a4ead0c5d1b --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/debug/ServerPacketSniffer.java @@ -0,0 +1,49 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.debug; + +/** + * Try to determine packet content by it header fingerprint. + */ +public class ServerPacketSniffer extends PacketSniffer { + + private static final Pair[] serverRegexps = new Pair[] { +// @formatter:off + new Pair("Server FastPath update", "04"), + new Pair("Server X224ConnectionRequest", "03 00 XX XX 0E D0"), + new Pair("Server MCSConnectResponse", "03 00 XX XX 02 F0 80 7F 66 5A"), + new Pair("Server AttachUserConfirm", "03 00 XX XX 02 F0 80 2E"), + new Pair("Server ChannelJoinConfirm", "03 00 XX XX 02 F0 80 3E"), + new Pair("Server ErrorAlert", "03 00 XX XX 02 F0 80 68 00 01 03 EB 70 14 80 00"), + new Pair("Server DemandActivePDU", "03 00 XX XX 02 F0 80 68 00 01 03 EB 70 XX XX XX XX 11"), + new Pair("Server ControlPDU", "03 00 XX XX 02 F0 80 68 00 01 03 EB 70 XX XX XX 17 00 EA 03 EA 03 XX 00 XX XX XX XX 14"), + new Pair("Server SynchronizePDU", "03 00 XX XX 02 F0 80 68 00 01 03 EB 70 XX XX XX 17 00 EA 03 EA 03 XX 00 XX XX XX XX 1F"), + new Pair("Server FontMapPDU", "03 00 XX XX 02 F0 80 68 00 01 03 EB 70 XX XX XX 17 00 EA 03 EA 03 XX 00 XX XX XX XX 28"), + new Pair("Server SET_ERROR_INFO_PDU", "03 00 XX XX 02 F0 80 68 00 01 03 EB 30 XX XX XX 17 00 00 00 EA 03 XX 00 XX XX XX XX 2F"), + new Pair("Server DeactivateAllPDU", "03 00 XX XX 02 F0 80 68 00 01 03 EB 70 XX XX XX 16 00"), + new Pair("Server CloseConnection", "03 00 00 09 02 F0 80 21 80"), + new Pair("Server CredSSP", "30"), + + new Pair("Server a TPKT packet", "03"), + new Pair("Server a FastPath packet", "00"), + // @formatter:on + }; + + public ServerPacketSniffer(String id) { + super(id, serverRegexps); + } +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/hyperv/ClientPreConnectionBlob.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/hyperv/ClientPreConnectionBlob.java new file mode 100755 index 00000000000..05af4c0937d --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/hyperv/ClientPreConnectionBlob.java @@ -0,0 +1,121 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.hyperv; + +import rdpclient.rdp.RdpConstants; +import streamer.ByteBuffer; +import streamer.Element; +import streamer.Link; +import streamer.OneTimeSwitch; +import streamer.Pipeline; +import streamer.PipelineImpl; +import streamer.debug.MockSink; +import streamer.debug.MockSource; + +/** + * For HyperV server, client must send VM ID before any other packet. + */ +public class ClientPreConnectionBlob extends OneTimeSwitch { + + protected String data; + + public ClientPreConnectionBlob(String id, String data) { + super(id); + this.data = data; + } + + @Override + protected void handleOneTimeData(ByteBuffer buf, Link link) { + if (buf == null) + return; + + throw new RuntimeException("This element only sends data. This method must not be called. Unexpected packet: " + buf + "."); + } + + @Override + protected void onStart() { + super.onStart(); + sendPreConnectionBlobData(data); + } + + protected void sendPreConnectionBlobData(String data) { + // Length of packet + ByteBuffer buf = new ByteBuffer(1024, true); + + // Header + buf.writeBytes(new byte[] {(byte)0x5e, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x02, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00,}); + + // Length of string in wide characters + two wide \0 (LE) + buf.writeShortLE(data.length() + 2); + + // Wide string + two wide '\0' characters + buf.writeString(data + "\0\0", RdpConstants.CHARSET_16); + + // Trim buffer to actual length of data written + buf.trimAtCursor(); + + pushDataToOTOut(buf); + + switchOff(); + } + + /** + * Example. + */ + public static void main(String[] args) { + // System.setProperty("streamer.Link.debug", "true"); + System.setProperty("streamer.Element.debug", "true"); + // System.setProperty("streamer.Pipeline.debug", "true"); + + /* @formatter:off */ + byte[] packet = new byte[] { + // Header + (byte) 0x5e, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + + // Length of string in wide characters + two wide \0 (LE) + (byte) 0x26, (byte) 0x00, + + // Wide string + (byte) 0x33, (byte) 0x00, (byte) 0x39, (byte) 0x00, (byte) 0x34, (byte) 0x00, (byte) 0x31, (byte) 0x00, (byte) 0x38, (byte) 0x00, (byte) 0x46, + (byte) 0x00, (byte) 0x39, (byte) 0x00, (byte) 0x30, (byte) 0x00, (byte) 0x2d, (byte) 0x00, (byte) 0x36, (byte) 0x00, (byte) 0x44, (byte) 0x00, + (byte) 0x30, (byte) 0x00, (byte) 0x33, (byte) 0x00, (byte) 0x2d, (byte) 0x00, (byte) 0x34, (byte) 0x00, (byte) 0x36, (byte) 0x00, (byte) 0x38, + (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x2d, (byte) 0x00, (byte) 0x42, (byte) 0x00, (byte) 0x37, (byte) 0x00, (byte) 0x39, (byte) 0x00, + (byte) 0x36, (byte) 0x00, (byte) 0x2d, (byte) 0x00, (byte) 0x39, (byte) 0x00, (byte) 0x31, (byte) 0x00, (byte) 0x43, (byte) 0x00, (byte) 0x36, + (byte) 0x00, (byte) 0x30, (byte) 0x00, (byte) 0x44, (byte) 0x00, (byte) 0x44, (byte) 0x00, (byte) 0x36, (byte) 0x00, (byte) 0x36, (byte) 0x00, + (byte) 0x35, (byte) 0x00, (byte) 0x33, (byte) 0x00, (byte) 0x41, (byte) 0x00, + + // Two wide \0 + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + }; + /* @formatter:on */ + + MockSource source = new MockSource("source", ByteBuffer.convertByteArraysToByteBuffers(new byte[] {1, 2, 3})); + Element pcb = new ClientPreConnectionBlob("pcb", "39418F90-6D03-468E-B796-91C60DD6653A"); + Element sink = new MockSink("sink", ByteBuffer.convertByteArraysToByteBuffers(packet)); + Element mainSink = new MockSink("mainSink", ByteBuffer.convertByteArraysToByteBuffers(new byte[] {1, 2, 3})); + + Pipeline pipeline = new PipelineImpl("test"); + pipeline.add(source, pcb, sink, mainSink); + pipeline.link("source", "pcb", "mainSink"); + pipeline.link("pcb >" + OTOUT, "sink"); + pipeline.runMainLoop("source", STDOUT, false, false); + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/ClientNtlmsspNegotiate.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/ClientNtlmsspNegotiate.java new file mode 100755 index 00000000000..8bac4abfe52 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/ClientNtlmsspNegotiate.java @@ -0,0 +1,177 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.ntlmssp; + +import rdpclient.ntlmssp.asn1.NegoItem; +import rdpclient.ntlmssp.asn1.TSRequest; +import rdpclient.rdp.RdpConstants; +import streamer.ByteBuffer; +import streamer.Element; +import streamer.Link; +import streamer.OneTimeSwitch; +import streamer.Pipeline; +import streamer.PipelineImpl; +import streamer.debug.MockSink; +import streamer.debug.MockSource; +import common.asn1.Tag; + +/** + * @see http://msdn.microsoft.com/en-us/library/cc236641.aspx + */ +public class ClientNtlmsspNegotiate extends OneTimeSwitch { + + /** + * The set of client configuration flags (section 2.2.2.5) that specify the + * full set of capabilities of the client. + */ + public NegoFlags clientConfigFlags = new NegoFlags().set_NEGOTIATE_56().set_NEGOTIATE_KEY_EXCH().set_NEGOTIATE_128().set_NEGOTIATE_VERSION() + .set_NEGOTIATE_EXTENDED_SESSION_SECURITY().set_NEGOTIATE_ALWAYS_SIGN().set_NEGOTIATE_NTLM().set_NEGOTIATE_LM_KEY().set_NEGOTIATE_SEAL() + .set_NEGOTIATE_SIGN().set_REQUEST_TARGET().set_NEGOTIATE_OEM().set_NEGOTIATE_UNICODE(); + + protected NtlmState ntlmState; + + public ClientNtlmsspNegotiate(String id, NtlmState state) { + super(id); + ntlmState = state; + } + + @Override + protected void handleOneTimeData(ByteBuffer buf, Link link) { + if (buf == null) + return; + + throw new RuntimeException("Unexpected packet: " + buf + "."); + } + + @Override + protected void onStart() { + super.onStart(); + + ByteBuffer negoToken = generateNegotiateMessage(); + ntlmState.negotiateMessage = negoToken.toByteArray(); // Store message for MIC calculation in AUTH message + + // Length of packet + ByteBuffer buf = new ByteBuffer(1024, true); + + TSRequest tsRequest = new TSRequest("TSRequest"); + tsRequest.version.value = 2L; + NegoItem negoItem = new NegoItem("NegoItem"); + negoItem.negoToken.value = negoToken; + tsRequest.negoTokens.tags = new Tag[] {negoItem}; + + tsRequest.writeTag(buf); + + // Trim buffer to actual length of data written + buf.trimAtCursor(); + + pushDataToOTOut(buf); + + switchOff(); + } + + private ByteBuffer generateNegotiateMessage() { + ByteBuffer buf = new ByteBuffer(1024); + + // Signature + buf.writeString("NTLMSSP", RdpConstants.CHARSET_8); + buf.writeByte(0); + + // Message type + buf.writeIntLE(NtlmConstants.NEGOTIATE); + + buf.writeIntLE(clientConfigFlags.value); // Flags + + // If the NTLMSSP_NEGOTIATE_VERSION flag is set by the client application, + // the Version field MUST be set to the current version (section 2.2.2.10), + // the DomainName field MUST be set to a zero-length string, and the + // Workstation field MUST be set to a zero-length string. + + // Domain: "" + buf.writeShortLE(0); // Length + buf.writeShortLE(0); // Allocated space + buf.writeIntLE(0); // Offset + + // Workstation: "" + buf.writeShortLE(0); // Length + buf.writeShortLE(0); // Allocated space + buf.writeIntLE(0); // Offset + + // OS Version: 6.1 (Build 7601); NTLM Current Revision 15 + buf.writeBytes(new byte[] {(byte)0x06, (byte)0x01, (byte)0xb1, (byte)0x1d, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x0f}); + + // Trim buffer to actual length of data written + buf.trimAtCursor(); + + return buf; + } + + /** + * Example. + */ + public static void main(String args[]) { + // System.setProperty("streamer.Link.debug", "true"); + System.setProperty("streamer.Element.debug", "true"); + // System.setProperty("streamer.Pipeline.debug", "true"); + + /* @formatter:off */ + byte[] packet = new byte[] { + // CredSSP BER header: + + (byte)0x30, // Sequence + (byte)0x37, // Length, 55 bytes + + (byte)0xa0, (byte)0x03, // TAG: [0] (constructed) LEN: 3 byte + (byte)0x02, (byte)0x01, (byte)0x02, // Version: (int, 1 byte, 0x02) + + // Sequence of sequence + (byte)0xa1, (byte)0x30, // TAG: [1] (constructed) LEN: 48 bytes + (byte)0x30, (byte)0x2e, // TAG: [UNIVERSAL 16] (constructed) "SEQUENCE" LEN: 46 bytes + (byte)0x30, (byte)0x2c, // TAG: [UNIVERSAL 16] (constructed) "SEQUENCE" LEN: 44 bytes + (byte)0xa0, (byte)0x2a, // TAG: [0] (constructed) LEN: 42 bytes + + + (byte)0x04, (byte)0x28, // TAG: [UNIVERSAL 4] (primitive) "OCTET STRING" LEN: 40 bytes + + // NTLM negotiate request + + (byte)0x4e, (byte)0x54, (byte)0x4c, (byte)0x4d, (byte)0x53, (byte)0x53, (byte)0x50, (byte)0x00, // "NTLMSSP\0" + + (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, // Message type: NEGOTIATE (0x1, LE) + + (byte)0xb7, (byte)0x82, (byte)0x08, (byte)0xe2, // Flags: 0xe20882b7 (LE) + + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Domain (security buffer, 8bit, 8 bytes): length: 0x0000 (LE), allocated space: 0x0000 (LE), offset: 0x00000000 (LE) + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Workstation (security buffer, 8bit, 8 bytes): length: 0x0000 (LE), allocated space: 0x0000 (LE), offset: 0x00000000 (LE) + (byte)0x06, (byte)0x01, (byte)0xb1, (byte)0x1d, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x0f, // OS Version: 6.1 (Build 7601); NTLM Current Revision 15, 8 bytes + + }; + /* @formatter:on */ + + NtlmState state = new NtlmState(); + + MockSource source = new MockSource("source", ByteBuffer.convertByteArraysToByteBuffers(new byte[] {1, 2, 3})); + Element ntlmssp_negotiate = new ClientNtlmsspNegotiate("ntlmssp_negotiate", state); + Element sink = new MockSink("sink", ByteBuffer.convertByteArraysToByteBuffers(packet)); + Element mainSink = new MockSink("mainSink", ByteBuffer.convertByteArraysToByteBuffers(new byte[] {1, 2, 3})); + + Pipeline pipeline = new PipelineImpl("test"); + pipeline.add(source, ntlmssp_negotiate, sink, mainSink); + pipeline.link("source", "ntlmssp_negotiate", "mainSink"); + pipeline.link("ntlmssp_negotiate >" + OTOUT, "sink"); + pipeline.runMainLoop("source", STDOUT, false, false); + } +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/ClientNtlmsspPubKeyAuth.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/ClientNtlmsspPubKeyAuth.java new file mode 100755 index 00000000000..ffd16304df0 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/ClientNtlmsspPubKeyAuth.java @@ -0,0 +1,680 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.ntlmssp; + +import java.nio.charset.Charset; + +import rdpclient.ntlmssp.asn1.NegoItem; +import rdpclient.ntlmssp.asn1.SubjectPublicKeyInfo; +import rdpclient.ntlmssp.asn1.TSRequest; +import rdpclient.rdp.RdpConstants; +import streamer.ByteBuffer; +import streamer.Element; +import streamer.Link; +import streamer.OneTimeSwitch; +import streamer.Pipeline; +import streamer.PipelineImpl; +import streamer.debug.Dumper; +import streamer.debug.MockSink; +import streamer.debug.MockSource; +import streamer.ssl.SSLState; +import common.asn1.Tag; + +/** + * @see http://msdn.microsoft.com/en-us/library/cc236643.aspx + */ +public class ClientNtlmsspPubKeyAuth extends OneTimeSwitch implements NtlmConstants, Dumper { + + /** + * Offset of first byte of allocated block after NTLMSSP header and block + * descriptors. + */ + private static final int BLOCKS_OFFSET = 88; + + protected NtlmState ntlmState; + protected SSLState sslState; + + protected String targetDomain; + protected String user; + protected String password; + protected String workstation; + protected String serverHostName; + + public ClientNtlmsspPubKeyAuth(String id, NtlmState ntlmState, SSLState sslState, String serverHostName, String targetDomain, String workstation, + String user, String password) { + super(id); + this.ntlmState = ntlmState; + this.sslState = sslState; + this.serverHostName = serverHostName; + this.targetDomain = targetDomain; + this.workstation = workstation; + this.user = user; + this.password = password; + } + + @Override + protected void handleOneTimeData(ByteBuffer buf, Link link) { + if (buf == null) + return; + + throw new RuntimeException("Unexpected packet: " + buf + "."); + } + + @Override + protected void onStart() { + super.onStart(); + + /* + * @see + * http://blogs.msdn.com/b/openspecification/archive/2010/04/20/ntlm-keys + * -and-sundry-stuff.aspx + */ + ntlmState.domain = targetDomain; + ntlmState.user = user; + ntlmState.password = password; + ntlmState.workstation = workstation; + ntlmState.generateServicePrincipalName(serverHostName); + ntlmState.ntlm_construct_authenticate_target_info(); + ntlmState.ntlm_generate_timestamp(); + ntlmState.ntlm_generate_client_challenge(); + ntlmState.ntlm_compute_lm_v2_response(); + ntlmState.ntlm_compute_ntlm_v2_response(); + ntlmState.ntlm_generate_key_exchange_key(); + ntlmState.ntlm_generate_random_session_key(); + ntlmState.ntlm_generate_exported_session_key(); + ntlmState.ntlm_encrypt_random_session_key(); + ntlmState.ntlm_init_rc4_seal_states(); + + ByteBuffer authenticateMessage = generateAuthenticateMessage(ntlmState); + ByteBuffer messageSignatureAndEncryptedServerPublicKey = generateMessageSignatureAndEncryptedServerPublicKey(ntlmState); + + // Length of packet + ByteBuffer buf = new ByteBuffer(4096, true); + + TSRequest tsRequest = new TSRequest("TSRequest"); + tsRequest.version.value = 2L; + NegoItem negoItem = new NegoItem("NegoItem"); + negoItem.negoToken.value = authenticateMessage; + + tsRequest.negoTokens.tags = new Tag[] {negoItem}; + + tsRequest.pubKeyAuth.value = messageSignatureAndEncryptedServerPublicKey; + + tsRequest.writeTag(buf); + + // Trim buffer to actual length of data written + buf.trimAtCursor(); + + pushDataToOTOut(buf); + + switchOff(); + } + + private byte[] getServerPublicKey() { + // SSL certificate public key with algorithm + ByteBuffer subjectPublicKeyInfo = new ByteBuffer(sslState.serverCertificateSubjectPublicKeyInfo); + + // Parse subjectPublicKeyInfo + SubjectPublicKeyInfo parser = new SubjectPublicKeyInfo("SubjectPublicKeyInfo"); + parser.readTag(subjectPublicKeyInfo); + + // Copy subjectPublicKey subfield to separate byte buffer + ByteBuffer subjectPublicKey = new ByteBuffer(subjectPublicKeyInfo.length); + parser.subjectPublicKey.writeTag(subjectPublicKey); + + subjectPublicKeyInfo.unref(); + subjectPublicKey.trimAtCursor(); + + // Skip tag: + // 03 82 01 0f (tag) 00 (padding byte) + subjectPublicKey.trimHeader(5);// FIXME: parse it properly + // * DEBUG */System.out.println("DEBUG: subjectPublicKey:\n" + + // subjectPublicKey.dump()); + + ntlmState.subjectPublicKey = subjectPublicKey.toByteArray(); + + return ntlmState.subjectPublicKey; + } + + /** + * The client encrypts the public key it received from the server (contained + * in the X.509 certificate) in the TLS handshake from step 1, by using the + * confidentiality support of SPNEGO. + * + * The public key that is encrypted is the ASN.1-encoded SubjectPublicKey + * sub-field of SubjectPublicKeyInfo from the X.509 certificate, as specified + * in [RFC3280] section 4.1. The encrypted key is encapsulated in the + * pubKeyAuth field of the TSRequest structure and is sent over the TLS + * channel to the server. + */ + private ByteBuffer generateMessageSignatureAndEncryptedServerPublicKey(NtlmState ntlmState) { + return new ByteBuffer(ntlmState.ntlm_EncryptMessage(getServerPublicKey())); + } + + public static ByteBuffer generateAuthenticateMessage(NtlmState ntlmState) { + + // Allocate memory for blocks from given fixed offset + int blocksCursor = BLOCKS_OFFSET; + + ByteBuffer buf = new ByteBuffer(4096); + + // Signature: "NTLMSSP\0" + buf.writeString(NTLMSSP, RdpConstants.CHARSET_8); + buf.writeByte(0); + + // NTLM Message Type: NTLMSSP_AUTH (0x00000003) + buf.writeIntLE(NtlmConstants.NTLMSSP_AUTH); + + // Although the protocol allows authentication to succeed if the client + // provides either LmChallengeResponse or NtChallengeResponse, Windows + // implementations provide both. + + // LM V2 response + blocksCursor = writeBlock(buf, ntlmState.lmChallengeResponse, blocksCursor); + + // NT v2 response + blocksCursor = writeBlock(buf, ntlmState.ntChallengeResponse, blocksCursor); + + // DomainName + blocksCursor = writeStringBlock(buf, ntlmState.domain, blocksCursor, RdpConstants.CHARSET_16); + + // UserName + blocksCursor = writeStringBlock(buf, ntlmState.user, blocksCursor, RdpConstants.CHARSET_16); + + // Workstation + blocksCursor = writeStringBlock(buf, ntlmState.workstation, blocksCursor, RdpConstants.CHARSET_16); + + // EncryptedRandomSessionKey, 16 bytes + blocksCursor = writeBlock(buf, ntlmState.encryptedRandomSessionKey, blocksCursor); + + // NegotiateFlags (4 bytes): In connection-oriented mode, a NEGOTIATE + // structure that contains the set of bit flags (section 2.2.2.5) negotiated + // in the previous messages. + buf.writeIntLE(/*ntlmState.negotiatedFlags.value*/0xe288b235); // FIXME: remove hardcoded value + + buf.writeBytes(generateVersion()); + + // If the CHALLENGE_MESSAGE TargetInfo field (section 2.2.1.2) has an + // MsvAvTimestamp present, the client SHOULD provide a MIC(Message Integrity + // Check) + + int savedCursorForMIC = buf.cursor; // Save cursor position to write MIC + // later + buf.writeBytes(new byte[16]); // Write 16 zeroes + + if (BLOCKS_OFFSET != buf.cursor) + throw new RuntimeException("BUG: Actual offset of first byte of allocated blocks is not equal hardcoded offset. Hardcoded offset: " + BLOCKS_OFFSET + + ", actual offset: " + buf.cursor + ". Update hardcoded offset to match actual offset."); + + buf.cursor = blocksCursor; + buf.trimAtCursor(); + + ntlmState.authenticateMessage = buf.toByteArray(); + + // Calculate and write MIC to reserved position + ntlmState.ntlm_compute_message_integrity_check(); + buf.cursor = savedCursorForMIC; + buf.writeBytes(ntlmState.messageIntegrityCheck); + buf.rewindCursor(); + + return buf; + } + + /** + * Write string as security buffer, using given charset, without trailing '\0' + * character. + */ + private static int writeStringBlock(ByteBuffer buf, String string, int blocksCursor, Charset charset) { + return writeBlock(buf, string.getBytes(charset), blocksCursor); + } + + /** + * Write block to blocks buffer and block descriptor to main buffer. + */ + private static int writeBlock(ByteBuffer buf, byte[] block, int blocksCursor) { + + // Write block descriptor + + // Length + buf.writeShortLE(block.length); + // Allocated + buf.writeShortLE(block.length); + // Offset + buf.writeIntLE(blocksCursor); + + // Write block to position pointed by blocksCursor instead of buf.cursor + int savedCursor = buf.cursor; + buf.cursor = blocksCursor; + buf.writeBytes(block); + blocksCursor = buf.cursor; + buf.cursor = savedCursor; + + return blocksCursor; + } + + /** + * Version (8 bytes): A VERSION structure (section 2.2.2.10) that is present + * only when the NTLMSSP_NEGOTIATE_VERSION flag is set in the NegotiateFlags + * field. This structure is used for debugging purposes only. In normal + * protocol messages, it is ignored and does not affect the NTLM message + * processing. + */ + private static byte[] generateVersion() { + // Version (6.1, Build 7601), NTLM current revision: 15 + return new byte[] {0x06, 0x01, (byte)0xb1, 0x1d, 0x00, 0x00, 0x00, 0x0f}; + } + + /** + * Example. + */ + public static void main(String args[]) { + System.setProperty("streamer.Element.debug", "true"); + + /* @formatter:off */ + // + // Client NEGOTIATE + // + byte[] clientNegotiatePacket = new byte[] { + (byte)0x30, (byte)0x37, (byte)0xa0, (byte)0x03, (byte)0x02, (byte)0x01, (byte)0x02, (byte)0xa1, (byte)0x30, (byte)0x30, (byte)0x2e, (byte)0x30, (byte)0x2c, (byte)0xa0, (byte)0x2a, (byte)0x04, + (byte)0x28, (byte)0x4e, (byte)0x54, (byte)0x4c, (byte)0x4d, (byte)0x53, (byte)0x53, (byte)0x50, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xb7, (byte)0x82, (byte)0x08, + (byte)0xe2, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x06, (byte)0x01, (byte)0xb1, (byte)0x1d, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x0f, + }; + +// +// Server CHALLENGE +// + byte[] serverChallengePacket = new byte[] { + 0x30, (byte) 0x82, 0x01, 0x02, // TAG: [UNIVERSAL 16] (constructed) "SEQUENCE" LEN: 258 bytes + + (byte) 0xa0, 0x03, // TAG: [0] (constructed) LEN: 3 bytes + 0x02, 0x01, 0x03, // TAG: [UNIVERSAL 2] (primitive) "INTEGER" LEN: 1 bytes, Version: 0x3 + (byte) 0xa1, (byte) 0x81, (byte) 0xfa, // TAG: [1] (constructed) LEN: 250 bytes + 0x30, (byte) 0x81, (byte) 0xf7, // TAG: [UNIVERSAL 16] (constructed) "SEQUENCE" LEN: 247 bytes + 0x30, (byte) 0x81, (byte) 0xf4, // TAG: [UNIVERSAL 16] (constructed) "SEQUENCE" LEN: 244 bytes + (byte) 0xa0, (byte) 0x81, (byte) 0xf1, // TAG: [0] (constructed) LEN: 241 bytes + 0x04, (byte) 0x81, (byte) 0xee, // TAG: [UNIVERSAL 4] (primitive) "OCTET STRING" LEN: 238 bytes + + 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00, // "NTLMSSP\0" + + 0x02, 0x00, 0x00, 0x00, // MessageType (CHALLENGE) + + 0x1e, 0x00, 0x1e, 0x00, 0x38, 0x00, 0x00, 0x00, // TargetName (length: 30, allocated space: 30, offset: 56) + 0x35, (byte) 0x82, (byte) 0x8a, (byte) 0xe2, // NegotiateFlags: NEGOTIATE_56 NEGOTIATE_KEY_EXCH NEGOTIATE_128 NEGOTIATE_VERSION NEGOTIATE_TARGET_INFO NEGOTIATE_EXTENDED_SESSION_SECURITY TARGET_TYPE_SERVER NEGOTIATE_ALWAYS_SIGN NEGOTIATE_NTLM NEGOTIATE_SEAL NEGOTIATE_SIGN REQUEST_TARGET NEGOTIATE_UNICODE + + (byte)0xc1, (byte)0x4a, (byte)0xc8, (byte)0x98, (byte)0x2f, (byte)0xd1, (byte)0x93, (byte)0xd4, // ServerChallenge + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Reserved + (byte) 0x98, 0x00, (byte) 0x98, 0x00, 0x56, 0x00, 0x00, 0x00, // TargetInfo (length: 152, allocated space: 152, offset: 86) + 0x06, 0x03, (byte) 0xd7, 0x24, 0x00, 0x00, 0x00, 0x0f, // Version (6.3, build 9431) , NTLM current revision: 15 + + + 0x57, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x2d, 0x00, 0x4c, 0x00, 0x4f, 0x00, 0x34, 0x00, 0x31, 0x00, 0x39, 0x00, 0x42, 0x00, 0x32, 0x00, 0x4c, 0x00, 0x53, 0x00, 0x52, 0x00, 0x30, 0x00, // Target name value: "WIN-LO419B2LSR0" + + // Target Info value: + + // Attribute list + + 0x02, 0x00, // Item Type: NetBIOS domain name (0x0002, LE) + 0x1e, 0x00, // Item Length: 30 (LE) + 0x57, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x2d, 0x00, 0x4c, 0x00, 0x4f, 0x00, 0x34, 0x00, 0x31, 0x00, 0x39, 0x00, 0x42, 0x00, 0x32, 0x00, 0x4c, 0x00, 0x53, 0x00, 0x52, 0x00, 0x30, 0x00, // "WIN-LO419B2LSR0" + + 0x01, 0x00, // Item Type: NetBIOS computer name (0x0001, LE) + 0x1e, 0x00, // Item Length: 30 (LE) + 0x57, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x2d, 0x00, 0x4c, 0x00, 0x4f, 0x00, 0x34, 0x00, 0x31, 0x00, 0x39, 0x00, 0x42, 0x00, 0x32, 0x00, 0x4c, 0x00, 0x53, 0x00, 0x52, 0x00, 0x30, 0x00, // "WIN-LO419B2LSR0" + + 0x04, 0x00, // Item Type: DNS domain name (0x0004, LE) + 0x1e, 0x00, // Item Length: 30 (LE) + 0x57, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x2d, 0x00, 0x4c, 0x00, 0x4f, 0x00, 0x34, 0x00, 0x31, 0x00, 0x39, 0x00, 0x42, 0x00, 0x32, 0x00, 0x4c, 0x00, 0x53, 0x00, 0x52, 0x00, 0x30, 0x00, // "WIN-LO419B2LSR0" + + 0x03, 0x00, // Item Type: DNS computer name (0x0003, LE) + 0x1e, 0x00, // Item Length: 30 (LE) + 0x57, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x2d, 0x00, 0x4c, 0x00, 0x4f, 0x00, 0x34, 0x00, 0x31, 0x00, 0x39, 0x00, 0x42, 0x00, 0x32, 0x00, 0x4c, 0x00, 0x53, 0x00, 0x52, 0x00, 0x30, 0x00, // "WIN-LO419B2LSR0" + + 0x07, 0x00, // Item Type: Timestamp (0x0007, LE) + 0x08, 0x00, // Item Length: 8 (LE) + (byte)0x1d, (byte)0xea, (byte)0x6b, (byte)0x60, (byte)0xf8, (byte)0xc5, (byte)0xce, (byte)0x01, // Time: Oct 10, 2013 23:36:20.056937300 EEST + + // Attribute: End of list + 0x00, 0x00, + 0x00, 0x00, + + }; + +// +// Client NTLMSSP_AUTH +// + byte[] clientAuthPacket = new byte[] { + 0x30, (byte) 0x82, 0x03, 0x13, // TAG: [UNIVERSAL 16] (constructed) "SEQUENCE" LEN: 787 bytes + + // + // TSRequest.version + // + (byte) 0xa0, 0x03, // TAG: [0] (constructed) LEN: 3 bytes + 0x02, 0x01, 0x02, // TAG: [UNIVERSAL 2] (primitive) "INTEGER" LEN: 1 bytes + + // + // TSRequest.negoData + // + (byte) 0xa1, (byte) 0x82, 0x01, (byte) 0xe4, // TAG: [1] (constructed) LEN: 484 bytes + 0x30, (byte) 0x82, 0x01, (byte) 0xe0, // TAG: [UNIVERSAL 16] (constructed) "SEQUENCE" LEN: 480 bytes + 0x30, (byte) 0x82, 0x01, (byte) 0xdc, // TAG: [UNIVERSAL 16] (constructed) "SEQUENCE" LEN: 476 bytes + + // + // NegoItem.negoToken + // + (byte) 0xa0, (byte) 0x82, 0x01, (byte) 0xd8, // TAG: [0] (constructed) LEN: 472 bytes + 0x04, (byte) 0x82, 0x01, (byte) 0xd4, // TAG: [UNIVERSAL 4] (primitive) "OCTET STRING" LEN: 468 bytes + + // NTLMSSP + + 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00, // "NTLMSSP\0" + + 0x03, 0x00, 0x00, 0x00, // NTLM Message Type: NTLMSSP_AUTH (0x00000003) + 0x18, 0x00, 0x18, 0x00, (byte) 0x92, 0x00, 0x00, 0x00, // LmChallengeResponse (length 24, allocated: 24, offset 146) + 0x1a, 0x01, 0x1a, 0x01, (byte) 0xaa, 0x00, 0x00, 0x00, // NtChallengeResponse (length 282, allocated: 282, offset 170) + 0x12, 0x00, 0x12, 0x00, 0x58, 0x00, 0x00, 0x00, // DomainName (length 18, allocated: 88, offset 88) + 0x1a, 0x00, 0x1a, 0x00, 0x6a, 0x00, 0x00, 0x00, // UserName (length 26, allocated:26, offset 106) + 0x0e, 0x00, 0x0e, 0x00, (byte) 0x84, 0x00, 0x00, 0x00, // Workstation (length 14, offset 132) + 0x10, 0x00, 0x10, 0x00, (byte) 0xc4, 0x01, 0x00, 0x00, // EncryptedRandomSessionKey (length 16, offset 452) + 0x35, (byte) 0xb2, (byte) 0x88, (byte) 0xe2, // NegotiateFlags + 0x06, 0x01, (byte) 0xb1, 0x1d, 0x00, 0x00, 0x00, 0x0f, // Version (6.1, Build 7601), NTLM current revision: 15 + + (byte)0x8c, (byte)0x69, (byte)0x53, (byte)0x1c, (byte)0xbb, (byte)0x6f, (byte)0xfb, (byte)0x9a, (byte)0x5d, (byte)0x2c, (byte)0x63, (byte)0xf2, (byte)0xc9, (byte)0x51, (byte)0xc5, (byte)0x11, // Message integrity check + + 0x77, 0x00, 0x6f, 0x00, 0x72, 0x00, 0x6b, 0x00, 0x67, 0x00, 0x72, 0x00, 0x6f, 0x00, 0x75, 0x00, 0x70, 0x00, // Domain name value: "Workgroup" + + 0x41, 0x00, 0x64, 0x00, 0x6d, 0x00, 0x69, 0x00, 0x6e, 0x00, 0x69, 0x00, 0x73, 0x00, 0x74, 0x00, 0x72, 0x00, 0x61, 0x00, 0x74, 0x00, 0x6f, 0x00, 0x72, 0x00, // User name value: "Administrator" + + 0x61, 0x00, 0x70, 0x00, 0x6f, 0x00, 0x6c, 0x00, 0x6c, 0x00, 0x6f, 0x00, 0x33, 0x00, // Workstation host name value: "apollo3" + + // Lan manager challenge response value + // Response: HMAC_MD(ResponseKeyLM, concatenate(ServerChallenge, ClientChallenge), where ResponseKeyLM=ntlmv2Hash(target, user, password) + (byte)0x17, (byte)0x9b, (byte)0x7d, (byte)0x7b, (byte)0x2f, (byte)0x79, (byte)0x9f, (byte)0x19, (byte)0xa0, (byte)0x4b, (byte)0x00, (byte)0xed, (byte)0x2b, (byte)0x39, (byte)0xbb, (byte)0x23, + // Client challenge (fixed for debugging) + (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08, + + // + // NTLM challenge response value: + // + + (byte)0x49, (byte)0xea, (byte)0x27, (byte)0x4f, (byte)0xcc, (byte)0x05, (byte)0x8b, (byte)0x79, (byte)0x20, (byte)0x0b, (byte)0x08, (byte)0x42, (byte)0xa9, (byte)0xc8, (byte)0x0e, (byte)0xc7, // HMAC + + 0x01, 0x01, 0x00, 0x00, // Header: 0x00000101 (LE) + 0x00, 0x00, 0x00, 0x00, // Reserved: 0x00000000 + (byte)0x1d, (byte)0xea, (byte)0x6b, (byte)0x60, (byte)0xf8, (byte)0xc5, (byte)0xce, (byte)0x01, // Time: Oct 10, 2013 23:36:20.056937300 EEST + (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08, // Client challenge (fixed) + 0x00, 0x00, 0x00, 0x00, // Reserved + + // Target Info value: + + // Attribute list + + 0x02, 0x00, // Item Type: NetBIOS domain name (0x0002, LE) + 0x1e, 0x00, // Item Length: 30 (LE) + 0x57, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x2d, 0x00, 0x4c, 0x00, 0x4f, 0x00, 0x34, 0x00, 0x31, 0x00, 0x39, 0x00, 0x42, 0x00, 0x32, 0x00, 0x4c, 0x00, 0x53, 0x00, 0x52, 0x00, 0x30, 0x00, // "WIN-LO419B2LSR0 " + + 0x01, 0x00, // Item Type: NetBIOS computer name (0x0001, LE) + 0x1e, 0x00, // Item Length: 30 (LE) + 0x57, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x2d, 0x00, 0x4c, 0x00, 0x4f, 0x00, 0x34, 0x00, 0x31, 0x00, 0x39, 0x00, 0x42, 0x00, 0x32, 0x00, 0x4c, 0x00, 0x53, 0x00, 0x52, 0x00, 0x30, 0x00, // "WIN-LO419B2LSR0 " + + 0x04, 0x00, // Item Type: DNS domain name (0x0004, LE) + 0x1e, 0x00, // Item Length: 30 (LE) + 0x57, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x2d, 0x00, 0x4c, 0x00, 0x4f, 0x00, 0x34, 0x00, 0x31, 0x00, 0x39, 0x00, 0x42, 0x00, 0x32, 0x00, 0x4c, 0x00, 0x53, 0x00, 0x52, 0x00, 0x30, 0x00, // "WIN-LO419B2LSR0 " + + 0x03, 0x00, // Item Type: DNS computer name (0x0003, LE) + 0x1e, 0x00, // Item Length: 30 (LE) + 0x57, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x2d, 0x00, 0x4c, 0x00, 0x4f, 0x00, 0x34, 0x00, 0x31, 0x00, 0x39, 0x00, 0x42, 0x00, 0x32, 0x00, 0x4c, 0x00, 0x53, 0x00, 0x52, 0x00, 0x30, 0x00, // "WIN-LO419B2LSR0 " + + 0x07, 0x00, // Item Type: Timestamp (0x0007, LE) + 0x08, 0x00, // Item Length: 8 (LE) + (byte)0x1d, (byte)0xea, (byte)0x6b, (byte)0x60, (byte)0xf8, (byte)0xc5, (byte)0xce, (byte)0x01, // Timestamp: Oct 10, 2013 23:36:20.056937300 EEST + + 0x06, 0x00, // Item Type: Flags (0x0006, LE) + 0x04, 0x00, // Item Length: 4 (LE) + 0x02, 0x00, 0x00, 0x00, // Flags: 0x00000002 + + 0x0a, 0x00, // Item Type: Channel Bindings (0x000a, LE) + 0x10, 0x00, // Item Length: 16 (LE) + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Channel Bindings: 00000000000000000000000000000000 + + 0x09, 0x00, // Item Type: Target Name (0x0009, LE) + 0x2a, 0x00, // Item Length: 42 (LE) + 0x54, 0x00, 0x45, 0x00, 0x52, 0x00, 0x4d, 0x00, 0x53, 0x00, 0x52, 0x00, 0x56, 0x00, 0x2f, 0x00, 0x31, 0x00, 0x39, 0x00, 0x32, 0x00, 0x2e, 0x00, 0x31, 0x00, 0x36, 0x00, 0x38, 0x00, 0x2e, 0x00, 0x30, 0x00, 0x2e, 0x00, 0x31, 0x00, 0x30, 0x00, 0x31, 0x00, // Target Name: "TERMSRV/192.168.0.101" (UTF-16) + + // Attribute: End of list + 0x00, 0x00, // + 0x00, 0x00, // + // Attribute: End of list + 0x00, 0x00, // + 0x00, 0x00, // + // Attribute: End of list + 0x00, 0x00, // + 0x00, 0x00, // + // Attribute: End of list + 0x00, 0x00, // + 0x00, 0x00, // + + // Session Key + // RC4 key (Server KeyExchangeKey or SessionBaseKey): + // 6e bd e3 da 83 c2 fd f1 38 a2 78 be 8c e6 75 d6 + // + // RC4 data (Client nonce): + // 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 + // + // RC4 encrypted: + // 2c 24 da 10 17 cf 40 69 35 49 6f 58 e1 29 9e 79 + (byte)0x2c, (byte)0x24, (byte)0xda, (byte)0x10, (byte)0x17, (byte)0xcf, (byte)0x40, (byte)0x69, (byte)0x35, (byte)0x49, (byte)0x6f, (byte)0x58, (byte)0xe1, (byte)0x29, (byte)0x9e, (byte)0x79, + + // + // TSRequest.publicKey + // + (byte) 0xa3, (byte) 0x82, 0x01, 0x22, // TAG: [3] (constructed) LEN: 290 bytes + 0x04, (byte) 0x82, 0x01, 0x1e, // TAG: [UNIVERSAL 4] (primitive) "OCTET STRING" LEN: 286 bytes + + // NTLMSSP_MESSAGE_SIGNATURE, @see http://msdn.microsoft.com/en-us/library/cc422952.aspx + + // Version: 0x00000001 + (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, + + // Checksum (8 bytes): An 8-byte array that contains the checksum for the message. + (byte)0x72, (byte)0x76, (byte)0x1e, (byte)0x57, (byte)0x49, (byte)0xb5, (byte)0x0f, (byte)0xad, + + // seqNum of the message: 0 + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + + // Encrypted public key + (byte)0x15, (byte)0xf7, (byte)0xf2, (byte)0x54, (byte)0xda, (byte)0xa9, (byte)0xe5, (byte)0xad, (byte)0x85, (byte)0x04, (byte)0x67, (byte)0x4d, (byte)0x0b, (byte)0xcb, (byte)0xf9, (byte)0xb1, + (byte)0xf8, (byte)0x02, (byte)0x8a, (byte)0x77, (byte)0xc2, (byte)0x63, (byte)0xab, (byte)0xd5, (byte)0x74, (byte)0x23, (byte)0x9f, (byte)0x9d, (byte)0x5d, (byte)0x1f, (byte)0xd3, (byte)0xb3, + (byte)0xa0, (byte)0xac, (byte)0x16, (byte)0x8a, (byte)0x4b, (byte)0x08, (byte)0xf5, (byte)0x47, (byte)0x70, (byte)0x58, (byte)0x10, (byte)0xb4, (byte)0xe7, (byte)0x87, (byte)0xb3, (byte)0x4b, + (byte)0xc9, (byte)0xa2, (byte)0xd5, (byte)0xd1, (byte)0xca, (byte)0x0f, (byte)0xd4, (byte)0xe3, (byte)0x8d, (byte)0x76, (byte)0x5a, (byte)0x60, (byte)0x28, (byte)0xf8, (byte)0x06, (byte)0x5d, + (byte)0xe4, (byte)0x7e, (byte)0x21, (byte)0xc8, (byte)0xbb, (byte)0xac, (byte)0xe5, (byte)0x79, (byte)0x85, (byte)0x30, (byte)0x9b, (byte)0x88, (byte)0x13, (byte)0x2f, (byte)0x8f, (byte)0xfc, + (byte)0x04, (byte)0x52, (byte)0xfe, (byte)0x87, (byte)0x94, (byte)0xcf, (byte)0xcb, (byte)0x49, (byte)0x4a, (byte)0xda, (byte)0x6f, (byte)0xdd, (byte)0xee, (byte)0x57, (byte)0xa5, (byte)0xe4, + (byte)0x4d, (byte)0x0e, (byte)0x5c, (byte)0x3d, (byte)0x0b, (byte)0x63, (byte)0x1f, (byte)0xf6, (byte)0x3d, (byte)0x1b, (byte)0xae, (byte)0x5a, (byte)0xf6, (byte)0x42, (byte)0x2a, (byte)0x46, + (byte)0xfa, (byte)0x42, (byte)0x71, (byte)0x67, (byte)0x46, (byte)0x02, (byte)0x71, (byte)0xea, (byte)0x51, (byte)0x98, (byte)0xf7, (byte)0xd4, (byte)0x43, (byte)0xbf, (byte)0x8e, (byte)0xe8, + (byte)0x3c, (byte)0xc8, (byte)0xfa, (byte)0x79, (byte)0x9d, (byte)0x8c, (byte)0xfc, (byte)0xc2, (byte)0x42, (byte)0xc9, (byte)0xbb, (byte)0xd0, (byte)0xab, (byte)0x81, (byte)0xc4, (byte)0x53, + (byte)0xfd, (byte)0x41, (byte)0xda, (byte)0xab, (byte)0x0f, (byte)0x25, (byte)0x79, (byte)0x5f, (byte)0xbd, (byte)0xa3, (byte)0x8c, (byte)0xd3, (byte)0xf5, (byte)0x1b, (byte)0xab, (byte)0x20, + (byte)0xd1, (byte)0xf4, (byte)0xd8, (byte)0x81, (byte)0x9c, (byte)0x18, (byte)0x4a, (byte)0xa4, (byte)0x77, (byte)0xee, (byte)0xe1, (byte)0x51, (byte)0xee, (byte)0x2a, (byte)0xc1, (byte)0x94, + (byte)0x37, (byte)0xc5, (byte)0x06, (byte)0x7a, (byte)0x3f, (byte)0x0f, (byte)0x25, (byte)0x5b, (byte)0x4e, (byte)0x6a, (byte)0xdc, (byte)0x0b, (byte)0x62, (byte)0x6f, (byte)0x12, (byte)0x83, + (byte)0x03, (byte)0xae, (byte)0x4e, (byte)0xce, (byte)0x2b, (byte)0x6e, (byte)0xd4, (byte)0xd5, (byte)0x23, (byte)0x27, (byte)0xf6, (byte)0xa6, (byte)0x38, (byte)0x67, (byte)0xec, (byte)0x95, + (byte)0x82, (byte)0xc6, (byte)0xba, (byte)0xd4, (byte)0xf6, (byte)0xe6, (byte)0x22, (byte)0x7d, (byte)0xb9, (byte)0xe4, (byte)0x81, (byte)0x97, (byte)0x24, (byte)0xff, (byte)0x40, (byte)0xb2, + (byte)0x42, (byte)0x3c, (byte)0x11, (byte)0x24, (byte)0xd0, (byte)0x3a, (byte)0x96, (byte)0xd9, (byte)0xc1, (byte)0x13, (byte)0xd6, (byte)0x62, (byte)0x45, (byte)0x21, (byte)0x60, (byte)0x5b, + (byte)0x7b, (byte)0x2b, (byte)0x62, (byte)0x44, (byte)0xf7, (byte)0x40, (byte)0x93, (byte)0x29, (byte)0x5b, (byte)0x44, (byte)0xb7, (byte)0xda, (byte)0x9c, (byte)0xa6, (byte)0xa9, (byte)0x3b, + (byte)0xe1, (byte)0x3b, (byte)0x9d, (byte)0x31, (byte)0xf2, (byte)0x21, (byte)0x53, (byte)0x0f, (byte)0xb3, (byte)0x70, (byte)0x55, (byte)0x84, (byte)0x2c, (byte)0xb4, + }; + + SSLState sslState = new SSLState(); + + sslState.serverCertificateSubjectPublicKeyInfo = new byte[] { + 0x30, (byte) 0x82, 0x01, 0x22, // Sequence, length: 290 bytes + 0x30, 0x0d, // Sequence, length: 13 bytes { + 0x06, 0x09, // Object ID, length: 9 bytes + 0x2a, (byte) 0x86, 0x48, (byte) 0x86, (byte) 0xf7, 0x0d, 0x01, 0x01, 0x01, + 0x05, 0x00, // NULL, length: 0 bytes + + (byte)0x03, (byte)0x82, (byte)0x01, (byte)0x0f, // Bit string, length: 271 bytes + + (byte)0x00, // Pading + (byte)0x30, (byte)0x82, (byte)0x01, (byte)0x0a, // Sequence + (byte)0x02, (byte)0x82, (byte)0x01, (byte)0x01, // Integer, length: 257 bytes + + (byte)0x00, (byte)0xa8, (byte)0x56, + (byte)0x65, (byte)0xd3, (byte)0xce, (byte)0x8a, (byte)0x54, (byte)0x4d, (byte)0x9d, (byte)0xb0, + (byte)0x84, (byte)0x31, (byte)0x19, (byte)0x71, (byte)0x7f, (byte)0xdd, (byte)0x42, (byte)0xfb, + (byte)0x2a, (byte)0x7a, (byte)0x72, (byte)0x13, (byte)0xa1, (byte)0xb9, (byte)0x72, (byte)0xbb, + (byte)0xd3, (byte)0x08, (byte)0xad, (byte)0x7d, (byte)0x6c, (byte)0x15, (byte)0x65, (byte)0x03, + (byte)0xd1, (byte)0xc4, (byte)0x54, (byte)0xc5, (byte)0x33, (byte)0x6b, (byte)0x7d, (byte)0x69, + (byte)0x89, (byte)0x5e, (byte)0xfe, (byte)0xe0, (byte)0x01, (byte)0xc0, (byte)0x7e, (byte)0x9b, + (byte)0xcb, (byte)0x5d, (byte)0x65, (byte)0x36, (byte)0xcd, (byte)0x77, (byte)0x5d, (byte)0xf3, + (byte)0x7a, (byte)0x5b, (byte)0x29, (byte)0x44, (byte)0x72, (byte)0xd5, (byte)0x38, (byte)0xe2, + (byte)0xcf, (byte)0xb1, (byte)0xc7, (byte)0x78, (byte)0x9b, (byte)0x58, (byte)0xb9, (byte)0x17, + (byte)0x7c, (byte)0xb7, (byte)0xd6, (byte)0xc7, (byte)0xc7, (byte)0xbf, (byte)0x90, (byte)0x4e, + (byte)0x7c, (byte)0x39, (byte)0x93, (byte)0xcb, (byte)0x2e, (byte)0xe0, (byte)0xc2, (byte)0x33, + (byte)0x2d, (byte)0xa5, (byte)0x7e, (byte)0xe0, (byte)0x7b, (byte)0xb6, (byte)0xf9, (byte)0x91, + (byte)0x32, (byte)0xb7, (byte)0xd4, (byte)0x85, (byte)0xb7, (byte)0x35, (byte)0x2d, (byte)0x2b, + (byte)0x00, (byte)0x6d, (byte)0xf8, (byte)0xea, (byte)0x8c, (byte)0x97, (byte)0x5f, (byte)0x51, + (byte)0x1d, (byte)0x68, (byte)0x04, (byte)0x3c, (byte)0x79, (byte)0x14, (byte)0x71, (byte)0xa7, + (byte)0xc7, (byte)0xd7, (byte)0x70, (byte)0x7a, (byte)0xe0, (byte)0xba, (byte)0x12, (byte)0x69, + (byte)0xc8, (byte)0xd3, (byte)0xd9, (byte)0x4e, (byte)0xab, (byte)0x51, (byte)0x47, (byte)0xa3, + (byte)0xec, (byte)0x99, (byte)0xd4, (byte)0x88, (byte)0xca, (byte)0xda, (byte)0xc2, (byte)0x7f, + (byte)0x79, (byte)0x4b, (byte)0x66, (byte)0xed, (byte)0x87, (byte)0xbe, (byte)0xc2, (byte)0x5f, + (byte)0xea, (byte)0xcf, (byte)0xe1, (byte)0xb5, (byte)0xf0, (byte)0x3d, (byte)0x9b, (byte)0xf2, + (byte)0x19, (byte)0xc3, (byte)0xe0, (byte)0xe1, (byte)0x7a, (byte)0x45, (byte)0x71, (byte)0x12, + (byte)0x3d, (byte)0x72, (byte)0x1d, (byte)0x6f, (byte)0x2b, (byte)0x1c, (byte)0x46, (byte)0x68, + (byte)0xc0, (byte)0x8f, (byte)0x4f, (byte)0xce, (byte)0x3a, (byte)0xc5, (byte)0xcd, (byte)0x22, + (byte)0x65, (byte)0x2d, (byte)0x43, (byte)0xb0, (byte)0x5c, (byte)0xdd, (byte)0x89, (byte)0xae, + (byte)0xbe, (byte)0x70, (byte)0x59, (byte)0x5e, (byte)0x0c, (byte)0xbd, (byte)0xf5, (byte)0x46, + (byte)0x82, (byte)0x1e, (byte)0xe4, (byte)0x86, (byte)0x95, (byte)0x7b, (byte)0x60, (byte)0xae, + (byte)0x45, (byte)0x50, (byte)0xc2, (byte)0x54, (byte)0x08, (byte)0x49, (byte)0x9a, (byte)0x9e, + (byte)0xfb, (byte)0xb2, (byte)0xb6, (byte)0x78, (byte)0xe5, (byte)0x2f, (byte)0x9c, (byte)0x5a, + (byte)0xd0, (byte)0x8a, (byte)0x03, (byte)0x77, (byte)0x68, (byte)0x30, (byte)0x93, (byte)0x78, + (byte)0x6d, (byte)0x90, (byte)0x6d, (byte)0x50, (byte)0xfa, (byte)0xa7, (byte)0x65, (byte)0xfe, + (byte)0x59, (byte)0x33, (byte)0x27, (byte)0x4e, (byte)0x4b, (byte)0xf8, (byte)0x38, (byte)0x44, + (byte)0x3a, (byte)0x12, (byte)0xf4, (byte)0x07, (byte)0xa0, (byte)0x8d, (byte)0x02, (byte)0x03, + (byte)0x01, (byte)0x00, (byte)0x01, + }; + /* @formatter:on */ + + NtlmState ntlmState = new NtlmState(); + MockSource source = new MockSource("source", ByteBuffer.convertByteArraysToByteBuffers(serverChallengePacket, new byte[] {1, 2, 3})); + Element ntlmssp_negotiate = new ClientNtlmsspNegotiate("ntlmssp_negotiate", ntlmState); + Element ntlmssp_challenge = new ServerNtlmsspChallenge("ntlmssp_challenge", ntlmState); + Element ntlmssp_auth = new ClientNtlmsspPubKeyAuth("ntlmssp_auth", ntlmState, sslState, "192.168.0.101", "workgroup", "apollo3", "Administrator", + "R2Preview!"); + Element sink = new MockSink("sink", ByteBuffer.convertByteArraysToByteBuffers(clientNegotiatePacket, clientAuthPacket), (Dumper)ntlmssp_auth); + Element mainSink = new MockSink("mainSink", ByteBuffer.convertByteArraysToByteBuffers(new byte[] {1, 2, 3})); + + Pipeline pipeline = new PipelineImpl("test"); + pipeline.add(source, ntlmssp_negotiate, ntlmssp_challenge, ntlmssp_auth, sink, mainSink); + pipeline.link("source", "ntlmssp_negotiate", "ntlmssp_challenge", "ntlmssp_auth", "mainSink"); + pipeline.link("ntlmssp_negotiate >" + OTOUT, "ntlmssp_negotiate< sink"); + pipeline.link("ntlmssp_challenge >" + OTOUT, "ntlmssp_challenge< sink"); + pipeline.link("ntlmssp_auth >" + OTOUT, "ntlmssp_auth< sink"); + pipeline.runMainLoop("source", STDOUT, false, false); + + } + + @Override + public void dump(ByteBuffer buf) { + buf.rewindCursor(); + TSRequest request = new TSRequest("TSRequest"); + request.readTag(buf); + System.out.println("TSRequest version: " + request.version.value); + System.out.println("TSRequest pubKey: " + request.pubKeyAuth.value.toPlainHexString()); + + ByteBuffer negoToken = ((NegoItem)request.negoTokens.tags[0]).negoToken.value; + System.out.println("TSRequest negotoken: " + negoToken.toPlainHexString()); + dumpNegoToken(negoToken); + + negoToken.unref(); + } + + private void dumpNegoToken(ByteBuffer buf) { + String signature = buf.readVariableString(RdpConstants.CHARSET_8); + if (!signature.equals(NTLMSSP)) + throw new RuntimeException("Unexpected NTLM message singature: \"" + signature + "\". Expected signature: \"" + NTLMSSP + "\". Data: " + buf + "."); + + // MessageType (CHALLENGE) + int messageType = buf.readSignedIntLE(); + if (messageType != NtlmConstants.NTLMSSP_AUTH) + throw new RuntimeException("Unexpected NTLM message type: " + messageType + ". Expected type: CHALLENGE (" + NtlmConstants.CHALLENGE + "). Data: " + buf + + "."); + + System.out.println("lmChallengeResponseFields: " + ServerNtlmsspChallenge.readBlockByDescription(buf).toPlainHexString()); + ByteBuffer ntChallengeResponseBuf = ServerNtlmsspChallenge.readBlockByDescription(buf); + System.out.println("NtChallengeResponse: " + ntChallengeResponseBuf.toPlainHexString()); + System.out.println("DomainName: " + ServerNtlmsspChallenge.readStringByDescription(buf)); + System.out.println("UserName: " + ServerNtlmsspChallenge.readStringByDescription(buf)); + System.out.println("Workstation: " + ServerNtlmsspChallenge.readStringByDescription(buf)); + System.out.println("EncryptedRandomSessionKey: " + ServerNtlmsspChallenge.readBlockByDescription(buf).toPlainHexString()); + System.out.println("NegotiateFlags: " + new NegoFlags(buf.readSignedIntLE())); + System.out.println("Version: " + buf.readBytes(8).toPlainHexString()); + + dumpNtChallengeResponse(ntChallengeResponseBuf); + } + + private void dumpNtChallengeResponse(ByteBuffer buf) { + System.out.println("HMAC: " + buf.readBytes(16).toPlainHexString()); + System.out.format("Header: 0x%08x\n", buf.readUnsignedIntLE()); + System.out.format("Reserved: 0x%08x\n", buf.readUnsignedIntLE()); + System.out.println("Time: " + buf.readBytes(8).toPlainHexString()); + System.out.println("Client challenge: " + buf.readBytes(8).toPlainHexString()); + System.out.format("Reserved: 0x%08x\n", buf.readUnsignedIntLE()); + + // Parse attribute list + + while (buf.remainderLength() > 0) { + int type = buf.readUnsignedShortLE(); + int length = buf.readUnsignedShortLE(); + + if (type == MSV_AV_EOL) + // End of list + break; + + ByteBuffer data = buf.readBytes(length); + switch (type) { + case MSV_AV_NETBIOS_DOMAIN_NAME: + System.out.println("AV Netbios Domain name: " + data.readString(length, RdpConstants.CHARSET_16)); + break; + case MSV_AV_NETBIOS_COMPUTER_NAME: + System.out.println("AV Netbios Computer name: " + data.readString(length, RdpConstants.CHARSET_16)); + break; + case MSV_AV_DNS_DOMAIN_NAME: + System.out.println("AV DNS Domain name: " + data.readString(length, RdpConstants.CHARSET_16)); + break; + case MSV_AV_DNS_COMPUTER_NAME: + System.out.println("AV DNS Computer name: " + data.readString(length, RdpConstants.CHARSET_16)); + break; + case MSV_AV_CHANNEL_BINDINGS: + System.out.println("AV Channel Bindings: " + data.readBytes(length).toPlainHexString()); + break; + case MSV_AV_TIMESTAMP: + System.out.println("AV Timestamp: " + data.readBytes(length).toPlainHexString()); + break; + case MSV_AV_FLAGS: + System.out.println("AV Flags: " + data.readBytes(length).toPlainHexString()); + break; + case MSV_AV_TARGET_NAME: + System.out.println("AV Target Name: " + data.readString(length, RdpConstants.CHARSET_16)); + break; + default: + System.out.println("Unknown NTLM target info attribute: " + type + ". Data: " + data + "."); + } + data.unref(); + } + + } +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/ClientNtlmsspUserCredentials.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/ClientNtlmsspUserCredentials.java new file mode 100755 index 00000000000..480f448ece0 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/ClientNtlmsspUserCredentials.java @@ -0,0 +1,128 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.ntlmssp; + +import rdpclient.ntlmssp.asn1.TSCredentials; +import rdpclient.ntlmssp.asn1.TSPasswordCreds; +import rdpclient.ntlmssp.asn1.TSRequest; +import rdpclient.rdp.RdpConstants; +import streamer.ByteBuffer; +import streamer.Element; +import streamer.Link; +import streamer.OneTimeSwitch; + +public class ClientNtlmsspUserCredentials extends OneTimeSwitch implements Element { + + protected NtlmState ntlmState; + + public ClientNtlmsspUserCredentials(String id, NtlmState ntlmState) { + super(id); + this.ntlmState = ntlmState; + } + + @Override + protected void handleOneTimeData(ByteBuffer buf, Link link) { + if (buf == null) + return; + + throw new RuntimeException("Unexpected packet: " + buf + "."); + } + + @Override + protected void onStart() { + super.onStart(); + + ByteBuffer buf = new ByteBuffer(4096, true); + + TSRequest tsRequest = new TSRequest("TSRequest"); + tsRequest.version.value = 2L; + + ByteBuffer tsCredentialsBuf = generateTSCredentials(); + tsRequest.authInfo.value = encryptTSCredentials(tsCredentialsBuf); + tsCredentialsBuf.unref(); + + tsRequest.writeTag(buf); + + // Trim buffer to actual length of data written + buf.trimAtCursor(); + + pushDataToOTOut(buf); + + switchOff(); + } + + private ByteBuffer encryptTSCredentials(ByteBuffer buf2) { + return new ByteBuffer(ntlmState.ntlm_EncryptMessage(buf2.toByteArray())); + } + + private ByteBuffer generateTSCredentials() { + ByteBuffer buf = new ByteBuffer(4096); + + TSCredentials tsCredentials = new TSCredentials("authInfo"); + // 1 means that credentials field contains a TSPasswordCreds structure + tsCredentials.credType.value = 1L; + + ByteBuffer tsPasswordCredsBuf = new ByteBuffer(4096, true); + TSPasswordCreds tsPasswordCreds = new TSPasswordCreds("credentials"); + tsPasswordCreds.domainName.value = new ByteBuffer(ntlmState.domain.getBytes(RdpConstants.CHARSET_16)); + tsPasswordCreds.userName.value = new ByteBuffer(ntlmState.user.getBytes(RdpConstants.CHARSET_16)); + tsPasswordCreds.password.value = new ByteBuffer(ntlmState.password.getBytes(RdpConstants.CHARSET_16)); + tsPasswordCreds.writeTag(tsPasswordCredsBuf); + tsPasswordCredsBuf.trimAtCursor(); + //* DEBUG */System.out.println("TSPasswordCreds:\n" + tsPasswordCredsBuf.dump()); + + tsCredentials.credentials.value = tsPasswordCredsBuf; + + tsCredentials.writeTag(buf); + tsPasswordCredsBuf.unref(); + + // Trim buffer to actual length of data written + buf.trimAtCursor(); + //* DEBUG */System.out.println("TSCredentials:\n" + buf.dump()); + + return buf; + } + + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + + /* @formatter:off */ + // TSCredentials +// 30 57 // Sequence +// a0 03 // TAG 0 +// 02 01 01 // Integer: 1 : credentials contains a TSPasswordCreds structure +// a1 50 // TAG 1 +// 04 4e // OCTETSTRING + // TSPasswordCreds +// 30 4c // SEQUENCE +// a0 14 // TAG 0 +// 04 12 // OCTETSTRING +// 77 00 6f 00 72 00 6b 00 67 00 72 00 6f 00 75 00 70 00 // "workgroup" +// a1 1c // TAG 1 +// 04 1a // OCTETSTRING +// 41 00 64 00 6d 00 69 00 6e 00 69 00 73 00 74 00 72 00 61 00 74 00 6f 00 72 00 // "Administrator" +// a2 16 // TAG 2 +// 04 14 // +// 52 00 32 00 50 00 72 00 65 00 76 00 69 00 65 00 77 00 21 00 // "R2Preview!" + /* @formatter:on */ + + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/CryptoAlgos.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/CryptoAlgos.java new file mode 100755 index 00000000000..d0e72e961fd --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/CryptoAlgos.java @@ -0,0 +1,361 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.ntlmssp; + +import java.lang.reflect.Method; +import java.security.Key; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.util.Arrays; + +import javax.crypto.Cipher; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; + +import rdpclient.rdp.RdpConstants; + +/** + * @see http://msdn.microsoft.com/en-us/library/cc236717.aspx + */ +public class CryptoAlgos implements NtlmConstants { + + /** + * Indicates the left-to-right concatenation of the string parameters, from + * the first string to the Nnth. Any numbers are converted to strings and all + * numeric conversions to strings retain all digits, even nonsignificant ones. + * The result is a string. For example, ConcatenationOf(0x00122, "XYZ", + * "Client") results in the string "00122XYZClient." + */ + public static String concatenationOf(String... args) { + StringBuffer sb = new StringBuffer(); + for (String arg : args) { + sb.append(arg); + } + return sb.toString(); + } + + /** + * Concatenate byte arrays. + */ + public static byte[] concatenationOf(byte[]... arrays) { + int length = 0; + for (byte[] array : arrays) { + length += array.length; + } + + byte[] result = new byte[length]; + int destPos = 0; + for (byte[] array : arrays) { + System.arraycopy(array, 0, result, destPos, array.length); + destPos += array.length; + } + + return result; + } + + /** Indicates a 32-bit CRC calculated over m. */ + public static byte[] CRC32(byte[] m) { + throw new RuntimeException("FATAL: Not implemented."); + } + + /** + * Indicates the encryption of an 8-byte data item d with the 7-byte key k + * using the Data Encryption Standard (DES) algorithm in Electronic Codebook + * (ECB) mode. The result is 8 bytes in length ([FIPS46-2]). + */ + public static byte[] DES(byte[] k, byte[] d) { + throw new RuntimeException("FATAL: Not implemented."); + } + + /** + * Indicates the encryption of an 8-byte data item D with the 16-byte key K + * using the Data Encryption Standard Long (DESL) algorithm. The result is 24 + * bytes in length. DESL(K, D) is computed as follows. + * + *
+     *   ConcatenationOf( DES(K[0..6], D),
+     *     DES(K[7..13], D), DES(
+     *       ConcatenationOf(K[14..15], Z(5)), D));
+     * 
+ * + * Note K[] implies a key represented as a character array. + */ + public static byte[] DESL(byte[] k, byte[] d) { + throw new RuntimeException("FATAL: Not implemented."); + } + + /** + * An auxiliary function that returns an operating system version-specific + * value (section 2.2.2.8). + */ + public static byte[] getVersion() { + // Version (6.1, Build 7601), NTLM current revision: 15 + return new byte[] {0x06, 0x01, (byte)0xb1, 0x1d, 0x00, 0x00, 0x00, 0x0f}; + } + + /** + * Retrieve the user's LM response key from the server database (directory or + * local database). + */ + public static byte[] LMGETKEY(byte[] u, byte[] d) { + throw new RuntimeException("FATAL: Not implemented."); + } + + /** Retrieve the user's NT response key from the server database. */ + public static byte[] NTGETKEY(byte[] u, byte[] d) { + throw new RuntimeException("FATAL: Not implemented."); + } + + /** + * Indicates the encryption of data item m with the key k using the HMAC + * algorithm ([RFC2104]). + */ + public static byte[] HMAC(byte[] k, byte[] m) { + throw new RuntimeException("FATAL: Not implemented."); + } + + /** + * Indicates the computation of a 16-byte HMAC-keyed MD5 message digest of the + * byte string m using the key k. + */ + public static byte[] HMAC_MD5(byte[] k, byte[] m) { + try { + String algorithm = "HMacMD5"; + Mac hashMac = Mac.getInstance(algorithm); + + Key secretKey = new SecretKeySpec(k, 0, k.length, algorithm); + hashMac.init(secretKey); + return hashMac.doFinal(m); + } catch (Exception e) { + throw new RuntimeException("Cannot calculate HMAC-MD5.", e); + } + } + + /** + * Produces a key exchange key from the session base key K, LM response and + * server challenge SC as defined in the sections KXKEY, SIGNKEY, and SEALKEY. + */ + public static byte[] KXKEY(byte[] sessionBaseKey/*K, byte[] LM, byte[] SC*/) { + // Key eXchange Key is server challenge + /* In NTLMv2, KeyExchangeKey is the 128-bit SessionBaseKey */ + return Arrays.copyOf(sessionBaseKey, sessionBaseKey.length); + } + + /** + * Computes a one-way function of the user's password to use as the response + * key. NTLM v1 and NTLM v2 define separate LMOWF() functions in the NTLM v1 + * authentication and NTLM v2 authentication sections, respectively. + */ + public static byte[] LMOWF() { + throw new RuntimeException("FATAL: Not implemented."); + } + + /** + * Indicates the computation of an MD4 message digest of the null-terminated + * byte string m ([RFC1320]). + */ + public static byte[] MD4(byte[] m) { + try { + return sun.security.provider.MD4.getInstance().digest(m); + } catch (Exception e) { + throw new RuntimeException("Cannot calculate MD5.", e); + } + } + + /** + * Indicates the computation of an MD5 message digest of the null-terminated + * byte string m ([RFC1321]). + */ + public static byte[] MD5(byte[] m) { + try { + return MessageDigest.getInstance("MD5").digest(m); + } catch (Exception e) { + throw new RuntimeException("Cannot calculate MD5.", e); + } + } + + /** + * Indicates the computation of an MD5 message digest of a binary blob + * ([RFC4121] section 4.1.1.2). + */ + public static byte[] MD5_HASH(byte[] m) { + try { + return MessageDigest.getInstance("MD5").digest(m); + } catch (Exception e) { + throw new RuntimeException("Cannot calculate MD5.", e); + } + } + + /** A zero-length string. */ + public static final String NIL = ""; + + /** + * Indicates the computation of an n-byte cryptographic-strength random + * number. + * + * Note The NTLM Authentication Protocol does not define the statistical + * properties of the random number generator. It is left to the discretion of + * the implementation to define the strength requirements of the NONCE(n) + * operation. + */ + public static byte[] NONCE(int n) { + // Generate random nonce for LMv2 and NTv2 responses + byte[] nonce = new byte[n]; + SecureRandom random = new SecureRandom(); + random.nextBytes(nonce); + + // Fixed nonce for debugging purposes + //* DEBUG */for (int i = 0; i < N; i++) nonce[i] = (byte) (i + 1); + + return nonce; + } + + /** + * Computes a one-way function of the user's password to use as the response + * key. NTLM v1 and NTLM v2 define separate NTOWF() functions in the NTLM v1 + * authentication and NTLM v2 authentication sections, respectively. + */ + public static byte[] NTOWF() { + throw new RuntimeException("FATAL: Not implemented."); + } + + /** + * The RC4 Encryption Algorithm. To obtain this stream cipher that is licensed + * by RSA Data Security, Inc., contact this company. + * + * Indicates the encryption of data item d with the current session or message + * key state, using the RC4 algorithm. h is the handle to a key state + * structure initialized by RC4INIT. + */ + public static byte[] RC4(Cipher h, byte[] d) { + return h.update(d); + } + + /** + * Indicates the encryption of data item d with the key k using the RC4 + * algorithm. + * + * Note The key sizes for RC4 encryption in NTLM are defined in sections + * KXKEY, SIGNKEY, and SEALKEY, where they are created. + */ + public static byte[] RC4K(byte[] k, byte[] d) { + try { + Cipher cipher = Cipher.getInstance("RC4"); + Key key = new SecretKeySpec(k, "RC4"); + cipher.init(Cipher.ENCRYPT_MODE, key); + return cipher.doFinal(d); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * Initialization of the RC4 key and handle to a key state structure for the + * session. + */ + public static Cipher RC4Init(byte[] k) { + throw new RuntimeException("FATAL: Not implemented."); + } + + /** + * Produces an encryption key from the session key as defined in sections + * KXKEY, SIGNKEY, and SEALKEY. + */ + public static byte[] SEALKEY(byte[] f, byte[] k, byte[] string1) { + throw new RuntimeException("FATAL: Not implemented."); + } + + /** + * Produces a signing key from the session key as defined in sections KXKEY, + * SIGNKEY, and SEALKEY. + */ + public static byte[] SIGNKEY(int flag, byte[] k, byte[] string1) { + throw new RuntimeException("FATAL: Not implemented."); + } + + /** + * Indicates the retrieval of the current time as a 64-bit value, represented + * as the number of 100-nanosecond ticks elapsed since midnight of January + * 1st, 1601 (UTC). + */ + public static byte[] Currenttime() { + // (current time + milliseconds from 1.01.1601 to 1.01.1970) * + // 100-nanosecond ticks + long time = (System.currentTimeMillis() + 11644473600000L) * 10000; + + // Convert 64bit value to byte array. + byte[] result = new byte[8]; + for (int i = 0; i < 8; i++, time >>>= 8) { + result[i] = (byte)time; + } + + return result; + } + + /** + * Indicates the 2-byte little-endian byte order encoding of the Unicode + * UTF-16 representation of string. The Byte Order Mark (BOM) is not sent over + * the wire. + */ + public static byte[] UNICODE(String string) { + return string.getBytes(RdpConstants.CHARSET_16); + } + + /** Indicates the uppercase representation of string. */ + public static String UpperCase(String string) { + return string.toUpperCase(); + } + + /** + * Indicates the creation of a byte array of length N. Each byte in the array + * is initialized to the value zero. + */ + public static byte[] Z(int n) { + return new byte[n]; + } + + public static Cipher initRC4(byte[] key) { + try { + Cipher cipher = Cipher.getInstance("RC4"); + cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "RC4")); + return cipher; + } catch (Exception e) { + throw new RuntimeException("Cannot initialize RC4 sealing handle with client sealing key.", e); + } + } + + /** + * Helper method for embedded test cases. + */ + public static void callAll(Object obj) { + Method[] methods = obj.getClass().getDeclaredMethods(); + for (Method m : methods) { + if (m.getName().startsWith("test")) { + try { + m.invoke(obj, (Object[])null); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + + public static void main(String args[]) { + callAll(new CryptoAlgos()); + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/NegoFlags.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/NegoFlags.java new file mode 100755 index 00000000000..3208a77c30c --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/NegoFlags.java @@ -0,0 +1,492 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.ntlmssp; + +/** + * During NTLM authentication, each of the following flags is a possible value + * of the NegotiateFlags field of the NEGOTIATE_MESSAGE, CHALLENGE_MESSAGE, and + * AUTHENTICATE_MESSAGE, unless otherwise noted. These flags define client or + * server NTLM capabilities supported by the sender. + * + * @see http://msdn.microsoft.com/en-us/library/cc236650.aspx + */ +public class NegoFlags { + + /** + * 56-bit encryption. If the client sends NTLMSSP_NEGOTIATE_SEAL or + * NTLMSSP_NEGOTIATE_SIGN with NTLMSSP_NEGOTIATE_56 to the server in the + * NEGOTIATE_MESSAGE, the server MUST return NTLMSSP_NEGOTIATE_56 to the + * client in the CHALLENGE_MESSAGE. Otherwise it is ignored. If both + * NTLMSSP_NEGOTIATE_56 and NTLMSSP_NEGOTIATE_128 are requested and supported + * by the client and server, NTLMSSP_NEGOTIATE_56 and NTLMSSP_NEGOTIATE_128 + * will both be returned to the client. Clients and servers that set + * NTLMSSP_NEGOTIATE_SEAL SHOULD set NTLMSSP_NEGOTIATE_56 if it is supported. + * An alternate name for this field is + */ + public static final int NTLMSSP_NEGOTIATE_56 = 0x80000000; + + /** + * Explicit key exchange. This capability SHOULD be used because it improves + * security for message integrity or confidentiality. See sections 3.2.5.1.2, + * 3.2.5.2.1, and 3.2.5.2.2 for details. + */ + public static final int NTLMSSP_NEGOTIATE_KEY_EXCH = 0x40000000; + + /** + * 128-bit session key negotiation. An alternate name for this field is + * NTLMSSP_NEGOTIATE_128. If the client sends NTLMSSP_NEGOTIATE_128 to the + * server in the NEGOTIATE_MESSAGE, the server MUST return + * NTLMSSP_NEGOTIATE_128 to the client in the CHALLENGE_MESSAGE only if the + * client sets NTLMSSP_NEGOTIATE_SEAL or NTLMSSP_NEGOTIATE_SIGN. Otherwise it + * is ignored. If both NTLMSSP_NEGOTIATE_56 and NTLMSSP_NEGOTIATE_128 are + * requested and supported by the client and server, NTLMSSP_NEGOTIATE_56 and + * NTLMSSP_NEGOTIATE_128 will both be returned to the client. Clients and + * servers that set NTLMSSP_NEGOTIATE_SEAL SHOULD set NTLMSSP_NEGOTIATE_128 if + * it is supported. + */ + public static final int NTLMSSP_NEGOTIATE_128 = 0x20000000; + + /** + * Protocol version number. The data corresponding to this flag is provided in + * the Version field of the NEGOTIATE_MESSAGE, the CHALLENGE_MESSAGE, and the + * AUTHENTICATE_MESSAGE. + */ + public static final int NTLMSSP_NEGOTIATE_VERSION = 0x02000000; + + /** + * TargetInfo fields in the CHALLENGE_MESSAGE (section 2.2.1.2) are populated. + */ + public static final int NTLMSSP_NEGOTIATE_TARGET_INFO = 0x00800000; + + /** LMOWF (section 3.3). */ + public static final int NTLMSSP_REQUEST_NON_NT_SESSION_KEY = 0x00400000; + + /** An identify level token. */ + public static final int NTLMSSP_NEGOTIATE_IDENTIFY = 0x00100000; + + /** + * NTLM v2 session security. NTLM v2 session security is a misnomer because it + * is not NTLM v2. It is NTLM v1 using the extended session security that is + * also in NTLM v2. NTLMSSP_NEGOTIATE_LM_KEY and + * NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY are mutually exclusive. If both + * NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY and NTLMSSP_NEGOTIATE_LM_KEY are + * requested, NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY alone MUST be + * returned to the client. NTLM v2 authentication session key generation MUST + * be supported by both the client and the DC in order to be used, and + * extended session security signing and sealing requires support from the + * client and the server in order to be used. + */ + public static final int NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY = 0x00080000; + + /** + * TargetName MUST be a server name. The data corresponding to this flag is + * provided by the server in the TargetName field of the CHALLENGE_MESSAGE. If + * this bit is set, then NTLMSSP_TARGET_TYPE_DOMAIN MUST NOT be set. This flag + * MUST be ignored in the NEGOTIATE_MESSAGE and the AUTHENTICATE_MESSAGE. + */ + public static final int NTLMSSP_TARGET_TYPE_SERVER = 0x00020000; + + /** + * TargetName MUST be a domain name. The data corresponding to this flag is + * provided by the server in the TargetName field of the CHALLENGE_MESSAGE. If + * set, then NTLMSSP_TARGET_TYPE_SERVER MUST NOT be set. This flag MUST be + * ignored in the NEGOTIATE_MESSAGE and the AUTHENTICATE_MESSAGE. + */ + public static final int NTLMSSP_TARGET_TYPE_DOMAIN = 0x00010000; + + /** + * Signature block on all messages. NTLMSSP_NEGOTIATE_ALWAYS_SIGN MUST be set + * in the NEGOTIATE_MESSAGE to the server and the CHALLENGE_MESSAGE to the + * client. NTLMSSP_NEGOTIATE_ALWAYS_SIGN is overridden by + * NTLMSSP_NEGOTIATE_SIGN and NTLMSSP_NEGOTIATE_SEAL, if they are supported. + */ + public static final int NTLMSSP_NEGOTIATE_ALWAYS_SIGN = 0x00008000; + + /** + * Workstation field is present. If this flag is not set, the Workstation + * field MUST be ignored. If this flag is set, the length field of the + * Workstation field specifies whether the workstation name is nonempty or + * not. + */ + public static final int NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED = 0x00002000; + + /** + * Domain name is provided. + * + * Sent by the client in the Type 1 message to indicate that the name of the + * domain in which the client workstation has membership is included in the + * message. This is used by the server to determine whether the client is + * eligible for local authentication. + */ + public static final int NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED = 0x00001000; + + /** + * Connection SHOULD be anonymous. + * + * Sent by the client in the Type 3 message to indicate that an anonymous + * context has been established. This also affects the response fields (as + * detailed in the "Anonymous Response" section). + */ + public static final int NTLMSSP_NEGOTIATE_ANONYMOUS = 0x00000800; + + /** + * Usage of the NTLM v1 session security protocol. NTLMSSP_NEGOTIATE_NTLM MUST + * be set in the NEGOTIATE_MESSAGE to the server and the CHALLENGE_MESSAGE to + * the client. + */ + public static final int NTLMSSP_NEGOTIATE_NTLM = 0x00000200; + + /** + * LAN Manager (LM) session key computation. NTLMSSP_NEGOTIATE_LM_KEY and + * NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY are mutually exclusive. If both + * NTLMSSP_NEGOTIATE_LM_KEY and NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY are + * requested, NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY alone MUST be + * returned to the client. NTLM v2 authentication session key generation MUST + * be supported by both the client and the DC in order to be used, and + * extended session security signing and sealing requires support from the + * client and the server to be used. + */ + public static final int NTLMSSP_NEGOTIATE_LM_KEY = 0x00000080; + + /** + * Connectionless authentication. If NTLMSSP_NEGOTIATE_DATAGRAM is set, then + * NTLMSSP_NEGOTIATE_KEY_EXCH MUST always be set in the AUTHENTICATE_MESSAGE + * to the server and the CHALLENGE_MESSAGE to the client. + */ + public static final int NTLMSSP_NEGOTIATE_DATAGRAM = 0x00000040; + + /** + * Session key negotiation for message confidentiality. If the client sends + * NTLMSSP_NEGOTIATE_SEAL to the server in the NEGOTIATE_MESSAGE, the server + * MUST return NTLMSSP_NEGOTIATE_SEAL to the client in the CHALLENGE_MESSAGE. + * Clients and servers that set NTLMSSP_NEGOTIATE_SEAL SHOULD always set + * NTLMSSP_NEGOTIATE_56 and NTLMSSP_NEGOTIATE_128, if they are supported. + */ + public static final int NTLMSSP_NEGOTIATE_SEAL = 0x00000020; + + /** + * Session key negotiation for message signatures. If the client sends + * NTLMSSP_NEGOTIATE_SIGN to the server in the NEGOTIATE_MESSAGE, the server + * MUST return NTLMSSP_NEGOTIATE_SIGN to the client in the CHALLENGE_MESSAGE. + */ + public static final int NTLMSSP_NEGOTIATE_SIGN = 0x00000010; + + /** + * TargetName field of the CHALLENGE_MESSAGE (section 2.2.1.2) MUST be + * supplied. + */ + public static final int NTLMSSP_REQUEST_TARGET = 0x00000004; + + /** + * OEM character set encoding. + * + * @see NTLMSSP_NEGOTIATE_UNICODE + */ + public static final int NTLMSSP_NEGOTIATE_OEM = 0x00000002; + + /** + * Unicode character set encoding. + * + * The NTLMSSP_NEGOTIATE_UNICODE(A) and NTLM_NEGOTIATE_OEM(B) bits are + * evaluated together as follows: + *
    + *
  • A==1: The choice of character set encoding MUST be Unicode. + * + *
  • A==0 and B==1: The choice of character set encoding MUST be OEM. + * + *
  • A==0 and B==0: The protocol MUST return SEC_E_INVALID_TOKEN. + *
      + * */ + public static final int NTLMSSP_NEGOTIATE_UNICODE = 0x00000001; + + public int value; + + public NegoFlags(int value) { + this.value = value; + } + + public NegoFlags() { + value = 0; + } + + @Override + public String toString() { + return String.format("NegoFlags [value=0x%04x (%s)]", value, flagsToSting()); + } + + public String flagsToSting() { + + String str = ""; + + if (NEGOTIATE_56()) + str += "NEGOTIATE_56 "; + if (NEGOTIATE_KEY_EXCH()) + str += "NEGOTIATE_KEY_EXCH "; + if (NEGOTIATE_128()) + str += "NEGOTIATE_128 "; + if (NEGOTIATE_VERSION()) + str += "NEGOTIATE_VERSION "; + if (NEGOTIATE_TARGET_INFO()) + str += "NEGOTIATE_TARGET_INFO "; + if (REQUEST_NON_NT_SESSION_KEY()) + str += "REQUEST_NON_NT_SESSION_KEY "; + if (NEGOTIATE_IDENTIFY()) + str += "NEGOTIATE_IDENTIFY "; + if (NEGOTIATE_EXTENDED_SESSION_SECURITY()) + str += "NEGOTIATE_EXTENDED_SESSION_SECURITY "; + if (TARGET_TYPE_SERVER()) + str += "TARGET_TYPE_SERVER "; + if (TARGET_TYPE_DOMAIN()) + str += "TARGET_TYPE_DOMAIN "; + if (NEGOTIATE_ALWAYS_SIGN()) + str += "NEGOTIATE_ALWAYS_SIGN "; + if (NEGOTIATE_OEM_WORKSTATION_SUPPLIED()) + str += "NEGOTIATE_OEM_WORKSTATION_SUPPLIED "; + if (NEGOTIATE_OEM_DOMAIN_SUPPLIED()) + str += "NEGOTIATE_OEM_DOMAIN_SUPPLIED "; + if (NEGOTIATE_ANONYMOUS()) + str += "NEGOTIATE_ANONYMOUS "; + if (NEGOTIATE_NTLM()) + str += "NEGOTIATE_NTLM "; + if (NEGOTIATE_LM_KEY()) + str += "NEGOTIATE_LM_KEY "; + if (NEGOTIATE_DATAGRAM()) + str += "NEGOTIATE_DATAGRAM "; + if (NEGOTIATE_SEAL()) + str += "NEGOTIATE_SEAL "; + if (NEGOTIATE_SIGN()) + str += "NEGOTIATE_SIGN "; + if (REQUEST_TARGET()) + str += "REQUEST_TARGET "; + if (NEGOTIATE_OEM()) + str += "NEGOTIATE_OEM "; + if (NEGOTIATE_UNICODE()) + str += "NEGOTIATE_UNICODE "; + + return str; + } + + public boolean NEGOTIATE_56() { + return ((value & NTLMSSP_NEGOTIATE_56) != 0); + } + + public boolean NEGOTIATE_KEY_EXCH() { + return ((value & NTLMSSP_NEGOTIATE_KEY_EXCH) != 0); + } + + public boolean NEGOTIATE_128() { + return ((value & NTLMSSP_NEGOTIATE_128) != 0); + } + + public boolean NEGOTIATE_VERSION() { + return ((value & NTLMSSP_NEGOTIATE_VERSION) != 0); + } + + public boolean NEGOTIATE_TARGET_INFO() { + return ((value & NTLMSSP_NEGOTIATE_TARGET_INFO) != 0); + } + + public boolean REQUEST_NON_NT_SESSION_KEY() { + return ((value & NTLMSSP_REQUEST_NON_NT_SESSION_KEY) != 0); + } + + public boolean NEGOTIATE_IDENTIFY() { + return ((value & NTLMSSP_NEGOTIATE_IDENTIFY) != 0); + } + + public boolean NEGOTIATE_EXTENDED_SESSION_SECURITY() { + return ((value & NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY) != 0); + } + + public boolean TARGET_TYPE_SERVER() { + return ((value & NTLMSSP_TARGET_TYPE_SERVER) != 0); + } + + public boolean TARGET_TYPE_DOMAIN() { + return ((value & NTLMSSP_TARGET_TYPE_DOMAIN) != 0); + } + + public boolean NEGOTIATE_ALWAYS_SIGN() { + return ((value & NTLMSSP_NEGOTIATE_ALWAYS_SIGN) != 0); + } + + public boolean NEGOTIATE_OEM_WORKSTATION_SUPPLIED() { + return ((value & NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED) != 0); + } + + public boolean NEGOTIATE_OEM_DOMAIN_SUPPLIED() { + return ((value & NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED) != 0); + } + + public boolean NEGOTIATE_ANONYMOUS() { + return ((value & NTLMSSP_NEGOTIATE_ANONYMOUS) != 0); + } + + public boolean NEGOTIATE_NTLM() { + return ((value & NTLMSSP_NEGOTIATE_NTLM) != 0); + } + + public boolean NEGOTIATE_LM_KEY() { + return ((value & NTLMSSP_NEGOTIATE_LM_KEY) != 0); + } + + public boolean NEGOTIATE_DATAGRAM() { + return ((value & NTLMSSP_NEGOTIATE_DATAGRAM) != 0); + } + + public boolean NEGOTIATE_SEAL() { + return ((value & NTLMSSP_NEGOTIATE_SEAL) != 0); + } + + public boolean NEGOTIATE_SIGN() { + return ((value & NTLMSSP_NEGOTIATE_SIGN) != 0); + } + + public boolean REQUEST_TARGET() { + return ((value & NTLMSSP_REQUEST_TARGET) != 0); + } + + public boolean NEGOTIATE_OEM() { + return ((value & NTLMSSP_NEGOTIATE_OEM) != 0); + } + + public boolean NEGOTIATE_UNICODE() { + return ((value & NTLMSSP_NEGOTIATE_UNICODE) != 0); + } + + public NegoFlags set_NEGOTIATE_56() { + value |= NTLMSSP_NEGOTIATE_56; + return this; + } + + public NegoFlags set_NEGOTIATE_KEY_EXCH() { + value |= NTLMSSP_NEGOTIATE_KEY_EXCH; + return this; + } + + public NegoFlags set_NEGOTIATE_128() { + value |= NTLMSSP_NEGOTIATE_128; + return this; + } + + public NegoFlags set_NEGOTIATE_VERSION() { + value |= NTLMSSP_NEGOTIATE_VERSION; + return this; + } + + public NegoFlags set_NEGOTIATE_TARGET_INFO() { + value |= NTLMSSP_NEGOTIATE_TARGET_INFO; + return this; + } + + public NegoFlags set_REQUEST_NON_NT_SESSION_KEY() { + value |= NTLMSSP_REQUEST_NON_NT_SESSION_KEY; + return this; + } + + public NegoFlags set_NEGOTIATE_IDENTIFY() { + value |= NTLMSSP_NEGOTIATE_IDENTIFY; + return this; + } + + public NegoFlags set_NEGOTIATE_EXTENDED_SESSION_SECURITY() { + value |= NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY; + return this; + } + + public NegoFlags set_TARGET_TYPE_SERVER() { + value |= NTLMSSP_TARGET_TYPE_SERVER; + return this; + } + + public NegoFlags set_TARGET_TYPE_DOMAIN() { + value |= NTLMSSP_TARGET_TYPE_DOMAIN; + return this; + } + + public NegoFlags set_NEGOTIATE_ALWAYS_SIGN() { + value |= NTLMSSP_NEGOTIATE_ALWAYS_SIGN; + return this; + } + + public NegoFlags set_NEGOTIATE_OEM_WORKSTATION_SUPPLIED() { + value |= NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED; + return this; + } + + public NegoFlags set_NEGOTIATE_OEM_DOMAIN_SUPPLIED() { + value |= NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED; + return this; + } + + public NegoFlags set_NEGOTIATE_ANONYMOUS() { + value |= NTLMSSP_NEGOTIATE_ANONYMOUS; + return this; + } + + public NegoFlags set_NEGOTIATE_NTLM() { + value |= NTLMSSP_NEGOTIATE_NTLM; + return this; + } + + public NegoFlags set_NEGOTIATE_LM_KEY() { + value |= NTLMSSP_NEGOTIATE_LM_KEY; + return this; + } + + public NegoFlags set_NEGOTIATE_DATAGRAM() { + value |= NTLMSSP_NEGOTIATE_DATAGRAM; + return this; + } + + public NegoFlags set_NEGOTIATE_SEAL() { + value |= NTLMSSP_NEGOTIATE_SEAL; + return this; + } + + public NegoFlags set_NEGOTIATE_SIGN() { + value |= NTLMSSP_NEGOTIATE_SIGN; + return this; + } + + public NegoFlags set_REQUEST_TARGET() { + value |= NTLMSSP_REQUEST_TARGET; + return this; + } + + public NegoFlags set_NEGOTIATE_OEM() { + value |= NTLMSSP_NEGOTIATE_OEM; + return this; + } + + public NegoFlags set_NEGOTIATE_UNICODE() { + value |= NTLMSSP_NEGOTIATE_UNICODE; + return this; + } + + /** + * Example. + */ + + public static void main(String args[]) { + + NegoFlags flags = new NegoFlags(0xe20882b7); + System.out.println("Negotiation flags: " + flags); + + } + +} diff --git a/server/src/com/cloud/uuididentity/dao/IdentityVO.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/NtlmCompute.java old mode 100644 new mode 100755 similarity index 87% rename from server/src/com/cloud/uuididentity/dao/IdentityVO.java rename to services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/NtlmCompute.java index c40f40bc702..e75c73c17e3 --- a/server/src/com/cloud/uuididentity/dao/IdentityVO.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/NtlmCompute.java @@ -14,12 +14,11 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.uuididentity.dao; +package rdpclient.ntlmssp; -import javax.persistence.Entity; +public class NtlmCompute { -/** - */ -@Entity -public class IdentityVO { + public void compute_ntlm_v2_hash() { + + } } diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/NtlmConstants.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/NtlmConstants.java new file mode 100755 index 00000000000..a823aac89ec --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/NtlmConstants.java @@ -0,0 +1,157 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.ntlmssp; + +public interface NtlmConstants { + + /** + * Attribute type: Indicates that this is the last AV_PAIR in the list. AvLen + * MUST be 0. This type of information MUST be present in the AV pair list. + */ + public final static int MSV_AV_EOL = 0x0000; + + /** + * Attribute type: The server's NetBIOS computer name. The name MUST be in + * Unicode, and is not null-terminated. This type of information MUST be + * present in the AV_pair list. + */ + public final static int MSV_AV_NETBIOS_COMPUTER_NAME = 0x0001; + + /** + * Attribute type: The server's NetBIOS domain name. The name MUST be in + * Unicode, and is not null-terminated. This type of information MUST be + * present in the AV_pair list. + */ + public final static int MSV_AV_NETBIOS_DOMAIN_NAME = 0x0002; + + /** + * Attribute type: The fully qualified domain name (FQDN (1)) of the computer. + * The name MUST be in Unicode, and is not null-terminated. + */ + public final static int MSV_AV_DNS_COMPUTER_NAME = 0x0003; + + /** + * Attribute type: The FQDN of the domain. The name MUST be in Unicode, and is + * not null-terminated. + */ + public final static int MSV_AV_DNS_DOMAIN_NAME = 0x0004; + + /** + * Attribute type: The FQDN of the forest. The name MUST be in Unicode, and is + * not null-terminated. + */ + public final static int MSV_AV_DNS_TREE_NAME = 0x0005; + + /** + * Attribute type: A 32-bit value indicating server or client configuration. + * + *
    • 0x00000001: indicates to the client that the account authentication is + * constrained. + * + *
    • 0x00000002: indicates that the client is providing message integrity in + * the MIC field (section 2.2.1.3) in the AUTHENTICATE_MESSAGE. + * + *
    • 0x00000004: indicates that the client is providing a target SPN + * generated from an untrusted source. + **/ + public final static int MSV_AV_FLAGS = 0x0006; + + public static final int MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK = 0x00000002; + + /** + * Attribute type: A FILETIME structure ([MS-DTYP] section 2.3.3) in + * little-endian byte order that contains the server local time. + */ + public final static int MSV_AV_TIMESTAMP = 0x0007; + + /** + * Attribute type: A Single_Host_Data (section 2.2.2.2) structure. The Value + * field contains a platform-specific blob, as well as a MachineID created at + * computer startup to identify the calling machine.<15> + */ + public final static int MSV_AV_SINGLE_HOST = 0x0008; + + /** + * Attribute type: The SPN of the target server. The name MUST be in Unicode + * and is not null-terminated.<16> + */ + public final static int MSV_AV_TARGET_NAME = 0x0009; + + /** + * Attribute type: A channel bindings hash. The Value field contains an MD5 + * hash ([RFC4121] section 4.1.1.2) of a gss_channel_bindings_struct + * ([RFC2744] section 3.11). An all-zero value of the hash is used to indicate + * absence of channel bindings. + */ + public final static int MSV_AV_CHANNEL_BINDINGS = 0x000A; + + /** + * Signature of NTLMSSP blob. + */ + public static final String NTLMSSP = "NTLMSSP"; + + public static final String GSS_RDP_SERVICE_NAME = "TERMSRV"; + + /** + * NTLM message type: NEGOTIATE. + */ + public static final int NEGOTIATE = 0x00000001; + + /** + * NTLM message type: CHALLENGE. + */ + public static final int CHALLENGE = 0x00000002; + + /** + * NTLM message type: NTLMSSP_AUTH. + */ + public static final int NTLMSSP_AUTH = 0x00000003; + + public static final String OID_SPNEGO = "1.3.6.1.5.5.2"; + + public static final String OID_KERBEROS5 = "1.2.840.113554.1.2.2"; + public static final String OID_MSKERBEROS5 = "1.2.840.48018.1.2.2"; + + public static final String OID_KRB5USERTOUSER = "1.2.840.113554.1.2.2.3"; + + public static final String OID_NTLMSSP = "1.3.6.1.4.1.311.2.2.10"; + + /** + * Magic constant used in calculation of Lan Manager response. + */ + public static final String LM_MAGIC = "KGS!@#$%"; + + /** + * Magic constant used in generation of client signing key. + */ + public static final String CLIENT_SIGN_MAGIC = "session key to client-to-server signing key magic constant"; + + /** + * Magic constant used in generation of client sealing key. + */ + public static final String CLIENT_SEAL_MAGIC = "session key to client-to-server sealing key magic constant"; + + public static final String SERVER_SIGN_MAGIC = "session key to server-to-client signing key magic constant"; + public static final String SERVER_SEAL_MAGIC = "session key to server-to-client sealing key magic constant"; + + /** + * In Windows XP, Windows Server 2003, Windows Vista, Windows Server 2008, + * Windows 7, Windows Server 2008 R2, Windows 8, Windows Server 2012, Windows + * 8.1, and Windows Server 2012 R2, the maximum lifetime of challenge is 36 hours. + */ + public static final int CHALLENGE_MAX_LIFETIME = 36 * 60 * 60; +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/NtlmState.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/NtlmState.java new file mode 100755 index 00000000000..248f16654dd --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/NtlmState.java @@ -0,0 +1,887 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.ntlmssp; + +import java.util.Arrays; + +import javax.crypto.Cipher; + +import rdpclient.rdp.RdpConstants; +import streamer.ByteBuffer; + +public class NtlmState implements NtlmConstants { + + /** + * The set of configuration flags (section 2.2.2.5) that specifies the + * negotiated capabilities of the client and server for the current NTLM + * session. + */ + public NegoFlags negotiatedFlags; + + /** + * Target Information extracted from Type2 server response. + */ + public byte[] serverTargetInfo; + + /** + * Challenge extracted from Type2 server response. + */ + public byte[] serverChallenge; + + public byte[] clientChallenge; + + public byte[] keyExchangeKey; + + /** + * A 128-bit (16-byte) session key used to derive ClientSigningKey, + * ClientSealingKey, ServerSealingKey, and ServerSigningKey. + */ + public byte[] exportedSessionKey; + + /** + * The signing key used by the client to sign messages and used by the server + * to verify signed client messages. It is generated after the client is + * authenticated by the server and is not passed over the wire. + */ + public byte[] clientSigningKey; + + /** + * The sealing key used by the client to seal messages and used by the server + * to unseal client messages. It is generated after the client is + * authenticated by the server and is not passed over the wire. + */ + public byte[] clientSealingKey; + + public byte[] encryptedRandomSessionKey; + + public byte[] sessionBaseKey; + + public byte[] responseKeyNT; + + public byte[] ntProofStr1; + + public String domain; + + public String user; + + public String workstation; + + public String password; + + public String serverNetbiosDomainName; + + public String serverNetbiosComputerName; + + public String serverDnsDomainName; + + public String serverDnsComputerName; + + public String serverDnsTreeName; + + public String serverTargetName; + + public byte[] serverTimestamp; + public byte[] clientChallengeTimestamp; + + public byte[] lmChallengeResponse; + + public byte[] ntChallengeResponse; + + public byte[] ntProofStr2; + + public byte[] randomSessionKey; + + public byte[] serverSigningKey; + + public byte[] serverSealingKey; + + public byte[] sendSigningKey; + + public byte[] recvSigningKey; + + public byte[] sendSealingKey; + + public byte[] recvSealingKey; + + public Cipher sendRc4Seal; + + public Cipher recvRc4Seal; + + public byte[] messageIntegrityCheck; + + public byte[] negotiateMessage; + + public byte[] challengeMessage; + + public byte[] authenticateMessage; + + /** + * A 4-byte sequence number. + * + * In the case of connection-oriented authentication, the SeqNum parameter + * MUST start at 0 and is incremented by one for each message sent. The + * receiver expects the first received message to have SeqNum equal to 0, and + * to be one greater for each subsequent message received. If a received + * message does not contain the expected SeqNum, an error MUST be returned to + * the receiving application, and SeqNum is not incremented. + */ + public int sendSeqNum; + public int recvSeqNum; + + public byte[] authenticateTargetInfo; + + public String servicePrincipalName; + + private byte[] channelBindingsHash = new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + + public byte[] subjectPublicKey; + + public byte[] ntlm_generate_timestamp() { + clientChallengeTimestamp = serverTimestamp; + return clientChallengeTimestamp; + } + + /** + * MD4(UNICODE(Password)) + */ + public byte[] NTOWFv1W(String password) { + return CryptoAlgos.MD4(password.getBytes(RdpConstants.CHARSET_16)); + } + + public void testNTOWFv1W() { + byte[] expected = new byte[] {(byte)0x25, (byte)0xf3, (byte)0x39, (byte)0xc9, (byte)0x86, (byte)0xb5, (byte)0xc2, (byte)0x6f, (byte)0xdc, + (byte)0xab, (byte)0x91, (byte)0x34, (byte)0x93, (byte)0xa2, (byte)0x18, (byte)0x2a}; + byte[] actual = NTOWFv1W("R2Preview!"); + if (!Arrays.equals(expected, actual)) + throw new RuntimeException("Incorrect result.\nExpected:\n" + new ByteBuffer(expected).toPlainHexString() + "\n actual:\n" + + new ByteBuffer(actual).toPlainHexString() + "."); + } + + /** + * HMAC_MD5(NTOWFv1W(Password), UNICODE(ConcatenationOf(UpperCase(User), + * Domain))) + */ + public byte[] NTOWFv2W(String password, String user, String domain) { + return CryptoAlgos.HMAC_MD5(NTOWFv1W(password), (user.toUpperCase() + domain).getBytes(RdpConstants.CHARSET_16)); + } + + public void testNTOWFv2W() { + byte[] expected = new byte[] {(byte)0x5f, (byte)0xcc, (byte)0x4c, (byte)0x48, (byte)0x74, (byte)0x6b, (byte)0x94, (byte)0xce, (byte)0xb7, + (byte)0xae, (byte)0xf1, (byte)0x0d, (byte)0xc9, (byte)0x11, (byte)0x22, (byte)0x8f,}; + byte[] actual = NTOWFv2W("R2Preview!", "Administrator", "workgroup"); + if (!Arrays.equals(expected, actual)) + throw new RuntimeException("Incorrect result.\nExpected:\n" + new ByteBuffer(expected).toPlainHexString() + "\n actual:\n" + + new ByteBuffer(actual).toPlainHexString() + "."); + } + + public byte[] ntlm_compute_ntlm_v2_hash() { + return NTOWFv2W(password, user, domain); + } + + public byte[] ntlm_generate_client_challenge() { + if (clientChallenge == null) { + clientChallenge = CryptoAlgos.NONCE(8); + } + return clientChallenge; + } + + public byte[] ntlm_compute_lm_v2_response() { + if (lmChallengeResponse == null) { + + byte[] ntlm_v2_hash = ntlm_compute_ntlm_v2_hash(); + + ntlm_generate_client_challenge(); + + byte[] challenges = CryptoAlgos.concatenationOf(serverChallenge, clientChallenge); + + lmChallengeResponse = CryptoAlgos.concatenationOf(CryptoAlgos.HMAC_MD5(ntlm_v2_hash, challenges), clientChallenge); + } + + return lmChallengeResponse; + } + + public void testComputeLmV2Response() { + serverChallenge = new byte[] {(byte)0x34, (byte)0xe4, (byte)0x4c, (byte)0xd5, (byte)0x75, (byte)0xe3, (byte)0x43, (byte)0x0f}; + clientChallenge = new byte[] {1, 2, 3, 4, 5, 6, 7, 8}; + password = "R2Preview!"; + user = "Administrator"; + domain = "workgroup"; + byte[] expected = new byte[] {(byte)0xa8, (byte)0xae, (byte)0xd7, (byte)0x46, (byte)0x06, (byte)0x32, (byte)0x02, (byte)0x35, (byte)0x1d, + (byte)0x95, (byte)0x99, (byte)0x36, (byte)0x20, (byte)0x36, (byte)0xac, (byte)0xc3, (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, + (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08,}; + byte[] actual = ntlm_compute_lm_v2_response(); + if (!Arrays.equals(expected, actual)) + throw new RuntimeException("Incorrect result.\nExpected:\n" + new ByteBuffer(expected).toPlainHexString() + "\n actual:\n" + + new ByteBuffer(actual).toPlainHexString() + "."); + } + + public byte[] computeNtProofStr(byte[] ntlmV2Hash, byte[] data) { + return CryptoAlgos.HMAC_MD5(ntlmV2Hash, data); + } + + public void testComputeNtProofStr() { + byte[] ntlm_v2_hash = new byte[] {(byte)0x5f, (byte)0xcc, (byte)0x4c, (byte)0x48, (byte)0x74, (byte)0x6b, (byte)0x94, (byte)0xce, (byte)0xb7, + (byte)0xae, (byte)0xf1, (byte)0x0d, (byte)0xc9, (byte)0x11, (byte)0x22, (byte)0x8f,}; + byte[] data = new byte[] {(byte)0x4a, (byte)0x25, (byte)0x50, (byte)0xa5, (byte)0x11, (byte)0x9b, (byte)0xd6, (byte)0x16, (byte)0x01, + (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xa0, (byte)0xe8, (byte)0x85, (byte)0x2c, + (byte)0xe4, (byte)0xc9, (byte)0xce, (byte)0x01, (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07, + (byte)0x08, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x02, (byte)0x00, (byte)0x1e, (byte)0x00, (byte)0x57, (byte)0x00, + (byte)0x49, (byte)0x00, (byte)0x4e, (byte)0x00, (byte)0x2d, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x4f, (byte)0x00, (byte)0x34, + (byte)0x00, (byte)0x31, (byte)0x00, (byte)0x39, (byte)0x00, (byte)0x42, (byte)0x00, (byte)0x32, (byte)0x00, (byte)0x4c, (byte)0x00, + (byte)0x53, (byte)0x00, (byte)0x52, (byte)0x00, (byte)0x30, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x1e, (byte)0x00, (byte)0x57, + (byte)0x00, (byte)0x49, (byte)0x00, (byte)0x4e, (byte)0x00, (byte)0x2d, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x4f, (byte)0x00, + (byte)0x34, (byte)0x00, (byte)0x31, (byte)0x00, (byte)0x39, (byte)0x00, (byte)0x42, (byte)0x00, (byte)0x32, (byte)0x00, (byte)0x4c, + (byte)0x00, (byte)0x53, (byte)0x00, (byte)0x52, (byte)0x00, (byte)0x30, (byte)0x00, (byte)0x04, (byte)0x00, (byte)0x1e, (byte)0x00, + (byte)0x57, (byte)0x00, (byte)0x49, (byte)0x00, (byte)0x4e, (byte)0x00, (byte)0x2d, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x4f, + (byte)0x00, (byte)0x34, (byte)0x00, (byte)0x31, (byte)0x00, (byte)0x39, (byte)0x00, (byte)0x42, (byte)0x00, (byte)0x32, (byte)0x00, + (byte)0x4c, (byte)0x00, (byte)0x53, (byte)0x00, (byte)0x52, (byte)0x00, (byte)0x30, (byte)0x00, (byte)0x03, (byte)0x00, (byte)0x1e, + (byte)0x00, (byte)0x57, (byte)0x00, (byte)0x49, (byte)0x00, (byte)0x4e, (byte)0x00, (byte)0x2d, (byte)0x00, (byte)0x4c, (byte)0x00, + (byte)0x4f, (byte)0x00, (byte)0x34, (byte)0x00, (byte)0x31, (byte)0x00, (byte)0x39, (byte)0x00, (byte)0x42, (byte)0x00, (byte)0x32, + (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x53, (byte)0x00, (byte)0x52, (byte)0x00, (byte)0x30, (byte)0x00, (byte)0x07, (byte)0x00, + (byte)0x08, (byte)0x00, (byte)0xa0, (byte)0xe8, (byte)0x85, (byte)0x2c, (byte)0xe4, (byte)0xc9, (byte)0xce, (byte)0x01, (byte)0x06, + (byte)0x00, (byte)0x04, (byte)0x00, (byte)0x02, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x0a, (byte)0x00, (byte)0x10, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x09, (byte)0x00, (byte)0x26, (byte)0x00, (byte)0x54, (byte)0x00, + (byte)0x45, (byte)0x00, (byte)0x52, (byte)0x00, (byte)0x4d, (byte)0x00, (byte)0x53, (byte)0x00, (byte)0x52, (byte)0x00, (byte)0x56, + (byte)0x00, (byte)0x2f, (byte)0x00, (byte)0x31, (byte)0x00, (byte)0x39, (byte)0x00, (byte)0x32, (byte)0x00, (byte)0x2e, (byte)0x00, + (byte)0x31, (byte)0x00, (byte)0x36, (byte)0x00, (byte)0x38, (byte)0x00, (byte)0x2e, (byte)0x00, (byte)0x31, (byte)0x00, (byte)0x2e, + (byte)0x00, (byte)0x33, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00,}; + + byte[] expected = new byte[] {(byte)0x19, (byte)0x4b, (byte)0xeb, (byte)0xad, (byte)0xda, (byte)0x24, (byte)0xd5, (byte)0x96, (byte)0x85, + (byte)0x2e, (byte)0x24, (byte)0x94, (byte)0xd6, (byte)0x4a, (byte)0xb8, (byte)0x5e,}; + byte[] actual = computeNtProofStr(ntlm_v2_hash, data); + if (!Arrays.equals(expected, actual)) + throw new RuntimeException("Incorrect result.\nExpected:\n" + new ByteBuffer(expected).toPlainHexString() + "\n actual:\n" + + new ByteBuffer(actual).toPlainHexString() + "."); + } + + public byte[] computeSessionBaseKey(byte[] ntlmV2Hash, byte[] ntProofStr) { + return CryptoAlgos.HMAC_MD5(ntlmV2Hash, ntProofStr); + } + + public void testComputeSessionBaseKey() { + byte[] ntlm_v2_hash = new byte[] {(byte)0x5f, (byte)0xcc, (byte)0x4c, (byte)0x48, (byte)0x74, (byte)0x6b, (byte)0x94, (byte)0xce, (byte)0xb7, + (byte)0xae, (byte)0xf1, (byte)0x0d, (byte)0xc9, (byte)0x11, (byte)0x22, (byte)0x8f,}; + byte[] nt_proof_str = new byte[] {(byte)0x19, (byte)0x4b, (byte)0xeb, (byte)0xad, (byte)0xda, (byte)0x24, (byte)0xd5, (byte)0x96, (byte)0x85, + (byte)0x2e, (byte)0x24, (byte)0x94, (byte)0xd6, (byte)0x4a, (byte)0xb8, (byte)0x5e,}; + + byte[] expected = new byte[] {(byte)0x8e, (byte)0x0f, (byte)0xdd, (byte)0x12, (byte)0x4c, (byte)0x3b, (byte)0x11, (byte)0x7f, (byte)0x22, + (byte)0xb9, (byte)0x4b, (byte)0x59, (byte)0x52, (byte)0xbc, (byte)0xa7, (byte)0x18,}; + byte[] actual = computeSessionBaseKey(ntlm_v2_hash, nt_proof_str); + if (!Arrays.equals(expected, actual)) + throw new RuntimeException("Incorrect result.\nExpected:\n" + new ByteBuffer(expected).toPlainHexString() + "\n actual:\n" + + new ByteBuffer(actual).toPlainHexString() + "."); + } + + public String generateServicePrincipalName(String serverHostName) { + servicePrincipalName = GSS_RDP_SERVICE_NAME + "/" + serverHostName; + return servicePrincipalName; + } + + public void writeAVPair(ByteBuffer buf, int avPairType, byte[] value) { + if (value != null) { + buf.writeShortLE(avPairType); + buf.writeShortLE(value.length); + buf.writeBytes(value); + } + } + + public void writeAVPair(ByteBuffer buf, int avPairType, String value) { + if (value != null) { + writeAVPair(buf, avPairType, value.getBytes(RdpConstants.CHARSET_16)); + } + } + + public byte[] ntlm_construct_authenticate_target_info() { + ByteBuffer buf = new ByteBuffer(4096); + + writeAVPair(buf, MSV_AV_NETBIOS_DOMAIN_NAME, serverNetbiosDomainName); + + writeAVPair(buf, MSV_AV_NETBIOS_COMPUTER_NAME, serverNetbiosComputerName); + + writeAVPair(buf, MSV_AV_DNS_DOMAIN_NAME, serverDnsDomainName); + + writeAVPair(buf, MSV_AV_DNS_COMPUTER_NAME, serverDnsComputerName); + + writeAVPair(buf, MSV_AV_DNS_TREE_NAME, serverDnsTreeName); + + writeAVPair(buf, MSV_AV_TIMESTAMP, serverTimestamp); + + byte[] flags = new byte[] {(byte)MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK, 0, 0, 0}; + writeAVPair(buf, MSV_AV_FLAGS, flags); + + writeAVPair(buf, MSV_AV_CHANNEL_BINDINGS, channelBindingsHash); + + writeAVPair(buf, MSV_AV_TARGET_NAME, servicePrincipalName); + + writeAVPair(buf, MSV_AV_EOL, ""); + // DEBUG: put EOL 4 times, for compatibility with FreeRDP output + //*DEBUG*/writeAVPair(buf, MSV_AV_EOL, ""); + //*DEBUG*/writeAVPair(buf, MSV_AV_EOL, ""); + //*DEBUG*/writeAVPair(buf, MSV_AV_EOL, ""); + buf.trimAtCursor(); + + authenticateTargetInfo = buf.toByteArray(); + buf.unref(); + + return authenticateTargetInfo; + } + + public void testConstructAuthenticateTargetInfo() { + serverNetbiosDomainName = "WIN-LO419B2LSR0"; + serverNetbiosComputerName = "WIN-LO419B2LSR0"; + serverDnsDomainName = "WIN-LO419B2LSR0"; + serverDnsComputerName = "WIN-LO419B2LSR0"; + serverTimestamp = new byte[] {(byte)0xa0, (byte)0xe8, (byte)0x85, (byte)0x2c, (byte)0xe4, (byte)0xc9, (byte)0xce, (byte)0x01,}; + servicePrincipalName = "TERMSRV/192.168.1.3"; + + byte[] expected = new byte[] {(byte)0x02, (byte)0x00, (byte)0x1e, (byte)0x00, (byte)0x57, (byte)0x00, (byte)0x49, (byte)0x00, (byte)0x4e, + (byte)0x00, (byte)0x2d, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x4f, (byte)0x00, (byte)0x34, (byte)0x00, (byte)0x31, (byte)0x00, + (byte)0x39, (byte)0x00, (byte)0x42, (byte)0x00, (byte)0x32, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x53, (byte)0x00, (byte)0x52, + (byte)0x00, (byte)0x30, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x1e, (byte)0x00, (byte)0x57, (byte)0x00, (byte)0x49, (byte)0x00, + (byte)0x4e, (byte)0x00, (byte)0x2d, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x4f, (byte)0x00, (byte)0x34, (byte)0x00, (byte)0x31, + (byte)0x00, (byte)0x39, (byte)0x00, (byte)0x42, (byte)0x00, (byte)0x32, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x53, (byte)0x00, + (byte)0x52, (byte)0x00, (byte)0x30, (byte)0x00, (byte)0x04, (byte)0x00, (byte)0x1e, (byte)0x00, (byte)0x57, (byte)0x00, (byte)0x49, + (byte)0x00, (byte)0x4e, (byte)0x00, (byte)0x2d, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x4f, (byte)0x00, (byte)0x34, (byte)0x00, + (byte)0x31, (byte)0x00, (byte)0x39, (byte)0x00, (byte)0x42, (byte)0x00, (byte)0x32, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x53, + (byte)0x00, (byte)0x52, (byte)0x00, (byte)0x30, (byte)0x00, (byte)0x03, (byte)0x00, (byte)0x1e, (byte)0x00, (byte)0x57, (byte)0x00, + (byte)0x49, (byte)0x00, (byte)0x4e, (byte)0x00, (byte)0x2d, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x4f, (byte)0x00, (byte)0x34, + (byte)0x00, (byte)0x31, (byte)0x00, (byte)0x39, (byte)0x00, (byte)0x42, (byte)0x00, (byte)0x32, (byte)0x00, (byte)0x4c, (byte)0x00, + (byte)0x53, (byte)0x00, (byte)0x52, (byte)0x00, (byte)0x30, (byte)0x00, (byte)0x07, (byte)0x00, (byte)0x08, (byte)0x00, (byte)0xa0, + (byte)0xe8, (byte)0x85, (byte)0x2c, (byte)0xe4, (byte)0xc9, (byte)0xce, (byte)0x01, (byte)0x06, (byte)0x00, (byte)0x04, (byte)0x00, + (byte)0x02, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x0a, (byte)0x00, (byte)0x10, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x09, (byte)0x00, (byte)0x26, (byte)0x00, (byte)0x54, (byte)0x00, (byte)0x45, (byte)0x00, (byte)0x52, + (byte)0x00, (byte)0x4d, (byte)0x00, (byte)0x53, (byte)0x00, (byte)0x52, (byte)0x00, (byte)0x56, (byte)0x00, (byte)0x2f, (byte)0x00, + (byte)0x31, (byte)0x00, (byte)0x39, (byte)0x00, (byte)0x32, (byte)0x00, (byte)0x2e, (byte)0x00, (byte)0x31, (byte)0x00, (byte)0x36, + (byte)0x00, (byte)0x38, (byte)0x00, (byte)0x2e, (byte)0x00, (byte)0x31, (byte)0x00, (byte)0x2e, (byte)0x00, (byte)0x33, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00,}; + byte[] actual = ntlm_construct_authenticate_target_info(); + if (!Arrays.equals(expected, actual)) + throw new RuntimeException("Incorrect result.\nExpected:\n" + new ByteBuffer(expected).toPlainHexString() + "\n actual:\n" + + new ByteBuffer(actual).toPlainHexString() + "."); + } + + public byte[] ntlm_compute_ntlm_v2_response() { + ByteBuffer buf = new ByteBuffer(4096); + + byte[] ntlm_v2_hash = ntlm_compute_ntlm_v2_hash(); + + buf.writeByte(0x1); // RespType + buf.writeByte(0x1); // HighRespType + buf.writeShort(0); // reserved + buf.writeInt(0); // reserved + buf.writeBytes(clientChallengeTimestamp); // Timestamp, 8 bytes + buf.writeBytes(clientChallenge); // Client nonce, 8 bytes + buf.writeInt(0); // reserved + buf.writeBytes(authenticateTargetInfo); // Target Info block + buf.trimAtCursor(); + byte[] bufBytes = buf.toByteArray(); + buf.unref(); + + ntProofStr2 = computeNtProofStr(ntlm_v2_hash, CryptoAlgos.concatenationOf(serverChallenge, bufBytes)); + + ntChallengeResponse = CryptoAlgos.concatenationOf(ntProofStr2, bufBytes); + + sessionBaseKey = computeSessionBaseKey(ntlm_v2_hash, ntProofStr2); + + return ntChallengeResponse; + } + + public void testComputeNtlmV2Response() { + serverChallenge = new byte[] {(byte)0x4a, (byte)0x25, (byte)0x50, (byte)0xa5, (byte)0x11, (byte)0x9b, (byte)0xd6, (byte)0x16,}; + clientChallenge = new byte[] {1, 2, 3, 4, 5, 6, 7, 8}; + password = "R2Preview!"; + user = "Administrator"; + domain = "workgroup"; + clientChallengeTimestamp = new byte[] {(byte)0xa0, (byte)0xe8, (byte)0x85, (byte)0x2c, (byte)0xe4, (byte)0xc9, (byte)0xce, (byte)0x01,}; + authenticateTargetInfo = new byte[] {(byte)0x02, (byte)0x00, (byte)0x1e, (byte)0x00, (byte)0x57, (byte)0x00, (byte)0x49, (byte)0x00, (byte)0x4e, + (byte)0x00, (byte)0x2d, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x4f, (byte)0x00, (byte)0x34, (byte)0x00, (byte)0x31, (byte)0x00, + (byte)0x39, (byte)0x00, (byte)0x42, (byte)0x00, (byte)0x32, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x53, (byte)0x00, (byte)0x52, + (byte)0x00, (byte)0x30, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x1e, (byte)0x00, (byte)0x57, (byte)0x00, (byte)0x49, (byte)0x00, + (byte)0x4e, (byte)0x00, (byte)0x2d, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x4f, (byte)0x00, (byte)0x34, (byte)0x00, (byte)0x31, + (byte)0x00, (byte)0x39, (byte)0x00, (byte)0x42, (byte)0x00, (byte)0x32, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x53, (byte)0x00, + (byte)0x52, (byte)0x00, (byte)0x30, (byte)0x00, (byte)0x04, (byte)0x00, (byte)0x1e, (byte)0x00, (byte)0x57, (byte)0x00, (byte)0x49, + (byte)0x00, (byte)0x4e, (byte)0x00, (byte)0x2d, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x4f, (byte)0x00, (byte)0x34, (byte)0x00, + (byte)0x31, (byte)0x00, (byte)0x39, (byte)0x00, (byte)0x42, (byte)0x00, (byte)0x32, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x53, + (byte)0x00, (byte)0x52, (byte)0x00, (byte)0x30, (byte)0x00, (byte)0x03, (byte)0x00, (byte)0x1e, (byte)0x00, (byte)0x57, (byte)0x00, + (byte)0x49, (byte)0x00, (byte)0x4e, (byte)0x00, (byte)0x2d, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x4f, (byte)0x00, (byte)0x34, + (byte)0x00, (byte)0x31, (byte)0x00, (byte)0x39, (byte)0x00, (byte)0x42, (byte)0x00, (byte)0x32, (byte)0x00, (byte)0x4c, (byte)0x00, + (byte)0x53, (byte)0x00, (byte)0x52, (byte)0x00, (byte)0x30, (byte)0x00, (byte)0x07, (byte)0x00, (byte)0x08, (byte)0x00, (byte)0xa0, + (byte)0xe8, (byte)0x85, (byte)0x2c, (byte)0xe4, (byte)0xc9, (byte)0xce, (byte)0x01, (byte)0x06, (byte)0x00, (byte)0x04, (byte)0x00, + (byte)0x02, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x0a, (byte)0x00, (byte)0x10, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x09, (byte)0x00, (byte)0x26, (byte)0x00, (byte)0x54, (byte)0x00, (byte)0x45, (byte)0x00, (byte)0x52, + (byte)0x00, (byte)0x4d, (byte)0x00, (byte)0x53, (byte)0x00, (byte)0x52, (byte)0x00, (byte)0x56, (byte)0x00, (byte)0x2f, (byte)0x00, + (byte)0x31, (byte)0x00, (byte)0x39, (byte)0x00, (byte)0x32, (byte)0x00, (byte)0x2e, (byte)0x00, (byte)0x31, (byte)0x00, (byte)0x36, + (byte)0x00, (byte)0x38, (byte)0x00, (byte)0x2e, (byte)0x00, (byte)0x31, (byte)0x00, (byte)0x2e, (byte)0x00, (byte)0x33, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00,}; + + byte[] expected = new byte[] {(byte)0x19, (byte)0x4b, (byte)0xeb, (byte)0xad, (byte)0xda, (byte)0x24, (byte)0xd5, (byte)0x96, (byte)0x85, + (byte)0x2e, (byte)0x24, (byte)0x94, (byte)0xd6, (byte)0x4a, (byte)0xb8, (byte)0x5e, (byte)0x01, (byte)0x01, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xa0, (byte)0xe8, (byte)0x85, (byte)0x2c, (byte)0xe4, (byte)0xc9, (byte)0xce, + (byte)0x01, (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x02, (byte)0x00, (byte)0x1e, (byte)0x00, (byte)0x57, (byte)0x00, (byte)0x49, (byte)0x00, (byte)0x4e, + (byte)0x00, (byte)0x2d, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x4f, (byte)0x00, (byte)0x34, (byte)0x00, (byte)0x31, (byte)0x00, + (byte)0x39, (byte)0x00, (byte)0x42, (byte)0x00, (byte)0x32, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x53, (byte)0x00, (byte)0x52, + (byte)0x00, (byte)0x30, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x1e, (byte)0x00, (byte)0x57, (byte)0x00, (byte)0x49, (byte)0x00, + (byte)0x4e, (byte)0x00, (byte)0x2d, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x4f, (byte)0x00, (byte)0x34, (byte)0x00, (byte)0x31, + (byte)0x00, (byte)0x39, (byte)0x00, (byte)0x42, (byte)0x00, (byte)0x32, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x53, (byte)0x00, + (byte)0x52, (byte)0x00, (byte)0x30, (byte)0x00, (byte)0x04, (byte)0x00, (byte)0x1e, (byte)0x00, (byte)0x57, (byte)0x00, (byte)0x49, + (byte)0x00, (byte)0x4e, (byte)0x00, (byte)0x2d, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x4f, (byte)0x00, (byte)0x34, (byte)0x00, + (byte)0x31, (byte)0x00, (byte)0x39, (byte)0x00, (byte)0x42, (byte)0x00, (byte)0x32, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x53, + (byte)0x00, (byte)0x52, (byte)0x00, (byte)0x30, (byte)0x00, (byte)0x03, (byte)0x00, (byte)0x1e, (byte)0x00, (byte)0x57, (byte)0x00, + (byte)0x49, (byte)0x00, (byte)0x4e, (byte)0x00, (byte)0x2d, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x4f, (byte)0x00, (byte)0x34, + (byte)0x00, (byte)0x31, (byte)0x00, (byte)0x39, (byte)0x00, (byte)0x42, (byte)0x00, (byte)0x32, (byte)0x00, (byte)0x4c, (byte)0x00, + (byte)0x53, (byte)0x00, (byte)0x52, (byte)0x00, (byte)0x30, (byte)0x00, (byte)0x07, (byte)0x00, (byte)0x08, (byte)0x00, (byte)0xa0, + (byte)0xe8, (byte)0x85, (byte)0x2c, (byte)0xe4, (byte)0xc9, (byte)0xce, (byte)0x01, (byte)0x06, (byte)0x00, (byte)0x04, (byte)0x00, + (byte)0x02, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x0a, (byte)0x00, (byte)0x10, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x09, (byte)0x00, (byte)0x26, (byte)0x00, (byte)0x54, (byte)0x00, (byte)0x45, (byte)0x00, (byte)0x52, + (byte)0x00, (byte)0x4d, (byte)0x00, (byte)0x53, (byte)0x00, (byte)0x52, (byte)0x00, (byte)0x56, (byte)0x00, (byte)0x2f, (byte)0x00, + (byte)0x31, (byte)0x00, (byte)0x39, (byte)0x00, (byte)0x32, (byte)0x00, (byte)0x2e, (byte)0x00, (byte)0x31, (byte)0x00, (byte)0x36, + (byte)0x00, (byte)0x38, (byte)0x00, (byte)0x2e, (byte)0x00, (byte)0x31, (byte)0x00, (byte)0x2e, (byte)0x00, (byte)0x33, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00,}; + byte[] actual = ntlm_compute_ntlm_v2_response(); + if (!Arrays.equals(expected, actual)) + throw new RuntimeException("Incorrect result.\nExpected:\n" + new ByteBuffer(expected).toPlainHexString() + "\n actual:\n" + + new ByteBuffer(actual).toPlainHexString() + "."); + } + + public byte[] ntlm_generate_key_exchange_key() { + keyExchangeKey = sessionBaseKey; + return keyExchangeKey; + } + + public byte[] ntlm_generate_random_session_key() { + randomSessionKey = CryptoAlgos.NONCE(16); + return randomSessionKey; + } + + public byte[] ntlm_generate_exported_session_key() { + exportedSessionKey = randomSessionKey; + return exportedSessionKey; + } + + public byte[] ntlm_encrypt_random_session_key() { + encryptedRandomSessionKey = CryptoAlgos.RC4K(keyExchangeKey, randomSessionKey); + return encryptedRandomSessionKey; + } + + public void testComputeEncryptedRandomSessionKey() { + keyExchangeKey = new byte[] {(byte)0x8e, (byte)0x0f, (byte)0xdd, (byte)0x12, (byte)0x4c, (byte)0x3b, (byte)0x11, (byte)0x7f, (byte)0x22, + (byte)0xb9, (byte)0x4b, (byte)0x59, (byte)0x52, (byte)0xbc, (byte)0xa7, (byte)0x18,}; + randomSessionKey = new byte[] {(byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08, (byte)0x09, + (byte)0x0a, (byte)0x0b, (byte)0x0c, (byte)0x0d, (byte)0x0e, (byte)0x0f, (byte)0x10,}; + + byte[] expected = new byte[] {(byte)0xe4, (byte)0xe9, (byte)0xc2, (byte)0xad, (byte)0x41, (byte)0x02, (byte)0x2f, (byte)0x3c, (byte)0xf9, + (byte)0x4c, (byte)0x72, (byte)0x84, (byte)0xc5, (byte)0x2a, (byte)0x7c, (byte)0x6f,}; + byte[] actual = ntlm_encrypt_random_session_key(); + + if (!Arrays.equals(expected, actual)) + throw new RuntimeException("Incorrect result.\nExpected:\n" + new ByteBuffer(expected).toPlainHexString() + "\n actual:\n" + + new ByteBuffer(actual).toPlainHexString() + "."); + } + + public byte[] ntlm_generate_signing_key(String signMagic) { + return CryptoAlgos.MD5(CryptoAlgos.concatenationOf(exportedSessionKey, signMagic.getBytes(RdpConstants.CHARSET_8), new byte[] {0})); + } + + public void testGenerateSigningKey() { + exportedSessionKey = new byte[] {(byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08, (byte)0x09, + (byte)0x0a, (byte)0x0b, (byte)0x0c, (byte)0x0d, (byte)0x0e, (byte)0x0f, (byte)0x10,}; + byte[] expected = new byte[] {(byte)0xf6, (byte)0xae, (byte)0x96, (byte)0xcb, (byte)0x05, (byte)0xe2, (byte)0xab, (byte)0x54, (byte)0xf6, + (byte)0xdd, (byte)0x59, (byte)0xf3, (byte)0xc9, (byte)0xd9, (byte)0xa0, (byte)0x43,}; + byte[] actual = ntlm_generate_signing_key(CLIENT_SIGN_MAGIC); + + if (!Arrays.equals(expected, actual)) + throw new RuntimeException("Incorrect result.\nExpected:\n" + new ByteBuffer(expected).toPlainHexString() + "\n actual:\n" + + new ByteBuffer(actual).toPlainHexString() + "."); + } + + public byte[] ntlm_generate_client_signing_key() { + clientSigningKey = ntlm_generate_signing_key(CLIENT_SIGN_MAGIC); + return clientSigningKey; + } + + public void testGenerateClientSigningKey() { + exportedSessionKey = new byte[] {(byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08, (byte)0x09, + (byte)0x0a, (byte)0x0b, (byte)0x0c, (byte)0x0d, (byte)0x0e, (byte)0x0f, (byte)0x10,}; + byte[] expected = new byte[] {(byte)0xf6, (byte)0xae, (byte)0x96, (byte)0xcb, (byte)0x05, (byte)0xe2, (byte)0xab, (byte)0x54, (byte)0xf6, + (byte)0xdd, (byte)0x59, (byte)0xf3, (byte)0xc9, (byte)0xd9, (byte)0xa0, (byte)0x43,}; + byte[] actual = ntlm_generate_client_signing_key(); + + if (!Arrays.equals(expected, actual)) + throw new RuntimeException("Incorrect result.\nExpected:\n" + new ByteBuffer(expected).toPlainHexString() + "\n actual:\n" + + new ByteBuffer(actual).toPlainHexString() + "."); + } + + public byte[] ntlm_generate_server_signing_key() { + serverSigningKey = ntlm_generate_signing_key(SERVER_SIGN_MAGIC); + return serverSigningKey; + } + + public void testGenerateServerSigningKey() { + exportedSessionKey = new byte[] {(byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08, (byte)0x09, + (byte)0x0a, (byte)0x0b, (byte)0x0c, (byte)0x0d, (byte)0x0e, (byte)0x0f, (byte)0x10,}; + byte[] expected = new byte[] {(byte)0xb6, (byte)0x58, (byte)0xc5, (byte)0x98, (byte)0x7a, (byte)0x25, (byte)0xf8, (byte)0x6e, (byte)0xd8, + (byte)0xe5, (byte)0x6c, (byte)0xe9, (byte)0x3e, (byte)0x3c, (byte)0xc0, (byte)0x88,}; + byte[] actual = ntlm_generate_server_signing_key(); + + if (!Arrays.equals(expected, actual)) + throw new RuntimeException("Incorrect result.\nExpected:\n" + new ByteBuffer(expected).toPlainHexString() + "\n actual:\n" + + new ByteBuffer(actual).toPlainHexString() + "."); + } + + public byte[] ntlm_generate_client_sealing_key() { + clientSealingKey = ntlm_generate_signing_key(CLIENT_SEAL_MAGIC); + return clientSealingKey; + } + + public void testGenerateClientSealingKey() { + exportedSessionKey = new byte[] {(byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08, (byte)0x09, + (byte)0x0a, (byte)0x0b, (byte)0x0c, (byte)0x0d, (byte)0x0e, (byte)0x0f, (byte)0x10,}; + byte[] expected = new byte[] {(byte)0x58, (byte)0x19, (byte)0x44, (byte)0xc2, (byte)0x7a, (byte)0xc6, (byte)0x34, (byte)0x45, (byte)0xe4, + (byte)0xb8, (byte)0x2b, (byte)0x55, (byte)0xb9, (byte)0x0b, (byte)0x1f, (byte)0xb5,}; + byte[] actual = ntlm_generate_client_sealing_key(); + + if (!Arrays.equals(expected, actual)) + throw new RuntimeException("Incorrect result.\nExpected:\n" + new ByteBuffer(expected).toPlainHexString() + "\n actual:\n" + + new ByteBuffer(actual).toPlainHexString() + "."); + } + + public byte[] ntlm_generate_server_sealing_key() { + serverSealingKey = ntlm_generate_signing_key(SERVER_SEAL_MAGIC); + return serverSealingKey; + } + + public void testGenerateServerSealingKey() { + exportedSessionKey = new byte[] {(byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08, (byte)0x09, + (byte)0x0a, (byte)0x0b, (byte)0x0c, (byte)0x0d, (byte)0x0e, (byte)0x0f, (byte)0x10,}; + byte[] expected = new byte[] {(byte)0x92, (byte)0x3a, (byte)0x73, (byte)0x5c, (byte)0x92, (byte)0xa7, (byte)0x04, (byte)0x34, (byte)0xbe, + (byte)0x9a, (byte)0xa2, (byte)0x9f, (byte)0xed, (byte)0xc1, (byte)0xe6, (byte)0x13,}; + byte[] actual = ntlm_generate_server_sealing_key(); + + if (!Arrays.equals(expected, actual)) + throw new RuntimeException("Incorrect result.\nExpected:\n" + new ByteBuffer(expected).toPlainHexString() + "\n actual:\n" + + new ByteBuffer(actual).toPlainHexString() + "."); + } + + public void ntlm_init_rc4_seal_states() { + ntlm_generate_client_signing_key(); + ntlm_generate_server_signing_key(); + ntlm_generate_client_sealing_key(); + ntlm_generate_server_sealing_key(); + + sendSigningKey = clientSigningKey; + recvSigningKey = serverSigningKey; + sendSealingKey = clientSealingKey; + recvSealingKey = serverSealingKey; + + sendRc4Seal = CryptoAlgos.initRC4(sendSealingKey); + recvRc4Seal = CryptoAlgos.initRC4(recvSealingKey); + } + + public byte[] ntlm_compute_message_integrity_check() { + //* DEBUG */System.out.println("ntlm_compute_message_integrity_check: exportedSessionKey:\n" + new ByteBuffer(exportedSessionKey).dump() + "\n"); + //* DEBUG */System.out.println("ntlm_compute_message_integrity_check: negotiateMessage:\n" + new ByteBuffer(negotiateMessage).dump() + "\n"); + //* DEBUG */System.out.println("ntlm_compute_message_integrity_check: challengeMessage:\n" + new ByteBuffer(challengeMessage).dump() + "\n"); + //* DEBUG */System.out.println("ntlm_compute_message_integrity_check: authenticateMessage:\n" + new ByteBuffer(authenticateMessage).dump() + "\n"); + messageIntegrityCheck = CryptoAlgos.HMAC_MD5(exportedSessionKey, CryptoAlgos.concatenationOf(negotiateMessage, challengeMessage, authenticateMessage)); + //* DEBUG */System.out.println("ntlm_compute_message_integrity_check: messageIntegrityCheck:\n" + new ByteBuffer(messageIntegrityCheck).dump() + "\n"); + return messageIntegrityCheck; + } + + public void testComputeMessageIntegrityCheck() { + exportedSessionKey = new byte[] {(byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08, (byte)0x09, + (byte)0x0a, (byte)0x0b, (byte)0x0c, (byte)0x0d, (byte)0x0e, (byte)0x0f, (byte)0x10,}; + + negotiateMessage = new byte[] {(byte)0x4e, (byte)0x54, (byte)0x4c, (byte)0x4d, (byte)0x53, (byte)0x53, (byte)0x50, (byte)0x00, (byte)0x01, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xb7, (byte)0x82, (byte)0x08, (byte)0xe2, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x06, (byte)0x01, (byte)0xb1, (byte)0x1d, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x0f,}; + + challengeMessage = new byte[] {(byte)0x4e, (byte)0x54, (byte)0x4c, (byte)0x4d, (byte)0x53, (byte)0x53, (byte)0x50, (byte)0x00, (byte)0x02, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x1e, (byte)0x00, (byte)0x1e, (byte)0x00, (byte)0x38, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x35, (byte)0x82, (byte)0x8a, (byte)0xe2, (byte)0x4a, (byte)0x25, (byte)0x50, (byte)0xa5, (byte)0x11, (byte)0x9b, (byte)0xd6, + (byte)0x16, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x98, (byte)0x00, + (byte)0x98, (byte)0x00, (byte)0x56, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x03, (byte)0xd7, (byte)0x24, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x0f, (byte)0x57, (byte)0x00, (byte)0x49, (byte)0x00, (byte)0x4e, (byte)0x00, (byte)0x2d, (byte)0x00, + (byte)0x4c, (byte)0x00, (byte)0x4f, (byte)0x00, (byte)0x34, (byte)0x00, (byte)0x31, (byte)0x00, (byte)0x39, (byte)0x00, (byte)0x42, + (byte)0x00, (byte)0x32, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x53, (byte)0x00, (byte)0x52, (byte)0x00, (byte)0x30, (byte)0x00, + (byte)0x02, (byte)0x00, (byte)0x1e, (byte)0x00, (byte)0x57, (byte)0x00, (byte)0x49, (byte)0x00, (byte)0x4e, (byte)0x00, (byte)0x2d, + (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x4f, (byte)0x00, (byte)0x34, (byte)0x00, (byte)0x31, (byte)0x00, (byte)0x39, (byte)0x00, + (byte)0x42, (byte)0x00, (byte)0x32, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x53, (byte)0x00, (byte)0x52, (byte)0x00, (byte)0x30, + (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x1e, (byte)0x00, (byte)0x57, (byte)0x00, (byte)0x49, (byte)0x00, (byte)0x4e, (byte)0x00, + (byte)0x2d, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x4f, (byte)0x00, (byte)0x34, (byte)0x00, (byte)0x31, (byte)0x00, (byte)0x39, + (byte)0x00, (byte)0x42, (byte)0x00, (byte)0x32, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x53, (byte)0x00, (byte)0x52, (byte)0x00, + (byte)0x30, (byte)0x00, (byte)0x04, (byte)0x00, (byte)0x1e, (byte)0x00, (byte)0x57, (byte)0x00, (byte)0x49, (byte)0x00, (byte)0x4e, + (byte)0x00, (byte)0x2d, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x4f, (byte)0x00, (byte)0x34, (byte)0x00, (byte)0x31, (byte)0x00, + (byte)0x39, (byte)0x00, (byte)0x42, (byte)0x00, (byte)0x32, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x53, (byte)0x00, (byte)0x52, + (byte)0x00, (byte)0x30, (byte)0x00, (byte)0x03, (byte)0x00, (byte)0x1e, (byte)0x00, (byte)0x57, (byte)0x00, (byte)0x49, (byte)0x00, + (byte)0x4e, (byte)0x00, (byte)0x2d, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x4f, (byte)0x00, (byte)0x34, (byte)0x00, (byte)0x31, + (byte)0x00, (byte)0x39, (byte)0x00, (byte)0x42, (byte)0x00, (byte)0x32, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x53, (byte)0x00, + (byte)0x52, (byte)0x00, (byte)0x30, (byte)0x00, (byte)0x07, (byte)0x00, (byte)0x08, (byte)0x00, (byte)0xa0, (byte)0xe8, (byte)0x85, + (byte)0x2c, (byte)0xe4, (byte)0xc9, (byte)0xce, (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00,}; + + authenticateMessage = new byte[] {(byte)0x4e, (byte)0x54, (byte)0x4c, (byte)0x4d, (byte)0x53, (byte)0x53, (byte)0x50, (byte)0x00, (byte)0x03, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x18, (byte)0x00, (byte)0x18, (byte)0x00, (byte)0x90, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x16, (byte)0x01, (byte)0x16, (byte)0x01, (byte)0xa8, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x12, (byte)0x00, (byte)0x12, + (byte)0x00, (byte)0x58, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x1a, (byte)0x00, (byte)0x1a, (byte)0x00, (byte)0x6a, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x0c, (byte)0x00, (byte)0x0c, (byte)0x00, (byte)0x84, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x10, + (byte)0x00, (byte)0x10, (byte)0x00, (byte)0xbe, (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x35, (byte)0xb2, (byte)0x88, (byte)0xe2, + (byte)0x06, (byte)0x01, (byte)0xb1, (byte)0x1d, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x0f, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x77, (byte)0x00, (byte)0x6f, (byte)0x00, (byte)0x72, (byte)0x00, (byte)0x6b, (byte)0x00, (byte)0x67, + (byte)0x00, (byte)0x72, (byte)0x00, (byte)0x6f, (byte)0x00, (byte)0x75, (byte)0x00, (byte)0x70, (byte)0x00, (byte)0x41, (byte)0x00, + (byte)0x64, (byte)0x00, (byte)0x6d, (byte)0x00, (byte)0x69, (byte)0x00, (byte)0x6e, (byte)0x00, (byte)0x69, (byte)0x00, (byte)0x73, + (byte)0x00, (byte)0x74, (byte)0x00, (byte)0x72, (byte)0x00, (byte)0x61, (byte)0x00, (byte)0x74, (byte)0x00, (byte)0x6f, (byte)0x00, + (byte)0x72, (byte)0x00, (byte)0x61, (byte)0x00, (byte)0x70, (byte)0x00, (byte)0x6f, (byte)0x00, (byte)0x6c, (byte)0x00, (byte)0x6c, + (byte)0x00, (byte)0x6f, (byte)0x00, (byte)0x7c, (byte)0xc0, (byte)0xfd, (byte)0x08, (byte)0xc5, (byte)0x14, (byte)0x05, (byte)0x34, + (byte)0xf3, (byte)0x12, (byte)0x9e, (byte)0x3e, (byte)0xa3, (byte)0x09, (byte)0xbc, (byte)0xc6, (byte)0x01, (byte)0x02, (byte)0x03, + (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08, (byte)0x19, (byte)0x4b, (byte)0xeb, (byte)0xad, (byte)0xda, (byte)0x24, + (byte)0xd5, (byte)0x96, (byte)0x85, (byte)0x2e, (byte)0x24, (byte)0x94, (byte)0xd6, (byte)0x4a, (byte)0xb8, (byte)0x5e, (byte)0x01, + (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xa0, (byte)0xe8, (byte)0x85, (byte)0x2c, + (byte)0xe4, (byte)0xc9, (byte)0xce, (byte)0x01, (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07, + (byte)0x08, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x02, (byte)0x00, (byte)0x1e, (byte)0x00, (byte)0x57, (byte)0x00, + (byte)0x49, (byte)0x00, (byte)0x4e, (byte)0x00, (byte)0x2d, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x4f, (byte)0x00, (byte)0x34, + (byte)0x00, (byte)0x31, (byte)0x00, (byte)0x39, (byte)0x00, (byte)0x42, (byte)0x00, (byte)0x32, (byte)0x00, (byte)0x4c, (byte)0x00, + (byte)0x53, (byte)0x00, (byte)0x52, (byte)0x00, (byte)0x30, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x1e, (byte)0x00, (byte)0x57, + (byte)0x00, (byte)0x49, (byte)0x00, (byte)0x4e, (byte)0x00, (byte)0x2d, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x4f, (byte)0x00, + (byte)0x34, (byte)0x00, (byte)0x31, (byte)0x00, (byte)0x39, (byte)0x00, (byte)0x42, (byte)0x00, (byte)0x32, (byte)0x00, (byte)0x4c, + (byte)0x00, (byte)0x53, (byte)0x00, (byte)0x52, (byte)0x00, (byte)0x30, (byte)0x00, (byte)0x04, (byte)0x00, (byte)0x1e, (byte)0x00, + (byte)0x57, (byte)0x00, (byte)0x49, (byte)0x00, (byte)0x4e, (byte)0x00, (byte)0x2d, (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x4f, + (byte)0x00, (byte)0x34, (byte)0x00, (byte)0x31, (byte)0x00, (byte)0x39, (byte)0x00, (byte)0x42, (byte)0x00, (byte)0x32, (byte)0x00, + (byte)0x4c, (byte)0x00, (byte)0x53, (byte)0x00, (byte)0x52, (byte)0x00, (byte)0x30, (byte)0x00, (byte)0x03, (byte)0x00, (byte)0x1e, + (byte)0x00, (byte)0x57, (byte)0x00, (byte)0x49, (byte)0x00, (byte)0x4e, (byte)0x00, (byte)0x2d, (byte)0x00, (byte)0x4c, (byte)0x00, + (byte)0x4f, (byte)0x00, (byte)0x34, (byte)0x00, (byte)0x31, (byte)0x00, (byte)0x39, (byte)0x00, (byte)0x42, (byte)0x00, (byte)0x32, + (byte)0x00, (byte)0x4c, (byte)0x00, (byte)0x53, (byte)0x00, (byte)0x52, (byte)0x00, (byte)0x30, (byte)0x00, (byte)0x07, (byte)0x00, + (byte)0x08, (byte)0x00, (byte)0xa0, (byte)0xe8, (byte)0x85, (byte)0x2c, (byte)0xe4, (byte)0xc9, (byte)0xce, (byte)0x01, (byte)0x06, + (byte)0x00, (byte)0x04, (byte)0x00, (byte)0x02, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x0a, (byte)0x00, (byte)0x10, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x09, (byte)0x00, (byte)0x26, (byte)0x00, (byte)0x54, (byte)0x00, + (byte)0x45, (byte)0x00, (byte)0x52, (byte)0x00, (byte)0x4d, (byte)0x00, (byte)0x53, (byte)0x00, (byte)0x52, (byte)0x00, (byte)0x56, + (byte)0x00, (byte)0x2f, (byte)0x00, (byte)0x31, (byte)0x00, (byte)0x39, (byte)0x00, (byte)0x32, (byte)0x00, (byte)0x2e, (byte)0x00, + (byte)0x31, (byte)0x00, (byte)0x36, (byte)0x00, (byte)0x38, (byte)0x00, (byte)0x2e, (byte)0x00, (byte)0x31, (byte)0x00, (byte)0x2e, + (byte)0x00, (byte)0x33, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xe4, (byte)0xe9, (byte)0xc2, + (byte)0xad, (byte)0x41, (byte)0x02, (byte)0x2f, (byte)0x3c, (byte)0xf9, (byte)0x4c, (byte)0x72, (byte)0x84, (byte)0xc5, (byte)0x2a, + (byte)0x7c, (byte)0x6f,}; + + byte[] expected = new byte[] {(byte)0xd9, (byte)0xe9, (byte)0xbc, (byte)0x9b, (byte)0x6f, (byte)0xa5, (byte)0xf9, (byte)0xc8, (byte)0x70, + (byte)0x16, (byte)0x10, (byte)0x20, (byte)0xf8, (byte)0xf1, (byte)0x61, (byte)0x42,}; + byte[] actual = ntlm_compute_message_integrity_check(); + + if (!Arrays.equals(expected, actual)) + throw new RuntimeException("Incorrect result.\nExpected:\n" + new ByteBuffer(expected).toPlainHexString() + "\n actual:\n" + + new ByteBuffer(actual).toPlainHexString() + "."); + } + + public byte[] ntlm_EncryptMessage(byte[] message) { + byte[] versionBytes = new byte[] {0x01, 0x00, 0x00, 0x00}; // 0x00000001 + // LE + byte[] seqNumBytes = new byte[] {(byte)(sendSeqNum & 0xff), (byte)((sendSeqNum >> 8) & 0xff), (byte)((sendSeqNum >> 16) & 0xff), + (byte)((sendSeqNum >> 24) & 0xff)}; + + byte[] digest = CryptoAlgos.HMAC_MD5(sendSigningKey, CryptoAlgos.concatenationOf(seqNumBytes, message)); + + byte[] encrypted = CryptoAlgos.RC4(sendRc4Seal, message); + + // Encrypt first 8 bytes of digest only + byte[] checksum = CryptoAlgos.RC4(sendRc4Seal, Arrays.copyOf(digest, 8)); + + byte[] signature = CryptoAlgos.concatenationOf(versionBytes, checksum, seqNumBytes); + + sendSeqNum++; + + return CryptoAlgos.concatenationOf(signature, encrypted); + } + + public void testNtlmEncryptMessage() { + sendSigningKey = new byte[] {(byte)0xf6, (byte)0xae, (byte)0x96, (byte)0xcb, (byte)0x05, (byte)0xe2, (byte)0xab, (byte)0x54, (byte)0xf6, + (byte)0xdd, (byte)0x59, (byte)0xf3, (byte)0xc9, (byte)0xd9, (byte)0xa0, (byte)0x43,}; + sendRc4Seal = CryptoAlgos.initRC4(new byte[] {(byte)0x58, (byte)0x19, (byte)0x44, (byte)0xc2, (byte)0x7a, (byte)0xc6, (byte)0x34, (byte)0x45, + (byte)0xe4, (byte)0xb8, (byte)0x2b, (byte)0x55, (byte)0xb9, (byte)0x0b, (byte)0x1f, (byte)0xb5,}); + sendSeqNum = 0; + byte[] serverPublicKey = new byte[] {(byte)0x30, (byte)0x82, (byte)0x01, (byte)0x0a, (byte)0x02, (byte)0x82, (byte)0x01, (byte)0x01, (byte)0x00, + (byte)0xa8, (byte)0x56, (byte)0x65, (byte)0xd3, (byte)0xce, (byte)0x8a, (byte)0x54, (byte)0x4d, (byte)0x9d, (byte)0xb0, (byte)0x84, + (byte)0x31, (byte)0x19, (byte)0x71, (byte)0x7f, (byte)0xdd, (byte)0x42, (byte)0xfb, (byte)0x2a, (byte)0x7a, (byte)0x72, (byte)0x13, + (byte)0xa1, (byte)0xb9, (byte)0x72, (byte)0xbb, (byte)0xd3, (byte)0x08, (byte)0xad, (byte)0x7d, (byte)0x6c, (byte)0x15, (byte)0x65, + (byte)0x03, (byte)0xd1, (byte)0xc4, (byte)0x54, (byte)0xc5, (byte)0x33, (byte)0x6b, (byte)0x7d, (byte)0x69, (byte)0x89, (byte)0x5e, + (byte)0xfe, (byte)0xe0, (byte)0x01, (byte)0xc0, (byte)0x7e, (byte)0x9b, (byte)0xcb, (byte)0x5d, (byte)0x65, (byte)0x36, (byte)0xcd, + (byte)0x77, (byte)0x5d, (byte)0xf3, (byte)0x7a, (byte)0x5b, (byte)0x29, (byte)0x44, (byte)0x72, (byte)0xd5, (byte)0x38, (byte)0xe2, + (byte)0xcf, (byte)0xb1, (byte)0xc7, (byte)0x78, (byte)0x9b, (byte)0x58, (byte)0xb9, (byte)0x17, (byte)0x7c, (byte)0xb7, (byte)0xd6, + (byte)0xc7, (byte)0xc7, (byte)0xbf, (byte)0x90, (byte)0x4e, (byte)0x7c, (byte)0x39, (byte)0x93, (byte)0xcb, (byte)0x2e, (byte)0xe0, + (byte)0xc2, (byte)0x33, (byte)0x2d, (byte)0xa5, (byte)0x7e, (byte)0xe0, (byte)0x7b, (byte)0xb6, (byte)0xf9, (byte)0x91, (byte)0x32, + (byte)0xb7, (byte)0xd4, (byte)0x85, (byte)0xb7, (byte)0x35, (byte)0x2d, (byte)0x2b, (byte)0x00, (byte)0x6d, (byte)0xf8, (byte)0xea, + (byte)0x8c, (byte)0x97, (byte)0x5f, (byte)0x51, (byte)0x1d, (byte)0x68, (byte)0x04, (byte)0x3c, (byte)0x79, (byte)0x14, (byte)0x71, + (byte)0xa7, (byte)0xc7, (byte)0xd7, (byte)0x70, (byte)0x7a, (byte)0xe0, (byte)0xba, (byte)0x12, (byte)0x69, (byte)0xc8, (byte)0xd3, + (byte)0xd9, (byte)0x4e, (byte)0xab, (byte)0x51, (byte)0x47, (byte)0xa3, (byte)0xec, (byte)0x99, (byte)0xd4, (byte)0x88, (byte)0xca, + (byte)0xda, (byte)0xc2, (byte)0x7f, (byte)0x79, (byte)0x4b, (byte)0x66, (byte)0xed, (byte)0x87, (byte)0xbe, (byte)0xc2, (byte)0x5f, + (byte)0xea, (byte)0xcf, (byte)0xe1, (byte)0xb5, (byte)0xf0, (byte)0x3d, (byte)0x9b, (byte)0xf2, (byte)0x19, (byte)0xc3, (byte)0xe0, + (byte)0xe1, (byte)0x7a, (byte)0x45, (byte)0x71, (byte)0x12, (byte)0x3d, (byte)0x72, (byte)0x1d, (byte)0x6f, (byte)0x2b, (byte)0x1c, + (byte)0x46, (byte)0x68, (byte)0xc0, (byte)0x8f, (byte)0x4f, (byte)0xce, (byte)0x3a, (byte)0xc5, (byte)0xcd, (byte)0x22, (byte)0x65, + (byte)0x2d, (byte)0x43, (byte)0xb0, (byte)0x5c, (byte)0xdd, (byte)0x89, (byte)0xae, (byte)0xbe, (byte)0x70, (byte)0x59, (byte)0x5e, + (byte)0x0c, (byte)0xbd, (byte)0xf5, (byte)0x46, (byte)0x82, (byte)0x1e, (byte)0xe4, (byte)0x86, (byte)0x95, (byte)0x7b, (byte)0x60, + (byte)0xae, (byte)0x45, (byte)0x50, (byte)0xc2, (byte)0x54, (byte)0x08, (byte)0x49, (byte)0x9a, (byte)0x9e, (byte)0xfb, (byte)0xb2, + (byte)0xb6, (byte)0x78, (byte)0xe5, (byte)0x2f, (byte)0x9c, (byte)0x5a, (byte)0xd0, (byte)0x8a, (byte)0x03, (byte)0x77, (byte)0x68, + (byte)0x30, (byte)0x93, (byte)0x78, (byte)0x6d, (byte)0x90, (byte)0x6d, (byte)0x50, (byte)0xfa, (byte)0xa7, (byte)0x65, (byte)0xfe, + (byte)0x59, (byte)0x33, (byte)0x27, (byte)0x4e, (byte)0x4b, (byte)0xf8, (byte)0x38, (byte)0x44, (byte)0x3a, (byte)0x12, (byte)0xf4, + (byte)0x07, (byte)0xa0, (byte)0x8d, (byte)0x02, (byte)0x03, (byte)0x01, (byte)0x00, (byte)0x01,}; + + byte[] expected = new byte[] {(byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x72, (byte)0x76, (byte)0x1e, (byte)0x57, (byte)0x49, + (byte)0xb5, (byte)0x0f, (byte)0xad, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x15, (byte)0xf7, (byte)0xf2, (byte)0x54, + (byte)0xda, (byte)0xa9, (byte)0xe5, (byte)0xad, (byte)0x85, (byte)0x04, (byte)0x67, (byte)0x4d, (byte)0x0b, (byte)0xcb, (byte)0xf9, + (byte)0xb1, (byte)0xf8, (byte)0x02, (byte)0x8a, (byte)0x77, (byte)0xc2, (byte)0x63, (byte)0xab, (byte)0xd5, (byte)0x74, (byte)0x23, + (byte)0x9f, (byte)0x9d, (byte)0x5d, (byte)0x1f, (byte)0xd3, (byte)0xb3, (byte)0xa0, (byte)0xac, (byte)0x16, (byte)0x8a, (byte)0x4b, + (byte)0x08, (byte)0xf5, (byte)0x47, (byte)0x70, (byte)0x58, (byte)0x10, (byte)0xb4, (byte)0xe7, (byte)0x87, (byte)0xb3, (byte)0x4b, + (byte)0xc9, (byte)0xa2, (byte)0xd5, (byte)0xd1, (byte)0xca, (byte)0x0f, (byte)0xd4, (byte)0xe3, (byte)0x8d, (byte)0x76, (byte)0x5a, + (byte)0x60, (byte)0x28, (byte)0xf8, (byte)0x06, (byte)0x5d, (byte)0xe4, (byte)0x7e, (byte)0x21, (byte)0xc8, (byte)0xbb, (byte)0xac, + (byte)0xe5, (byte)0x79, (byte)0x85, (byte)0x30, (byte)0x9b, (byte)0x88, (byte)0x13, (byte)0x2f, (byte)0x8f, (byte)0xfc, (byte)0x04, + (byte)0x52, (byte)0xfe, (byte)0x87, (byte)0x94, (byte)0xcf, (byte)0xcb, (byte)0x49, (byte)0x4a, (byte)0xda, (byte)0x6f, (byte)0xdd, + (byte)0xee, (byte)0x57, (byte)0xa5, (byte)0xe4, (byte)0x4d, (byte)0x0e, (byte)0x5c, (byte)0x3d, (byte)0x0b, (byte)0x63, (byte)0x1f, + (byte)0xf6, (byte)0x3d, (byte)0x1b, (byte)0xae, (byte)0x5a, (byte)0xf6, (byte)0x42, (byte)0x2a, (byte)0x46, (byte)0xfa, (byte)0x42, + (byte)0x71, (byte)0x67, (byte)0x46, (byte)0x02, (byte)0x71, (byte)0xea, (byte)0x51, (byte)0x98, (byte)0xf7, (byte)0xd4, (byte)0x43, + (byte)0xbf, (byte)0x8e, (byte)0xe8, (byte)0x3c, (byte)0xc8, (byte)0xfa, (byte)0x79, (byte)0x9d, (byte)0x8c, (byte)0xfc, (byte)0xc2, + (byte)0x42, (byte)0xc9, (byte)0xbb, (byte)0xd0, (byte)0xab, (byte)0x81, (byte)0xc4, (byte)0x53, (byte)0xfd, (byte)0x41, (byte)0xda, + (byte)0xab, (byte)0x0f, (byte)0x25, (byte)0x79, (byte)0x5f, (byte)0xbd, (byte)0xa3, (byte)0x8c, (byte)0xd3, (byte)0xf5, (byte)0x1b, + (byte)0xab, (byte)0x20, (byte)0xd1, (byte)0xf4, (byte)0xd8, (byte)0x81, (byte)0x9c, (byte)0x18, (byte)0x4a, (byte)0xa4, (byte)0x77, + (byte)0xee, (byte)0xe1, (byte)0x51, (byte)0xee, (byte)0x2a, (byte)0xc1, (byte)0x94, (byte)0x37, (byte)0xc5, (byte)0x06, (byte)0x7a, + (byte)0x3f, (byte)0x0f, (byte)0x25, (byte)0x5b, (byte)0x4e, (byte)0x6a, (byte)0xdc, (byte)0x0b, (byte)0x62, (byte)0x6f, (byte)0x12, + (byte)0x83, (byte)0x03, (byte)0xae, (byte)0x4e, (byte)0xce, (byte)0x2b, (byte)0x6e, (byte)0xd4, (byte)0xd5, (byte)0x23, (byte)0x27, + (byte)0xf6, (byte)0xa6, (byte)0x38, (byte)0x67, (byte)0xec, (byte)0x95, (byte)0x82, (byte)0xc6, (byte)0xba, (byte)0xd4, (byte)0xf6, + (byte)0xe6, (byte)0x22, (byte)0x7d, (byte)0xb9, (byte)0xe4, (byte)0x81, (byte)0x97, (byte)0x24, (byte)0xff, (byte)0x40, (byte)0xb2, + (byte)0x42, (byte)0x3c, (byte)0x11, (byte)0x24, (byte)0xd0, (byte)0x3a, (byte)0x96, (byte)0xd9, (byte)0xc1, (byte)0x13, (byte)0xd6, + (byte)0x62, (byte)0x45, (byte)0x21, (byte)0x60, (byte)0x5b, (byte)0x7b, (byte)0x2b, (byte)0x62, (byte)0x44, (byte)0xf7, (byte)0x40, + (byte)0x93, (byte)0x29, (byte)0x5b, (byte)0x44, (byte)0xb7, (byte)0xda, (byte)0x9c, (byte)0xa6, (byte)0xa9, (byte)0x3b, (byte)0xe1, + (byte)0x3b, (byte)0x9d, (byte)0x31, (byte)0xf2, (byte)0x21, (byte)0x53, (byte)0x0f, (byte)0xb3, (byte)0x70, (byte)0x55, (byte)0x84, + (byte)0x2c, (byte)0xb4,}; + byte[] actual = ntlm_EncryptMessage(serverPublicKey); + + if (!Arrays.equals(expected, actual)) + throw new RuntimeException("Incorrect result.\nExpected:\n" + new ByteBuffer(expected).toPlainHexString() + "\n actual:\n" + + new ByteBuffer(actual).toPlainHexString() + "."); + } + + public byte[] ntlm_DecryptMessage(byte[] wrappedMssage) { + + byte[] versionBytes = new byte[] {0x01, 0x00, 0x00, 0x00}; // 0x00000001 + // LE + byte[] seqNumBytes = new byte[] {(byte)(recvSeqNum & 0xff), (byte)((recvSeqNum >> 8) & 0xff), (byte)((recvSeqNum >> 16) & 0xff), + (byte)((recvSeqNum >> 24) & 0xff)}; + + // Unwrap message + byte[] actualSignature = Arrays.copyOf(wrappedMssage, 16); + byte[] encryptedMessage = Arrays.copyOfRange(wrappedMssage, 16, wrappedMssage.length); + + // Decrypt message + byte[] decryptedMessage = CryptoAlgos.RC4(recvRc4Seal, encryptedMessage); + + // Compare actual signature with expected signature + byte[] digest = CryptoAlgos.HMAC_MD5(recvSigningKey, CryptoAlgos.concatenationOf(seqNumBytes, decryptedMessage)); + + // Encrypt first 8 bytes of digest only + byte[] checksum = CryptoAlgos.RC4(recvRc4Seal, Arrays.copyOf(digest, 8)); + + byte[] expectedSignature = CryptoAlgos.concatenationOf(versionBytes, checksum, seqNumBytes); + + if (!Arrays.equals(expectedSignature, actualSignature)) + throw new RuntimeException("Unexpected signature of message:\nExpected signature: " + new ByteBuffer(expectedSignature).toPlainHexString() + + "\n Actual signature: " + new ByteBuffer(actualSignature).toPlainHexString()); + + recvSeqNum++; + + return decryptedMessage; + } + + public void testNtlmDecryptMessage() { + recvSigningKey = new byte[] {(byte)0xb6, (byte)0x58, (byte)0xc5, (byte)0x98, (byte)0x7a, (byte)0x25, (byte)0xf8, (byte)0x6e, (byte)0xd8, + (byte)0xe5, (byte)0x6c, (byte)0xe9, (byte)0x3e, (byte)0x3c, (byte)0xc0, (byte)0x88,}; + recvRc4Seal = CryptoAlgos.initRC4(new byte[] {(byte)0x92, (byte)0x3a, (byte)0x73, (byte)0x5c, (byte)0x92, (byte)0xa7, (byte)0x04, (byte)0x34, + (byte)0xbe, (byte)0x9a, (byte)0xa2, (byte)0x9f, (byte)0xed, (byte)0xc1, (byte)0xe6, (byte)0x13,}); + recvSeqNum = 0; + byte[] encryptedMessage = new byte[] {(byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x25, (byte)0xf8, (byte)0x2d, (byte)0x1e, (byte)0x4e, + (byte)0x6a, (byte)0xec, (byte)0x4f, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x03, (byte)0x12, (byte)0xdd, (byte)0xea, + (byte)0x47, (byte)0xb3, (byte)0xff, (byte)0xe1, (byte)0x66, (byte)0x08, (byte)0xf6, (byte)0x6b, (byte)0xa0, (byte)0x62, (byte)0x42, + (byte)0x67, (byte)0xbf, (byte)0x3d, (byte)0x59, (byte)0x60, (byte)0xef, (byte)0x52, (byte)0xb0, (byte)0x26, (byte)0x95, (byte)0xed, + (byte)0x84, (byte)0x48, (byte)0x44, (byte)0xbb, (byte)0x8d, (byte)0x65, (byte)0xcf, (byte)0xe4, (byte)0x8e, (byte)0x6f, (byte)0x69, + (byte)0xae, (byte)0xed, (byte)0x44, (byte)0xbb, (byte)0x49, (byte)0x1d, (byte)0x2a, (byte)0x40, (byte)0x29, (byte)0x2b, (byte)0x13, + (byte)0x42, (byte)0x1c, (byte)0xeb, (byte)0xb1, (byte)0x6c, (byte)0x8a, (byte)0x3b, (byte)0x80, (byte)0xd1, (byte)0x70, (byte)0xfd, + (byte)0xdd, (byte)0x79, (byte)0xe4, (byte)0x93, (byte)0x0b, (byte)0x47, (byte)0xbd, (byte)0x3a, (byte)0x7e, (byte)0x31, (byte)0x66, + (byte)0x4b, (byte)0x65, (byte)0x8d, (byte)0x5c, (byte)0x2a, (byte)0xcd, (byte)0xc2, (byte)0x09, (byte)0x7a, (byte)0x3b, (byte)0xb2, + (byte)0xfd, (byte)0x09, (byte)0x52, (byte)0x09, (byte)0x47, (byte)0x05, (byte)0xa4, (byte)0x6f, (byte)0x32, (byte)0xd1, (byte)0x76, + (byte)0xb2, (byte)0xd4, (byte)0x59, (byte)0xe0, (byte)0x85, (byte)0xf1, (byte)0x36, (byte)0x7d, (byte)0x76, (byte)0x50, (byte)0x21, + (byte)0x0e, (byte)0x20, (byte)0x22, (byte)0x83, (byte)0x1a, (byte)0x08, (byte)0xc0, (byte)0x85, (byte)0x5d, (byte)0x4f, (byte)0x5c, + (byte)0x77, (byte)0x68, (byte)0x32, (byte)0x95, (byte)0xa9, (byte)0xa2, (byte)0x59, (byte)0x69, (byte)0xea, (byte)0x19, (byte)0x34, + (byte)0x08, (byte)0xed, (byte)0x76, (byte)0xa3, (byte)0x58, (byte)0x37, (byte)0xf2, (byte)0x0a, (byte)0x0c, (byte)0xba, (byte)0x4d, + (byte)0xbb, (byte)0x6f, (byte)0x82, (byte)0x94, (byte)0xd3, (byte)0x87, (byte)0xde, (byte)0xc9, (byte)0x8f, (byte)0xef, (byte)0x34, + (byte)0x2d, (byte)0x8f, (byte)0xd0, (byte)0x0c, (byte)0x91, (byte)0x59, (byte)0xfd, (byte)0xea, (byte)0x6b, (byte)0xcb, (byte)0xbd, + (byte)0xa2, (byte)0x20, (byte)0xed, (byte)0xb9, (byte)0x76, (byte)0xd3, (byte)0x64, (byte)0x1b, (byte)0xb3, (byte)0x3b, (byte)0xf5, + (byte)0x9b, (byte)0x61, (byte)0xd7, (byte)0xab, (byte)0x26, (byte)0x9b, (byte)0x0d, (byte)0xa0, (byte)0xea, (byte)0xbf, (byte)0xad, + (byte)0x2c, (byte)0xad, (byte)0x63, (byte)0x65, (byte)0xc6, (byte)0x70, (byte)0xc4, (byte)0xe5, (byte)0x8d, (byte)0x40, (byte)0xaa, + (byte)0x08, (byte)0x45, (byte)0x66, (byte)0xe2, (byte)0x4d, (byte)0xc9, (byte)0x46, (byte)0x00, (byte)0x33, (byte)0x43, (byte)0xe0, + (byte)0xba, (byte)0xd6, (byte)0x80, (byte)0x29, (byte)0x21, (byte)0x5e, (byte)0xd1, (byte)0x9a, (byte)0xbc, (byte)0x44, (byte)0xfa, + (byte)0x4d, (byte)0x46, (byte)0xf9, (byte)0x25, (byte)0x80, (byte)0x40, (byte)0xb5, (byte)0x27, (byte)0xdd, (byte)0xc5, (byte)0x02, + (byte)0xf8, (byte)0xa4, (byte)0x9a, (byte)0xcb, (byte)0xcf, (byte)0x3f, (byte)0xef, (byte)0xc7, (byte)0xcd, (byte)0x71, (byte)0x45, + (byte)0xa5, (byte)0x35, (byte)0xb1, (byte)0x21, (byte)0x14, (byte)0x39, (byte)0x57, (byte)0xf8, (byte)0x0a, (byte)0x24, (byte)0x98, + (byte)0xea, (byte)0x15, (byte)0xe1, (byte)0xe3, (byte)0xcb, (byte)0x9d, (byte)0xf2, (byte)0x4e, (byte)0xef, (byte)0x89, (byte)0x97, + (byte)0xc0, (byte)0xb2, (byte)0x96, (byte)0x9a, (byte)0x1e, (byte)0xad, (byte)0xd0, (byte)0x9a, (byte)0x99, (byte)0x62, (byte)0x9f, + (byte)0x13, (byte)0x2e,}; + + byte[] expected = new byte[] { + // First byte is increased by 1 + (byte)0x31, (byte)0x82, (byte)0x01, (byte)0x0a, (byte)0x02, (byte)0x82, (byte)0x01, (byte)0x01, (byte)0x00, (byte)0xa8, (byte)0x56, + (byte)0x65, (byte)0xd3, (byte)0xce, (byte)0x8a, (byte)0x54, (byte)0x4d, (byte)0x9d, (byte)0xb0, (byte)0x84, (byte)0x31, (byte)0x19, + (byte)0x71, (byte)0x7f, (byte)0xdd, (byte)0x42, (byte)0xfb, (byte)0x2a, (byte)0x7a, (byte)0x72, (byte)0x13, (byte)0xa1, (byte)0xb9, + (byte)0x72, (byte)0xbb, (byte)0xd3, (byte)0x08, (byte)0xad, (byte)0x7d, (byte)0x6c, (byte)0x15, (byte)0x65, (byte)0x03, (byte)0xd1, + (byte)0xc4, (byte)0x54, (byte)0xc5, (byte)0x33, (byte)0x6b, (byte)0x7d, (byte)0x69, (byte)0x89, (byte)0x5e, (byte)0xfe, (byte)0xe0, + (byte)0x01, (byte)0xc0, (byte)0x7e, (byte)0x9b, (byte)0xcb, (byte)0x5d, (byte)0x65, (byte)0x36, (byte)0xcd, (byte)0x77, (byte)0x5d, + (byte)0xf3, (byte)0x7a, (byte)0x5b, (byte)0x29, (byte)0x44, (byte)0x72, (byte)0xd5, (byte)0x38, (byte)0xe2, (byte)0xcf, (byte)0xb1, + (byte)0xc7, (byte)0x78, (byte)0x9b, (byte)0x58, (byte)0xb9, (byte)0x17, (byte)0x7c, (byte)0xb7, (byte)0xd6, (byte)0xc7, (byte)0xc7, + (byte)0xbf, (byte)0x90, (byte)0x4e, (byte)0x7c, (byte)0x39, (byte)0x93, (byte)0xcb, (byte)0x2e, (byte)0xe0, (byte)0xc2, (byte)0x33, + (byte)0x2d, (byte)0xa5, (byte)0x7e, (byte)0xe0, (byte)0x7b, (byte)0xb6, (byte)0xf9, (byte)0x91, (byte)0x32, (byte)0xb7, (byte)0xd4, + (byte)0x85, (byte)0xb7, (byte)0x35, (byte)0x2d, (byte)0x2b, (byte)0x00, (byte)0x6d, (byte)0xf8, (byte)0xea, (byte)0x8c, (byte)0x97, + (byte)0x5f, (byte)0x51, (byte)0x1d, (byte)0x68, (byte)0x04, (byte)0x3c, (byte)0x79, (byte)0x14, (byte)0x71, (byte)0xa7, (byte)0xc7, + (byte)0xd7, (byte)0x70, (byte)0x7a, (byte)0xe0, (byte)0xba, (byte)0x12, (byte)0x69, (byte)0xc8, (byte)0xd3, (byte)0xd9, (byte)0x4e, + (byte)0xab, (byte)0x51, (byte)0x47, (byte)0xa3, (byte)0xec, (byte)0x99, (byte)0xd4, (byte)0x88, (byte)0xca, (byte)0xda, (byte)0xc2, + (byte)0x7f, (byte)0x79, (byte)0x4b, (byte)0x66, (byte)0xed, (byte)0x87, (byte)0xbe, (byte)0xc2, (byte)0x5f, (byte)0xea, (byte)0xcf, + (byte)0xe1, (byte)0xb5, (byte)0xf0, (byte)0x3d, (byte)0x9b, (byte)0xf2, (byte)0x19, (byte)0xc3, (byte)0xe0, (byte)0xe1, (byte)0x7a, + (byte)0x45, (byte)0x71, (byte)0x12, (byte)0x3d, (byte)0x72, (byte)0x1d, (byte)0x6f, (byte)0x2b, (byte)0x1c, (byte)0x46, (byte)0x68, + (byte)0xc0, (byte)0x8f, (byte)0x4f, (byte)0xce, (byte)0x3a, (byte)0xc5, (byte)0xcd, (byte)0x22, (byte)0x65, (byte)0x2d, (byte)0x43, + (byte)0xb0, (byte)0x5c, (byte)0xdd, (byte)0x89, (byte)0xae, (byte)0xbe, (byte)0x70, (byte)0x59, (byte)0x5e, (byte)0x0c, (byte)0xbd, + (byte)0xf5, (byte)0x46, (byte)0x82, (byte)0x1e, (byte)0xe4, (byte)0x86, (byte)0x95, (byte)0x7b, (byte)0x60, (byte)0xae, (byte)0x45, + (byte)0x50, (byte)0xc2, (byte)0x54, (byte)0x08, (byte)0x49, (byte)0x9a, (byte)0x9e, (byte)0xfb, (byte)0xb2, (byte)0xb6, (byte)0x78, + (byte)0xe5, (byte)0x2f, (byte)0x9c, (byte)0x5a, (byte)0xd0, (byte)0x8a, (byte)0x03, (byte)0x77, (byte)0x68, (byte)0x30, (byte)0x93, + (byte)0x78, (byte)0x6d, (byte)0x90, (byte)0x6d, (byte)0x50, (byte)0xfa, (byte)0xa7, (byte)0x65, (byte)0xfe, (byte)0x59, (byte)0x33, + (byte)0x27, (byte)0x4e, (byte)0x4b, (byte)0xf8, (byte)0x38, (byte)0x44, (byte)0x3a, (byte)0x12, (byte)0xf4, (byte)0x07, (byte)0xa0, + (byte)0x8d, (byte)0x02, (byte)0x03, (byte)0x01, (byte)0x00, (byte)0x01,}; + byte[] actual = ntlm_DecryptMessage(encryptedMessage); + + if (!Arrays.equals(expected, actual)) + throw new RuntimeException("Incorrect result.\nExpected:\n" + new ByteBuffer(expected).toPlainHexString() + "\n actual:\n" + + new ByteBuffer(actual).toPlainHexString() + "."); + } + + public static void main(String args[]) { + CryptoAlgos.callAll(new NtlmState()); + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/SecBuffer.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/SecBuffer.java new file mode 100755 index 00000000000..6aeb39b5348 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/SecBuffer.java @@ -0,0 +1,21 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.ntlmssp; + +public class SecBuffer { + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/ServerNtlmsspChallenge.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/ServerNtlmsspChallenge.java new file mode 100755 index 00000000000..eaac62b92d9 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/ServerNtlmsspChallenge.java @@ -0,0 +1,293 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.ntlmssp; + +import java.util.Arrays; + +import rdpclient.ntlmssp.asn1.NegoItem; +import rdpclient.ntlmssp.asn1.TSRequest; +import rdpclient.rdp.RdpConstants; +import streamer.ByteBuffer; +import streamer.Element; +import streamer.Link; +import streamer.OneTimeSwitch; +import streamer.Pipeline; +import streamer.PipelineImpl; +import streamer.debug.MockSink; +import streamer.debug.MockSource; + +/** + * @see http://msdn.microsoft.com/en-us/library/cc236642.aspx + */ +public class ServerNtlmsspChallenge extends OneTimeSwitch implements NtlmConstants { + + protected NtlmState ntlmState; + + public ServerNtlmsspChallenge(String id, NtlmState state) { + super(id); + ntlmState = state; + } + + @Override + protected void handleOneTimeData(ByteBuffer buf, Link link) { + if (buf == null) + return; + + if (verbose) + System.out.println("[" + this + "] INFO: Data received: " + buf + "."); + + // Extract server challenge, extract server flags. + + // Parse TSRequest in BER format + TSRequest request = new TSRequest("TSRequest"); + request.readTag(buf); + + ByteBuffer negoToken = ((NegoItem)request.negoTokens.tags[0]).negoToken.value; + ntlmState.challengeMessage = negoToken.toByteArray(); // Store message for MIC calculation in AUTH message + + parseNtlmChallenge(negoToken); + + negoToken.unref(); + buf.unref(); + switchOff(); + } + + public void parseNtlmChallenge(ByteBuffer buf) { + + // Signature: "NTLMSSP\0" + String signature = buf.readVariableString(RdpConstants.CHARSET_8); + if (!signature.equals(NTLMSSP)) + throw new RuntimeException("Unexpected NTLM message singature: \"" + signature + "\". Expected signature: \"" + NTLMSSP + "\". Data: " + buf + "."); + + // MessageType (CHALLENGE) + int messageType = buf.readSignedIntLE(); + if (messageType != NtlmConstants.CHALLENGE) + throw new RuntimeException("Unexpected NTLM message type: " + messageType + ". Expected type: CHALLENGE (" + NtlmConstants.CHALLENGE + "). Data: " + buf + + "."); + + // TargetName + ntlmState.serverTargetName = readStringByDescription(buf); + + // NegotiateFlags + ntlmState.negotiatedFlags = new NegoFlags(buf.readSignedIntLE()); + if (verbose) + System.out.println("[" + this + "] INFO: Server negotiate flags: " + ntlmState.negotiatedFlags + "."); + + // ServerChallenge + ByteBuffer challenge = buf.readBytes(8); + ntlmState.serverChallenge = challenge.toByteArray(); + if (verbose) + System.out.println("[" + this + "] INFO: Server challenge: " + challenge + "."); + challenge.unref(); + + // Reserved/context + buf.skipBytes(8); + + // TargetInfo + ByteBuffer targetInfo = readBlockByDescription(buf); + + // Store raw target info block for Type3 message + ntlmState.serverTargetInfo = targetInfo.toByteArray(); + + // Parse target info block + parseTargetInfo(targetInfo); + targetInfo.unref(); + + // OS Version, NTLM revision, 8 bytes, Optional. Ignore it. + + // Ignore rest of buffer with allocated blocks + + buf.unref(); + } + + public void parseTargetInfo(ByteBuffer buf) { + // Parse attribute list + + while (buf.remainderLength() > 0) { + int type = buf.readUnsignedShortLE(); + int length = buf.readUnsignedShortLE(); + + if (type == MSV_AV_EOL) + // End of list + break; + + ByteBuffer data = buf.readBytes(length); + parseAttribute(data, type, length); + data.unref(); + } + } + + public void parseAttribute(ByteBuffer buf, int type, int length) { + switch (type) { + case MSV_AV_NETBIOS_DOMAIN_NAME: + ntlmState.serverNetbiosDomainName = buf.readString(length, RdpConstants.CHARSET_16); + break; + case MSV_AV_NETBIOS_COMPUTER_NAME: + ntlmState.serverNetbiosComputerName = buf.readString(length, RdpConstants.CHARSET_16); + break; + case MSV_AV_DNS_DOMAIN_NAME: + ntlmState.serverDnsDomainName = buf.readString(length, RdpConstants.CHARSET_16); + break; + case MSV_AV_DNS_COMPUTER_NAME: + ntlmState.serverDnsComputerName = buf.readString(length, RdpConstants.CHARSET_16); + break; + case MSV_AV_DNS_TREE_NAME: + ntlmState.serverDnsTreeName = buf.readString(length, RdpConstants.CHARSET_16); + break; + + case MSV_AV_TIMESTAMP: + ByteBuffer tmp = buf.readBytes(length); + ntlmState.serverTimestamp = tmp.toByteArray(); + //*DEBUG*/System.out.println("Server timestamp: "+tmp.toPlainHexString()); + tmp.unref(); + break; + + default: + // Ignore + //throw new RuntimeException("[" + this + "] ERROR: Unknown NTLM target info attribute: " + type + ". Data: " + buf + "."); + + } + + } + + /** + * Read NTLM wide string, by it description. Buffer offset must point to + * beginning of NTLM message signature. + * + * @param buf + * buffer with cursor pointing to description + * @return + */ + public static String readStringByDescription(ByteBuffer buf) { + ByteBuffer block = readBlockByDescription(buf); + String value = block.readString(block.length, RdpConstants.CHARSET_16); + block.unref(); + + return value; + } + + public static ByteBuffer readBlockByDescription(ByteBuffer buf) { + int blockLength = buf.readUnsignedShortLE(); // In bytes + int allocatedSpace = buf.readUnsignedShortLE(); + int offset = buf.readSignedIntLE(); + + if (allocatedSpace < blockLength) + blockLength = allocatedSpace; + + if (offset > buf.length || offset < 0 || offset + allocatedSpace > buf.length) + throw new RuntimeException("ERROR: NTLM block is too long. Allocated space: " + allocatedSpace + ", block offset: " + offset + ", data: " + + buf + "."); + + // Move cursor to position of allocated block, starting from beginning of + // this buffer + int storedCursor = buf.cursor; + buf.cursor = offset; + + // Read string + ByteBuffer value = buf.readBytes(blockLength); + + // Restore cursor + buf.cursor = storedCursor; + + return value; + } + + /** + * Example. + */ + public static void main(String args[]) { + // System.setProperty("streamer.Link.debug", "true"); + System.setProperty("streamer.Element.debug", "true"); + // System.setProperty("streamer.Pipeline.debug", "true"); + + /* @formatter:off */ + byte[] packet = new byte[] { + 0x30, (byte) 0x82, 0x01, 0x02, // TAG: [UNIVERSAL 16] (constructed) "SEQUENCE" LEN: 258 bytes + (byte) 0xa0, 0x03, // TAG: [0] (constructed) LEN: 3 bytes + 0x02, 0x01, 0x03, // TAG: [UNIVERSAL 2] (primitive) "INTEGER" LEN: 1 bytes, Version: 0x3 + (byte) 0xa1, (byte) 0x81, (byte) 0xfa, // TAG: [1] (constructed) LEN: 250 bytes + 0x30, (byte) 0x81, (byte) 0xf7, // TAG: [UNIVERSAL 16] (constructed) "SEQUENCE" LEN: 247 bytes + 0x30, (byte) 0x81, (byte) 0xf4, // TAG: [UNIVERSAL 16] (constructed) "SEQUENCE" LEN: 244 bytes + (byte) 0xa0, (byte) 0x81, (byte) 0xf1, // TAG: [0] (constructed) LEN: 241 bytes + 0x04, (byte) 0x81, (byte) 0xee, // TAG: [UNIVERSAL 4] (primitive) "OCTET STRING" LEN: 238 bytes + + 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00, // "NTLMSSP\0" + + 0x02, 0x00, 0x00, 0x00, // MessageType (CHALLENGE) + 0x1e, 0x00, 0x1e, 0x00, 0x38, 0x00, 0x00, 0x00, // TargetName (length: 30, allocated space: 30, offset: 56) + 0x35, (byte) 0x82, (byte) 0x8a, (byte) 0xe2, // NegotiateFlags + 0x52, (byte) 0xbe, (byte) 0x83, (byte) 0xd1, (byte) 0xf8, (byte) 0x80, 0x16, 0x6a, // ServerChallenge + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Reserved + (byte) 0x98, 0x00, (byte) 0x98, 0x00, 0x56, 0x00, 0x00, 0x00, // TargetInfo (length: 152, allocated space: 152, offset: 86) + 0x06, 0x03, (byte) 0xd7, 0x24, 0x00, 0x00, 0x00, 0x0f, // Version (6.3, build 9431) , NTLM current revision: 15 + + + 0x57, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x2d, 0x00, 0x4c, 0x00, 0x4f, 0x00, 0x34, 0x00, 0x31, 0x00, 0x39, 0x00, 0x42, 0x00, 0x32, 0x00, 0x4c, 0x00, 0x53, 0x00, 0x52, 0x00, 0x30, 0x00, // Target name value: "WIN-LO419B2LSR0" + + // Target Info value: + + // Attribute list + + 0x02, 0x00, // Item Type: NetBIOS domain name (0x0002, LE) + 0x1e, 0x00, // Item Length: 30 (LE) + 0x57, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x2d, 0x00, 0x4c, 0x00, 0x4f, 0x00, 0x34, 0x00, 0x31, 0x00, 0x39, 0x00, 0x42, 0x00, 0x32, 0x00, 0x4c, 0x00, 0x53, 0x00, 0x52, 0x00, 0x30, 0x00, // "WIN-LO419B2LSR0" + + 0x01, 0x00, // Item Type: NetBIOS computer name (0x0001, LE) + 0x1e, 0x00, // Item Length: 30 (LE) + 0x57, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x2d, 0x00, 0x4c, 0x00, 0x4f, 0x00, 0x34, 0x00, 0x31, 0x00, 0x39, 0x00, 0x42, 0x00, 0x32, 0x00, 0x4c, 0x00, 0x53, 0x00, 0x52, 0x00, 0x30, 0x00, // "WIN-LO419B2LSR0" + + 0x04, 0x00, // Item Type: DNS domain name (0x0004, LE) + 0x1e, 0x00, // Item Length: 30 (LE) + 0x57, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x2d, 0x00, 0x4c, 0x00, 0x4f, 0x00, 0x34, 0x00, 0x31, 0x00, 0x39, 0x00, 0x42, 0x00, 0x32, 0x00, 0x4c, 0x00, 0x53, 0x00, 0x52, 0x00, 0x30, 0x00, // "WIN-LO419B2LSR0" + + 0x03, 0x00, // Item Type: DNS computer name (0x0003, LE) + 0x1e, 0x00, // Item Length: 30 (LE) + 0x57, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x2d, 0x00, 0x4c, 0x00, 0x4f, 0x00, 0x34, 0x00, 0x31, 0x00, 0x39, 0x00, 0x42, 0x00, 0x32, 0x00, 0x4c, 0x00, 0x53, 0x00, 0x52, 0x00, 0x30, 0x00, // "WIN-LO419B2LSR0" + + 0x07, 0x00, // Item Type: Timestamp (0x0007, LE) + 0x08, 0x00, // Item Length: 8 (LE) + (byte) 0x99, 0x4f, 0x02, (byte) 0xd8, (byte) 0xf4, (byte) 0xaf, (byte) 0xce, 0x01, // TODO + + // Attribute: End of list + 0x00, 0x00, + 0x00, 0x00, + }; + /* @formatter:on */ + + MockSource source = new MockSource("source", ByteBuffer.convertByteArraysToByteBuffers(packet, new byte[] {1, 2, 3})); + NtlmState state = new NtlmState(); + Element ntlmssp_challenge = new ServerNtlmsspChallenge("ntlmssp_challenge", state); + Element sink = new MockSink("sink", ByteBuffer.convertByteArraysToByteBuffers()); + Element mainSink = new MockSink("mainSink", ByteBuffer.convertByteArraysToByteBuffers(new byte[] {1, 2, 3})); + + Pipeline pipeline = new PipelineImpl("test"); + pipeline.add(source, ntlmssp_challenge, sink, mainSink); + pipeline.link("source", "ntlmssp_challenge", "mainSink"); + pipeline.link("ntlmssp_challenge >" + OTOUT, "sink"); + pipeline.runMainLoop("source", STDOUT, false, false); + + // Check state challenge + byte[] challenge = new byte[] {0x52, (byte)0xbe, (byte)0x83, (byte)0xd1, (byte)0xf8, (byte)0x80, 0x16, 0x6a}; + if (state.serverChallenge == null) + throw new RuntimeException("Challenge was not extracted from server NTLMSSP Challenge packet."); + if (!Arrays.equals(challenge, state.serverChallenge)) + throw new RuntimeException("Challenge was extracted from server NTLMSSP Challenge packet is not equal to expected. Actual value: " + + state.serverChallenge + ", expected value: " + challenge + "."); + + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/ServerNtlmsspPubKeyPlus1.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/ServerNtlmsspPubKeyPlus1.java new file mode 100755 index 00000000000..bbb75fcadbb --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/ServerNtlmsspPubKeyPlus1.java @@ -0,0 +1,125 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.ntlmssp; + +import java.util.Arrays; + +import rdpclient.ntlmssp.asn1.TSRequest; +import streamer.ByteBuffer; +import streamer.Element; +import streamer.Link; +import streamer.OneTimeSwitch; + +public class ServerNtlmsspPubKeyPlus1 extends OneTimeSwitch implements Element { + + protected NtlmState ntlmState; + + public ServerNtlmsspPubKeyPlus1(String id, NtlmState ntlmState) { + super(id); + this.ntlmState = ntlmState; + } + + @Override + protected void handleOneTimeData(ByteBuffer buf, Link link) { + TSRequest tsRequest = new TSRequest("TSRequest"); + tsRequest.readTag(buf); + + ByteBuffer encryptedPubKey = tsRequest.pubKeyAuth.value; + if (encryptedPubKey == null || encryptedPubKey.length == 0) + throw new RuntimeException("[" + this + + "] ERROR: Unexpected message from RDP server. Expected encrypted server public key but got nothing instead. Data: " + buf); + + byte[] decryptedPubKey = ntlmState.ntlm_DecryptMessage(encryptedPubKey.toByteArray()); + //* DEBUG */System.out.println("Decrypted pub key:\n" + new ByteBuffer(decryptedPubKey).dump()); + + // Decrease first byte by 1 + decryptedPubKey[0]--; + + // Compare returned value with expected value + if (!Arrays.equals(decryptedPubKey, ntlmState.subjectPublicKey)) + throw new RuntimeException("[" + this + + "] ERROR: Unexpected message from RDP server. Expected encrypted server public key but an unknown response. Encryted key after decryption: " + + new ByteBuffer(decryptedPubKey).toPlainHexString()); + + buf.unref(); + switchOff(); // Ignore packet + } +} + +/* @formatter:off */ + +// CredSSP header in BER format: + +// 0x30, (byte) 0x82, 0x01, 0x2b, // TAG: [UNIVERSAL 16] (constructed) +// "SEQUENCE" LEN: 299 bytes +// (byte) 0xa0, 0x03, // TAG: [0] (constructed) LEN: 3 bytes +// 0x02, 0x01, 0x03, // TAG: [UNIVERSAL 2] (primitive) "INTEGER" LEN: 1 bytes, +// Version: 0x3 +// (byte) 0xa3, (byte) 0x82, 0x01, 0x22, // TAG: [3] (constructed) LEN: 290 +// bytes +// 0x04, (byte) 0x82, 0x01, 0x1e, // TAG: [UNIVERSAL 4] (primitive) +// "OCTET STRING" LEN: 286 bytes + +// ??? + +// 0x01, 0x00, 0x00, 0x00, // ??? +// (byte) 0x98, (byte) 0xb0, 0x72, 0x48, 0x42, 0x09, (byte) 0xbd, 0x42, 0x00, +// 0x00, 0x00, // +// 0x00, (byte) 0xf6, 0x76, 0x0a, 0x40, (byte) 0xb4, 0x7b, (byte) 0xee, 0x69, +// (byte) 0xfc, (byte) 0x95, 0x2d, 0x5f, 0x6a, (byte) 0xe8, (byte) 0x87, // +// 0x4e, (byte) 0xeb, (byte) 0xae, 0x29, (byte) 0xf2, (byte) 0xde, 0x5e, 0x0a, +// 0x6e, 0x45, (byte) 0xeb, (byte) 0x95, (byte) 0xd9, 0x48, (byte) 0xfc, 0x44, +// // +// 0x7a, 0x34, (byte) 0xb4, (byte) 0xc4, (byte) 0xee, (byte) 0x93, (byte) 0xd2, +// (byte) 0xb4, (byte) 0xe5, (byte) 0xe5, (byte) 0xc1, 0x0f, (byte) 0x9e, 0x3b, +// (byte) 0xce, (byte) 0xaa, // +// 0x76, (byte) 0x9e, 0x2b, 0x33, 0x44, 0x76, 0x2f, 0x2f, (byte) 0x83, 0x34, +// 0x3c, (byte) 0xe9, (byte) 0xc2, (byte) 0xeb, 0x0e, (byte) 0xce, // +// 0x6c, (byte) 0xcd, 0x1c, (byte) 0xae, 0x74, 0x78, 0x3e, (byte) 0x8c, 0x17, +// (byte) 0xb4, 0x39, (byte) 0x9a, 0x21, (byte) 0x99, (byte) 0xde, (byte) 0xae, +// // +// 0x72, 0x23, (byte) 0x94, (byte) 0xc6, (byte) 0xe9, (byte) 0xcb, 0x48, (byte) +// 0xb1, 0x54, 0x20, 0x70, 0x70, (byte) 0xc0, 0x77, 0x10, 0x4b, // +// (byte) 0x8a, (byte) 0xe0, (byte) 0xa0, 0x6c, (byte) 0xb9, 0x65, (byte) 0xfc, +// 0x67, (byte) 0xe3, 0x3b, (byte) 0xb6, 0x46, 0x5e, (byte) 0xaf, (byte) 0xe7, +// (byte) 0x92, // +// 0x6a, (byte) 0xaf, (byte) 0x86, 0x4d, 0x74, 0x33, 0x49, 0x2a, (byte) 0xf0, +// (byte) 0xdd, 0x66, (byte) 0xce, (byte) 0xec, (byte) 0xcc, 0x6b, 0x62, // +// 0x4f, 0x35, (byte) 0xb5, 0x0f, (byte) 0x95, (byte) 0xd7, (byte) 0xf7, (byte) +// 0xf3, 0x4b, 0x59, 0x5f, 0x29, (byte) 0xc9, (byte) 0xc4, (byte) 0xdc, 0x47, // +// (byte) 0xe9, (byte) 0x8d, 0x47, (byte) 0xd2, 0x1d, 0x35, 0x43, (byte) 0xce, +// (byte) 0xff, (byte) 0xd7, 0x6b, 0x28, (byte) 0xd8, 0x06, (byte) 0xe8, (byte) +// 0xba, // +// (byte) 0xf1, 0x4d, (byte) 0xba, 0x43, (byte) 0x8e, 0x64, (byte) 0xba, (byte) +// 0xcd, (byte) 0xcb, (byte) 0xaf, 0x1a, 0x61, (byte) 0xd8, 0x11, 0x19, (byte) +// 0xf7, // +// (byte) 0xae, (byte) 0xfe, (byte) 0x94, 0x48, (byte) 0x8e, (byte) 0x9f, 0x57, +// 0x17, (byte) 0xd2, (byte) 0xa3, (byte) 0xfd, 0x79, (byte) 0xb5, (byte) 0xa3, +// 0x7d, (byte) 0xca, // +// (byte) 0xff, (byte) 0x94, (byte) 0xb5, (byte) 0xb5, 0x03, (byte) 0xf3, 0x13, +// 0x6a, 0x74, 0x7a, (byte) 0xae, (byte) 0x9d, (byte) 0xe9, 0x5c, 0x32, 0x42, // +// 0x37, (byte) 0xa6, (byte) 0xb3, (byte) 0xf5, 0x4b, (byte) 0xaa, 0x22, 0x61, +// (byte) 0xf5, 0x28, 0x5b, 0x41, 0x26, 0x32, 0x63, 0x5f, // +// 0x43, (byte) 0xfd, 0x2e, 0x44, 0x7d, (byte) 0xfb, (byte) 0xb6, 0x09, (byte) +// 0xc5, (byte) 0xc8, 0x33, (byte) 0xbe, (byte) 0x81, 0x08, (byte) 0xd4, 0x5f, +// // +// (byte) 0xad, (byte) 0xee, 0x49, 0x25, 0x62, 0x52, (byte) 0x83, (byte) 0xc1, +// 0x3e, 0x17, 0x5b, (byte) 0xea, 0x4b, (byte) 0x90, 0x62, (byte) 0xf7, // +// 0x4e, 0x28, (byte) 0xfb, (byte) 0xab, (byte) 0x9a, (byte) 0xbc, 0x5e, (byte) +// 0xd4, (byte) 0xd5, 0x56, (byte) 0xf4, 0x4a, 0x2a, 0x7e, (byte) 0xd7, // + +/* @formatter:on */ diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/asn1/AlgorithmIdentifier.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/asn1/AlgorithmIdentifier.java new file mode 100755 index 00000000000..94f83852e1b --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/asn1/AlgorithmIdentifier.java @@ -0,0 +1,40 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.ntlmssp.asn1; + +import common.asn1.Any; +import common.asn1.ObjectID; +import common.asn1.Sequence; +import common.asn1.Tag; + +/** + * X509 SubjectPublicKeyInfo field ASN.1 description. + */ +public class AlgorithmIdentifier extends Sequence { + public ObjectID algorithm = new ObjectID("algorithm"); + public Any parameters = new Any("parameters") { + { + optional = true; + } + }; + + public AlgorithmIdentifier(String name) { + super(name); + tags = new Tag[] {algorithm, parameters}; + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/asn1/NegoData.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/asn1/NegoData.java new file mode 100755 index 00000000000..ef0afc78745 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/asn1/NegoData.java @@ -0,0 +1,64 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.ntlmssp.asn1; + +import common.asn1.SequenceOf; +import common.asn1.Tag; + +/** + * The NegoData structure contains the SPNEGO messages, as specified in + * [MS-SPNG] section 2. + * + *
      + * NegoData ::= SEQUENCE OF SEQUENCE {
      + *   negoToken     [0] OCTET STRING
      + * }
      + * 
      + * + * If we write NegoItem as + * + *
      + * NegoItem ::= SEQUENCE {
      + *   negoToken     [0] OCTET STRING
      + * }
      + * 
      + * + * then NegoData can be written as + * + *
      + * NegoData ::= SEQUENCE OF NegoItem
      + * 
      + * + *
        + *
      • negoToken: One or more SPNEGO tokens, as specified in [MS-SPNG]. + *
      + * + * @see http://msdn.microsoft.com/en-us/library/cc226781.aspx + */ +public class NegoData extends SequenceOf { + + public NegoData(String name) { + super(name); + type = new NegoItem("NegoItem"); + } + + @Override + public Tag deepCopy(String suffix) { + return new NegoData(name + suffix).copyFrom(this); + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/asn1/NegoItem.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/asn1/NegoItem.java new file mode 100755 index 00000000000..2b8a26babd0 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/asn1/NegoItem.java @@ -0,0 +1,73 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.ntlmssp.asn1; + +import common.asn1.OctetString; +import common.asn1.Sequence; +import common.asn1.Tag; + +/** + * The NegoData structure contains the SPNEGO messages, as specified in + * [MS-SPNG] section 2. + * + *
      + * NegoData ::= SEQUENCE OF SEQUENCE {
      + *   negoToken     [0] OCTET STRING
      + * }
      + * 
      + * + * If we write NegoItem as + * + *
      + * NegoItem ::= SEQUENCE {
      + *   negoToken     [0] OCTET STRING
      + * }
      + * 
      + * + * then NegoData can be written as + * + *
      + * NegoData ::= SEQUENCE OF NegoItem
      + * 
      + * + *
        + *
      • negoToken: One or more SPNEGO tokens, as specified in [MS-SPNG]. + *
      + * + * @see http://msdn.microsoft.com/en-us/library/cc226781.aspx + */ +public class NegoItem extends Sequence { + + public OctetString negoToken = new OctetString("negoToken") { + { + explicit = true; + tagClass = CONTEXT_CLASS; + tagNumber = 0; + } + }; + + public NegoItem(String name) { + super(name); + tags = new Tag[] {negoToken}; + } + + @Override + public Tag deepCopy(String suffix) { + return new NegoItem(name + suffix).copyFrom(this); + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/asn1/SubjectPublicKeyInfo.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/asn1/SubjectPublicKeyInfo.java new file mode 100755 index 00000000000..c3e9137ffc0 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/asn1/SubjectPublicKeyInfo.java @@ -0,0 +1,35 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.ntlmssp.asn1; + +import common.asn1.BitString; +import common.asn1.Sequence; +import common.asn1.Tag; + +/** + * X509 SubjectPublicKeyInfo field ASN.1 description. + */ +public class SubjectPublicKeyInfo extends Sequence { + public AlgorithmIdentifier algorithm = new AlgorithmIdentifier("algorithm"); + public BitString subjectPublicKey = new BitString("subjectPublicKey"); + + public SubjectPublicKeyInfo(String name) { + super(name); + tags = new Tag[] {algorithm, subjectPublicKey}; + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/asn1/TSCredentials.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/asn1/TSCredentials.java new file mode 100755 index 00000000000..8142b04d341 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/asn1/TSCredentials.java @@ -0,0 +1,62 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.ntlmssp.asn1; + +import common.asn1.Asn1Integer; +import common.asn1.OctetString; +import common.asn1.Sequence; +import common.asn1.Tag; + +/** + *
      + * TSCredentials ::= SEQUENCE {
      + *   credType      [0] INTEGER,
      + *   credentials   [1] OCTET STRING
      + * }
      + *
      + * credType:
      + *   1 - credentials contains a TSPasswordCreds structure that defines the user's password credentials.
      + *   2 - credentials contains a TSSmartCardCreds structure that defines the user's smart card credentials.
      + * 
      + */ +public class TSCredentials extends Sequence { + public Asn1Integer credType = new Asn1Integer("credType") { + { + explicit = true; + tagClass = CONTEXT_CLASS; + tagNumber = 0; + } + }; + public OctetString credentials = new OctetString("credentials") { + { + explicit = true; + tagClass = CONTEXT_CLASS; + tagNumber = 1; + } + }; + + public TSCredentials(String name) { + super(name); + tags = new Tag[] {credType, credentials}; + } + + @Override + public Tag deepCopy(String suffix) { + return new TSCredentials(name + suffix).copyFrom(this); + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/asn1/TSCspDataDetail.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/asn1/TSCspDataDetail.java new file mode 100755 index 00000000000..86257c71694 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/asn1/TSCspDataDetail.java @@ -0,0 +1,98 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.ntlmssp.asn1; + +import common.asn1.Asn1Integer; +import common.asn1.OctetString; +import common.asn1.Sequence; +import common.asn1.Tag; + +/** + *
      + * TSCspDataDetail ::= SEQUENCE {
      + *   keySpec       [0] INTEGER,
      + *   cardName      [1] OCTET STRING OPTIONAL,
      + *   readerName    [2] OCTET STRING OPTIONAL,
      + *   containerName [3] OCTET STRING OPTIONAL,
      + *   cspName       [4] OCTET STRING OPTIONAL
      + * }
      + * 
      + *
        + *
      • keySpec: Defines the specification of the user's smart card. + * + *
      • cardName: Specifies the name of the smart card. + * + *
      • readerName: Specifies the name of the smart card reader. + * + *
      • containerName: Specifies the name of the certificate container. + * + *
      • cspName: Specifies the name of the CSP. + *
      + * @see http://msdn.microsoft.com/en-us/library/cc226785.aspx + */ +public class TSCspDataDetail extends Sequence { + public Asn1Integer keySpec = new Asn1Integer("keySpec") { + { + explicit = true; + tagClass = CONTEXT_CLASS; + tagNumber = 0; + } + }; + public OctetString cardName = new OctetString("cardName") { + { + explicit = true; + tagClass = CONTEXT_CLASS; + tagNumber = 1; + optional = true; + } + }; + public OctetString readerName = new OctetString("readerName") { + { + explicit = true; + tagClass = CONTEXT_CLASS; + tagNumber = 2; + optional = true; + } + }; + public OctetString containerName = new OctetString("containerName") { + { + explicit = true; + tagClass = CONTEXT_CLASS; + tagNumber = 3; + optional = true; + } + }; + public OctetString cspName = new OctetString("cspName") { + { + explicit = true; + tagClass = CONTEXT_CLASS; + tagNumber = 4; + optional = true; + } + }; + + public TSCspDataDetail(String name) { + super(name); + tags = new Tag[] {keySpec, cardName, readerName, containerName, cspName}; + } + + @Override + public Tag deepCopy(String suffix) { + return new TSCspDataDetail(name + suffix).copyFrom(this); + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/asn1/TSPasswordCreds.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/asn1/TSPasswordCreds.java new file mode 100755 index 00000000000..4922c075974 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/asn1/TSPasswordCreds.java @@ -0,0 +1,76 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.ntlmssp.asn1; + +import common.asn1.OctetString; +import common.asn1.Sequence; +import common.asn1.Tag; + +/** + *
      + * TSPasswordCreds ::= SEQUENCE {
      + *   domainName    [0] OCTET STRING,
      + *   userName      [1] OCTET STRING,
      + *   password      [2] OCTET STRING
      + * }
      + * 
      + * + *
        + *
      • domainName: Contains the name of the user's account domain, as defined in + * [MS-GLOS]. + * + *
      • userName: Contains the user's account name. + * + *
      • Password: Contains the user's account password. + *
      + * + * @see http://msdn.microsoft.com/en-us/library/cc226783.aspx + */ +public class TSPasswordCreds extends Sequence { + public OctetString domainName = new OctetString("domainName") { + { + explicit = true; + tagClass = CONTEXT_CLASS; + tagNumber = 0; + } + }; + public OctetString userName = new OctetString("userName") { + { + explicit = true; + tagClass = CONTEXT_CLASS; + tagNumber = 1; + } + }; + public OctetString password = new OctetString("password") { + { + explicit = true; + tagClass = CONTEXT_CLASS; + tagNumber = 2; + } + }; + + public TSPasswordCreds(String name) { + super(name); + tags = new Tag[] {domainName, userName, password}; + } + + @Override + public Tag deepCopy(String suffix) { + return new TSPasswordCreds(name + suffix).copyFrom(this); + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/asn1/TSRequest.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/asn1/TSRequest.java new file mode 100755 index 00000000000..c5ba5d62ba9 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/asn1/TSRequest.java @@ -0,0 +1,201 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.ntlmssp.asn1; + +import streamer.ByteBuffer; +import common.asn1.Asn1Integer; +import common.asn1.OctetString; +import common.asn1.Sequence; +import common.asn1.Tag; + +/** + * The TSRequest structure is the top-most structure used by the CredSSP client + * and CredSSP server. It contains the SPNEGO messages between the client and + * server, and either the public key authentication messages that are used to + * bind to the TLS session or the client credentials that are delegated to the + * server. The TSRequest message is always sent over the TLS-encrypted channel + * between the client and server in a CredSSP Protocol exchange (see step 1 in + * section 3.1.5). + * + *
      + * TSRequest ::= SEQUENCE {
      + *   version       [0] INTEGER,
      + *   negoTokens    [1] NegoData OPTIONAL,
      + *   authInfo      [2] OCTET STRING OPTIONAL,
      + *   pubKeyAuth    [3] OCTET STRING OPTIONAL
      + * }
      + *
      + * 
      + *
        + * + *
      • version: This field specifies the supported version of the CredSSP + * Protocol. This field MUST be 2. If the version is greater than 2, a version 2 + * client or server treats its peer as one that is compatible with version 2 of + * the CredSSP Protocol. + * + *
      • negoTokens: A NegoData structure, as defined in section 2.2.1.1, that + * contains the SPNEGO messages that are passed between the client and server. + * + *
      • authInfo: A TSCredentials structure, as defined in section 2.2.1.2, that + * contains the user's credentials that are delegated to the server. The + * authinfo field MUST be encrypted under the encryption key that is + * negotiated under the SPNEGO package. + * + *
      • pubKeyAuth: This field is used to assure that the public key that is used + * by the server during the TLS handshake belongs to the target server and not + * to a "man in the middle". The client encrypts the public key it received from + * the server (contained in the X.509 certificate) in the TLS handshake from + * step 1, by using the confidentiality support of SPNEGO. The public key that + * is encrypted is the ASN.1-encoded SubjectPublicKey sub-field of + * SubjectPublicKeyInfo from the X.509 certificate, as specified in [RFC3280] + * section 4.1. The encrypted key is encapsulated in the pubKeyAuth field of the + * TSRequest structure and is sent over the TLS channel to the server. After the + * client completes the SPNEGO phase of the CredSSP Protocol, it uses + * GSS_WrapEx() for the negotiated protocol to encrypt the server's public key. + * The pubKeyAuth field carries the message signature and then the encrypted + * public key to the server. In response, the server uses the pubKeyAuth field + * to transmit to the client a modified version of the public key (as described + * in section 3.1.5) that is encrypted under the encryption key that is + * negotiated under SPNEGO. + *
      + * + * @see http://msdn.microsoft.com/en-us/library/cc226780.aspx + */ +public class TSRequest extends Sequence { + public Asn1Integer version = new Asn1Integer("version") { + { + explicit = true; + tagClass = CONTEXT_CLASS; + tagNumber = 0; + } + }; + public NegoData negoTokens = new NegoData("negoTokens") { + { + explicit = true; + tagClass = CONTEXT_CLASS; + tagNumber = 1; + optional = true; + } + }; + public OctetString authInfo = new OctetString("authInfo") { + { + explicit = true; + tagClass = CONTEXT_CLASS; + tagNumber = 2; + optional = true; + } + }; + public OctetString pubKeyAuth = new OctetString("pubKeyAuth") { + { + explicit = true; + tagClass = CONTEXT_CLASS; + tagNumber = 3; + optional = true; + } + }; + + public TSRequest(String name) { + super(name); + tags = new Tag[] {version, negoTokens, authInfo, pubKeyAuth}; + } + + @Override + public Tag deepCopy(String suffix) { + return new TSRequest(name + suffix).copyFrom(this); + } + + /** + * Example. + */ + public static void main(String[] args) { + + /* @formatter:off */ + byte[] packet = new byte[] { + 0x30, (byte) 0x82, 0x01, 0x02, // TAG: [UNIVERSAL 16] (constructed) "SEQUENCE" LEN: 258 bytes + (byte) 0xa0, 0x03, // TAG: [0] (constructed) LEN: 3 bytes + 0x02, 0x01, 0x03, // TAG: [UNIVERSAL 2] (primitive) "INTEGER" LEN: 1 bytes, Version: 0x3 + (byte) 0xa1, (byte) 0x81, (byte) 0xfa, // TAG: [1] (constructed) LEN: 250 bytes + 0x30, (byte) 0x81, (byte) 0xf7, // TAG: [UNIVERSAL 16] (constructed) "SEQUENCE" LEN: 247 bytes + 0x30, (byte) 0x81, (byte) 0xf4, // TAG: [UNIVERSAL 16] (constructed) "SEQUENCE" LEN: 244 bytes + (byte) 0xa0, (byte) 0x81, (byte) 0xf1, // TAG: [0] (constructed) LEN: 241 bytes + 0x04, (byte) 0x81, (byte) 0xee, // TAG: [UNIVERSAL 4] (primitive) "OCTET STRING" LEN: 238 bytes + + 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00, // "NTLMSSP\0" + + 0x02, 0x00, 0x00, 0x00, // MessageType (CHALLENGE) + 0x1e, 0x00, 0x1e, 0x00, 0x38, 0x00, 0x00, 0x00, // TargetName (length: 30, allocated space: 30, offset: 56) + 0x35, (byte) 0x82, (byte) 0x8a, (byte) 0xe2, // NegotiateFlags TODO + 0x52, (byte) 0xbe, (byte) 0x83, (byte) 0xd1, (byte) 0xf8, (byte) 0x80, 0x16, 0x6a, // ServerChallenge + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Reserved + (byte) 0x98, 0x00, (byte) 0x98, 0x00, 0x56, 0x00, 0x00, 0x00, // TargetInfo (length: 152, allocated space: 152, offset: 86) + 0x06, 0x03, (byte) 0xd7, 0x24, 0x00, 0x00, 0x00, 0x0f, // Version (6.3, build 9431) , NTLM current revision: 15 + + + 0x57, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x2d, 0x00, 0x4c, 0x00, 0x4f, 0x00, 0x34, 0x00, 0x31, 0x00, 0x39, 0x00, 0x42, 0x00, 0x32, 0x00, 0x4c, 0x00, 0x53, 0x00, 0x52, 0x00, 0x30, 0x00, // Target name value: "WIN-LO419B2LSR0" + + // Target Info value: + + // Attribute list + + 0x02, 0x00, // Item Type: NetBIOS domain name (0x0002, LE) + 0x1e, 0x00, // Item Length: 30 (LE) + 0x57, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x2d, 0x00, 0x4c, 0x00, 0x4f, 0x00, 0x34, 0x00, 0x31, 0x00, 0x39, 0x00, 0x42, 0x00, 0x32, 0x00, 0x4c, 0x00, 0x53, 0x00, 0x52, 0x00, 0x30, 0x00, // "WIN-LO419B2LSR0" + + 0x01, 0x00, // Item Type: NetBIOS computer name (0x0001, LE) + 0x1e, 0x00, // Item Length: 30 (LE) + 0x57, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x2d, 0x00, 0x4c, 0x00, 0x4f, 0x00, 0x34, 0x00, 0x31, 0x00, 0x39, 0x00, 0x42, 0x00, 0x32, 0x00, 0x4c, 0x00, 0x53, 0x00, 0x52, 0x00, 0x30, 0x00, // "WIN-LO419B2LSR0" + + 0x04, 0x00, // Item Type: DNS domain name (0x0004, LE) + 0x1e, 0x00, // Item Length: 30 (LE) + 0x57, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x2d, 0x00, 0x4c, 0x00, 0x4f, 0x00, 0x34, 0x00, 0x31, 0x00, 0x39, 0x00, 0x42, 0x00, 0x32, 0x00, 0x4c, 0x00, 0x53, 0x00, 0x52, 0x00, 0x30, 0x00, // "WIN-LO419B2LSR0" + + 0x03, 0x00, // Item Type: DNS computer name (0x0003, LE) + 0x1e, 0x00, // Item Length: 30 (LE) + 0x57, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x2d, 0x00, 0x4c, 0x00, 0x4f, 0x00, 0x34, 0x00, 0x31, 0x00, 0x39, 0x00, 0x42, 0x00, 0x32, 0x00, 0x4c, 0x00, 0x53, 0x00, 0x52, 0x00, 0x30, 0x00, // "WIN-LO419B2LSR0" + + 0x07, 0x00, // Item Type: Timestamp (0x0007, LE) + 0x08, 0x00, // Item Length: 8 (LE) + (byte) 0x99, 0x4f, 0x02, (byte) 0xd8, (byte) 0xf4, (byte) 0xaf, (byte) 0xce, 0x01, // TODO + + // Attribute: End of list + 0x00, 0x00, + 0x00, 0x00, + }; + /* @formatter:on */ + + TSRequest request = new TSRequest("TSRequest"); + + // Read request from buffer + // System.out.println("Request BER tree before parsing: " + request); + ByteBuffer toReadBuf = new ByteBuffer(packet); + request.readTag(toReadBuf); + // System.out.println("Request BER tree after parsing: " + request); + + // System.out.println("version value: " + request.version.value); + // System.out.println("negoToken value: " + ((NegoItem) + // request.negoTokens.tags[0]).negoToken.value); + + // Write request to buffer and compare with original + ByteBuffer toWriteBuf = new ByteBuffer(packet.length + 100, true); + request.writeTag(toWriteBuf); + toWriteBuf.trimAtCursor(); + + if (!toReadBuf.equals(toWriteBuf)) + throw new RuntimeException("Data written to buffer is not equal to data read from buffer. \nExpected: " + toReadBuf + "\nActual: " + toWriteBuf + "."); + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/asn1/TSSmartCardCreds.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/asn1/TSSmartCardCreds.java new file mode 100755 index 00000000000..4e8fb36da47 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/asn1/TSSmartCardCreds.java @@ -0,0 +1,90 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.ntlmssp.asn1; + +import common.asn1.OctetString; +import common.asn1.Sequence; +import common.asn1.Tag; + +/** + *
      + * TSSmartCardCreds ::= SEQUENCE {
      + *   pin           [0] OCTET STRING,
      + *   cspData       [1] TSCspDataDetail,
      + *   userHint      [2] OCTET STRING OPTIONAL,
      + *   domainHint    [3] OCTET STRING OPTIONAL
      + * }
      + * 
      + * + *
        + *
      • pin: Contains the user's smart card PIN. + * + *
      • cspData: A TSCspDataDetail structure that contains information about the + * cryptographic service provider (CSP). + * + *
      • userHint: Contains the user's account hint. + * + *
      • domainHint: Contains the user's domain name to which the user's account + * belongs. This name could be entered by the user when the user is first + * prompted for the PIN. + *
      + * + * @see http://msdn.microsoft.com/en-us/library/cc226784.aspx + */ +public class TSSmartCardCreds extends Sequence { + public OctetString pin = new OctetString("pin") { + { + explicit = true; + tagClass = CONTEXT_CLASS; + tagNumber = 0; + } + }; + public TSCspDataDetail cspData = new TSCspDataDetail("cspData") { + { + explicit = true; + tagClass = CONTEXT_CLASS; + tagNumber = 1; + } + }; + public OctetString userHint = new OctetString("userHint") { + { + explicit = true; + tagClass = CONTEXT_CLASS; + tagNumber = 2; + optional = true; + } + }; + public OctetString domainHint = new OctetString("domainHint") { + { + explicit = true; + tagClass = CONTEXT_CLASS; + tagNumber = 3; + optional = true; + } + }; + + public TSSmartCardCreds(String name) { + super(name); + tags = new Tag[] {pin, cspData, userHint, domainHint}; + } + + @Override + public Tag deepCopy(String suffix) { + return new TSSmartCardCreds(name + suffix).copyFrom(this); + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/package-info.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/package-info.java new file mode 100755 index 00000000000..42e7c41d9d2 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ntlmssp/package-info.java @@ -0,0 +1,71 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +/** + * + * CredSSP/SPNEGO/NTLMSSP implementation. + * + * CredSSP ASN.1 definition: + * +
      +CredSSP DEFINITIONS EXPLICIT TAGS ::=
      +
      +BEGIN
      +
      +TSPasswordCreds ::= SEQUENCE {
      +  domainName    [0] OCTET STRING,
      +  userName      [1] OCTET STRING,
      +  password      [2] OCTET STRING
      +}
      +
      +TSCspDataDetail ::= SEQUENCE {
      +  keySpec       [0] INTEGER,
      +  cardName      [1] OCTET STRING OPTIONAL,
      +  readerName    [2] OCTET STRING OPTIONAL,
      +  containerName [3] OCTET STRING OPTIONAL,
      +  cspName       [4] OCTET STRING OPTIONAL
      +}
      +
      +TSSmartCardCreds ::= SEQUENCE {
      +  pin           [0] OCTET STRING,
      +  cspData       [1] TSCspDataDetail,
      +  userHint      [2] OCTET STRING OPTIONAL,
      +  domainHint    [3] OCTET STRING OPTIONAL
      +}
      +
      +TSCredentials ::= SEQUENCE {
      +  credType      [0] INTEGER,
      +  credentials   [1] OCTET STRING
      +}
      +
      +NegoData ::= SEQUENCE OF SEQUENCE {
      +  negoToken     [0] OCTET STRING
      +}
      +
      +TSRequest ::= SEQUENCE {
      +  version       [0] INTEGER,
      +  negoTokens    [1] NegoData OPTIONAL,
      +  authInfo      [2] OCTET STRING OPTIONAL,
      +  pubKeyAuth    [3] OCTET STRING OPTIONAL
      +}
      +
      +END
      +
      + +For packet flow, @see http://msdn.microsoft.com/en-us/library/cc226794.aspx + */ +package rdpclient.ntlmssp; + diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientConfirmActivePDU.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientConfirmActivePDU.java new file mode 100755 index 00000000000..b77f201dd77 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientConfirmActivePDU.java @@ -0,0 +1,1131 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.rdp; + +import streamer.BaseElement; +import streamer.ByteBuffer; +import streamer.Element; +import streamer.Link; +import streamer.Pipeline; +import streamer.PipelineImpl; +import streamer.debug.MockSink; +import streamer.debug.MockSource; +import common.ScreenDescription; + +/** + * @see http://msdn.microsoft.com/en-us/library/cc240488.aspx + */ +public class ClientConfirmActivePDU extends BaseElement { + + public static final String SOURCE_DESC = "MSTSC"; + + public static final int CAPSTYPE_BITMAP = 0x2; + + protected int numberCapabilities; + + protected RdpState state; + protected ScreenDescription screen; + + protected boolean desktopResize = false; + protected int prefferedBitsPerPixel = 16; + + public ClientConfirmActivePDU(String id, ScreenDescription screen, RdpState state) { + super(id); + this.state = state; + this.screen = screen; + } + + @Override + public void handleData(ByteBuffer aBuf, Link link) { + + // Body + ByteBuffer buf = new ByteBuffer(1024, true); + numberCapabilities = 0; + writeCapabilities(buf); + buf.trimAtCursor(); + + // Header + ByteBuffer header = createMCSHeader(buf); + + // Length of source descriptor, including NULL character (LE) + header.writeShortLE(SOURCE_DESC.length() + 1); + + // Length of combined capabilities + 4 bytes (number of capabilities and + // padding) (LE) + header.writeShortLE(buf.length + 4); + + header.writeString(SOURCE_DESC, RdpConstants.CHARSET_8); + header.writeByte(0); + + // Number of capabilities + header.writeShortLE(numberCapabilities); + + // Padding 2 bytes + header.writeShortLE(0); + + header.trimAtCursor(); + + // Prepend header to capabilities + buf.prepend(header); + + // Trim buffer to actual length of data written + buf.trimAtCursor(); + + pushDataToPad(STDOUT, buf); + + sendOtherRequredPackets(); + + } + + private ByteBuffer createMCSHeader(ByteBuffer buf) { + ByteBuffer header = new ByteBuffer(100); + // MCS Send Data Request + header.writeByte(0x64); + + // Initiator: 1004 (1001+3) + header.writeShort(3); + + // Channel ID: 1003 (I/O channel) + header.writeShort(RdpConstants.CHANNEL_IO); + + // Data priority: high (0x40), segmentation: begin (0x20) | end (0x10) + header.writeByte(0x70); + + int length = buf.length + 26; + + // User data length: (variable length field, LE) + header.writeVariableShort(length); + + // Total length: (LE) + header.writeShortLE(length); + + // PDU type: Confirm Active PDU (0x3), TS_PROTOCOL_VERSION (0x10) (LE) + header.writeShortLE(0x13); + + // PDU source: 1004 (LE) + header.writeShortLE(1004); + + // Share ID, e.g. 0x000103ea (LE) + header.writeIntLE((int)state.serverShareId); + + // Originator ID: 1002 (LE) + header.writeShortLE(1002); + return header; + } + + private void sendOtherRequredPackets() { + // Send sequence in bulk + + sendSynchronizePDU(); + sendControlPDUActionCooperate(); + sendControlPDUActionRequestControl(); + // sendBitmapCachePersistentListPDU(); + sendFontListPDU(); + } + + private void sendFontListPDU() { + { + int length = 1024; // Large enough + ByteBuffer buf = new ByteBuffer(length, true); + + /* @formatter:off */ + buf.writeBytes(new byte[] { + // MCS Send Data Request + (byte)0x64, + // Initiator: 1004 (1001+3) + (byte)0x00, (byte)0x03, + // Channel ID: 1003 (I/O channel) + (byte)0x03, (byte)0xeb, + // Data priority: high (0x40), segmentation: begin (0x20) | end (0x10) + (byte)0x70, + // User data length: 26 bytes (0x1a, variable length field) + (byte)0x80, (byte)0x1a, + + // Total length: 26 bytes (0x1a, LE) + (byte)0x1a, (byte)0x00, + // PDU type: PDUTYPE_DATAPDU (0x7), PDU version: 1 (0x0010) (LE) + (byte)0x17, (byte)0x00, + // PDU source: 1004 (LE) + (byte)0xec, (byte)0x03, + }); + // Share ID, 4 bytes (LE) + buf.writeIntLE((int)state.serverShareId); + + buf.writeBytes(new byte[] { + // Padding 1 byte + (byte)0x00, + // Stream ID: STREAM_LOW (1) + (byte)0x01, + // uncompressedLength : 12 bytes (LE) + (byte)0x0c, (byte)0x00, + + // pduType2: PDUTYPE2_FONTLIST (39) + (byte)0x27, + // generalCompressedType: 0 + (byte)0x00, + // generalCompressedLength: 0 (LE) + (byte)0x00, (byte)0x00, + + // numberEntries (should be set to zero): 0 (LE) + (byte)0x00, (byte)0x00, + // totalNumEntries (should be set to zero): 0 (LE) + (byte)0x00, (byte)0x00, + // listFlags (should be set to 0x3): 0x0003 (LE), FONTLIST_LAST(0x2) | FONTLIST_FIRST(0x1) + (byte)0x03, (byte)0x00, + // entrySize: 50 bytes (0x0032, LE) + (byte)0x32, (byte)0x00, + }); + /* @formatter:on */ + + // Trim buffer to actual length of data written + buf.trimAtCursor(); + + pushDataToPad(STDOUT, buf); + } + } + + private void sendControlPDUActionRequestControl() { + int length = 1024; // Large enough + ByteBuffer buf = new ByteBuffer(length, true); + + /* @formatter:off */ + buf.writeBytes(new byte[] { + // MCS Send Data Request + (byte)0x64, + // Initiator: 1004 (1001+3) + (byte)0x00, (byte)0x03, + // Channel ID: 1003 (I/O channel) + (byte)0x03, (byte)0xeb, + // Data priority: high (0x40), segmentation: begin (0x20) | end (0x10) + (byte)0x70, + // User data length: 26 bytes (0x1a, variable length field) + (byte)0x80, (byte)0x1a, + + // Total length: 26 bytes (0x1a, LE) + (byte)0x1a, (byte)0x00, + // PDU type: PDUTYPE_DATAPDU (0x7), PDU version: 1 (0x0010) (LE) + (byte)0x17, (byte)0x00, + // PDU source: 1004 (LE) + (byte)0xec, (byte)0x03, + }); + // Share ID, 4 bytes (LE) + buf.writeIntLE((int)state.serverShareId); + + buf.writeBytes(new byte[] { + // Padding 1 byte + (byte)0x00, + // Stream ID: STREAM_LOW (1) + (byte)0x01, + // uncompressedLength : 12 bytes (LE) + (byte)0x0c, (byte)0x00, + // pduType2: PDUTYPE2_CONTROL (20) + (byte)0x14, + // generalCompressedType: 0 + (byte)0x00, + // generalCompressedLength: 0 (LE) + (byte)0x00, (byte)0x00, + + // action: CTRLACTION_REQUEST_CONTROL (1) (LE) + (byte)0x01, (byte)0x00, + // grantId: 0 (LE) + (byte)0x00, (byte)0x00, + // controlId: 0 (LE) + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + }); + /* @formatter:on */ + + // Trim buffer to actual length of data written + buf.trimAtCursor(); + + pushDataToPad(STDOUT, buf); + } + + private void sendControlPDUActionCooperate() { + int length = 1024; // Large enough + ByteBuffer buf = new ByteBuffer(length, true); + + /* @formatter:off */ + buf.writeBytes(new byte[] { + // MCS Send Data Request + (byte)0x64, + // Initiator: 1004 (1001+3) + (byte)0x00, (byte)0x03, + // Channel ID: 1003 (I/O channel) + (byte)0x03, (byte)0xeb, + // Data priority: high (0x40), segmentation: begin (0x20) | end (0x10) + (byte)0x70, + // User data length: 26 bytes (0x1a, variable length field) + (byte)0x80, (byte)0x1a, + + // Total length: 26 bytes (0x1a, LE) + (byte)0x1a,(byte)0x00, + // PDU type: PDUTYPE_DATAPDU (0x7), PDU version: 1 (0x0010) (LE) + (byte)0x17, (byte)0x00, + // PDU source: 1004 (LE) + (byte)0xec, (byte)0x03, + }); + // Share ID, 4 bytes (LE) + buf.writeIntLE((int)state.serverShareId); + + buf.writeBytes(new byte[] { + // Padding 1 byte + (byte)0x00, + // Stream ID: STREAM_LOW (1) + (byte)0x01, + // uncompressedLength : 12 bytes (LE) + (byte)0x0c, (byte)0x00, + // pduType2: PDUTYPE2_CONTROL (20) + (byte)0x14, + // generalCompressedType: 0 + (byte)0x00, + // generalCompressedLength: 0 (LE?) + (byte)0x00, (byte)0x00, + // action: CTRLACTION_COOPERATE (4) (LE) + (byte)0x04, (byte)0x00, + // grantId: 0 (LE) + (byte)0x00, (byte)0x00, + // controlId: 0 + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + }); + /* @formatter:on */ + + buf.trimAtCursor(); + + pushDataToPad(STDOUT, buf); + } + + private void sendSynchronizePDU() { + + ByteBuffer buf = new ByteBuffer(1024, true); + /* @formatter:off */ + buf.writeBytes(new byte[] { + // MCS send data request + (byte)0x64, + // Initiator: 1004 (1001+3) + (byte)0x00, (byte)0x03, + // Channel ID: 1003 (I/O Channel) + (byte)0x03, (byte)0xeb, + // Data priority: high (0x40), segmentation: begin (0x20) | end (0x10) + (byte)0x70, + // Data length: 22 bytes (0x16, variable length field) + (byte)0x80, (byte)0x16, + + // RDP: total length: 22 bytes (LE) + (byte)0x16, (byte)0x00, + + // PDU type: PDUTYPE_DATAPDU (0x7), TS_PROTOCOL_VERSION (0x10) (LE) + (byte)0x17, (byte)0x00, + + // PDU source: 1007 (LE) + (byte)0xec, (byte)0x03, + }); + // Share ID, 4 bytes (LE) + buf.writeIntLE((int)state.serverShareId); + + buf.writeBytes(new byte[] { + // Padding: 1 byte + (byte)0x00, + // Stream ID: STREAM_LOW (1) + (byte)0x01, + // uncompressedLength : 8 bytes (LE) + (byte)0x08, (byte)0x00, + // pduType2 = PDUTYPE2_SYNCHRONIZE (31) + (byte)0x1f, + // generalCompressedType: 0 + (byte)0x00, + // generalCompressedLength: 0 (LE?) + (byte)0x00, (byte)0x00, + // messageType: SYNCMSGTYPE_SYNC (1) (LE) + (byte)0x01, (byte)0x00, + // targetUser: 0x03ea + (byte)0xea, (byte)0x03, + }); + /* @formatter:on */ + buf.trimAtCursor(); + pushDataToPad(STDOUT, buf); + } + + private void writeCapabilities(ByteBuffer buf) { + writeGeneralCS(buf); + + writeBitmapCS(buf); + + writeOrderCS(buf); + + writeBitmapCache2CS(buf); + + writeColorTableCacheCS(buf); + + writeWindowActivationCS(buf); + + writeControlCS(buf); + + writePointerCS(buf); + + writeShareCS(buf); + + writeInputCS(buf); + + writeBrushCS(buf); + + writeSoundCS(buf); + + writeFontCS(buf); + + writeOffscreenBitmapCS(buf); + + writeGlyphCacheCS(buf); + } + + private void writeBrushCS(ByteBuffer buf) { + numberCapabilities++; + buf.writeBytes(new byte[] { + // + // Brush Capability Set (8 bytes), see + // http://msdn.microsoft.com/en-us/library/cc240564.aspx + (byte)0x0f, (byte)0x00, // capability set type: CAPSTYPE_BRUSH (15, + // LE) + (byte)0x08, (byte)0x00, // length of capability set: 8 bytes (LE) + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // brushSupportLevel: + // BRUSH_DEFAULT + // (0x0, LE) + + }); + } + + private void writeInputCS(ByteBuffer buf) { + numberCapabilities++; + buf.writeBytes(new byte[] { + // + // Input Capability Set (88 bytes), see + // http://msdn.microsoft.com/en-us/library/cc240563.aspx + (byte)0x0d, + (byte)0x00, // capability set type: CAPSTYPE_INPUT (13, LE) + (byte)0x58, + (byte)0x00, // length of capability set: 88 bytes (LE) + (byte)0x35, + (byte)0x00, // inputFlags: 0x0035 (LE), INPUT_FLAG_FASTPATH_INPUT2 + // (0x20), INPUT_FLAG_VKPACKET (0x10), INPUT_FLAG_MOUSEX + // (0x4), INPUT_FLAG_SCANCODES (0x1) + (byte)0x00, + (byte)0x00, // Padding 2 bytes + (byte)0x09, + (byte)0x04, + (byte)0x00, + (byte)0x00, // keyboardLayout: "US" keyboard layout (0x000409, LE) + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, // keyboardType: unknown (LE) + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, // keyboardSubType: unknown (LE) + (byte)0x00, + (byte)0x00, + (byte)0x00, + (byte)0x00, // keyboardFunctionKey: unknown (LE) + // imeFileName: "", (64 bytes, including trailing NULL characters, UCS2) + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + + }); + } + + private void writeShareCS(ByteBuffer buf) { + numberCapabilities++; + buf.writeBytes(new byte[] { + // + // Share Capability Set (8 bytes), see + // http://msdn.microsoft.com/en-us/library/cc240570.aspx + (byte)0x09, (byte)0x00, // capability set type: CAPSTYPE_SHARE (9, LE) + (byte)0x08, (byte)0x00, // length of capability set: 8 bytes (LE) + (byte)0x00, (byte)0x00, // nodeID (must be set to 0 by client): 0 (LE) + (byte)0x00, (byte)0x00, // Padding 2 bytes (LE) + + }); + } + + private void writePointerCS(ByteBuffer buf) { + numberCapabilities++; + buf.writeBytes(new byte[] { + // + // Pointer Capability Set (10 bytes), see + // http://msdn.microsoft.com/en-us/library/cc240562.aspx + (byte)0x08, (byte)0x00, // capability set type: CAPSTYPE_POINTER (8, + // LE) + (byte)0x0a, (byte)0x00, // length of capability set: 10 bytes (LE) + (byte)0x00, (byte)0x00, // colorPointerFlag: FALSE (LE) + (byte)0x00, (byte)0x00, // colorPointerCacheSize: 0 (LE) + (byte)0x14, (byte)0x00, // pointerCacheSize: 20 (LE) + + }); + } + + private void writeControlCS(ByteBuffer buf) { + numberCapabilities++; + buf.writeBytes(new byte[] { + // + // Control Capability Set (12 bytes), see + // http://msdn.microsoft.com/en-us/library/cc240568.aspx + (byte)0x05, (byte)0x00, // capability set type: CAPSTYPE_ACTIVATION + // (7) + (byte)0x0c, (byte)0x00, // length of capability set: 12 bytes (LE) + (byte)0x00, (byte)0x00, // controlFlags (should be set to 0): 0 (LE) + (byte)0x00, (byte)0x00, // remoteDetachFlag (should be set to 0): 0 + // (LE) + (byte)0x02, (byte)0x00, // controlInterest (should be set to + // CONTROLPRIORITY_NEVER): + // CONTROLPRIORITY_NEVER (2) (LE) + (byte)0x02, (byte)0x00, // detachInterest (should be set to + // CONTROLPRIORITY_NEVER): + // CONTROLPRIORITY_NEVER (2) (LE) + + }); + } + + private void writeWindowActivationCS(ByteBuffer buf) { + numberCapabilities++; + buf.writeBytes(new byte[] { + // + // Window Activation Capability Set (12 bytes), see + // http://msdn.microsoft.com/en-us/library/cc240569.aspx + (byte)0x07, (byte)0x00, // capability set type: CAPSTYPE_ACTIVATION + // (7) (LE) + (byte)0x0c, (byte)0x00, // length of capability set: 12 bytes (LE) + (byte)0x00, (byte)0x00, // helpKeyFlag (should be set to FALSE (0)): + // FALSE (0, LE) + (byte)0x00, (byte)0x00, // helpKeyIndexFlag (should be set to FALSE + // (0)): FALSE (0, LE) + (byte)0x00, (byte)0x00, // helpExtendedKeyFlag (should be set to FALSE + // (0)): FALSE (0, LE) + (byte)0x00, (byte)0x00, // windowManagerKeyFlag (should be set to + // FALSE (0)): FALSE (0, LE) + + }); + } + + private void writeColorTableCacheCS(ByteBuffer buf) { + numberCapabilities++; + buf.writeBytes(new byte[] { + + // + // Color Table Cache Capability Set (8 bytes), see + // http://msdn.microsoft.com/en-us/library/cc241564.aspx + (byte)0x0a, (byte)0x00, // capability set type: CAPSTYPE_COLORCACHE + // (10) (LE) + (byte)0x08, (byte)0x00, // length of capability set: 8 bytes (LE) + (byte)0x06, (byte)0x00, // Color table cache size (must be ignored + // during capability exchange and is assumed + // to be 0x0006): 6 (LE) + (byte)0x00, (byte)0x00, // Padding 2 bytes + + }); + } + + private void writeBitmapCache2CS(ByteBuffer buf) { + numberCapabilities++; + buf.writeBytes(new byte[] { + // + // Bitmap Cache Rev. 2 Capability Set (40 bytes), see + // http://msdn.microsoft.com/en-us/library/cc240560.aspx + (byte)0x13, (byte)0x00, // capability set type: + // CAPSTYPE_BITMAPCACHE_REV2 (19) (LE) + (byte)0x28, (byte)0x00, // length of capability set: 40 bytes (LE) + (byte)0x00, (byte)0x00, // Cache flags: 0 (LE) + (byte)0x00, // Padding 1 byte + (byte)0x00, // Number of cell caches: 0 + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Bitmap cache0 + // cell info: 0 (LE) + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Bitmap cache1 + // cell info: 0 (LE) + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Bitmap cache2 + // cell info: 0 (LE) + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Bitmap cache3 + // cell info: 0 (LE) + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Bitmap cache4 + // cell info: 0 (LE) + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Padding 12 bytes + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Padding + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Padding + }); + } + + private void writeGeneralCS(ByteBuffer buf) { + numberCapabilities++; + buf.writeBytes(new byte[] { + // Capabilities, see + // http://msdn.microsoft.com/en-us/library/cc240486.aspx + + // + // General capability set (24 bytes), see + // http://msdn.microsoft.com/en-us/library/cc240549.aspx + (byte)0x01, (byte)0x00, // capability set type: CAPSTYPE_GENERAL (1) + // (LE) + (byte)0x18, (byte)0x00, // length of capability set: 24 bytes (LE) + (byte)0x01, (byte)0x00, // TS_OSMAJORTYPE_WINDOWS (1) (LE) + (byte)0x03, (byte)0x00, // TS_OSMINORTYPE_WINDOWS_NT (3) (LE) + (byte)0x00, (byte)0x02, // TS_CAPS_PROTOCOLVERSION (0x0200) (LE) + (byte)0x00, (byte)0x00, // Padding 2 bytes + (byte)0x00, (byte)0x00, // generalCompressionTypes: 0 (LE) + + // Extra flags: 0x040d (LE) + // FastPathOutput: (...............1) Advertiser supports fast-path + // output + // ShadowCompression: (..............0.) Advertiser NOT supports shadow + // compression + // LongLengthCredentials: (.............1..) Advertiser supports + // long-length credentials for the user name, password, or domain name + // SessionAutoreconnection: (............1...) Advertiser supports + // session auto-reconnection + // ImprovedEncryptionChecksum: (...........0....) Client and server NOT + // support improved encryption checksum + // Reserved1: (......00000.....) + // CompressedBitMapDataFlag: (.....1..........) No 8-UINT8 header is + // present for compressed bitmap data + // Reserved2: (00000...........) + (byte)0x0d, (byte)0x04, + + (byte)0x00, (byte)0x00, // updateCapabilityFlag: 0 (LE) + (byte)0x00, (byte)0x00, // remoteUnshareFlag: 0 (LE) + (byte)0x00, (byte)0x00, // generalCompressionLevel: 0 (LE) + (byte)0x00, // refreshRectSupport: FALSE (0) + (byte)0x00, // suppressOutputSupport: FALSE (0) + + }); + } + + private void writeBitmapCS(ByteBuffer buf) { + // Bitmap capability set (28 bytes), see + // http://msdn.microsoft.com/en-us/library/cc240554.aspx + + numberCapabilities++; + + // Capability set type: CAPSTYPE_BITMAP (2) (LE) + buf.writeShortLE(CAPSTYPE_BITMAP); + + // Length of capability set: 28 bytes (LE) + buf.writeShortLE(28); + + // preferredBitsPerPixel: 16 bpp (LE) + buf.writeShortLE(prefferedBitsPerPixel); + + // receive1BitPerPixel (ignored and SHOULD be set to TRUE (0x1)): TRUE (0x1) (LE) + buf.writeShortLE(1); + + // receive4BitsPerPixel (ignored and SHOULD be set to TRUE (0x1)): TRUE (0x1) (LE) + buf.writeShortLE(1); + + // receive8BitsPerPixel (ignored and SHOULD be set to TRUE (0x1)): TRUE (0x1) (LE) + buf.writeShortLE(1); + + // Desktop width and height (LE) + buf.writeShortLE(screen.getFramebufferWidth()); + buf.writeShortLE(screen.getFramebufferHeight()); + + // Padding 2 bytes + buf.writeShortLE(0); + + // desktopResizeFlag (LE) + buf.writeShortLE((desktopResize) ? 1 : 0); + + buf.writeBytes(new byte[] { + (byte)0x01, (byte)0x00, // bitmapCompressionFlag (must be set to TRUE + // (0x1)): TRUE (0x1) (LE) + (byte)0x00, // highColorFlags (field is ignored and SHOULD be set to + // zero): 0 + (byte)0x01, // drawingFlags: 0x1 TODO: padding, why 0x1 ??? + (byte)0x01, (byte)0x00, // multipleRectangleSupport: TRUE (LE) + (byte)0x00, (byte)0x00, // Padding 2 bytes + + }); + } + + private void writeOrderCS(ByteBuffer buf) { + numberCapabilities++; + buf.writeBytes(new byte[] { + // + // Order Capability Set (88 bytes), see + // http://msdn.microsoft.com/en-us/library/cc240556.aspx + (byte)0x03, + (byte)0x00, // capability set type: CAPSTYPE_ORDER (3) (LE) + (byte)0x58, + (byte)0x00, // length of capability set: 88 bytes (LE) + // terminalDescriptor = "" (16 bytes, UCS2) + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // pad4octetsA + (byte)0x01, (byte)0x00, // desktopSaveXGranularity (ignored): 1 (LE) + (byte)0x14, (byte)0x00, // desktopSaveYGranularity (ignored): 20 (LE) + (byte)0x00, (byte)0x00, // pad2octetsA (ignored) + (byte)0x01, (byte)0x00, // maximumOrderLevel: ORD_LEVEL_1_ORDERS (1) + (byte)0x00, (byte)0x00, // number of fonts (ignored): 0 + (byte)0x4a, (byte)0x00, // orderFlags = 0x004a (LE), + // SOLIDPATTERNBRUSHONLY (0x40), + // ZEROBOUNDSDELTASSUPPORT (0x8, MUST), + // NEGOTIATEORDERSUPPORT (0x2, MUST) + // Order support: 32 bytes (no primary drawing orders are supported, so + // this array MUST be initialized to all zeros, use 0x01 for TRUE). + (byte)0x00, // TS_NEG_DSTBLT_INDEX: FALSE + (byte)0x00, // TS_NEG_PATBLT_INDEX: FALSE + (byte)0x00, // TS_NEG_SCRBLT_INDEX: FALSE + (byte)0x00, // TS_NEG_MEMBLT_INDEX: FALSE + (byte)0x00, // TS_NEG_MEM3BLT_INDEX: FALSE + (byte)0x00, // TS_NEG_ATEXTOUT_INDEX: FALSE + (byte)0x00, // TS_NEG_AEXTTEXTOUT_INDEX: FALSE + (byte)0x00, // TS_NEG_DRAWNINEGRID_INDEX: FALSE + (byte)0x00, // TS_NEG_LINETO_INDEX: FALSE + (byte)0x00, // TS_NEG_MULTI_DRAWNINEGRID_INDEX: FALSE + (byte)0x00, // TS_NEG_OPAQUERECT_INDEX: FALSE + (byte)0x00, // TS_NEG_SAVEBITMAP_INDEX: FALSE + (byte)0x00, // TS_NEG_WTEXTOUT_INDEX: FALSE + (byte)0x00, // TS_NEG_MEMBLT_R2_INDEX: FALSE + (byte)0x00, // TS_NEG_MEM3BLT_R2_INDEX: FALSE + (byte)0x00, // TS_NEG_MULTIDSTBLT_INDEX: FALSE + (byte)0x00, // TS_NEG_MULTIPATBLT_INDEX: FALSE + (byte)0x00, // TS_NEG_MULTISCRBLT_INDEX: FALSE + (byte)0x00, // TS_NEG_MULTIOPAQUERECT_INDEX: FALSE + (byte)0x00, // TS_NEG_FAST_INDEX_INDEX: FALSE + (byte)0x00, // TS_NEG_POLYGON_SC_INDEX: FALSE + (byte)0x00, // TS_NEG_POLYGON_CB_INDEX: FALSE + (byte)0x00, // TS_NEG_POLYLINE_INDEX: TRUE + (byte)0x00, // Unused: 0 + (byte)0x00, // TS_NEG_FAST_GLYPH_INDEX: FALSE + (byte)0x00, // TS_NEG_ELLIPSE_SC_INDEX: FALSE + (byte)0x00, // TS_NEG_ELLIPSE_CB_INDEX: FALSE + (byte)0x00, // TS_NEG_INDEX_INDEX: FALSE + (byte)0x00, // TS_NEG_WEXTTEXTOUT_INDEX: FALSE + (byte)0x00, // TS_NEG_WLONGTEXTOUT_INDEX: FALSE + (byte)0x00, // TS_NEG_WLONGEXTTEXTOUT_INDEX: FALSE + (byte)0x00, // Unused: 0 + (byte)0x00, (byte)0x00, // Text flags (ignored): 0 (LE) + (byte)0x00, (byte)0x00, // Order support extra flags: 0 (LE) + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Padding 4 bytes + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Desktop save size + // (ignored): 0 + // (assumed to be + // 230400 bytes + // (480*480, + // 0x38400, LE)) + (byte)0x00, (byte)0x00, // Padding 2 bytes + (byte)0x00, (byte)0x00, // Padding 2 bytes + (byte)0xe4, (byte)0x04, // Text ANSI Code Page: 1252, ANSI - Latin I + // (0x04e4, LE) + (byte)0x00, (byte)0x00, // Padding 2 bytes + + }); + } + + private void writeSoundCS(ByteBuffer buf) { + numberCapabilities++; + buf.writeBytes(new byte[] { + // + // Sound Capability Set (8 bytes), see + // http://msdn.microsoft.com/en-us/library/cc240552.aspx + (byte)0x0c, (byte)0x00, // capability set type: CAPSTYPE_SOUND (12, + // LE) + (byte)0x08, (byte)0x00, // length of capability set: 8 bytes (LE) + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // soundFlags: + // 0x0000 (LE) // + // SOUND_FLAG_BEEPS + // (0x1) + + }); + } + + private void writeFontCS(ByteBuffer buf) { + numberCapabilities++; + buf.writeBytes(new byte[] { + // + // Font Capability Set (8 bytes), see + // http://msdn.microsoft.com/en-us/library/cc240571.aspx + (byte)0x0e, (byte)0x00, (byte)0x08, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, + + }); + } + + private void writeOffscreenBitmapCS(ByteBuffer buf) { + numberCapabilities++; + buf.writeBytes(new byte[] { + // + // Offscreen Bitmap Cache Capability Set (12 bytes), see + // http://msdn.microsoft.com/en-us/library/cc240550.aspx + (byte)0x11, (byte)0x00, // capability set type: + // CAPSTYPE_OFFSCREENCACHE (17, LE) + (byte)0x0c, (byte)0x00, // length of capability set: 12 bytes (LE) + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // offscreenSupportLevel: + // FALSE (LE) + (byte)0x00, (byte)0x00, // offscreenCacheSize: 0 (LE) + (byte)0x00, (byte)0x00, // offscreenCacheEntries: 0 (LE) + + }); + } + + private void writeGlyphCacheCS(ByteBuffer buf) { + numberCapabilities++; + buf.writeBytes(new byte[] { + // + // Glyph Cache Capability Set (52 bytes), see + // http://msdn.microsoft.com/en-us/library/cc240565.aspx + (byte)0x10, (byte)0x00, // capability set type: + // CAPSTYPE_OFFSCREENCACHE (16, LE) + (byte)0x34, (byte)0x00, // length of capability set: 52 bytes (LE) + // Glyph Cache (40 bytes) + (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) + (byte)0x04, (byte)0x00, // CacheMaximumCellSize: 4 (LE) + (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) + (byte)0x04, (byte)0x00, // CacheMaximumCellSize: 4 (LE) + (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) + (byte)0x08, (byte)0x00, // CacheMaximumCellSize: 4 (LE) + (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) + (byte)0x08, (byte)0x00, // CacheMaximumCellSize: 4 (LE) + (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) + (byte)0x10, (byte)0x00, // CacheMaximumCellSize: 4 (LE) + (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) + (byte)0x20, (byte)0x00, // CacheMaximumCellSize: 4 (LE) + (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) + (byte)0x40, (byte)0x00, // CacheMaximumCellSize: 4 (LE) + (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) + (byte)0x80, (byte)0x00, // CacheMaximumCellSize: 4 (LE) + (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) + (byte)0x00, (byte)0x01, // CacheMaximumCellSize: 4 (LE) + (byte)0x40, (byte)0x00, // CacheEntries: 64 (LE) + (byte)0x00, (byte)0x08, // CacheMaximumCellSize: 2048 (LE) + // FragCache + (byte)0x00, (byte)0x01, // CacheEntries: 256 (LE) + (byte)0x00, (byte)0x01, // CacheMaximumCellSize: 256 (LE) + // + (byte)0x00, (byte)0x00, // GlyphSupportLevel: GLYPH_SUPPORT_NONE (0x0, + // LE) + (byte)0x00, (byte)0x00, // Padding 2 bytes + }); + } + + /** + * Example. + */ + public static void main(String args[]) { + // System.setProperty("streamer.Link.debug", "true"); + System.setProperty("streamer.Element.debug", "true"); + // System.setProperty("streamer.Pipeline.debug", "true"); + + /* @formatter:off */ + byte[] packet = new byte[] { + // MCS Send Data Request + (byte)0x64, + + // Initiator: 1004 (1001+3) + (byte)0x00, (byte)0x03, + + // Channel ID: 1003 (I/O channel) + (byte)0x03, (byte)0xeb, + + // Data priority: high (0x40), segmentation: begin (0x20) | end (0x10) + (byte)0x70, + + // User data length: 432 bytes (0x1b0, variable length field) + (byte)0x81, (byte)0xb0, + + // Total length: 432 bytes (0x1b0, LE) + (byte)0xb0, (byte)0x01, + + // PDU type: Confirm Active PDU (0x3), TS_PROTOCOL_VERSION (0x10) (LE) + (byte)0x13, (byte)0x00, + + // PDU source: 1004 (LE) + (byte)0xec, (byte)0x03, + + // Share ID: 0x000103ea (LE) + (byte)0xea, (byte)0x03, (byte)0x01, (byte)0x00, + + // Originator ID: 1002 (LE) + (byte)0xea, (byte)0x03, + + // Length of source descriptor: 6 bytes (including NULL character) (LE) + (byte)0x06, (byte)0x00, + + // Length of combined capabilities: 410 bytes (LE) + (byte)0x9a, (byte)0x01, + + // Source descriptor: "MSTSC" ??? + (byte)0x4d, (byte)0x53, (byte)0x54, (byte)0x53, (byte)0x43, (byte)0x00, + + // Number of capabilities: 15 (LE) + (byte)0x0f, (byte)0x00, + + // Padding 2 bytes + (byte)0x00, (byte)0x00, + + // Capabilities, see http://msdn.microsoft.com/en-us/library/cc240486.aspx + + // + // General capability set (24 bytes), see http://msdn.microsoft.com/en-us/library/cc240549.aspx + (byte)0x01, (byte)0x00, // capability set type: CAPSTYPE_GENERAL (1) (LE) + (byte)0x18, (byte)0x00, // length of capability set: 24 bytes (LE) + (byte)0x01, (byte)0x00, // TS_OSMAJORTYPE_WINDOWS (1) (LE) + (byte)0x03, (byte)0x00, // TS_OSMINORTYPE_WINDOWS_NT (3) (LE) + (byte)0x00, (byte)0x02, // TS_CAPS_PROTOCOLVERSION (0x0200) (LE) + (byte)0x00, (byte)0x00, // Padding 2 bytes + (byte)0x00, (byte)0x00, // generalCompressionTypes: 0 (LE) + + // Extra flags: 0x040d (LE) +// FastPathOutput: (...............1) Advertiser supports fast-path output +// ShadowCompression: (..............0.) Advertiser NOT supports shadow compression +// LongLengthCredentials: (.............1..) Advertiser supports long-length credentials for the user name, password, or domain name +// SessionAutoreconnection: (............1...) Advertiser supports session auto-reconnection +// ImprovedEncryptionChecksum: (...........0....) Client and server NOT support improved encryption checksum +// Reserved1: (......00000.....) +// CompressedBitMapDataFlag: (.....1..........) No 8-UINT8 header is present for compressed bitmap data +// Reserved2: (00000...........) + (byte)0x0d, (byte)0x04, + + (byte)0x00, (byte)0x00, // updateCapabilityFlag: 0 (LE) + (byte)0x00, (byte)0x00, // remoteUnshareFlag: 0 (LE) + (byte)0x00, (byte)0x00, // generalCompressionLevel: 0 (LE) + (byte)0x00, // refreshRectSupport: FALSE (0) + (byte)0x00, // suppressOutputSupport: FALSE (0) + + // + // Bitmap capability set (28 bytes), see http://msdn.microsoft.com/en-us/library/cc240554.aspx + (byte)0x02, (byte)0x00, // capability set type: CAPSTYPE_BITMAP (2) (LE) + (byte)0x1c, (byte)0x00, // length of capability set: 28 bytes (LE) + (byte)0x10, (byte)0x00, // preferredBitsPerPixel: 16 bpp (LE) + (byte)0x01, (byte)0x00, // receive1BitPerPixel (ignored and SHOULD be set to TRUE (0x1)): TRUE (0x1) (LE) + (byte)0x01, (byte)0x00, // receive4BitsPerPixel (ignored and SHOULD be set to TRUE (0x1)): TRUE (0x1) (LE) + (byte)0x01, (byte)0x00, // receive8BitsPerPixel (ignored and SHOULD be set to TRUE (0x1)): TRUE (0x1) (LE) + (byte)0x00, (byte)0x04, // desktopWidth = 1024 pixels (LE) + (byte)0x00, (byte)0x03, // desktopHeight = 768 pixels (LE) + (byte)0x00, (byte)0x00, // Padding 2 bytes + (byte)0x00, (byte)0x00, // desktopResizeFlag: FALSE (0x0) (LE) + (byte)0x01, (byte)0x00, // bitmapCompressionFlag (must be set to TRUE (0x1)): TRUE (0x1) (LE) + (byte)0x00, // highColorFlags (field is ignored and SHOULD be set to zero): 0 + (byte)0x01, // drawingFlags: 0x1 TODO: padding, why 0x1 ??? + (byte)0x01, (byte)0x00, // multipleRectangleSupport: TRUE (LE) + (byte)0x00, (byte)0x00, // Padding 2 bytes + + // + // Order Capability Set (88 bytes), see http://msdn.microsoft.com/en-us/library/cc240556.aspx + (byte)0x03, (byte)0x00, // capability set type: CAPSTYPE_ORDER (3) (LE) + (byte)0x58, (byte)0x00, // length of capability set: 88 bytes (LE) + // terminalDescriptor = "" (16 bytes, UCS2) + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // pad4octetsA + (byte)0x01, (byte)0x00, // desktopSaveXGranularity (ignored): 1 (LE) + (byte)0x14, (byte)0x00, // desktopSaveYGranularity (ignored): 20 (LE) + (byte)0x00, (byte)0x00, // pad2octetsA (ignored) + (byte)0x01, (byte)0x00, // maximumOrderLevel: ORD_LEVEL_1_ORDERS (1) + (byte)0x00, (byte)0x00, // number of fonts (ignored): 0 + (byte)0x4a, (byte)0x00, // orderFlags = 0x004a (LE), SOLIDPATTERNBRUSHONLY (0x40), ZEROBOUNDSDELTASSUPPORT (0x8, MUST), NEGOTIATEORDERSUPPORT (0x2, MUST) + // Order support: 32 bytes (no primary drawing orders are supported, so this array MUST be initialized to all zeros, use 0x01 for TRUE). + (byte)0x00, // TS_NEG_DSTBLT_INDEX: FALSE + (byte)0x00, // TS_NEG_PATBLT_INDEX: FALSE + (byte)0x00, // TS_NEG_SCRBLT_INDEX: FALSE + (byte)0x00, // TS_NEG_MEMBLT_INDEX: FALSE + (byte)0x00, // TS_NEG_MEM3BLT_INDEX: FALSE + (byte)0x00, // TS_NEG_ATEXTOUT_INDEX: FALSE + (byte)0x00, // TS_NEG_AEXTTEXTOUT_INDEX: FALSE + (byte)0x00, // TS_NEG_DRAWNINEGRID_INDEX: FALSE + (byte)0x00, // TS_NEG_LINETO_INDEX: FALSE + (byte)0x00, // TS_NEG_MULTI_DRAWNINEGRID_INDEX: FALSE + (byte)0x00, // TS_NEG_OPAQUERECT_INDEX: FALSE + (byte)0x00, // TS_NEG_SAVEBITMAP_INDEX: FALSE + (byte)0x00, // TS_NEG_WTEXTOUT_INDEX: FALSE + (byte)0x00, // TS_NEG_MEMBLT_R2_INDEX: FALSE + (byte)0x00, // TS_NEG_MEM3BLT_R2_INDEX: FALSE + (byte)0x00, // TS_NEG_MULTIDSTBLT_INDEX: FALSE + (byte)0x00, // TS_NEG_MULTIPATBLT_INDEX: FALSE + (byte)0x00, // TS_NEG_MULTISCRBLT_INDEX: FALSE + (byte)0x00, // TS_NEG_MULTIOPAQUERECT_INDEX: FALSE + (byte)0x00, // TS_NEG_FAST_INDEX_INDEX: FALSE + (byte)0x00, // TS_NEG_POLYGON_SC_INDEX: FALSE + (byte)0x00, // TS_NEG_POLYGON_CB_INDEX: FALSE + (byte)0x00, // TS_NEG_POLYLINE_INDEX: TRUE + (byte)0x00, // Unused: 0 + (byte)0x00, // TS_NEG_FAST_GLYPH_INDEX: FALSE + (byte)0x00, // TS_NEG_ELLIPSE_SC_INDEX: FALSE + (byte)0x00, // TS_NEG_ELLIPSE_CB_INDEX: FALSE + (byte)0x00, // TS_NEG_INDEX_INDEX: FALSE + (byte)0x00, // TS_NEG_WEXTTEXTOUT_INDEX: FALSE + (byte)0x00, // TS_NEG_WLONGTEXTOUT_INDEX: FALSE + (byte)0x00, // TS_NEG_WLONGEXTTEXTOUT_INDEX: FALSE + (byte)0x00, // Unused: 0 + (byte)0x00, (byte)0x00, // Text flags (ignored): 0 (LE) + (byte)0x00, (byte)0x00, // Order support extra flags: 0 (LE) + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Padding 4 bytes + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Desktop save size (ignored): 0 (assumed to be 230400 bytes (480*480, 0x38400, LE)) + (byte)0x00, (byte)0x00, // Padding 2 bytes + (byte)0x00, (byte)0x00, // Padding 2 bytes + (byte)0xe4, (byte)0x04, // Text ANSI Code Page: 1252, ANSI - Latin I (0x04e4, LE) + (byte)0x00, (byte)0x00, // Padding 2 bytes + + // + // Bitmap Cache Rev. 2 Capability Set (40 bytes), see http://msdn.microsoft.com/en-us/library/cc240560.aspx + (byte)0x13, (byte)0x00, // capability set type: CAPSTYPE_BITMAPCACHE_REV2 (19) (LE) + (byte)0x28, (byte)0x00, // length of capability set: 40 bytes (LE) + (byte)0x00, (byte)0x00, // Cache flags: 0 (LE) + (byte)0x00, // Padding 1 byte + (byte)0x00, // Number of cell caches: 0 + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Bitmap cache0 cell info: 0 (LE) + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Bitmap cache1 cell info: 0 (LE) + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Bitmap cache2 cell info: 0 (LE) + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Bitmap cache3 cell info: 0 (LE) + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Bitmap cache4 cell info: 0 (LE) + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Padding 12 bytes + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Padding + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Padding + + // + // Color Table Cache Capability Set (8 bytes), see http://msdn.microsoft.com/en-us/library/cc241564.aspx + (byte)0x0a, (byte)0x00, // capability set type: CAPSTYPE_COLORCACHE (10) (LE) + (byte)0x08, (byte)0x00, // length of capability set: 8 bytes (LE) + (byte)0x06, (byte)0x00, // Color table cache size (must be ignored during capability exchange and is assumed to be 0x0006): 6 (LE) + (byte)0x00, (byte)0x00, // Padding 2 bytes + + // + // Window Activation Capability Set (12 bytes), see http://msdn.microsoft.com/en-us/library/cc240569.aspx + (byte)0x07, (byte)0x00, // capability set type: CAPSTYPE_ACTIVATION (7) (LE) + (byte)0x0c, (byte)0x00, // length of capability set: 12 bytes (LE) + (byte)0x00, (byte)0x00, // helpKeyFlag (should be set to FALSE (0)): FALSE (0, LE) + (byte)0x00, (byte)0x00, // helpKeyIndexFlag (should be set to FALSE (0)): FALSE (0, LE) + (byte)0x00, (byte)0x00, // helpExtendedKeyFlag (should be set to FALSE (0)): FALSE (0, LE) + (byte)0x00, (byte)0x00, // windowManagerKeyFlag (should be set to FALSE (0)): FALSE (0, LE) + + // + // Control Capability Set (12 bytes), see http://msdn.microsoft.com/en-us/library/cc240568.aspx + (byte)0x05, (byte)0x00, // capability set type: CAPSTYPE_ACTIVATION (7) + (byte)0x0c, (byte)0x00, // length of capability set: 12 bytes (LE) + (byte)0x00, (byte)0x00, // controlFlags (should be set to 0): 0 (LE) + (byte)0x00, (byte)0x00, // remoteDetachFlag (should be set to 0): 0 (LE) + (byte)0x02, (byte)0x00, // controlInterest (should be set to CONTROLPRIORITY_NEVER): CONTROLPRIORITY_NEVER (2) (LE) + (byte)0x02, (byte)0x00, // detachInterest (should be set to CONTROLPRIORITY_NEVER): CONTROLPRIORITY_NEVER (2) (LE) + + // + // Pointer Capability Set (10 bytes), see http://msdn.microsoft.com/en-us/library/cc240562.aspx + (byte)0x08, (byte)0x00, // capability set type: CAPSTYPE_POINTER (8, LE) + (byte)0x0a, (byte)0x00, // length of capability set: 10 bytes (LE) + (byte)0x00, (byte)0x00, // colorPointerFlag: FALSE (LE) + (byte)0x00, (byte)0x00, // colorPointerCacheSize: 0 (LE) + (byte)0x14, (byte)0x00, // pointerCacheSize: 20 (LE) + + // + // Share Capability Set (8 bytes), see http://msdn.microsoft.com/en-us/library/cc240570.aspx + (byte)0x09, (byte)0x00, // capability set type: CAPSTYPE_SHARE (9, LE) + (byte)0x08, (byte)0x00, // length of capability set: 8 bytes (LE) + (byte)0x00, (byte)0x00, // nodeID (must be set to 0 by client): 0 (LE) + (byte)0x00, (byte)0x00, // Padding 2 bytes (LE) + + // + // Input Capability Set (88 bytes), see http://msdn.microsoft.com/en-us/library/cc240563.aspx + (byte)0x0d, (byte)0x00, // capability set type: CAPSTYPE_INPUT (13, LE) + (byte)0x58, (byte)0x00, // length of capability set: 88 bytes (LE) + (byte)0x35, (byte)0x00, // inputFlags: 0x0035 (LE), INPUT_FLAG_FASTPATH_INPUT2 (0x20), INPUT_FLAG_VKPACKET (0x10), INPUT_FLAG_MOUSEX (0x4), INPUT_FLAG_SCANCODES (0x1) + (byte)0x00, (byte)0x00, // Padding 2 bytes + (byte)0x09, (byte)0x04, (byte)0x00, (byte)0x00, // keyboardLayout: "US" keyboard layout (0x000409, LE) + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // keyboardType: unknown (LE) + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // keyboardSubType: unknown (LE) + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // keyboardFunctionKey: unknown (LE) + // imeFileName: "", (64 bytes, including trailing NULL characters, UCS2) + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + + // + // Brush Capability Set (8 bytes), see http://msdn.microsoft.com/en-us/library/cc240564.aspx + (byte)0x0f, (byte)0x00, // capability set type: CAPSTYPE_BRUSH (15, LE) + (byte)0x08, (byte)0x00, // length of capability set: 8 bytes (LE) + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // brushSupportLevel: BRUSH_DEFAULT (0x0, LE) + + // + // Sound Capability Set (8 bytes), see http://msdn.microsoft.com/en-us/library/cc240552.aspx + (byte)0x0c, (byte)0x00, // capability set type: CAPSTYPE_SOUND (12, LE) + (byte)0x08, (byte)0x00, // length of capability set: 8 bytes (LE) + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // soundFlags: 0x0000 (LE) // SOUND_FLAG_BEEPS (0x1) + + // + // Font Capability Set (8 bytes), see http://msdn.microsoft.com/en-us/library/cc240571.aspx + (byte)0x0e, (byte)0x00, + (byte)0x08, (byte)0x00, + (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, + + // + // Offscreen Bitmap Cache Capability Set (12 bytes), see http://msdn.microsoft.com/en-us/library/cc240550.aspx + (byte)0x11, (byte)0x00, // capability set type: CAPSTYPE_OFFSCREENCACHE (17, LE) + (byte)0x0c, (byte)0x00, // length of capability set: 12 bytes (LE) + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // offscreenSupportLevel: FALSE (LE) + (byte)0x00, (byte)0x00, // offscreenCacheSize: 0 (LE) + (byte)0x00, (byte)0x00, // offscreenCacheEntries: 0 (LE) + + // + // Glyph Cache Capability Set (52 bytes), see http://msdn.microsoft.com/en-us/library/cc240565.aspx + (byte)0x10, (byte)0x00, // capability set type: CAPSTYPE_OFFSCREENCACHE (16, LE) + (byte)0x34, (byte)0x00, // length of capability set: 52 bytes (LE) + // Glyph Cache (40 bytes) + (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) + (byte)0x04, (byte)0x00, // CacheMaximumCellSize: 4 (LE) + (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) + (byte)0x04, (byte)0x00, // CacheMaximumCellSize: 4 (LE) + (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) + (byte)0x08, (byte)0x00, // CacheMaximumCellSize: 4 (LE) + (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) + (byte)0x08, (byte)0x00, // CacheMaximumCellSize: 4 (LE) + (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) + (byte)0x10, (byte)0x00, // CacheMaximumCellSize: 4 (LE) + (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) + (byte)0x20, (byte)0x00, // CacheMaximumCellSize: 4 (LE) + (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) + (byte)0x40, (byte)0x00, // CacheMaximumCellSize: 4 (LE) + (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) + (byte)0x80, (byte)0x00, // CacheMaximumCellSize: 4 (LE) + (byte)0xfe, (byte)0x00, // CacheEntries: 254 (LE) + (byte)0x00, (byte)0x01, // CacheMaximumCellSize: 4 (LE) + (byte)0x40, (byte)0x00, // CacheEntries: 64 (LE) + (byte)0x00, (byte)0x08, // CacheMaximumCellSize: 2048 (LE) + // FragCache + (byte)0x00, (byte)0x01, // CacheEntries: 256 (LE) + (byte)0x00, (byte)0x01, // CacheMaximumCellSize: 256 (LE) + // + (byte)0x00, (byte)0x00, // GlyphSupportLevel: GLYPH_SUPPORT_NONE (0x0, LE) + (byte)0x00, (byte)0x00, // Padding 2 bytes + }; + /* @formatter:on */ + + RdpState rdpState = new RdpState(); + ScreenDescription screenDescription = new ScreenDescription(); + screenDescription.setFramebufferSize(1024, 768); + + rdpState.serverShareId = 0x000103ea; + + MockSource source = new MockSource("source", ByteBuffer.convertByteArraysToByteBuffers(new byte[] {})); + Element confirm_active = new ClientConfirmActivePDU("confirm_active", screenDescription, rdpState); + Element sink = new MockSink("sink", ByteBuffer.convertByteArraysToByteBuffers(packet)); + + Pipeline pipeline = new PipelineImpl("test"); + pipeline.add(source, confirm_active, sink); + pipeline.link("source", "confirm_active", "sink"); + pipeline.runMainLoop("source", STDOUT, false, false); + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientFastPathPDU.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientFastPathPDU.java old mode 100644 new mode 100755 similarity index 98% rename from services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientFastPathPDU.java rename to services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientFastPathPDU.java index 39dc81a2f9c..108429c82bd --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientFastPathPDU.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientFastPathPDU.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package rdpclient; +package rdpclient.rdp; import streamer.BaseElement; import streamer.ByteBuffer; diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientInfoPDU.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientInfoPDU.java new file mode 100755 index 00000000000..61960049dfd --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientInfoPDU.java @@ -0,0 +1,456 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.rdp; + +import streamer.ByteBuffer; +import streamer.Element; +import streamer.Link; +import streamer.OneTimeSwitch; +import streamer.Pipeline; +import streamer.PipelineImpl; +import streamer.debug.MockSink; +import streamer.debug.MockSource; + +/** + * @see http://msdn.microsoft.com/en-us/library/cc240475.aspx + */ +public class ClientInfoPDU extends OneTimeSwitch { + + public static final int INFO_MOUSE = 0x1; + public static final int INFO_DISABLECTRLALTDEL = 0x2; + public static final int INFO_UNICODE = 0x10; + + public static final int INFO_MAXIMIZESHELL = 0x20; + public static final int INFO_LOGONNOTIFY = 0x40; + public static final int INFO_ENABLEWINDOWSKEY = 0x100; + public static final int INFO_MOUSE_HAS_WHEEL = 0x00020000; + public static final int INFO_NOAUDIOPLAYBACK = 0x00080000; + + public static final int PERF_DISABLE_WALLPAPER = 0x1; + public static final int PERF_DISABLE_FULLWINDOWDRAG = 0x2; + public static final int PERF_DISABLE_MENUANIMATIONS = 0x4; + + protected byte[] userName = "".getBytes(RdpConstants.CHARSET_16); + protected byte[] password = "".getBytes(RdpConstants.CHARSET_16); // No effect + protected byte[] alternateShell = "".getBytes(RdpConstants.CHARSET_16); + protected byte[] domain = "".getBytes(RdpConstants.CHARSET_16); + protected byte[] workingDir = "".getBytes(RdpConstants.CHARSET_16); + protected byte[] clientAddress = "192.168.0.100".getBytes(RdpConstants.CHARSET_16); + protected byte[] clientDir = "C:\\Windows\\System32\\mstscax.dll".getBytes(RdpConstants.CHARSET_16); + + protected String standardTimeZoneName = "EET, Standard Time"; + protected String daylightTimeZoneName = "EET, Summer Time"; + protected int standardTimeZoneBias = 0; /* in minutes */ + protected int daylightTimeZoneBias = 60; /* in minutes */ + + public ClientInfoPDU(String id, String userName) { + super(id); + this.userName = userName.getBytes(RdpConstants.CHARSET_16); + } + + @Override + protected void handleOneTimeData(ByteBuffer buf, Link link) { + if (buf == null) + return; + + throw new RuntimeException("Unexpected packet: " + buf + "."); + } + + @Override + protected void onStart() { + super.onStart(); + + // Length of packet + ByteBuffer buf = new ByteBuffer(1024, true); + + // MCS Send Data Request PDU + buf.writeByte(0x64); + + // Initiator: 0x03 + 1001 = 1004 + buf.writeShort(3); + + // Channel ID: 1003 + buf.writeShort(1003); + + // Data priority: high, segmentation: begin | end (0x40 | 0x20 | 0x10 = 0x70) + buf.writeByte(0x70); + + // User data length: (variable length field) + int length = 224 + userName.length + password.length + alternateShell.length + domain.length + workingDir.length + clientAddress.length + clientDir.length; + buf.writeShort(length | 0x8000); + + // Flags: SEC_INFO_PKT (0x4000) + buf.writeShort(0x4000); + + // TS_SECURITY_HEADER::flagsHi - ignored + buf.writeShort(0x0000); + + // Codepage: 0 (UNKNOWN, LE) (use 0x04090409 (1033,1033) for EN_US) + buf.writeIntLE(0x0000); + + // Flags + buf.writeIntLE(INFO_MOUSE | INFO_DISABLECTRLALTDEL | INFO_UNICODE | + INFO_MAXIMIZESHELL | INFO_LOGONNOTIFY | INFO_ENABLEWINDOWSKEY | + INFO_MOUSE_HAS_WHEEL | INFO_NOAUDIOPLAYBACK); + + // + // Lengths + // + + // cbDomain length: 0 bytes (LE) (NOT including size of mandatory NULL terminator) + buf.writeShortLE(domain.length); + + // cbUserName length: 16 bytes (0x10, LE) (NOT including size of mandatory NULL terminator) + buf.writeShortLE(userName.length); + + // cbPassword length: (LE) (NOT including size of mandatory NULL terminator) + buf.writeShortLE(password.length); + + // cbAlternateShell: (LE) (NOT including size of mandatory NULL terminator) + buf.writeShortLE(alternateShell.length); + + // cbWorkingDir: (LE) (NOT including size of mandatory NULL terminator) + buf.writeShortLE(workingDir.length); + + // + // Values + // + + // Domain: (UCS2), see cbDomain + buf.writeBytes(domain); + buf.writeShort(0); + + // User name: (UCS2), see cbUserName + buf.writeBytes(userName); + buf.writeShort(0); + + // Password: (UCS2), see cbPassword + buf.writeBytes(password); + buf.writeShort(0); + + // Alternate shell: (UCS2), see cbAlternateShell + buf.writeBytes(alternateShell); + buf.writeShort(0); + + // Working directory: (UCS2), see cbWorkingDir + buf.writeBytes(workingDir); + buf.writeShort(0); + + // Client address family: 2 (AF_INET, LE) + buf.writeShortLE(2); + + // cbClientAddress: ( LE) (including the size of the mandatory NULL terminator) + buf.writeShortLE(clientAddress.length + 2); + + // Client address: (UCS2) + buf.writeBytes(clientAddress); + buf.writeShort(0); + + // cbClientDir: 64 bytes (0x40, LE) (including the size of the mandatory NULL terminator) + buf.writeShortLE(clientDir.length + 2); + + // Client directory: (UCS2) + buf.writeBytes(clientDir); + buf.writeShort(0); + + // + // Client time zone: + // + + // Bias: 0 minutes (LE) + buf.writeIntLE(0); + + // Standard name: "EET, Standard Time" (fixed string: 64 bytes, UCS2) + buf.writeFixedString(62, standardTimeZoneName, RdpConstants.CHARSET_16); + buf.writeShort(0); + + // Standard date + buf.writeBytes(new byte[] { + // wYear: 0 (LE) + (byte)0x00, (byte)0x00, + // wMonth: unknown (LE) + (byte)0x00, (byte)0x00, + // wDayOfWeek: Sunday (LE) + (byte)0x00, (byte)0x00, + // wDay: unknown (LE) + (byte)0x00, (byte)0x00, + // wHour: 0 (LE) + (byte)0x00, (byte)0x00, + // wMinute: 0 (LE) + (byte)0x00, (byte)0x00, + // wSecond: 0 (LE) + (byte)0x00, (byte)0x00, + // wMilliseconds: 0 + (byte)0x00, (byte)0x00, + + }); + + // StandardBias: 0 minutes (LE) + buf.writeIntLE(standardTimeZoneBias); + + // Daylight name: "EET, Summer Time" (fixed string: 64 bytes, UCS2) + buf.writeFixedString(62, daylightTimeZoneName, RdpConstants.CHARSET_16); + buf.writeShort(0); + + // Daylight date + buf.writeBytes(new byte[] { + // wYear: 0 (LE) + (byte)0x00, (byte)0x00, + // wMonth: unknown (LE) + (byte)0x00, (byte)0x00, + // wDayOfWeek: Sunday (LE) + (byte)0x00, (byte)0x00, + // wDay: unknown (LE) + (byte)0x00, (byte)0x00, + // wHour: 0 (LE) + (byte)0x00, (byte)0x00, + // wMinute: 0 (LE) + (byte)0x00, (byte)0x00, + // wSecond: 0 (LE) + (byte)0x00, (byte)0x00, + // wMilliseconds: 0 + (byte)0x00, (byte)0x00, + + }); + + // Daylight bias: 60 minutes (LE) + buf.writeIntLE(daylightTimeZoneBias); + + // Client session ID: 0x00000000 (LE) + buf.writeIntLE(0); + + // Performance flags: 0x7 (LE) = PERF_DISABLE_WALLPAPER (0x1), PERF_DISABLE_FULLWINDOWDRAG (0x2), PERF_DISABLE_MENUANIMATIONS (0x4) + buf.writeIntLE(PERF_DISABLE_WALLPAPER | PERF_DISABLE_FULLWINDOWDRAG | PERF_DISABLE_MENUANIMATIONS); + + // cbAutoReconnectCookie: 0 bytes (LE) + buf.writeShortLE(0); + + // Trim buffer to actual length of data written + buf.trimAtCursor(); + + pushDataToOTOut(buf); + + switchOff(); + } + + /** + * Example. + */ + public static void main(String args[]) { + // System.setProperty("streamer.Link.debug", "true"); + System.setProperty("streamer.Element.debug", "true"); + // System.setProperty("streamer.Pipeline.debug", "true"); + + /* @formatter:off */ + byte[] packet = new byte[] { + + // TPKT + (byte) 0x03, (byte) 0x00, + + // TPKT length: 343 bytes + (byte) 0x01, (byte) 0x57, + + // X224 Data PDU + (byte) 0x02, (byte) 0xf0, (byte) 0x80, + + + // MCS Send Data Request PDU + (byte) 0x64, + + // Initiator: 0x03 + 1001 = 1004 + (byte) 0x00, (byte) 0x03, + + // Channel ID: 1003 (IO Channel) + (byte) 0x03, (byte) 0xeb, + + // Data priority: high, segmentation: begin | end (0x40 | 0x20 | 0x10 = 0x70) + (byte) 0x70, + + // User data length: 328 (0x148) bytes, variable length field + (byte) 0x81, (byte) 0x48, + + // Flags: SEC_INFO_PKT (0x4000) + (byte) 0x40, (byte) 0x00, + + // TS_SECURITY_HEADER::flagsHi - ignored + (byte) 0x00, (byte) 0x00, + + // Codepage: 0 (UNKNOWN, LE) (use 0x04090409 (1033,1033) for EN_US) + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + + // Flags: 0xa0173 (LE), INFO_MOUSE (0x1), INFO_DISABLECTRLALTDEL (0x2), INFO_UNICODE (0x10), + // INFO_MAXIMIZESHELL (0x20), INFO_LOGONNOTIFY (0x40), INFO_ENABLEWINDOWSKEY (0x100), + // INFO_MOUSE_HAS_WHEEL (0x00020000), INFO_NOAUDIOPLAYBACK (0x00080000), + (byte) 0x73, (byte) 0x01, (byte) 0x0a, (byte) 0x00, + + // Lengths + + // cbDomain length: 0 bytes (LE) (NOT including size of mandatory NULL terminator) + (byte) 0x00, (byte) 0x00, + + // cbUserName length: 16 bytes (0x10, LE) (NOT including size of mandatory NULL terminator) + (byte) 0x10, (byte) 0x00, + + // cbPassword length: 0 bytes (LE) (NOT including size of mandatory NULL terminator) + (byte) 0x00, (byte) 0x00, + + // cbAlternateShell: 0 bytes (LE) (NOT including size of mandatory NULL terminator) + (byte) 0x00, (byte) 0x00, + + // cbWorkingDir: 0 bytes (LE) (NOT including size of mandatory NULL terminator) + (byte) 0x00, (byte) 0x00, + + // Values + + // Domain: "" (UCS2), see cbDomain + (byte) 0x00, (byte) 0x00, + + // User name: "vlisivka" (UCS2), see cbUserName + (byte) 0x76, (byte) 0x00, (byte) 0x6c, (byte) 0x00, (byte) 0x69, (byte) 0x00, (byte) 0x73, (byte) 0x00, + (byte) 0x69, (byte) 0x00, (byte) 0x76, (byte) 0x00, (byte) 0x6b, (byte) 0x00, (byte) 0x61, (byte) 0x00, + (byte) 0x00, (byte) 0x00, + + // Password: "" (UCS2), see cbPassword + (byte) 0x00, (byte) 0x00, + + // Alternate shell: "" (UCS2), see cbAlternateShell + (byte) 0x00, (byte) 0x00, + + // Working directory: "" (UCS2), see cbWorkingDir + (byte) 0x00, (byte) 0x00, + + // Client address family: 2 (AF_INET, LE) + (byte) 0x02, (byte) 0x00, + + // cbClientAddress = 28 bytes (0x1c, LE) (including the size of the mandatory NULL terminator) + (byte) 0x1c, (byte) 0x00, + + // Client address: "192.168.0.100" (UCS2) + (byte) 0x31, (byte) 0x00, (byte) 0x39, (byte) 0x00, (byte) 0x32, (byte) 0x00, (byte) 0x2e, (byte) 0x00, + (byte) 0x31, (byte) 0x00, (byte) 0x36, (byte) 0x00, (byte) 0x38, (byte) 0x00, (byte) 0x2e, (byte) 0x00, + (byte) 0x30, (byte) 0x00, (byte) 0x2e, (byte) 0x00, (byte) 0x31, (byte) 0x00, (byte) 0x30, (byte) 0x00, + (byte) 0x30, (byte) 0x00, (byte) 0x00, (byte) 0x00, + + // cbClientDir: 64 bytes (0x40, LE) (including the size of the mandatory NULL terminator) + (byte) 0x40, (byte) 0x00, + + // Client directory: "C:\Windows\System32\mstscax.dll" (UCS2) + (byte) 0x43, (byte) 0x00, (byte) 0x3a, (byte) 0x00, (byte) 0x5c, (byte) 0x00, (byte) 0x57, (byte) 0x00, + (byte) 0x69, (byte) 0x00, (byte) 0x6e, (byte) 0x00, (byte) 0x64, (byte) 0x00, (byte) 0x6f, (byte) 0x00, + (byte) 0x77, (byte) 0x00, (byte) 0x73, (byte) 0x00, (byte) 0x5c, (byte) 0x00, (byte) 0x53, (byte) 0x00, + (byte) 0x79, (byte) 0x00, (byte) 0x73, (byte) 0x00, (byte) 0x74, (byte) 0x00, (byte) 0x65, (byte) 0x00, + (byte) 0x6d, (byte) 0x00, (byte) 0x33, (byte) 0x00, (byte) 0x32, (byte) 0x00, (byte) 0x5c, (byte) 0x00, + (byte) 0x6d, (byte) 0x00, (byte) 0x73, (byte) 0x00, (byte) 0x74, (byte) 0x00, (byte) 0x73, (byte) 0x00, + (byte) 0x63, (byte) 0x00, (byte) 0x61, (byte) 0x00, (byte) 0x78, (byte) 0x00, (byte) 0x2e, (byte) 0x00, + (byte) 0x64, (byte) 0x00, (byte) 0x6c, (byte) 0x00, (byte) 0x6c, (byte) 0x00, (byte) 0x00, (byte) 0x00, + + // + // Client time zone: + + // Bias: 0 minutes (LE) + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + + // Standard name: "EET, Standard Time" (fixed string: 64 bytes, UCS2) + (byte) 0x45, (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x54, (byte) 0x00, (byte) 0x2c, (byte) 0x00, + (byte) 0x20, (byte) 0x00, (byte) 0x53, (byte) 0x00, (byte) 0x74, (byte) 0x00, (byte) 0x61, (byte) 0x00, + (byte) 0x6e, (byte) 0x00, (byte) 0x64, (byte) 0x00, (byte) 0x61, (byte) 0x00, (byte) 0x72, (byte) 0x00, + (byte) 0x64, (byte) 0x00, (byte) 0x20, (byte) 0x00, (byte) 0x54, (byte) 0x00, (byte) 0x69, (byte) 0x00, + (byte) 0x6d, (byte) 0x00, (byte) 0x65, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + + // + // Standard date + // wYear: 0 (LE) + (byte) 0x00, (byte) 0x00, + // wMonth: unknown (LE) + (byte) 0x00, (byte) 0x00, + // wDayOfWeek: Sunday (LE) + (byte) 0x00, (byte) 0x00, + // wDay: unknown (LE) + (byte) 0x00, (byte) 0x00, + // wHour: 0 (LE) + (byte) 0x00, (byte) 0x00, + // wMinute: 0 (LE) + (byte) 0x00, (byte) 0x00, + // wSecond: 0 (LE) + (byte) 0x00, (byte) 0x00, + // wMilliseconds: 0 + (byte) 0x00, (byte) 0x00, + + // StandardBias: 0 minutes (LE) + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + + // Daylight name: "EET, Summer Time" (fixed string: 64 bytes, UCS2) + (byte) 0x45, (byte) 0x00, (byte) 0x45, (byte) 0x00, (byte) 0x54, (byte) 0x00, (byte) 0x2c, (byte) 0x00, + (byte) 0x20, (byte) 0x00, (byte) 0x53, (byte) 0x00, (byte) 0x75, (byte) 0x00, (byte) 0x6d, (byte) 0x00, + (byte) 0x6d, (byte) 0x00, (byte) 0x65, (byte) 0x00, (byte) 0x72, (byte) 0x00, (byte) 0x20, (byte) 0x00, + (byte) 0x54, (byte) 0x00, (byte) 0x69, (byte) 0x00, (byte) 0x6d, (byte) 0x00, (byte) 0x65, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + + // Daylight date + // wYear: 0 (LE) + (byte) 0x00, (byte) 0x00, + // wMonth: unknown (LE) + (byte) 0x00, (byte) 0x00, + // wDayOfWeek: Sunday (LE) + (byte) 0x00, (byte) 0x00, + // wDay: unknown (LE) + (byte) 0x00, (byte) 0x00, + // wHour: 0 (LE) + (byte) 0x00, (byte) 0x00, + // wMinute: 0 (LE) + (byte) 0x00, (byte) 0x00, + // wSecond: 0 (LE) + (byte) 0x00, (byte) 0x00, + // wMilliseconds: 0 + (byte) 0x00, (byte) 0x00, + + // Daylight bias: 60 minutes (LE) + (byte) 0x3c, (byte) 0x00, (byte) 0x00, (byte) 0x00, + + + // Client session ID: 0x00000000 (LE) + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + + // Performance flags: 0x7 (LE) = PERF_DISABLE_WALLPAPER (0x1), PERF_DISABLE_FULLWINDOWDRAG (0x2), PERF_DISABLE_MENUANIMATIONS (0x4) + (byte) 0x07, (byte) 0x00, (byte) 0x00, (byte) 0x00, + + // cbAutoReconnectCookie: 0 bytes (LE) + (byte) 0x00, (byte) 0x00, + }; + /* @formatter:on */ + + MockSource source = new MockSource("source", ByteBuffer.convertByteArraysToByteBuffers(new byte[] {1, 2, 3})); + Element client_info = new ClientInfoPDU("client_info", "vlisivka"); + Element x224 = new ClientX224DataPDU("x224"); + Element tpkt = new ClientTpkt("tpkt"); + Element sink = new MockSink("sink", ByteBuffer.convertByteArraysToByteBuffers(packet)); + Element mainSink = new MockSink("mainSink", ByteBuffer.convertByteArraysToByteBuffers(new byte[] {1, 2, 3})); + + Pipeline pipeline = new PipelineImpl("test"); + pipeline.add(source, client_info, x224, tpkt, sink, mainSink); + pipeline.link("source", "client_info", "mainSink"); + pipeline.link("client_info >" + OTOUT, "x224", "tpkt", "sink"); + pipeline.runMainLoop("source", STDOUT, false, false); + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientMCSAttachUserRequest.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientMCSAttachUserRequest.java old mode 100644 new mode 100755 similarity index 77% rename from services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientMCSAttachUserRequest.java rename to services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientMCSAttachUserRequest.java index 55ca08acb53..47a07da73e0 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientMCSAttachUserRequest.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientMCSAttachUserRequest.java @@ -14,16 +14,16 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package rdpclient; +package rdpclient.rdp; import streamer.ByteBuffer; import streamer.Element; import streamer.Link; -import streamer.MockSink; -import streamer.MockSource; import streamer.OneTimeSwitch; import streamer.Pipeline; import streamer.PipelineImpl; +import streamer.debug.MockSink; +import streamer.debug.MockSource; /** * @see http://msdn.microsoft.com/en-us/library/cc240684.aspx @@ -65,30 +65,30 @@ public class ClientMCSAttachUserRequest extends OneTimeSwitch { // System.setProperty("streamer.Pipeline.debug", "true"); /* @formatter:off */ - byte[] packet = new byte[] { + byte[] packet = new byte[] { - 0x03, 0x00, 0x00, 0x08, // TPKT Header (length = 8 bytes) - 0x02, (byte) 0xf0, (byte) 0x80, // X.224 Data TPDU + 0x03, 0x00, 0x00, 0x08, // TPKT Header (length = 8 bytes) + 0x02, (byte) 0xf0, (byte) 0x80, // X.224 Data TPDU - // PER encoded (ALIGNED variant of BASIC-PER) PDU contents: - 0x28, + // PER encoded (ALIGNED variant of BASIC-PER) PDU contents: + 0x28, - // 0x28: - // 0 - --\ - // 0 - | - // 1 - | CHOICE: From DomainMCSPDU select attachUserRequest (10) - // 0 - | of type AttachUserRequest - // 1 - | - // 0 - --/ - // 0 - padding - // 0 - padding + // 0x28: + // 0 - --\ + // 0 - | + // 1 - | CHOICE: From DomainMCSPDU select attachUserRequest (10) + // 0 - | of type AttachUserRequest + // 1 - | + // 0 - --/ + // 0 - padding + // 0 - padding - }; - /* @formatter:on */ + }; + /* @formatter:on */ MockSource source = new MockSource("source", ByteBuffer.convertByteArraysToByteBuffers(new byte[] {1, 2, 3})); Element todo = new ClientMCSAttachUserRequest("TODO"); - Element x224 = new ClientX224DataPdu("x224"); + Element x224 = new ClientX224DataPDU("x224"); Element tpkt = new ClientTpkt("tpkt"); Element sink = new MockSink("sink", ByteBuffer.convertByteArraysToByteBuffers(packet)); Element mainSink = new MockSink("mainSink", ByteBuffer.convertByteArraysToByteBuffers(new byte[] {1, 2, 3})); diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientMCSChannelJoinRequest_ServerMCSChannelConfirmPDUs.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientMCSChannelJoinRequestServerMCSChannelConfirmPDUs.java old mode 100644 new mode 100755 similarity index 61% rename from services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientMCSChannelJoinRequest_ServerMCSChannelConfirmPDUs.java rename to services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientMCSChannelJoinRequestServerMCSChannelConfirmPDUs.java index 0b902a32326..12d94381310 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientMCSChannelJoinRequest_ServerMCSChannelConfirmPDUs.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientMCSChannelJoinRequestServerMCSChannelConfirmPDUs.java @@ -14,16 +14,16 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package rdpclient; +package rdpclient.rdp; import streamer.ByteBuffer; import streamer.Element; import streamer.Link; -import streamer.MockSink; -import streamer.MockSource; import streamer.OneTimeSwitch; import streamer.Pipeline; import streamer.PipelineImpl; +import streamer.debug.MockSink; +import streamer.debug.MockSource; /** * The MCS Channel Join Request PDUs are sent sequentially. The first PDU is @@ -34,7 +34,7 @@ import streamer.PipelineImpl; * * @see http://msdn.microsoft.com/en-us/library/cc240686.aspx */ -public class ClientMCSChannelJoinRequest_ServerMCSChannelConfirmPDUs extends OneTimeSwitch { +public class ClientMCSChannelJoinRequestServerMCSChannelConfirmPDUs extends OneTimeSwitch { private static final int MCS_CHANNEL_CONFIRM_PDU = 15; @@ -43,7 +43,7 @@ public class ClientMCSChannelJoinRequest_ServerMCSChannelConfirmPDUs extends One protected RdpState state; - public ClientMCSChannelJoinRequest_ServerMCSChannelConfirmPDUs(String id, int[] channels, RdpState state) { + public ClientMCSChannelJoinRequestServerMCSChannelConfirmPDUs(String id, int[] channels, RdpState state) { super(id); this.channels = channels; this.state = state; @@ -60,13 +60,13 @@ public class ClientMCSChannelJoinRequest_ServerMCSChannelConfirmPDUs extends One // int flags = typeAndFlags & 0x3; if (type != MCS_CHANNEL_CONFIRM_PDU) - throw new RuntimeException("[" + this + "] ERROR: Incorrect type of MCS AttachUserConfirm PDU. Expected value: 15, actual value: " + type + ", data: " + buf + - "."); + throw new RuntimeException("[" + this + "] ERROR: Incorrect type of MCS AttachUserConfirm PDU. Expected value: 15, actual value: " + type + ", data: " + buf + "."); int rtSuccess = buf.readUnsignedByte() >> 4; if (rtSuccess != 0) - throw new RuntimeException("[" + this + "] ERROR: Cannot connect to channel: request failed. Error code: " + rtSuccess + ", channel ID: " + - channels[channelRequestsSent - 1] + ", data: " + buf + "."); + throw new RuntimeException("[" + this + "] ERROR: Cannot connect to channel: request failed. Error code: " + rtSuccess + ", channel ID: " + + channels[channelRequestsSent - 1] + + ", data: " + buf + "."); // Initiator and requested fields MAY be ignored, however, the channelId // field MUST be examined. If the value of the channelId field does not @@ -84,8 +84,8 @@ public class ClientMCSChannelJoinRequest_ServerMCSChannelConfirmPDUs extends One // Actual channel int actualChannel = buf.readUnsignedShort(); if (actualChannel != channels[channelRequestsSent - 1]) - throw new RuntimeException("Unexpeceted channeld ID returned. Expected channeld ID: " + channels[channelRequestsSent - 1] + ", actual channel ID: " + - actualChannel + ", data: " + buf + "."); + throw new RuntimeException("Unexpeceted channeld ID returned. Expected channeld ID: " + channels[channelRequestsSent - 1] + ", actual channel ID: " + + actualChannel + ", data: " + buf + "."); state.channelJoined(actualChannel); @@ -111,7 +111,7 @@ public class ClientMCSChannelJoinRequest_ServerMCSChannelConfirmPDUs extends One buf.writeByte(0x38); // Channel Join request - buf.writeShort(0x03); // ChannelJoinRequest::initiator: 1004 + buf.writeShort(state.serverUserChannelId - 1001); // ChannelJoinRequest::initiator: 1004 buf.writeShort(channel); pushDataToOTOut(buf); @@ -128,86 +128,87 @@ public class ClientMCSChannelJoinRequest_ServerMCSChannelConfirmPDUs extends One // System.setProperty("streamer.Pipeline.debug", "true"); /* @formatter:off */ - byte[] clientRequestPacket = new byte[] { - 0x03, 0x00, 0x00, 0x0c, // TPKT Header (length = 12 bytes) - 0x02, (byte) 0xf0, (byte) 0x80, // X.224 Data TPDU + byte[] clientRequestPacket = new byte[] { + 0x03, 0x00, 0x00, 0x0c, // TPKT Header (length = 12 bytes) + 0x02, (byte) 0xf0, (byte) 0x80, // X.224 Data TPDU - // PER encoded (ALIGNED variant of BASIC-PER) PDU contents: - 0x38, 0x00, 0x03, 0x03, (byte) 0xef, + // PER encoded (ALIGNED variant of BASIC-PER) PDU contents: + 0x38, 0x00, 0x03, 0x03, (byte) 0xef, - // 0x38: - // 0 - --\ - // 0 - | - // 1 - | CHOICE: From DomainMCSPDU select channelJoinRequest (14) - // 1 - | of type ChannelJoinRequest - // 1 - | - // 0 - --/ - // 0 - padding - // 0 - padding + // 0x38: + // 0 - --\ + // 0 - | + // 1 - | CHOICE: From DomainMCSPDU select channelJoinRequest (14) + // 1 - | of type ChannelJoinRequest + // 1 - | + // 0 - --/ + // 0 - padding + // 0 - padding - // 0x00: - // 0 - --\ - // 0 - | - // 0 - | - // 0 - | - // 0 - | - // 0 - | - // 0 - | - // 0 - | - // | ChannelJoinRequest::initiator = 0x03 + 1001 = 1004 - // 0x03: | - // 0 - | - // 0 - | - // 0 - | - // 0 - | - // 0 - | - // 1 - | - // 1 - | - // 0 - --/ + // 0x00: + // 0 - --\ + // 0 - | + // 0 - | + // 0 - | + // 0 - | + // 0 - | + // 0 - | + // 0 - | + // | ChannelJoinRequest::initiator = 0x03 + 1001 = 1004 + // 0x03: | + // 0 - | + // 0 - | + // 0 - | + // 0 - | + // 0 - | + // 1 - | + // 1 - | + // 0 - --/ - // 0x03: - // 0 - --\ - // 0 - | - // 0 - | - // 0 - | - // 0 - | - // 0 - | - // 1 - | - // 1 - | - // | ChannelJoinRequest::channelId = 0x03ef = 1007 - // 0xef: | - // 1 - | - // 1 - | - // 1 - | - // 0 - | - // 1 - | - // 1 - | - // 1 - | - // 1 - --/ - }; + // 0x03: + // 0 - --\ + // 0 - | + // 0 - | + // 0 - | + // 0 - | + // 0 - | + // 1 - | + // 1 - | + // | ChannelJoinRequest::channelId = 0x03ef = 1007 + // 0xef: | + // 1 - | + // 1 - | + // 1 - | + // 0 - | + // 1 - | + // 1 - | + // 1 - | + // 1 - --/ + }; - byte[] serverResponsePacket = new byte[] { - // MCS Channel Confirm - (byte)0x3e, + byte[] serverResponsePacket = new byte[] { + // MCS Channel Confirm + (byte)0x3e, - // result: rt-successful (0) - (byte)0x00, + // result: rt-successful (0) + (byte)0x00, - // Initiator: 1007 (6+1001) - (byte)0x00, (byte)0x06, + // Initiator: 1007 (6+1001) + (byte)0x00, (byte)0x06, - // Requested channel - (byte)0x03, (byte)0xef, + // Requested channel + (byte)0x03, (byte)0xef, - // Actual channel - (byte)0x03, (byte)0xef, - }; - /* @formatter:on */ + // Actual channel + (byte)0x03, (byte)0xef, + }; + /* @formatter:on */ RdpState rdpState = new RdpState(); + rdpState.serverUserChannelId = 1004; MockSource source = new MockSource("source", ByteBuffer.convertByteArraysToByteBuffers(serverResponsePacket, new byte[] {1, 2, 3})); - Element todo = new ClientMCSChannelJoinRequest_ServerMCSChannelConfirmPDUs("channels", new int[] {1007}, rdpState); - Element x224 = new ClientX224DataPdu("x224"); + Element todo = new ClientMCSChannelJoinRequestServerMCSChannelConfirmPDUs("channels", new int[] {1007}, rdpState); + Element x224 = new ClientX224DataPDU("x224"); Element tpkt = new ClientTpkt("tpkt"); Element sink = new MockSink("sink", ByteBuffer.convertByteArraysToByteBuffers(clientRequestPacket)); Element mainSink = new MockSink("mainSink", ByteBuffer.convertByteArraysToByteBuffers(new byte[] {1, 2, 3})); diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientMCSConnectInitial.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientMCSConnectInitial.java new file mode 100755 index 00000000000..37730aa403a --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientMCSConnectInitial.java @@ -0,0 +1,696 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.rdp; + +import streamer.ByteBuffer; +import streamer.Element; +import streamer.Link; +import streamer.OneTimeSwitch; +import streamer.Pipeline; +import streamer.PipelineImpl; +import streamer.debug.MockSink; +import streamer.debug.MockSource; + +public class ClientMCSConnectInitial extends OneTimeSwitch { + + public ClientMCSConnectInitial(String id) { + super(id); + } + + @Override + protected void handleOneTimeData(ByteBuffer buf, Link link) { + if (buf == null) + return; + + throw new RuntimeException("Unexpected packet: " + buf + "."); + } + + @Override + protected void onStart() { + super.onStart(); + + int length = 1024; // Large enough + ByteBuffer buf = new ByteBuffer(length, true); + + /* @formatter:off */ + buf.writeBytes(new byte[] { + (byte)0x7f, (byte)0x65, (byte)0x82, (byte)0x01, (byte)0x6d, (byte)0x04, (byte)0x01, (byte)0x01, (byte)0x04, (byte)0x01, (byte)0x01, (byte)0x01, (byte)0x01, (byte)0xff, (byte)0x30, (byte)0x1a, + (byte)0x02, (byte)0x01, (byte)0x22, (byte)0x02, (byte)0x01, (byte)0x02, (byte)0x02, (byte)0x01, (byte)0x00, (byte)0x02, (byte)0x01, (byte)0x01, (byte)0x02, (byte)0x01, (byte)0x00, (byte)0x02, + (byte)0x01, (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x00, (byte)0xff, (byte)0xff, (byte)0x02, (byte)0x01, (byte)0x02, (byte)0x30, (byte)0x19, (byte)0x02, (byte)0x01, (byte)0x01, (byte)0x02, + (byte)0x01, (byte)0x01, (byte)0x02, (byte)0x01, (byte)0x01, (byte)0x02, (byte)0x01, (byte)0x01, (byte)0x02, (byte)0x01, (byte)0x00, (byte)0x02, (byte)0x01, (byte)0x01, (byte)0x02, (byte)0x02, + (byte)0x04, (byte)0x20, (byte)0x02, (byte)0x01, (byte)0x02, (byte)0x30, (byte)0x20, (byte)0x02, (byte)0x03, (byte)0x00, (byte)0xff, (byte)0xff, (byte)0x02, (byte)0x03, (byte)0x00, (byte)0xfc, + (byte)0x17, (byte)0x02, (byte)0x03, (byte)0x00, (byte)0xff, (byte)0xff, (byte)0x02, (byte)0x01, (byte)0x01, (byte)0x02, (byte)0x01, (byte)0x00, (byte)0x02, (byte)0x01, (byte)0x01, (byte)0x02, + (byte)0x03, (byte)0x00, (byte)0xff, (byte)0xff, (byte)0x02, (byte)0x01, (byte)0x02, (byte)0x04, (byte)0x82, (byte)0x01, (byte)0x07, (byte)0x00, (byte)0x05, (byte)0x00, (byte)0x14, (byte)0x7c, + (byte)0x00, (byte)0x01, (byte)0x80, (byte)0xfe, (byte)0x00, (byte)0x08, (byte)0x00, (byte)0x10, (byte)0x00, (byte)0x01, (byte)0xc0, (byte)0x00, (byte)0x44, (byte)0x75, (byte)0x63, (byte)0x61, + (byte)0x80, (byte)0xf0, (byte)0x01, (byte)0xc0, (byte)0xd8, (byte)0x00, (byte)0x04, (byte)0x00, (byte)0x08, (byte)0x00, (byte)0x00, (byte)0x04, (byte)0x00, (byte)0x03, (byte)0x01, (byte)0xca, + (byte)0x03, (byte)0xaa, (byte)0x09, (byte)0x04, (byte)0x00, (byte)0x00, (byte)0x28, (byte)0x0a, (byte)0x00, (byte)0x00, (byte)0x61, (byte)0x00, (byte)0x70, (byte)0x00, (byte)0x6f, (byte)0x00, + (byte)0x6c, (byte)0x00, (byte)0x6c, (byte)0x00, (byte)0x6f, (byte)0x00, (byte)0x2e, (byte)0x00, (byte)0x76, (byte)0x00, (byte)0x6c, (byte)0x00, (byte)0x69, (byte)0x00, (byte)0x73, (byte)0x00, + (byte)0x69, (byte)0x00, (byte)0x76, (byte)0x00, (byte)0x6b, (byte)0x00, (byte)0x61, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x04, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x0c, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x01, (byte)0xca, (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x10, (byte)0x00, + (byte)0x07, (byte)0x00, (byte)0x21, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x00, (byte)0x02, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x04, (byte)0xc0, (byte)0x0c, (byte)0x00, (byte)0x0d, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x02, (byte)0xc0, (byte)0x0c, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, + }); +// +// buf.writeBytes(new byte[] { +//// - T125: MCSConnect Initial +//// - MCSConnectInitial: Identifier=Generic Conference Control (0.0.20.124.0.1), ConnectPDULength=254 +//// - ConnectInitialHeader: +// (byte)0x7F, (byte)0x65, +//// - AsnId: Application Constructed Tag (101) +//// - HighTag: +//// Class: (01......) Application (1) +//// Type: (..1.....) Constructed +//// TagNumber: (...11111) +//// TagValueEnd: 101 (0x65) +// (byte)0x82, (byte)0x01, (byte)0x6C, +//// - AsnLen: Length = 364, LengthOfLength = 2 +//// LengthType: LengthOfLength = 2 +//// Length: 364 bytes +// (byte)0x04, (byte)0x01, (byte)0x01, +//// - CallingDomainSelector: 0x1 +//// - AsnOctetStringHeader: +//// - AsnId: OctetString type (Universal 4) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..0.....) Primitive +//// TagValue: (...00100) 4 +//// - AsnLen: Length = 1, LengthOfLength = 0 +//// Length: 1 bytes, LengthOfLength = 0 +//// OctetStream: 0x1 +// (byte)0x04, (byte)0x01, (byte)0x01, +//// - CalledDomainSelector: 0x1 +//// - AsnOctetStringHeader: +//// - AsnId: OctetString type (Universal 4) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..0.....) Primitive +//// TagValue: (...00100) 4 +//// - AsnLen: Length = 1, LengthOfLength = 0 +//// Length: 1 bytes, LengthOfLength = 0 +//// OctetStream: 0x1 +// (byte)0x01, (byte)0x01, (byte)0xFF, +//// - UpwardFlag: True +//// - AsnBooleanHeader: +//// - AsnId: Boolean type (Universal 1) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..0.....) Primitive +//// TagValue: (...00001) 1 +//// - AsnLen: Length = 1, LengthOfLength = 0 +//// Length: 1 bytes, LengthOfLength = 0 +//// Tf: 255 (0xFF) +// +//// +//// - TargetParameters: Length = 26, LengthOfLength = 0 +// (byte)0x30, (byte)0x1A, +//// - DomainParametersHeader: 0x1 +//// - AsnId: Sequence and SequenceOf types (Universal 16) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..1.....) Constructed +//// TagValue: (...10000) 16 +//// - AsnLen: Length = 26, LengthOfLength = 0 +//// Length: 26 bytes, LengthOfLength = 0 +// (byte)0x02, (byte)0x01, (byte)0x22, +//// - ChannelIds: 34 +//// - AsnIntegerHeader: +//// - AsnId: Integer type (Universal 2) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..0.....) Primitive +//// TagValue: (...00010) 2 +//// - AsnLen: Length = 1, LengthOfLength = 0 +//// Length: 1 bytes, LengthOfLength = 0 +//// AsnInt: 34 (0x22) +// (byte)0x02, (byte)0x01, (byte)0x02, +//// - UserIDs: 2 +//// - AsnIntegerHeader: +//// - AsnId: Integer type (Universal 2) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..0.....) Primitive +//// TagValue: (...00010) 2 +//// - AsnLen: Length = 1, LengthOfLength = 0 +//// Length: 1 bytes, LengthOfLength = 0 +//// AsnInt: 2 (0x2) +// (byte)0x02, (byte)0x01, (byte)0x00, +//// - TokenIds: 0 +//// - AsnIntegerHeader: +//// - AsnId: Integer type (Universal 2) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..0.....) Primitive +//// TagValue: (...00010) 2 +//// - AsnLen: Length = 1, LengthOfLength = 0 +//// Length: 1 bytes, LengthOfLength = 0 +//// AsnInt: 0 (0x0) +// (byte)0x02, (byte)0x01, (byte)0x01, +//// - NumPriorities: 1 +//// - AsnIntegerHeader: +//// - AsnId: Integer type (Universal 2) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..0.....) Primitive +//// TagValue: (...00010) 2 +//// - AsnLen: Length = 1, LengthOfLength = 0 +//// Length: 1 bytes, LengthOfLength = 0 +//// AsnInt: 1 (0x1) +// (byte)0x02, (byte)0x01, (byte)0x00, +//// - MinThroughput: 0 +//// - AsnIntegerHeader: +//// - AsnId: Integer type (Universal 2) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..0.....) Primitive +//// TagValue: (...00010) 2 +//// - AsnLen: Length = 1, LengthOfLength = 0 +//// Length: 1 bytes, LengthOfLength = 0 +//// AsnInt: 0 (0x0) +// (byte)0x02, (byte)0x01, (byte)0x01, +//// - Height: 1 +//// - AsnIntegerHeader: +//// - AsnId: Integer type (Universal 2) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..0.....) Primitive +//// TagValue: (...00010) 2 +//// - AsnLen: Length = 1, LengthOfLength = 0 +//// Length: 1 bytes, LengthOfLength = 0 +//// AsnInt: 1 (0x1) +// (byte)0x02, (byte)0x03, (byte)0x00, (byte)0xFF, (byte)0xFF, +//// - MCSPDUsize: 65535 +//// - AsnIntegerHeader: +//// - AsnId: Integer type (Universal 2) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..0.....) Primitive +//// TagValue: (...00010) 2 +//// - AsnLen: Length = 3, LengthOfLength = 0 +//// Length: 3 bytes, LengthOfLength = 0 +//// AsnInt: 65535 (0xFFFF) +// (byte)0x02, (byte)0x01, (byte)0x02, +//// - protocolVersion: 2 +//// - AsnIntegerHeader: +//// - AsnId: Integer type (Universal 2) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..0.....) Primitive +//// TagValue: (...00010) 2 +//// - AsnLen: Length = 1, LengthOfLength = 0 +//// Length: 1 bytes, LengthOfLength = 0 +//// AsnInt: 2 (0x2) +// +//// +//// - MinimumParameters: Length = 25, LengthOfLength = 0 +// (byte)0x30, (byte)0x19, +//// - DomainParametersHeader: 0x1 +//// - AsnId: Sequence and SequenceOf types (Universal 16) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..1.....) Constructed +//// TagValue: (...10000) 16 +//// - AsnLen: Length = 25, LengthOfLength = 0 +//// Length: 25 bytes, LengthOfLength = 0 +// (byte)0x02, (byte)0x01, (byte)0x01, +//// - ChannelIds: 1 +//// - AsnIntegerHeader: +//// - AsnId: Integer type (Universal 2) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..0.....) Primitive +//// TagValue: (...00010) 2 +//// - AsnLen: Length = 1, LengthOfLength = 0 +//// Length: 1 bytes, LengthOfLength = 0 +//// AsnInt: 1 (0x1) +// (byte)0x02, (byte)0x01, (byte)0x01, +//// - UserIDs: 1 +//// - AsnIntegerHeader: +//// - AsnId: Integer type (Universal 2) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..0.....) Primitive +//// TagValue: (...00010) 2 +//// - AsnLen: Length = 1, LengthOfLength = 0 +//// Length: 1 bytes, LengthOfLength = 0 +//// AsnInt: 1 (0x1) +// (byte)0x02, (byte)0x01, (byte)0x01, +//// - TokenIds: 1 +//// - AsnIntegerHeader: +//// - AsnId: Integer type (Universal 2) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..0.....) Primitive +//// TagValue: (...00010) 2 +//// - AsnLen: Length = 1, LengthOfLength = 0 +//// Length: 1 bytes, LengthOfLength = 0 +//// AsnInt: 1 (0x1) +// (byte)0x02, (byte)0x01, (byte)0x01, +//// - NumPriorities: 1 +//// - AsnIntegerHeader: +//// - AsnId: Integer type (Universal 2) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..0.....) Primitive +//// TagValue: (...00010) 2 +//// - AsnLen: Length = 1, LengthOfLength = 0 +//// Length: 1 bytes, LengthOfLength = 0 +//// AsnInt: 1 (0x1) +// (byte)0x02, (byte)0x01, (byte)0x00, +//// - MinThroughput: 0 +//// - AsnIntegerHeader: +//// - AsnId: Integer type (Universal 2) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..0.....) Primitive +//// TagValue: (...00010) 2 +//// - AsnLen: Length = 1, LengthOfLength = 0 +//// Length: 1 bytes, LengthOfLength = 0 +//// AsnInt: 0 (0x0) +// (byte)0x02, (byte)0x01, (byte)0x01, +//// - Height: 1 +//// - AsnIntegerHeader: +//// - AsnId: Integer type (Universal 2) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..0.....) Primitive +//// TagValue: (...00010) 2 +//// - AsnLen: Length = 1, LengthOfLength = 0 +//// Length: 1 bytes, LengthOfLength = 0 +//// AsnInt: 1 (0x1) +// (byte)0x02, (byte)0x02, (byte)0x04, (byte)0x20, +//// - MCSPDUsize: 1056 +//// - AsnIntegerHeader: +//// - AsnId: Integer type (Universal 2) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..0.....) Primitive +//// TagValue: (...00010) 2 +//// - AsnLen: Length = 2, LengthOfLength = 0 +//// Length: 2 bytes, LengthOfLength = 0 +//// AsnInt: 1056 (0x420) +// (byte)0x02, (byte)0x01, (byte)0x02, +//// - protocolVersion: 2 +//// - AsnIntegerHeader: +//// - AsnId: Integer type (Universal 2) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..0.....) Primitive +//// TagValue: (...00010) 2 +//// - AsnLen: Length = 1, LengthOfLength = 0 +//// Length: 1 bytes, LengthOfLength = 0 +//// AsnInt: 2 (0x2) +//// - MaximumParameters: Length = 31, LengthOfLength = 0 +//// - DomainParametersHeader: 0x1 +// (byte)0x30, (byte)0x1F, +//// - AsnId: Sequence and SequenceOf types (Universal 16) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..1.....) Constructed +//// TagValue: (...10000) 16 +//// - AsnLen: Length = 31, LengthOfLength = 0 +//// Length: 31 bytes, LengthOfLength = 0 +// (byte)0x02, (byte)0x03, (byte)0x00, (byte)0xFF, (byte)0xFF, +//// - ChannelIds: 65535 +//// - AsnIntegerHeader: +//// - AsnId: Integer type (Universal 2) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..0.....) Primitive +//// TagValue: (...00010) 2 +//// - AsnLen: Length = 3, LengthOfLength = 0 +//// Length: 3 bytes, LengthOfLength = 0 +//// AsnInt: 65535 (0xFFFF) +// (byte)0x02, (byte)0x02, (byte)0xFC, (byte)0x17, +//// - UserIDs: 64535 +//// - AsnIntegerHeader: +//// - AsnId: Integer type (Universal 2) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..0.....) Primitive +//// TagValue: (...00010) 2 +//// - AsnLen: Length = 2, LengthOfLength = 0 +//// Length: 2 bytes, LengthOfLength = 0 +//// AsnInt: 64535 (0xFC17) +// (byte)0x02, (byte)0x03, (byte)0x00, (byte)0xFF, (byte)0xFF, +//// - TokenIds: 65535 +//// - AsnIntegerHeader: +//// - AsnId: Integer type (Universal 2) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..0.....) Primitive +//// TagValue: (...00010) 2 +//// - AsnLen: Length = 3, LengthOfLength = 0 +//// Length: 3 bytes, LengthOfLength = 0 +//// AsnInt: 65535 (0xFFFF) +// (byte)0x02, (byte)0x01, (byte)0x01, +//// - NumPriorities: 1 +//// - AsnIntegerHeader: +//// - AsnId: Integer type (Universal 2) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..0.....) Primitive +//// TagValue: (...00010) 2 +//// - AsnLen: Length = 1, LengthOfLength = 0 +//// Length: 1 bytes, LengthOfLength = 0 +//// AsnInt: 1 (0x1) +// (byte)0x02, (byte)0x01, (byte)0x00, +//// - MinThroughput: 0 +//// - AsnIntegerHeader: +//// - AsnId: Integer type (Universal 2) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..0.....) Primitive +//// TagValue: (...00010) 2 +//// - AsnLen: Length = 1, LengthOfLength = 0 +//// Length: 1 bytes, LengthOfLength = 0 +//// AsnInt: 0 (0x0) +// (byte)0x02, (byte)0x01, (byte)0x01, +//// - Height: 1 +//// - AsnIntegerHeader: +//// - AsnId: Integer type (Universal 2) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..0.....) Primitive +//// TagValue: (...00010) 2 +//// - AsnLen: Length = 1, LengthOfLength = 0 +//// Length: 1 bytes, LengthOfLength = 0 +//// AsnInt: 1 (0x1) +// (byte)0x02, (byte)0x03, (byte)0x00, (byte)0xFF, (byte)0xFF, +//// - MCSPDUsize: 65535 +//// - AsnIntegerHeader: +//// - AsnId: Integer type (Universal 2) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..0.....) Primitive +//// TagValue: (...00010) 2 +//// - AsnLen: Length = 3, LengthOfLength = 0 +//// Length: 3 bytes, LengthOfLength = 0 +//// AsnInt: 65535 (0xFFFF) +// (byte)0x02, (byte)0x01, (byte)0x02, +//// - protocolVersion: 2 +//// - AsnIntegerHeader: +//// - AsnId: Integer type (Universal 2) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..0.....) Primitive +//// TagValue: (...00010) 2 +//// - AsnLen: Length = 1, LengthOfLength = 0 +//// Length: 1 bytes, LengthOfLength = 0 +//// AsnInt: 2 (0x2) +//// - UserData: Identifier=Generic Conference Control (0.0.20.124.0.1), ConnectPDULength=254 +//// - UserDataHeader: +// (byte)0x04, (byte)0x82, (byte)0x01, (byte)0x07, +//// - AsnId: OctetString type (Universal 4) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..0.....) Primitive +//// TagValue: (...00100) 4 +//// - AsnLen: Length = 263, LengthOfLength = 2 +//// LengthType: LengthOfLength = 2 +//// Length: 263 bytes +// (byte)0x00, (byte)0x05, (byte)0x00, (byte)0x14, (byte)0x7C, (byte)0x00, (byte)0x01, +//// - AsnBerObjectIdentifier: Generic Conference Contro (0.0.20.124.0.1) +//// - AsnObjectIdentifierHeader: +//// - AsnId: Reserved for use by the encoding rules (Universal 0) +//// - LowTag: +//// Class: (00......) Universal (0) +//// Type: (..0.....) Primitive +//// TagValue: (...00000) 0 +//// - AsnLen: Length = 5, LengthOfLength = 0 +//// Length: 5 bytes, LengthOfLength = 0 +//// First: 0 (0x0) +//// Final: 20 (0x14) +//// Final: 124 (0x7C) +//// Final: 0 (0x0) +//// Final: 1 (0x1) +// (byte)0x80, (byte)0xFE, +//// - ConnectPDULength: 254 +//// Align: No Padding +//// Length: 254 +// (byte)0x00, (byte)0x08, (byte)0x00, (byte)0x10, +//// - ConnectGCCPDU: conferenceCreateRequest +//// ExtensionBit: 0 (0x0) +//// - ChoiceValue: conferenceCreateRequest +//// Value: (000.....) 0x0 +//// - conferenceCreateRequest: +//// ExtensionBit: 0 (0x0) +//// convenerPasswordPresent: 0 (0x0) +//// passwordPresent: 0 (0x0) +//// conductorPrivilegesPresent: 0 (0x0) +//// conductedPrivilegesPresent: 0 (0x0) +//// nonConductedPrivilegesPresent: 0 (0x0) +//// conferenceDescriptionPresent: 0 (0x0) +//// callerIdentifierPresent: 0 (0x0) +//// userDataPresent: 1 (0x1) +//// - conferenceName: +//// ExtensionBit: 0 (0x0) +//// textPresent: 0 (0x0) +//// - numeric: 1 +//// - SimpleNumericString: 1 +//// - NumericString: 1 +//// - Align: No Padding +//// Padding1: (0.......) 0x0 +//// - Length: 1 +//// Value: (00000000) 0x0 +//// - Restrictedstr: 1 +//// FourBits: (0001....) 0x1 +//// - lockedConference: False +//// Value: False 0....... +//// - listedConference: False +//// Value: False 0....... +//// - conductibleConference: False +//// Value: False 0....... +//// - TerminationMethod: automatic +//// ExtensionBit: 0 (0x0) +//// - RootIndex: 0 +//// Value: (0.......) 0x0 +//// - userData: +// (byte)0x00, (byte)0x01, +//// - Size: 1 +//// - Align: No Padding +//// Padding7: (0000000.) 0x0 +//// Length: 1 +//// - UserData: 0x44756361 +// (byte)0xC0, (byte)0x00, (byte)0x44, (byte)0x75, (byte)0x63, (byte)0x61, +//// valuePresent: 1 (0x1) +//// - key: h221NonStandard "Duca" +//// - ChoiceValue: h221NonStandard +//// Value: (1.......) 0x1 +//// - h221NonStandard: +//// - H221NonStandardIdentifier: length: 4 +//// - ConstrainedLength: 4 +//// Value: (00000000) 0x0 +//// - Align: No Padding +//// Padding6: (000000..) 0x0 +//// Value: Binary Large Object (4 Bytes) "Duca" +//// - ClientMcsConnectInitialPdu: +// (byte)0x80, (byte)0xF0, +//// - RDPGCCUserDataRequestLength: 240 +//// Align: No Padding +//// Length: 240 +//// - TsUd: CS_CORE +// (byte)0x01, (byte)0xC0, (byte)0xD8, (byte)0x00, +//// - TsUdHeader: Type = CS_CORE, Length = 216 +//// Type: CS_CORE +//// Length: 216 (0xD8) +//// - TsUdCsCore: +// (byte)0x04, (byte)0x00, (byte)0x08, (byte)0x00, +//// Version: RDP 5.0, 5.1, 5.2, 6.0, 6.1, and 7.0 +// (byte)0x00, (byte)0x04, +//// DesktopWidth: 1024 (0x400) +// (byte)0x00, (byte)0x03, +//// DesktopHeight: 768 (0x300) +// (byte)0x01, (byte)0xCA, +//// ColorDepth: 8 bpp +// (byte)0x03, (byte)0xAA, +//// SASSequence: 0xaa03, SHOULD be set to RNS_UD_SAS_DEL(0xAA03) +// (byte)0x09, (byte)0x04, (byte)0x00, (byte)0x00, +//// KeyboardLayout: Language: English, Location: United States +// (byte)0x28, (byte)0x0A, (byte)0x00, (byte)0x00, +//// ClientBuild: 2600 (0xA28) +// (byte)0x61, (byte)0x00, (byte)0x70, (byte)0x00, (byte)0x6F, (byte)0x00, (byte)0x6C, (byte)0x00, (byte)0x6C, (byte)0x00, (byte)0x6F, (byte)0x00, (byte)0x33, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, +//// ClientName: apollo3 +// (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, +//// KeyboardType: Undefined value: 0 +// (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, +//// KeyboardSubType: 0 (0x0) +// (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, +//// KeyboardFunctionKey: 0 (0x0) +// (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, +//// ImeFileName: +// (byte)0x01, (byte)0xCA, +//// PostBeta2ColorDepth: 8 bpp +// (byte)0x01, (byte)0x00, +//// ClientProductId: 0x1, SHOULD be set to initialized to 1 +// (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, +//// SerialNumber: 0x0, SHOULD be set to 0 +// (byte)0x10, (byte)0x00, +//// HighColorDepth: 16-bit 565 RGB +// (byte)0x07, (byte)0x00, +//// - SupportedColorDepth: 7 (0x7) +//// Support24BPP: (...............1) Support 24BPP +//// Support16BPP: (..............1.) Support 16BPP +//// Support15BPP: (.............1..) Support 15BPP +//// Support32BPP: (............0...) Not Support 32BPP +//// Reserved: (000000000000....) +// (byte)0x01, (byte)0x00, +//// - EarlyCapabilityFlags: 1 (0x1) +//// SupportSetErrorPdu: (...............1) Indicates that the client supports the Set Error Info PDU +//// Want32BppSession: (..............0.) Client is not requesting 32BPP session +//// SupportStatusInfoPdu: (.............0..) Client not supports the Server Status Info PDU +//// StrongAsymmetricKeys: (............0...) Not support asymmetric keys larger than 512-bits +//// Unused: (...........0....) +//// ValidConnection: (..........0.....) Not Indicates ConnectionType field contains valid data +//// SupportMonitorLayoutPdu: (.........0......) Not Indicates that the client supports the Monitor Layout PDU +//// Unused2: (000000000.......) +// (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, +//// ClientDigProductId: +//(byte)0x00, +//// connectionType: invalid connection type +//(byte)0x00, +//// pad1octet: 0 (0x0) +//(byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, +//// ServerSelectedProtocols: TLS 1.0 +//// +//// - TsUd: CS_CLUSTER +//// - TsUdHeader: Type = CS_CLUSTER, Length = 12 +//(byte)0x04, (byte)0xC0, +//// Type: CS_CLUSTER +//(byte)0x0C, (byte)0x00, +//// Length: 12 (0xC) +//(byte)0x0D, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, +//// - TsUdCsCluster: +//// - Flags: 13 (0xD) +//// RedirectedSupported: (...............................1) Support Redirected +//// SessionIDFieldValid: (..............................0.) SessionID Field not Valid +//// SupportedVersion: (..........................0011..) REDIRECTION_VERSION4 +//// RedirectedSmartcard: (.........................0......) Not Logon with Smartcard +//// Unused: (0000000000000000000000000.......) +//// RedirectedSessionID: 0 (0x0) +//// +//// - TsUd: CS_SECURITY +//// - TsUdHeader: Type = CS_SECURITY, Length = 12 +//(byte)0x02, (byte)0xC0, +//// Type: CS_SECURITY +//(byte)0x0C, (byte)0x00, +//// Length: 12 (0xC) +//// +//// - TsUdCsSec: +//(byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, +//// - EncryptionMethod: +//// Support40Bit: (...............................0) Not Support +//// Support128Bit: (..............................0.) Not Support 128-bit +//// Reserved1: (.............................0..) +//// Support56Bit: (............................0...) Not Support 56-bit +//// SupportFIPS: (...........................0....) Not Support FIPS Compliant +//// Reserved2: (000000000000000000000000000.....) +//(byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, +//// - ExtEncryptionMethod: +//// Support40Bit: (...............................0) Not Support +//// Support128Bit: (..............................0.) Not Support 128-bit +//// Reserved1: (.............................0..) +//// Support56Bit: (............................0...) Not Support 56-bit +//// SupportFIPS: (...........................0....) Not Support FIPS Compliant +//// Reserved2: (000000000000000000000000000.....) +// }); + /* @formatter:on */ + + buf.trimAtCursor(); + + pushDataToOTOut(buf); + + switchOff(); + } + + /** + * Example. + * + * @see http://msdn.microsoft.com/en-us/library/cc240836.aspx + */ + public static void main(String args[]) { + // System.setProperty("streamer.Link.debug", "true"); + System.setProperty("streamer.Element.debug", "true"); + // System.setProperty("streamer.Pipeline.debug", "true"); + + /* @formatter:off */ + byte[] packet = new byte[] { + // TPKT: TPKT version = 3 + (byte) 0x03, (byte) 0x00, + // TPKT: Packet length: 378 bytes + (byte) 0x01, (byte) 0x78, + + // X.224: Length indicator = 2 + (byte) 0x02, + // X.224: Type: Data TPDU + (byte) 0xf0, + // X.224: EOT + (byte) 0x80, + + // Captured packet + (byte)0x7f, (byte)0x65, (byte)0x82, (byte)0x01, (byte)0x6c, (byte)0x04, (byte)0x01, (byte)0x01, (byte)0x04, + (byte)0x01, (byte)0x01, (byte)0x01, (byte)0x01, (byte)0xff, (byte)0x30, (byte)0x1a, (byte)0x02, (byte)0x01, (byte)0x22, (byte)0x02, (byte)0x01, (byte)0x02, (byte)0x02, (byte)0x01, (byte)0x00, + (byte)0x02, (byte)0x01, (byte)0x01, (byte)0x02, (byte)0x01, (byte)0x00, (byte)0x02, (byte)0x01, (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x00, (byte)0xff, (byte)0xff, (byte)0x02, (byte)0x01, + (byte)0x02, (byte)0x30, (byte)0x19, (byte)0x02, (byte)0x01, (byte)0x01, (byte)0x02, (byte)0x01, (byte)0x01, (byte)0x02, (byte)0x01, (byte)0x01, (byte)0x02, (byte)0x01, (byte)0x01, (byte)0x02, + (byte)0x01, (byte)0x00, (byte)0x02, (byte)0x01, (byte)0x01, (byte)0x02, (byte)0x02, (byte)0x04, (byte)0x20, (byte)0x02, (byte)0x01, (byte)0x02, (byte)0x30, (byte)0x1f, (byte)0x02, (byte)0x03, + (byte)0x00, (byte)0xff, (byte)0xff, (byte)0x02, (byte)0x02, (byte)0xfc, (byte)0x17, (byte)0x02, (byte)0x03, (byte)0x00, (byte)0xff, (byte)0xff, (byte)0x02, (byte)0x01, (byte)0x01, (byte)0x02, + (byte)0x01, (byte)0x00, (byte)0x02, (byte)0x01, (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x00, (byte)0xff, (byte)0xff, (byte)0x02, (byte)0x01, (byte)0x02, (byte)0x04, (byte)0x82, (byte)0x01, + (byte)0x07, (byte)0x00, (byte)0x05, (byte)0x00, (byte)0x14, (byte)0x7c, (byte)0x00, (byte)0x01, (byte)0x80, (byte)0xfe, (byte)0x00, (byte)0x08, (byte)0x00, (byte)0x10, (byte)0x00, (byte)0x01, + (byte)0xc0, (byte)0x00, (byte)0x44, (byte)0x75, (byte)0x63, (byte)0x61, (byte)0x80, (byte)0xf0, (byte)0x01, (byte)0xc0, (byte)0xd8, (byte)0x00, (byte)0x04, (byte)0x00, (byte)0x08, (byte)0x00, + (byte)0x00, (byte)0x04, (byte)0x00, (byte)0x03, (byte)0x01, (byte)0xca, (byte)0x03, (byte)0xaa, (byte)0x09, (byte)0x04, (byte)0x00, (byte)0x00, (byte)0x28, (byte)0x0a, (byte)0x00, (byte)0x00, + (byte)0x61, (byte)0x00, (byte)0x70, (byte)0x00, (byte)0x6f, (byte)0x00, (byte)0x6c, (byte)0x00, (byte)0x6c, (byte)0x00, (byte)0x6f, (byte)0x00, (byte)0x33, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x01, (byte)0xca, (byte)0x01, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x10, (byte)0x00, (byte)0x07, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x04, (byte)0xc0, (byte)0x0c, (byte)0x00, (byte)0x0d, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x02, (byte)0xc0, (byte)0x0c, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + }; + /* @formatter:on */ + + MockSource source = new MockSource("source", ByteBuffer.convertByteArraysToByteBuffers(new byte[] {1, 2, 3})); + Element todo = new ClientMCSConnectInitial("ClientMCSConnectInitial"); + Element x224 = new ClientX224DataPDU("x224"); + Element tpkt = new ClientTpkt("tpkt"); + + Element sink = new MockSink("sink", ByteBuffer.convertByteArraysToByteBuffers(packet)); + + Element mainSink = new MockSink("mainSink", ByteBuffer.convertByteArraysToByteBuffers(new byte[] {1, 2, 3})); + + Pipeline pipeline = new PipelineImpl("test"); + pipeline.add(source, todo, x224, tpkt, sink, mainSink); + pipeline.link("source", "ClientMCSConnectInitial", "mainSink"); + pipeline.link("ClientMCSConnectInitial >" + OTOUT, "x224", "tpkt", "sink"); + pipeline.runMainLoop("source", STDOUT, false, false); + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientMCSErectDomainRequest.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientMCSErectDomainRequest.java old mode 100644 new mode 100755 similarity index 67% rename from services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientMCSErectDomainRequest.java rename to services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientMCSErectDomainRequest.java index 4cb00aad2ae..a6ea406d8c1 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientMCSErectDomainRequest.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientMCSErectDomainRequest.java @@ -14,16 +14,16 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package rdpclient; +package rdpclient.rdp; import streamer.ByteBuffer; import streamer.Element; import streamer.Link; -import streamer.MockSink; -import streamer.MockSource; import streamer.OneTimeSwitch; import streamer.Pipeline; import streamer.PipelineImpl; +import streamer.debug.MockSink; +import streamer.debug.MockSource; /** * @see http://msdn.microsoft.com/en-us/library/cc240683.aspx @@ -74,71 +74,71 @@ public class ClientMCSErectDomainRequest extends OneTimeSwitch { // System.setProperty("streamer.Pipeline.debug", "true"); /* @formatter:off */ - byte[] packet = new byte[] { + byte[] packet = new byte[] { - 0x03, 0x00, 0x00, 0x0c, // TPKT Header (length = 12 bytes) - 0x02, (byte) 0xf0, (byte) 0x80, // X.224 Data TPDU + 0x03, 0x00, 0x00, 0x0c, // TPKT Header (length = 12 bytes) + 0x02, (byte) 0xf0, (byte) 0x80, // X.224 Data TPDU - // PER encoded (ALIGNED variant of BASIC-PER) PDU contents: - 0x04, 0x01, 0x00, 0x01, 0x00, + // PER encoded (ALIGNED variant of BASIC-PER) PDU contents: + 0x04, 0x01, 0x00, 0x01, 0x00, - // 0x04: - // 0 - --\ - // 0 - | - // 0 - | CHOICE: From DomainMCSPDU select erectDomainRequest (1) - // 0 - | of type ErectDomainRequest - // 0 - | - // 1 - --/ - // 0 - padding - // 0 - padding + // 0x04: + // 0 - --\ + // 0 - | + // 0 - | CHOICE: From DomainMCSPDU select erectDomainRequest (1) + // 0 - | of type ErectDomainRequest + // 0 - | + // 1 - --/ + // 0 - padding + // 0 - padding - // 0x01: - // 0 - --\ - // 0 - | - // 0 - | - // 0 - | ErectDomainRequest::subHeight length = 1 byte - // 0 - | - // 0 - | - // 0 - | - // 1 - --/ + // 0x01: + // 0 - --\ + // 0 - | + // 0 - | + // 0 - | ErectDomainRequest::subHeight length = 1 byte + // 0 - | + // 0 - | + // 0 - | + // 1 - --/ - // 0x00: - // 0 - --\ - // 0 - | - // 0 - | - // 0 - | ErectDomainRequest::subHeight = 0 - // 0 - | - // 0 - | - // 0 - | - // 0 - --/ + // 0x00: + // 0 - --\ + // 0 - | + // 0 - | + // 0 - | ErectDomainRequest::subHeight = 0 + // 0 - | + // 0 - | + // 0 - | + // 0 - --/ - // 0x01: - // 0 - --\ - // 0 - | - // 0 - | - // 0 - | ErectDomainRequest::subInterval length = 1 byte - // 0 - | - // 0 - | - // 0 - | - // 1 - --/ + // 0x01: + // 0 - --\ + // 0 - | + // 0 - | + // 0 - | ErectDomainRequest::subInterval length = 1 byte + // 0 - | + // 0 - | + // 0 - | + // 1 - --/ - // 0x00: - // 0 - --\ - // 0 - | - // 0 - | - // 0 - | ErectDomainRequest::subInterval = 0 - // 0 - | - // 0 - | - // 0 - | - // 0 - --/ + // 0x00: + // 0 - --\ + // 0 - | + // 0 - | + // 0 - | ErectDomainRequest::subInterval = 0 + // 0 - | + // 0 - | + // 0 - | + // 0 - --/ - }; - /* @formatter:on */ + }; + /* @formatter:on */ MockSource source = new MockSource("source", ByteBuffer.convertByteArraysToByteBuffers(new byte[] {1, 2, 3})); Element todo = new ClientMCSErectDomainRequest("TODO"); - Element x224 = new ClientX224DataPdu("x224"); + Element x224 = new ClientX224DataPDU("x224"); Element tpkt = new ClientTpkt("tpkt"); Element sink = new MockSink("sink", ByteBuffer.convertByteArraysToByteBuffers(packet)); Element mainSink = new MockSink("mainSink", ByteBuffer.convertByteArraysToByteBuffers(new byte[] {1, 2, 3})); diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientSynchronizePDU.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientSynchronizePDU.java old mode 100644 new mode 100755 similarity index 58% rename from services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientSynchronizePDU.java rename to services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientSynchronizePDU.java index 5b370b5cd21..c9d8d0ce316 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientSynchronizePDU.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientSynchronizePDU.java @@ -14,16 +14,16 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package rdpclient; +package rdpclient.rdp; import streamer.ByteBuffer; import streamer.Element; import streamer.Link; -import streamer.MockSink; -import streamer.MockSource; import streamer.OneTimeSwitch; import streamer.Pipeline; import streamer.PipelineImpl; +import streamer.debug.MockSink; +import streamer.debug.MockSource; /** * @see http://msdn.microsoft.com/en-us/library/cc240489.aspx @@ -50,46 +50,46 @@ public class ClientSynchronizePDU extends OneTimeSwitch { ByteBuffer buf = new ByteBuffer(length, true); /* @formatter:off */ - buf.writeBytes(new byte[] { - // MCS send data request - (byte)0x64, - // Initiator: 1004 (1001+3) - (byte)0x00, (byte)0x03, - // Channel ID: 1003 (I/O Channel) - (byte)0x03, (byte)0xeb, - // Data priority: high (0x40), segmentation: begin (0x20) | end (0x10) - (byte)0x70, - // Data length: 22 bytes (0x16, variable length field) - (byte)0x80, (byte)0x16, + buf.writeBytes(new byte[] { + // MCS send data request + (byte)0x64, + // Initiator: 1004 (1001+3) + (byte)0x00, (byte)0x03, + // Channel ID: 1003 (I/O Channel) + (byte)0x03, (byte)0xeb, + // Data priority: high (0x40), segmentation: begin (0x20) | end (0x10) + (byte)0x70, + // Data length: 22 bytes (0x16, variable length field) + (byte)0x80, (byte)0x16, - // RDP: total length: 22 bytes (LE) - (byte)0x16, (byte)0x00, + // RDP: total length: 22 bytes (LE) + (byte)0x16, (byte)0x00, - // PDU type: PDUTYPE_DATAPDU (0x7), TS_PROTOCOL_VERSION (0x10) (LE) - (byte)0x17, (byte)0x00, + // PDU type: PDUTYPE_DATAPDU (0x7), TS_PROTOCOL_VERSION (0x10) (LE) + (byte)0x17, (byte)0x00, - // PDU source: 1007 (LE) - (byte)0xec, (byte)0x03, - // Share ID: 0x000103ea (LE) - (byte)0xea, (byte)0x03, (byte)0x01, (byte)0x00, - // Padding: 1 byte - (byte)0x00, - // Stream ID: STREAM_LOW (1) - (byte)0x01, - // uncompressedLength : 8 bytes (LE) - (byte)0x08, (byte)0x00, - // pduType2 = PDUTYPE2_SYNCHRONIZE (31) - (byte)0x1f, - // generalCompressedType: 0 - (byte)0x00, - // generalCompressedLength: 0 (LE?) - (byte)0x00, (byte)0x00, - // messageType: SYNCMSGTYPE_SYNC (1) (LE) - (byte)0x01, (byte)0x00, - // targetUser: 0x03ea - (byte)0xea, (byte)0x03, - }); - /* @formatter:on */ + // PDU source: 1007 (LE) + (byte)0xec, (byte)0x03, + // Share ID: 0x000103ea (LE) + (byte)0xea, (byte)0x03, (byte)0x01, (byte)0x00, + // Padding: 1 byte + (byte)0x00, + // Stream ID: STREAM_LOW (1) + (byte)0x01, + // uncompressedLength : 8 bytes (LE) + (byte)0x08, (byte)0x00, + // pduType2 = PDUTYPE2_SYNCHRONIZE (31) + (byte)0x1f, + // generalCompressedType: 0 + (byte)0x00, + // generalCompressedLength: 0 (LE?) + (byte)0x00, (byte)0x00, + // messageType: SYNCMSGTYPE_SYNC (1) (LE) + (byte)0x01, (byte)0x00, + // targetUser: 0x03ea + (byte)0xea, (byte)0x03, + }); + /* @formatter:on */ // Trim buffer to actual length of data written buf.trimAtCursor(); @@ -110,56 +110,56 @@ public class ClientSynchronizePDU extends OneTimeSwitch { // System.setProperty("streamer.Pipeline.debug", "true"); /* @formatter:off */ - byte[] packet = new byte[] { - // TPKT - (byte)0x03, (byte)0x00, - // TPKT length: 37 bytes - (byte)0x00, (byte)0x25, - // X224 Data PDU - (byte)0x02, (byte)0xf0, (byte)0x80, + byte[] packet = new byte[] { + // TPKT + (byte)0x03, (byte)0x00, + // TPKT length: 37 bytes + (byte)0x00, (byte)0x25, + // X224 Data PDU + (byte)0x02, (byte)0xf0, (byte)0x80, - // MCS send data request - (byte)0x64, - // Initiator: 1004 (1001+3) - (byte)0x00, (byte)0x03, - // Channel ID: 1003 (I/O Channel) - (byte)0x03, (byte)0xeb, - // Data priority: high (0x40), segmentation: begin (0x20) | end (0x10) - (byte)0x70, - // Data length: 22 bytes (0x16, variable length field) - (byte)0x80, (byte)0x16, + // MCS send data request + (byte)0x64, + // Initiator: 1004 (1001+3) + (byte)0x00, (byte)0x03, + // Channel ID: 1003 (I/O Channel) + (byte)0x03, (byte)0xeb, + // Data priority: high (0x40), segmentation: begin (0x20) | end (0x10) + (byte)0x70, + // Data length: 22 bytes (0x16, variable length field) + (byte)0x80, (byte)0x16, - // RDP: total length: 22 bytes (LE) - (byte)0x16, (byte)0x00, - // PDU type: PDUTYPE_DATAPDU (0x7), TS_PROTOCOL_VERSION (0x10) (LE) - (byte)0x17, (byte)0x00, - // PDU source: 1007 (LE) - (byte)0xec, (byte)0x03, - // Share ID: 0x000103ea (LE) - (byte)0xea, (byte)0x03, (byte)0x01, (byte)0x00, - // Padding: 1 byte - (byte)0x00, - // Stream ID: STREAM_LOW (1) - (byte)0x01, - // uncompressedLength : 8 bytes (LE) - (byte)0x08, (byte)0x00, - // pduType2 = PDUTYPE2_SYNCHRONIZE (31) - (byte)0x1f, - // generalCompressedType: 0 - (byte)0x00, - // generalCompressedLength: 0 (LE?) - (byte)0x00, (byte)0x00, - // messageType: SYNCMSGTYPE_SYNC (1) (LE) - (byte)0x01, (byte)0x00, - // targetUser: 0x03ea - (byte)0xea, (byte)0x03, + // RDP: total length: 22 bytes (LE) + (byte)0x16, (byte)0x00, + // PDU type: PDUTYPE_DATAPDU (0x7), TS_PROTOCOL_VERSION (0x10) (LE) + (byte)0x17, (byte)0x00, + // PDU source: 1007 (LE) + (byte)0xec, (byte)0x03, + // Share ID: 0x000103ea (LE) + (byte)0xea, (byte)0x03, (byte)0x01, (byte)0x00, + // Padding: 1 byte + (byte)0x00, + // Stream ID: STREAM_LOW (1) + (byte)0x01, + // uncompressedLength : 8 bytes (LE) + (byte)0x08, (byte)0x00, + // pduType2 = PDUTYPE2_SYNCHRONIZE (31) + (byte)0x1f, + // generalCompressedType: 0 + (byte)0x00, + // generalCompressedLength: 0 (LE?) + (byte)0x00, (byte)0x00, + // messageType: SYNCMSGTYPE_SYNC (1) (LE) + (byte)0x01, (byte)0x00, + // targetUser: 0x03ea + (byte)0xea, (byte)0x03, - }; - /* @formatter:on */ + }; + /* @formatter:on */ MockSource source = new MockSource("source", ByteBuffer.convertByteArraysToByteBuffers(new byte[] {1, 2, 3})); Element todo = new ClientSynchronizePDU("TODO"); - Element x224 = new ClientX224DataPdu("x224"); + Element x224 = new ClientX224DataPDU("x224"); Element tpkt = new ClientTpkt("tpkt"); Element sink = new MockSink("sink", ByteBuffer.convertByteArraysToByteBuffers(packet)); Element mainSink = new MockSink("mainSink", ByteBuffer.convertByteArraysToByteBuffers(new byte[] {1, 2, 3})); diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientTpkt.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientTpkt.java old mode 100644 new mode 100755 similarity index 98% rename from services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientTpkt.java rename to services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientTpkt.java index 036c9591e6f..926c80705aa --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientTpkt.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientTpkt.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package rdpclient; +package rdpclient.rdp; import streamer.BaseElement; import streamer.ByteBuffer; diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientX224ConnectionRequestPDU.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientX224ConnectionRequestPDU.java old mode 100644 new mode 100755 similarity index 76% rename from services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientX224ConnectionRequestPDU.java rename to services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientX224ConnectionRequestPDU.java index fbbfecbc341..6413432b711 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientX224ConnectionRequestPDU.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientX224ConnectionRequestPDU.java @@ -14,16 +14,16 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package rdpclient; +package rdpclient.rdp; import streamer.ByteBuffer; import streamer.Element; import streamer.Link; -import streamer.MockSink; -import streamer.MockSource; import streamer.OneTimeSwitch; import streamer.Pipeline; import streamer.PipelineImpl; +import streamer.debug.MockSink; +import streamer.debug.MockSource; /** * @see http://msdn.microsoft.com/en-us/library/cc240470.aspx @@ -47,9 +47,15 @@ public class ClientX224ConnectionRequestPDU extends OneTimeSwitch { */ protected String userName; - public ClientX224ConnectionRequestPDU(String id, String userName) { + /** + * Protocol to use: RDP_NEG_REQ_PROTOCOL_SSL or RDP_NEG_REQ_PROTOCOL_HYBRID. + */ + protected int protocol; + + public ClientX224ConnectionRequestPDU(String id, String userName, int protocol) { super(id); this.userName = userName; + this.protocol = protocol; } @Override @@ -85,7 +91,7 @@ public class ClientX224ConnectionRequestPDU extends OneTimeSwitch { buf.writeByte(0x00); // RDP_NEG_REQ: Requested protocols: PROTOCOL_SSL - buf.writeIntLE(RdpConstants.RDP_NEG_REQ_PROTOCOL_SSL); + buf.writeIntLE(protocol); // Calculate length of packet and prepend it to buffer ByteBuffer data = new ByteBuffer(5); @@ -119,29 +125,29 @@ public class ClientX224ConnectionRequestPDU extends OneTimeSwitch { byte[] packet = new byte[] { - 0x03, // TPKT Header: version = 3 - 0x00, // TPKT Header: Reserved = 0 - 0x00, // TPKT Header: Packet length - high part - 0x2c, // TPKT Header: Packet length - low part (total = 44 bytes) - 0x27, // X.224: Length indicator (39 bytes) - (byte)0xe0, // X.224: Type (high nibble) = 0xe = CR TPDU; - // credit (low nibble) = 0 - 0x00, 0x00, // X.224: Destination reference = 0 - 0x00, 0x00, // X.224: Source reference = 0 - 0x00, // X.224: Class and options = 0 + 0x03, // TPKT Header: version = 3 + 0x00, // TPKT Header: Reserved = 0 + 0x00, // TPKT Header: Packet length - high part + 0x2c, // TPKT Header: Packet length - low part (total = 44 bytes) + 0x27, // X.224: Length indicator (39 bytes) + (byte)0xe0, // X.224: Type (high nibble) = 0xe = CR TPDU; + // credit (low nibble) = 0 + 0x00, 0x00, // X.224: Destination reference = 0 + 0x00, 0x00, // X.224: Source reference = 0 + 0x00, // X.224: Class and options = 0 - 'C', 'o', 'o', 'k', 'i', 'e', ':', ' ', 'm', 's', 't', 's', 'h', 'a', 's', 'h', '=', 'e', 'l', 't', 'o', 'n', 's', // "Cookie: mstshash=eltons" - '\r', '\n', // -Cookie terminator sequence + 'C', 'o', 'o', 'k', 'i', 'e', ':', ' ', 'm', 's', 't', 's', 'h', 'a', 's', 'h', '=', 'e', 'l', 't', 'o', 'n', 's', // "Cookie: mstshash=eltons" + '\r', '\n', // -Cookie terminator sequence - 0x01, // RDP_NEG_REQ::type (TYPE_RDP_NEG_REQ) - 0x00, // RDP_NEG_REQ::flags (0) - 0x08, 0x00, // RDP_NEG_REQ::length (8 bytes) - 0x01, 0x00, 0x00, 0x00 // RDP_NEG_REQ: Requested protocols - // (PROTOCOL_SSL in little endian format) - }; + 0x01, // RDP_NEG_REQ::type (TYPE_RDP_NEG_REQ) + 0x00, // RDP_NEG_REQ::flags (0) + 0x08, 0x00, // RDP_NEG_REQ::length (8 bytes) + 0x01, 0x00, 0x00, 0x00 // RDP_NEG_REQ: Requested protocols + // (PROTOCOL_SSL in little endian format) + }; MockSource source = new MockSource("source", ByteBuffer.convertByteArraysToByteBuffers(new byte[] {1, 2, 3})); - Element cr = new ClientX224ConnectionRequestPDU("cr", cookie); + Element cr = new ClientX224ConnectionRequestPDU("cr", cookie, RdpConstants.RDP_NEG_REQ_PROTOCOL_SSL); Element tpkt = new ClientTpkt("tpkt"); Element sink = new MockSink("sink", ByteBuffer.convertByteArraysToByteBuffers(packet)); Element mainSink = new MockSink("mainSink", ByteBuffer.convertByteArraysToByteBuffers(new byte[] {1, 2, 3})); diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientX224DataPdu.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientX224DataPDU.java old mode 100644 new mode 100755 similarity index 92% rename from services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientX224DataPdu.java rename to services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientX224DataPDU.java index fc22c430758..b0373ad0340 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ClientX224DataPdu.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ClientX224DataPDU.java @@ -14,18 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package rdpclient; +package rdpclient.rdp; import streamer.BaseElement; import streamer.ByteBuffer; import streamer.Link; -public class ClientX224DataPdu extends BaseElement { +public class ClientX224DataPDU extends BaseElement { public static final int X224_TPDU_DATA = 0xF0; public static final int X224_TPDU_LAST_DATA_UNIT = 0x80; - public ClientX224DataPdu(String id) { + public ClientX224DataPDU(String id) { super(id); } diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/RLEBitmapDecompression.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/RLEBitmapDecompression.java new file mode 100755 index 00000000000..559091172d0 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/RLEBitmapDecompression.java @@ -0,0 +1,1014 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.rdp; + +import streamer.ByteBuffer; +import streamer.debug.AssertingByteBuffer; + +/** + * Based on code example from MSDN, @see + * http://msdn.microsoft.com/en-us/library/dd240593.aspx . + */ +public class RLEBitmapDecompression { + + public static final int g_MaskRegularRunLength = 0x1F; + public static final int g_MaskLiteRunLength = 0x0F; + + public static final int g_MaskSpecialFgBg1 = 0x03; + public static final int g_MaskSpecialFgBg2 = 0x05; + + public static final int REGULAR_BG_RUN = 0x00; + public static final int REGULAR_FG_RUN = 0x01; + public static final int REGULAR_FGBG_IMAGE = 0x02; + public static final int REGULAR_COLOR_RUN = 0x03; + public static final int REGULAR_COLOR_IMAGE = 0x04; + + public static final int LITE_SET_FG_FG_RUN = 0x0C; + public static final int LITE_SET_FG_FGBG_IMAGE = 0x0D; + public static final int LITE_DITHERED_RUN = 0x0E; + + public static final int MEGA_MEGA_BG_RUN = 0xF0; + public static final int MEGA_MEGA_FG_RUN = 0xF1; + public static final int MEGA_MEGA_FGBG_IMAGE = 0xF2; + public static final int MEGA_MEGA_COLOR_RUN = 0xF3; + public static final int MEGA_MEGA_COLOR_IMAGE = 0xF4; + public static final int MEGA_MEGA_SET_FG_RUN = 0xF6; + public static final int MEGA_MEGA_SET_FGBG_IMAGE = 0xF7; + public static final int MEGA_MEGA_DITHERED_RUN = 0xF8; + + public static final int SPECIAL_FGBG_1 = 0xF9; + public static final int SPECIAL_FGBG_2 = 0xFA; + + public static final int SPECIAL_WHITE = 0xFD; + public static final int SPECIAL_BLACK = 0xFE; + + /** + * Writes a pixel to the specified buffer and advance cursor by bpp. + * + * @param bpp + * bytes per pixel + */ + private static void writePixel(int bpp, ByteBuffer destBuf, int pixel) { + switch (bpp) { + case 1: + destBuf.writeByte(pixel); + break; + case 2: + destBuf.writeShortLE(pixel); + break; + case 3: + destBuf.writeByte(pixel); + destBuf.writeShortLE(pixel >> 8); + break; + case 4: + destBuf.writeIntLE(pixel); + break; + default: + throw new RuntimeException("Unsupported color depth."); + } + } + + /** + * Reads a pixel from the specified buffer at given offset without changing of + * cursor. + * + * @param bpp + * bytes per pixel + * @param offset + * -rowDelta (i.e. (-width*bpp)) + */ + private static int peekPixel(int bpp, ByteBuffer destBuf, int offset) { + if (offset >= 0 || (-offset) > destBuf.cursor) + throw new RuntimeException("Incorrect value for offset: offset in destination buffer must point to pixel in previous row."); + + // Adjust cursor to point to pixel in previous row + int oldCursor = destBuf.cursor; + destBuf.cursor += offset; + + int pixel; + switch (bpp) { + case 1: + pixel = destBuf.readUnsignedByte(); + break; + case 2: + pixel = destBuf.readUnsignedShortLE(); + break; + case 3: + pixel = destBuf.readUnsignedByte() | (destBuf.readUnsignedShortLE() >> 8); + break; + case 4: + pixel = destBuf.readSignedIntLE(); + break; + default: + throw new RuntimeException("Unsupported color depth."); + } + destBuf.cursor = oldCursor; + + return pixel; + } + + /** + * Reads a pixel from the specified buffer and advance cursor by bpp value. + * + * @param bpp + * bytes per pixel + */ + private static int readPixel(int bpp, ByteBuffer srcBuf) { + int pixel; + switch (bpp) { + case 1: + pixel = srcBuf.readUnsignedByte(); + break; + case 2: + pixel = srcBuf.readUnsignedShortLE(); + break; + case 3: + pixel = srcBuf.readUnsignedByte() | (srcBuf.readUnsignedShortLE() >> 8); + break; + case 4: + pixel = srcBuf.readSignedIntLE(); + break; + default: + throw new RuntimeException("Unsupported color depth."); + } + + return pixel; + } + + /** + * Returns the size of a pixel in bytes. + */ + private static int getPixelSize(int colorDepth) { + switch (colorDepth) { + case 8: + return 1; + case 15: + case 16: + return 2; + case 24: + return 3; + default: + throw new RuntimeException("Unsupported pixel color depth: " + colorDepth + " bpp."); + } + } + + /** + * Reads the supplied order header & extracts the compression order code ID. + */ + private static int extractCodeId(int orderHeader) { + // Taken from FreeRDP code, bitmap.c + switch (orderHeader) { + case MEGA_MEGA_BG_RUN: + case MEGA_MEGA_FG_RUN: + case MEGA_MEGA_SET_FG_RUN: + case MEGA_MEGA_DITHERED_RUN: + case MEGA_MEGA_COLOR_RUN: + case MEGA_MEGA_FGBG_IMAGE: + case MEGA_MEGA_SET_FGBG_IMAGE: + case MEGA_MEGA_COLOR_IMAGE: + case SPECIAL_FGBG_1: + case SPECIAL_FGBG_2: + case SPECIAL_WHITE: + case SPECIAL_BLACK: + return orderHeader; + } + + int code = orderHeader >> 5; + switch (code) { + case REGULAR_BG_RUN: + case REGULAR_FG_RUN: + case REGULAR_COLOR_RUN: + case REGULAR_FGBG_IMAGE: + case REGULAR_COLOR_IMAGE: + return code; + } + + return orderHeader >> 4; + } + + /** + * Returns a black pixel. + */ + private static int getColorBlack() { + return 0x000000; + } + + /** + * Returns a white pixel. + */ + private static int getColorWhite(int colorDepth) { + if (colorDepth == 8) { + // + // Palette entry #255 holds white. + // + return 0xFF; + } else if (colorDepth == 15) { + // + // 5 bits per RGB component: + // 0111 1111 1111 1111 (binary) + // + return 0x7FFF; + } else if (colorDepth == 16) { + // + // 5 bits for red, 6 bits for green, 5 bits for green: + // 1111 1111 1111 1111 (binary) + // + return 0xFFFF; + } else if (colorDepth == 24) { + // + // 8 bits per RGB component: + // 1111 1111 1111 1111 1111 1111 (binary) + // + return 0xFFFFFF; + } else + throw new RuntimeException("Unsupported color depth."); + } + + /** + * Extract the run length of a compression order. + */ + private static int extractRunLength(int code, int orderHeader, ByteBuffer srcBuf) { + switch (code) { + case REGULAR_FGBG_IMAGE: { + int runLength = orderHeader & g_MaskRegularRunLength; + if (runLength == 0) + runLength = srcBuf.readUnsignedByte() + 1; + else + runLength = runLength * 8; + return runLength; + } + case LITE_SET_FG_FGBG_IMAGE: { + int runLength = orderHeader & g_MaskLiteRunLength; + if (runLength == 0) + runLength = srcBuf.readUnsignedByte() + 1; + else + runLength = runLength * 8; + return runLength; + } + case REGULAR_BG_RUN: + case REGULAR_COLOR_IMAGE: + case REGULAR_COLOR_RUN: + case REGULAR_FG_RUN: { + int runLength = orderHeader & g_MaskRegularRunLength; + if (runLength == 0) + // An extended (MEGA) run. + runLength = srcBuf.readUnsignedByte() + 32; + return runLength; + } + case LITE_DITHERED_RUN: + case LITE_SET_FG_FG_RUN: { + int runLength = orderHeader & g_MaskLiteRunLength; + if (runLength == 0) + // An extended (MEGA) run. + runLength = srcBuf.readUnsignedByte() + 16; + return runLength; + } + case MEGA_MEGA_BG_RUN: + case MEGA_MEGA_COLOR_IMAGE: + case MEGA_MEGA_COLOR_RUN: + case MEGA_MEGA_DITHERED_RUN: + case MEGA_MEGA_FG_RUN: + case MEGA_MEGA_FGBG_IMAGE: + case MEGA_MEGA_SET_FG_RUN: + case MEGA_MEGA_SET_FGBG_IMAGE: { + return srcBuf.readUnsignedShortLE(); + } + default: + return 0; + } + + } + + /** + * Write a foreground/background image to a destination buffer. + */ + private static void writeFgBgImage(int bpp, ByteBuffer destBuf, int rowDelta, int bitmask, int fgPel, int cBits) { + for (; cBits > 0; cBits--, bitmask >>= 1) { + int xorPixel = peekPixel(bpp, destBuf, -rowDelta); + writePixel(bpp, destBuf, ((bitmask & 0x1) > 0) ? xorPixel ^ fgPel : xorPixel); + } + } + + /** + * Write a foreground/background image to a destination buffer for the first + * line of compressed data. + */ + private static void writeFirstLineFgBgImage(int bpp, ByteBuffer destBuf, int bitmask, int fgPel, int cBits) { + for (; cBits > 0; cBits--, bitmask >>= 1) { + writePixel(bpp, destBuf, ((bitmask & 0x1) > 0) ? fgPel : getColorBlack()); + } + } + + /** + * Decompress a RLE compressed bitmap and flip decompressed image. + * + * @param srcBuf + * source buffer containing compressed bitmap + * @param imageWidth + * width of destination image in pixels + * @param imageHeight + * height of destination image in pixels + * @param colorDepth + * bits per pixel + * @return destination image buffer + */ + public static ByteBuffer rleDecompress(ByteBuffer srcBuf, int imageWidth, int imageHeight, int colorDepth) { + int bpp = getPixelSize(colorDepth); + + // Decompress image + ByteBuffer destBuf = new ByteBuffer(new byte[imageWidth * imageHeight * bpp]); + rleDecompress(srcBuf, destBuf, imageWidth, imageHeight, colorDepth); + + // Flip image + return flipRawImage(destBuf, imageWidth, imageHeight, bpp); + } + + /** + * Decompress a RLE compressed bitmap. + * + * @param srcBuf + * source buffer containing compressed bitmap + * @param destBuf + * destination buffer + * @param imageWidth + * width of destination image in pixels + * @param imageHeight + * height of destination image in pixels + * @param colorDepth + * bits per pixel + */ + protected static void rleDecompress(final ByteBuffer srcBuf, final ByteBuffer destBuf, final int imageWidth, final int imageHeight, final int colorDepth) { + final int bpp = getPixelSize(colorDepth); + final int rowDelta = imageWidth * bpp; + final int whitePixel = getColorWhite(colorDepth); + final int blackPixel = getColorBlack(); + + int fgPel = whitePixel; + boolean insertFgPel = false; + boolean firstLine = true; + + if (destBuf.length != imageWidth * imageHeight * bpp) + throw new RuntimeException("Incorrect size of destination buffer. Expected size (imageWidth*imageHeight*bpp): " + (imageWidth * imageHeight * bpp) + + ", actual size: " + destBuf.length + "."); + + while (srcBuf.cursor < srcBuf.length) { + // Watch out for the end of the first scanline in destination buffer. + if (firstLine) { + if (destBuf.cursor >= rowDelta) { + firstLine = false; + insertFgPel = false; + } + } + + // Extract the compression order code ID from the compression + // order header. + int orderHeader = srcBuf.readUnsignedByte(); + int code = extractCodeId(orderHeader); + + // Handle Background Run Orders. + if (code == REGULAR_BG_RUN | code == MEGA_MEGA_BG_RUN) { + int runLength = extractRunLength(code, orderHeader, srcBuf); + + if (firstLine) { + if (insertFgPel) { + writePixel(bpp, destBuf, fgPel); + runLength--; + } + + for (; runLength > 0; runLength--) + writePixel(bpp, destBuf, blackPixel); + + } else { + if (insertFgPel) { + writePixel(bpp, destBuf, peekPixel(bpp, destBuf, -rowDelta) ^ fgPel); + runLength--; + } + + // Copy pixels from previous row of destination image + for (; runLength > 0; runLength--) + writePixel(bpp, destBuf, peekPixel(bpp, destBuf, -rowDelta)); + } + + // + // A follow-on background run order will need a + // foreground pel inserted. + // + insertFgPel = true; + continue; + } + + // + // For any of the other run-types a follow-on background run + // order does not need a foreground pel inserted. + // + insertFgPel = false; + + // + // Handle Foreground Run Orders. + // + if (code == REGULAR_FG_RUN | code == MEGA_MEGA_FG_RUN | code == LITE_SET_FG_FG_RUN | code == MEGA_MEGA_SET_FG_RUN) { + int runLength = extractRunLength(code, orderHeader, srcBuf); + + if (code == LITE_SET_FG_FG_RUN | code == MEGA_MEGA_SET_FG_RUN) + fgPel = readPixel(bpp, srcBuf); + + if (firstLine) { + for (; runLength > 0; runLength--) { + writePixel(bpp, destBuf, fgPel); + } + } else { + for (; runLength > 0; runLength--) { + writePixel(bpp, destBuf, peekPixel(bpp, destBuf, -rowDelta) ^ fgPel); + } + } + + continue; + } + + // + // Handle Dithered Run Orders. + // + if (code == LITE_DITHERED_RUN | code == MEGA_MEGA_DITHERED_RUN) { + int runLength = extractRunLength(code, orderHeader, srcBuf); + + int pixelA = readPixel(bpp, srcBuf); + int pixelB = readPixel(bpp, srcBuf); + + for (; runLength > 0; runLength--) { + writePixel(bpp, destBuf, pixelA); + writePixel(bpp, destBuf, pixelB); + } + + continue; + } + + // + // Handle Color Run Orders. + // + if (code == REGULAR_COLOR_RUN | code == MEGA_MEGA_COLOR_RUN) { + int runLength = extractRunLength(code, orderHeader, srcBuf); + + int pixelA = readPixel(bpp, srcBuf); + + for (; runLength > 0; runLength--) + writePixel(bpp, destBuf, pixelA); + + continue; + } + + // + // Handle Foreground/Background Image Orders. + // + if (code == REGULAR_FGBG_IMAGE | code == MEGA_MEGA_FGBG_IMAGE | code == LITE_SET_FG_FGBG_IMAGE | code == MEGA_MEGA_SET_FGBG_IMAGE) { + int runLength = extractRunLength(code, orderHeader, srcBuf); + + if (code == LITE_SET_FG_FGBG_IMAGE | code == MEGA_MEGA_SET_FGBG_IMAGE) { + fgPel = readPixel(bpp, srcBuf); + } + + for (; runLength > 8; runLength -= 8) { + int bitmask = srcBuf.readUnsignedByte(); + + if (firstLine) + writeFirstLineFgBgImage(bpp, destBuf, bitmask, fgPel, 8); + else + writeFgBgImage(bpp, destBuf, rowDelta, bitmask, fgPel, 8); + } + + if (runLength > 0) { + int bitmask = srcBuf.readUnsignedByte(); + + if (firstLine) + writeFirstLineFgBgImage(bpp, destBuf, bitmask, fgPel, runLength); + else + writeFgBgImage(bpp, destBuf, rowDelta, bitmask, fgPel, runLength); + } + + continue; + } + + // + // Handle Color Image Orders. + // + if (code == REGULAR_COLOR_IMAGE | code == MEGA_MEGA_COLOR_IMAGE) { + int runLength = extractRunLength(code, orderHeader, srcBuf); + + //* DEBUG */ + // Copy bytes from source to destination using writeByte(readByte()) + // for (int byteCount = runLength * bpp; byteCount > 0; byteCount--) { + // destBuf.writeByte(srcBuf.readUnsignedByte()); + // } + //* DEBUG */ + + // Copy bytes from source to destination directly using arraycopy() + int lengthInBytes = runLength * bpp; + System.arraycopy(srcBuf.data, srcBuf.offset + srcBuf.cursor, destBuf.data, destBuf.offset + destBuf.cursor, lengthInBytes); + srcBuf.cursor += lengthInBytes; + destBuf.cursor += lengthInBytes; + + continue; + } + + // + // Handle Special Order 1. + // + if (code == SPECIAL_FGBG_1) { + if (firstLine) + writeFirstLineFgBgImage(bpp, destBuf, g_MaskSpecialFgBg1, fgPel, 8); + else + writeFgBgImage(bpp, destBuf, rowDelta, g_MaskSpecialFgBg1, fgPel, 8); + + continue; + } + + // + // Handle Special Order 2. + // + if (code == SPECIAL_FGBG_2) { + if (firstLine) + writeFirstLineFgBgImage(bpp, destBuf, g_MaskSpecialFgBg2, fgPel, 8); + else + writeFgBgImage(bpp, destBuf, rowDelta, g_MaskSpecialFgBg2, fgPel, 8); + + continue; + } + + // + // Handle White Order. + // + if (code == SPECIAL_WHITE) { + writePixel(bpp, destBuf, whitePixel); + + continue; + } + + // + // Handle Black Order. + // + if (code == SPECIAL_BLACK) { + writePixel(bpp, destBuf, blackPixel); + + continue; + } + + throw new RuntimeException("Unknown code: " + code + "."); + } + } + + /** + * Flip image in vertical direction. + */ + public static ByteBuffer flipRawImage(ByteBuffer src, int width, int height, int bpp) { + if (width * height * bpp != src.length) + throw new RuntimeException("Incorrect size of buffer. Expected size (imageWidth*imageHeight*bpp): " + (width * height * bpp) + ", actual size: " + + src.length + "."); + ByteBuffer dest = new ByteBuffer(new byte[src.length]); + + int scanLine = width * bpp; + + for (int i = 0; i < height; i++) { + // Copy one row + System.arraycopy(src.data, (height - i - 1) * scanLine, dest.data, i * scanLine, scanLine); + } + + return dest; + + } + + /** + * Example. + */ + public static void main(String args[]) { + + if (true) { + // 16x1@8bpp, all black + int width = 16, height = 1, depth = 8, bpp = depth / 8; + ByteBuffer src = new ByteBuffer(new byte[] {0x10}); + ByteBuffer dest = new AssertingByteBuffer(new byte[width * height * bpp]); + rleDecompress(src, dest, width, height, depth); + } + + if (true) { + // 16x1@16bpp, all black + int width = 16, height = 1, depth = 16, bpp = depth / 8; + ByteBuffer src = new ByteBuffer(new byte[] {0x0c, (byte)0x84, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}); + ByteBuffer dest = new AssertingByteBuffer(new byte[width * height * bpp]); + rleDecompress(src, dest, width, height, depth); + } + + if (true) { + // 32x32@8 + int width = 32, height = 32, depth = 8, bpp = depth / 8; + + ByteBuffer src = new ByteBuffer(new byte[] {(byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x80, (byte)0x00, (byte)0x06, (byte)0x06, + (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0xec, (byte)0x6c, (byte)0x0e, + (byte)0x0e, (byte)0x44, (byte)0x0e, (byte)0x0e, (byte)0x0e, (byte)0x13, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, + (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0xe4, (byte)0x04, (byte)0x06, + (byte)0x8e, (byte)0x60, (byte)0x0e, (byte)0x60, (byte)0x8c, (byte)0xb4, (byte)0xb5, (byte)0xdc, (byte)0xdc, (byte)0xbb, (byte)0xb4, + (byte)0x8c, (byte)0x66, (byte)0x0b, (byte)0x6c, (byte)0xe4, (byte)0x04, (byte)0x06, (byte)0x02, (byte)0x8b, (byte)0x06, (byte)0x06, + (byte)0xed, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0xf8, (byte)0x0e, (byte)0x66, (byte)0xb4, (byte)0xdc, (byte)0x68, (byte)0xe2, + (byte)0x97, (byte)0xdd, (byte)0xb4, (byte)0xa7, (byte)0x16, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0xed, + (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x06, (byte)0x0b, (byte)0xae, + (byte)0xdc, (byte)0xe9, (byte)0x6a, (byte)0xdc, (byte)0x96, (byte)0xe9, (byte)0xe9, (byte)0xb4, (byte)0x0e, (byte)0x00, (byte)0x06, + (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x06, + (byte)0x0e, (byte)0xae, (byte)0xdc, (byte)0xdb, (byte)0xdb, (byte)0xd0, (byte)0x09, (byte)0x07, (byte)0xcf, (byte)0x03, (byte)0x95, + (byte)0xdb, (byte)0xdb, (byte)0xdc, (byte)0xb4, (byte)0x66, (byte)0x6c, (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0x00, + (byte)0x00, (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x0b, (byte)0xae, (byte)0xdb, (byte)0xd4, (byte)0xd5, (byte)0x6c, + (byte)0xdb, (byte)0x80, (byte)0xaf, (byte)0xd5, (byte)0xd4, (byte)0xdb, (byte)0xb4, (byte)0x66, (byte)0x04, (byte)0x06, (byte)0x04, + (byte)0x06, (byte)0x00, (byte)0x00, (byte)0xed, (byte)0x06, (byte)0xed, (byte)0x66, (byte)0xae, (byte)0xd5, (byte)0xad, (byte)0xd4, + (byte)0xd4, (byte)0xd5, (byte)0xd5, (byte)0xd5, (byte)0xdb, (byte)0xb4, (byte)0xb4, (byte)0xb4, (byte)0xb4, (byte)0xb4, (byte)0xd5, + (byte)0xd5, (byte)0xd5, (byte)0xd4, (byte)0xd4, (byte)0xad, (byte)0xd5, (byte)0xb4, (byte)0x0e, (byte)0x06, (byte)0x06, (byte)0x06, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x60, (byte)0xa7, (byte)0xb4, (byte)0xad, (byte)0xad, (byte)0xad, (byte)0xb3, + (byte)0xb3, (byte)0xd4, (byte)0xd4, (byte)0xb3, (byte)0x8c, (byte)0xb6, (byte)0x07, (byte)0xb6, (byte)0x8c, (byte)0xb3, (byte)0xd4, + (byte)0xb3, (byte)0xb3, (byte)0xad, (byte)0xad, (byte)0xad, (byte)0xb4, (byte)0xad, (byte)0x66, (byte)0x00, (byte)0x06, (byte)0x00, + (byte)0x00, (byte)0x06, (byte)0x06, (byte)0x66, (byte)0xae, (byte)0xad, (byte)0x8b, (byte)0xad, (byte)0xad, (byte)0xad, (byte)0xad, + (byte)0xad, (byte)0xb3, (byte)0xad, (byte)0xb5, (byte)0x07, (byte)0x07, (byte)0x07, (byte)0xf0, (byte)0x8b, (byte)0xad, (byte)0xad, + (byte)0xad, (byte)0xad, (byte)0xad, (byte)0x8b, (byte)0xa7, (byte)0xae, (byte)0xa7, (byte)0x6c, (byte)0x06, (byte)0x00, (byte)0x00, + (byte)0x04, (byte)0x6c, (byte)0xa7, (byte)0xad, (byte)0xa7, (byte)0xa7, (byte)0x8b, (byte)0xad, (byte)0xad, (byte)0xad, (byte)0xad, + (byte)0xad, (byte)0xad, (byte)0xb5, (byte)0xbd, (byte)0xbd, (byte)0xbd, (byte)0xbd, (byte)0xf0, (byte)0x8b, (byte)0x8b, (byte)0xad, + (byte)0x8b, (byte)0x8b, (byte)0xa7, (byte)0xa7, (byte)0xc8, (byte)0xc8, (byte)0x60, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x06, + (byte)0x66, (byte)0xc8, (byte)0xa7, (byte)0x66, (byte)0xa7, (byte)0xa7, (byte)0x8b, (byte)0x8b, (byte)0x8b, (byte)0x8b, (byte)0xad, + (byte)0x8b, (byte)0x92, (byte)0xf1, (byte)0xf1, (byte)0xf1, (byte)0xf1, (byte)0xf2, (byte)0x07, (byte)0xa7, (byte)0xa7, (byte)0x8b, + (byte)0xa7, (byte)0xa7, (byte)0x66, (byte)0x66, (byte)0xc8, (byte)0x66, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x60, + (byte)0xa7, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0xa7, (byte)0xa7, (byte)0xa7, (byte)0xa7, (byte)0x8b, (byte)0x8b, (byte)0x8b, + (byte)0xa7, (byte)0xb6, (byte)0xf3, (byte)0xf3, (byte)0xf3, (byte)0xf3, (byte)0xf3, (byte)0x07, (byte)0x66, (byte)0xa7, (byte)0xa7, + (byte)0x66, (byte)0x66, (byte)0x66, (byte)0xa7, (byte)0xa7, (byte)0x6c, (byte)0x00, (byte)0x00, (byte)0x6c, (byte)0x04, (byte)0xa7, + (byte)0x60, (byte)0x6b, (byte)0x66, (byte)0x99, (byte)0xb6, (byte)0xf5, (byte)0xf5, (byte)0xf5, (byte)0xf5, (byte)0xf5, (byte)0xef, + (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0xa7, (byte)0x66, (byte)0x00, (byte)0x00, (byte)0x60, + (byte)0xa7, (byte)0x66, (byte)0x60, (byte)0x66, (byte)0x66, (byte)0x8c, (byte)0xf1, (byte)0x6e, (byte)0xff, (byte)0x85, (byte)0xbd, + (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x60, (byte)0x05, (byte)0x87, (byte)0x13, (byte)0x04, (byte)0x66, (byte)0x66, (byte)0x66, + (byte)0x66, (byte)0xf4, (byte)0x70, (byte)0xff, (byte)0x84, (byte)0xbd, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x05, (byte)0x85, + (byte)0x0b, (byte)0xa7, (byte)0xb5, (byte)0xae, (byte)0x8c, (byte)0xd0, (byte)0x13, (byte)0xc1, (byte)0x01, (byte)0x00, (byte)0x08, + (byte)0x8e, (byte)0x8c, (byte)0xae, (byte)0xb5, (byte)0xae, (byte)0x66, (byte)0x00, (byte)0x00, (byte)0x6c, (byte)0xae, (byte)0xbc, + (byte)0xb5, (byte)0xb5, (byte)0xae, (byte)0xb5, (byte)0xd0, (byte)0x0e, (byte)0x0c, (byte)0x01, (byte)0x00, (byte)0x90, (byte)0xf2, + (byte)0xae, (byte)0xae, (byte)0xb5, (byte)0xb5, (byte)0xbc, (byte)0xb5, (byte)0x66, (byte)0x00, (byte)0x00, (byte)0x04, (byte)0xae, + (byte)0x0a, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0x68, (byte)0xae, (byte)0x82, (byte)0x8c, (byte)0x0a, (byte)0x05, (byte)0x8c, + (byte)0xf2, (byte)0xae, (byte)0xae, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xbc, (byte)0xb5, (byte)0x6c, (byte)0x00, (byte)0x00, + (byte)0x06, (byte)0x05, (byte)0x81, (byte)0xd0, (byte)0x06, (byte)0x9a, (byte)0x8c, (byte)0x0a, (byte)0xff, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0xf2, (byte)0xae, (byte)0xae, (byte)0xd0, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0x0a, (byte)0xb5, + (byte)0x6c, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x8b, (byte)0x0a, (byte)0xbc, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0x06, + (byte)0x9b, (byte)0xb6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xf2, (byte)0xae, (byte)0xae, (byte)0xae, + (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb6, (byte)0x0a, (byte)0x8c, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x6c, + (byte)0xb5, (byte)0x0a, (byte)0xb6, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0x05, (byte)0x80, (byte)0x7d, (byte)0xbc, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xf2, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb6, + (byte)0x0a, (byte)0x0a, (byte)0x8b, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x04, (byte)0x06, (byte)0x87, (byte)0x0a, (byte)0xbc, + (byte)0xb6, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xd0, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xb6, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0xf2, (byte)0xd0, (byte)0xae, (byte)0xd0, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb6, (byte)0xbc, (byte)0x1a, + (byte)0xb5, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0xed, (byte)0x06, (byte)0x6e, (byte)0xb5, (byte)0x0a, (byte)0xbc, + (byte)0xb6, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xd0, (byte)0xd0, (byte)0xd0, (byte)0xb5, (byte)0xf4, (byte)0xff, (byte)0xf2, + (byte)0xd0, (byte)0xd0, (byte)0xd0, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb6, (byte)0xbc, (byte)0x0a, (byte)0x0a, (byte)0x8b, + (byte)0x06, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x04, (byte)0x8b, (byte)0xbc, (byte)0x1a, (byte)0x0a, + (byte)0xb6, (byte)0xb6, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xd0, (byte)0xb5, (byte)0xb5, (byte)0xb5, + (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb6, (byte)0xb6, (byte)0x0a, (byte)0xde, (byte)0x0a, (byte)0xa7, (byte)0x06, (byte)0x00, + (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x8b, (byte)0xbc, (byte)0xf2, (byte)0x0a, + (byte)0xb6, (byte)0xb6, (byte)0xb6, (byte)0xb6, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb6, + (byte)0xb6, (byte)0xb6, (byte)0xb6, (byte)0x0a, (byte)0xf2, (byte)0x1a, (byte)0x8c, (byte)0xec, (byte)0x06, (byte)0x06, (byte)0x06, + (byte)0x00, (byte)0x00, (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x04, (byte)0xa7, (byte)0xbc, (byte)0x1a, (byte)0x0a, + (byte)0x0a, (byte)0x6a, (byte)0xb6, (byte)0x96, (byte)0x0a, (byte)0x0a, (byte)0xf2, (byte)0x0a, (byte)0x87, (byte)0x06, (byte)0x04, + (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0xed, (byte)0x06, + (byte)0x8c, (byte)0xb6, (byte)0xf4, (byte)0xf2, (byte)0xd0, (byte)0x09, (byte)0xbc, (byte)0x87, (byte)0x03, (byte)0x80, (byte)0x2c, + (byte)0xde, (byte)0xf4, (byte)0x0a, (byte)0x8b, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x06, (byte)0x04, (byte)0x6c, (byte)0x87, (byte)0x0a, + (byte)0xf4, (byte)0xf4, (byte)0xf2, (byte)0xde, (byte)0xbd, (byte)0xbd, (byte)0xde, (byte)0xf2, (byte)0xf4, (byte)0xf4, (byte)0x0a, + (byte)0xd0, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x06, (byte)0x00, (byte)0x00, + (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x6c, (byte)0x8c, + (byte)0xb5, (byte)0xbc, (byte)0x0a, (byte)0xde, (byte)0xf2, (byte)0xbd, (byte)0x0a, (byte)0xb5, (byte)0x8c, (byte)0x6c, (byte)0x06, + (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0xe6, + (byte)0x04, (byte)0x06, (byte)0x86, (byte)0x04, (byte)0x6c, (byte)0x04, (byte)0x8b, (byte)0x04, (byte)0x6c, (byte)0xe6, (byte)0x04, + (byte)0x06, (byte)0x82, (byte)0x00, (byte)0x00 + + }); + + ByteBuffer flippedImage = new ByteBuffer(new byte[] {(byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x04, + (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x6c, (byte)0x04, (byte)0x8b, (byte)0x04, (byte)0x6c, + (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x04, + (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, + (byte)0x06, (byte)0x6c, (byte)0x8c, (byte)0xb5, (byte)0xbc, (byte)0x0a, (byte)0xde, (byte)0xf2, (byte)0xbd, (byte)0x0a, (byte)0xb5, + (byte)0x8c, (byte)0x6c, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x06, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x06, (byte)0x04, (byte)0x6c, (byte)0x87, + (byte)0x0a, (byte)0xf4, (byte)0xf4, (byte)0xf2, (byte)0xde, (byte)0xbd, (byte)0xbd, (byte)0xde, (byte)0xf2, (byte)0xf4, (byte)0xf4, + (byte)0x0a, (byte)0xd0, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x06, (byte)0x00, + (byte)0x00, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x8c, (byte)0xb6, (byte)0xf4, (byte)0xf2, + (byte)0x0a, (byte)0x0a, (byte)0x0a, (byte)0xb6, (byte)0xb6, (byte)0xb6, (byte)0xb6, (byte)0x0a, (byte)0x0a, (byte)0x0a, (byte)0xde, + (byte)0xf4, (byte)0x0a, (byte)0x8b, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x00, (byte)0x00, + (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x04, (byte)0xa7, (byte)0xbc, (byte)0x1a, (byte)0x0a, (byte)0x0a, (byte)0xb6, + (byte)0xb6, (byte)0xb6, (byte)0xb6, (byte)0xb6, (byte)0xb6, (byte)0xb6, (byte)0xb6, (byte)0xb6, (byte)0xb6, (byte)0x0a, (byte)0x0a, + (byte)0xf2, (byte)0x0a, (byte)0x87, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x06, + (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x8b, (byte)0xbc, (byte)0xf2, (byte)0x0a, (byte)0xb6, (byte)0xb6, (byte)0xb6, (byte)0xb6, + (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb6, (byte)0xb6, (byte)0xb6, (byte)0xb6, (byte)0x0a, + (byte)0xf2, (byte)0x1a, (byte)0x8c, (byte)0xec, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x06, + (byte)0x04, (byte)0x8b, (byte)0xbc, (byte)0x1a, (byte)0x0a, (byte)0xb6, (byte)0xb6, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb5, + (byte)0xb5, (byte)0xd0, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb6, (byte)0xb6, (byte)0x0a, + (byte)0xde, (byte)0x0a, (byte)0xa7, (byte)0x06, (byte)0x00, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0xed, (byte)0x06, (byte)0x6e, + (byte)0xb5, (byte)0x0a, (byte)0xbc, (byte)0xb6, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xd0, (byte)0xd0, (byte)0xd0, (byte)0xb5, + (byte)0xf4, (byte)0xff, (byte)0xf2, (byte)0xd0, (byte)0xd0, (byte)0xd0, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb6, (byte)0xbc, + (byte)0x0a, (byte)0x0a, (byte)0x8b, (byte)0x06, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x04, (byte)0x06, (byte)0x87, (byte)0x0a, + (byte)0xbc, (byte)0xb6, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xd0, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xb6, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0xf2, (byte)0xd0, (byte)0xae, (byte)0xd0, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb6, (byte)0xbc, + (byte)0x1a, (byte)0xb5, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x6c, (byte)0xb5, (byte)0x0a, (byte)0xb6, + (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xbc, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0xf2, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb6, (byte)0x0a, + (byte)0x0a, (byte)0x8b, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x8b, (byte)0x0a, (byte)0xbc, (byte)0xb5, (byte)0xb5, + (byte)0xb5, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xb6, (byte)0xff, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0xf2, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xb6, (byte)0x0a, + (byte)0x8c, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0xae, (byte)0x0a, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xd0, + (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0x8c, (byte)0x0a, (byte)0xff, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0xf2, (byte)0xae, (byte)0xae, (byte)0xd0, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0x0a, (byte)0xb5, + (byte)0x6c, (byte)0x00, (byte)0x00, (byte)0x04, (byte)0xae, (byte)0x0a, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xae, (byte)0xae, + (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0xae, (byte)0x8c, (byte)0x0a, (byte)0xff, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0xf2, (byte)0xae, (byte)0xae, (byte)0xb5, (byte)0xb5, (byte)0xb5, (byte)0xbc, (byte)0xb5, (byte)0x6c, + (byte)0x00, (byte)0x00, (byte)0x6c, (byte)0xae, (byte)0xbc, (byte)0xb5, (byte)0xb5, (byte)0xae, (byte)0xb5, (byte)0xf3, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0xf2, (byte)0xae, (byte)0xae, (byte)0xb5, (byte)0xb5, (byte)0xbc, (byte)0xb5, (byte)0x66, (byte)0x00, + (byte)0x00, (byte)0x0b, (byte)0xa7, (byte)0xb5, (byte)0xae, (byte)0x8c, (byte)0xa7, (byte)0xf4, (byte)0xff, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0xbd, (byte)0xa7, (byte)0x8c, (byte)0xae, (byte)0xb5, (byte)0xae, (byte)0x66, (byte)0x00, (byte)0x00, + (byte)0x13, (byte)0x04, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0xf4, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0xbd, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0xa7, (byte)0x66, (byte)0x00, (byte)0x00, (byte)0x60, + (byte)0xa7, (byte)0x66, (byte)0x60, (byte)0x66, (byte)0x66, (byte)0x8c, (byte)0xf1, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xbd, + (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x60, (byte)0x66, (byte)0xa7, (byte)0x66, (byte)0x00, (byte)0x00, (byte)0x6c, (byte)0x04, + (byte)0xa7, (byte)0x60, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x66, + (byte)0x66, (byte)0x66, (byte)0xb6, (byte)0xf5, (byte)0xf5, (byte)0xf5, (byte)0xf5, (byte)0xf5, (byte)0xef, (byte)0x66, (byte)0x66, + (byte)0x66, (byte)0x66, (byte)0x66, (byte)0x66, (byte)0xa7, (byte)0x66, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x60, (byte)0xa7, + (byte)0x66, (byte)0x66, (byte)0x66, (byte)0xa7, (byte)0xa7, (byte)0xa7, (byte)0xa7, (byte)0x8b, (byte)0x8b, (byte)0x8b, (byte)0xa7, + (byte)0xb6, (byte)0xf3, (byte)0xf3, (byte)0xf3, (byte)0xf3, (byte)0xf3, (byte)0x07, (byte)0x66, (byte)0xa7, (byte)0xa7, (byte)0x66, + (byte)0x66, (byte)0x66, (byte)0xa7, (byte)0xa7, (byte)0x6c, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x66, (byte)0xc8, (byte)0xa7, + (byte)0x66, (byte)0xa7, (byte)0xa7, (byte)0x8b, (byte)0x8b, (byte)0x8b, (byte)0x8b, (byte)0xad, (byte)0x8b, (byte)0x92, (byte)0xf1, + (byte)0xf1, (byte)0xf1, (byte)0xf1, (byte)0xf2, (byte)0x07, (byte)0xa7, (byte)0xa7, (byte)0x8b, (byte)0xa7, (byte)0xa7, (byte)0x66, + (byte)0x66, (byte)0xc8, (byte)0x66, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x04, (byte)0x6c, (byte)0xa7, (byte)0xad, (byte)0xa7, + (byte)0xa7, (byte)0x8b, (byte)0xad, (byte)0xad, (byte)0xad, (byte)0xad, (byte)0xad, (byte)0xad, (byte)0xb5, (byte)0xbd, (byte)0xbd, + (byte)0xbd, (byte)0xbd, (byte)0xf0, (byte)0x8b, (byte)0x8b, (byte)0xad, (byte)0x8b, (byte)0x8b, (byte)0xa7, (byte)0xa7, (byte)0xc8, + (byte)0xc8, (byte)0x60, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x06, (byte)0x66, (byte)0xae, (byte)0xad, (byte)0x8b, + (byte)0xad, (byte)0xad, (byte)0xad, (byte)0xad, (byte)0xad, (byte)0xb3, (byte)0xad, (byte)0xb5, (byte)0x07, (byte)0x07, (byte)0x07, + (byte)0xf0, (byte)0x8b, (byte)0xad, (byte)0xad, (byte)0xad, (byte)0xad, (byte)0xad, (byte)0x8b, (byte)0xa7, (byte)0xae, (byte)0xa7, + (byte)0x6c, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x60, (byte)0xa7, (byte)0xb4, (byte)0xad, (byte)0xad, + (byte)0xad, (byte)0xb3, (byte)0xb3, (byte)0xd4, (byte)0xd4, (byte)0xb3, (byte)0x8c, (byte)0xb6, (byte)0x07, (byte)0xb6, (byte)0x8c, + (byte)0xb3, (byte)0xd4, (byte)0xb3, (byte)0xb3, (byte)0xad, (byte)0xad, (byte)0xad, (byte)0xb4, (byte)0xad, (byte)0x66, (byte)0x00, + (byte)0x06, (byte)0x00, (byte)0x00, (byte)0xed, (byte)0x06, (byte)0xed, (byte)0x66, (byte)0xae, (byte)0xd5, (byte)0xad, (byte)0xd4, + (byte)0xd4, (byte)0xd5, (byte)0xd5, (byte)0xd5, (byte)0xdb, (byte)0xb4, (byte)0xb4, (byte)0xb4, (byte)0xb4, (byte)0xb4, (byte)0xd5, + (byte)0xd5, (byte)0xd5, (byte)0xd4, (byte)0xd4, (byte)0xad, (byte)0xd5, (byte)0xb4, (byte)0x0e, (byte)0x06, (byte)0x06, (byte)0x06, + (byte)0x00, (byte)0x00, (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x0b, (byte)0xae, (byte)0xdb, (byte)0xd4, (byte)0xd5, + (byte)0xdb, (byte)0xdb, (byte)0xdb, (byte)0xdb, (byte)0xdb, (byte)0xdb, (byte)0xdb, (byte)0xdb, (byte)0xdb, (byte)0xdb, (byte)0xdb, + (byte)0xdb, (byte)0xd5, (byte)0xd4, (byte)0xdb, (byte)0xb4, (byte)0x66, (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x00, + (byte)0x00, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x0e, (byte)0xae, (byte)0xdc, (byte)0xdb, (byte)0xdb, + (byte)0xdb, (byte)0xdb, (byte)0xdb, (byte)0xdb, (byte)0xdc, (byte)0xdc, (byte)0xdb, (byte)0xdb, (byte)0xdb, (byte)0xdb, (byte)0xdb, + (byte)0xdb, (byte)0xdc, (byte)0xb4, (byte)0x66, (byte)0x6c, (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x06, (byte)0x0b, (byte)0xae, (byte)0xdc, (byte)0xe9, (byte)0xdc, + (byte)0xdc, (byte)0xdc, (byte)0xdc, (byte)0xdc, (byte)0xdc, (byte)0xdc, (byte)0xdc, (byte)0xdc, (byte)0xdc, (byte)0xe9, (byte)0xe9, + (byte)0xb4, (byte)0x0e, (byte)0x00, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x06, + (byte)0x06, (byte)0xed, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0xf8, (byte)0x0e, (byte)0x66, (byte)0xb4, (byte)0xdc, (byte)0xe2, + (byte)0xe2, (byte)0xe2, (byte)0xe2, (byte)0xe2, (byte)0xe2, (byte)0xe2, (byte)0xe2, (byte)0xdd, (byte)0xb4, (byte)0xa7, (byte)0x16, + (byte)0x06, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x04, (byte)0x06, + (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x60, (byte)0x0e, (byte)0x60, (byte)0x8c, (byte)0xb4, + (byte)0xb5, (byte)0xdc, (byte)0xdc, (byte)0xbb, (byte)0xb4, (byte)0x8c, (byte)0x66, (byte)0x0b, (byte)0x6c, (byte)0x04, (byte)0x06, + (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x04, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x06, (byte)0xed, + (byte)0x06, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0xec, (byte)0x6c, (byte)0x0e, (byte)0x0e, + (byte)0x44, (byte)0x0e, (byte)0x0e, (byte)0x0e, (byte)0x13, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x06, + (byte)0x06, (byte)0xed, (byte)0x06, (byte)0x06, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00}); + ByteBuffer dest = new AssertingByteBuffer(flipRawImage(flippedImage, width, height, bpp).data); + + rleDecompress(src, dest, width, height, depth); + + } + + if (true) { + // 32x32@16 + int width = 32, height = 32, depth = 16; + + ByteBuffer src = new ByteBuffer(new byte[] {(byte)0x85, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x06, (byte)0x8b, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x06, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0x16, (byte)0x69, (byte)0x99, (byte)0xd6, (byte)0x06, (byte)0x69, (byte)0x99, + (byte)0xd6, (byte)0x04, (byte)0xcc, (byte)0x89, (byte)0x52, (byte)0x03, (byte)0x6e, (byte)0xff, (byte)0xff, (byte)0x02, (byte)0x6e, + (byte)0x08, (byte)0x42, (byte)0x01, (byte)0x70, (byte)0x08, (byte)0x42, (byte)0x71, (byte)0xff, (byte)0xff, (byte)0xce, (byte)0x18, + (byte)0xc6, (byte)0x01, (byte)0x81, (byte)0x08, (byte)0x42, (byte)0xce, (byte)0x66, (byte)0x29, (byte)0x02, (byte)0xcd, (byte)0x89, + (byte)0x52, (byte)0x03, (byte)0x88, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xd8, (byte)0x99, (byte)0xd6, + (byte)0x03, (byte)0xf8, (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xf0, (byte)0x66, (byte)0x99, (byte)0xd6, + (byte)0x05, (byte)0x6a, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0xc4, (byte)0xcc, (byte)0x89, (byte)0x52, (byte)0x03, (byte)0x6e, + (byte)0xff, (byte)0xff, (byte)0x02, (byte)0x6e, (byte)0x08, (byte)0x42, (byte)0x01, (byte)0x70, (byte)0x08, (byte)0x42, (byte)0x71, + (byte)0xff, (byte)0xff, (byte)0xce, (byte)0x18, (byte)0xc6, (byte)0x01, (byte)0x81, (byte)0x08, (byte)0x42, (byte)0xce, (byte)0x66, + (byte)0x29, (byte)0x02, (byte)0xcd, (byte)0x89, (byte)0x52, (byte)0x03, (byte)0x00, (byte)0x04, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0xc3, (byte)0x80, (byte)0x61, (byte)0x00, (byte)0xa5, (byte)0x80, (byte)0x40, (byte)0xec, (byte)0x52, (byte)0x00, (byte)0x5a, + (byte)0x00, (byte)0x2d, (byte)0x00, (byte)0x24, (byte)0x00, (byte)0x12, (byte)0x00, (byte)0x24, (byte)0x00, (byte)0x12, (byte)0x00, + (byte)0x5a, (byte)0x00, (byte)0x2d, (byte)0x00, (byte)0xa5, (byte)0x80, (byte)0x52, (byte)0x00, (byte)0xc3, (byte)0x80, (byte)0x61, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xcc, (byte)0x89, (byte)0x52, (byte)0x03, (byte)0x6e, (byte)0xff, + (byte)0xff, (byte)0x02, (byte)0xcb, (byte)0x18, (byte)0xc6, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, + (byte)0x42, (byte)0xff, (byte)0xff,}); + + ByteBuffer dest = new AssertingByteBuffer(new byte[] {(byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, + (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, + (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, + (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, + (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, + (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, + (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, + (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, + (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0xff, (byte)0xff, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, + (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, + (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, + (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, + (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, + (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, + (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, + (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, + (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, + (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, + (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, + (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, + (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, + (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, + (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, + (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x99, + (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, + (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, + (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, + (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0xff, + (byte)0xff, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, + (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, + (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, + (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, + (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, + (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, + (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, + (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, + (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, + (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, + (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, + (byte)0x08, (byte)0x42, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, + (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, + (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x99, (byte)0xd6, (byte)0x10, (byte)0x84, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, + (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, + (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, + (byte)0x10, (byte)0x84, (byte)0x10, (byte)0x84, (byte)0x99, (byte)0xd6, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, + (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, + (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, + (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, + (byte)0x08, (byte)0x42, (byte)0x08, (byte)0x42, (byte)0xff, (byte)0xff,}); + + rleDecompress(src, dest, width, height, depth); + + } + } +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/RdpConstants.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/RdpConstants.java old mode 100644 new mode 100755 similarity index 86% rename from services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/RdpConstants.java rename to services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/RdpConstants.java index 3da132815c5..147d0a72bad --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/RdpConstants.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/RdpConstants.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package rdpclient; +package rdpclient.rdp; import java.nio.charset.Charset; @@ -63,8 +63,29 @@ public interface RdpConstants { */ public static final int RDP_NEG_REQ_TYPE_NEG_FAILURE = 3; + /** + * I/O Channel. + */ public static final int CHANNEL_IO = 1003; + /** + * RDP channel. + */ public static final int CHANNEL_RDPRDR = 1004; + /** + * Clipboard channel. + */ + public static final int CHANNEL_CLIPRDR = 1005; + + /** + * RDP sound channel. + */ + public static final int CHANNEL_RDPSND = 1006; + + /** + * User channel. + */ + public static final int CHANNEL_USER = 1007; + } diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/RdpState.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/RdpState.java old mode 100644 new mode 100755 similarity index 97% rename from services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/RdpState.java rename to services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/RdpState.java index 951f0be8e98..1113d149452 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/RdpState.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/RdpState.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package rdpclient; +package rdpclient.rdp; import java.util.HashSet; import java.util.Set; diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerBitmapUpdate.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerBitmapUpdate.java old mode 100644 new mode 100755 similarity index 94% rename from services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerBitmapUpdate.java rename to services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerBitmapUpdate.java index 5c30b69dbac..6accc162f0b --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerBitmapUpdate.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerBitmapUpdate.java @@ -14,15 +14,15 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package rdpclient; +package rdpclient.rdp; import streamer.BaseElement; import streamer.ByteBuffer; import streamer.Element; -import streamer.FakeSink; import streamer.Link; import streamer.Pipeline; import streamer.PipelineImpl; +import streamer.debug.FakeSink; import common.BitmapOrder; import common.BitmapRectangle; @@ -62,7 +62,8 @@ public class ServerBitmapUpdate extends BaseElement { // be set to UPDATETYPE_BITMAP (0x0001). int updateType = buf.readSignedShortLE(); if (updateType != UPDATETYPE_BITMAP) - throw new RuntimeException("Unknown update type. Expected update type: UPDATETYPE_BITMAP (0x1). Actual update type: " + updateType + ", buf: " + buf + "."); + throw new RuntimeException("Unknown update type. Expected update type: UPDATETYPE_BITMAP (0x1). Actual update type: " + updateType + ", buf: " + buf + + "."); // (2 bytes): A 16-bit, unsigned integer. The number of screen rectangles // present in the rectangles field. @@ -80,8 +81,7 @@ public class ServerBitmapUpdate extends BaseElement { buf.assertThatBufferIsFullyRead(); - ByteBuffer data = new ByteBuffer(0); - data.setOrder(order); + ByteBuffer data = new ByteBuffer(order); pushDataToAllOuts(data); buf.unref(); @@ -172,9 +172,8 @@ public class ServerBitmapUpdate extends BaseElement { * Example. */ public static void main(String args[]) { - ByteBuffer packet = - new ByteBuffer(new byte[] {0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x10, 0x00, 0x01, 0x00, 0x10, 0x00, 0x01, 0x04, 0x0a, - 0x00, 0x0c, (byte)0x84, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}); + ByteBuffer packet = new ByteBuffer(new byte[] {0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x10, 0x00, 0x01, 0x00, 0x10, 0x00, + 0x01, 0x04, 0x0a, 0x00, 0x0c, (byte)0x84, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}); Element bitmap = new ServerBitmapUpdate("bitmap") { { diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerControlPDUCooperate.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerControlPDUCooperate.java old mode 100644 new mode 100755 similarity index 99% rename from services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerControlPDUCooperate.java rename to services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerControlPDUCooperate.java index 7bbe0c346cb..2a9d49db551 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerControlPDUCooperate.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerControlPDUCooperate.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package rdpclient; +package rdpclient.rdp; import streamer.ByteBuffer; import streamer.Link; diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerControlPDUGrantedControl.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerControlPDUGrantedControl.java old mode 100644 new mode 100755 similarity index 99% rename from services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerControlPDUGrantedControl.java rename to services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerControlPDUGrantedControl.java index 62cbd6cedc8..974d622a57e --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerControlPDUGrantedControl.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerControlPDUGrantedControl.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package rdpclient; +package rdpclient.rdp; import streamer.ByteBuffer; import streamer.Link; diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerDemandActivePDU.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerDemandActivePDU.java new file mode 100755 index 00000000000..88ede17a19a --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerDemandActivePDU.java @@ -0,0 +1,660 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.rdp; + +import streamer.BaseElement; +import streamer.ByteBuffer; +import streamer.Element; +import streamer.Link; +import streamer.Order; +import streamer.Pipeline; +import streamer.PipelineImpl; +import streamer.debug.FakeSink; +import streamer.debug.MockSource; +import common.ScreenDescription; + +/** + * @see http://msdn.microsoft.com/en-us/library/cc240669.aspx + * @see http://msdn.microsoft.com/en-us/library/cc240484.aspx + */ +public class ServerDemandActivePDU extends BaseElement { + + /** + * Demand Active PDU. + */ + public static final int PDUTYPE_DEMANDACTIVEPDU = 0x1; + + protected RdpState state; + protected ScreenDescription screen; + + public ServerDemandActivePDU(String id, ScreenDescription screen, RdpState state) { + super(id); + this.state = state; + this.screen = screen; + } + + @Override + public void handleData(ByteBuffer buf, Link link) { + if (verbose) + System.out.println("[" + this + "] INFO: Data received: " + buf + "."); + + // Total length of packet + int length = buf.readSignedShortLE(); // Ignore + if (buf.length != length) + throw new RuntimeException("Incorrect length of packet. Length: " + length + ", data: " + buf + "."); + + int type = buf.readSignedShortLE() & 0xf; + if (type != PDUTYPE_DEMANDACTIVEPDU) + throw new RuntimeException("Unknown PDU type. Expected type: Demand Active PDU (0x1), actual tyoe: " + type + ", data: " + buf + "."); + + // TS_SHARECONTROLHEADER::pduSource = 0x03ea (1002) + int pduSource = buf.readSignedShortLE(); + if (pduSource != 1002) + throw new RuntimeException("Unexepcted source of demand active PDU. Expected source: 1002, actual source: " + pduSource + "."); + + // (4 bytes): A 32-bit, unsigned integer. The share identifier for the + // packet (see [T128] section 8.4.2 for more information regarding share + // IDs). + long shareId = buf.readUnsignedIntLE(); + state.serverShareId = shareId; + + // Ignore rest of server data because it is not used by this client. + // (2 bytes): A 16-bit, unsigned integer. The size in bytes of the + // sourceDescriptor field. + int lengthSourceDescriptor = buf.readUnsignedShortLE(); + + // (2 bytes): A 16-bit, unsigned integer. The combined size in bytes of the + // numberCapabilities, pad2Octets, and capabilitySets fields. + int lengthCombinedCapabilities = buf.readUnsignedShortLE(); + + // (variable): A variable-length array of bytes containing a source + // descriptor, + // ByteBuffer sourceDescriptor = buf.readBytes(lengthSourceDescriptor); + buf.skipBytes(lengthSourceDescriptor); + + // (variable): An array of Capability Set (section 2.2.1.13.1.1.1) + // structures. The number of capability sets is specified by the + // numberCapabilities field. + handleCapabiltySets(buf.readBytes(lengthCombinedCapabilities)); + + // (4 bytes): A 32-bit, unsigned integer. The session identifier. This field + // is ignored by the client. + buf.skipBytes(4); + + /* DEBUG */buf.assertThatBufferIsFullyRead(); + + buf.unref(); + + sendHandshakePackets(); + } + + /** + * General Capability Set + */ + public static final int CAPSTYPE_GENERAL = 0x0001; + /** + * Bitmap Capability Set + */ + public static final int CAPSTYPE_BITMAP = 0x0002; + /** + * Order Capability Set + */ + public static final int CAPSTYPE_ORDER = 0x0003; + /** + * Revision 1 Bitmap Cache Capability Set + */ + public static final int CAPSTYPE_BITMAPCACHE = 0x0004; + /** + * Control Capability Set + */ + public static final int CAPSTYPE_CONTROL = 0x0005; + /** + * Window Activation Capability Set + */ + public static final int CAPSTYPE_ACTIVATION = 0x0007; + /** + * Pointer Capability Set + */ + public static final int CAPSTYPE_POINTER = 0x0008; + /** + * Share Capability Set + */ + public static final int CAPSTYPE_SHARE = 0x0009; + /** + * Color Table Cache Capability Set + */ + public static final int CAPSTYPE_COLORCACHE = 0x000A; + /** + * Sound Capability Set + */ + public static final int CAPSTYPE_SOUND = 0x000C; + /** + * Input Capability Set + */ + public static final int CAPSTYPE_INPUT = 0x000D; + /** + * Font Capability Set + */ + public static final int CAPSTYPE_FONT = 0x000E; + /** + * Brush Capability Set + */ + public static final int CAPSTYPE_BRUSH = 0x000F; + /** + * Glyph Cache Capability Set + */ + public static final int CAPSTYPE_GLYPHCACHE = 0x0010; + /** + * Offscreen Bitmap Cache Capability Set + */ + public static final int CAPSTYPE_OFFSCREENCACHE = 0x0011; + /** + * Bitmap Cache Host Support Capability Set + */ + public static final int CAPSTYPE_BITMAPCACHE_HOSTSUPPORT = 0x0012; + /** + * Revision 2 Bitmap Cache Capability Set + */ + public static final int CAPSTYPE_BITMAPCACHE_REV2 = 0x0013; + /** + * Virtual Channel Capability Set + */ + public static final int CAPSTYPE_VIRTUALCHANNEL = 0x0014; + /** + * DrawNineGrid Cache Capability Set + */ + public static final int CAPSTYPE_DRAWNINEGRIDCACHE = 0x0015; + /** + * Draw GDI+ Cache Capability Set + */ + public static final int CAPSTYPE_DRAWGDIPLUS = 0x0016; + /** + * Remote Programs Capability Set + */ + public static final int CAPSTYPE_RAIL = 0x0017; + /** + * Window List Capability Set + */ + public static final int CAPSTYPE_WINDOW = 0x0018; + /** + * Desktop Composition Extension Capability Set + */ + public static final int CAPSETTYPE_COMPDESK = 0x0019; + /** + * Multifragment Update Capability Set + */ + public static final int CAPSETTYPE_MULTIFRAGMENTUPDATE = 0x001A; + /** + * Large Pointer Capability Set + */ + public static final int CAPSETTYPE_LARGE_POINTER = 0x001B; + /** + * Surface Commands Capability Set + */ + public static final int CAPSETTYPE_SURFACE_COMMANDS = 0x001C; + /** + * Bitmap Codecs Capability Set + */ + public static final int CAPSETTYPE_BITMAP_CODECS = 0x001D; + /** + * Frame Acknowledge Capability Set + */ + public static final int CAPSSETTYPE_FRAME_ACKNOWLEDGE = 0x001E; + + /** + * @see http://msdn.microsoft.com/en-us/library/cc240486.aspx + */ + protected void handleCapabiltySets(ByteBuffer buf) { + // (2 bytes): A 16-bit, unsigned integer. The number of capability sets + // included in the Demand Active PDU. + int numberCapabilities = buf.readSignedShortLE(); + + // (2 bytes): Padding. + buf.skipBytes(2); + + for (int i = 0; i < numberCapabilities; i++) { + // (2 bytes): A 16-bit, unsigned integer. The type identifier of the + // capability set. + int capabilitySetType = buf.readUnsignedShortLE(); + + // (2 bytes): A 16-bit, unsigned integer. The length in bytes of the + // capability data, including the size of the capabilitySetType and + // lengthCapability fields. + int lengthCapability = buf.readUnsignedShortLE(); + + // (variable): Capability set data which conforms to the structure of the + // type given by the capabilitySetType field. + ByteBuffer capabilityData = buf.readBytes(lengthCapability - 4); + + switch (capabilitySetType) { + case CAPSTYPE_GENERAL: + break; + case CAPSTYPE_BITMAP: + handleBitmapCapabilities(capabilityData); + break; + case CAPSTYPE_ORDER: + break; + case CAPSTYPE_BITMAPCACHE: + break; + case CAPSTYPE_CONTROL: + break; + case CAPSTYPE_ACTIVATION: + break; + case CAPSTYPE_POINTER: + break; + case CAPSTYPE_SHARE: + break; + case CAPSTYPE_COLORCACHE: + break; + case CAPSTYPE_SOUND: + break; + case CAPSTYPE_INPUT: + break; + case CAPSTYPE_FONT: + break; + case CAPSTYPE_BRUSH: + break; + case CAPSTYPE_GLYPHCACHE: + break; + case CAPSTYPE_OFFSCREENCACHE: + break; + case CAPSTYPE_BITMAPCACHE_HOSTSUPPORT: + break; + case CAPSTYPE_BITMAPCACHE_REV2: + break; + case CAPSTYPE_VIRTUALCHANNEL: + break; + case CAPSTYPE_DRAWNINEGRIDCACHE: + break; + case CAPSTYPE_DRAWGDIPLUS: + break; + case CAPSTYPE_RAIL: + break; + case CAPSTYPE_WINDOW: + break; + case CAPSETTYPE_COMPDESK: + break; + case CAPSETTYPE_MULTIFRAGMENTUPDATE: + break; + case CAPSETTYPE_LARGE_POINTER: + break; + case CAPSETTYPE_SURFACE_COMMANDS: + break; + case CAPSETTYPE_BITMAP_CODECS: + break; + case CAPSSETTYPE_FRAME_ACKNOWLEDGE: + break; + default: + // Ignore + break; + } + + capabilityData.unref(); + } + + // TODO + + buf.unref(); + } + + /** + * @see http://msdn.microsoft.com/en-us/library/cc240554.aspx + */ + protected void handleBitmapCapabilities(ByteBuffer buf) { + + // (2 bytes): A 16-bit, unsigned integer. The server MUST set this field to + // the color depth of the session, while the client SHOULD set this field to + // the color depth requested in the Client Core Data (section 2.2.1.3.2). + int preferredBitsPerPixel = buf.readUnsignedShortLE(); + screen.setPixelFormatRGBTrueColor(preferredBitsPerPixel); + + // receive1BitPerPixel (2 bytes): A 16-bit, unsigned integer. Indicates + // whether the client can receive 1 bpp. This field is ignored and SHOULD be + // set to TRUE (0x0001). + buf.skipBytes(2); + + // receive4BitsPerPixel(2 bytes): A 16-bit, unsigned integer. Indicates + // whether the client can receive 4 bpp. This field is ignored and SHOULD be + // set to TRUE (0x0001). + buf.skipBytes(2); + + // receive8BitsPerPixel (2 bytes): A 16-bit, unsigned integer. Indicates + // whether the client can receive 8 bpp. This field is ignored and SHOULD be + // set to TRUE (0x0001). + buf.skipBytes(2); + + // (2 bytes): A 16-bit, unsigned integer. The width of the desktop in the + // session. + int desktopWidth = buf.readUnsignedShortLE(); + + // (2 bytes): A 16-bit, unsigned integer. The height of the desktop in the + // session. + int desktopHeight = buf.readUnsignedShortLE(); + + screen.setFramebufferSize(desktopWidth, desktopHeight); + + // pad2octets (2 bytes): A 16-bit, unsigned integer. Padding. Values in this + // field MUST be ignored. + + // desktopResizeFlag (2 bytes): A 16-bit, unsigned integer. Indicates + // whether resizing the desktop by using a Deactivation-Reactivation + // Sequence is supported. + + // bitmapCompressionFlag (2 bytes): A 16-bit, unsigned integer. Indicates + // whether bitmap compression is supported. This field MUST be set to TRUE + // (0x0001) because support for compressed bitmaps is required for a + // connection to proceed. + + // highColorFlags (1 byte): An 8-bit, unsigned integer. Client support for + // 16 bpp color modes. This field is ignored and SHOULD be set to zero. + + // drawingFlags (1 byte): An 8-bit, unsigned integer. Flags describing + // support for 32 bpp bitmaps. + + // multipleRectangleSupport (2 bytes): A 16-bit, unsigned integer. Indicates + // whether the use of multiple bitmap rectangles is supported in the Bitmap + // Update (section 2.2.9.1.1.3.1.2). This field MUST be set to TRUE (0x0001) + // because multiple rectangle support is required for a connection to + // proceed. + + // pad2octetsB (2 bytes): A 16-bit, unsigned integer. Padding. Values in + // this field MUST be ignored. + } + + /** + * Send all client requests in one hop, to simplify logic. + */ + protected void sendHandshakePackets() { + // Send reactivation sequence in bulk + pushDataToPad("confirm_active", new ByteBuffer((Order)null)); + } + + /** + * Example. + * + */ + public static void main(String args[]) { + // System.setProperty("streamer.Link.debug", "true"); + System.setProperty("streamer.Element.debug", "true"); + // System.setProperty("streamer.Pipeline.debug", "true"); + + /* @formatter:off */ + byte[] packet = new byte[] { + 0x67, 0x01, // TS_SHARECONTROLHEADER::totalLength = 0x0167 = 359 bytes + 0x11, 0x00, // TS_SHARECONTROLHEADER::pduType = 0x0011 0x0011 = 0x0010 | 0x0001 = TS_PROTOCOL_VERSION | PDUTYPE_DEMANDACTIVEPDU + + (byte) 0xea, 0x03, // TS_SHARECONTROLHEADER::pduSource = 0x03ea (1002) + + (byte) 0xea, 0x03, 0x01, 0x00, // TS_DEMAND_ACTIVE_PDU::shareId + 0x04, 0x00, // TS_DEMAND_ACTIVE_PDU::lengthSourceDescriptor = 4 bytes + 0x51, 0x01, // TS_DEMAND_ACTIVE_PDU::lengthCombinedCapabilities = 0x151 = 337 bytes + + 0x52, 0x44, 0x50, 0x00, // TS_DEMAND_ACTIVE_PDU::sourceDescriptor = "RDP" + + 0x0d, 0x00, // TS_DEMAND_ACTIVE_PDU::numberCapabilities = 13 + 0x00, 0x00, // TS_DEMAND_ACTIVE_PDU::pad2octets + + // Share Capability Set (8 bytes) + // 0x09, 0x00, 0x08, 0x00, (byte) 0xea, 0x03, (byte) 0xdc, (byte) 0xe2, + // + 0x09, 0x00, // TS_SHARE_CAPABILITYSET::capabilitySetType = CAPSTYPE_SHARE (9) + 0x08, 0x00, // TS_SHARE_CAPABILITYSET::lengthCapability = 8 bytes + (byte) 0xea, 0x03, // TS_SHARE_CAPABILITYSET::nodeID = 0x03ea (1002) + (byte) 0xdc, (byte) 0xe2, // TS_SHARE_CAPABILITYSET::pad2octets + + // General Capability Set (24 bytes) + // 0x01, 0x00, 0x18, 0x00, 0x01, 0x00, 0x03, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x1d, 0x04, + // 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, + // + 0x01, 0x00, // TS_GENERAL_CAPABILITYSET::capabilitySetType = CAPSTYPE_GENERAL (1) + 0x18, 0x00, // TS_GENERAL_CAPABILITYSET::lengthCapability = 24 bytes + + 0x01, 0x00, // TS_GENERAL_CAPABILITYSET::osMajorType = TS_OSMAJORTYPE_WINDOWS (1) + 0x03, 0x00, // TS_GENERAL_CAPABILITYSET::osMinorType = TS_OSMINORTYPE_WINDOWS_NT (3) + 0x00, 0x02, // TS_GENERAL_CAPABILITYSET::protocolVersion = TS_CAPS_PROTOCOLVERSION (0x0200) + 0x00, 0x00, // TS_GENERAL_CAPABILITYSET::pad2octetsA + 0x00, 0x00, // TS_GENERAL_CAPABILITYSET::generalCompressionTypes = 0 + 0x1d, 0x04, // TS_GENERAL_CAPABILITYSET::extraFlags = 0x041d = 0x0400 | 0x0010 | 0x0008 | 0x0004 | 0x0001 = NO_BITMAP_COMPRESSION_HDR | ENC_SALTED_CHECKSUM | AUTORECONNECT_SUPPORTED | LONG_CREDENTIALS_SUPPORTED | FASTPATH_OUTPUT_SUPPORTED + + 0x00, 0x00, // TS_GENERAL_CAPABILITYSET::updateCapabilityFlag = 0 + 0x00, 0x00, // TS_GENERAL_CAPABILITYSET::remoteUnshareFlag = 0 + 0x00, 0x00, // TS_GENERAL_CAPABILITYSET::generalCompressionLevel = 0 + 0x01, // TS_GENERAL_CAPABILITYSET::refreshRectSupport = TRUE + 0x01, // TS_GENERAL_CAPABILITYSET::suppressOutputSupport = TRUE + + // Virtual Channel Capability Set (8 bytes) + // 0x14, 0x00, 0x08, 0x00, 0x02, 0x00, 0x00, 0x00, + // + 0x14, 0x00, // TS_VIRTUALCHANNEL_CAPABILITYSET::capabilitySetType = CAPSTYPE_VIRTUALCHANNEL (20) + 0x08, 0x00, // TS_VIRTUALCHANNEL_CAPABILITYSET::lengthCapability = 8 bytes + + 0x02, 0x00, 0x00, 0x00, // TS_VIRTUALCHANNEL_CAPABILITYSET::vccaps1 = 0x00000002 = VCCAPS_COMPR_CS_8K + + // DrawGdiPlus Capability Set (40 bytes) + // 0x16, 0x00, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, (byte) 0xf6, 0x13, (byte) 0xf3, 0x01, 0x00, 0x00, 0x00, + // 0x01, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, (byte) 0x9c, (byte) 0xf6, 0x13, (byte) 0xf3, 0x61, (byte) 0xa6, (byte) 0x82, (byte) 0x80, + // 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, (byte) 0x91, (byte) 0xbf, + // + 0x16, 0x00, // TS_DRAW_GDIPLUS_CAPABILITYSET::capabilitySetType = CAPSTYPE_DRAWGDIPLUS (22) + 0x28, 0x00, // TS_DRAW_GDIPLUS_CAPABILITYSET::lengthCapability = 40 bytes + + 0x00, 0x00, 0x00, 0x00, // TS_DRAW_GDIPLUS_CAPABILITYSET::drawGdiplusSupportLevel = TS_DRAW_GDIPLUS_DEFAULT (0) + 0x70, (byte) 0xf6, 0x13, (byte) 0xf3, // TS_DRAW_GDIPLUS_CAPABILITYSET::GdipVersion (not initialized by server) + 0x01, 0x00, 0x00, 0x00, // TS_DRAW_GDIPLUS_CAPABILITYSET::drawGdiplusCacheLevel = TS_DRAW_GDIPLUS_CACHE_LEVEL_ONE (1) + + 0x01, 0x00, // TS_GDIPLUS_CACHE_ENTRIES::GdipGraphicsCacheEntries (not initialized by server) + 0x00, 0x00, // TS_GDIPLUS_CACHE_ENTRIES::GdipObjectBrushCacheEntries (not initialized by server) + 0x18, 0x00, // TS_GDIPLUS_CACHE_ENTRIES::GdipObjectPenCacheEntries (not initialized by server) + 0x00, 0x00, // TS_GDIPLUS_CACHE_ENTRIES::GdipObjectImageCacheEntries (not initialized by server) + (byte) 0x9c, (byte) 0xf6, // TS_GDIPLUS_CACHE_ENTRIES::GdipObjectImageAttributesCacheEntries (not initialized by server) + + 0x13, (byte) 0xf3, // TS_GDIPLUS_CACHE_CHUNK_SIZE::GdipGraphicsCacheChunkSize (not initialized by server) + 0x61, (byte) 0xa6, // TS_GDIPLUS_CACHE_CHUNK_SIZE::GdipObjectBrushCacheChunkSize (not initialized by server) + (byte) 0x82, (byte) 0x80, // TS_GDIPLUS_CACHE_CHUNK_SIZE::GdipObjectPenCacheChunkSize (not initialized by server) + 0x00, 0x00, // TS_GDIPLUS_CACHE_CHUNK_SIZE::GdipObjectImageAttributesCacheChunkSize (not initialized by server) + + 0x00, 0x00, // TS_GDIPLUS_IMAGE_CACHE_PROPERTIES::GdipObjectImageCacheChunkSize (not initialized by server) + 0x00, 0x50, // TS_GDIPLUS_IMAGE_CACHE_PROPERTIES::GdipObjectImageCacheTotalSize (not initialized by server) + (byte) 0x91, (byte) 0xbf, // TS_GDIPLUS_IMAGE_CACHE_PROPERTIES::GdipObjectImageCacheMaxSize (not initialized by server) + + // Font Capability Set (4 bytes) + // 0x0e, 0x00, 0x04, 0x00, + // + // Due to a bug, the TS_FONT_CAPABILITYSET capability set size is incorrectly set to 4 bytes (it must be 8 bytes). As a result of this bug, the fontSupportFlags and pad2octets fields are missing. + 0x0e, 0x00, // TS_FONT_CAPABILITYSET::capabilitySetType = CAPSTYPE_FONT (14) + 0x04, 0x00, // TS_FONT_CAPABILITYSET::lengthCapability = 4 bytes + + + // Bitmap Capability Set (28 bytes) + // 0x02, 0x00, 0x1c, 0x00, 0x18, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x04, + // 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, + // + 0x02, 0x00, // TS_BITMAP_CAPABILITYSET::capabilitySetType = CAPSTYPE_BITMAP (2) + 0x1c, 0x00, // TS_BITMAP_CAPABILITYSET::lengthCapability = 28 bytes + + 0x18, 0x00, // TS_BITMAP_CAPABILITYSET::preferredBitsPerPixel = 24 bpp + 0x01, 0x00, // TS_BITMAP_CAPABILITYSET::receive1BitPerPixel = TRUE + 0x01, 0x00, // TS_BITMAP_CAPABILITYSET::receive4BitsPerPixel = TRUE + 0x01, 0x00, // TS_BITMAP_CAPABILITYSET::receive8BitsPerPixel = TRUE + 0x00, 0x05, // TS_BITMAP_CAPABILITYSET::desktopWidth = 1280 pixels + 0x00, 0x04, // TS_BITMAP_CAPABILITYSET::desktopHeight = 1024 pixels + 0x00, 0x00, // TS_BITMAP_CAPABILITYSET::pad2octets + 0x01, 0x00, // TS_BITMAP_CAPABILITYSET::desktopResizeFlag = TRUE + 0x01, 0x00, // TS_BITMAP_CAPABILITYSET::bitmapCompressionFlag = TRUE + 0x00, // TS_BITMAP_CAPABILITYSET::highColorFlags = 0 + 0x00, // TS_BITMAP_CAPABILITYSET::pad1octet + 0x01, 0x00, // TS_BITMAP_CAPABILITYSET::multipleRectangleSupport = TRUE + 0x00, 0x00, // TS_BITMAP_CAPABILITYSET::pad2octetsB + + // Order Capability Set (88 bytes) + // 0x03, 0x00, 0x58, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // 0x00, 0x00, 0x00, 0x00, 0x40, 0x42, 0x0f, 0x00, 0x01, 0x00, 0x14, 0x00, 0x00, 0x00, 0x01, 0x00, + // 0x00, 0x00, 0x22, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, + // 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x01, 0x01, 0x01, 0x01, + // 0x00, 0x00, 0x00, 0x00, (byte) 0xa1, 0x06, 0x00, 0x00, 0x40, 0x42, 0x0f, 0x00, 0x40, 0x42, 0x0f, 0x00, + // 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // + 0x03, 0x00, // TS_ORDER_CAPABILITYSET::capabilitySetType = CAPSTYPE_ORDER (3) + 0x58, 0x00, // TS_ORDER_CAPABILITYSET::lengthCapability = 88 bytes + + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // TS_ORDER_CAPABILITYSET::terminalDescriptor = "" + 0x40, 0x42, 0x0f, 0x00, // TS_ORDER_CAPABILITYSET::pad4octetsA + + 0x01, 0x00, // TS_ORDER_CAPABILITYSET::desktopSaveXGranularity = 1 + 0x14, 0x00, // TS_ORDER_CAPABILITYSET::desktopSaveYGranularity = 20 + 0x00, 0x00, // TS_ORDER_CAPABILITYSET::pad2octetsA + 0x01, 0x00, // TS_ORDER_CAPABILITYSET::maximumOrderLevel = ORD_LEVEL_1_ORDERS (1) + 0x00, 0x00, // TS_ORDER_CAPABILITYSET::numberFonts = 0 + + 0x22, 0x00, // TS_ORDER_CAPABILITYSET::orderFlags = 0x0022 = 0x0020 | 0x0002 = COLORINDEXSUPPORT | NEGOTIATEORDERSUPPORT + + 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_DSTBLT_INDEX] = TRUE + 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_PATBLT_INDEX] = TRUE + 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_SCRBLT_INDEX] = TRUE + 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_MEMBLT_INDEX] = TRUE + 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_MEM3BLT_INDEX] = TRUE + 0x00, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_ATEXTOUT_INDEX] = FALSE + 0x00, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_AEXTTEXTOUT_INDEX] = FALSE + 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_DRAWNINEGRID_INDEX] = TRUE + 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_LINETO_INDEX] = TRUE + 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_MULTI_DRAWNINEGRID_INDEX] = TRUE + 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_OPAQUERECT_INDEX] = TRUE + 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_SAVEBITMAP_INDEX] = TRUE + 0x00, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_WTEXTOUT_INDEX] = FALSE + 0x00, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_MEMBLT_R2_INDEX] = FALSE + 0x00, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_MEM3BLT_R2_INDEX] = FALSE + 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_MULTIDSTBLT_INDEX] = TRUE + 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_MULTIPATBLT_INDEX] = TRUE + 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_MULTISCRBLT_INDEX] = TRUE + 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_MULTIOPAQUERECT_INDEX] = TRUE + 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_FAST_INDEX_INDEX] = TRUE + 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_POLYGON_SC_INDEX] = TRUE + 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_POLYGON_CB_INDEX] = TRUE + 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_POLYLINE_INDEX] = TRUE + 0x00, // TS_ORDER_CAPABILITYSET::orderSupport[23] = 0 + 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_FAST_GLYPH_INDEX] = TRUE + 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_ELLIPSE_SC_INDEX] = TRUE + 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_ELLIPSE_CB_INDEX] = TRUE + 0x01, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_INDEX_INDEX] = TRUE + 0x00, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_WEXTTEXTOUT_INDEX] = FALSE + 0x00, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_WLONGTEXTOUT_INDEX] = FALSE + 0x00, // TS_ORDER_CAPABILITYSET::orderSupport[TS_NEG_WLONGEXTTEXTOUT_INDEX] = FALSE + 0x00, // TS_ORDER_CAPABILITYSET::orderSupport[24] = 0 + + (byte) 0xa1, 0x06, // TS_ORDER_CAPABILITYSET::textFlags = 0x06a1 + + 0x00, 0x00, // TS_ORDER_CAPABILITYSET::pad2octetsB + 0x40, 0x42, 0x0f, 0x00, // TS_ORDER_CAPABILITYSET::pad4octetsB + + 0x40, 0x42, 0x0f, 0x00, // TS_ORDER_CAPABILITYSET::desktopSaveSize = 0xf4240 = 1000000 + 0x01, 0x00, // TS_ORDER_CAPABILITYSET::pad2octetsC + 0x00, 0x00, // TS_ORDER_CAPABILITYSET::pad2octetsD + 0x00, 0x00, // TS_ORDER_CAPABILITYSET::textANSICodePage + 0x00, 0x00, // TS_ORDER_CAPABILITYSET::pad2octetsE + + // Color Table Cache Capability Set (8 bytes) + // 0x0a, 0x00, 0x08, 0x00, 0x06, 0x00, 0x00, 0x00, + // + 0x0a, 0x00, // TS_COLORTABLECACHE_CAPABILITYSET::capabilitySetType = CAPSTYPE_COLORCACHE (10) + 0x08, 0x00, // TS_COLORTABLECACHE_CAPABILITYSET::lengthCapability = 8 bytes + + 0x06, 0x00, // TS_COLORTABLECACHE_CAPABILITYSET::colorTableCacheSize = 6 + 0x00, 0x00, // TS_COLORTABLECACHE_CAPABILITYSET::pad2octets + + // Bitmap Cache Host Support Capability Set (8 bytes) + // 0x12, 0x00, 0x08, 0x00, 0x01, 0x00, 0x00, 0x00, + // + 0x12, 0x00, // TS_BITMAPCACHE_CAPABILITYSET_HOSTSUPPORT::capabilitySetType = CAPSTYPE_BITMAPCACHE_HOSTSUPPORT (18) + 0x08, 0x00, // TS_BITMAPCACHE_CAPABILITYSET_HOSTSUPPORT::lengthCapability = 8 bytes + + 0x01, // TS_BITMAPCACHE_CAPABILITYSET_HOSTSUPPORT::CacheVersion = 1 (corresponds to rev. 2 capabilities) + 0x00, // TS_BITMAPCACHE_CAPABILITYSET_HOSTSUPPORT::Pad1 + 0x00, 0x00, // TS_BITMAPCACHE_CAPABILITYSET_HOSTSUPPORT::Pad2 + + // Pointer Capability Set (10 bytes) + // 0x08, 0x00, 0x0a, 0x00, 0x01, 0x00, 0x19, 0x00, 0x19, 0x00, + // + 0x08, 0x00, // TS_POINTER_CAPABILITYSET::capabilitySetType = CAPSTYPE_POINTER (8) + 0x0a, 0x00, // TS_POINTER_CAPABILITYSET::lengthCapability = 10 bytes + + 0x01, 0x00, // TS_POINTER_CAPABILITYSET::colorPointerFlag = TRUE + 0x19, 0x00, // TS_POINTER_CAPABILITYSET::colorPointerCacheSize = 25 + 0x19, 0x00, // TS_POINTER_CAPABILITYSET::pointerCacheSize = 25 + + // Input Capability Set (88 bytes) + // 0x0d, 0x00, 0x58, 0x00, 0x35, 0x00, 0x00, 0x00, (byte) 0xa1, 0x06, 0x00, 0x00, 0x40, 0x42, 0x0f, 0x00, + // 0x0c, (byte) 0xf6, 0x13, (byte) 0xf3, (byte) 0x93, 0x5a, 0x37, (byte) 0xf3, 0x00, (byte) 0x90, 0x30, (byte) 0xe1, 0x34, 0x1c, 0x38, (byte) 0xf3, + // 0x40, (byte) 0xf6, 0x13, (byte) 0xf3, 0x04, 0x00, 0x00, 0x00, 0x4c, 0x54, (byte) 0xdc, (byte) 0xe2, 0x08, 0x50, (byte) 0xdc, (byte) 0xe2, + // 0x01, 0x00, 0x00, 0x00, 0x08, 0x50, (byte) 0xdc, (byte) 0xe2, 0x00, 0x00, 0x00, 0x00, 0x38, (byte) 0xf6, 0x13, (byte) 0xf3, + // 0x2e, 0x05, 0x38, (byte) 0xf3, 0x08, 0x50, (byte) 0xdc, (byte) 0xe2, 0x2c, (byte) 0xf6, 0x13, (byte) 0xf3, 0x00, 0x00, 0x00, 0x00, + // 0x08, 0x00, 0x0a, 0x00, 0x01, 0x00, 0x19, 0x00, + // + 0x0d, 0x00, // TS_INPUT_CAPABILITYSET::capabilitySetType = CAPSTYPE_INPUT (13) + 0x58, 0x00, // TS_INPUT_CAPABILITYSET::lengthCapability = 88 bytes + + 0x35, 0x00, // TS_INPUT_CAPABILITYSET::inputFlags = 0x0035 = 0x0020 | 0x0010 | 0x0004 | 0x0001 = INPUT_FLAG_FASTPATH_INPUT2 | INPUT_FLAG_VKPACKET | INPUT_FLAG_MOUSEX | INPUT_FLAG_SCANCODES + + 0x00, 0x00, // TS_INPUT_CAPABILITYSET::pad2octetsA + (byte) 0xa1, 0x06, 0x00, 0x00, // TS_INPUT_CAPABILITYSET::keyboardLayout (not initialized by server) + 0x40, 0x42, 0x0f, 0x00, // TS_INPUT_CAPABILITYSET::keyboardType (not initialized by server) + 0x0c, (byte) 0xf6, 0x13, (byte) 0xf3, // TS_INPUT_CAPABILITYSET::keyboardSubType (not initialized by server) + (byte) 0x93, 0x5a, 0x37, (byte) 0xf3, // TS_INPUT_CAPABILITYSET::keyboardFunctionKey (not initialized by server) + + // TS_INPUT_CAPABILITYSET::imeFileName (not initialized by server) + 0x00, (byte) 0x90, 0x30, (byte) 0xe1, 0x34, 0x1c, 0x38, (byte) 0xf3, 0x40, (byte) 0xf6, 0x13, (byte) 0xf3, 0x04, 0x00, 0x00, 0x00, + 0x4c, 0x54, (byte) 0xdc, (byte) 0xe2, 0x08, 0x50, (byte) 0xdc, (byte) 0xe2, 0x01, 0x00, 0x00, 0x00, 0x08, 0x50, (byte) 0xdc, (byte) 0xe2, + 0x00, 0x00, 0x00, 0x00, 0x38, (byte) 0xf6, 0x13, (byte) 0xf3, 0x2e, 0x05, 0x38, (byte) 0xf3, 0x08, 0x50, (byte) 0xdc, (byte) 0xe2, + 0x2c, (byte) 0xf6, 0x13, (byte) 0xf3, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x0a, 0x00, 0x01, 0x00, 0x19, 0x00, + + // RAIL Capability Set (8 bytes) + // 0x17, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, + // + 0x17, 0x00, // TS_RAIL_CAPABILITYSET::capabilitySetType = CAPSTYPE_RAIL (23) + 0x08, 0x00, // TS_RAIL_CAPABILITYSET::lengthCapability = 8 bytes + + 0x00, 0x00, 0x00, 0x00, // TS_RAIL_CAPABILITYSET::railSupportLevel = TS_RAIL_LEVEL_DEFAULT (0) + + // Windowing Capability Set (11 bytes) + // 0x18, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // + 0x18, 0x00, // TS_WINDOW_CAPABILITYSET::capabilitySetType = CAPSTYPE_WINDOW (24) + 0x0b, 0x00, // TS_WINDOW_CAPABILITYSET::lengthCapability = 11 bytes + + 0x00, 0x00, 0x00, 0x00, // TS_WINDOW_CAPABILITYSET::wndSupportLevel = TS_WINDOW_LEVEL_DEFAULT (0) + 0x00, // TS_WINDOW_CAPABILITYSET::nIconCaches = 0 + 0x00, 0x00, // TS_WINDOW_CAPABILITYSET::nIconCacheEntries = 0 + + // Remainder of Demand Active PDU: + + 0x00, 0x00, 0x00, 0x00, // TS_DEMAND_ACTIVE_PDU::sessionId = 0 + }; + /* @formatter:on */ + + RdpState rdpState = new RdpState(); + ScreenDescription screenDescription = new ScreenDescription(); + + MockSource source = new MockSource("source", ByteBuffer.convertByteArraysToByteBuffers(packet)); + Element demandActive = new ServerDemandActivePDU("demand_active", screenDescription, rdpState); + Element sink = new FakeSink("sink"); + + Pipeline pipeline = new PipelineImpl("test"); + pipeline.add(source, demandActive, sink); + pipeline.link("source", "demand_active", "sink"); + pipeline.runMainLoop("source", STDOUT, false, false); + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerFastPath.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerFastPath.java new file mode 100755 index 00000000000..f88f492b047 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerFastPath.java @@ -0,0 +1,315 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.rdp; + +import streamer.BaseElement; +import streamer.ByteBuffer; +import streamer.Link; + +/** + * @see http://msdn.microsoft.com/en-us/library/cc240621.aspx + */ +public class ServerFastPath extends BaseElement { + + /** + * TPKT protocol version (first byte). + */ + public static final int PROTOCOL_TPKT = 0x03; + + /** + * Fast path protocol version (first two bits of first byte). + */ + public static final int PROTOCOL_FASTPATH = 0x00; + + /** + * CredSSP packets. + */ + public static final int PROTOCOL_CREDSSP = 0x30; + + /** + * TPKT packets will be pushed to that pad. + */ + public static final String TPKT_PAD = "tpkt"; + + /** + * CredSSP packets will be pushed to same pad as TPKT, because they are part + * of slow-path initialization sequence. + */ + public static final String CREDSSP_PAD = "tpkt"; + + private static final String ORDERS_PAD = "orders"; + private static final String BITMAP_PAD = "bitmap"; + private static final String PALETTE_PAD = "palette"; + + /** + * Indicates that packet contains 8 byte secure checksum at top of packet. Top + * two bits of first byte. + */ + public static final int FASTPATH_OUTPUT_SECURE_CHECKSUM = 1; + + /** + * Indicates that packet contains 8 byte secure checksum at top of packet and + * packet content is encrypted. Top two bits of first byte. + */ + public static final int FASTPATH_OUTPUT_ENCRYPTED = 2; + + public static final int FASTPATH_UPDATETYPE_ORDERS = 0; + public static final int FASTPATH_UPDATETYPE_BITMAP = 1; + public static final int FASTPATH_UPDATETYPE_PALETTE = 2; + public static final int FASTPATH_UPDATETYPE_SYNCHRONIZE = 3; + public static final int FASTPATH_UPDATETYPE_SURFCMDS = 4; + public static final int FASTPATH_UPDATETYPE_PTR_NULL = 5; + public static final int FASTPATH_UPDATETYPE_PTR_DEFAULT = 6; + public static final int FASTPATH_UPDATETYPE_PTR_POSITION = 8; + public static final int FASTPATH_UPDATETYPE_COLOR = 9; + public static final int FASTPATH_UPDATETYPE_CACHED = 0xa; + public static final int FASTPATH_UPDATETYPE_POINTER = 0xb; + + public static final int FASTPATH_FRAGMENT_SINGLE = 0; + public static final int FASTPATH_FRAGMENT_LAST = 1; + public static final int FASTPATH_FRAGMENT_FIRST = 2; + public static final int FASTPATH_FRAGMENT_NEXT = 3; + + public static final int FASTPATH_OUTPUT_COMPRESSION_USED = 2; + + public ServerFastPath(String id) { + super(id); + } + + @Override + public void handleData(ByteBuffer buf, Link link) { + if (buf == null) + return; + + if (verbose) + System.out.println("[" + this + "] INFO: Data received: " + buf + "."); + + // * DEBUG */System.out.println(buf.toHexString(buf.length)); + + // We need at 4 bytes to read packet type (TPKT or FastPath) and packet + // length + if (!cap(buf, 4, UNLIMITED, link, false)) + return; + + int typeAndFlags = buf.readUnsignedByte(); + + switch (typeAndFlags) { + case PROTOCOL_TPKT: // 0x03 + handleTpkt(buf, link); + break; + + case PROTOCOL_CREDSSP: // 0x30, potential clash with FastPath + handleCredSSP(buf, link); + break; + + default: // (value & 0x03) == 0x00 + case PROTOCOL_FASTPATH: + handleFastPath(buf, link, typeAndFlags); + break; + } + + } + + private void handleTpkt(ByteBuffer buf, Link link) { + // Reserved + buf.skipBytes(1); + + // Read TPKT length + int length = buf.readUnsignedShort(); + + if (!cap(buf, length, length, link, false)) + // Wait for full packet to arrive + return; + + int payloadLength = length - buf.cursor; + + // Extract payload + ByteBuffer outBuf = buf.slice(buf.cursor, payloadLength, true); + buf.unref(); + + if (verbose) { + outBuf.putMetadata("source", this); + } + + pushDataToPad(TPKT_PAD, outBuf); + } + + private void handleCredSSP(ByteBuffer buf, Link link) { + + if (verbose) + System.out.println("[" + this + "] INFO: CredSSP data received: " + buf + "."); + + // Store header position: will parse whole header later in BER format parser + int headerPosition = buf.cursor - 1; + + long payloadLength = buf.readBerLength(); + if (payloadLength > 10 * 1024) + throw new RuntimeException("[" + this + "] ERROR: CredSSP packets seems to be too long: " + payloadLength + "bytes. Data: " + buf + "."); + + // Length is the size of payload, so we need to append size of header + int headerLength = buf.cursor - headerPosition; + int packetLength = (int)payloadLength + headerLength; + if (!cap(buf, packetLength, packetLength, link, false)) + // Wait for full packet to arrive + return; + + // Extract payload (with header) + ByteBuffer outBuf = buf.slice(headerPosition, packetLength, true); + buf.unref(); + + if (verbose) { + outBuf.putMetadata("source", this); + } + + pushDataToPad(CREDSSP_PAD, outBuf); + } + + private void handleFastPath(ByteBuffer buf, Link link, int typeAndFlags) { + // Number of bytes in updateData field (including header (1+1 or 2 + // bytes)) + int length = buf.readVariableUnsignedShort(); + + if (!cap(buf, length, length, link, false)) + // Wait for full packet to arrive + return; + + int type = typeAndFlags & 0x3; + int securityFlags = (typeAndFlags >> 6) & 0x3; + + // Assertions + { + if (type != PROTOCOL_FASTPATH) + throw new RuntimeException("Unknown protocol. Expected protocol: 0 (FastPath). Actual protocol: " + type + ", data: " + buf + "."); + + switch (securityFlags) { + case FASTPATH_OUTPUT_SECURE_CHECKSUM: + // TODO + throw new RuntimeException("Secure checksum is not supported in FastPath packets."); + case FASTPATH_OUTPUT_ENCRYPTED: + // TODO + throw new RuntimeException("Encryption is not supported in FastPath packets."); + } + } + + // TODO: optional FIPS information, when FIPS is selected + // TODO: optional data signature (checksum), when checksum or FIPS is + // selected + + // Array of FastPath update fields + while (buf.cursor < buf.length) { + + int updateHeader = buf.readUnsignedByte(); + + int size = buf.readUnsignedShortLE(); + + int updateCode = updateHeader & 0xf; + int fragmentation = (updateHeader >> 4) & 0x3; + int compression = (updateHeader >> 6) & 0x3; + + if (verbose) + System.out.println("[" + this + "] INFO: FastPath update received. UpdateCode: " + updateCode + ", fragmentation: " + fragmentation + ", compression: " + + compression + ", size: " + size + "."); + + ByteBuffer data = buf.readBytes(size); + buf.putMetadata("fragmentation", fragmentation); + buf.putMetadata("compression", compression); + + switch (updateCode) { + + case FASTPATH_UPDATETYPE_ORDERS: + if (verbose) + System.out.println("[" + this + "] INFO: FASTPATH_UPDATETYPE_ORDERS."); + pushDataToPad(ORDERS_PAD, data); + break; + + case FASTPATH_UPDATETYPE_BITMAP: + if (verbose) + System.out.println("[" + this + "] INFO: FASTPATH_UPDATETYPE_BITMAP."); + pushDataToPad(BITMAP_PAD, data); + break; + + case FASTPATH_UPDATETYPE_PALETTE: + if (verbose) + System.out.println("[" + this + "] INFO: FASTPATH_UPDATETYPE_PALETTE."); + pushDataToPad(PALETTE_PAD, data); + break; + + case FASTPATH_UPDATETYPE_SYNCHRONIZE: + // @see http://msdn.microsoft.com/en-us/library/cc240625.aspx + if (verbose) + System.out.println("[" + this + "] INFO: FASTPATH_UPDATETYPE_SYNCHRONIZE."); + + data.unref(); + + if (size != 0) + throw new RuntimeException("Size of FastPath synchronize packet must be 0. UpdateCode: " + updateCode + ", fragmentation: " + fragmentation + + ", compression: " + compression + ", size: " + size + ", data: " + data + "."); + break; + + case FASTPATH_UPDATETYPE_SURFCMDS: + if (verbose) + System.out.println("[" + this + "] INFO: FASTPATH_UPDATETYPE_SURFCMDS."); + + break; + + case FASTPATH_UPDATETYPE_PTR_NULL: + if (verbose) + System.out.println("[" + this + "] INFO: FASTPATH_UPDATETYPE_PTR_NULL."); + + break; + + case FASTPATH_UPDATETYPE_PTR_DEFAULT: + if (verbose) + System.out.println("[" + this + "] INFO: FASTPATH_UPDATETYPE_PTR_DEFAULT."); + + break; + + case FASTPATH_UPDATETYPE_PTR_POSITION: + if (verbose) + System.out.println("[" + this + "] INFO: FASTPATH_UPDATETYPE_PTR_POSITION."); + + break; + + case FASTPATH_UPDATETYPE_COLOR: + if (verbose) + System.out.println("[" + this + "] INFO: FASTPATH_UPDATETYPE_COLOR."); + + break; + + case FASTPATH_UPDATETYPE_CACHED: + if (verbose) + System.out.println("[" + this + "] INFO: FASTPATH_UPDATETYPE_CACHED."); + + break; + + case FASTPATH_UPDATETYPE_POINTER: + if (verbose) + System.out.println("[" + this + "] INFO: FASTPATH_UPDATETYPE_POINTER."); + + break; + + default: + throw new RuntimeException("Unknown FastPath update. UpdateCode: " + updateCode + ", fragmentation: " + fragmentation + ", compression: " + compression + + ", size: " + size + ", data: " + data + "."); + + } + buf.unref(); + + } + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerIOChannelRouter.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerIOChannelRouter.java new file mode 100755 index 00000000000..dad3548d593 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerIOChannelRouter.java @@ -0,0 +1,534 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.rdp; + +import streamer.BaseElement; +import streamer.ByteBuffer; +import streamer.Element; +import streamer.Link; +import streamer.Pipeline; +import streamer.PipelineImpl; +import streamer.debug.MockSink; +import streamer.debug.MockSource; + +public class ServerIOChannelRouter extends BaseElement { + + /** + * Demand Active PDU. + */ + public static final int PDUTYPE_DEMANDACTIVEPDU = 0x1; + + /** + * Confirm Active PDU. + */ + public static final int PDUTYPE_CONFIRMACTIVEPDU = 0x3; + + /** + * Deactivate All PDU. + */ + public static final int PDUTYPE_DEACTIVATEALLPDU = 0x6; + + /** + * Data PDU (actual type is revealed by the pduType2 field in the Share Data + * Header). + */ + public static final int PDUTYPE_DATAPDU = 0x7; + + /** + * Enhanced Security Server Redirection PDU. + */ + public static final int PDUTYPE_SERVER_REDIR_PKT = 0xA; + + protected RdpState state; + + public ServerIOChannelRouter(String id, RdpState state) { + super(id); + this.state = state; + } + + /** + * @see http://msdn.microsoft.com/en-us/library/cc240576.aspx + */ + @Override + public void handleData(ByteBuffer buf, Link link) { + if (verbose) + System.out.println("[" + this + "] INFO: Data received: " + buf + "."); + + int length = buf.readUnsignedShortLE(); + if (buf.length != length) + { + // It is ServerErrorAlert-ValidClient + // Ignore it + //throw new RuntimeException("[" + this + "] ERROR: Incorrect PDU length: " + length + ", data: " + buf + "."); + } + + int type = buf.readUnsignedShortLE() & 0xf; + + // int sourceId = buf.readUnsignedShortLE(); + buf.skipBytes(2); + + switch (type) { + case PDUTYPE_DEMANDACTIVEPDU: + pushDataToPad("demand_active", buf); + break; + case PDUTYPE_CONFIRMACTIVEPDU: + throw new RuntimeException("Unexpected client CONFIRM ACTIVE PDU. Data: " + buf + "."); + case PDUTYPE_DEACTIVATEALLPDU: + // pushDataToPad("deactivate_all", buf); + /* ignore */buf.unref(); + break; + case PDUTYPE_DATAPDU: + handleDataPdu(buf); + break; + case PDUTYPE_SERVER_REDIR_PKT: + // pushDataToPad("server_redir", buf); + /* ignore */buf.unref(); + break; + default: + throw new RuntimeException("[" + this + "] ERROR: Unknown PDU type: " + type + ", data: " + buf + "."); + } + + } + + /** + * Graphics Update PDU. + */ + public static final int PDUTYPE2_UPDATE = 0x02; + + /** + * Control PDU. + */ + public static final int PDUTYPE2_CONTROL = 0x14; + + /** + * Pointer Update PDU. + */ + public static final int PDUTYPE2_POINTER = 0x1B; + + /** + * Input Event PDU. + */ + public static final int PDUTYPE2_INPUT = 0x1C; + + /** + * Synchronize PDU. + */ + public static final int PDUTYPE2_SYNCHRONIZE = 0x1F; + + /** + * Refresh Rect PDU. + */ + public static final int PDUTYPE2_REFRESH_RECT = 0x21; + + /** + * Play Sound PDU. + */ + public static final int PDUTYPE2_PLAY_SOUND = 0x22; + + /** + * Suppress Output PDU. + */ + public static final int PDUTYPE2_SUPPRESS_OUTPUT = 0x23; + + /** + * Shutdown Request PDU. + */ + public static final int PDUTYPE2_SHUTDOWN_REQUEST = 0x24; + + /** + * Shutdown Request Denied PDU. + */ + public static final int PDUTYPE2_SHUTDOWN_DENIED = 0x25; + + /** + * Save Session Info PDU. + */ + public static final int PDUTYPE2_SAVE_SESSION_INFO = 0x26; + + /** + * Font List PDU. + */ + public static final int PDUTYPE2_FONTLIST = 0x27; + + /** + * Font Map PDU. + */ + public static final int PDUTYPE2_FONTMAP = 0x28; + + /** + * Set Keyboard Indicators PDU. + */ + public static final int PDUTYPE2_SET_KEYBOARD_INDICATORS = 0x29; + + /** + * Persistent Key List PDU. + */ + public static final int PDUTYPE2_BITMAPCACHE_PERSISTENT_LIST = 0x2B; + + /** + * Bitmap Cache Error PDU. + */ + public static final int PDUTYPE2_BITMAPCACHE_ERROR_PDU = 0x2C; + + /** + * Set Keyboard IME Status PDU. + */ + public static final int PDUTYPE2_SET_KEYBOARD_IME_STATUS = 0x2D; + + /** + * Offscreen Bitmap Cache Error PDU. + */ + public static final int PDUTYPE2_OFFSCRCACHE_ERROR_PDU = 0x2E; + + /** + * Set Error Info PDU. + */ + public static final int PDUTYPE2_SET_ERROR_INFO_PDU = 0x2F; + + /** + * DrawNineGrid Cache Error PDU. + */ + public static final int PDUTYPE2_DRAWNINEGRID_ERROR_PDU = 0x30; + + /** + * GDI+ Error PDU. + */ + public static final int PDUTYPE2_DRAWGDIPLUS_ERROR_PDU = 0x31; + + /** + * Auto-Reconnect Status PDU. + */ + public static final int PDUTYPE2_ARC_STATUS_PDU = 0x32; + + /** + * Status Info PDU. + */ + public static final int PDUTYPE2_STATUS_INFO_PDU = 0x36; + + /** + * Monitor Layout PDU. + */ + public static final int PDUTYPE2_MONITOR_LAYOUT_PDU = 0x37; + + /** + * Indicates an Orders Update. + */ + public static final int UPDATETYPE_ORDERS = 0x0000; + + /** + * Indicates a Bitmap Graphics Update. + */ + public static final int UPDATETYPE_BITMAP = 0x0001; + + /** + * Indicates a Palette Update. + */ + public static final int UPDATETYPE_PALETTE = 0x0002; + + /** + * Indicates a Synchronize Update. + */ + public static final int UPDATETYPE_SYNCHRONIZE = 0x0003; + + /** + * @see http://msdn.microsoft.com/en-us/library/cc240577.aspx + */ + protected void handleDataPdu(ByteBuffer buf) { + + // (4 bytes): A 32-bit, unsigned integer. Share identifier for the packet. + long shareId = buf.readUnsignedIntLE(); + if (shareId != state.serverShareId) + throw new RuntimeException("Unexpected share ID: " + shareId + "."); +// buf.skipBytes(4); + + // Padding. + buf.skipBytes(1); + + // (1 byte): An 8-bit, unsigned integer. The stream identifier for the + // packet. + // int streamId = buf.readUnsignedByte(); + buf.skipBytes(1); + + // (2 bytes): A 16-bit, unsigned integer. The uncompressed length of the + // packet in bytes. + int uncompressedLength = buf.readUnsignedShortLE(); + + // (1 byte): An 8-bit, unsigned integer. The type of Data PDU. + int type2 = buf.readUnsignedByte(); + + // (1 byte): An 8-bit, unsigned integer. The compression type and flags + // specifying the data following the Share Data Header + int compressedType = buf.readUnsignedByte(); + if (compressedType != 0) + throw new RuntimeException("Compression of protocol packets is not supported. Data: " + buf + "."); + + // (2 bytes): A 16-bit, unsigned integer. The compressed length of the + // packet in bytes. + int compressedLength = buf.readUnsignedShortLE(); + if (compressedLength != 0) + throw new RuntimeException("Compression of protocol packets is not supported. Data: " + buf + "."); + + ByteBuffer data = buf.readBytes(uncompressedLength - 18); + buf.unref(); + + switch (type2) { + + case PDUTYPE2_UPDATE: { + + // (2 bytes): A 16-bit, unsigned integer. Type of the graphics update. + int updateType = data.readUnsignedShortLE(); + ByteBuffer payload = data.readBytes(data.length - data.cursor); + data.unref(); + + switch (updateType) { + case UPDATETYPE_ORDERS: + pushDataToPad("orders", payload); + break; + case UPDATETYPE_BITMAP: + pushDataToPad("bitmap", payload); + break; + case UPDATETYPE_PALETTE: + pushDataToPad("palette", payload); + break; + case UPDATETYPE_SYNCHRONIZE: + // Ignore + payload.unref(); + break; + } + + break; + } + case PDUTYPE2_CONTROL: + if (verbose) + System.out.println("[" + this + "] INFO: Packet PDUTYPE2_CONTROL ignored."); + // Ignore + data.unref(); + break; + case PDUTYPE2_POINTER: + if (verbose) + System.out.println("[" + this + "] INFO: Packet PDUTYPE2_POINTER ignored."); + // Ignore + data.unref(); + break; + case PDUTYPE2_INPUT: + if (verbose) + System.out.println("[" + this + "] INFO: Packet PDUTYPE2_INPUT ignored."); + // Ignore + data.unref(); + break; + case PDUTYPE2_SYNCHRONIZE: + if (verbose) + System.out.println("[" + this + "] INFO: Packet PDUTYPE2_SYNCHRONIZE ignored."); + // Ignore + data.unref(); + break; + case PDUTYPE2_REFRESH_RECT: + if (verbose) + System.out.println("[" + this + "] INFO: Packet PDUTYPE2_REFRESH_RECT ignored."); + // Ignore + data.unref(); + break; + case PDUTYPE2_PLAY_SOUND: + if (verbose) + System.out.println("[" + this + "] INFO: Packet PDUTYPE2_PLAY_SOUND ignored."); + // Ignore + data.unref(); + break; + case PDUTYPE2_SUPPRESS_OUTPUT: + if (verbose) + System.out.println("[" + this + "] INFO: Packet PDUTYPE2_SUPPRESS_OUTPUT ignored."); + // Ignore + data.unref(); + break; + case PDUTYPE2_SHUTDOWN_REQUEST: + if (verbose) + System.out.println("[" + this + "] INFO: Packet PDUTYPE2_SHUTDOWN_REQUEST ignored."); + // Ignore + data.unref(); + break; + case PDUTYPE2_SHUTDOWN_DENIED: + if (verbose) + System.out.println("[" + this + "] INFO: Packet PDUTYPE2_SHUTDOWN_DENIED ignored."); + // Ignore + data.unref(); + break; + case PDUTYPE2_SAVE_SESSION_INFO: + if (verbose) + System.out.println("[" + this + "] INFO: Packet PDUTYPE2_SAVE_SESSION_INFO ignored."); + // Ignore + data.unref(); + break; + case PDUTYPE2_FONTLIST: + if (verbose) + System.out.println("[" + this + "] INFO: Packet PDUTYPE2_FONTLIST ignored."); + // Ignore + data.unref(); + break; + case PDUTYPE2_FONTMAP: + if (verbose) + System.out.println("[" + this + "] INFO: Packet PDUTYPE2_FONTMAP ignored."); + // Ignore + data.unref(); + break; + case PDUTYPE2_SET_KEYBOARD_INDICATORS: + if (verbose) + System.out.println("[" + this + "] INFO: Packet PDUTYPE2_SET_KEYBOARD_INDICATORS ignored."); + // Ignore + data.unref(); + break; + case PDUTYPE2_BITMAPCACHE_PERSISTENT_LIST: + if (verbose) + System.out.println("[" + this + "] INFO: Packet PDUTYPE2_BITMAPCACHE_PERSISTENT_LIST ignored."); + // Ignore + data.unref(); + break; + case PDUTYPE2_BITMAPCACHE_ERROR_PDU: + if (verbose) + System.out.println("[" + this + "] INFO: Packet PDUTYPE2_BITMAPCACHE_ERROR_PDU ignored."); + // Ignore + data.unref(); + break; + case PDUTYPE2_SET_KEYBOARD_IME_STATUS: + if (verbose) + System.out.println("[" + this + "] INFO: Packet PDUTYPE2_SET_KEYBOARD_IME_STATUS ignored."); + // Ignore + data.unref(); + break; + case PDUTYPE2_OFFSCRCACHE_ERROR_PDU: + if (verbose) + System.out.println("[" + this + "] INFO: Packet PDUTYPE2_OFFSCRCACHE_ERROR_PDU ignored."); + // Ignore + data.unref(); + break; + case PDUTYPE2_SET_ERROR_INFO_PDU: + if (verbose) + System.out.println("[" + this + "] INFO: Packet PDUTYPE2_SET_ERROR_INFO_PDU ignored."); + // Ignore + data.unref(); + break; + case PDUTYPE2_DRAWNINEGRID_ERROR_PDU: + if (verbose) + System.out.println("[" + this + "] INFO: Packet PDUTYPE2_DRAWNINEGRID_ERROR_PDU ignored."); + // Ignore + data.unref(); + break; + case PDUTYPE2_DRAWGDIPLUS_ERROR_PDU: + if (verbose) + System.out.println("[" + this + "] INFO: Packet PDUTYPE2_DRAWGDIPLUS_ERROR_PDU ignored."); + // Ignore + data.unref(); + break; + case PDUTYPE2_ARC_STATUS_PDU: + if (verbose) + System.out.println("[" + this + "] INFO: Packet PDUTYPE2_ARC_STATUS_PDU ignored."); + // Ignore + data.unref(); + break; + case PDUTYPE2_STATUS_INFO_PDU: + if (verbose) + System.out.println("[" + this + "] INFO: Packet PDUTYPE2_STATUS_INFO_PDU ignored."); + // Ignore + data.unref(); + break; + case PDUTYPE2_MONITOR_LAYOUT_PDU: + if (verbose) + System.out.println("[" + this + "] INFO: Packet PDUTYPE2_MONITOR_LAYOUT_PDU ignored."); + // Ignore + data.unref(); + break; + + default: + throw new RuntimeException("Unknow data PDU type: " + type2 + ", data: " + buf + "."); + } + } + + /** + * Example. + * + */ + public static void main(String args[]) { + // System.setProperty("streamer.Link.debug", "true"); + System.setProperty("streamer.Element.debug", "true"); + // System.setProperty("streamer.Pipeline.debug", "true"); + + byte[] packet = new byte[] { + // TPKT + (byte)0x03, (byte)0x00, // TPKT Header: TPKT version = 3 + (byte)0x00, (byte)0x1B, // TPKT length: 27 bytes + + // X224 + (byte)0x02, // X224 Length: 2 bytes + (byte)0xF0, // X224 Type: Data + (byte)0x80, // X224 EOT + + // MCS + // Type: send data indication: 26 (0x1a, top 6 bits) + (byte)0x68, // ?? + + (byte)0x00, (byte)0x01, // User ID: 1002 (1001+1) + (byte)0x03, (byte)0xEB, // Channel ID: 1003 + (byte)0x70, // Data priority: high, segmentation: begin|end + (byte)0x0D, // Payload length: 13 bytes + + // Deactivate all PDU + (byte)0x0D, (byte)0x00, // Length: 13 bytes (LE) + + // - PDUType: (0x16, LE) + // Type: (............0110) TS_PDUTYPE_DEACTIVATEALLPDU + // ProtocolVersion: (000000000001....) 1 + (byte)0x16, (byte)0x00, + + (byte)0xEA, (byte)0x03, // PDU source: 1002 (LE) + (byte)0xEA, (byte)0x03, (byte)0x01, (byte)0x00, // ShareID = 66538 + + (byte)0x01, (byte)0x00, // Length if source descriptor: 1 (LE) + (byte)0x00, // Source descriptor (should be set to 0): 0 + }; + + MockSource source = new MockSource("source", ByteBuffer.convertByteArraysToByteBuffers(packet)); + RdpState rdpState = new RdpState() { + { + serverShareId = 66538; + } + }; + Element channel1003 = new ServerIOChannelRouter("channel_1003", rdpState); + Element mcs = new ServerMCSPDU("mcs"); + Element tpkt = new ServerTpkt("tpkt"); + Element x224 = new ServerX224DataPdu("x224"); + Element sink = new MockSink("sink", ByteBuffer.convertByteArraysToByteBuffers(new byte[] { + // Deactivate all PDU + (byte)0x0D, (byte)0x00, // Length: 13 bytes (LE) + + // - PDUType: 22 (0x16, LE) + // Type: (............0110) TS_PDUTYPE_DEACTIVATEALLPDU + // ProtocolVersion: (000000000001....) 1 + (byte)0x16, (byte)0x00, + + (byte)0xEA, (byte)0x03, // PDU source: 1002 (LE) + (byte)0xEA, (byte)0x03, (byte)0x01, (byte)0x00, // ShareID = 66538 + + (byte)0x01, (byte)0x00, // Length if source descriptor: 1 (LE) + (byte)0x00, // Source descriptor (should be set to 0): 0 + })); + + Pipeline pipeline = new PipelineImpl("test"); + pipeline.add(source, tpkt, x224, mcs, channel1003, sink); + pipeline.link("source", "tpkt", "x224", "mcs >channel_1003", "channel_1003 >deactivate_all", "sink"); + pipeline.runMainLoop("source", STDOUT, false, false); + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerLicenseErrorPDUValidClient.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerLicenseErrorPDUValidClient.java old mode 100644 new mode 100755 similarity index 99% rename from services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerLicenseErrorPDUValidClient.java rename to services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerLicenseErrorPDUValidClient.java index 7384c95a212..22e809442dc --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerLicenseErrorPDUValidClient.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerLicenseErrorPDUValidClient.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package rdpclient; +package rdpclient.rdp; import streamer.ByteBuffer; import streamer.Link; diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerMCSAttachUserConfirmPDU.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerMCSAttachUserConfirmPDU.java old mode 100644 new mode 100755 similarity index 75% rename from services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerMCSAttachUserConfirmPDU.java rename to services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerMCSAttachUserConfirmPDU.java index b4462534c5a..cbefcb93b69 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerMCSAttachUserConfirmPDU.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerMCSAttachUserConfirmPDU.java @@ -14,16 +14,16 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package rdpclient; +package rdpclient.rdp; import streamer.ByteBuffer; import streamer.Element; import streamer.Link; -import streamer.MockSink; -import streamer.MockSource; import streamer.OneTimeSwitch; import streamer.Pipeline; import streamer.PipelineImpl; +import streamer.debug.MockSink; +import streamer.debug.MockSource; /** * Server response to MCS Attach User request. @@ -56,8 +56,7 @@ public class ServerMCSAttachUserConfirmPDU extends OneTimeSwitch { int flags = typeAndFlags & 0x3; if (type != MCS_ATTACH_USER_CONFIRM_PDU) - throw new RuntimeException("[" + this + "] ERROR: Incorrect type of MCS AttachUserConfirm PDU. Expected value: 11, actual value: " + type + ", data: " + buf + - "."); + throw new RuntimeException("[" + this + "] ERROR: Incorrect type of MCS AttachUserConfirm PDU. Expected value: 11, actual value: " + type + ", data: " + buf + "."); if (flags != INITIATOR_PRESENT) throw new RuntimeException("Initator field is not present in MCS AttachUserConfirm PDU. Data: " + buf + "."); @@ -92,11 +91,11 @@ public class ServerMCSAttachUserConfirmPDU extends OneTimeSwitch { // System.setProperty("streamer.Pipeline.debug", "true"); byte[] packet = new byte[] {(byte)0x2E, // MCS user confirm (001011.., - // 0xb), InitiatorPresent: 1 - // (......01, 0x1) - (byte)0x00, // RT successfull (0000...., 0x0) - // Initiator: 1001+3 = 1004 - (byte)0x00, (byte)0x03,}; + // 0xb), InitiatorPresent: 1 + // (......01, 0x1) + (byte)0x00, // RT successfull (0000...., 0x0) + // Initiator: 1001+3 = 1004 + (byte)0x00, (byte)0x03,}; RdpState rdpState = new RdpState(); MockSource source = new MockSource("source", ByteBuffer.convertByteArraysToByteBuffers(packet, new byte[] {1, 2, 3})); @@ -115,20 +114,3 @@ public class ServerMCSAttachUserConfirmPDU extends OneTimeSwitch { } } - -/* - * 03 00 00 0B 02 F0 80 2E 00 00 03. - * - * Frame: Number = 18, Captured Frame Length = 68, MediaType = - * DecryptedPayloadHeader + DecryptedPayloadHeader: FrameCount = 1, ErrorStatus - * = SUCCESS TLSSSLData: Transport Layer Security (TLS) Payload Data + TLS: TLS - * Rec Layer-1 SSL Application Data ISOTS: TPKTCount = 1 - TPKT: version: 3, - * Length: 11 version: 3 (0x3) Reserved: 0 (0x0) PacketLength: 11 (0xB) - X224: - * Data Length: 2 (0x2) Type: Data EOT: 128 (0x80) - T125: Attach User Confirm, - * Result = rt-successful, Indicator = 0x3ec - MCSHeader: Type=Attach User - * Confirm - Type: Attach User Confirm - RootIndex: 11 Value: (001011..) 0xb - - * MCSAttachUserConfirm: Result = rt-successful, Indicator = 0x3ec - * InitiatorPresent: 1 (0x1) - Result: rt-successful - Result: rt-successful - - * RootIndex: 0 Value: (0000....) 0x0 - Initiator: 0x3ec - UserID: 0x3ec - - * ChannelId: 1004 - Align: No Padding Padding5: (00000...) 0x0 Value: 3 (0x3) - */ diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerMCSChannelJoinConfirmPDU.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerMCSChannelJoinConfirmPDU.java old mode 100644 new mode 100755 similarity index 99% rename from services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerMCSChannelJoinConfirmPDU.java rename to services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerMCSChannelJoinConfirmPDU.java index e753cd9a99f..d3a5954b4e8 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerMCSChannelJoinConfirmPDU.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerMCSChannelJoinConfirmPDU.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package rdpclient; +package rdpclient.rdp; import streamer.ByteBuffer; import streamer.Link; diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerMCSConnectResponse.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerMCSConnectResponse.java old mode 100644 new mode 100755 similarity index 99% rename from services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerMCSConnectResponse.java rename to services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerMCSConnectResponse.java index 030edbf683e..a62ae8b9518 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerMCSConnectResponse.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerMCSConnectResponse.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package rdpclient; +package rdpclient.rdp; import streamer.ByteBuffer; import streamer.Link; @@ -193,7 +193,7 @@ public class ServerMCSConnectResponse extends OneTimeSwitch { TagValue: (...00100) 4 - AsnLen: Length = 54, LengthOfLength = 0 Length: 54 bytes, LengthOfLength = 0 - - AsnBerObjectIdentifier: Generic Conference Contro (0.0.20.124.0.1) + - AsnBerObjectIdentifier: Generic Conference Control (0.0.20.124.0.1) - AsnObjectIdentifierHeader: - AsnId: Reserved for use by the encoding rules (Universal 0) - LowTag: diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerMCSPDU.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerMCSPDU.java new file mode 100755 index 00000000000..d28d0a09f70 --- /dev/null +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerMCSPDU.java @@ -0,0 +1,149 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package rdpclient.rdp; + +import streamer.BaseElement; +import streamer.ByteBuffer; +import streamer.Element; +import streamer.Link; +import streamer.Pipeline; +import streamer.PipelineImpl; +import streamer.debug.MockSink; +import streamer.debug.MockSource; + +public class ServerMCSPDU extends BaseElement { + + public ServerMCSPDU(String id) { + super(id); + } + + @Override + public void handleData(ByteBuffer buf, Link link) { + if (verbose) + System.out.println("[" + this + "] INFO: Data received: " + buf + "."); + + byte headerByte = buf.readSignedByte(); + int type = headerByte >> 2; + + switch (type) { + // Expected type: send data indication: 26 (0x1a, top 6 bits, or 0x68) + case 0x1a: { + // int userId = buf.readUnsignedShort() + 1001; // User ID: 1002 (1001+1) + buf.skipBytes(2); // Ignore user ID + + int channelId = buf.readUnsignedShort(); // Channel ID: 1003 + + int flags = buf.readSignedByte(); + if ((flags & 0x30) != 0x30) + throw new RuntimeException("Fragmented MCS packets are not supported."); + + int payloadLength = buf.readVariableUnsignedShort(); + + ByteBuffer data = buf.readBytes(payloadLength); + + buf.unref(); + + pushDataToPad("channel_" + channelId, data); + break; + } + + case 0x8: { + // Disconnection sequence. + buf.unref(); + break; + } + + default: + throw new RuntimeException("Unsupported MCS packet type: " + type + "(" + headerByte + "), data: " + buf + "."); + } + + } + + /** + * Example. + * + */ + public static void main(String args[]) { + // System.setProperty("streamer.Link.debug", "true"); + // System.setProperty("streamer.Element.debug", "true"); + // System.setProperty("streamer.Pipeline.debug", "true"); + + byte[] packet = new byte[] { + // TPKT + (byte)0x03, (byte)0x00, // TPKT Header: TPKT version = 3 + (byte)0x00, (byte)0x1B, // TPKT length: 27 bytes + + // X224 + (byte)0x02, // X224 Length: 2 bytes + (byte)0xF0, // X224 Type: Data + (byte)0x80, // X224 EOT + + // MCS + // Type: send data indication: 26 (0x1a, top 6 bits) + (byte)0x68, // ?? + + (byte)0x00, (byte)0x01, // User ID: 1002 (1001+1) + (byte)0x03, (byte)0xEB, // Channel ID: 1003 + (byte)0x70, // Data priority: high, segmentation: begin|end + (byte)0x0D, // Payload length: 13 bytes + + // Deactivate all PDU + (byte)0x0D, (byte)0x00, // Length: 13 bytes (LE) + + // - PDUType: 22 (0x16, LE) + // Type: (............0110) TS_PDUTYPE_DEACTIVATEALLPDU + // ProtocolVersion: (000000000001....) 1 + (byte)0x16, (byte)0x00, + + (byte)0xEA, (byte)0x03, // PDU source: 1002 (LE) + (byte)0xEA, (byte)0x03, (byte)0x01, (byte)0x00, // ShareID = 66538 + + (byte)0x01, (byte)0x00, // Length if source descriptor: 1 (LE) + (byte)0x00, // Source descriptor (should be set to 0): 0 + }; + + MockSource source = new MockSource("source", ByteBuffer.convertByteArraysToByteBuffers(packet)); + Element mcs = new ServerMCSPDU("mcs") { + { + verbose = true; + } + }; + Element tpkt = new ServerTpkt("tpkt"); + Element x224 = new ServerX224DataPdu("x224"); + Element sink = new MockSink("sink", ByteBuffer.convertByteArraysToByteBuffers(new byte[] { + // Deactivate all PDU + (byte)0x0D, (byte)0x00, // Length: 13 bytes (LE) + + // - PDUType: 22 (0x16, LE) + // Type: (............0110) TS_PDUTYPE_DEACTIVATEALLPDU + // ProtocolVersion: (000000000001....) 1 + (byte)0x16, (byte)0x00, + + (byte)0xEA, (byte)0x03, // PDU source: 1002 (LE) + (byte)0xEA, (byte)0x03, (byte)0x01, (byte)0x00, // ShareID = 66538 + + (byte)0x01, (byte)0x00, // Length if source descriptor: 1 (LE) + (byte)0x00, // Source descriptor (should be set to 0): 0 + })); + + Pipeline pipeline = new PipelineImpl("test"); + pipeline.add(source, tpkt, x224, mcs, sink); + pipeline.link("source", "tpkt", "x224", "mcs >channel_1003", "sink"); + pipeline.runMainLoop("source", STDOUT, false, false); + } + +} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerPaletteUpdate.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerPaletteUpdate.java old mode 100644 new mode 100755 similarity index 96% rename from services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerPaletteUpdate.java rename to services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerPaletteUpdate.java index 8fb2fe0498b..606bd89fa84 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerPaletteUpdate.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerPaletteUpdate.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package rdpclient; +package rdpclient.rdp; import java.awt.image.IndexColorModel; @@ -57,8 +57,8 @@ public class ServerPaletteUpdate extends BaseElement { // in an 8 bpp palette). int numberColors = (int)buf.readUnsignedIntLE(); if (numberColors != 256) - throw new RuntimeException("Unexpected value for number of color field in server Palette Update packet. Expected value: 256 colors, actual value: " + - numberColors + ", data: " + buf + "."); + throw new RuntimeException("Unexpected value for number of color field in server Palette Update packet. Expected value: 256 colors, actual value: " + + numberColors + ", data: " + buf + "."); // (variable): An array of palette entries in RGB triplet format packed on // byte boundaries. The number of triplet entries is given by the diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerSynchronizePDU.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerSynchronizePDU.java old mode 100644 new mode 100755 similarity index 99% rename from services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerSynchronizePDU.java rename to services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerSynchronizePDU.java index ad8704deb92..f464a4a887d --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerSynchronizePDU.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerSynchronizePDU.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package rdpclient; +package rdpclient.rdp; import streamer.ByteBuffer; import streamer.Link; diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerTpkt.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerTpkt.java old mode 100644 new mode 100755 similarity index 98% rename from services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerTpkt.java rename to services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerTpkt.java index 240c6243459..d9662d216f9 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerTpkt.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerTpkt.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package rdpclient; +package rdpclient.rdp; import streamer.BaseElement; import streamer.ByteBuffer; diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerX224ConnectionConfirmPDU.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerX224ConnectionConfirmPDU.java old mode 100644 new mode 100755 similarity index 73% rename from services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerX224ConnectionConfirmPDU.java rename to services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerX224ConnectionConfirmPDU.java index c320573dc33..5a8dfaf4eeb --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerX224ConnectionConfirmPDU.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerX224ConnectionConfirmPDU.java @@ -14,16 +14,16 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package rdpclient; +package rdpclient.rdp; import streamer.ByteBuffer; import streamer.Element; import streamer.Link; -import streamer.MockSink; -import streamer.MockSource; import streamer.OneTimeSwitch; import streamer.Pipeline; import streamer.PipelineImpl; +import streamer.debug.MockSink; +import streamer.debug.MockSource; /** * Once the External Security Protocol handshake has run to completion, the @@ -100,8 +100,8 @@ public class ServerX224ConnectionConfirmPDU extends OneTimeSwitch { int x224Type = buf.readUnsignedByte(); if (x224Type != X224_TPDU_CONNECTION_CONFIRM) - throw new RuntimeException("Unexpected type of packet. Expected type: " + X224_TPDU_CONNECTION_CONFIRM + " (CONNECTION CONFIRM), actual type: " + x224Type + - ", length: " + x224Length + ", buf: " + buf + "."); + throw new RuntimeException("Unexpected type of packet. Expected type: " + X224_TPDU_CONNECTION_CONFIRM + " (CONNECTION CONFIRM), actual type: " + + x224Type + ", length: " + x224Length + ", buf: " + buf + "."); // Ignore destination reference, because client side has only one node buf.skipBytes(2); @@ -134,39 +134,36 @@ public class ServerX224ConnectionConfirmPDU extends OneTimeSwitch { int errorCode = protocol; String message = "Unknown error."; switch (errorCode) { - case SSL_REQUIRED_BY_SERVER: - message = - "The server requires that the client support Enhanced RDP Security with either TLS 1.0, 1.1 or 1.2 or CredSSP. If only CredSSP was requested then the server only supports TLS."; - break; + case SSL_REQUIRED_BY_SERVER: + message = "The server requires that the client support Enhanced RDP Security with either TLS 1.0, 1.1 or 1.2 or CredSSP. If only CredSSP was requested then the server only supports TLS."; + break; - case SSL_NOT_ALLOWED_BY_SERVER: - message = "The server is configured to only use Standard RDP Security mechanisms and does not support any External Security Protocols."; - break; + case SSL_NOT_ALLOWED_BY_SERVER: + message = "The server is configured to only use Standard RDP Security mechanisms and does not support any External Security Protocols."; + break; - case SSL_CERT_NOT_ON_SERVER: - message = "The server does not possess a valid authentication certificate and cannot initialize the External Security Protocol Provider."; - break; + case SSL_CERT_NOT_ON_SERVER: + message = "The server does not possess a valid authentication certificate and cannot initialize the External Security Protocol Provider."; + break; - case INCONSISTENT_FLAGS: - message = - "The list of requested security protocols is not consistent with the current security protocol in effect. This error is only possible when the Direct Approach is used and an External Security Protocolis already being used."; - break; + case INCONSISTENT_FLAGS: + message = "The list of requested security protocols is not consistent with the current security protocol in effect. This error is only possible when the Direct Approach is used and an External Security Protocolis already being used."; + break; - case HYBRID_REQUIRED_BY_SERVER: - message = "The server requires that the client support Enhanced RDP Security with CredSSP."; - break; + case HYBRID_REQUIRED_BY_SERVER: + message = "The server requires that the client support Enhanced RDP Security with CredSSP."; + break; - case SSL_WITH_USER_AUTH_REQUIRED_BY_SERVER: - message = "The server requires that the client support Enhanced RDP Security with TLS 1.0, 1.1 or 1.2 and certificate-based client authentication."; - break; + case SSL_WITH_USER_AUTH_REQUIRED_BY_SERVER: + message = "The server requires that the client support Enhanced RDP Security with TLS 1.0, 1.1 or 1.2 and certificate-based client authentication."; + break; } throw new RuntimeException("Connection failure: " + message); } - if (protocol != RdpConstants.RDP_NEG_REQ_PROTOCOL_SSL) - throw new RuntimeException("Unexpected protocol type. Expected protocol type: " + RdpConstants.RDP_NEG_REQ_PROTOCOL_SSL + " (SSL), actual response type: " + - protocol + ", RDP NEG buf: " + buf + "."); + if (protocol != RdpConstants.RDP_NEG_REQ_PROTOCOL_SSL && protocol != RdpConstants.RDP_NEG_REQ_PROTOCOL_HYBRID) + throw new RuntimeException("Unexpected protocol type (nor SSL, nor HYBRID (SSL+CredSSP)): " + protocol + ", RDP NEG buf: " + buf + "."); if (verbose) System.out.println("[" + this + "] INFO: RDP Negotiation response. Type: " + negType + ", protocol: " + protocol + "."); @@ -206,19 +203,19 @@ public class ServerX224ConnectionConfirmPDU extends OneTimeSwitch { // 03 00 00 13 0e d0 00 00 12 34 00 03 00 08 00 05 00 00 00 byte[] packet = new byte[] { - 0x03, // -> TPKT Header: TPKT version = 3 - 0x00, // TPKT Header: Reserved = 0 - 0x00, 0x13, // TPKT Header: Packet length - (total = 19 bytes) - 0x0e, // X.224: Length indicator (14 bytes) - (byte)0xd0, // X.224: Type (high nibble) = 0xd = CC TPDU; credit - // (low nibble) = 0 - 0x00, 0x00, // X.224: Destination reference = 0 - 0x12, 0x34, // X.224: Source reference = 0x1234 (bogus value) - 0x00, // X.224: Class and options = 0 - (byte)0x03, // Failure - (byte)0x00, // RDP_NEG_RSP::flags (0) - (byte)0x08, (byte)0x00, // RDP_NEG_RSP::length (8 bytes) - (byte)0x05, (byte)0x00, (byte)0x00, (byte)0x00, // Code: HYBRID_REQUIRED_BY_SERVER + 0x03, // -> TPKT Header: TPKT version = 3 + 0x00, // TPKT Header: Reserved = 0 + 0x00, 0x13, // TPKT Header: Packet length - (total = 19 bytes) + 0x0e, // X.224: Length indicator (14 bytes) + (byte)0xd0, // X.224: Type (high nibble) = 0xd = CC TPDU; credit + // (low nibble) = 0 + 0x00, 0x00, // X.224: Destination reference = 0 + 0x12, 0x34, // X.224: Source reference = 0x1234 (bogus value) + 0x00, // X.224: Class and options = 0 + (byte)0x03, // Failure + (byte)0x00, // RDP_NEG_RSP::flags (0) + (byte)0x08, (byte)0x00, // RDP_NEG_RSP::length (8 bytes) + (byte)0x05, (byte)0x00, (byte)0x00, (byte)0x00, // Code: HYBRID_REQUIRED_BY_SERVER }; diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerX224DataPdu.java b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerX224DataPdu.java old mode 100644 new mode 100755 similarity index 88% rename from services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerX224DataPdu.java rename to services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerX224DataPdu.java index 62b0f557adf..2c0087e0fe1 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/ServerX224DataPdu.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/rdp/ServerX224DataPdu.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package rdpclient; +package rdpclient.rdp; import streamer.BaseElement; import streamer.ByteBuffer; @@ -46,14 +46,14 @@ public class ServerX224DataPdu extends BaseElement { int type = buf.readUnsignedByte(); // High nibble: type, low nibble: if ((type & 0xf0) != X224_TPDU_DATA) - throw new RuntimeException("[" + this + "] ERROR: Unexepcted X224 packet type. Expected packet type: " + X224_TPDU_DATA + - " (X224_TPDU_DATA), actual packet type: " + type + ", buf: " + buf + "."); + throw new RuntimeException("[" + this + "] ERROR: Unexepcted X224 packet type. Expected packet type: " + X224_TPDU_DATA + + " (X224_TPDU_DATA), actual packet type: " + type + ", buf: " + buf + "."); int options = buf.readUnsignedByte(); if ((options & X224_TPDU_LAST_DATA_UNIT) != X224_TPDU_LAST_DATA_UNIT) - throw new RuntimeException("Unexepcted X224 packet options. Expected options: " + X224_TPDU_LAST_DATA_UNIT + - " (X224_TPDU_LAST_DATA_UNIT), actual packet options: " + options + ", buf: " + buf + "."); + throw new RuntimeException("Unexepcted X224 packet options. Expected options: " + X224_TPDU_LAST_DATA_UNIT + + " (X224_TPDU_LAST_DATA_UNIT), actual packet options: " + options + ", buf: " + buf + "."); ByteBuffer payload = buf.readBytes(buf.length - buf.cursor); diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/BaseElement.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/BaseElement.java old mode 100644 new mode 100755 index dd2b541b202..1ca68ceaa80 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/BaseElement.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/BaseElement.java @@ -21,6 +21,9 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Set; +import streamer.debug.FakeSink; +import streamer.debug.FakeSource; + public class BaseElement implements Element { protected String id; @@ -78,11 +81,11 @@ public class BaseElement implements Element { @Override public Set getPads(Direction direction) { switch (direction) { - case IN: - return inputPads.keySet(); + case IN: + return inputPads.keySet(); - case OUT: - return outputPads.keySet(); + case OUT: + return outputPads.keySet(); } return null; } @@ -103,24 +106,24 @@ public class BaseElement implements Element { @Override public void setLink(String padName, Link link, Direction direction) { switch (direction) { - case IN: - if (inputPads.get(padName) != null) - throw new RuntimeException("Cannot link more than one wire to same pad. Element: " + this + ", pad: " + padName + ":" + direction + ", new link: " + - link + ", existing link: " + inputPads.get(padName) + "."); - inputPads.put(padName, link); - link.setSink(this); + case IN: + if (inputPads.get(padName) != null) + throw new RuntimeException("Cannot link more than one wire to same pad. Element: " + this + ", pad: " + padName + ":" + direction + ", new link: " + + link + ", existing link: " + inputPads.get(padName) + "."); + inputPads.put(padName, link); + link.setSink(this); - break; + break; - case OUT: - if (outputPads.get(padName) != null) - throw new RuntimeException("Cannot link more than one wire to same pad. Element: " + this + ", pad: " + padName + ":" + direction + ", new link: " + - link + ", existing link: " + outputPads.get(padName) + "."); + case OUT: + if (outputPads.get(padName) != null) + throw new RuntimeException("Cannot link more than one wire to same pad. Element: " + this + ", pad: " + padName + ":" + direction + ", new link: " + + link + ", existing link: " + outputPads.get(padName) + "."); - outputPads.put(padName, link); - link.setSource(this); + outputPads.put(padName, link); + link.setSource(this); - break; + break; } } @@ -162,9 +165,6 @@ public class BaseElement implements Element { */ @Override public void handleData(ByteBuffer buf, Link link) { - if (buf == null) - return; - if (verbose) System.out.println("[" + this + "] INFO: Data received: " + buf + "."); @@ -177,7 +177,8 @@ public class BaseElement implements Element { protected final void pushDataToAllOuts(ByteBuffer buf) { if (buf == null) - return; + throw new NullPointerException(); + //return; if (outputPads.size() == 0) throw new RuntimeException("Number of outgoing connection is zero. Cannot send data to output. Data: " + buf + "."); @@ -218,18 +219,19 @@ public class BaseElement implements Element { * By default, do nothing with incoming event and retransmit event to all * pads. */ + @SuppressWarnings("incomplete-switch") @Override public void handleEvent(Event event, Direction direction) { if (verbose) System.out.println("[" + this + "] INFO: Event " + event + ":" + direction + " is received."); switch (event) { - case STREAM_CLOSE: - onClose(); - break; - case STREAM_START: - onStart(); - break; + case STREAM_CLOSE: + onClose(); + break; + case STREAM_START: + onStart(); + break; } sendEventToAllPads(event, direction); @@ -261,18 +263,18 @@ public class BaseElement implements Element { System.out.println("[" + this + "] INFO: Sending event " + event + ":" + direction + "."); switch (direction) { - case IN: - // Send event to all pads with IN direction - for (DataSource in : inputPads.values()) { - in.sendEvent(event, direction); - } - break; - case OUT: - // Send event to all pads with OUT direction - for (DataSink out : outputPads.values()) { - out.sendEvent(event, direction); - } - break; + case IN: + // Send event to all pads with IN direction + for (DataSource in : inputPads.values()) { + in.sendEvent(event, direction); + } + break; + case OUT: + // Send event to all pads with OUT direction + for (DataSink out : outputPads.values()) { + out.sendEvent(event, direction); + } + break; } } @@ -290,7 +292,7 @@ public class BaseElement implements Element { * source link, to push unnecessary data back * @param fromCursor * if true, then position will be included into calculation - * @return true, + * @return true, if buffer is long enough, false otherwise */ public boolean cap(ByteBuffer buf, int minLength, int maxLength, Link link, boolean fromCursor) { @@ -384,16 +386,16 @@ public class BaseElement implements Element { public static void main(String args[]) { Element source = new FakeSource("source") { { - this.verbose = true; - this.numBuffers = 10; - this.incommingBufLength = 3; - this.delay = 100; + verbose = true; + numBuffers = 10; + incommingBufLength = 3; + delay = 100; } }; Element sink = new FakeSink("sink") { { - this.verbose = true; + verbose = true; } }; @@ -411,7 +413,9 @@ public class BaseElement implements Element { // Links between t3-t4-sink will operate in push mode. // Link between t2-t3 will run main loop (pull from source and push to // sink). - pipeline.getLink("t3", STDOUT).run(); + Link link = pipeline.getLink("t3", STDOUT); + link.sendEvent(Event.STREAM_START, Direction.IN); + link.run(); } } diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/BufferPool.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/BufferPool.java old mode 100644 new mode 100755 diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/ByteBuffer.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/ByteBuffer.java old mode 100644 new mode 100755 index 8543a5aa7ab..3a718ba0bd5 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/ByteBuffer.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/ByteBuffer.java @@ -19,7 +19,9 @@ package streamer; import java.nio.charset.Charset; import java.util.Arrays; import java.util.HashMap; +import java.util.HashSet; import java.util.Map; +import java.util.Set; /** * This class represents a slice in a buffer. @@ -45,9 +47,9 @@ public class ByteBuffer { */ public ByteBuffer(int minLength) { // Get buffer of acceptable size from buffer pool - this.data = BufferPool.allocateNewBuffer(minLength); - this.offset = 0; - this.length = minLength; + data = BufferPool.allocateNewBuffer(minLength); + offset = 0; + length = minLength; } public ByteBuffer(byte data[]) { @@ -55,8 +57,8 @@ public class ByteBuffer { throw new NullPointerException("Data must be non-null."); this.data = data; - this.offset = 0; - this.length = data.length; + offset = 0; + length = data.length; } public ByteBuffer(byte[] data, int offset, int length) { @@ -74,9 +76,9 @@ public class ByteBuffer { */ public ByteBuffer(int minLength, boolean reserveSpaceForHeader) { // Get buffer of acceptable size from buffer pool - this.data = BufferPool.allocateNewBuffer(128 + minLength); - this.offset = 128; // 100 bytes should be enough for headers - this.length = minLength; + data = BufferPool.allocateNewBuffer(128 + minLength); + offset = 128; // 100 bytes should be enough for headers + length = minLength; } /** @@ -96,7 +98,7 @@ public class ByteBuffer { @Override public String toString() { - return toString(100); + return toString(length); } /** @@ -106,8 +108,8 @@ public class ByteBuffer { * number of bytes to show in string */ public String toString(int maxLength) { - return "ByteRange(){offset=" + offset + ", length=" + length + ", cursor=" + cursor + ", data=" + ((data == null) ? "null" : toHexString(maxLength)) + - ((metadata == null || metadata.size() == 0) ? "" : ", metadata=" + metadata) + "}"; + return "ByteRange(){offset=" + offset + ", length=" + length + ", cursor=" + cursor + ", data=" + ((data == null) ? "null" : toHexString(maxLength)) + + ((metadata == null || metadata.size() == 0) ? "" : ", metadata=" + metadata) + "}"; } /** @@ -143,13 +145,68 @@ public class ByteBuffer { if (i > 0) builder.append(" "); int b = data[offset + i] & 0xff; - builder.append(((b < 16) ? "0" : "") + Integer.toString(b, 16)); + builder.append(String.format("%02x", b)); } return builder.toString(); } - public void dump() { - System.out.println(toString(length)); + /** + * Return string representation of this byte buffer as dump, e.g. + * "0000 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 .................". + * + * @param maxLength + * number of bytes to show in string + */ + public String dump() { + StringBuilder builder = new StringBuilder(length * 4); + int i = 0; + for (; i < length && i < length; i++) { + if (i % 16 == 0) { + builder.append(String.format("%04x", i)); + } + + builder.append(' '); + int b = data[offset + i] & 0xff; + builder.append(String.format("%02x", b)); + + if (i % 16 == 15) { + builder.append(' '); + builder.append(toASCIIString(i - 15, i)); + builder.append('\n'); + } + } + int end = i - 1; + if (end % 16 != 15) { + int begin = end & ~0xf; + for (int j = 0; j < (15 - (end % 16)); j++) { + builder.append(" "); + } + builder.append(' '); + builder.append(toASCIIString(begin, end)); + builder.append('\n'); + } + return builder.toString(); + } + + private String toASCIIString(int start, int finish) { + StringBuffer sb = new StringBuffer(16); + for (int i = start; i <= finish; i++) { + char ch = (char)data[offset + i]; + if (ch < ' ' || ch >= 0x7f) { + sb.append('.'); + } else { + sb.append(ch); + } + } + return sb.toString(); + } + + /** + * Return string representation of this byte buffer as hexadecimal numbers, + * e.g. "01 02". + */ + public String toPlainHexString() { + return toPlainHexString(length); } public void extend(int newLength) { @@ -190,12 +247,12 @@ public class ByteBuffer { ref(); if (this.length < (offset + length)) - throw new RuntimeException("Length of region is larger that length of this buffer. Buffer length: " + this.length + ", offset: " + offset + - ", new region length: " + length + "."); + throw new RuntimeException("Length of region is larger that length of this buffer. Buffer length: " + this.length + ", offset: " + offset + + ", new region length: " + length + "."); ByteBuffer slice = new ByteBuffer(data, this.offset + offset, length); - if (copyMetadata && this.metadata != null) + if (copyMetadata && metadata != null) slice.metadata = new HashMap(metadata); return slice; @@ -251,8 +308,8 @@ public class ByteBuffer { public short[] toShortArray() { if (length % 2 != 0) - throw new ArrayIndexOutOfBoundsException("Length of byte array must be dividable by 2 without remainder. Array length: " + length + ", remainder: " + - (length % 2) + "."); + throw new ArrayIndexOutOfBoundsException("Length of byte array must be dividable by 2 without remainder. Array length: " + length + ", remainder: " + + (length % 2) + "."); short[] buf = new short[length / 2]; @@ -267,8 +324,8 @@ public class ByteBuffer { */ public int[] toIntLEArray() { if (length % 4 != 0) - throw new ArrayIndexOutOfBoundsException("Length of byte array must be dividable by 4 without remainder. Array length: " + length + ", remainder: " + - (length % 4) + "."); + throw new ArrayIndexOutOfBoundsException("Length of byte array must be dividable by 4 without remainder. Array length: " + length + ", remainder: " + + (length % 4) + "."); int[] buf = new int[length / 4]; @@ -279,12 +336,13 @@ public class ByteBuffer { } /** - * Return array of int's in little endian order, but use only 3 bytes per int (3RGB). + * Return array of int's in little endian order, but use only 3 bytes per int + * (3RGB). */ public int[] toInt3LEArray() { if (length % 3 != 0) - throw new ArrayIndexOutOfBoundsException("Length of byte array must be dividable by 3 without remainder. Array length: " + length + ", remainder: " + - (length % 3) + "."); + throw new ArrayIndexOutOfBoundsException("Length of byte array must be dividable by 3 without remainder. Array length: " + length + ", remainder: " + + (length % 3) + "."); int[] buf = new int[length / 3]; @@ -315,8 +373,8 @@ public class ByteBuffer { if (cursor + 4 > length) throw new ArrayIndexOutOfBoundsException("Cannot read 4 bytes from this buffer: " + this + "."); - int result = - (((data[offset + cursor] & 0xff) << 24) + ((data[offset + cursor + 1] & 0xff) << 16) + ((data[offset + cursor + 2] & 0xff) << 8) + (data[offset + cursor + 3] & 0xff)); + int result = (((data[offset + cursor] & 0xff) << 24) + ((data[offset + cursor + 1] & 0xff) << 16) + ((data[offset + cursor + 2] & 0xff) << 8) + (data[offset + + cursor + 3] & 0xff)); cursor += 4; return result; } @@ -328,8 +386,8 @@ public class ByteBuffer { if (cursor + 4 > length) throw new ArrayIndexOutOfBoundsException("Cannot read 4 bytes from this buffer: " + this + "."); - int result = - (((data[offset + cursor + 3] & 0xff) << 24) + ((data[offset + cursor + 2] & 0xff) << 16) + ((data[offset + cursor + 1] & 0xff) << 8) + (data[offset + cursor] & 0xff)); + int result = (((data[offset + cursor + 3] & 0xff) << 24) + ((data[offset + cursor + 2] & 0xff) << 16) + ((data[offset + cursor + 1] & 0xff) << 8) + (data[offset + + cursor] & 0xff)); cursor += 4; return result; } @@ -341,9 +399,21 @@ public class ByteBuffer { if (cursor + 4 > length) throw new ArrayIndexOutOfBoundsException("Cannot read 4 bytes from this buffer: " + this + "."); - long result = - (((long)(data[offset + cursor + 3] & 0xff) << 24) + ((long)(data[offset + cursor + 2] & 0xff) << 16) + ((long)(data[offset + cursor + 1] & 0xff) << 8) + (data[offset + - cursor] & 0xff)); + long result = (((long)(data[offset + cursor + 3] & 0xff) << 24) + ((long)(data[offset + cursor + 2] & 0xff) << 16) + + ((long)(data[offset + cursor + 1] & 0xff) << 8) + (data[offset + cursor + 0] & 0xff)); + cursor += 4; + return result; + } + + /** + * Read unsigned int in network order. Cursor is advanced by 4. + */ + public long readUnsignedInt() { + if (cursor + 4 > length) + throw new ArrayIndexOutOfBoundsException("Cannot read 4 bytes from this buffer: " + this + "."); + + long result = (((long)(data[offset + cursor + 0] & 0xff) << 24) + ((long)(data[offset + cursor + 1] & 0xff) << 16) + + ((long)(data[offset + cursor + 2] & 0xff) << 8) + (data[offset + cursor + 3] & 0xff)); cursor += 4; return result; } @@ -379,19 +449,19 @@ public class ByteBuffer { int firstByte = readUnsignedByte(); int result; switch (firstByte & 0xc0) { - default: - case 0x00: - result = firstByte & 0x3f; - break; - case 0x40: - result = (firstByte & 0x3f << 8) | readUnsignedByte(); - break; - case 0x80: - result = (((firstByte & 0x3f << 8) | readUnsignedByte()) << 8) | readUnsignedByte(); - break; - case 0xc0: - result = ((((firstByte & 0x3f << 8) | readUnsignedByte()) << 8) | readUnsignedByte() << 8) | readUnsignedByte(); - break; + default: + case 0x00: + result = firstByte & 0x3f; + break; + case 0x40: + result = (firstByte & 0x3f << 8) | readUnsignedByte(); + break; + case 0x80: + result = (((firstByte & 0x3f << 8) | readUnsignedByte()) << 8) | readUnsignedByte(); + break; + case 0xc0: + result = ((((firstByte & 0x3f << 8) | readUnsignedByte()) << 8) | readUnsignedByte() << 8) | readUnsignedByte(); + break; } return result; @@ -445,6 +515,18 @@ public class ByteBuffer { return result; } + /** + * Read signed short in network order. Cursor is advanced by 2. + */ + public short readSignedShort() { + if (cursor + 2 > length) + throw new ArrayIndexOutOfBoundsException("Cannot read 2 bytes from this buffer: " + this + "."); + + short result = (short)(((data[offset + cursor + 0] & 0xff) << 8) | (data[offset + cursor + 1] & 0xff)); + cursor += 2; + return result; + } + /** * Read unsigned short in network order in variable length format. Cursor is * advanced by 1 or 2 bytes. @@ -456,9 +538,9 @@ public class ByteBuffer { int firstByte = readUnsignedByte(); int result; - if ((firstByte & 0x80) == 0) + if ((firstByte & 0x80) == 0) { result = firstByte & 0x7f; - else { + } else { int secondByte = readUnsignedByte(); result = (((firstByte & 0x7f) << 8) | secondByte); } @@ -466,6 +548,174 @@ public class ByteBuffer { return result; } + /** + * Read integer in BER format. + * + * Most significant bit of first byte indicates type of date in first byte: if + * 0, then byte contains length (up to 7f), if 1, then byte contains number of + * following bytes with value in network order. Value 0x80 means unlimited + * length, which ends with two zero bytes (0x00 0x00) sequence. + * + * If -1 is returned by this method, then caller must seek two consecutive + * zeroes in buffer and consume all that data from buffer, including these two + * zeroes, but caller should not parse these two zeroes. + * + * @return length or -1, for unlimited length + */ + public long readBerLength() { + int firstByte = readUnsignedByte(); + + long result; + if ((firstByte & 0x80) == 0) { + result = firstByte & 0x7f; + } else { + int intLength = firstByte & 0x7f; + if (intLength != 0) + result = readUnsignedVarInt(intLength); + else + return -1; + } + + return result; + } + + /** + * Read integer in BER format. + * + * Most significant bit of first byte indicates type of date in first byte: if + * 0, then byte contains length (up to 7f), if 1, then byte contains number of + * following bytes with value in network order. + */ + public void writeBerLength(long length) { + if (length < 0) + throw new RuntimeException("Length cannot be less than zero: " + length + ". Data: " + this + "."); + + if (length < 0x80) { + writeByte((int)length); + } else { + if (length < 0xff) { + writeByte(0x81); + writeByte((int)length); + } else if (length <= 0xffFF) { + writeByte(0x82); + writeShort((int)length); + } else if (length <= 0xffFFff) { + writeByte(0x83); + writeByte((int)(length >> 16)); + writeShort((int)length); + } else if (length <= 0xffFFffFFL) { + writeByte(0x84); + writeInt((int)length); + } else if (length <= 0xffFFffFFffL) { + writeByte(0x85); + writeByte((int)(length >> 32)); + writeInt((int)length); + } else if (length <= 0xffFFffFFffFFL) { + writeByte(0x86); + writeShort((int)(length >> 32)); + writeInt((int)length); + } else if (length <= 0xffFFffFFffFFffL) { + writeByte(0x87); + writeByte((int)(length >> (32 + 16))); + writeShort((int)(length >> 32)); + writeInt((int)length); + } else { + writeByte(0x88); + writeInt((int)(length >> 32)); + writeInt((int)length); + } + } + + } + + /** + * Read signed variable length integers in network order. + * + * @param len + * length of integer + */ + public long readSignedVarInt(int len) { + long value = 0; + switch (len) { + case 0: + value = 0; + break; + case 1: + value = readSignedByte(); + break; + case 2: + value = readSignedShort(); + break; + case 3: + value = (readSignedByte() << 16) | readUnsignedShort(); + break; + case 4: + value = readSignedInt(); + break; + case 5: + value = (readSignedByte() << 32) | readUnsignedInt(); + break; + case 6: + value = (readSignedShort() << 32) | readUnsignedInt(); + break; + case 7: + value = (readSignedByte() << 32 + 24) | (readUnsignedShort() << 32) | readUnsignedInt(); + break; + case 8: + value = readSignedLong(); + break; + default: + throw new RuntimeException("Cannot read integers which are more than 8 bytes long. Length: " + len + ". Data: " + this + "."); + } + + return value; + } + + /** + * Read unsigned variable length integers in network order. Values, which are + * larger than 0x7FffFFffFFffFFff cannot be parsed by this method. + */ + public long readUnsignedVarInt(int len) { + long value = 0; + switch (len) { + case 0: + value = 0; + break; + case 1: + value = readUnsignedByte(); + break; + case 2: + value = readUnsignedShort(); + break; + case 3: + value = (readUnsignedByte() << 16) | readUnsignedShort(); + break; + case 4: + value = readUnsignedInt(); + break; + case 5: + value = (readUnsignedByte() << 32) | readUnsignedInt(); + break; + case 6: + value = (readUnsignedShort() << 32) | readUnsignedInt(); + break; + case 7: + value = (readUnsignedByte() << 32 + 16) | (readUnsignedShort() << 32) | readUnsignedInt(); + break; + case 8: + value = readSignedLong(); + if (value < 0) + throw new RuntimeException( + "Cannot read 64 bit integers which are larger than 0x7FffFFffFFffFFff, because of lack of unsinged long type in Java. Value: " + value + ". Data: " + + this + "."); + break; + default: + throw new RuntimeException("Cannot read integers which are more than 8 bytes long. Length: " + len + ". Data: " + this + "."); + } + + return value; + } + /** * Read unsigned short in little endian order. Cursor is advanced by 2. */ @@ -535,6 +785,13 @@ public class ByteBuffer { return ((readSignedIntLE()) & 0xffFFffFFL) | (((long)readSignedIntLE()) << 32); } + /** + * Read signed long in network order. Cursor is advanced by 8 bytes. + */ + public long readSignedLong() { + return (((long)readSignedInt()) << 32) | ((readSignedInt()) & 0xffFFffFFL); + } + /** * Read string from buffer. Cursor is advanced by string length. */ @@ -547,6 +804,38 @@ public class ByteBuffer { return string; } + /** + * Read string with '\0' character at end. + */ + public String readVariableString(Charset charset) { + + int start = cursor; + + // Find end of string + while (readUnsignedByte() != 0) { + } + + String string = new String(data, offset + start, cursor - start - 1, charset); + + return string; + } + + /** + * Read wide string with wide '\0' character at end. + */ + public String readVariableWideString(Charset charset) { + + int start = cursor; + + // Find end of string + while (readUnsignedShortLE() != 0) { + } + + String string = new String(data, offset + start, cursor - start - 2, charset); + + return string; + } + /** * Get bytes as lightweight slice. Cursor is advanced by data length. */ @@ -682,8 +971,8 @@ public class ByteBuffer { */ public void prepend(byte[] data, int offset, int length) { if (!isSoleOwner()) { - throw new RuntimeException("Create full copy of this byte buffer data for modification. refCount: " + refCount + ", parentByteBuffer: " + parentByteBuffer + - "."); + throw new RuntimeException("Create full copy of this byte buffer data for modification. refCount: " + refCount + ", parentByteBuffer: " + + parentByteBuffer + "."); } // If there is no enough space for header to prepend @@ -697,9 +986,13 @@ public class ByteBuffer { // Extend byte range to include header this.offset -= length; this.length += length; - this.cursor += length; + cursor += length; } + /** + * Write byte representation of given string, without string terminators (zero + * or zeroes at end of string). + */ public void writeString(String str, Charset charset) { writeBytes(str.getBytes(charset)); } @@ -725,44 +1018,10 @@ public class ByteBuffer { } public void writeBytes(byte[] bytes, int offset, int length) { - System.arraycopy(bytes, offset, this.data, this.offset + this.cursor, length); + System.arraycopy(bytes, offset, data, this.offset + cursor, length); cursor += length; } - // /** - // * Write BER encoded definite long variant of the ASN.1 length field. - // */ - // public void writeBerLength(int value) { - // int fieldLength; - // if (value > 0xFFffFF) - // fieldLength = 4; - // else if (value > 0xFFff) - // fieldLength = 3; - // else if (value > 0xFF) - // fieldLength = 2; - // else - // fieldLength = 1; - // - // if (cursor + fieldLength + 1 > length) - // throw new ArrayIndexOutOfBoundsException("Cannot write " + (fieldLength + - // 1) + " byte(s) to this buffer: " + this + "."); - // - // // Write length of length field itself - // writeByte(0x80 | fieldLength); - // - // switch (fieldLength) { - // case 4: - // data[offset + cursor++] = (byte) (value >> 24); - // case 3: - // data[offset + cursor++] = (byte) (value >> 16); - // case 2: - // data[offset + cursor++] = (byte) (value >> 8); - // case 1: - // data[offset + cursor++] = (byte) value; - // } - // - // } - /** * Reduce length of buffer to cursor position. */ @@ -771,7 +1030,7 @@ public class ByteBuffer { } /** - * Rewind cursor to beginning of buffer. + * Rewind cursor to beginning of the buffer. */ public void rewindCursor() { cursor = 0; @@ -808,8 +1067,11 @@ public class ByteBuffer { public boolean equals(Object obj) { if (this == obj) return true; + if (obj == null) return false; + + // Does not work in case of anonymous type(s) if (getClass() != obj.getClass()) return false; @@ -824,4 +1086,38 @@ public class ByteBuffer { return true; } + /** + * Return length of data left after cursor. + */ + public int remainderLength() { + if (length >= cursor) + return length - cursor; + else + throw new RuntimeException("Inconsistent state of buffer: cursor is after end of buffer: " + this + "."); + } + + public Set getMetadataKeys() { + if (metadata != null) + return metadata.keySet(); + else + return new HashSet(0); + } + + /** + * Return unsigned value of byte at given position relative to cursor. Cursor + * is not advanced. + */ + public int peekUnsignedByte(int i) { + return data[offset + cursor + i] & 0xff; + } + + /** + * Trim few first bytes. + */ + public void trimHeader(int length) { + offset += length; + this.length -= length; + rewindCursor(); + } + } diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/DataSink.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/DataSink.java old mode 100644 new mode 100755 diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/DataSource.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/DataSource.java old mode 100644 new mode 100755 diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/Direction.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/Direction.java old mode 100644 new mode 100755 diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/Element.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/Element.java old mode 100644 new mode 100755 index d489b182393..e78e3012856 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/Element.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/Element.java @@ -19,7 +19,7 @@ package streamer; import java.util.Set; /** - * Element is for processing of data. It has one or more contact pads, which can + * Element is basic building block for constructing data processing pipes. It has one or more contact pads, which can * be wired with other elements using links. */ public interface Element { diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/Event.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/Event.java old mode 100644 new mode 100755 index 9808f62b684..998274cf1d0 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/Event.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/Event.java @@ -17,7 +17,8 @@ package streamer; public enum Event { - STREAM_START, STREAM_CLOSE, + STREAM_START, + STREAM_CLOSE, /** * Upgrade socket to SSL. diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/InputStreamSource.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/InputStreamSource.java old mode 100644 new mode 100755 index 45155e185fb..0c8c97df690 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/InputStreamSource.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/InputStreamSource.java @@ -20,13 +20,15 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; +import streamer.debug.FakeSink; + /** * Source element, which reads data from InputStream. */ public class InputStreamSource extends BaseElement { protected InputStream is; - protected SocketWrapper socketWrapper; + protected SocketWrapperImpl socketWrapper; public InputStreamSource(String id) { super(id); @@ -37,7 +39,7 @@ public class InputStreamSource extends BaseElement { this.is = is; } - public InputStreamSource(String id, SocketWrapper socketWrapper) { + public InputStreamSource(String id, SocketWrapperImpl socketWrapper) { super(id); this.socketWrapper = socketWrapper; } @@ -45,27 +47,27 @@ public class InputStreamSource extends BaseElement { @Override public void handleEvent(Event event, Direction direction) { switch (event) { - case SOCKET_UPGRADE_TO_SSL: - socketWrapper.upgradeToSsl(); - break; - default: - super.handleEvent(event, direction); + case SOCKET_UPGRADE_TO_SSL: + socketWrapper.upgradeToSsl(); + break; + default: + super.handleEvent(event, direction); } } @Override public void setLink(String padName, Link link, Direction direction) { switch (direction) { - case OUT: - super.setLink(padName, link, direction); + case OUT: + super.setLink(padName, link, direction); - if (is == null) { - // Pause links until data stream will be ready - link.pause(); - } - break; - case IN: - throw new RuntimeException("Cannot assign link to input pad in source element. Element: " + this + ", pad: " + padName + ", link: " + link + "."); + if (is == null) { + // Pause links until data stream will be ready + link.pause(); + } + break; + case IN: + throw new RuntimeException("Cannot assign link to input pad in source element. Element: " + this + ", pad: " + padName + ", link: " + link + "."); } } diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/Link.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/Link.java old mode 100644 new mode 100755 diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/MockSink.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/MockSink.java deleted file mode 100644 index 8094c82b7b3..00000000000 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/MockSink.java +++ /dev/null @@ -1,113 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package streamer; - -import java.util.Arrays; - -/** - * Compare incoming packets with expected packets. - */ -public class MockSink extends BaseElement { - - protected ByteBuffer bufs[] = null; - - public MockSink(String id) { - super(id); - } - - public MockSink(String id, ByteBuffer bufs[]) { - super(id); - this.bufs = bufs; - } - - @Override - public void handleData(ByteBuffer buf, Link link) { - if (verbose) - System.out.println("[" + this + "] INFO: Received buf #" + (packetNumber) + " " + buf + "."); - - if (buf == null) - return; - - if (packetNumber >= bufs.length) - throw new AssertionError("[" + this + "] Incoming buffer #" + packetNumber + " is not expected. Number of expected buffers: " + bufs.length + - ", unexpected buffer: " + buf + "."); - - // Compare incoming buffer with expected buffer - if (!Arrays.equals(bufs[packetNumber].toByteArray(), buf.toByteArray())) - throw new AssertionError("[" + this + "] Incoming buffer #" + packetNumber + " is not equal to expected buffer.\n Actual bufer: " + buf + - ",\n expected buffer: " + bufs[packetNumber] + "."); - - if (verbose) - System.out.println("[" + this + "] INFO: buffers are equal."); - - // Use packetNumber variable to count incoming packets - packetNumber++; - - buf.unref(); - } - - @Override - protected void onClose() { - super.onClose(); - - if (packetNumber != bufs.length) - throw new AssertionError("[" + this + "] Number of expected buffers: " + bufs.length + ", number of actual buffers: " + packetNumber + "."); - } - - @Override - public String toString() { - return "MockSink(" + id + ")"; - } - - /** - * Example. - */ - public static void main(String args[]) { - - Element mockSource = new MockSource("source") { - { - this.bufs = - new ByteBuffer[] {new ByteBuffer(new byte[] {1, 1, 2, 3, 4, 5}), new ByteBuffer(new byte[] {2, 1, 2, 3, 4}), new ByteBuffer(new byte[] {3, 1, 2, 3}), - new ByteBuffer(new byte[] {4, 1, 2}), new ByteBuffer(new byte[] {5, 1})}; - this.verbose = true; - this.delay = 100; - this.numBuffers = this.bufs.length; - } - }; - - Element mockSink = new MockSink("sink") { - { - this.bufs = - new ByteBuffer[] {new ByteBuffer(new byte[] {1, 1, 2, 3, 4, 5}), new ByteBuffer(new byte[] {2, 1, 2, 3, 4}), new ByteBuffer(new byte[] {3, 1, 2, 3}), - new ByteBuffer(new byte[] {4, 1, 2}), new ByteBuffer(new byte[] {5, 1})}; - this.verbose = true; - } - }; - - Link link = new SyncLink() { - { - this.verbose = true; - } - }; - - mockSource.setLink(STDOUT, link, Direction.OUT); - mockSink.setLink(STDIN, link, Direction.IN); - - link.run(); - } - -} diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/OneTimeSwitch.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/OneTimeSwitch.java old mode 100644 new mode 100755 index d50995eae72..9cccb5bf2c2 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/OneTimeSwitch.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/OneTimeSwitch.java @@ -87,13 +87,16 @@ public abstract class OneTimeSwitch extends BaseElement { // Wake up next peer(s) sendEventToAllPads(Event.STREAM_START, Direction.OUT); + // Disconnect our stdin from this element stdin.setSink(null); inputPads.remove(STDIN); + // Replace next peer stdin (our stdout) by our stdin Element nextPeer = stdout.getSink(); nextPeer.replaceLink(stdout, stdin); stdout.drop(); + // Drop all other links for (Object link : inputPads.values().toArray()) ((Link)link).drop(); for (Object link : outputPads.values().toArray()) diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/Order.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/Order.java old mode 100644 new mode 100755 diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/OutputStreamSink.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/OutputStreamSink.java old mode 100644 new mode 100755 index 7a55ea81bea..e66899df8fc --- a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/OutputStreamSink.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/OutputStreamSink.java @@ -20,10 +20,12 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; +import streamer.debug.FakeSource; + public class OutputStreamSink extends BaseElement { protected OutputStream os; - protected SocketWrapper socketWrapper; + protected SocketWrapperImpl socketWrapper; public OutputStreamSink(String id) { super(id); @@ -34,7 +36,7 @@ public class OutputStreamSink extends BaseElement { this.os = os; } - public OutputStreamSink(String id, SocketWrapper socketWrapper) { + public OutputStreamSink(String id, SocketWrapperImpl socketWrapper) { super(id); this.socketWrapper = socketWrapper; } @@ -68,26 +70,26 @@ public class OutputStreamSink extends BaseElement { @Override public void handleEvent(Event event, Direction direction) { switch (event) { - case SOCKET_UPGRADE_TO_SSL: - socketWrapper.upgradeToSsl(); - break; - default: - super.handleEvent(event, direction); + case SOCKET_UPGRADE_TO_SSL: + socketWrapper.upgradeToSsl(); + break; + default: + super.handleEvent(event, direction); } } @Override public void setLink(String padName, Link link, Direction direction) { switch (direction) { - case IN: - super.setLink(padName, link, direction); + case IN: + super.setLink(padName, link, direction); - if (os == null) - // Pause links until data stream will be ready - link.pause(); - break; - case OUT: - throw new RuntimeException("Cannot assign link to output pad in sink element. Element: " + this + ", pad: " + padName + ", link: " + link + "."); + if (os == null) + // Pause links until data stream will be ready + link.pause(); + break; + case OUT: + throw new RuntimeException("Cannot assign link to output pad in sink element. Element: " + this + ", pad: " + padName + ", link: " + link + "."); } } @@ -126,10 +128,10 @@ public class OutputStreamSink extends BaseElement { public static void main(String args[]) { Element source = new FakeSource("source") { { - this.verbose = true; - this.numBuffers = 3; - this.incommingBufLength = 5; - this.delay = 100; + verbose = true; + numBuffers = 3; + incommingBufLength = 5; + delay = 100; } }; diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/Pipeline.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/Pipeline.java old mode 100644 new mode 100755 index d2e52ddbb27..0f6089bcf23 --- a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/Pipeline.java +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/Pipeline.java @@ -48,6 +48,8 @@ public interface Pipeline extends Element { * so when pipeline will be connected with other elements, outside of this * pipeline, they will be connected to IN and OUT elements. * + * Empty names are skipped. + * * Example: * *
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/PipelineImpl.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/PipelineImpl.java
      old mode 100644
      new mode 100755
      index 4e6fc0a44ca..299d0a466f7
      --- a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/PipelineImpl.java
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/PipelineImpl.java
      @@ -16,10 +16,15 @@
       // under the License.
       package streamer;
       
      +import java.util.ArrayList;
       import java.util.HashMap;
      +import java.util.List;
       import java.util.Map;
       import java.util.Set;
       
      +import streamer.debug.FakeSink;
      +import streamer.debug.FakeSource;
      +
       public class PipelineImpl implements Pipeline {
       
           protected String id;
      @@ -51,11 +56,11 @@ public class PipelineImpl implements Pipeline {
           @Override
           public Set getPads(Direction direction) {
               switch (direction) {
      -            case IN:
      -                return elements.get(IN).getPads(direction);
      +        case IN:
      +            return elements.get(IN).getPads(direction);
       
      -            case OUT:
      -                return elements.get(OUT).getPads(direction);
      +        case OUT:
      +            return elements.get(OUT).getPads(direction);
               }
               return null;
           }
      @@ -71,8 +76,8 @@ public class PipelineImpl implements Pipeline {
                   int outPadsNumber = element.getPads(Direction.OUT).size();
                   int inPadsNumber = element.getPads(Direction.IN).size();
                   if ((outPadsNumber | inPadsNumber) > 0 && (outPadsNumber == 0 || inPadsNumber == 0))
      -                throw new RuntimeException("[ " + this + "] Pads of input element of pipeline are not balanced. Element: " + element + ", output pads: " +
      -                    element.getPads(Direction.OUT).toString() + ", input pads: " + element.getPads(Direction.IN).toString() + ".");
      +                throw new RuntimeException("[ " + this + "] Pads of input element of pipeline are not balanced. Element: " + element + ", output pads: "
      +                        + element.getPads(Direction.OUT).toString() + ", input pads: " + element.getPads(Direction.IN).toString() + ".");
               }
       
               // Check OUT element
      @@ -81,8 +86,8 @@ public class PipelineImpl implements Pipeline {
                   int outPadsNumber = element.getPads(Direction.OUT).size();
                   int inPadsNumber = element.getPads(Direction.IN).size();
                   if ((outPadsNumber | inPadsNumber) > 0 && (outPadsNumber == 0 || inPadsNumber == 0))
      -                throw new RuntimeException("[ " + this + "] Pads of output element of pipeline are not balanced. Element: " + element + ", output pads: " +
      -                    element.getPads(Direction.OUT).toString() + ", input pads: " + element.getPads(Direction.IN).toString() + ".");
      +                throw new RuntimeException("[ " + this + "] Pads of output element of pipeline are not balanced. Element: " + element + ", output pads: "
      +                        + element.getPads(Direction.OUT).toString() + ", input pads: " + element.getPads(Direction.IN).toString() + ".");
               }
       
           }
      @@ -127,12 +132,12 @@ public class PipelineImpl implements Pipeline {
           @Override
           public void handleEvent(Event event, Direction direction) {
               switch (direction) {
      -            case IN:
      -                get(IN).handleEvent(event, direction);
      -                break;
      -            case OUT:
      -                get(OUT).handleEvent(event, direction);
      -                break;
      +        case IN:
      +            get(IN).handleEvent(event, direction);
      +            break;
      +        case OUT:
      +            get(OUT).handleEvent(event, direction);
      +            break;
               }
           }
       
      @@ -142,8 +147,8 @@ public class PipelineImpl implements Pipeline {
                   String id = element.getId();
       
                   if (this.elements.containsKey(id))
      -                throw new RuntimeException("This pipeline already contains element with same ID. New element: " + element + ", existing element: " +
      -                    this.elements.get(id) + ".");
      +                throw new RuntimeException("This pipeline already contains element with same ID. New element: " + element + ", existing element: "
      +                        + this.elements.get(id) + ".");
       
                   this.elements.put(id, element);
               }
      @@ -152,6 +157,8 @@ public class PipelineImpl implements Pipeline {
           @Override
           public void link(String... elementNames) {
       
      +        elementNames = filterOutEmptyStrings(elementNames);
      +
               if (elementNames.length < 2)
                   throw new RuntimeException("At least two elements are necessary to create link between them.");
       
      @@ -180,8 +187,8 @@ public class PipelineImpl implements Pipeline {
                   elements[i] = get(elementName);
       
                   if (elements[i] == null)
      -                throw new RuntimeException("Cannot find element by name in this pipeline. Element name: \"" + elementName + "\" (" + elementNames[i] + "), pipeline: " +
      -                    this + ".");
      +                throw new RuntimeException("Cannot find element by name in this pipeline. Element name: \"" + elementName + "\" (" + elementNames[i] + "), pipeline: "
      +                        + this + ".");
       
                   i++;
               }
      @@ -204,6 +211,30 @@ public class PipelineImpl implements Pipeline {
               }
           }
       
      +    /**
      +     * Filter out empty strings from array and return new array with non-empty
      +     * elements only. If array contains no empty string, returns same array.
      +     */
      +    private String[] filterOutEmptyStrings(String[] strings) {
      +
      +        boolean found = false;
      +        for (String string : strings) {
      +            if (string == null || string.isEmpty()) {
      +                found = true;
      +                break;
      +            }
      +        }
      +
      +        if (!found)
      +            return strings;
      +
      +        List filteredStrings = new ArrayList(strings.length);
      +        for (String string : strings)
      +            if (string != null && !string.isEmpty())
      +                filteredStrings.add(string);
      +        return filteredStrings.toArray(new String[filteredStrings.size()]);
      +    }
      +
           @Override
           public void addAndLink(Element... elements) {
               add(elements);
      @@ -281,20 +312,20 @@ public class PipelineImpl implements Pipeline {
               // Create elements
               pipeline.add(new FakeSource("source") {
                   {
      -                this.incommingBufLength = 3;
      -                this.numBuffers = 10;
      -                this.delay = 100;
      +                incommingBufLength = 3;
      +                numBuffers = 10;
      +                delay = 100;
                   }
               });
               pipeline.add(new BaseElement("tee"));
               pipeline.add(new FakeSink("sink") {
                   {
      -                this.verbose = true;
      +                verbose = true;
                   }
               });
               pipeline.add(new FakeSink("sink2") {
                   {
      -                this.verbose = true;
      +                verbose = true;
                   }
               });
       
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/Queue.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/Queue.java
      old mode 100644
      new mode 100755
      index 23c57e0add8..910e073a058
      --- a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/Queue.java
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/Queue.java
      @@ -19,6 +19,9 @@ package streamer;
       import java.util.concurrent.LinkedBlockingQueue;
       import java.util.concurrent.TimeUnit;
       
      +import streamer.debug.FakeSink;
      +import streamer.debug.FakeSource;
      +
       /**
        * Message queue for safe transfer of packets between threads.
        */
      @@ -30,7 +33,6 @@ public class Queue extends BaseElement {
               super(id);
           }
       
      -    @SuppressWarnings("incomplete-switch")
           @Override
           public void poll(boolean block) {
               try {
      @@ -67,12 +69,12 @@ public class Queue extends BaseElement {
           @Override
           public void handleEvent(Event event, Direction direction) {
               switch (event) {
      -            case LINK_SWITCH_TO_PULL_MODE:
      -                // Do not propagate this event, because this element is boundary between
      -                // threads
      -                break;
      -            default:
      -                super.handleEvent(event, direction);
      +        case LINK_SWITCH_TO_PULL_MODE:
      +            // Do not propagate this event, because this element is boundary between
      +            // threads
      +            break;
      +        default:
      +            super.handleEvent(event, direction);
               }
           }
       
      @@ -104,17 +106,17 @@ public class Queue extends BaseElement {
       
               Element source1 = new FakeSource("source1") {
                   {
      -                this.delay = 100;
      -                this.numBuffers = 10;
      -                this.incommingBufLength = 10;
      +                delay = 100;
      +                numBuffers = 10;
      +                incommingBufLength = 10;
                   }
               };
       
               Element source2 = new FakeSource("source2") {
                   {
      -                this.delay = 100;
      -                this.numBuffers = 10;
      -                this.incommingBufLength = 10;
      +                delay = 100;
      +                numBuffers = 10;
      +                incommingBufLength = 10;
                   }
               };
       
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/SocketWrapper.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/SocketWrapper.java
      old mode 100644
      new mode 100755
      index 19ac0629f45..22d436e5c67
      --- a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/SocketWrapper.java
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/SocketWrapper.java
      @@ -16,224 +16,20 @@
       // under the License.
       package streamer;
       
      -import static rdpclient.MockServer.Packet.PacketType.CLIENT;
      -import static rdpclient.MockServer.Packet.PacketType.SERVER;
      -
       import java.io.IOException;
      -import java.io.InputStream;
      -import java.io.OutputStream;
       import java.net.InetSocketAddress;
      -import java.net.Socket;
      -import java.util.HashMap;
       
      -import javax.net.SocketFactory;
      -import javax.net.ssl.SSLContext;
      -import javax.net.ssl.SSLSocket;
      -import javax.net.ssl.SSLSocketFactory;
      -import javax.net.ssl.TrustManager;
      -
      -import rdpclient.MockServer;
      -import rdpclient.MockServer.Packet;
      -import rdpclient.TrustAllX509TrustManager;
      -
      -public class SocketWrapper extends PipelineImpl {
      -
      -    protected InputStreamSource source;
      -    protected OutputStreamSink sink;
      -    protected Socket socket;
      -    protected InetSocketAddress address;
      -
      -    protected SSLSocket sslSocket;
      -
      -    //protected String SSL_VERSION_TO_USE = "TLSv1.2";
      -    /*DEBUG*/protected String SSL_VERSION_TO_USE = "TLSv1";
      -
      -    public SocketWrapper(String id) {
      -        super(id);
      -    }
      -
      -    @Override
      -    protected HashMap initElementMap(String id) {
      -        HashMap map = new HashMap();
      -
      -        source = new InputStreamSource(id + "." + OUT, this);
      -        sink = new OutputStreamSink(id + "." + IN, this);
      -
      -        // Pass requests to read data to socket input stream
      -        map.put(OUT, source);
      -
      -        // All incoming data, which is sent to this socket wrapper, will be sent
      -        // to socket remote
      -        map.put(IN, sink);
      -
      -        return map;
      -    }
      +public interface SocketWrapper extends Element {
       
           /**
            * Connect this socket wrapper to remote server and start main loop on
      -     * IputStreamSource stdout link, to watch for incoming data, and
      -     * OutputStreamSink stdin link, to pull for outgoing data.
      -     *
      -     * @param address
      -     * @throws IOException
      +     * Source stdout link, to watch for incoming data, and
      +     * Sink stdin link, to pull for outgoing data.
            */
      -    public void connect(InetSocketAddress address) throws IOException {
      -        this.address = address;
      +    public void connect(InetSocketAddress address) throws IOException;
       
      -        // Connect socket to server
      -        socket = SocketFactory.getDefault().createSocket();
      -        try {
      -            socket.connect(address);
      +    public void shutdown();
       
      -            InputStream is = socket.getInputStream();
      -            source.setInputStream(is);
      +    void upgradeToSsl();
       
      -            OutputStream os = socket.getOutputStream();
      -            sink.setOutputStream(os);
      -
      -            // Start polling for data to send to remote sever
      -            runMainLoop(IN, STDIN, true, true);
      -
      -            // Push incoming data from server to handlers
      -            runMainLoop(OUT, STDOUT, false, false);
      -
      -        } finally {
      -            socket.close();
      -        }
      -    }
      -
      -    @Override
      -    public void handleEvent(Event event, Direction direction) {
      -        switch (event) {
      -            case SOCKET_UPGRADE_TO_SSL:
      -                upgradeToSsl();
      -                break;
      -            default:
      -                super.handleEvent(event, direction);
      -                break;
      -        }
      -    }
      -
      -    public void upgradeToSsl() {
      -
      -        if (sslSocket != null)
      -            // Already upgraded
      -            return;
      -
      -        if (verbose)
      -            System.out.println("[" + this + "] INFO: Upgrading socket to SSL.");
      -
      -        try {
      -            // Use most secure implementation of SSL available now.
      -            // JVM will try to negotiate TLS1.2, then will fallback to TLS1.0, if
      -            // TLS1.2 is not supported.
      -            SSLContext sslContext = SSLContext.getInstance(SSL_VERSION_TO_USE);
      -
      -            // Trust all certificates (FIXME: insecure)
      -            sslContext.init(null, new TrustManager[] {new TrustAllX509TrustManager()}, null);
      -
      -            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
      -            sslSocket = (SSLSocket)sslSocketFactory.createSocket(socket, address.getHostName(), address.getPort(), true);
      -            sslSocket.startHandshake();
      -
      -            InputStream sis = sslSocket.getInputStream();
      -            source.setInputStream(sis);
      -
      -            OutputStream sos = sslSocket.getOutputStream();
      -            sink.setOutputStream(sos);
      -
      -        } catch (Exception e) {
      -            throw new RuntimeException("Cannot upgrade socket to SSL: " + e.getMessage(), e);
      -        }
      -
      -    }
      -
      -    @Override
      -    public void validate() {
      -        for (Element element : elements.values())
      -            element.validate();
      -
      -        if (get(IN).getPads(Direction.IN).size() == 0)
      -            throw new RuntimeException("[ " + this + "] Input of socket is not connected.");
      -
      -        if (get(OUT).getPads(Direction.OUT).size() == 0)
      -            throw new RuntimeException("[ " + this + "] Output of socket is not connected.");
      -
      -    }
      -
      -    public void shutdown() {
      -        try {
      -            handleEvent(Event.STREAM_CLOSE, Direction.IN);
      -        } catch (Exception e) {
      -        }
      -        try {
      -            handleEvent(Event.STREAM_CLOSE, Direction.OUT);
      -        } catch (Exception e) {
      -        }
      -        try {
      -            if (sslSocket != null)
      -                sslSocket.close();
      -        } catch (Exception e) {
      -        }
      -        try {
      -            socket.close();
      -        } catch (Exception e) {
      -        }
      -    }
      -
      -    @Override
      -    public String toString() {
      -        return "SocketWrapper(" + id + ")";
      -    }
      -
      -    /**
      -     * Example.
      -     */
      -    public static void main(String args[]) {
      -        try {
      -            System.setProperty("streamer.Link.debug", "true");
      -            System.setProperty("streamer.Element.debug", "true");
      -            System.setProperty("rdpclient.MockServer.debug", "true");
      -
      -            Pipeline pipeline = new PipelineImpl("echo client");
      -
      -            SocketWrapper socketWrapper = new SocketWrapper("socket");
      -
      -            pipeline.add(socketWrapper);
      -            pipeline.add(new BaseElement("echo"));
      -
      -            pipeline.link("socket", "echo", "socket");
      -
      -            final byte[] mockData = new byte[] {0x01, 0x02, 0x03};
      -            MockServer server = new MockServer(new Packet[] {new Packet("Server hello") {
      -                {
      -                    type = SERVER;
      -                    data = mockData;
      -                }
      -            }, new Packet("Client hello") {
      -                {
      -                    type = CLIENT;
      -                    data = mockData;
      -                }
      -            }, new Packet("Server hello") {
      -                {
      -                    type = SERVER;
      -                    data = mockData;
      -                }
      -            }, new Packet("Client hello") {
      -                {
      -                    type = CLIENT;
      -                    data = mockData;
      -                }
      -            }});
      -            server.start();
      -            InetSocketAddress address = server.getAddress();
      -
      -            socketWrapper.connect(address);
      -
      -        } catch (IOException e) {
      -            e.printStackTrace(System.err);
      -        }
      -
      -    }
       }
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/SocketWrapperImpl.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/SocketWrapperImpl.java
      new file mode 100755
      index 00000000000..da89a0d0417
      --- /dev/null
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/SocketWrapperImpl.java
      @@ -0,0 +1,249 @@
      +// Licensed to the Apache Software Foundation (ASF) under one
      +// or more contributor license agreements.  See the NOTICE file
      +// distributed with this work for additional information
      +// regarding copyright ownership.  The ASF licenses this file
      +// to you under the Apache License, Version 2.0 (the
      +// "License"); you may not use this file except in compliance
      +// with the License.  You may obtain a copy of the License at
      +//
      +//   http://www.apache.org/licenses/LICENSE-2.0
      +//
      +// Unless required by applicable law or agreed to in writing,
      +// software distributed under the License is distributed on an
      +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
      +// KIND, either express or implied.  See the License for the
      +// specific language governing permissions and limitations
      +// under the License.
      +package streamer;
      +
      +import static streamer.debug.MockServer.Packet.PacketType.CLIENT;
      +import static streamer.debug.MockServer.Packet.PacketType.SERVER;
      +
      +import java.io.IOException;
      +import java.io.InputStream;
      +import java.io.OutputStream;
      +import java.net.InetSocketAddress;
      +import java.net.Socket;
      +import java.util.HashMap;
      +
      +import javax.net.SocketFactory;
      +import javax.net.ssl.SSLContext;
      +import javax.net.ssl.SSLSocket;
      +import javax.net.ssl.SSLSocketFactory;
      +import javax.net.ssl.TrustManager;
      +
      +import streamer.debug.MockServer;
      +import streamer.debug.MockServer.Packet;
      +import streamer.ssl.SSLState;
      +import streamer.ssl.TrustAllX509TrustManager;
      +
      +public class SocketWrapperImpl extends PipelineImpl implements SocketWrapper {
      +
      +    protected InputStreamSource source;
      +    protected OutputStreamSink sink;
      +    protected Socket socket;
      +    protected InetSocketAddress address;
      +
      +    protected SSLSocket sslSocket;
      +
      +    protected String sslVersionToUse = "TLSv1.2";
      +
      +    protected SSLState sslState;
      +
      +    public SocketWrapperImpl(String id, SSLState sslState) {
      +        super(id);
      +        this.sslState = sslState;
      +    }
      +
      +    @Override
      +    protected HashMap initElementMap(String id) {
      +        HashMap map = new HashMap();
      +
      +        source = new InputStreamSource(id + "." + OUT, this);
      +        sink = new OutputStreamSink(id + "." + IN, this);
      +
      +        // Pass requests to read data to socket input stream
      +        map.put(OUT, source);
      +
      +        // All incoming data, which is sent to this socket wrapper, will be sent
      +        // to socket remote
      +        map.put(IN, sink);
      +
      +        return map;
      +    }
      +
      +    /**
      +     * Connect this socket wrapper to remote server and start main loop on
      +     * IputStreamSource stdout link, to watch for incoming data, and
      +     * OutputStreamSink stdin link, to pull for outgoing data.
      +     *
      +     * @param address
      +     * @throws IOException
      +     */
      +    @Override
      +    public void connect(InetSocketAddress address) throws IOException {
      +        this.address = address;
      +
      +        // Connect socket to server
      +        socket = SocketFactory.getDefault().createSocket();
      +        try {
      +            socket.connect(address);
      +
      +            InputStream is = socket.getInputStream();
      +            source.setInputStream(is);
      +
      +            OutputStream os = socket.getOutputStream();
      +            sink.setOutputStream(os);
      +
      +            // Start polling for data to send to remote sever
      +            runMainLoop(IN, STDIN, true, true);
      +
      +            // Push incoming data from server to handlers
      +            runMainLoop(OUT, STDOUT, false, false);
      +
      +        } finally {
      +            socket.close();
      +        }
      +    }
      +
      +    @Override
      +    public void handleEvent(Event event, Direction direction) {
      +        switch (event) {
      +        case SOCKET_UPGRADE_TO_SSL:
      +            upgradeToSsl();
      +            break;
      +        default:
      +            super.handleEvent(event, direction);
      +            break;
      +        }
      +    }
      +
      +    @Override
      +    public void upgradeToSsl() {
      +
      +        if (sslSocket != null)
      +            // Already upgraded
      +            return;
      +
      +        if (verbose)
      +            System.out.println("[" + this + "] INFO: Upgrading socket to SSL.");
      +
      +        try {
      +            // Use most secure implementation of SSL available now.
      +            // JVM will try to negotiate TLS1.2, then will fallback to TLS1.0, if
      +            // TLS1.2 is not supported.
      +            SSLContext sslContext = SSLContext.getInstance(sslVersionToUse);
      +
      +            // Trust all certificates (FIXME: insecure)
      +            sslContext.init(null, new TrustManager[] {new TrustAllX509TrustManager(sslState)}, null);
      +
      +            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
      +            sslSocket = (SSLSocket)sslSocketFactory.createSocket(socket, address.getHostName(), address.getPort(), true);
      +
      +            sslSocket.startHandshake();
      +
      +            InputStream sis = sslSocket.getInputStream();
      +            source.setInputStream(sis);
      +
      +            OutputStream sos = sslSocket.getOutputStream();
      +            sink.setOutputStream(sos);
      +
      +        } catch (Exception e) {
      +            throw new RuntimeException("Cannot upgrade socket to SSL: " + e.getMessage(), e);
      +        }
      +
      +    }
      +
      +    @Override
      +    public void validate() {
      +        for (Element element : elements.values())
      +            element.validate();
      +
      +        if (get(IN).getPads(Direction.IN).size() == 0)
      +            throw new RuntimeException("[ " + this + "] Input of socket is not connected.");
      +
      +        if (get(OUT).getPads(Direction.OUT).size() == 0)
      +            throw new RuntimeException("[ " + this + "] Output of socket is not connected.");
      +
      +    }
      +
      +    @Override
      +    public void shutdown() {
      +        try {
      +            handleEvent(Event.STREAM_CLOSE, Direction.IN);
      +        } catch (Exception e) {
      +        }
      +        try {
      +            handleEvent(Event.STREAM_CLOSE, Direction.OUT);
      +        } catch (Exception e) {
      +        }
      +        try {
      +            if (sslSocket != null)
      +                sslSocket.close();
      +        } catch (Exception e) {
      +        }
      +        try {
      +            socket.close();
      +        } catch (Exception e) {
      +        }
      +    }
      +
      +    @Override
      +    public String toString() {
      +        return "SocketWrapper(" + id + ")";
      +    }
      +
      +    /**
      +     * Example.
      +     */
      +    public static void main(String args[]) {
      +
      +        try {
      +            System.setProperty("streamer.Link.debug", "true");
      +            System.setProperty("streamer.Element.debug", "true");
      +            System.setProperty("rdpclient.MockServer.debug", "true");
      +
      +            Pipeline pipeline = new PipelineImpl("echo client");
      +
      +            SocketWrapperImpl socketWrapper = new SocketWrapperImpl("socket", null);
      +
      +            pipeline.add(socketWrapper);
      +            pipeline.add(new BaseElement("echo"));
      +            pipeline.add(new Queue("queue")); // To decouple input and output
      +
      +            pipeline.link("socket", "echo", "queue", "socket");
      +
      +            final byte[] mockData = new byte[] {0x01, 0x02, 0x03};
      +            MockServer server = new MockServer(new Packet[] {new Packet("Server hello") {
      +                {
      +                    type = SERVER;
      +                    data = mockData;
      +                }
      +            }, new Packet("Client hello") {
      +                {
      +                    type = CLIENT;
      +                    data = mockData;
      +                }
      +            }, new Packet("Server hello") {
      +                {
      +                    type = SERVER;
      +                    data = mockData;
      +                }
      +            }, new Packet("Client hello") {
      +                {
      +                    type = CLIENT;
      +                    data = mockData;
      +                }
      +            }});
      +            server.start();
      +            InetSocketAddress address = server.getAddress();
      +
      +            /*DEBUG*/System.out.println("Address: " + address);
      +            socketWrapper.connect(address);
      +
      +        } catch (Exception e) {
      +            e.printStackTrace(System.err);
      +        }
      +
      +    }
      +}
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/SyncLink.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/SyncLink.java
      old mode 100644
      new mode 100755
      index 2bd4919e5f4..94281d21c9d
      --- a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/SyncLink.java
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/SyncLink.java
      @@ -27,7 +27,7 @@ public class SyncLink implements Link {
            * avoid consuming of 100% of CPU in main loop in cases when link is pauses or
            * source element cannot produce data right now.
            */
      -    protected static final long STANDARD_DELAY_FOR_EMPTY_PACKET = 10; // Milliseconds
      +    public static final long STANDARD_DELAY_FOR_EMPTY_PACKET = 10; // Milliseconds
       
           /**
            * Delay for null packets in poll method when blocking is requested, in
      @@ -46,7 +46,8 @@ public class SyncLink implements Link {
           protected String id = null;
       
           /**
      -     * Buffer with data to hold because link is paused, or data is pushed back.
      +     * Buffer with data to hold because link is paused, on hold, or data is pushed
      +     * back from output element.
            */
           protected ByteBuffer cacheBuffer = null;
       
      @@ -61,11 +62,6 @@ public class SyncLink implements Link {
            */
           protected int packetNumber = 0;
       
      -    /**
      -     * Set to true to hold all data in link until it will be set to false again.
      -     */
      -    protected boolean paused = false;
      -
           /**
            * Element to pull data from, when in pull mode.
            */
      @@ -87,12 +83,24 @@ public class SyncLink implements Link {
            * Indicates that event STREAM_START is passed over this link, so main loop
            * can be started to pull data from source element.
            */
      -    protected boolean start;
      +    protected boolean started = false;
       
           /**
      -     * Operate in pull mode.
      +     * Set to true to hold all data in link until it will be set to false again.
            */
      -    protected boolean pullMode;
      +    protected boolean paused = false;
      +
      +    /**
      +     * Used by pull() method to hold all data in this link to avoid recursion when
      +     * source element is asked to push new data to it outputs.
      +     */
      +    protected boolean hold = false;
      +
      +    /**
      +     * Operate in pull mode instead of default push mode. In pull mode, link will
      +     * ask it source element for new data.
      +     */
      +    protected boolean pullMode = false;
       
           public SyncLink() {
           }
      @@ -139,7 +147,7 @@ public class SyncLink implements Link {
            */
           @Override
           public void sendData(ByteBuffer buf) {
      -        if (!paused && pullMode)
      +        if (!hold && pullMode)
                   throw new RuntimeException("[" + this + "] ERROR: link is not in push mode.");
       
               if (verbose)
      @@ -162,7 +170,7 @@ public class SyncLink implements Link {
               // When data pushed back and length of data is less than length of full
               // packet, then feed data to sink element immediately
               while (cacheBuffer != null) {
      -            if (paused) {
      +            if (paused || hold) {
                       if (verbose)
                           System.out.println("[" + this + "] INFO: Transfer is paused. Data in cache buffer: " + cacheBuffer + ".");
       
      @@ -172,8 +180,8 @@ public class SyncLink implements Link {
       
                   if (expectedPacketSize > 0 && cacheBuffer.length < expectedPacketSize) {
                       if (verbose)
      -                    System.out.println("[" + this + "] INFO: Transfer is suspended because available data is less than expected packet size. Expected packet size: " +
      -                        expectedPacketSize + ", data in cache buffer: " + cacheBuffer + ".");
      +                    System.out.println("[" + this + "] INFO: Transfer is suspended because available data is less than expected packet size. Expected packet size: "
      +                            + expectedPacketSize + ", data in cache buffer: " + cacheBuffer + ".");
       
                       // Wait until rest of packet will be read
                       return;
      @@ -203,43 +211,46 @@ public class SyncLink implements Link {
       
               // Shutdown main loop (if any) when STREAM_CLOSE event is received.
               switch (event) {
      -            case STREAM_START: {
      -                if (!start)
      -                    start = true;
      -                else
      -                    // Event already sent trough this link
      -                    return;
      -                break;
      -            }
      -            case STREAM_CLOSE: {
      -                if (!shutdown)
      -                    shutdown = true;
      -                else
      -                    // Event already sent trough this link
      -                    return;
      -                break;
      -            }
      -            case LINK_SWITCH_TO_PULL_MODE: {
      -                setPullMode();
      -                break;
      -            }
      +        case STREAM_START: {
      +            if (!started)
      +                started = true;
      +            else
      +                // Event already sent trough this link
      +                return;
      +            break;
      +        }
      +        case STREAM_CLOSE: {
      +            if (!shutdown)
      +                shutdown = true;
      +            else
      +                // Event already sent trough this link
      +                return;
      +            break;
      +        }
      +        case LINK_SWITCH_TO_PULL_MODE: {
      +            setPullMode();
      +            break;
      +        }
       
               }
       
               switch (direction) {
      -            case IN:
      -                source.handleEvent(event, direction);
      -                break;
      -            case OUT:
      -                sink.handleEvent(event, direction);
      -                break;
      +        case IN:
      +            source.handleEvent(event, direction);
      +            break;
      +        case OUT:
      +            sink.handleEvent(event, direction);
      +            break;
               }
           }
       
           @Override
           public ByteBuffer pull(boolean block) {
               if (!pullMode)
      -            throw new RuntimeException("This link is not in pull mode.");
      +            throw new RuntimeException("[" + this + "] ERROR: This link is not in pull mode.");
      +
      +        if (hold)
      +            throw new RuntimeException("[" + this + "] ERROR: This link is already on hold, waiting for data to be pulled in. Circular reference?");
       
               if (paused) {
                   if (verbose)
      @@ -269,9 +280,12 @@ public class SyncLink implements Link {
       
               // Pause this link, so incoming data will not be sent to sink
               // immediately, then ask source element for more data
      -        pause();
      -        source.poll(block);
      -        resume();
      +        try {
      +            hold = true;
      +            source.poll(block);
      +        } finally {
      +            hold = false;
      +        }
       
               // Can return something only when data was stored in buffer
               if (cacheBuffer != null && (expectedPacketSize == 0 || (expectedPacketSize > 0 && cacheBuffer.length >= expectedPacketSize))) {
      @@ -289,10 +303,11 @@ public class SyncLink implements Link {
           @Override
           public Element setSink(Element sink) {
               if (sink != null && this.sink != null)
      -            throw new RuntimeException("This link sink element is already set. Link: " + this + ", new sink: " + sink + ", existing sink: " + this.sink + ".");
      +            throw new RuntimeException("[" + this + "] ERROR: This link sink element is already set. Link: " + this + ", new sink: " + sink + ", existing sink: "
      +                    + this.sink + ".");
       
               if (sink == null && cacheBuffer != null)
      -            throw new RuntimeException("Cannot drop link: cache is not empty. Link: " + this + ", cache: " + cacheBuffer);
      +            throw new RuntimeException("[" + this + "] ERROR: Cannot drop link: cache is not empty. Link: " + this + ", cache: " + cacheBuffer);
       
               this.sink = sink;
       
      @@ -302,7 +317,8 @@ public class SyncLink implements Link {
           @Override
           public Element setSource(Element source) {
               if (this.source != null && source != null)
      -            throw new RuntimeException("This link source element is already set. Link: " + this + ", new source: " + source + ", existing source: " + this.source + ".");
      +            throw new RuntimeException("[" + this + "] ERROR: This link source element is already set. Link: " + this + ", new source: " + source
      +                    + ", existing source: " + this.source + ".");
       
               this.source = source;
               return source;
      @@ -321,7 +337,7 @@ public class SyncLink implements Link {
           @Override
           public void pause() {
               if (paused)
      -            throw new RuntimeException("Link is already paused.");
      +            throw new RuntimeException("[" + this + "] ERROR: Link is already paused.");
       
               paused = true;
       
      @@ -343,7 +359,7 @@ public class SyncLink implements Link {
           @Override
           public void run() {
               // Wait until even STREAM_START will arrive
      -        while (!start) {
      +        while (!started) {
                   delay();
               }
       
      @@ -374,8 +390,7 @@ public class SyncLink implements Link {
               try {
                   Thread.sleep(delay);
               } catch (InterruptedException e) {
      -            e.printStackTrace(System.err);
      -            throw new RuntimeException("Interrupted in main loop.", e);
      +            throw new RuntimeException("[" + this + "] ERROR: Interrupted in main loop.", e);
               }
           }
       
      @@ -384,16 +399,16 @@ public class SyncLink implements Link {
               if (verbose)
                   System.out.println("[" + this + "] INFO: Switching to PULL mode.");
       
      -        this.pullMode = true;
      +        pullMode = true;
           }
       
           @Override
           public void drop() {
               if (pullMode)
      -            throw new RuntimeException("Cannot drop link in pull mode.");
      +            throw new RuntimeException("[" + this + "] ERROR: Cannot drop link in pull mode.");
       
               if (cacheBuffer != null)
      -            throw new RuntimeException("Cannot drop link when cache conatains data: " + cacheBuffer + ".");
      +            throw new RuntimeException("[" + this + "] ERROR: Cannot drop link when cache conatains data: " + cacheBuffer + ".");
       
               source.dropLink(this);
               sink.dropLink(this);
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/apr/AprSocketSink.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/apr/AprSocketSink.java
      new file mode 100755
      index 00000000000..edfe8dbc752
      --- /dev/null
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/apr/AprSocketSink.java
      @@ -0,0 +1,129 @@
      +// Licensed to the Apache Software Foundation (ASF) under one
      +// or more contributor license agreements.  See the NOTICE file
      +// distributed with this work for additional information
      +// regarding copyright ownership.  The ASF licenses this file
      +// to you under the Apache License, Version 2.0 (the
      +// "License"); you may not use this file except in compliance
      +// with the License.  You may obtain a copy of the License at
      +//
      +//   http://www.apache.org/licenses/LICENSE-2.0
      +//
      +// Unless required by applicable law or agreed to in writing,
      +// software distributed under the License is distributed on an
      +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
      +// KIND, either express or implied.  See the License for the
      +// specific language governing permissions and limitations
      +// under the License.
      +package streamer.apr;
      +
      +import org.apache.tomcat.jni.Socket;
      +
      +import streamer.BaseElement;
      +import streamer.ByteBuffer;
      +import streamer.DataSource;
      +import streamer.Direction;
      +import streamer.Event;
      +import streamer.Link;
      +
      +public class AprSocketSink extends BaseElement {
      +
      +    protected AprSocketWrapperImpl socketWrapper;
      +    protected Long socket;
      +
      +    public AprSocketSink(String id) {
      +        super(id);
      +    }
      +
      +    public AprSocketSink(String id, AprSocketWrapperImpl socketWrapper) {
      +        super(id);
      +        this.socketWrapper = socketWrapper;
      +    }
      +
      +    public void setSocket(long socket) {
      +        this.socket = socket;
      +
      +        // Resume links
      +        resumeLinks();
      +    }
      +
      +    /**
      +     * Send incoming data to stream.
      +     */
      +    @Override
      +    public void handleData(ByteBuffer buf, Link link) {
      +        if (buf == null)
      +            return;
      +
      +        if (socketWrapper.shutdown)
      +            return;
      +
      +        try {
      +            if (verbose)
      +                System.out.println("[" + this + "] INFO: Writing data to stream: " + buf + ".");
      +
      +            // FIXME: If pull is destroyed or socket is closed, segfault will happen here
      +            Socket.send(socket, buf.data, buf.offset, buf.length);
      +        } catch (Exception e) {
      +            System.err.println("[" + this + "] ERROR: " + e.getMessage());
      +            closeStream();
      +        }
      +    }
      +
      +    @Override
      +    public void handleEvent(Event event, Direction direction) {
      +        switch (event) {
      +        case SOCKET_UPGRADE_TO_SSL:
      +            socketWrapper.upgradeToSsl();
      +            break;
      +        case LINK_SWITCH_TO_PULL_MODE:
      +            throw new RuntimeException("[" + this + "] ERROR: Unexpected event: sink recived LINK_SWITCH_TO_PULL_MODE event.");
      +        default:
      +            super.handleEvent(event, direction);
      +        }
      +    }
      +
      +    @Override
      +    public void setLink(String padName, Link link, Direction direction) {
      +        switch (direction) {
      +        case IN:
      +            super.setLink(padName, link, direction);
      +
      +            if (socket == null)
      +                // Pause links until data stream will be ready
      +                link.pause();
      +            break;
      +        case OUT:
      +            throw new RuntimeException("Cannot assign link to output pad in sink element. Element: " + this + ", pad: " + padName + ", link: " + link + ".");
      +        }
      +    }
      +
      +    private void resumeLinks() {
      +        for (DataSource source : inputPads.values())
      +            ((Link)source).resume();
      +    }
      +
      +    @Override
      +    protected void onClose() {
      +        closeStream();
      +    }
      +
      +    private void closeStream() {
      +        if (socketWrapper.shutdown)
      +            return;
      +
      +        if (verbose)
      +            System.out.println("[" + this + "] INFO: Closing stream.");
      +
      +        try {
      +            sendEventToAllPads(Event.STREAM_CLOSE, Direction.IN);
      +        } catch (Exception e) {
      +        }
      +        socketWrapper.shutdown();
      +    }
      +
      +    @Override
      +    public String toString() {
      +        return "AprSocketSink(" + id + ")";
      +    }
      +
      +}
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/apr/AprSocketSource.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/apr/AprSocketSource.java
      new file mode 100755
      index 00000000000..02983492e8d
      --- /dev/null
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/apr/AprSocketSource.java
      @@ -0,0 +1,171 @@
      +// Licensed to the Apache Software Foundation (ASF) under one
      +// or more contributor license agreements.  See the NOTICE file
      +// distributed with this work for additional information
      +// regarding copyright ownership.  The ASF licenses this file
      +// to you under the Apache License, Version 2.0 (the
      +// "License"); you may not use this file except in compliance
      +// with the License.  You may obtain a copy of the License at
      +//
      +//   http://www.apache.org/licenses/LICENSE-2.0
      +//
      +// Unless required by applicable law or agreed to in writing,
      +// software distributed under the License is distributed on an
      +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
      +// KIND, either express or implied.  See the License for the
      +// specific language governing permissions and limitations
      +// under the License.
      +package streamer.apr;
      +
      +import org.apache.tomcat.jni.Socket;
      +
      +import streamer.BaseElement;
      +import streamer.ByteBuffer;
      +import streamer.DataSink;
      +import streamer.Direction;
      +import streamer.Event;
      +import streamer.Link;
      +
      +/**
      + * Source element, which reads data from InputStream.
      + */
      +public class AprSocketSource extends BaseElement {
      +
      +    protected AprSocketWrapperImpl socketWrapper;
      +    protected Long socket;
      +
      +    public AprSocketSource(String id) {
      +        super(id);
      +    }
      +
      +    public AprSocketSource(String id, AprSocketWrapperImpl socketWrapper) {
      +        super(id);
      +        this.socketWrapper = socketWrapper;
      +    }
      +
      +    @Override
      +    public void handleEvent(Event event, Direction direction) {
      +        switch (event) {
      +        case SOCKET_UPGRADE_TO_SSL:
      +            socketWrapper.upgradeToSsl();
      +            break;
      +        case LINK_SWITCH_TO_PULL_MODE:
      +            // Do nothing - this is the source
      +            break;
      +        default:
      +            super.handleEvent(event, direction);
      +        }
      +    }
      +
      +    @Override
      +    public void setLink(String padName, Link link, Direction direction) {
      +        switch (direction) {
      +        case OUT:
      +            super.setLink(padName, link, direction);
      +
      +            if (socket == null) {
      +                // Pause links until data stream will be ready
      +                link.pause();
      +            }
      +            break;
      +        case IN:
      +            throw new RuntimeException("Cannot assign link to input pad in source element. Element: " + this + ", pad: " + padName + ", link: " + link + ".");
      +        }
      +    }
      +
      +    public void setSocket(long socket) {
      +        this.socket = socket;
      +
      +        // Resume links
      +        resumeLinks();
      +    }
      +
      +    private void resumeLinks() {
      +        for (DataSink sink : outputPads.values())
      +            ((Link)sink).resume();
      +    }
      +
      +    /**
      +     * Read data from input stream.
      +     */
      +    @Override
      +    public void poll(boolean block) {
      +        if (socketWrapper.shutdown) {
      +            socketWrapper.destroyPull();
      +            return;
      +        }
      +
      +        try {
      +            // Create buffer of recommended size and with default offset
      +            ByteBuffer buf = new ByteBuffer(incommingBufLength);
      +
      +            if (verbose)
      +                System.out.println("[" + this + "] INFO: Reading data from stream.");
      +
      +            // FIXME: If pull is destroyed or socket is closed, segfault will happen here
      +            int actualLength = (block) ? // Blocking read
      +                    Socket.recv(socket, buf.data, buf.offset, buf.data.length - buf.offset)
      +                    : // Non-blocking read
      +                        Socket.recvt(socket, buf.data, buf.offset, buf.data.length - buf.offset, 1);
      +
      +                    if (socketWrapper.shutdown) {
      +                        socketWrapper.destroyPull();
      +                        return;
      +                    }
      +
      +                    if (actualLength < 0) {
      +                        if (verbose)
      +                            System.out.println("[" + this + "] INFO: End of stream.");
      +
      +                        buf.unref();
      +                        closeStream();
      +                        sendEventToAllPads(Event.STREAM_CLOSE, Direction.OUT);
      +                        return;
      +                    }
      +
      +                    if (actualLength == 0) {
      +                        if (verbose)
      +                            System.out.println("[" + this + "] INFO: Empty buffer is read from stream.");
      +
      +                        buf.unref();
      +                        return;
      +                    }
      +
      +                    buf.length = actualLength;
      +
      +                    if (verbose)
      +                        System.out.println("[" + this + "] INFO: Data read from stream: " + buf + ".");
      +
      +                    pushDataToAllOuts(buf);
      +
      +        } catch (Exception e) {
      +            System.err.println("[" + this + "] ERROR: " + e.getMessage());
      +            closeStream();
      +        }
      +    }
      +
      +    @Override
      +    protected void onClose() {
      +        closeStream();
      +    }
      +
      +    private void closeStream() {
      +
      +        if (socketWrapper.shutdown)
      +            return;
      +
      +        if (verbose)
      +            System.out.println("[" + this + "] INFO: Closing stream.");
      +
      +        try {
      +            sendEventToAllPads(Event.STREAM_CLOSE, Direction.OUT);
      +        } catch (Exception e) {
      +        }
      +        socketWrapper.shutdown();
      +    }
      +
      +    @Override
      +    public String toString() {
      +        return "AprSocketSource(" + id + ")";
      +    }
      +
      +}
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/apr/AprSocketWrapperImpl.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/apr/AprSocketWrapperImpl.java
      new file mode 100755
      index 00000000000..2ee426b89c3
      --- /dev/null
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/apr/AprSocketWrapperImpl.java
      @@ -0,0 +1,281 @@
      +// Licensed to the Apache Software Foundation (ASF) under one
      +// or more contributor license agreements.  See the NOTICE file
      +// distributed with this work for additional information
      +// regarding copyright ownership.  The ASF licenses this file
      +// to you under the Apache License, Version 2.0 (the
      +// "License"); you may not use this file except in compliance
      +// with the License.  You may obtain a copy of the License at
      +//
      +//   http://www.apache.org/licenses/LICENSE-2.0
      +//
      +// Unless required by applicable law or agreed to in writing,
      +// software distributed under the License is distributed on an
      +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
      +// KIND, either express or implied.  See the License for the
      +// specific language governing permissions and limitations
      +// under the License.
      +package streamer.apr;
      +
      +import static streamer.debug.MockServer.Packet.PacketType.CLIENT;
      +import static streamer.debug.MockServer.Packet.PacketType.SERVER;
      +
      +import java.io.IOException;
      +import java.net.InetSocketAddress;
      +import java.util.HashMap;
      +
      +import org.apache.tomcat.jni.Address;
      +import org.apache.tomcat.jni.Error;
      +import org.apache.tomcat.jni.Library;
      +import org.apache.tomcat.jni.Pool;
      +import org.apache.tomcat.jni.SSL;
      +import org.apache.tomcat.jni.SSLContext;
      +import org.apache.tomcat.jni.SSLSocket;
      +import org.apache.tomcat.jni.Socket;
      +
      +import streamer.BaseElement;
      +import streamer.Direction;
      +import streamer.Element;
      +import streamer.Event;
      +import streamer.Pipeline;
      +import streamer.PipelineImpl;
      +import streamer.Queue;
      +import streamer.SocketWrapper;
      +import streamer.debug.MockServer;
      +import streamer.debug.MockServer.Packet;
      +import streamer.ssl.SSLState;
      +import sun.security.x509.X509CertImpl;
      +
      +public class AprSocketWrapperImpl extends PipelineImpl implements SocketWrapper {
      +
      +    static {
      +        try {
      +            Library.initialize(null);
      +            SSL.initialize(null);
      +        } catch (Exception e) {
      +            throw new RuntimeException("Cannot load Tomcat Native Library (Apache Portable Runtime).", e);
      +        }
      +    }
      +
      +    private final SSLState sslState;
      +
      +    final long pool = Pool.create(0);
      +    long inetAddress;
      +    long socket;
      +    private AprSocketSource source;
      +    private AprSocketSink sink;
      +
      +    boolean shutdown = false;
      +
      +    private final boolean shutdowned = false;
      +
      +    public AprSocketWrapperImpl(String id, SSLState sslState) {
      +        super(id);
      +        this.sslState = sslState;
      +    }
      +
      +    @Override
      +    protected HashMap initElementMap(String id) {
      +        HashMap map = new HashMap();
      +
      +        source = new AprSocketSource(id + "." + OUT, this);
      +        sink = new AprSocketSink(id + "." + IN, this);
      +
      +        // Pass requests to read data to socket input stream
      +        map.put(OUT, source);
      +
      +        // All incoming data, which is sent to this socket wrapper, will be sent
      +        // to socket remote
      +        map.put(IN, sink);
      +
      +        return map;
      +    }
      +
      +    /**
      +     * Connect this socket wrapper to remote server and start main loop on
      +     * AprSocketSource stdout link, to watch for incoming data, and
      +     * AprSocketSink stdin link, to pull for outgoing data.
      +     */
      +    @Override
      +    public void connect(InetSocketAddress address) throws IOException {
      +        try {
      +            inetAddress = Address.info(address.getHostName(), Socket.APR_UNSPEC, address.getPort(), 0, pool);
      +            socket = Socket.create(Address.getInfo(inetAddress).family, Socket.SOCK_STREAM, Socket.APR_PROTO_TCP, pool);
      +        } catch (Exception e) {
      +            throw new IOException("[" + this + "] ERROR: Cannot create socket for \"" + address + "\".", e);
      +        }
      +
      +        int ret = Socket.connect(socket, inetAddress);
      +        if (ret != 0)
      +            throw new IOException("[" + this + "] ERROR: Cannot connect to remote host \"" + address + "\": " + Error.strerror(ret));
      +
      +        source.setSocket(socket);
      +        sink.setSocket(socket);
      +
      +        // Start polling for data to send to remote sever
      +        runMainLoop(IN, STDIN, true, true);
      +
      +        // Push incoming data from server to handlers
      +        runMainLoop(OUT, STDOUT, false, false);
      +
      +    }
      +
      +    @Override
      +    public void handleEvent(Event event, Direction direction) {
      +        switch (event) {
      +        case SOCKET_UPGRADE_TO_SSL:
      +            upgradeToSsl();
      +            break;
      +        default:
      +            super.handleEvent(event, direction);
      +            break;
      +        }
      +    }
      +
      +    @Override
      +    public void validate() {
      +
      +        if (getPads(Direction.IN).size() == 0)
      +            throw new RuntimeException("[ " + this + "] BUG: Input of socket is not connected.");
      +
      +        if (getPads(Direction.OUT).size() == 0)
      +            throw new RuntimeException("[ " + this + "] BUG: Output of socket is not connected.");
      +
      +    }
      +
      +    @Override
      +    public void upgradeToSsl() {
      +
      +        try {
      +            long sslContext;
      +            try {
      +                sslContext = SSLContext.make(pool, SSL.SSL_PROTOCOL_TLSV1, SSL.SSL_MODE_CLIENT);
      +            } catch (Exception e) {
      +                throw new RuntimeException("Cannot create SSL context using Tomcat native library.", e);
      +            }
      +
      +            SSLContext.setOptions(sslContext, SSL.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS | SSL.SSL_OP_TLS_BLOCK_PADDING_BUG | SSL.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
      +                    | SSL.SSL_OP_MSIE_SSLV2_RSA_PADDING);
      +            // FIXME: verify certificate by default
      +            SSLContext.setVerify(sslContext, SSL.SSL_CVERIFY_NONE, 0);
      +            int ret;
      +            try {
      +                ret = SSLSocket.attach(sslContext, socket);
      +            } catch (Exception e) {
      +                throw new RuntimeException("[" + this + "] ERROR: Cannot attach SSL context to socket: ", e);
      +            }
      +            if (ret != 0)
      +                throw new RuntimeException("[" + this + "] ERROR: Cannot attach SSL context to socket(" + ret + "): " + SSL.getLastError());
      +
      +            try {
      +                ret = SSLSocket.handshake(socket);
      +            } catch (Exception e) {
      +                throw new RuntimeException("[" + this + "] ERROR: Cannot make SSL handshake with server: ", e);
      +            }
      +            if (ret != 0 && ret != 20014) // 20014: bad certificate signature FIXME: show prompt for self signed certificate
      +                throw new RuntimeException("[" + this + "] ERROR: Cannot make SSL handshake with server(" + ret + "): " + SSL.getLastError());
      +
      +            try {
      +                byte[] key = SSLSocket.getInfoB(socket, SSL.SSL_INFO_CLIENT_CERT);
      +                //*DEBUG*/System.out.println("DEBUG: Server cert:\n"+new ByteBuffer(key).dump());
      +                sslState.serverCertificateSubjectPublicKeyInfo = new X509CertImpl(key).getPublicKey().getEncoded();
      +            } catch (Exception e) {
      +                throw new RuntimeException("[" + this + "] ERROR: Cannot get server public key: ", e);
      +            }
      +
      +        } catch (RuntimeException e) {
      +            shutdown();
      +            throw e;
      +        }
      +    }
      +
      +    @Override
      +    public void shutdown() {
      +        if (shutdown)
      +            return;
      +
      +        shutdown = true;
      +
      +        try {
      +            handleEvent(Event.STREAM_CLOSE, Direction.IN);
      +        } catch (Exception e) {
      +        }
      +        try {
      +            handleEvent(Event.STREAM_CLOSE, Direction.OUT);
      +        } catch (Exception e) {
      +        }
      +    }
      +
      +    void destroyPull() {
      +        if (shutdowned)
      +            return;
      +
      +        // Causes segfault in AprSocketSource.poll() method, so this function must be called from it
      +        try {
      +            Socket.close(socket);
      +            // or
      +            // Socket.shutdown(socket, Socket.APR_SHUTDOWN_READWRITE);
      +            Pool.destroy(pool);
      +        } catch (Exception e) {
      +        }
      +
      +    }
      +
      +    @Override
      +    public String toString() {
      +        return "AprSocketWrapper(" + id + ")";
      +    }
      +
      +    /**
      +     * Example.
      +     */
      +    public static void main(String args[]) {
      +
      +        try {
      +            System.setProperty("streamer.Link.debug", "true");
      +            System.setProperty("streamer.Element.debug", "true");
      +            System.setProperty("rdpclient.MockServer.debug", "true");
      +
      +            Pipeline pipeline = new PipelineImpl("echo client");
      +
      +            AprSocketWrapperImpl socketWrapper = new AprSocketWrapperImpl("socket", null);
      +
      +            pipeline.add(socketWrapper);
      +            pipeline.add(new BaseElement("echo"));
      +            pipeline.add(new Queue("queue")); // To decouple input and output
      +
      +            pipeline.link("socket", "echo", "queue", "socket");
      +
      +            final byte[] mockData = new byte[] {0x01, 0x02, 0x03};
      +            MockServer server = new MockServer(new Packet[] {new Packet("Server hello") {
      +                {
      +                    type = SERVER;
      +                    data = mockData;
      +                }
      +            }, new Packet("Client hello") {
      +                {
      +                    type = CLIENT;
      +                    data = mockData;
      +                }
      +            }, new Packet("Server hello") {
      +                {
      +                    type = SERVER;
      +                    data = mockData;
      +                }
      +            }, new Packet("Client hello") {
      +                {
      +                    type = CLIENT;
      +                    data = mockData;
      +                }
      +            }});
      +            server.start();
      +            InetSocketAddress address = server.getAddress();
      +
      +            socketWrapper.connect(address);
      +
      +        } catch (Exception e) {
      +            e.printStackTrace(System.err);
      +        }
      +
      +    }
      +
      +}
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/bco/BcoSocketWrapperImpl.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/bco/BcoSocketWrapperImpl.java
      new file mode 100755
      index 00000000000..67e2dbd019e
      --- /dev/null
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/bco/BcoSocketWrapperImpl.java
      @@ -0,0 +1,119 @@
      +// Licensed to the Apache Software Foundation (ASF) under one
      +// or more contributor license agreements.  See the NOTICE file
      +// distributed with this work for additional information
      +// regarding copyright ownership.  The ASF licenses this file
      +// to you under the Apache License, Version 2.0 (the
      +// "License"); you may not use this file except in compliance
      +// with the License.  You may obtain a copy of the License at
      +//
      +//   http://www.apache.org/licenses/LICENSE-2.0
      +//
      +// Unless required by applicable law or agreed to in writing,
      +// software distributed under the License is distributed on an
      +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
      +// KIND, either express or implied.  See the License for the
      +// specific language governing permissions and limitations
      +// under the License.
      +package streamer.bco;
      +
      +import java.io.IOException;
      +import java.io.InputStream;
      +import java.io.OutputStream;
      +import java.security.SecureRandom;
      +import java.security.Security;
      +
      +import org.bouncycastle.asn1.x509.X509CertificateStructure;
      +import org.bouncycastle.crypto.tls.CertificateVerifyer;
      +import org.bouncycastle.crypto.tls.TlsProtocolHandler;
      +import org.bouncycastle.jce.provider.BouncyCastleProvider;
      +
      +import streamer.Direction;
      +import streamer.Event;
      +import streamer.SocketWrapperImpl;
      +import streamer.ssl.SSLState;
      +
      +@SuppressWarnings("deprecation")
      +public class BcoSocketWrapperImpl extends SocketWrapperImpl {
      +
      +    static {
      +        Security.addProvider(new BouncyCastleProvider());
      +    }
      +
      +    private TlsProtocolHandler bcoSslSocket;
      +
      +    public BcoSocketWrapperImpl(String id, SSLState sslState) {
      +        super(id, sslState);
      +    }
      +
      +    @Override
      +    public void upgradeToSsl() {
      +
      +        if (sslSocket != null)
      +            // Already upgraded
      +            return;
      +
      +        if (verbose)
      +            System.out.println("[" + this + "] INFO: Upgrading socket to SSL.");
      +
      +        try {
      +
      +            SecureRandom secureRandom = new SecureRandom();
      +            bcoSslSocket = new TlsProtocolHandler(socket.getInputStream(), socket.getOutputStream(), secureRandom);
      +
      +            CertificateVerifyer client = new CertificateVerifyer() {
      +
      +                @Override
      +                public boolean isValid(X509CertificateStructure[] chain) {
      +
      +                    try {
      +                        if (sslState != null) {
      +                            sslState.serverCertificateSubjectPublicKeyInfo = chain[0].getSubjectPublicKeyInfo().getEncoded();
      +                        }
      +                    } catch (IOException e) {
      +                        throw new RuntimeException("Cannot get server public key.", e);
      +                    }
      +
      +                    return true;
      +                }
      +            };
      +            bcoSslSocket.connect(client);
      +
      +            InputStream sis = bcoSslSocket.getInputStream();
      +            source.setInputStream(sis);
      +
      +            OutputStream sos = bcoSslSocket.getOutputStream();
      +            sink.setOutputStream(sos);
      +
      +        } catch (Exception e) {
      +            throw new RuntimeException("Cannot upgrade socket to SSL: " + e.getMessage(), e);
      +        }
      +
      +    }
      +
      +    @Override
      +    public void shutdown() {
      +        try {
      +            handleEvent(Event.STREAM_CLOSE, Direction.IN);
      +        } catch (Exception e) {
      +        }
      +        try {
      +            handleEvent(Event.STREAM_CLOSE, Direction.OUT);
      +        } catch (Exception e) {
      +        }
      +        try {
      +            if (bcoSslSocket != null)
      +                bcoSslSocket.close();
      +        } catch (Exception e) {
      +        }
      +        try {
      +            socket.close();
      +        } catch (Exception e) {
      +        }
      +    }
      +
      +    @Override
      +    public String toString() {
      +        return "BcoSocketWrapper(" + id + ")";
      +    }
      +
      +}
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/AssertingByteBuffer.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/debug/AssertingByteBuffer.java
      old mode 100644
      new mode 100755
      similarity index 98%
      rename from services/console-proxy-rdp/rdpconsole/src/main/java/streamer/AssertingByteBuffer.java
      rename to services/console-proxy-rdp/rdpconsole/src/main/java/streamer/debug/AssertingByteBuffer.java
      index fe9cc50ad60..15449c315ba
      --- a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/AssertingByteBuffer.java
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/debug/AssertingByteBuffer.java
      @@ -14,10 +14,12 @@
       // KIND, either express or implied.  See the License for the
       // specific language governing permissions and limitations
       // under the License.
      -package streamer;
      +package streamer.debug;
       
       import java.nio.charset.Charset;
       
      +import streamer.ByteBuffer;
      +
       /**
        * Assert that writes to this buffer are matching expected data.
        */
      diff --git a/api/src/org/apache/cloudstack/api/IdentityService.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/debug/Dumper.java
      old mode 100644
      new mode 100755
      similarity index 79%
      rename from api/src/org/apache/cloudstack/api/IdentityService.java
      rename to services/console-proxy-rdp/rdpconsole/src/main/java/streamer/debug/Dumper.java
      index 8451945ef81..c884cfbdfa7
      --- a/api/src/org/apache/cloudstack/api/IdentityService.java
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/debug/Dumper.java
      @@ -14,10 +14,15 @@
       // KIND, either express or implied.  See the License for the
       // specific language governing permissions and limitations
       // under the License.
      -package org.apache.cloudstack.api;
      +package streamer.debug;
       
      -public interface IdentityService {
      -    Long getIdentityId(String tableName, String identityString);
      +import streamer.ByteBuffer;
      +
      +public interface Dumper {
      +
      +    /**
      +     * Parse and dump content of buffer.
      +     */
      +    void dump(ByteBuffer buf);
       
      -    String getIdentityUuid(String tableName, String identityString);
       }
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/FakeSink.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/debug/FakeSink.java
      old mode 100644
      new mode 100755
      similarity index 90%
      rename from services/console-proxy-rdp/rdpconsole/src/main/java/streamer/FakeSink.java
      rename to services/console-proxy-rdp/rdpconsole/src/main/java/streamer/debug/FakeSink.java
      index e373b19a10c..93154886503
      --- a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/FakeSink.java
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/debug/FakeSink.java
      @@ -14,7 +14,15 @@
       // KIND, either express or implied.  See the License for the
       // specific language governing permissions and limitations
       // under the License.
      -package streamer;
      +package streamer.debug;
      +
      +import streamer.BaseElement;
      +import streamer.ByteBuffer;
      +import streamer.Direction;
      +import streamer.Element;
      +import streamer.Event;
      +import streamer.Link;
      +import streamer.SyncLink;
       
       public class FakeSink extends BaseElement {
       
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/FakeSource.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/debug/FakeSource.java
      old mode 100644
      new mode 100755
      similarity index 86%
      rename from services/console-proxy-rdp/rdpconsole/src/main/java/streamer/FakeSource.java
      rename to services/console-proxy-rdp/rdpconsole/src/main/java/streamer/debug/FakeSource.java
      index 9056852855b..7f0c554cab0
      --- a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/FakeSource.java
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/debug/FakeSource.java
      @@ -14,7 +14,15 @@
       // KIND, either express or implied.  See the License for the
       // specific language governing permissions and limitations
       // under the License.
      -package streamer;
      +package streamer.debug;
      +
      +import streamer.BaseElement;
      +import streamer.ByteBuffer;
      +import streamer.Direction;
      +import streamer.Element;
      +import streamer.Event;
      +import streamer.Link;
      +import streamer.SyncLink;
       
       public class FakeSource extends BaseElement {
       
      @@ -40,7 +48,8 @@ public class FakeSource extends BaseElement {
               ByteBuffer buf = initializeData();
       
               // Push it to output(s)
      -        pushDataToAllOuts(buf);
      +        if (buf != null)
      +            pushDataToAllOuts(buf);
       
               // Make slight delay when blocking input was requested (to avoid
               // consuming of 100% in parent loop)
      @@ -85,26 +94,29 @@ public class FakeSource extends BaseElement {
               return "FakeSource(" + id + ")";
           }
       
      +    /**
      +     * Example.
      +     */
           public static void main(String args[]) {
       
               Element fakeSource = new FakeSource("source 3/10/100") {
                   {
                       verbose = true;
      -                this.incommingBufLength = 3;
      -                this.numBuffers = 10;
      -                this.delay = 100;
      +                incommingBufLength = 3;
      +                numBuffers = 10;
      +                delay = 100;
                   }
               };
       
               Element fakeSink = new FakeSink("sink") {
                   {
      -                this.verbose = true;
      +                verbose = true;
                   }
               };
       
               Element fakeSink2 = new FakeSink("sink2") {
                   {
      -                this.verbose = true;
      +                verbose = true;
                   }
               };
       
      @@ -118,6 +130,7 @@ public class FakeSource extends BaseElement {
               fakeSource.setLink("out2", link2, Direction.OUT);
               fakeSink2.setLink(STDIN, link2, Direction.IN);
       
      +        link.sendEvent(Event.STREAM_START, Direction.IN);
               link.run();
       
           }
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/MockServer.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/debug/MockServer.java
      old mode 100644
      new mode 100755
      similarity index 57%
      rename from services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/MockServer.java
      rename to services/console-proxy-rdp/rdpconsole/src/main/java/streamer/debug/MockServer.java
      index 72e4a6f182c..348a006c1aa
      --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/MockServer.java
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/debug/MockServer.java
      @@ -14,7 +14,7 @@
       // KIND, either express or implied.  See the License for the
       // specific language governing permissions and limitations
       // under the License.
      -package rdpclient;
      +package streamer.debug;
       
       import java.io.IOException;
       import java.io.InputStream;
      @@ -51,7 +51,9 @@ public class MockServer implements Runnable {
               exception = null;
               shutdowned = false;
       
      -        new Thread(this).start();
      +        Thread thread = new Thread(this);
      +        thread.setDaemon(true);
      +        thread.start();
           }
       
           @Override
      @@ -60,6 +62,9 @@ public class MockServer implements Runnable {
               try {
                   Socket socket = serverSocket.accept();
       
      +            if (verbose)
      +                System.out.println("[" + this + "] INFO: Clien connected: " + socket.getRemoteSocketAddress() + ".");
      +
                   InputStream is = socket.getInputStream();
                   OutputStream os = socket.getOutputStream();
       
      @@ -68,58 +73,58 @@ public class MockServer implements Runnable {
       
                           Packet packet = packets[i];
                           switch (packet.type) {
      -                        case CLIENT: {
      -                            // Read client data and compare it with mock data
      -                            // (unless "ignore" option is set)
      -                            byte actualData[] = new byte[packet.data.length];
      -                            int actualDataLength = is.read(actualData);
      +                    case CLIENT: {
      +                        // Read client data and compare it with mock data
      +                        // (unless "ignore" option is set)
      +                        byte actualData[] = new byte[packet.data.length];
      +                        int actualDataLength = is.read(actualData);
       
      -                            if (verbose)
      -                                System.out.println("[" + this + "] INFO: Data is read: {" + Arrays.toString(Arrays.copyOf(actualData, actualDataLength)) + "}.");
      +                        if (verbose)
      +                            System.out.println("[" + this + "] INFO: Data is read: {" + Arrays.toString(Arrays.copyOf(actualData, actualDataLength)) + "}.");
       
      -                            if (!packet.ignore) {
      -                                // Compare actual data with expected data
      -                                if (actualDataLength != packet.data.length) {
      -                                    throw new AssertionError("Actual length of client request for packet #" + (i + 1) + " (\"" + packet.id + "\")" +
      -                                        " does not match length of expected client request. Actual length: " + actualDataLength + ", expected legnth: " +
      -                                        packet.data.length + ".");
      -                                }
      +                        if (!packet.ignore) {
      +                            // Compare actual data with expected data
      +                            if (actualDataLength != packet.data.length) {
      +                                throw new AssertionError("Actual length of client request for packet #" + (i + 1) + " (\"" + packet.id + "\")"
      +                                        + " does not match length of expected client request. Actual length: " + actualDataLength + ", expected legnth: " + packet.data.length
      +                                        + ".");
      +                            }
       
      -                                for (int j = 0; j < packet.data.length; j++) {
      +                            for (int j = 0; j < packet.data.length; j++) {
       
      -                                    if (packet.data[j] != actualData[j]) {
      -                                        throw new AssertionError("Actual byte #" + (j + 1) + " of client request for packet #" + (i + 1) + " (\"" + packet.id + "\")" +
      -                                            " does not match corresponding byte of expected client request. Actual byte: " + actualData[j] + ", expected byte: " +
      -                                            packet.data[j] + ".");
      -                                    }
      +                                if (packet.data[j] != actualData[j]) {
      +                                    throw new AssertionError("Actual byte #" + (j + 1) + " of client request for packet #" + (i + 1) + " (\"" + packet.id + "\")"
      +                                            + " does not match corresponding byte of expected client request. Actual byte: " + actualData[j] + ", expected byte: " + packet.data[j]
      +                                                    + ".");
                                       }
                                   }
      -                            break;
                               }
      -                        case SERVER: {
      -                            // Send mock data to client
      -                            os.write(packet.data);
      +                        break;
      +                    }
      +                    case SERVER: {
      +                        // Send mock data to client
      +                        os.write(packet.data);
       
      -                            if (verbose)
      -                                System.out.println("[" + this + "] INFO: Data is written: {" + Arrays.toString(packet.data) + "}.");
      +                        if (verbose)
      +                            System.out.println("[" + this + "] INFO: Data is written: {" + Arrays.toString(packet.data) + "}.");
       
      -                            break;
      -                        }
      -                        case UPGRADE_TO_SSL: {
      -                            // Attach SSL context to socket
      +                        break;
      +                    }
      +                    case UPGRADE_TO_SSL: {
      +                        // Attach SSL context to socket
       
      -                            final SSLSocketFactory sslSocketFactory = (SSLSocketFactory)SSLSocketFactory.getDefault();
      -                            SSLSocket sslSocket = (SSLSocket)sslSocketFactory.createSocket(socket, null, serverSocket.getLocalPort(), true);
      -                            sslSocket.setEnabledCipherSuites(sslSocket.getSupportedCipherSuites());
      -                            sslSocket.setUseClientMode(false);
      -                            sslSocket.startHandshake();
      -                            is = sslSocket.getInputStream();
      -                            os = sslSocket.getOutputStream();
      +                        final SSLSocketFactory sslSocketFactory = (SSLSocketFactory)SSLSocketFactory.getDefault();
      +                        SSLSocket sslSocket = (SSLSocket)sslSocketFactory.createSocket(socket, null, serverSocket.getLocalPort(), true);
      +                        sslSocket.setEnabledCipherSuites(sslSocket.getSupportedCipherSuites());
      +                        sslSocket.setUseClientMode(false);
      +                        sslSocket.startHandshake();
      +                        is = sslSocket.getInputStream();
      +                        os = sslSocket.getOutputStream();
       
      -                            break;
      -                        }
      -                        default:
      -                            throw new RuntimeException("Unknown packet type: " + packet.type);
      +                        break;
      +                    }
      +                    default:
      +                        throw new RuntimeException("Unknown packet type: " + packet.type);
                           }
       
                       }
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/debug/MockSink.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/debug/MockSink.java
      new file mode 100755
      index 00000000000..fe038a96454
      --- /dev/null
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/debug/MockSink.java
      @@ -0,0 +1,154 @@
      +// Licensed to the Apache Software Foundation (ASF) under one
      +// or more contributor license agreements.  See the NOTICE file
      +// distributed with this work for additional information
      +// regarding copyright ownership.  The ASF licenses this file
      +// to you under the Apache License, Version 2.0 (the
      +// "License"); you may not use this file except in compliance
      +// with the License.  You may obtain a copy of the License at
      +//
      +//   http://www.apache.org/licenses/LICENSE-2.0
      +//
      +// Unless required by applicable law or agreed to in writing,
      +// software distributed under the License is distributed on an
      +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
      +// KIND, either express or implied.  See the License for the
      +// specific language governing permissions and limitations
      +// under the License.
      +package streamer.debug;
      +
      +import java.util.Arrays;
      +import java.util.Set;
      +
      +import streamer.BaseElement;
      +import streamer.ByteBuffer;
      +import streamer.Direction;
      +import streamer.Element;
      +import streamer.Link;
      +import streamer.SyncLink;
      +
      +/**
      + * Compare incoming packets with expected packets.
      + */
      +public class MockSink extends BaseElement {
      +
      +    protected ByteBuffer bufs[];
      +    protected Dumper dumper;
      +
      +    public MockSink(String id) {
      +        super(id);
      +    }
      +
      +    public MockSink(String id, ByteBuffer bufs[]) {
      +        super(id);
      +        this.bufs = bufs;
      +    }
      +
      +    public MockSink(String id, ByteBuffer bufs[], Dumper dumper) {
      +        super(id);
      +        this.bufs = bufs;
      +        this.dumper = dumper;
      +    }
      +
      +    @Override
      +    public void handleData(ByteBuffer buf, Link link) {
      +        if (verbose)
      +            System.out.println("[" + this + "] INFO: Received buf #" + (packetNumber) + " " + buf + ".");
      +
      +        if (buf == null)
      +            return;
      +
      +        if (packetNumber >= bufs.length)
      +            throw new AssertionError("[" + this + "] Incoming buffer #" + packetNumber + " is not expected. Number of expected buffers: " + bufs.length
      +                    + ", unexpected buffer: " + buf + ".");
      +
      +        // Compare incoming buffer with expected buffer
      +        ByteBuffer expectedBuf = bufs[packetNumber];
      +        if (!Arrays.equals(expectedBuf.toByteArray(), buf.toByteArray())) {
      +            dump(buf, expectedBuf);
      +            throw new AssertionError("[" + this + "] Incoming buffer #" + packetNumber + " is not equal to expected buffer.\n  Actual bufer: " + buf
      +                    + ",\n  expected buffer: " + expectedBuf + ".");
      +        }
      +
      +        // If expected buffer has metadata, then compare it too
      +        Set metadataKeys = expectedBuf.getMetadataKeys();
      +        if (metadataKeys.size() > 0) {
      +            for (String key : metadataKeys) {
      +                Object expectedValue = expectedBuf.getMetadata(key);
      +                Object actualValue = buf.getMetadata(key);
      +                if (actualValue == null)
      +                    throw new AssertionError("[" + this + "] Incoming buffer #" + packetNumber + " is not equal to expected buffer in metadata for key \"" + key
      +                            + "\".\n  Actual metadata value: " + actualValue + ",\n  expected value: \"" + expectedValue + "\".");
      +
      +                if (!expectedValue.equals(actualValue))
      +                    throw new AssertionError("[" + this + "] Incoming buffer #" + packetNumber + " is not equal to expected buffer in metadata for key \"" + key
      +                            + "\".\n  Actual metadata value: \"" + actualValue + "\",\n  expected value: \"" + expectedValue + "\".");
      +            }
      +        }
      +
      +        if (verbose)
      +            System.out.println("[" + this + "] INFO: buffers are equal.");
      +
      +        // Use packetNumber variable to count incoming packets
      +        packetNumber++;
      +
      +        buf.unref();
      +    }
      +
      +    private void dump(ByteBuffer actualData, ByteBuffer expectedData) {
      +        if (dumper != null) {
      +            System.out.println("[" + this + "] INFO: Actual data:");
      +            dumper.dump(actualData);
      +            System.out.println("[" + this + "] INFO: Expected data:");
      +            dumper.dump(expectedData);
      +        }
      +    }
      +
      +    @Override
      +    protected void onClose() {
      +        super.onClose();
      +
      +        if (packetNumber != bufs.length)
      +            throw new AssertionError("[" + this + "] Number of expected buffers: " + bufs.length + ", number of actual buffers: " + packetNumber + ".");
      +    }
      +
      +    @Override
      +    public String toString() {
      +        return "MockSink(" + id + ")";
      +    }
      +
      +    /**
      +     * Example.
      +     */
      +    public static void main(String args[]) {
      +
      +        Element mockSource = new MockSource("source") {
      +            {
      +                bufs = new ByteBuffer[] {new ByteBuffer(new byte[] {1, 1, 2, 3, 4, 5}), new ByteBuffer(new byte[] {2, 1, 2, 3, 4}),
      +                        new ByteBuffer(new byte[] {3, 1, 2, 3}), new ByteBuffer(new byte[] {4, 1, 2}), new ByteBuffer(new byte[] {5, 1})};
      +                verbose = true;
      +                delay = 100;
      +                numBuffers = bufs.length;
      +            }
      +        };
      +
      +        Element mockSink = new MockSink("sink") {
      +            {
      +                bufs = new ByteBuffer[] {new ByteBuffer(new byte[] {1, 1, 2, 3, 4, 5}), new ByteBuffer(new byte[] {2, 1, 2, 3, 4}),
      +                        new ByteBuffer(new byte[] {3, 1, 2, 3}), new ByteBuffer(new byte[] {4, 1, 2}), new ByteBuffer(new byte[] {5, 1})};
      +                verbose = true;
      +            }
      +        };
      +
      +        Link link = new SyncLink() {
      +            {
      +                verbose = true;
      +            }
      +        };
      +
      +        mockSource.setLink(STDOUT, link, Direction.OUT);
      +        mockSink.setLink(STDIN, link, Direction.IN);
      +
      +        link.run();
      +    }
      +
      +}
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/MockSource.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/debug/MockSource.java
      old mode 100644
      new mode 100755
      similarity index 80%
      rename from services/console-proxy-rdp/rdpconsole/src/main/java/streamer/MockSource.java
      rename to services/console-proxy-rdp/rdpconsole/src/main/java/streamer/debug/MockSource.java
      index f758bab6aff..a77f1d4a84b
      --- a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/MockSource.java
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/debug/MockSource.java
      @@ -14,7 +14,14 @@
       // KIND, either express or implied.  See the License for the
       // specific language governing permissions and limitations
       // under the License.
      -package streamer;
      +package streamer.debug;
      +
      +import streamer.ByteBuffer;
      +import streamer.Direction;
      +import streamer.Element;
      +import streamer.Event;
      +import streamer.Link;
      +import streamer.SyncLink;
       
       public class MockSource extends FakeSource {
       
      @@ -64,18 +71,17 @@ public class MockSource extends FakeSource {
       
               Element mockSource = new MockSource("source") {
                   {
      -                this.bufs =
      -                    new ByteBuffer[] {new ByteBuffer(new byte[] {1, 1, 2, 3, 4, 5}), new ByteBuffer(new byte[] {2, 1, 2, 3, 4}), new ByteBuffer(new byte[] {3, 1, 2, 3}),
      -                        new ByteBuffer(new byte[] {4, 1, 2}), new ByteBuffer(new byte[] {5, 1})};
      -                this.verbose = true;
      -                this.delay = 100;
      +                bufs = new ByteBuffer[] {new ByteBuffer(new byte[] {1, 1, 2, 3, 4, 5}), new ByteBuffer(new byte[] {2, 1, 2, 3, 4}),
      +                        new ByteBuffer(new byte[] {3, 1, 2, 3}), new ByteBuffer(new byte[] {4, 1, 2}), new ByteBuffer(new byte[] {5, 1})};
      +                verbose = true;
      +                delay = 100;
                       // this.numBuffers = this.bufs.length;
                   }
               };
       
               Element fakeSink = new FakeSink("sink") {
                   {
      -                this.verbose = true;
      +                verbose = true;
                   }
               };
       
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/ssl/SSLState.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/ssl/SSLState.java
      new file mode 100755
      index 00000000000..f4050887329
      --- /dev/null
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/ssl/SSLState.java
      @@ -0,0 +1,26 @@
      +// Licensed to the Apache Software Foundation (ASF) under one
      +// or more contributor license agreements.  See the NOTICE file
      +// distributed with this work for additional information
      +// regarding copyright ownership.  The ASF licenses this file
      +// to you under the Apache License, Version 2.0 (the
      +// "License"); you may not use this file except in compliance
      +// with the License.  You may obtain a copy of the License at
      +//
      +//   http://www.apache.org/licenses/LICENSE-2.0
      +//
      +// Unless required by applicable law or agreed to in writing,
      +// software distributed under the License is distributed on an
      +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
      +// KIND, either express or implied.  See the License for the
      +// specific language governing permissions and limitations
      +// under the License.
      +package streamer.ssl;
      +
      +public class SSLState {
      +
      +    /**
      +     * Server public certificate in ASN.1 BER format.
      +     */
      +    public byte[] serverCertificateSubjectPublicKeyInfo;
      +
      +}
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/TrustAllX509TrustManager.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/ssl/TrustAllX509TrustManager.java
      old mode 100644
      new mode 100755
      similarity index 77%
      rename from services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/TrustAllX509TrustManager.java
      rename to services/console-proxy-rdp/rdpconsole/src/main/java/streamer/ssl/TrustAllX509TrustManager.java
      index 088094a38e6..4d9eac27d6a
      --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/TrustAllX509TrustManager.java
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/ssl/TrustAllX509TrustManager.java
      @@ -14,21 +14,33 @@
       // KIND, either express or implied.  See the License for the
       // specific language governing permissions and limitations
       // under the License.
      -package rdpclient;
      +package streamer.ssl;
       
       import java.security.cert.X509Certificate;
       
       import javax.net.ssl.X509TrustManager;
       
       public class TrustAllX509TrustManager implements X509TrustManager {
      +    private SSLState sslState;
      +
      +    public TrustAllX509TrustManager(SSLState sslState) {
      +        this.sslState = sslState;
      +    }
      +
           @Override
           public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
               // TODO: ask user to confirm self-signed certificates
      +        // Trust all (insecure)
           }
       
           @Override
           public void checkServerTrusted(final X509Certificate[] chain, final String authType) {
               // TODO: ask user to confirm self-signed certificates
      +        // Trust all (insecure)
      +
      +        // Store public certificates to use for NTLMSSP negotiation
      +        if (sslState != null)
      +            sslState.serverCertificateSubjectPublicKeyInfo = chain[0].getPublicKey().getEncoded();
           }
       
           @Override
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/UpgradeSocketToSSL.java b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/ssl/UpgradeSocketToSSL.java
      old mode 100644
      new mode 100755
      similarity index 98%
      rename from services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/UpgradeSocketToSSL.java
      rename to services/console-proxy-rdp/rdpconsole/src/main/java/streamer/ssl/UpgradeSocketToSSL.java
      index 72677081859..9d7c7087492
      --- a/services/console-proxy-rdp/rdpconsole/src/main/java/rdpclient/UpgradeSocketToSSL.java
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/streamer/ssl/UpgradeSocketToSSL.java
      @@ -14,7 +14,7 @@
       // KIND, either express or implied.  See the License for the
       // specific language governing permissions and limitations
       // under the License.
      -package rdpclient;
      +package streamer.ssl;
       
       import streamer.ByteBuffer;
       import streamer.Direction;
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/AwtKeyboardEventToVncAdapter.java b/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/AwtKeyboardEventToVncAdapter.java
      deleted file mode 100644
      index a804e262e59..00000000000
      --- a/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/AwtKeyboardEventToVncAdapter.java
      +++ /dev/null
      @@ -1,368 +0,0 @@
      -// Licensed to the Apache Software Foundation (ASF) under one
      -// or more contributor license agreements.  See the NOTICE file
      -// distributed with this work for additional information
      -// regarding copyright ownership.  The ASF licenses this file
      -// to you under the Apache License, Version 2.0 (the
      -// "License"); you may not use this file except in compliance
      -// with the License.  You may obtain a copy of the License at
      -//
      -//   http://www.apache.org/licenses/LICENSE-2.0
      -//
      -// Unless required by applicable law or agreed to in writing,
      -// software distributed under the License is distributed on an
      -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
      -// KIND, either express or implied.  See the License for the
      -// specific language governing permissions and limitations
      -// under the License.
      -package vncclient;
      -
      -import java.awt.event.KeyEvent;
      -
      -import streamer.BaseElement;
      -import streamer.ByteBuffer;
      -import streamer.Link;
      -import common.KeyOrder;
      -
      -public class AwtKeyboardEventToVncAdapter extends BaseElement {
      -
      -    protected boolean sh = false;
      -    protected boolean caps = false;
      -    protected boolean num = false;
      -
      -    public AwtKeyboardEventToVncAdapter(String id) {
      -        super(id);
      -    }
      -
      -    @Override
      -    public void handleData(ByteBuffer buf, Link link) {
      -        if (verbose)
      -            System.out.println("[" + this + "] INFO: Data received: " + buf + ".");
      -
      -        KeyOrder order = (KeyOrder)buf.getOrder();
      -        buf.unref();
      -
      -        ByteBuffer outBuf = new ByteBuffer(8);
      -        outBuf.writeByte(RfbConstants.CLIENT_KEYBOARD_EVENT);
      -
      -        outBuf.writeByte((order.pressed) ? RfbConstants.KEY_DOWN : RfbConstants.KEY_UP);
      -        outBuf.writeShort(0); // padding
      -        outBuf.writeInt(map_en_us(order));
      -
      -        pushDataToAllOuts(outBuf);
      -    }
      -
      -    /**
      -     * Return key scan code (in lower byte) and extended flags (in second byte).
      -     */
      -    private int map_en_us(KeyOrder order) {
      -
      -        switch (order.event.getKeyCode()) {
      -        // Functional keys
      -            case KeyEvent.VK_ESCAPE:
      -                return 0xff1b;
      -            case KeyEvent.VK_F1:
      -                return 0xffbe;
      -            case KeyEvent.VK_F2:
      -                return 0xffbf;
      -            case KeyEvent.VK_F3:
      -                return 0xffc0;
      -            case KeyEvent.VK_F4:
      -                return 0xffc1;
      -            case KeyEvent.VK_F5:
      -                return 0xffc2;
      -            case KeyEvent.VK_F6:
      -                return 0xffc3;
      -            case KeyEvent.VK_F7:
      -                return 0xffc4;
      -            case KeyEvent.VK_F8:
      -                return 0xffc5;
      -            case KeyEvent.VK_F9:
      -                return 0xffc6;
      -            case KeyEvent.VK_F10:
      -                return 0xffc7;
      -            case KeyEvent.VK_F11:
      -                return 0xffc8;
      -            case KeyEvent.VK_F12:
      -                return 0xffc9;
      -
      -                // Row #1
      -            case KeyEvent.VK_BACK_QUOTE:
      -                return (sh) ? '~' : '`';
      -            case KeyEvent.VK_1:
      -                return (sh) ? '!' : '1';
      -            case KeyEvent.VK_2:
      -                return (sh) ? '@' : '2';
      -            case KeyEvent.VK_3:
      -                return (sh) ? '#' : '3';
      -            case KeyEvent.VK_4:
      -                return (sh) ? '$' : '4';
      -            case KeyEvent.VK_5:
      -                return (sh) ? '%' : '5';
      -            case KeyEvent.VK_6:
      -                return (sh) ? '^' : '6';
      -            case KeyEvent.VK_7:
      -                return (sh) ? '&' : '7';
      -            case KeyEvent.VK_8:
      -                return (sh) ? '*' : '8';
      -            case KeyEvent.VK_9:
      -                return (sh) ? '(' : '9';
      -            case KeyEvent.VK_0:
      -                return (sh) ? ')' : '0';
      -            case KeyEvent.VK_MINUS:
      -                return (sh) ? '_' : '-';
      -            case KeyEvent.VK_EQUALS:
      -                return (sh) ? '+' : '=';
      -            case KeyEvent.VK_BACK_SPACE:
      -                return 0xff08;
      -
      -                // Row #2
      -            case KeyEvent.VK_TAB:
      -                return 0xff09;
      -            case KeyEvent.VK_Q:
      -                return (sh ^ caps) ? 'Q' : 'q';
      -            case KeyEvent.VK_W:
      -                return (sh ^ caps) ? 'W' : 'w';
      -            case KeyEvent.VK_E:
      -                return (sh ^ caps) ? 'E' : 'e';
      -            case KeyEvent.VK_R:
      -                return (sh ^ caps) ? 'R' : 'r';
      -            case KeyEvent.VK_T:
      -                return (sh ^ caps) ? 'T' : 't';
      -            case KeyEvent.VK_Y:
      -                return (sh ^ caps) ? 'Y' : 'y';
      -            case KeyEvent.VK_U:
      -                return (sh ^ caps) ? 'U' : 'u';
      -            case KeyEvent.VK_I:
      -                return (sh ^ caps) ? 'I' : 'i';
      -            case KeyEvent.VK_O:
      -                return (sh ^ caps) ? 'O' : 'o';
      -            case KeyEvent.VK_P:
      -                return (sh ^ caps) ? 'P' : 'p';
      -            case KeyEvent.VK_OPEN_BRACKET:
      -                return (sh) ? '{' : '[';
      -            case KeyEvent.VK_CLOSE_BRACKET:
      -                return (sh) ? '{' : ']';
      -            case KeyEvent.VK_ENTER:
      -                switch (order.event.getKeyLocation()) {
      -                    default:
      -                    case KeyEvent.KEY_LOCATION_STANDARD:
      -                        return 0xff0d;
      -                    case KeyEvent.KEY_LOCATION_NUMPAD:
      -                        return 0xff8d;
      -                }
      -
      -                // Row #3
      -            case KeyEvent.VK_CAPS_LOCK:
      -                if (order.pressed)
      -                    caps = !caps;
      -                return 0xFFE5;
      -            case KeyEvent.VK_A:
      -                return (sh ^ caps) ? 'A' : 'a';
      -            case KeyEvent.VK_S:
      -                return (sh ^ caps) ? 'S' : 's';
      -            case KeyEvent.VK_D:
      -                return (sh ^ caps) ? 'D' : 'd';
      -            case KeyEvent.VK_F:
      -                return (sh ^ caps) ? 'F' : 'f';
      -            case KeyEvent.VK_G:
      -                return (sh ^ caps) ? 'G' : 'g';
      -            case KeyEvent.VK_H:
      -                return (sh ^ caps) ? 'H' : 'h';
      -            case KeyEvent.VK_J:
      -                return (sh ^ caps) ? 'J' : 'j';
      -            case KeyEvent.VK_K:
      -                return (sh ^ caps) ? 'K' : 'k';
      -            case KeyEvent.VK_L:
      -                return (sh ^ caps) ? 'L' : 'l';
      -            case KeyEvent.VK_SEMICOLON:
      -                return (sh) ? ':' : ';';
      -            case KeyEvent.VK_QUOTE:
      -                return (sh) ? '"' : '\'';
      -
      -                // Row #4
      -            case KeyEvent.VK_SHIFT:
      -                sh = !sh;
      -                switch (order.event.getKeyLocation()) {
      -                    default:
      -                    case KeyEvent.KEY_LOCATION_LEFT:
      -                        return 0xffe1;
      -                    case KeyEvent.KEY_LOCATION_RIGHT:
      -                        return 0xffe2;
      -                }
      -            case KeyEvent.VK_BACK_SLASH:
      -                return (sh) ? '|' : '\\';
      -            case KeyEvent.VK_Z:
      -                return (sh ^ caps) ? 'Z' : 'z';
      -            case KeyEvent.VK_X:
      -                return (sh ^ caps) ? 'X' : 'x';
      -            case KeyEvent.VK_C:
      -                return (sh ^ caps) ? 'C' : 'c';
      -            case KeyEvent.VK_V:
      -                return (sh ^ caps) ? 'V' : 'v';
      -            case KeyEvent.VK_B:
      -                return (sh ^ caps) ? 'B' : 'b';
      -            case KeyEvent.VK_N:
      -                return (sh ^ caps) ? 'N' : 'n';
      -            case KeyEvent.VK_M:
      -                return (sh ^ caps) ? 'M' : 'M';
      -            case KeyEvent.VK_COMMA:
      -                return (sh) ? '<' : ',';
      -            case KeyEvent.VK_PERIOD:
      -                return (sh) ? '>' : '.';
      -            case KeyEvent.VK_SLASH:
      -                return (sh) ? '?' : '/';
      -
      -                //
      -                // Bottom row
      -            case KeyEvent.VK_CONTROL:
      -                switch (order.event.getKeyLocation()) {
      -                    default:
      -                    case KeyEvent.KEY_LOCATION_LEFT:
      -                        return 0xFFE3;
      -                    case KeyEvent.KEY_LOCATION_RIGHT:
      -                        return 0xFFE4;
      -                }
      -            case KeyEvent.VK_WINDOWS:
      -                switch (order.event.getKeyLocation()) {
      -                    default:
      -                    case KeyEvent.KEY_LOCATION_LEFT:
      -                        return 0xFFED; // HyperL
      -                    case KeyEvent.KEY_LOCATION_RIGHT:
      -                        return 0xFFEE; // HyperR
      -                }
      -            case KeyEvent.VK_META:
      -                switch (order.event.getKeyLocation()) {
      -                    default:
      -                    case KeyEvent.KEY_LOCATION_LEFT:
      -                        return 0xFFE7; // MetaL
      -                    case KeyEvent.KEY_LOCATION_RIGHT:
      -                        return 0xFFE8; // MetaR
      -                }
      -
      -            case KeyEvent.VK_ALT:
      -                switch (order.event.getKeyLocation()) {
      -                    default:
      -                    case KeyEvent.KEY_LOCATION_LEFT:
      -                        return 0xFFE9;
      -                    case KeyEvent.KEY_LOCATION_RIGHT:
      -                        return 0xFFEA;
      -                }
      -            case KeyEvent.VK_ALT_GRAPH:
      -                return 0xfe03;
      -
      -            case KeyEvent.VK_SPACE:
      -                return ' ';
      -
      -            case KeyEvent.VK_CONTEXT_MENU:
      -                return 0xff67;
      -
      -                //
      -                // Special keys
      -            case KeyEvent.VK_PRINTSCREEN:
      -                return (sh) ? 0xFF15/* SysRq */: 0xFF61 /* Print */;
      -            case KeyEvent.VK_SCROLL_LOCK:
      -                return 0xFF14;
      -            case KeyEvent.VK_PAUSE:
      -                return (sh) ? 0xFF6B/* Break */: 0xFF13/* Pause */;
      -
      -                // Text navigation keys
      -            case KeyEvent.VK_INSERT:
      -                return 0xff63;
      -            case KeyEvent.VK_DELETE:
      -                return 0xffff;
      -            case KeyEvent.VK_HOME:
      -                return 0xff50;
      -            case KeyEvent.VK_END:
      -                return 0xff57;
      -            case KeyEvent.VK_PAGE_UP:
      -                return 0xff55;
      -            case KeyEvent.VK_PAGE_DOWN:
      -                return 0xff56;
      -
      -                // Cursor keys
      -            case KeyEvent.VK_LEFT:
      -                switch (order.event.getKeyLocation()) {
      -                    default:
      -                    case KeyEvent.KEY_LOCATION_LEFT:
      -                        return 0xff51;
      -                    case KeyEvent.KEY_LOCATION_NUMPAD:
      -                        return 0xFF96;
      -                }
      -            case KeyEvent.VK_UP:
      -                switch (order.event.getKeyLocation()) {
      -                    default:
      -                    case KeyEvent.KEY_LOCATION_LEFT:
      -                        return 0xff52;
      -                    case KeyEvent.KEY_LOCATION_NUMPAD:
      -                        return 0xFF97;
      -                }
      -            case KeyEvent.VK_RIGHT:
      -                switch (order.event.getKeyLocation()) {
      -                    default:
      -                    case KeyEvent.KEY_LOCATION_LEFT:
      -                        return 0xff53;
      -                    case KeyEvent.KEY_LOCATION_NUMPAD:
      -                        return 0xFF98;
      -                }
      -            case KeyEvent.VK_DOWN:
      -                switch (order.event.getKeyLocation()) {
      -                    default:
      -                    case KeyEvent.KEY_LOCATION_LEFT:
      -                        return 0xff54;
      -                    case KeyEvent.KEY_LOCATION_NUMPAD:
      -                        return 0xFF99;
      -                }
      -
      -                // Keypad
      -            case KeyEvent.VK_NUM_LOCK:
      -                if (order.pressed)
      -                    num = !num;
      -                return 0xFF6F;
      -            case KeyEvent.VK_DIVIDE:
      -                return 0xFFAF;
      -            case KeyEvent.VK_MULTIPLY:
      -                return 0xFFAA;
      -            case KeyEvent.VK_SUBTRACT:
      -                return 0xFFAD;
      -            case KeyEvent.VK_ADD:
      -                return 0xFFAB;
      -
      -            case KeyEvent.VK_KP_LEFT:
      -                return 0xFF96;
      -            case KeyEvent.VK_KP_UP:
      -                return 0xFF97;
      -            case KeyEvent.VK_KP_RIGHT:
      -                return 0xFF98;
      -            case KeyEvent.VK_KP_DOWN:
      -                return 0xFF99;
      -
      -            case KeyEvent.VK_NUMPAD0:
      -                return 0xFFB0;
      -            case KeyEvent.VK_NUMPAD1:
      -                return 0xFFB1;
      -            case KeyEvent.VK_NUMPAD2:
      -                return 0xFFB2;
      -            case KeyEvent.VK_NUMPAD3:
      -                return 0xFFB3;
      -            case KeyEvent.VK_NUMPAD4:
      -                return 0xFFB4;
      -            case KeyEvent.VK_NUMPAD5:
      -                return 0xFFB5;
      -            case KeyEvent.VK_NUMPAD6:
      -                return 0xFFB6;
      -            case KeyEvent.VK_NUMPAD7:
      -                return 0xFFB7;
      -            case KeyEvent.VK_NUMPAD8:
      -                return 0xFFB8;
      -            case KeyEvent.VK_NUMPAD9:
      -                return 0xFFB9;
      -            case KeyEvent.VK_DECIMAL:
      -                return 0xFFAE;
      -
      -            default:
      -                System.err.println("Key is not mapped: " + order + ".");
      -                return ' '; // Space
      -        }
      -    }
      -
      -}
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/VncClient.java b/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/VncClient.java
      old mode 100644
      new mode 100755
      index c16a9f000c1..1c76656e0d9
      --- a/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/VncClient.java
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/VncClient.java
      @@ -18,13 +18,23 @@ package vncclient;
       
       import streamer.PipelineImpl;
       import streamer.Queue;
      -import common.AwtBellAdapter;
      -import common.AwtCanvasAdapter;
      -import common.AwtClipboardAdapter;
      +import vncclient.adapter.AwtVncKeyboardAdapter;
      +import vncclient.adapter.AwtVncMouseAdapter;
      +import vncclient.vnc.EncodingsMessage;
      +import vncclient.vnc.FrameBufferUpdateRequest;
      +import vncclient.vnc.RGB888LE32PixelFormatRequest;
      +import vncclient.vnc.RfbConstants;
      +import vncclient.vnc.VncInitializer;
      +import vncclient.vnc.VncMessageHandler;
      +import vncclient.vnc.Vnc33Authentication;
      +import vncclient.vnc.Vnc33Hello;
       import common.AwtKeyEventSource;
       import common.AwtMouseEventSource;
       import common.BufferedImageCanvas;
       import common.ScreenDescription;
      +import common.adapter.AwtBellAdapter;
      +import common.adapter.AwtCanvasAdapter;
      +import common.adapter.AwtClipboardAdapter;
       
       public class VncClient extends PipelineImpl {
       
      @@ -44,41 +54,41 @@ public class VncClient extends PipelineImpl {
               canvas.addKeyListener(keyEventSource);
       
               add(
      -        // Handshake
      +                // Handshake
       
      -        // RFB protocol version exchanger
      -        new Vnc_3_3_Hello("hello"),
      -        // Authenticator
      -            new Vnc_3_3_Authentication("auth", password),
      -            // Initializer
      -            new VncInitializer("init", true, screen),
      +                // RFB protocol version exchanger
      +                new Vnc33Hello("hello"),
      +                // Authenticator
      +                new Vnc33Authentication("auth", password),
      +                // Initializer
      +                new VncInitializer("init", true, screen),
       
      -            new EncodingsMessage("encodings", RfbConstants.SUPPORTED_ENCODINGS_ARRAY),
      +                new EncodingsMessage("encodings", RfbConstants.SUPPORTED_ENCODINGS_ARRAY),
       
      -            new RGB888LE32PixelFormatRequest("pixel_format", screen),
      +                new RGB888LE32PixelFormatRequest("pixel_format", screen),
       
      -            // Main
      +                // Main
       
      -            // Packet receiver
      -            new VncMessageHandler("message_handler", screen),
      +                // Packet receiver
      +                new VncMessageHandler("message_handler", screen),
       
      -            new AwtBellAdapter("bell"),
      +                new AwtBellAdapter("bell"),
       
      -            new AwtClipboardAdapter("clipboard"),
      +                new AwtClipboardAdapter("clipboard"),
       
      -            new AwtCanvasAdapter("pixels", canvas, screen),
      +                new AwtCanvasAdapter("pixels", canvas, screen),
       
      -            new Queue("queue"),
      +                new Queue("queue"),
       
      -            new FrameBufferUpdateRequest("fbur", screen),
      +                new FrameBufferUpdateRequest("fbur", screen),
       
      -            new AwtKeyboardEventToVncAdapter("keyboard_adapter"),
      +                new AwtVncKeyboardAdapter("keyboard_adapter"),
       
      -            new AwtMouseEventToVncAdapter("mouse_adapter"),
      +                new AwtVncMouseAdapter("mouse_adapter"),
       
      -            mouseEventSource, keyEventSource
      +                mouseEventSource, keyEventSource
       
      -        );
      +                );
       
               // Link handshake elements
               link("IN", "hello", "auth", "init", "message_handler");
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/adapter/AwtVncKeyboardAdapter.java b/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/adapter/AwtVncKeyboardAdapter.java
      new file mode 100755
      index 00000000000..6b50e35eafd
      --- /dev/null
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/adapter/AwtVncKeyboardAdapter.java
      @@ -0,0 +1,369 @@
      +// Licensed to the Apache Software Foundation (ASF) under one
      +// or more contributor license agreements.  See the NOTICE file
      +// distributed with this work for additional information
      +// regarding copyright ownership.  The ASF licenses this file
      +// to you under the Apache License, Version 2.0 (the
      +// "License"); you may not use this file except in compliance
      +// with the License.  You may obtain a copy of the License at
      +//
      +//   http://www.apache.org/licenses/LICENSE-2.0
      +//
      +// Unless required by applicable law or agreed to in writing,
      +// software distributed under the License is distributed on an
      +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
      +// KIND, either express or implied.  See the License for the
      +// specific language governing permissions and limitations
      +// under the License.
      +package vncclient.adapter;
      +
      +import java.awt.event.KeyEvent;
      +
      +import streamer.BaseElement;
      +import streamer.ByteBuffer;
      +import streamer.Link;
      +import vncclient.vnc.RfbConstants;
      +import common.KeyOrder;
      +
      +public class AwtVncKeyboardAdapter extends BaseElement {
      +
      +    protected boolean sh = false;
      +    protected boolean caps = false;
      +    protected boolean num = false;
      +
      +    public AwtVncKeyboardAdapter(String id) {
      +        super(id);
      +    }
      +
      +    @Override
      +    public void handleData(ByteBuffer buf, Link link) {
      +        if (verbose)
      +            System.out.println("[" + this + "] INFO: Data received: " + buf + ".");
      +
      +        KeyOrder order = (KeyOrder)buf.getOrder();
      +        buf.unref();
      +
      +        ByteBuffer outBuf = new ByteBuffer(8);
      +        outBuf.writeByte(RfbConstants.CLIENT_KEYBOARD_EVENT);
      +
      +        outBuf.writeByte((order.pressed) ? RfbConstants.KEY_DOWN : RfbConstants.KEY_UP);
      +        outBuf.writeShort(0); // padding
      +        outBuf.writeInt(map_en_us(order));
      +
      +        pushDataToAllOuts(outBuf);
      +    }
      +
      +    /**
      +     * Return key scan code (in lower byte) and extended flags (in second byte).
      +     */
      +    private int map_en_us(KeyOrder order) {
      +
      +        switch (order.event.getKeyCode()) {
      +        // Functional keys
      +        case KeyEvent.VK_ESCAPE:
      +            return 0xff1b;
      +        case KeyEvent.VK_F1:
      +            return 0xffbe;
      +        case KeyEvent.VK_F2:
      +            return 0xffbf;
      +        case KeyEvent.VK_F3:
      +            return 0xffc0;
      +        case KeyEvent.VK_F4:
      +            return 0xffc1;
      +        case KeyEvent.VK_F5:
      +            return 0xffc2;
      +        case KeyEvent.VK_F6:
      +            return 0xffc3;
      +        case KeyEvent.VK_F7:
      +            return 0xffc4;
      +        case KeyEvent.VK_F8:
      +            return 0xffc5;
      +        case KeyEvent.VK_F9:
      +            return 0xffc6;
      +        case KeyEvent.VK_F10:
      +            return 0xffc7;
      +        case KeyEvent.VK_F11:
      +            return 0xffc8;
      +        case KeyEvent.VK_F12:
      +            return 0xffc9;
      +
      +            // Row #1
      +        case KeyEvent.VK_BACK_QUOTE:
      +            return (sh) ? '~' : '`';
      +        case KeyEvent.VK_1:
      +            return (sh) ? '!' : '1';
      +        case KeyEvent.VK_2:
      +            return (sh) ? '@' : '2';
      +        case KeyEvent.VK_3:
      +            return (sh) ? '#' : '3';
      +        case KeyEvent.VK_4:
      +            return (sh) ? '$' : '4';
      +        case KeyEvent.VK_5:
      +            return (sh) ? '%' : '5';
      +        case KeyEvent.VK_6:
      +            return (sh) ? '^' : '6';
      +        case KeyEvent.VK_7:
      +            return (sh) ? '&' : '7';
      +        case KeyEvent.VK_8:
      +            return (sh) ? '*' : '8';
      +        case KeyEvent.VK_9:
      +            return (sh) ? '(' : '9';
      +        case KeyEvent.VK_0:
      +            return (sh) ? ')' : '0';
      +        case KeyEvent.VK_MINUS:
      +            return (sh) ? '_' : '-';
      +        case KeyEvent.VK_EQUALS:
      +            return (sh) ? '+' : '=';
      +        case KeyEvent.VK_BACK_SPACE:
      +            return 0xff08;
      +
      +            // Row #2
      +        case KeyEvent.VK_TAB:
      +            return 0xff09;
      +        case KeyEvent.VK_Q:
      +            return (sh ^ caps) ? 'Q' : 'q';
      +        case KeyEvent.VK_W:
      +            return (sh ^ caps) ? 'W' : 'w';
      +        case KeyEvent.VK_E:
      +            return (sh ^ caps) ? 'E' : 'e';
      +        case KeyEvent.VK_R:
      +            return (sh ^ caps) ? 'R' : 'r';
      +        case KeyEvent.VK_T:
      +            return (sh ^ caps) ? 'T' : 't';
      +        case KeyEvent.VK_Y:
      +            return (sh ^ caps) ? 'Y' : 'y';
      +        case KeyEvent.VK_U:
      +            return (sh ^ caps) ? 'U' : 'u';
      +        case KeyEvent.VK_I:
      +            return (sh ^ caps) ? 'I' : 'i';
      +        case KeyEvent.VK_O:
      +            return (sh ^ caps) ? 'O' : 'o';
      +        case KeyEvent.VK_P:
      +            return (sh ^ caps) ? 'P' : 'p';
      +        case KeyEvent.VK_OPEN_BRACKET:
      +            return (sh) ? '{' : '[';
      +        case KeyEvent.VK_CLOSE_BRACKET:
      +            return (sh) ? '{' : ']';
      +        case KeyEvent.VK_ENTER:
      +            switch (order.event.getKeyLocation()) {
      +            default:
      +            case KeyEvent.KEY_LOCATION_STANDARD:
      +                return 0xff0d;
      +            case KeyEvent.KEY_LOCATION_NUMPAD:
      +                return 0xff8d;
      +            }
      +
      +            // Row #3
      +        case KeyEvent.VK_CAPS_LOCK:
      +            if (order.pressed)
      +                caps = !caps;
      +            return 0xFFE5;
      +        case KeyEvent.VK_A:
      +            return (sh ^ caps) ? 'A' : 'a';
      +        case KeyEvent.VK_S:
      +            return (sh ^ caps) ? 'S' : 's';
      +        case KeyEvent.VK_D:
      +            return (sh ^ caps) ? 'D' : 'd';
      +        case KeyEvent.VK_F:
      +            return (sh ^ caps) ? 'F' : 'f';
      +        case KeyEvent.VK_G:
      +            return (sh ^ caps) ? 'G' : 'g';
      +        case KeyEvent.VK_H:
      +            return (sh ^ caps) ? 'H' : 'h';
      +        case KeyEvent.VK_J:
      +            return (sh ^ caps) ? 'J' : 'j';
      +        case KeyEvent.VK_K:
      +            return (sh ^ caps) ? 'K' : 'k';
      +        case KeyEvent.VK_L:
      +            return (sh ^ caps) ? 'L' : 'l';
      +        case KeyEvent.VK_SEMICOLON:
      +            return (sh) ? ':' : ';';
      +        case KeyEvent.VK_QUOTE:
      +            return (sh) ? '"' : '\'';
      +
      +            // Row #4
      +        case KeyEvent.VK_SHIFT:
      +            sh = !sh;
      +            switch (order.event.getKeyLocation()) {
      +            default:
      +            case KeyEvent.KEY_LOCATION_LEFT:
      +                return 0xffe1;
      +            case KeyEvent.KEY_LOCATION_RIGHT:
      +                return 0xffe2;
      +            }
      +        case KeyEvent.VK_BACK_SLASH:
      +            return (sh) ? '|' : '\\';
      +        case KeyEvent.VK_Z:
      +            return (sh ^ caps) ? 'Z' : 'z';
      +        case KeyEvent.VK_X:
      +            return (sh ^ caps) ? 'X' : 'x';
      +        case KeyEvent.VK_C:
      +            return (sh ^ caps) ? 'C' : 'c';
      +        case KeyEvent.VK_V:
      +            return (sh ^ caps) ? 'V' : 'v';
      +        case KeyEvent.VK_B:
      +            return (sh ^ caps) ? 'B' : 'b';
      +        case KeyEvent.VK_N:
      +            return (sh ^ caps) ? 'N' : 'n';
      +        case KeyEvent.VK_M:
      +            return (sh ^ caps) ? 'M' : 'M';
      +        case KeyEvent.VK_COMMA:
      +            return (sh) ? '<' : ',';
      +        case KeyEvent.VK_PERIOD:
      +            return (sh) ? '>' : '.';
      +        case KeyEvent.VK_SLASH:
      +            return (sh) ? '?' : '/';
      +
      +            //
      +            // Bottom row
      +        case KeyEvent.VK_CONTROL:
      +            switch (order.event.getKeyLocation()) {
      +            default:
      +            case KeyEvent.KEY_LOCATION_LEFT:
      +                return 0xFFE3;
      +            case KeyEvent.KEY_LOCATION_RIGHT:
      +                return 0xFFE4;
      +            }
      +        case KeyEvent.VK_WINDOWS:
      +            switch (order.event.getKeyLocation()) {
      +            default:
      +            case KeyEvent.KEY_LOCATION_LEFT:
      +                return 0xFFED; // HyperL
      +            case KeyEvent.KEY_LOCATION_RIGHT:
      +                return 0xFFEE; // HyperR
      +            }
      +        case KeyEvent.VK_META:
      +            switch (order.event.getKeyLocation()) {
      +            default:
      +            case KeyEvent.KEY_LOCATION_LEFT:
      +                return 0xFFE7; // MetaL
      +            case KeyEvent.KEY_LOCATION_RIGHT:
      +                return 0xFFE8; // MetaR
      +            }
      +
      +        case KeyEvent.VK_ALT:
      +            switch (order.event.getKeyLocation()) {
      +            default:
      +            case KeyEvent.KEY_LOCATION_LEFT:
      +                return 0xFFE9;
      +            case KeyEvent.KEY_LOCATION_RIGHT:
      +                return 0xFFEA;
      +            }
      +        case KeyEvent.VK_ALT_GRAPH:
      +            return 0xfe03;
      +
      +        case KeyEvent.VK_SPACE:
      +            return ' ';
      +
      +        case KeyEvent.VK_CONTEXT_MENU:
      +            return 0xff67;
      +
      +            //
      +            // Special keys
      +        case KeyEvent.VK_PRINTSCREEN:
      +            return (sh) ? 0xFF15/* SysRq */: 0xFF61 /* Print */;
      +        case KeyEvent.VK_SCROLL_LOCK:
      +            return 0xFF14;
      +        case KeyEvent.VK_PAUSE:
      +            return (sh) ? 0xFF6B/* Break */: 0xFF13/* Pause */;
      +
      +            // Text navigation keys
      +        case KeyEvent.VK_INSERT:
      +            return 0xff63;
      +        case KeyEvent.VK_DELETE:
      +            return 0xffff;
      +        case KeyEvent.VK_HOME:
      +            return 0xff50;
      +        case KeyEvent.VK_END:
      +            return 0xff57;
      +        case KeyEvent.VK_PAGE_UP:
      +            return 0xff55;
      +        case KeyEvent.VK_PAGE_DOWN:
      +            return 0xff56;
      +
      +            // Cursor keys
      +        case KeyEvent.VK_LEFT:
      +            switch (order.event.getKeyLocation()) {
      +            default:
      +            case KeyEvent.KEY_LOCATION_LEFT:
      +                return 0xff51;
      +            case KeyEvent.KEY_LOCATION_NUMPAD:
      +                return 0xFF96;
      +            }
      +        case KeyEvent.VK_UP:
      +            switch (order.event.getKeyLocation()) {
      +            default:
      +            case KeyEvent.KEY_LOCATION_LEFT:
      +                return 0xff52;
      +            case KeyEvent.KEY_LOCATION_NUMPAD:
      +                return 0xFF97;
      +            }
      +        case KeyEvent.VK_RIGHT:
      +            switch (order.event.getKeyLocation()) {
      +            default:
      +            case KeyEvent.KEY_LOCATION_LEFT:
      +                return 0xff53;
      +            case KeyEvent.KEY_LOCATION_NUMPAD:
      +                return 0xFF98;
      +            }
      +        case KeyEvent.VK_DOWN:
      +            switch (order.event.getKeyLocation()) {
      +            default:
      +            case KeyEvent.KEY_LOCATION_LEFT:
      +                return 0xff54;
      +            case KeyEvent.KEY_LOCATION_NUMPAD:
      +                return 0xFF99;
      +            }
      +
      +            // Keypad
      +        case KeyEvent.VK_NUM_LOCK:
      +            if (order.pressed)
      +                num = !num;
      +            return 0xFF6F;
      +        case KeyEvent.VK_DIVIDE:
      +            return 0xFFAF;
      +        case KeyEvent.VK_MULTIPLY:
      +            return 0xFFAA;
      +        case KeyEvent.VK_SUBTRACT:
      +            return 0xFFAD;
      +        case KeyEvent.VK_ADD:
      +            return 0xFFAB;
      +
      +        case KeyEvent.VK_KP_LEFT:
      +            return 0xFF96;
      +        case KeyEvent.VK_KP_UP:
      +            return 0xFF97;
      +        case KeyEvent.VK_KP_RIGHT:
      +            return 0xFF98;
      +        case KeyEvent.VK_KP_DOWN:
      +            return 0xFF99;
      +
      +        case KeyEvent.VK_NUMPAD0:
      +            return 0xFFB0;
      +        case KeyEvent.VK_NUMPAD1:
      +            return 0xFFB1;
      +        case KeyEvent.VK_NUMPAD2:
      +            return 0xFFB2;
      +        case KeyEvent.VK_NUMPAD3:
      +            return 0xFFB3;
      +        case KeyEvent.VK_NUMPAD4:
      +            return 0xFFB4;
      +        case KeyEvent.VK_NUMPAD5:
      +            return 0xFFB5;
      +        case KeyEvent.VK_NUMPAD6:
      +            return 0xFFB6;
      +        case KeyEvent.VK_NUMPAD7:
      +            return 0xFFB7;
      +        case KeyEvent.VK_NUMPAD8:
      +            return 0xFFB8;
      +        case KeyEvent.VK_NUMPAD9:
      +            return 0xFFB9;
      +        case KeyEvent.VK_DECIMAL:
      +            return 0xFFAE;
      +
      +        default:
      +            System.err.println("Key is not mapped: " + order + ".");
      +            return ' '; // Space
      +        }
      +    }
      +
      +}
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/AwtMouseEventToVncAdapter.java b/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/adapter/AwtVncMouseAdapter.java
      old mode 100644
      new mode 100755
      similarity index 85%
      rename from services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/AwtMouseEventToVncAdapter.java
      rename to services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/adapter/AwtVncMouseAdapter.java
      index a54d101f6a9..59216d3f2ce
      --- a/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/AwtMouseEventToVncAdapter.java
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/adapter/AwtVncMouseAdapter.java
      @@ -14,19 +14,19 @@
       // KIND, either express or implied.  See the License for the
       // specific language governing permissions and limitations
       // under the License.
      -package vncclient;
      +package vncclient.adapter;
       
       import java.awt.event.InputEvent;
      -import java.awt.event.MouseEvent;
       
       import streamer.BaseElement;
       import streamer.ByteBuffer;
       import streamer.Link;
      +import vncclient.vnc.RfbConstants;
       import common.MouseOrder;
       
      -public class AwtMouseEventToVncAdapter extends BaseElement {
      +public class AwtVncMouseAdapter extends BaseElement {
       
      -    public AwtMouseEventToVncAdapter(String id) {
      +    public AwtVncMouseAdapter(String id) {
               super(id);
           }
       
      @@ -63,9 +63,8 @@ public class AwtMouseEventToVncAdapter extends BaseElement {
            * @return VNC mouse button mask
            */
           public static int mapAwtModifiersToVncButtonMask(int modifiers) {
      -        int mask =
      -            (((modifiers & InputEvent.BUTTON1_DOWN_MASK) != 0) ? 0x1 : 0) | (((modifiers & InputEvent.BUTTON2_DOWN_MASK) != 0) ? 0x2 : 0) |
      -                (((modifiers & InputEvent.BUTTON3_DOWN_MASK) != 0) ? 0x4 : 0);
      +        int mask = (((modifiers & InputEvent.BUTTON1_DOWN_MASK) != 0) ? 0x1 : 0) | (((modifiers & InputEvent.BUTTON2_DOWN_MASK) != 0) ? 0x2 : 0)
      +                | (((modifiers & InputEvent.BUTTON3_DOWN_MASK) != 0) ? 0x4 : 0);
               return mask;
           }
       
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/EncodingsMessage.java b/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/vnc/EncodingsMessage.java
      old mode 100644
      new mode 100755
      similarity index 98%
      rename from services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/EncodingsMessage.java
      rename to services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/vnc/EncodingsMessage.java
      index 81540d66412..5dfa83101b1
      --- a/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/EncodingsMessage.java
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/vnc/EncodingsMessage.java
      @@ -14,7 +14,7 @@
       // KIND, either express or implied.  See the License for the
       // specific language governing permissions and limitations
       // under the License.
      -package vncclient;
      +package vncclient.vnc;
       
       import streamer.BaseElement;
       import streamer.ByteBuffer;
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/FrameBufferUpdateRequest.java b/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/vnc/FrameBufferUpdateRequest.java
      old mode 100644
      new mode 100755
      similarity index 89%
      rename from services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/FrameBufferUpdateRequest.java
      rename to services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/vnc/FrameBufferUpdateRequest.java
      index 0081827bd01..ee94c60cadc
      --- a/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/FrameBufferUpdateRequest.java
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/vnc/FrameBufferUpdateRequest.java
      @@ -14,16 +14,16 @@
       // KIND, either express or implied.  See the License for the
       // specific language governing permissions and limitations
       // under the License.
      -package vncclient;
      +package vncclient.vnc;
       
       import streamer.BaseElement;
       import streamer.ByteBuffer;
       import streamer.Element;
       import streamer.Link;
      -import streamer.MockSink;
      -import streamer.MockSource;
       import streamer.Pipeline;
       import streamer.PipelineImpl;
      +import streamer.debug.MockSink;
      +import streamer.debug.MockSource;
       import common.ScreenDescription;
       
       public class FrameBufferUpdateRequest extends BaseElement {
      @@ -95,18 +95,18 @@ public class FrameBufferUpdateRequest extends BaseElement {
               Element adapter = new FrameBufferUpdateRequest("renderer", screen);
       
               Element sink = new MockSink("sink", ByteBuffer.convertByteArraysToByteBuffers(new byte[] {
      -            // Request
      -            RfbConstants.CLIENT_FRAMEBUFFER_UPDATE_REQUEST,
      -            // Full update (redraw area)
      -            RfbConstants.FRAMEBUFFER_FULL_UPDATE_REQUEST,
      -            // X
      -            0, 1,
      -            // Y
      -            0, 2,
      -            // Width
      -            0, 3,
      -            // Height
      -            0, 4}));
      +                // Request
      +                RfbConstants.CLIENT_FRAMEBUFFER_UPDATE_REQUEST,
      +                // Full update (redraw area)
      +                RfbConstants.FRAMEBUFFER_FULL_UPDATE_REQUEST,
      +                // X
      +                0, 1,
      +                // Y
      +                0, 2,
      +                // Width
      +                0, 3,
      +                // Height
      +                0, 4}));
       
               ByteBuffer buf = new ByteBuffer(new byte[0]);
               buf.putMetadata(TARGET_X, 1);
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/RGB888LE32PixelFormatRequest.java b/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/vnc/RGB888LE32PixelFormatRequest.java
      old mode 100644
      new mode 100755
      similarity index 96%
      rename from services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/RGB888LE32PixelFormatRequest.java
      rename to services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/vnc/RGB888LE32PixelFormatRequest.java
      index 32de903d706..2350f1483f4
      --- a/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/RGB888LE32PixelFormatRequest.java
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/vnc/RGB888LE32PixelFormatRequest.java
      @@ -14,7 +14,7 @@
       // KIND, either express or implied.  See the License for the
       // specific language governing permissions and limitations
       // under the License.
      -package vncclient;
      +package vncclient.vnc;
       
       import streamer.BaseElement;
       import streamer.ByteBuffer;
      @@ -80,8 +80,8 @@ public class RGB888LE32PixelFormatRequest extends BaseElement {
               outBuf.writeByte(0);
               outBuf.writeByte(0);
       
      -        screen.setPixelFormat(bitsPerPixel, depth, bigEndianFlag != RfbConstants.LITTLE_ENDIAN, trueColourFlag == RfbConstants.TRUE_COLOR, redMax, greenMax, blueMax,
      -            redShift, greenShift, blueShift);
      +        screen.setPixelFormat(bitsPerPixel, depth, bigEndianFlag != RfbConstants.LITTLE_ENDIAN, trueColourFlag == RfbConstants.TRUE_COLOR, redMax, greenMax,
      +                blueMax, redShift, greenShift, blueShift);
       
               pushDataToAllOuts(outBuf);
           }
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/RfbConstants.java b/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/vnc/RfbConstants.java
      old mode 100644
      new mode 100755
      similarity index 99%
      rename from services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/RfbConstants.java
      rename to services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/vnc/RfbConstants.java
      index 7359cd30099..a3895d401ff
      --- a/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/RfbConstants.java
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/vnc/RfbConstants.java
      @@ -14,7 +14,7 @@
       // KIND, either express or implied.  See the License for the
       // specific language governing permissions and limitations
       // under the License.
      -package vncclient;
      +package vncclient.vnc;
       
       import java.nio.charset.Charset;
       
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/Vnc_3_3_Authentication.java b/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/vnc/Vnc33Authentication.java
      old mode 100644
      new mode 100755
      similarity index 73%
      rename from services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/Vnc_3_3_Authentication.java
      rename to services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/vnc/Vnc33Authentication.java
      index e810fdc0625..6fdb3b1f69e
      --- a/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/Vnc_3_3_Authentication.java
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/vnc/Vnc33Authentication.java
      @@ -14,7 +14,7 @@
       // KIND, either express or implied.  See the License for the
       // specific language governing permissions and limitations
       // under the License.
      -package vncclient;
      +package vncclient.vnc;
       
       import java.security.spec.KeySpec;
       
      @@ -25,15 +25,15 @@ import javax.crypto.spec.DESKeySpec;
       
       import streamer.ByteBuffer;
       import streamer.Element;
      -import streamer.FakeSink;
       import streamer.Link;
      -import streamer.MockSink;
      -import streamer.MockSource;
       import streamer.OneTimeSwitch;
       import streamer.Pipeline;
       import streamer.PipelineImpl;
      +import streamer.debug.FakeSink;
      +import streamer.debug.MockSink;
      +import streamer.debug.MockSource;
       
      -public class Vnc_3_3_Authentication extends OneTimeSwitch {
      +public class Vnc33Authentication extends OneTimeSwitch {
       
           /**
            * Password to use when authentication is required.
      @@ -49,11 +49,11 @@ public class Vnc_3_3_Authentication extends OneTimeSwitch {
            */
           protected int stage = 0;
       
      -    public Vnc_3_3_Authentication(String id) {
      +    public Vnc33Authentication(String id) {
               super(id);
           }
       
      -    public Vnc_3_3_Authentication(String id, String password) {
      +    public Vnc33Authentication(String id, String password) {
               super(id);
               this.password = password;
           }
      @@ -64,13 +64,13 @@ public class Vnc_3_3_Authentication extends OneTimeSwitch {
                   System.out.println("[" + this + "] INFO: Data received: " + buf + ".");
       
               switch (stage) {
      -            case 0: // Read security with optional challenge and response
      -                stage0(buf, link);
      +        case 0: // Read security with optional challenge and response
      +            stage0(buf, link);
       
      -                break;
      -            case 1: // Read authentication response
      -                stage1(buf, link);
      -                break;
      +            break;
      +        case 1: // Read authentication response
      +            stage1(buf, link);
      +            break;
               }
       
           }
      @@ -91,30 +91,30 @@ public class Vnc_3_3_Authentication extends OneTimeSwitch {
               int authType = buf.readSignedInt();
       
               switch (authType) {
      -            case RfbConstants.CONNECTION_FAILED: {
      -                // Server forbids to connect. Read reason and throw exception
      +        case RfbConstants.CONNECTION_FAILED: {
      +            // Server forbids to connect. Read reason and throw exception
       
      -                int length = buf.readSignedInt();
      -                String reason = new String(buf.data, buf.offset, length, RfbConstants.US_ASCII_CHARSET);
      +            int length = buf.readSignedInt();
      +            String reason = new String(buf.data, buf.offset, length, RfbConstants.US_ASCII_CHARSET);
       
      -                throw new RuntimeException("Authentication to VNC server is failed. Reason: " + reason);
      -            }
      +            throw new RuntimeException("Authentication to VNC server is failed. Reason: " + reason);
      +        }
       
      -            case RfbConstants.NO_AUTH: {
      -                // Client can connect without authorization. Nothing to do.
      -                // Switch off this element from circuit
      -                switchOff();
      -                break;
      -            }
      +        case RfbConstants.NO_AUTH: {
      +            // Client can connect without authorization. Nothing to do.
      +            // Switch off this element from circuit
      +            switchOff();
      +            break;
      +        }
       
      -            case RfbConstants.VNC_AUTH: {
      -                // Read challenge and generate response
      -                responseToChallenge(buf, link);
      -                break;
      -            }
      +        case RfbConstants.VNC_AUTH: {
      +            // Read challenge and generate response
      +            responseToChallenge(buf, link);
      +            break;
      +        }
       
      -            default:
      -                throw new RuntimeException("Unsupported VNC protocol authorization scheme, scheme code: " + authType + ".");
      +        default:
      +            throw new RuntimeException("Unsupported VNC protocol authorization scheme, scheme code: " + authType + ".");
               }
       
           }
      @@ -226,21 +226,21 @@ public class Vnc_3_3_Authentication extends OneTimeSwitch {
               int authResult = buf.readSignedInt();
       
               switch (authResult) {
      -            case RfbConstants.VNC_AUTH_OK: {
      -                // Nothing to do
      -                if (verbose)
      -                    System.out.println("[" + this + "] INFO: Authentication successfull.");
      -                break;
      -            }
      +        case RfbConstants.VNC_AUTH_OK: {
      +            // Nothing to do
      +            if (verbose)
      +                System.out.println("[" + this + "] INFO: Authentication successfull.");
      +            break;
      +        }
       
      -            case RfbConstants.VNC_AUTH_TOO_MANY:
      -                throw new RuntimeException("Connection to VNC server failed: too many wrong attempts.");
      +        case RfbConstants.VNC_AUTH_TOO_MANY:
      +            throw new RuntimeException("Connection to VNC server failed: too many wrong attempts.");
       
      -            case RfbConstants.VNC_AUTH_FAILED:
      -                throw new RuntimeException("Connection to VNC server failed: wrong password.");
      +        case RfbConstants.VNC_AUTH_FAILED:
      +            throw new RuntimeException("Connection to VNC server failed: wrong password.");
       
      -            default:
      -                throw new RuntimeException("Connection to VNC server failed, reason code: " + authResult);
      +        default:
      +            throw new RuntimeException("Connection to VNC server failed, reason code: " + authResult);
               }
       
               switchOff();
      @@ -265,15 +265,15 @@ public class Vnc_3_3_Authentication extends OneTimeSwitch {
               Element source = new MockSource("source") {
                   {
                       bufs = ByteBuffer.convertByteArraysToByteBuffers(
      -                // Request authentication and send 16 byte challenge
      -                    new byte[] {0, 0, 0, RfbConstants.VNC_AUTH, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
      -                    // Respond to challenge with AUTH_OK
      -                    new byte[] {0, 0, 0, RfbConstants.VNC_AUTH_OK});
      +                        // Request authentication and send 16 byte challenge
      +                        new byte[] {0, 0, 0, RfbConstants.VNC_AUTH, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
      +                        // Respond to challenge with AUTH_OK
      +                        new byte[] {0, 0, 0, RfbConstants.VNC_AUTH_OK});
                   }
               };
       
               Element mainSink = new FakeSink("mainSink");
      -        final Vnc_3_3_Authentication auth = new Vnc_3_3_Authentication("auth", password);
      +        final Vnc33Authentication auth = new Vnc33Authentication("auth", password);
               Element initSink = new MockSink("initSink") {
                   {
                       // Expect encoded password
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/Vnc_3_3_Hello.java b/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/vnc/Vnc33Hello.java
      old mode 100644
      new mode 100755
      similarity index 96%
      rename from services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/Vnc_3_3_Hello.java
      rename to services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/vnc/Vnc33Hello.java
      index 1a65a9933fa..812c6a83644
      --- a/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/Vnc_3_3_Hello.java
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/vnc/Vnc33Hello.java
      @@ -14,7 +14,7 @@
       // KIND, either express or implied.  See the License for the
       // specific language governing permissions and limitations
       // under the License.
      -package vncclient;
      +package vncclient.vnc;
       
       import java.io.ByteArrayInputStream;
       import java.io.ByteArrayOutputStream;
      @@ -33,9 +33,9 @@ import streamer.PipelineImpl;
        * "RFB 003.007\n". We need to send response packet with supported protocol
        * version, e.g. "RFB 003.003\n".
        */
      -public class Vnc_3_3_Hello extends OneTimeSwitch {
      +public class Vnc33Hello extends OneTimeSwitch {
       
      -    public Vnc_3_3_Hello(String id) {
      +    public Vnc33Hello(String id) {
               super(id);
           }
       
      @@ -92,7 +92,7 @@ public class Vnc_3_3_Hello extends OneTimeSwitch {
               InputStreamSource inputStreamSource = new InputStreamSource("source", is);
               OutputStreamSink outputStreamSink = new OutputStreamSink("mainSink", mainOS);
       
      -        Vnc_3_3_Hello hello = new Vnc_3_3_Hello("hello");
      +        Vnc33Hello hello = new Vnc33Hello("hello");
       
               Pipeline pipeline = new PipelineImpl("test");
       
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/VncInitializer.java b/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/vnc/VncInitializer.java
      old mode 100644
      new mode 100755
      similarity index 77%
      rename from services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/VncInitializer.java
      rename to services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/vnc/VncInitializer.java
      index a812a616945..0b96c7303e4
      --- a/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/VncInitializer.java
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/vnc/VncInitializer.java
      @@ -14,16 +14,16 @@
       // KIND, either express or implied.  See the License for the
       // specific language governing permissions and limitations
       // under the License.
      -package vncclient;
      +package vncclient.vnc;
       
       import streamer.ByteBuffer;
       import streamer.Element;
       import streamer.Link;
      -import streamer.MockSink;
      -import streamer.MockSource;
       import streamer.OneTimeSwitch;
       import streamer.Pipeline;
       import streamer.PipelineImpl;
      +import streamer.debug.MockSink;
      +import streamer.debug.MockSource;
       import common.ScreenDescription;
       
       public class VncInitializer extends OneTimeSwitch {
      @@ -113,13 +113,13 @@ public class VncInitializer extends OneTimeSwitch {
               String desktopName = buf.readString(length, RfbConstants.US_ASCII_CHARSET);
               buf.unref();
               if (verbose)
      -            System.out.println("[" + this + "] INFO: Desktop name: \"" + desktopName + "\", bpp: " + bitsPerPixel + ", depth: " + depth + ", screen size: " +
      -                framebufferWidth + "x" + framebufferHeight + ".");
      +            System.out.println("[" + this + "] INFO: Desktop name: \"" + desktopName + "\", bpp: " + bitsPerPixel + ", depth: " + depth + ", screen size: "
      +                    + framebufferWidth + "x" + framebufferHeight + ".");
       
               // Set screen properties
               screen.setFramebufferSize(framebufferWidth, framebufferHeight);
      -        screen.setPixelFormat(bitsPerPixel, depth, bigEndianFlag != RfbConstants.LITTLE_ENDIAN, trueColorFlag == RfbConstants.TRUE_COLOR, redMax, greenMax, blueMax,
      -            redShift, greenShift, blueShift);
      +        screen.setPixelFormat(bitsPerPixel, depth, bigEndianFlag != RfbConstants.LITTLE_ENDIAN, trueColorFlag == RfbConstants.TRUE_COLOR, redMax, greenMax, blueMax, redShift,
      +                greenShift, blueShift);
               screen.setDesktopName(desktopName);
       
               // If sever screen has different parameters than ours, then change it
      @@ -167,45 +167,45 @@ public class VncInitializer extends OneTimeSwitch {
               Element source = new MockSource("source") {
                   {
                       bufs = ByteBuffer.convertByteArraysToByteBuffers(
      -                // Send screen description
      -                    new byte[] {
      -                        // Framebuffer width (short)
      -                        0, (byte)200,
      -                        // Framebuffer height (short)
      -                        0, 100,
      -                        // Bits per pixel
      -                        32,
      -                        // Depth,
      -                        24,
      -                        // Endianness flag
      -                        RfbConstants.LITTLE_ENDIAN,
      -                        // Truecolor flag
      -                        RfbConstants.TRUE_COLOR,
      -                        // Red max (short)
      -                        0, (byte)255,
      -                        // Green max (short)
      -                        0, (byte)255,
      -                        // Blue max (short)
      -                        0, (byte)255,
      -                        // Red shift
      -                        16,
      -                        // Green shift
      -                        8,
      -                        // Blue shift
      -                        0,
      -                        // Padding
      -                        0, 0, 0,
      -                        // Desktop name length (int)
      -                        0, 0, 0, 4,
      -                        // Desktop name ("test", 4 bytes)
      -                        't', 'e', 's', 't',
      +                        // Send screen description
      +                        new byte[] {
      +                                // Framebuffer width (short)
      +                                0, (byte)200,
      +                                // Framebuffer height (short)
      +                                0, 100,
      +                                // Bits per pixel
      +                                32,
      +                                // Depth,
      +                                24,
      +                                // Endianness flag
      +                                RfbConstants.LITTLE_ENDIAN,
      +                                // Truecolor flag
      +                                RfbConstants.TRUE_COLOR,
      +                                // Red max (short)
      +                                0, (byte)255,
      +                                // Green max (short)
      +                                0, (byte)255,
      +                                // Blue max (short)
      +                                0, (byte)255,
      +                                // Red shift
      +                                16,
      +                                // Green shift
      +                                8,
      +                                // Blue shift
      +                                0,
      +                                // Padding
      +                                0, 0, 0,
      +                                // Desktop name length (int)
      +                                0, 0, 0, 4,
      +                                // Desktop name ("test", 4 bytes)
      +                                't', 'e', 's', 't',
       
      -                        // Tail
      -                        1, 2, 3
      +                                // Tail
      +                                1, 2, 3
       
      -                    },
      -                    // Tail packet
      -                    new byte[] {4, 5, 6});
      +                        },
      +                        // Tail packet
      +                        new byte[] {4, 5, 6});
                   }
               };
       
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/VncMessageHandler.java b/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/vnc/VncMessageHandler.java
      old mode 100644
      new mode 100755
      similarity index 83%
      rename from services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/VncMessageHandler.java
      rename to services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/vnc/VncMessageHandler.java
      index 0d4abfe0334..5914cb30f7a
      --- a/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/VncMessageHandler.java
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/java/vncclient/vnc/VncMessageHandler.java
      @@ -14,20 +14,21 @@
       // KIND, either express or implied.  See the License for the
       // specific language governing permissions and limitations
       // under the License.
      -package vncclient;
      +package vncclient.vnc;
       
       import streamer.BaseElement;
       import streamer.ByteBuffer;
       import streamer.Element;
       import streamer.Link;
      -import streamer.MockSink;
      -import streamer.MockSource;
       import streamer.Pipeline;
       import streamer.PipelineImpl;
      +import streamer.debug.MockSink;
      +import streamer.debug.MockSource;
       import common.BitmapOrder;
       import common.BitmapRectangle;
       import common.CopyRectOrder;
       import common.ScreenDescription;
      +import common.adapter.AwtClipboardAdapter;
       
       public class VncMessageHandler extends BaseElement {
           protected ScreenDescription screen = null;
      @@ -39,7 +40,6 @@ public class VncMessageHandler extends BaseElement {
           public static final String FRAME_BUFFER_UPDATE_REQUEST_ADAPTER_PAD = "fbur";
       
           // Keys for metadata
      -    public static final String CLIPBOARD_CONTENT = "content";
           public static final String TARGET_X = "x";
           public static final String TARGET_Y = "y";
           public static final String WIDTH = "width";
      @@ -88,33 +88,33 @@ public class VncMessageHandler extends BaseElement {
                   // Invoke packet handler by packet type.
                   switch (messageType) {
       
      -                case RfbConstants.SERVER_FRAMEBUFFER_UPDATE: {
      -                    // Handle frame buffer update
      -                    if (!handleFBU(buf, link))
      -                        return;
      +            case RfbConstants.SERVER_FRAMEBUFFER_UPDATE: {
      +                // Handle frame buffer update
      +                if (!handleFBU(buf, link))
      +                    return;
       
      -                    // Frame buffer update is received and fully processed, send request for
      -                    // another frame buffer update to server.
      -                    sendFBUR();
      +                // Frame buffer update is received and fully processed, send request for
      +                // another frame buffer update to server.
      +                sendFBUR();
       
      -                    break;
      -                }
      +                break;
      +            }
       
      -                case RfbConstants.SERVER_BELL: {
      -                    if (!handleBell(buf, link))
      -                        return;
      -                    break;
      -                }
      +            case RfbConstants.SERVER_BELL: {
      +                if (!handleBell(buf, link))
      +                    return;
      +                break;
      +            }
       
      -                case RfbConstants.SERVER_CUT_TEXT: {
      -                    if (!handleClipboard(buf, link))
      -                        return;
      -                    break;
      -                }
      +            case RfbConstants.SERVER_CUT_TEXT: {
      +                if (!handleClipboard(buf, link))
      +                    return;
      +                break;
      +            }
       
      -                default:
      -                    // TODO: allow to extend functionality
      -                    throw new RuntimeException("Unknown server packet type: " + messageType + ".");
      +            default:
      +                // TODO: allow to extend functionality
      +                throw new RuntimeException("Unknown server packet type: " + messageType + ".");
                   }
       
                   // Cut tail, if any
      @@ -144,7 +144,7 @@ public class VncMessageHandler extends BaseElement {
       
               // Send content in metadata
               ByteBuffer outBuf = new ByteBuffer(0);
      -        outBuf.putMetadata(CLIPBOARD_CONTENT, content);
      +        outBuf.putMetadata(AwtClipboardAdapter.CLIPBOARD_CONTENT, content);
       
               pushDataToPad(SERVER_CLIPBOARD_ADAPTER_PAD, outBuf);
       
      @@ -186,8 +186,8 @@ public class VncMessageHandler extends BaseElement {
                   buf.cursor = (Integer)buf.getMetadata(SAVED_CURSOR_POSITION);
       
               if (verbose && numberOfProcessedRectangles > 0)
      -            System.out.println("[" + this + "] INFO: Restarting from saved point. Number of already processed rectangles: " + numberOfRectangles + ", cursor: " +
      -                buf.cursor + ".");
      +            System.out.println("[" + this + "] INFO: Restarting from saved point. Number of already processed rectangles: " + numberOfRectangles + ", cursor: "
      +                    + buf.cursor + ".");
       
               // For all new rectangles
               for (int i = numberOfProcessedRectangles; i < numberOfRectangles; i++) {
      @@ -209,27 +209,27 @@ public class VncMessageHandler extends BaseElement {
                   // Process rectangle
                   switch (encodingType) {
       
      -                case RfbConstants.ENCODING_RAW: {
      -                    if (!handleRawRectangle(buf, link, x, y, width, height))
      -                        return false;
      -                    break;
      -                }
      +            case RfbConstants.ENCODING_RAW: {
      +                if (!handleRawRectangle(buf, link, x, y, width, height))
      +                    return false;
      +                break;
      +            }
       
      -                case RfbConstants.ENCODING_COPY_RECT: {
      -                    if (!handleCopyRect(buf, link, x, y, width, height))
      -                        return false;
      -                    break;
      -                }
      +            case RfbConstants.ENCODING_COPY_RECT: {
      +                if (!handleCopyRect(buf, link, x, y, width, height))
      +                    return false;
      +                break;
      +            }
       
      -                case RfbConstants.ENCODING_DESKTOP_SIZE: {
      -                    if (!handleScreenSizeChangeRect(buf, link, x, y, width, height))
      -                        return false;
      -                    break;
      -                }
      +            case RfbConstants.ENCODING_DESKTOP_SIZE: {
      +                if (!handleScreenSizeChangeRect(buf, link, x, y, width, height))
      +                    return false;
      +                break;
      +            }
       
      -                default:
      -                    // TODO: allow to extend functionality
      -                    throw new RuntimeException("Unsupported ecnoding: " + encodingType + ".");
      +            default:
      +                // TODO: allow to extend functionality
      +                throw new RuntimeException("Unsupported ecnoding: " + encodingType + ".");
                   }
       
                   // Update information about processed rectangles to avoid handling of same
      @@ -270,8 +270,8 @@ public class VncMessageHandler extends BaseElement {
               order.height = height;
       
               if (verbose)
      -            System.out.println("[" + this + "] INFO: Copy rect. X: " + x + ", y: " + y + ", width: " + width + ", height: " + height + ", srcX: " + order.srcX +
      -                ", srcY: " + order.srcY + ".");
      +            System.out.println("[" + this + "] INFO: Copy rect. X: " + x + ", y: " + y + ", width: " + width + ", height: " + height + ", srcX: " + order.srcX
      +                    + ", srcY: " + order.srcY + ".");
       
               pushDataToPad(PIXEL_ADAPTER_PAD, new ByteBuffer(order));
       
      @@ -288,8 +288,8 @@ public class VncMessageHandler extends BaseElement {
                   return false;
       
               if (verbose)
      -            System.out.println("[" + this + "] INFO: Raw rect. X: " + x + ", y: " + y + ", width: " + width + ", height: " + height + ", data length: " + rectDataLength +
      -                ".");
      +            System.out.println("[" + this + "] INFO: Raw rect. X: " + x + ", y: " + y + ", width: " + width + ", height: " + height + ", data length: "
      +                    + rectDataLength + ".");
       
               BitmapRectangle rectangle = new BitmapRectangle();
               rectangle.x = x;
      @@ -337,8 +337,7 @@ public class VncMessageHandler extends BaseElement {
               Element source = new MockSource("source") {
                   {
                       // Split messages at random boundaries to check "pushback" logic
      -                bufs =
      -                    ByteBuffer.convertByteArraysToByteBuffers(new byte[] {
      +                bufs = ByteBuffer.convertByteArraysToByteBuffers(new byte[] {
                               // Message type: server bell
                               RfbConstants.SERVER_BELL,
       
      @@ -349,7 +348,7 @@ public class VncMessageHandler extends BaseElement {
                               // Length (test)
                               0, 0, 0, 4,
       
      -                    }, new byte[] {
      +                }, new byte[] {
                               // Clipboard text
                               't', 'e', 's', 't',
       
      @@ -360,7 +359,7 @@ public class VncMessageHandler extends BaseElement {
                               // Number of rectangles
                               0, 3,},
       
      -                    new byte[] {
      +                        new byte[] {
       
                               // x, y, width, height: 0x0@4x4
                               0, 0, 0, 0, 0, 4, 0, 4,
      @@ -368,7 +367,7 @@ public class VncMessageHandler extends BaseElement {
                               (byte)((RfbConstants.ENCODING_DESKTOP_SIZE >> 24) & 0xff), (byte)((RfbConstants.ENCODING_DESKTOP_SIZE >> 16) & 0xff),
                               (byte)((RfbConstants.ENCODING_DESKTOP_SIZE >> 8) & 0xff), (byte)((RfbConstants.ENCODING_DESKTOP_SIZE >> 0) & 0xff),},
       
      -                    new byte[] {
      +                        new byte[] {
       
                               // x, y, width, height: 0x0@4x4
                               0, 0, 0, 0, 0, 4, 0, 4,
      @@ -390,7 +389,7 @@ public class VncMessageHandler extends BaseElement {
       
               ScreenDescription screen = new ScreenDescription() {
                   {
      -                this.bytesPerPixel = 1;
      +                bytesPerPixel = 1;
                   }
               };
       
      @@ -401,7 +400,8 @@ public class VncMessageHandler extends BaseElement {
               Element bellSink = new MockSink("bell", emptyBuf);
               Element clipboardSink = new MockSink("clipboard", emptyBuf);
               Element desktopSizeChangeSink = new MockSink("desktop_size", emptyBuf);
      -        Element pixelsSink = new MockSink("pixels", ByteBuffer.convertByteArraysToByteBuffers(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,}));
      +        Element pixelsSink = new MockSink("pixels",
      +                ByteBuffer.convertByteArraysToByteBuffers(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,}));
               Element copyRectSink = new MockSink("copy_rect", emptyBuf);
       
               Pipeline pipeline = new PipelineImpl("test");
      diff --git a/services/console-proxy-rdp/rdpconsole/src/main/resources/jaas_ntlm_config.txt b/services/console-proxy-rdp/rdpconsole/src/main/resources/jaas_ntlm_config.txt
      new file mode 100755
      index 00000000000..41376095acf
      --- /dev/null
      +++ b/services/console-proxy-rdp/rdpconsole/src/main/resources/jaas_ntlm_config.txt
      @@ -0,0 +1,21 @@
      +// Licensed to the Apache Software Foundation (ASF) under one
      +// or more contributor license agreements.  See the NOTICE file
      +// distributed with this work for additional information
      +// regarding copyright ownership.  The ASF licenses this file
      +// to you under the Apache License, Version 2.0 (the
      +// "License"); you may not use this file except in compliance
      +// with the License.  You may obtain a copy of the License at
      +//
      +//   http://www.apache.org/licenses/LICENSE-2.0
      +//
      +// Unless required by applicable law or agreed to in writing,
      +// software distributed under the License is distributed on an
      +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
      +// KIND, either express or implied.  See the License for the
      +// specific language governing permissions and limitations
      +// under the License.
      +
      +MyConfig { com.sun.security.auth.module.Krb5LoginModule required
      +  useTicketCache=true
      +  doNotPrompt=false;
      +};
      diff --git a/services/console-proxy-rdp/rdpconsole/src/test/doc/README.txt b/services/console-proxy-rdp/rdpconsole/src/test/doc/README.txt
      old mode 100644
      new mode 100755
      index dd4168373b1..704f5f52f16
      --- a/services/console-proxy-rdp/rdpconsole/src/test/doc/README.txt
      +++ b/services/console-proxy-rdp/rdpconsole/src/test/doc/README.txt
      @@ -30,3 +30,5 @@ fingerprints.
       
       File rdp-key.pem contains private key in PEM format for use with
       Wireshark.
      +
      +As alternative, mimikatz can be used to extract RDP private key.
      diff --git a/services/console-proxy-rdp/rdpconsole/src/test/doc/dev-rdp-config.bat b/services/console-proxy-rdp/rdpconsole/src/test/doc/dev-rdp-config.bat
      old mode 100644
      new mode 100755
      index 14a7bbd0f0a..4e19157e5d5
      --- a/services/console-proxy-rdp/rdpconsole/src/test/doc/dev-rdp-config.bat
      +++ b/services/console-proxy-rdp/rdpconsole/src/test/doc/dev-rdp-config.bat
      @@ -111,6 +111,19 @@ rem Start TS service
       
       net start Termservice
       
      +rem Enable logs
      +
      +wevtutil sl Microsoft-Windows-TerminalServices-RemoteConnectionManager/Admin /enabled:true /quiet:true
      +wevtutil sl Microsoft-Windows-TerminalServices-RemoteConnectionManager/Analytic /enabled:true /quiet:true
      +wevtutil sl Microsoft-Windows-TerminalServices-RemoteConnectionManager/Debug /enabled:true /quiet:true
      +wevtutil sl Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational /enabled:true /quiet:true
      +wevtutil sl Microsoft-Windows-TerminalServices-SessionBroker-Client/Admin /enabled:true /quiet:true
      +wevtutil sl Microsoft-Windows-TerminalServices-SessionBroker-Client/Analytic /enabled:true /quiet:true
      +wevtutil sl Microsoft-Windows-TerminalServices-SessionBroker-Client/Debug /enabled:true /quiet:true
      +wevtutil sl Microsoft-Windows-TerminalServices-SessionBroker-Client/Operational /enabled:true /quiet:true
      +wevtutil sl Microsoft-Windows-NTLM/Operational /enabled:true /quiet:true
      +
      +
       
       rem For Network Monitor Decrypt Expert.
       
      diff --git a/services/console-proxy-rdp/rdpconsole/src/test/doc/freerdp-debug-log.txt b/services/console-proxy-rdp/rdpconsole/src/test/doc/freerdp-debug-log.txt
      new file mode 100755
      index 00000000000..d3101d698ed
      --- /dev/null
      +++ b/services/console-proxy-rdp/rdpconsole/src/test/doc/freerdp-debug-log.txt
      @@ -0,0 +1,772 @@
      +// Licensed to the Apache Software Foundation (ASF) under one
      +// or more contributor license agreements.  See the NOTICE file
      +// distributed with this work for additional information
      +// regarding copyright ownership.  The ASF licenses this file
      +// to you under the Apache License, Version 2.0 (the
      +// "License"); you may not use this file except in compliance
      +// with the License.  You may obtain a copy of the License at
      +//
      +//   http://www.apache.org/licenses/LICENSE-2.0
      +//
      +// Unless required by applicable law or agreed to in writing,
      +// software distributed under the License is distributed on an
      +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
      +// KIND, either express or implied.  See the License for the
      +// specific language governing permissions and limitations
      +// under the License.
      +connected to 192.168.1.3:3389
      +NEGOTIATE_MESSAGE (length = 40)
      +0000 4e 54 4c 4d 53 53 50 00 01 00 00 00 b7 82 08 e2 NTLMSSP.........
      +0010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
      +0020 06 01 b1 1d 00 00 00 0f                         ........
      +
      +VERSION =
      +{
      +	ProductMajorVersion: 6
      +	ProductMinorVersion: 1
      +	ProductBuild: 7601
      +	Reserved: 0x000000
      +	NTLMRevisionCurrent: 0x0F
      +ntlm_generate_client_challenge: ClientChallenge (random bytes): 
      +0000 01 02 03 04 05 06 07 08                         ........
      +
      +CHALLENGE_MESSAGE (length = 238)
      +0000 4e 54 4c 4d 53 53 50 00 02 00 00 00 1e 00 1e 00 NTLMSSP.........
      +0010 38 00 00 00 35 82 8a e2 4a 25 50 a5 11 9b d6 16 8...5...J%P.....
      +0020 00 00 00 00 00 00 00 00 98 00 98 00 56 00 00 00 ............V...
      +0030 06 03 d7 24 00 00 00 0f 57 00 49 00 4e 00 2d 00 ...$....W.I.N.-.
      +0040 4c 00 4f 00 34 00 31 00 39 00 42 00 32 00 4c 00 L.O.4.1.9.B.2.L.
      +0050 53 00 52 00 30 00 02 00 1e 00 57 00 49 00 4e 00 S.R.0.....W.I.N.
      +0060 2d 00 4c 00 4f 00 34 00 31 00 39 00 42 00 32 00 -.L.O.4.1.9.B.2.
      +0070 4c 00 53 00 52 00 30 00 01 00 1e 00 57 00 49 00 L.S.R.0.....W.I.
      +0080 4e 00 2d 00 4c 00 4f 00 34 00 31 00 39 00 42 00 N.-.L.O.4.1.9.B.
      +0090 32 00 4c 00 53 00 52 00 30 00 04 00 1e 00 57 00 2.L.S.R.0.....W.
      +00a0 49 00 4e 00 2d 00 4c 00 4f 00 34 00 31 00 39 00 I.N.-.L.O.4.1.9.
      +00b0 42 00 32 00 4c 00 53 00 52 00 30 00 03 00 1e 00 B.2.L.S.R.0.....
      +00c0 57 00 49 00 4e 00 2d 00 4c 00 4f 00 34 00 31 00 W.I.N.-.L.O.4.1.
      +00d0 39 00 42 00 32 00 4c 00 53 00 52 00 30 00 07 00 9.B.2.L.S.R.0...
      +00e0 08 00 a0 e8 85 2c e4 c9 ce 01 00 00 00 00       .....,........
      +
      +negotiateFlags "0xE28A8235"{
      +	NTLMSSP_NEGOTIATE_56 (0),
      +	NTLMSSP_NEGOTIATE_KEY_EXCH (1),
      +	NTLMSSP_NEGOTIATE_128 (2),
      +	NTLMSSP_NEGOTIATE_VERSION (6),
      +	NTLMSSP_NEGOTIATE_TARGET_INFO (8),
      +	NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY (12),
      +	NTLMSSP_TARGET_TYPE_SERVER (14),
      +	NTLMSSP_NEGOTIATE_ALWAYS_SIGN (16),
      +	NTLMSSP_NEGOTIATE_NTLM (22),
      +	NTLMSSP_NEGOTIATE_SEAL (26),
      +	NTLMSSP_NEGOTIATE_SIGN (27),
      +	NTLMSSP_REQUEST_TARGET (29),
      +	NTLMSSP_NEGOTIATE_UNICODE (31),
      +}
      +VERSION =
      +{
      +	ProductMajorVersion: 6
      +	ProductMinorVersion: 3
      +	ProductBuild: 9431
      +	Reserved: 0x000000
      +	NTLMRevisionCurrent: 0x0F
      +TargetName (Len: 30 MaxLen: 30 BufferOffset: 56)
      +0000 57 00 49 00 4e 00 2d 00 4c 00 4f 00 34 00 31 00 W.I.N.-.L.O.4.1.
      +0010 39 00 42 00 32 00 4c 00 53 00 52 00 30 00       9.B.2.L.S.R.0.
      +
      +TargetInfo (Len: 152 MaxLen: 152 BufferOffset: 86)
      +0000 02 00 1e 00 57 00 49 00 4e 00 2d 00 4c 00 4f 00 ....W.I.N.-.L.O.
      +0010 34 00 31 00 39 00 42 00 32 00 4c 00 53 00 52 00 4.1.9.B.2.L.S.R.
      +0020 30 00 01 00 1e 00 57 00 49 00 4e 00 2d 00 4c 00 0.....W.I.N.-.L.
      +0030 4f 00 34 00 31 00 39 00 42 00 32 00 4c 00 53 00 O.4.1.9.B.2.L.S.
      +0040 52 00 30 00 04 00 1e 00 57 00 49 00 4e 00 2d 00 R.0.....W.I.N.-.
      +0050 4c 00 4f 00 34 00 31 00 39 00 42 00 32 00 4c 00 L.O.4.1.9.B.2.L.
      +0060 53 00 52 00 30 00 03 00 1e 00 57 00 49 00 4e 00 S.R.0.....W.I.N.
      +0070 2d 00 4c 00 4f 00 34 00 31 00 39 00 42 00 32 00 -.L.O.4.1.9.B.2.
      +0080 4c 00 53 00 52 00 30 00 07 00 08 00 a0 e8 85 2c L.S.R.0........,
      +0090 e4 c9 ce 01 00 00 00 00                         ........
      +
      +ChallengeTargetInfo (152):
      +AV_PAIRs =
      +{
      +	MsvAvNbDomainName AvId: 2 AvLen: 30
      +0000 57 00 49 00 4e 00 2d 00 4c 00 4f 00 34 00 31 00 W.I.N.-.L.O.4.1.
      +0010 39 00 42 00 32 00 4c 00 53 00 52 00 30 00       9.B.2.L.S.R.0.
      +	MsvAvNbComputerName AvId: 1 AvLen: 30
      +0000 57 00 49 00 4e 00 2d 00 4c 00 4f 00 34 00 31 00 W.I.N.-.L.O.4.1.
      +0010 39 00 42 00 32 00 4c 00 53 00 52 00 30 00       9.B.2.L.S.R.0.
      +	MsvAvDnsDomainName AvId: 4 AvLen: 30
      +0000 57 00 49 00 4e 00 2d 00 4c 00 4f 00 34 00 31 00 W.I.N.-.L.O.4.1.
      +0010 39 00 42 00 32 00 4c 00 53 00 52 00 30 00       9.B.2.L.S.R.0.
      +	MsvAvDnsComputerName AvId: 3 AvLen: 30
      +0000 57 00 49 00 4e 00 2d 00 4c 00 4f 00 34 00 31 00 W.I.N.-.L.O.4.1.
      +0010 39 00 42 00 32 00 4c 00 53 00 52 00 30 00       9.B.2.L.S.R.0.
      +	MsvAvTimestamp AvId: 7 AvLen: 8
      +0000 a0 e8 85 2c e4 c9 ce 01                         ...,....
      +}
      +ntlm_generate_timestamp: timestamp
      +0000 a0 e8 85 2c e4 c9 ce 01                         ...,....
      +
      +ntlm_generate_timestamp: ChallengeTimestamp
      +0000 a0 e8 85 2c e4 c9 ce 01                         ...,....
      +
      +NTOWFv1W: Password:
      +0000 52 00 32 00 50 00 72 00 65 00 76 00 69 00 65 00 R.2.P.r.e.v.i.e.
      +0010 77 00 21 00                                     w.!.
      +
      +NTOWFv1W: NtHash (MD4(Password)):
      +0000 25 f3 39 c9 86 b5 c2 6f dc ab 91 34 93 a2 18 2a %.9....o...4...*
      +
      +NTOWFv2W: NtHashV1 (NTOWFv1W(Password)):
      +0000 25 f3 39 c9 86 b5 c2 6f dc ab 91 34 93 a2 18 2a %.9....o...4...*
      +
      +NTOWFv2W: User:
      +0000 41 00 64 00 6d 00 69 00 6e 00 69 00 73 00 74 00 A.d.m.i.n.i.s.t.
      +0010 72 00 61 00 74 00 6f 00 72 00                   r.a.t.o.r.
      +
      +NTOWFv2W: Domain:
      +0000 77 00 6f 00 72 00 6b 00 67 00 72 00 6f 00 75 00 w.o.r.k.g.r.o.u.
      +0010 70 00                                           p.
      +
      +NTOWFv2W: buffer (User+Domain):
      +0000 41 00 44 00 4d 00 49 00 4e 00 49 00 53 00 54 00 A.D.M.I.N.I.S.T.
      +0010 52 00 41 00 54 00 4f 00 52 00 77 00 6f 00 72 00 R.A.T.O.R.w.o.r.
      +0020 6b 00 67 00 72 00 6f 00 75 00 70 00             k.g.r.o.u.p.
      +
      +NTOWFv2W: NtHash (HMAC_MD5(NtHashV1, User+Domain)):
      +0000 5f cc 4c 48 74 6b 94 ce b7 ae f1 0d c9 11 22 8f _.LHtk........".
      +
      +ntlm_compute_ntlm_v2_hash: hash (NTOWFv2W(Password, User, Domain)):
      +0000 5f cc 4c 48 74 6b 94 ce b7 ae f1 0d c9 11 22 8f _.LHtk........".
      +
      +ntlm_compute_lm_v2_response: ntlm_v2_hash:
      +0000 5f cc 4c 48 74 6b 94 ce b7 ae f1 0d c9 11 22 8f _.LHtk........".
      +
      +ntlm_compute_lm_v2_response: value (ServerChallenge + ClientChallenge):
      +0000 4a 25 50 a5 11 9b d6 16 01 02 03 04 05 06 07 08 J%P.............
      +
      +ntlm_compute_lm_v2_response: response (HMAC_MD5(ntlm_v2_hash, value) + ClientChallenge):
      +0000 7c c0 fd 08 c5 14 05 34 f3 12 9e 3e a3 09 bc c6 |......4...>....
      +0010 01 02 03 04 05 06 07 08                         ........
      +
      +NTOWFv1W: Password:
      +0000 52 00 32 00 50 00 72 00 65 00 76 00 69 00 65 00 R.2.P.r.e.v.i.e.
      +0010 77 00 21 00                                     w.!.
      +
      +NTOWFv1W: NtHash (MD4(Password)):
      +0000 25 f3 39 c9 86 b5 c2 6f dc ab 91 34 93 a2 18 2a %.9....o...4...*
      +
      +NTOWFv2W: NtHashV1 (NTOWFv1W(Password)):
      +0000 25 f3 39 c9 86 b5 c2 6f dc ab 91 34 93 a2 18 2a %.9....o...4...*
      +
      +NTOWFv2W: User:
      +0000 41 00 64 00 6d 00 69 00 6e 00 69 00 73 00 74 00 A.d.m.i.n.i.s.t.
      +0010 72 00 61 00 74 00 6f 00 72 00                   r.a.t.o.r.
      +
      +NTOWFv2W: Domain:
      +0000 77 00 6f 00 72 00 6b 00 67 00 72 00 6f 00 75 00 w.o.r.k.g.r.o.u.
      +0010 70 00                                           p.
      +
      +NTOWFv2W: buffer (User+Domain):
      +0000 41 00 44 00 4d 00 49 00 4e 00 49 00 53 00 54 00 A.D.M.I.N.I.S.T.
      +0010 52 00 41 00 54 00 4f 00 52 00 77 00 6f 00 72 00 R.A.T.O.R.w.o.r.
      +0020 6b 00 67 00 72 00 6f 00 75 00 70 00             k.g.r.o.u.p.
      +
      +NTOWFv2W: NtHash (HMAC_MD5(NtHashV1, User+Domain)):
      +0000 5f cc 4c 48 74 6b 94 ce b7 ae f1 0d c9 11 22 8f _.LHtk........".
      +
      +ntlm_compute_ntlm_v2_hash: hash (NTOWFv2W(Password, User, Domain)):
      +0000 5f cc 4c 48 74 6b 94 ce b7 ae f1 0d c9 11 22 8f _.LHtk........".
      +
      +ntlm_compute_ntlm_v2_response: Password (length = 20)
      +0000 52 00 32 00 50 00 72 00 65 00 76 00 69 00 65 00 R.2.P.r.e.v.i.e.
      +0010 77 00 21 00                                     w.!.
      +
      +ntlm_compute_ntlm_v2_response: Username (length = 26)
      +0000 41 00 64 00 6d 00 69 00 6e 00 69 00 73 00 74 00 A.d.m.i.n.i.s.t.
      +0010 72 00 61 00 74 00 6f 00 72 00                   r.a.t.o.r.
      +
      +ntlm_compute_ntlm_v2_response: Domain (length = 18)
      +0000 77 00 6f 00 72 00 6b 00 67 00 72 00 6f 00 75 00 w.o.r.k.g.r.o.u.
      +0010 70 00                                           p.
      +
      +ntlm_compute_ntlm_v2_response: Workstation (length = 12)
      +0000 61 00 70 00 6f 00 6c 00 6c 00 6f 00             a.p.o.l.l.o.
      +
      +ntlm_compute_ntlm_v2_response: TargetInfo (length = 234)
      +0000 02 00 1e 00 57 00 49 00 4e 00 2d 00 4c 00 4f 00 ....W.I.N.-.L.O.
      +0010 34 00 31 00 39 00 42 00 32 00 4c 00 53 00 52 00 4.1.9.B.2.L.S.R.
      +0020 30 00 01 00 1e 00 57 00 49 00 4e 00 2d 00 4c 00 0.....W.I.N.-.L.
      +0030 4f 00 34 00 31 00 39 00 42 00 32 00 4c 00 53 00 O.4.1.9.B.2.L.S.
      +0040 52 00 30 00 04 00 1e 00 57 00 49 00 4e 00 2d 00 R.0.....W.I.N.-.
      +0050 4c 00 4f 00 34 00 31 00 39 00 42 00 32 00 4c 00 L.O.4.1.9.B.2.L.
      +0060 53 00 52 00 30 00 03 00 1e 00 57 00 49 00 4e 00 S.R.0.....W.I.N.
      +0070 2d 00 4c 00 4f 00 34 00 31 00 39 00 42 00 32 00 -.L.O.4.1.9.B.2.
      +0080 4c 00 53 00 52 00 30 00 07 00 08 00 a0 e8 85 2c L.S.R.0........,
      +0090 e4 c9 ce 01 06 00 04 00 02 00 00 00 0a 00 10 00 ................
      +00a0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
      +00b0 09 00 26 00 54 00 45 00 52 00 4d 00 53 00 52 00 ..&.T.E.R.M.S.R.
      +00c0 56 00 2f 00 31 00 39 00 32 00 2e 00 31 00 36 00 V./.1.9.2...1.6.
      +00d0 38 00 2e 00 31 00 2e 00 33 00 00 00 00 00 00 00 8...1...3.......
      +00e0 00 00 00 00 00 00 00 00 00 00                   ..........
      +
      +ntlm_compute_ntlm_v2_response: ntlm_v2_hash (ntlm_compute_ntlm_v2_hash(context, (char*) ntlm_v2_hash))
      +0000 5f cc 4c 48 74 6b 94 ce b7 ae f1 0d c9 11 22 8f _.LHtk........".
      +
      +ntlm_compute_ntlm_v2_response: ntlm_v2_temp (0x0101 + reserved 6 bytes + Timestamp + ClientChallenge + TargetInfo)
      +0000 01 01 00 00 00 00 00 00 a0 e8 85 2c e4 c9 ce 01 ...........,....
      +0010 01 02 03 04 05 06 07 08 00 00 00 00 02 00 1e 00 ................
      +0020 57 00 49 00 4e 00 2d 00 4c 00 4f 00 34 00 31 00 W.I.N.-.L.O.4.1.
      +0030 39 00 42 00 32 00 4c 00 53 00 52 00 30 00 01 00 9.B.2.L.S.R.0...
      +0040 1e 00 57 00 49 00 4e 00 2d 00 4c 00 4f 00 34 00 ..W.I.N.-.L.O.4.
      +0050 31 00 39 00 42 00 32 00 4c 00 53 00 52 00 30 00 1.9.B.2.L.S.R.0.
      +0060 04 00 1e 00 57 00 49 00 4e 00 2d 00 4c 00 4f 00 ....W.I.N.-.L.O.
      +0070 34 00 31 00 39 00 42 00 32 00 4c 00 53 00 52 00 4.1.9.B.2.L.S.R.
      +0080 30 00 03 00 1e 00 57 00 49 00 4e 00 2d 00 4c 00 0.....W.I.N.-.L.
      +0090 4f 00 34 00 31 00 39 00 42 00 32 00 4c 00 53 00 O.4.1.9.B.2.L.S.
      +00a0 52 00 30 00 07 00 08 00 a0 e8 85 2c e4 c9 ce 01 R.0........,....
      +00b0 06 00 04 00 02 00 00 00 0a 00 10 00 00 00 00 00 ................
      +00c0 00 00 00 00 00 00 00 00 00 00 00 00 09 00 26 00 ..............&.
      +00d0 54 00 45 00 52 00 4d 00 53 00 52 00 56 00 2f 00 T.E.R.M.S.R.V./.
      +00e0 31 00 39 00 32 00 2e 00 31 00 36 00 38 00 2e 00 1.9.2...1.6.8...
      +00f0 31 00 2e 00 33 00 00 00 00 00 00 00 00 00 00 00 1...3...........
      +0100 00 00 00 00 00 00                               ......
      +
      +ntlm_compute_ntlm_v2_response: ntlm_v2_chal (ServerChallenge + ntlm_v2_temp)
      +0000 4a 25 50 a5 11 9b d6 16 01 01 00 00 00 00 00 00 J%P.............
      +0010 a0 e8 85 2c e4 c9 ce 01 01 02 03 04 05 06 07 08 ...,............
      +0020 00 00 00 00 02 00 1e 00 57 00 49 00 4e 00 2d 00 ........W.I.N.-.
      +0030 4c 00 4f 00 34 00 31 00 39 00 42 00 32 00 4c 00 L.O.4.1.9.B.2.L.
      +0040 53 00 52 00 30 00 01 00 1e 00 57 00 49 00 4e 00 S.R.0.....W.I.N.
      +0050 2d 00 4c 00 4f 00 34 00 31 00 39 00 42 00 32 00 -.L.O.4.1.9.B.2.
      +0060 4c 00 53 00 52 00 30 00 04 00 1e 00 57 00 49 00 L.S.R.0.....W.I.
      +0070 4e 00 2d 00 4c 00 4f 00 34 00 31 00 39 00 42 00 N.-.L.O.4.1.9.B.
      +0080 32 00 4c 00 53 00 52 00 30 00 03 00 1e 00 57 00 2.L.S.R.0.....W.
      +0090 49 00 4e 00 2d 00 4c 00 4f 00 34 00 31 00 39 00 I.N.-.L.O.4.1.9.
      +00a0 42 00 32 00 4c 00 53 00 52 00 30 00 07 00 08 00 B.2.L.S.R.0.....
      +00b0 a0 e8 85 2c e4 c9 ce 01 06 00 04 00 02 00 00 00 ...,............
      +00c0 0a 00 10 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
      +00d0 00 00 00 00 09 00 26 00 54 00 45 00 52 00 4d 00 ......&.T.E.R.M.
      +00e0 53 00 52 00 56 00 2f 00 31 00 39 00 32 00 2e 00 S.R.V./.1.9.2...
      +00f0 31 00 36 00 38 00 2e 00 31 00 2e 00 33 00 00 00 1.6.8...1...3...
      +0100 00 00 00 00 00 00 00 00 00 00 00 00 00 00       ..............
      +
      +ntlm_compute_ntlm_v2_response: nt_proof_str ( HMAC_MD5(ntlm_v2_hash, ntlm_v2_temp_chal))
      +0000 19 4b eb ad da 24 d5 96 85 2e 24 94 d6 4a b8 5e .K...$....$..J.^
      +
      +ntlm_compute_ntlm_v2_response: NtChallengeResponse ( nt_proof_str + ntlm_v2_temp)
      +0000 19 4b eb ad da 24 d5 96 85 2e 24 94 d6 4a b8 5e .K...$....$..J.^
      +0010 01 01 00 00 00 00 00 00 a0 e8 85 2c e4 c9 ce 01 ...........,....
      +0020 01 02 03 04 05 06 07 08 00 00 00 00 02 00 1e 00 ................
      +0030 57 00 49 00 4e 00 2d 00 4c 00 4f 00 34 00 31 00 W.I.N.-.L.O.4.1.
      +0040 39 00 42 00 32 00 4c 00 53 00 52 00 30 00 01 00 9.B.2.L.S.R.0...
      +0050 1e 00 57 00 49 00 4e 00 2d 00 4c 00 4f 00 34 00 ..W.I.N.-.L.O.4.
      +0060 31 00 39 00 42 00 32 00 4c 00 53 00 52 00 30 00 1.9.B.2.L.S.R.0.
      +0070 04 00 1e 00 57 00 49 00 4e 00 2d 00 4c 00 4f 00 ....W.I.N.-.L.O.
      +0080 34 00 31 00 39 00 42 00 32 00 4c 00 53 00 52 00 4.1.9.B.2.L.S.R.
      +0090 30 00 03 00 1e 00 57 00 49 00 4e 00 2d 00 4c 00 0.....W.I.N.-.L.
      +00a0 4f 00 34 00 31 00 39 00 42 00 32 00 4c 00 53 00 O.4.1.9.B.2.L.S.
      +00b0 52 00 30 00 07 00 08 00 a0 e8 85 2c e4 c9 ce 01 R.0........,....
      +00c0 06 00 04 00 02 00 00 00 0a 00 10 00 00 00 00 00 ................
      +00d0 00 00 00 00 00 00 00 00 00 00 00 00 09 00 26 00 ..............&.
      +00e0 54 00 45 00 52 00 4d 00 53 00 52 00 56 00 2f 00 T.E.R.M.S.R.V./.
      +00f0 31 00 39 00 32 00 2e 00 31 00 36 00 38 00 2e 00 1.9.2...1.6.8...
      +0100 31 00 2e 00 33 00 00 00 00 00 00 00 00 00 00 00 1...3...........
      +0110 00 00 00 00 00 00                               ......
      +
      +ntlm_compute_ntlm_v2_response: SessionBaseKey ( HMAC_MD5(ntlm_v2_hash, nt_proof_str)
      +0000 8e 0f dd 12 4c 3b 11 7f 22 b9 4b 59 52 bc a7 18 ....L;..".KYR...
      +
      +ntlm_generate_key_exchange_key: KeyExchangeKey (SessionBaseKey): 
      +0000 8e 0f dd 12 4c 3b 11 7f 22 b9 4b 59 52 bc a7 18 ....L;..".KYR...
      +
      +ntlm_generate_random_session_key: RandomSessionKey (random bytes): 
      +0000 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 ................
      +
      +ntlm_generate_exported_session_key: ExportedSessionKey (RandomSessionKey): 
      +0000 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 ................
      +
      +ntlm_rc4k: key, 
      +0000 8e 0f dd 12 4c 3b 11 7f 22 b9 4b 59 52 bc a7 18 ....L;..".KYR...
      +
      +ntlm_rc4k: plaintext 
      +0000 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 ................
      +
      +ntlm_rc4k: ciphertext (RC4K(key, plaintext)) 
      +0000 e4 e9 c2 ad 41 02 2f 3c f9 4c 72 84 c5 2a 7c 6f ....A./<.Lr..*|o
      +
      +ntlm_encrypt_random_session_key: KeyExchangeKey: 
      +0000 8e 0f dd 12 4c 3b 11 7f 22 b9 4b 59 52 bc a7 18 ....L;..".KYR...
      +
      +ntlm_encrypt_random_session_key: RandomSessionKey: 
      +0000 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 ................
      +
      +ntlm_encrypt_random_session_key: EncryptedRandomSessionKey (RC4K(KeyExchangeKey, RandomSessionKey)): 
      +0000 e4 e9 c2 ad 41 02 2f 3c f9 4c 72 84 c5 2a 7c 6f ....A./<.Lr..*|o
      +
      +ntlm_generate_signing_key: exported_session_key: 
      +0000 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 ................
      +
      +ntlm_generate_signing_key: sign_magic: 
      +0000 73 65 73 73 69 6f 6e 20 6b 65 79 20 74 6f 20 63 session key to c
      +0010 6c 69 65 6e 74 2d 74 6f 2d 73 65 72 76 65 72 20 lient-to-server 
      +0020 73 69 67 6e 69 6e 67 20 6b 65 79 20 6d 61 67 69 signing key magi
      +0030 63 20 63 6f 6e 73 74 61 6e 74 00                c constant.
      +
      +ntlm_generate_signing_key: value ( exported_session_key + sign_magic ): 
      +0000 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 ................
      +0010 73 65 73 73 69 6f 6e 20 6b 65 79 20 74 6f 20 63 session key to c
      +0020 6c 69 65 6e 74 2d 74 6f 2d 73 65 72 76 65 72 20 lient-to-server 
      +0030 73 69 67 6e 69 6e 67 20 6b 65 79 20 6d 61 67 69 signing key magi
      +0040 63 20 63 6f 6e 73 74 61 6e 74 00                c constant.
      +
      +ntlm_generate_signing_key: signing_key (MD5(value)): 
      +0000 f6 ae 96 cb 05 e2 ab 54 f6 dd 59 f3 c9 d9 a0 43 .......T..Y....C
      +
      +ntlm_generate_client_signing_key: ExportedSessionKey: 
      +0000 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 ................
      +
      +ntlm_generate_client_signing_key: client_sign_magic: ":session key to client-to-server signing key magic constant"
      +0000 73 65 73 73 69 6f 6e 20 6b 65 79 20 74 6f 20 63 session key to c
      +0010 6c 69 65 6e 74 2d 74 6f 2d 73 65 72 76 65 72 20 lient-to-server 
      +0020 73 69 67 6e 69 6e 67 20 6b 65 79 20 6d 61 67 69 signing key magi
      +0030 63 20 63 6f 6e 73 74 61 6e 74 00                c constant.
      +
      +ntlm_generate_client_signing_key: ClientSigningKey ( ntlm_generate_signing_key(context->ExportedSessionKey, &sign_magic, context->ClientSigningKey))
      +0000 f6 ae 96 cb 05 e2 ab 54 f6 dd 59 f3 c9 d9 a0 43 .......T..Y....C
      +
      +ntlm_generate_signing_key: exported_session_key: 
      +0000 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 ................
      +
      +ntlm_generate_signing_key: sign_magic: 
      +0000 73 65 73 73 69 6f 6e 20 6b 65 79 20 74 6f 20 73 session key to s
      +0010 65 72 76 65 72 2d 74 6f 2d 63 6c 69 65 6e 74 20 erver-to-client 
      +0020 73 69 67 6e 69 6e 67 20 6b 65 79 20 6d 61 67 69 signing key magi
      +0030 63 20 63 6f 6e 73 74 61 6e 74 00                c constant.
      +
      +ntlm_generate_signing_key: value ( exported_session_key + sign_magic ): 
      +0000 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 ................
      +0010 73 65 73 73 69 6f 6e 20 6b 65 79 20 74 6f 20 73 session key to s
      +0020 65 72 76 65 72 2d 74 6f 2d 63 6c 69 65 6e 74 20 erver-to-client 
      +0030 73 69 67 6e 69 6e 67 20 6b 65 79 20 6d 61 67 69 signing key magi
      +0040 63 20 63 6f 6e 73 74 61 6e 74 00                c constant.
      +
      +ntlm_generate_signing_key: signing_key (MD5(value)): 
      +0000 b6 58 c5 98 7a 25 f8 6e d8 e5 6c e9 3e 3c c0 88 .X..z%.n..l.><..
      +
      +ntlm_generate_server_signing_key: ExportedSessionKey: 
      +0000 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 ................
      +
      +ntlm_generate_server_signing_key: server_sign_magic: ":session key to server-to-client signing key magic constant"
      +0000 73 65 73 73 69 6f 6e 20 6b 65 79 20 74 6f 20 73 session key to s
      +0010 65 72 76 65 72 2d 74 6f 2d 63 6c 69 65 6e 74 20 erver-to-client 
      +0020 73 69 67 6e 69 6e 67 20 6b 65 79 20 6d 61 67 69 signing key magi
      +0030 63 20 63 6f 6e 73 74 61 6e 74 00                c constant.
      +
      +ntlm_generate_server_signing_key: ServerSigningKey (ntlm_generate_signing_key(context->ExportedSessionKey, &sign_magic, context->ServerSigningKey))
      +0000 b6 58 c5 98 7a 25 f8 6e d8 e5 6c e9 3e 3c c0 88 .X..z%.n..l.><..
      +
      +ntlm_generate_signing_key: exported_session_key: 
      +0000 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 ................
      +
      +ntlm_generate_signing_key: sign_magic: 
      +0000 73 65 73 73 69 6f 6e 20 6b 65 79 20 74 6f 20 63 session key to c
      +0010 6c 69 65 6e 74 2d 74 6f 2d 73 65 72 76 65 72 20 lient-to-server 
      +0020 73 65 61 6c 69 6e 67 20 6b 65 79 20 6d 61 67 69 sealing key magi
      +0030 63 20 63 6f 6e 73 74 61 6e 74 00                c constant.
      +
      +ntlm_generate_signing_key: value ( exported_session_key + sign_magic ): 
      +0000 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 ................
      +0010 73 65 73 73 69 6f 6e 20 6b 65 79 20 74 6f 20 63 session key to c
      +0020 6c 69 65 6e 74 2d 74 6f 2d 73 65 72 76 65 72 20 lient-to-server 
      +0030 73 65 61 6c 69 6e 67 20 6b 65 79 20 6d 61 67 69 sealing key magi
      +0040 63 20 63 6f 6e 73 74 61 6e 74 00                c constant.
      +
      +ntlm_generate_signing_key: signing_key (MD5(value)): 
      +0000 58 19 44 c2 7a c6 34 45 e4 b8 2b 55 b9 0b 1f b5 X.D.z.4E..+U....
      +
      +ntlm_generate_client_sealing_key: ExportedSessionKey: 
      +0000 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 ................
      +
      +ntlm_generate_client_sealing_key: client_seal_magic: ":session key to client-to-server sealing key magic constant"
      +0000 73 65 73 73 69 6f 6e 20 6b 65 79 20 74 6f 20 63 session key to c
      +0010 6c 69 65 6e 74 2d 74 6f 2d 73 65 72 76 65 72 20 lient-to-server 
      +0020 73 65 61 6c 69 6e 67 20 6b 65 79 20 6d 61 67 69 sealing key magi
      +0030 63 20 63 6f 6e 73 74 61 6e 74 00                c constant.
      +
      +ntlm_generate_client_sealing_key: ClientSealingKey (ntlm_generate_signing_key(context->ExportedSessionKey, &seal_magic, context->ClientSealingKey))
      +0000 58 19 44 c2 7a c6 34 45 e4 b8 2b 55 b9 0b 1f b5 X.D.z.4E..+U....
      +
      +ntlm_generate_signing_key: exported_session_key: 
      +0000 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 ................
      +
      +ntlm_generate_signing_key: sign_magic: 
      +0000 73 65 73 73 69 6f 6e 20 6b 65 79 20 74 6f 20 73 session key to s
      +0010 65 72 76 65 72 2d 74 6f 2d 63 6c 69 65 6e 74 20 erver-to-client 
      +0020 73 65 61 6c 69 6e 67 20 6b 65 79 20 6d 61 67 69 sealing key magi
      +0030 63 20 63 6f 6e 73 74 61 6e 74 00                c constant.
      +
      +ntlm_generate_signing_key: value ( exported_session_key + sign_magic ): 
      +0000 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 ................
      +0010 73 65 73 73 69 6f 6e 20 6b 65 79 20 74 6f 20 73 session key to s
      +0020 65 72 76 65 72 2d 74 6f 2d 63 6c 69 65 6e 74 20 erver-to-client 
      +0030 73 65 61 6c 69 6e 67 20 6b 65 79 20 6d 61 67 69 sealing key magi
      +0040 63 20 63 6f 6e 73 74 61 6e 74 00                c constant.
      +
      +ntlm_generate_signing_key: signing_key (MD5(value)): 
      +0000 92 3a 73 5c 92 a7 04 34 be 9a a2 9f ed c1 e6 13 .:s\...4........
      +
      +ntlm_generate_server_sealing_key: ExportedSessionKey: 
      +0000 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 ................
      +
      +ntlm_generate_server_sealing_key: server_seal_magic: ":session key to server-to-client sealing key magic constant"
      +0000 73 65 73 73 69 6f 6e 20 6b 65 79 20 74 6f 20 73 session key to s
      +0010 65 72 76 65 72 2d 74 6f 2d 63 6c 69 65 6e 74 20 erver-to-client 
      +0020 73 65 61 6c 69 6e 67 20 6b 65 79 20 6d 61 67 69 sealing key magi
      +0030 63 20 63 6f 6e 73 74 61 6e 74 00                c constant.
      +
      +ntlm_generate_server_sealing_key: ServerSealingKey (ntlm_generate_signing_key(context->ExportedSessionKey, &seal_magic, context->ServerSealingKey))
      +0000 92 3a 73 5c 92 a7 04 34 be 9a a2 9f ed c1 e6 13 .:s\...4........
      +
      +ntlm_init_rc4_seal_states: SendSigningKey (ClientSigningKey)
      +0000 f6 ae 96 cb 05 e2 ab 54 f6 dd 59 f3 c9 d9 a0 43 .......T..Y....C
      +
      +ntlm_init_rc4_seal_states: RecvSigningKey (ServerSigningKey)
      +0000 b6 58 c5 98 7a 25 f8 6e d8 e5 6c e9 3e 3c c0 88 .X..z%.n..l.><..
      +
      +ntlm_init_rc4_seal_states: SendSealingKey (ServerSealingKey)
      +0000 92 3a 73 5c 92 a7 04 34 be 9a a2 9f ed c1 e6 13 .:s\...4........
      +
      +ntlm_init_rc4_seal_states: RecvSealingKey (ClientSealingKey)
      +0000 58 19 44 c2 7a c6 34 45 e4 b8 2b 55 b9 0b 1f b5 X.D.z.4E..+U....
      +
      +ntlm_init_rc4_seal_states: SendRc4Seal = 0xb6a28da0 (RC4_set_key(&context->SendRc4Seal, 16, context->ClientSealingKey))
      +ntlm_init_rc4_seal_states: RecvRc4Seal = 0xb6a291a8 (RC4_set_key(&context->RecvRc4Seal, 16, context->ServerSealingKey))
      +ntlm_read_ChallengeMessage: ClientChallenge
      +0000 01 02 03 04 05 06 07 08                         ........
      +
      +ntlm_read_ChallengeMessage: ServerChallenge
      +0000 4a 25 50 a5 11 9b d6 16                         J%P.....
      +
      +ntlm_read_ChallengeMessage: SessionBaseKey
      +0000 8e 0f dd 12 4c 3b 11 7f 22 b9 4b 59 52 bc a7 18 ....L;..".KYR...
      +
      +ntlm_read_ChallengeMessage: KeyExchangeKey
      +0000 8e 0f dd 12 4c 3b 11 7f 22 b9 4b 59 52 bc a7 18 ....L;..".KYR...
      +
      +ntlm_read_ChallengeMessage: ExportedSessionKey
      +0000 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 ................
      +
      +ntlm_read_ChallengeMessage: RandomSessionKey
      +0000 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 ................
      +
      +ntlm_read_ChallengeMessage: ClientSigningKey
      +0000 f6 ae 96 cb 05 e2 ab 54 f6 dd 59 f3 c9 d9 a0 43 .......T..Y....C
      +
      +ntlm_read_ChallengeMessage: ClientSealingKey
      +0000 58 19 44 c2 7a c6 34 45 e4 b8 2b 55 b9 0b 1f b5 X.D.z.4E..+U....
      +
      +ntlm_read_ChallengeMessage: ServerSigningKey
      +0000 b6 58 c5 98 7a 25 f8 6e d8 e5 6c e9 3e 3c c0 88 .X..z%.n..l.><..
      +
      +ntlm_read_ChallengeMessage: ServerSealingKey
      +0000 92 3a 73 5c 92 a7 04 34 be 9a a2 9f ed c1 e6 13 .:s\...4........
      +
      +ntlm_read_ChallengeMessage: Timestamp
      +0000 a0 e8 85 2c e4 c9 ce 01                         ...,....
      +
      +ntlm_compute_message_integrity_check: ExportedSessionKey
      +0000 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 ................
      +
      +ntlm_compute_message_integrity_check: NegotiateMessage
      +0000 4e 54 4c 4d 53 53 50 00 01 00 00 00 b7 82 08 e2 NTLMSSP.........
      +0010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
      +0020 06 01 b1 1d 00 00 00 0f                         ........
      +
      +ntlm_compute_message_integrity_check: ChallengeMessage
      +0000 4e 54 4c 4d 53 53 50 00 02 00 00 00 1e 00 1e 00 NTLMSSP.........
      +0010 38 00 00 00 35 82 8a e2 4a 25 50 a5 11 9b d6 16 8...5...J%P.....
      +0020 00 00 00 00 00 00 00 00 98 00 98 00 56 00 00 00 ............V...
      +0030 06 03 d7 24 00 00 00 0f 57 00 49 00 4e 00 2d 00 ...$....W.I.N.-.
      +0040 4c 00 4f 00 34 00 31 00 39 00 42 00 32 00 4c 00 L.O.4.1.9.B.2.L.
      +0050 53 00 52 00 30 00 02 00 1e 00 57 00 49 00 4e 00 S.R.0.....W.I.N.
      +0060 2d 00 4c 00 4f 00 34 00 31 00 39 00 42 00 32 00 -.L.O.4.1.9.B.2.
      +0070 4c 00 53 00 52 00 30 00 01 00 1e 00 57 00 49 00 L.S.R.0.....W.I.
      +0080 4e 00 2d 00 4c 00 4f 00 34 00 31 00 39 00 42 00 N.-.L.O.4.1.9.B.
      +0090 32 00 4c 00 53 00 52 00 30 00 04 00 1e 00 57 00 2.L.S.R.0.....W.
      +00a0 49 00 4e 00 2d 00 4c 00 4f 00 34 00 31 00 39 00 I.N.-.L.O.4.1.9.
      +00b0 42 00 32 00 4c 00 53 00 52 00 30 00 03 00 1e 00 B.2.L.S.R.0.....
      +00c0 57 00 49 00 4e 00 2d 00 4c 00 4f 00 34 00 31 00 W.I.N.-.L.O.4.1.
      +00d0 39 00 42 00 32 00 4c 00 53 00 52 00 30 00 07 00 9.B.2.L.S.R.0...
      +00e0 08 00 a0 e8 85 2c e4 c9 ce 01 00 00 00 00       .....,........
      +
      +ntlm_compute_message_integrity_check: AuthenticateMessage
      +0000 4e 54 4c 4d 53 53 50 00 03 00 00 00 18 00 18 00 NTLMSSP.........
      +0010 90 00 00 00 16 01 16 01 a8 00 00 00 12 00 12 00 ................
      +0020 58 00 00 00 1a 00 1a 00 6a 00 00 00 0c 00 0c 00 X.......j.......
      +0030 84 00 00 00 10 00 10 00 be 01 00 00 35 b2 88 e2 ............5...
      +0040 06 01 b1 1d 00 00 00 0f 00 00 00 00 00 00 00 00 ................
      +0050 00 00 00 00 00 00 00 00 77 00 6f 00 72 00 6b 00 ........w.o.r.k.
      +0060 67 00 72 00 6f 00 75 00 70 00 41 00 64 00 6d 00 g.r.o.u.p.A.d.m.
      +0070 69 00 6e 00 69 00 73 00 74 00 72 00 61 00 74 00 i.n.i.s.t.r.a.t.
      +0080 6f 00 72 00 61 00 70 00 6f 00 6c 00 6c 00 6f 00 o.r.a.p.o.l.l.o.
      +0090 7c c0 fd 08 c5 14 05 34 f3 12 9e 3e a3 09 bc c6 |......4...>....
      +00a0 01 02 03 04 05 06 07 08 19 4b eb ad da 24 d5 96 .........K...$..
      +00b0 85 2e 24 94 d6 4a b8 5e 01 01 00 00 00 00 00 00 ..$..J.^........
      +00c0 a0 e8 85 2c e4 c9 ce 01 01 02 03 04 05 06 07 08 ...,............
      +00d0 00 00 00 00 02 00 1e 00 57 00 49 00 4e 00 2d 00 ........W.I.N.-.
      +00e0 4c 00 4f 00 34 00 31 00 39 00 42 00 32 00 4c 00 L.O.4.1.9.B.2.L.
      +00f0 53 00 52 00 30 00 01 00 1e 00 57 00 49 00 4e 00 S.R.0.....W.I.N.
      +0100 2d 00 4c 00 4f 00 34 00 31 00 39 00 42 00 32 00 -.L.O.4.1.9.B.2.
      +0110 4c 00 53 00 52 00 30 00 04 00 1e 00 57 00 49 00 L.S.R.0.....W.I.
      +0120 4e 00 2d 00 4c 00 4f 00 34 00 31 00 39 00 42 00 N.-.L.O.4.1.9.B.
      +0130 32 00 4c 00 53 00 52 00 30 00 03 00 1e 00 57 00 2.L.S.R.0.....W.
      +0140 49 00 4e 00 2d 00 4c 00 4f 00 34 00 31 00 39 00 I.N.-.L.O.4.1.9.
      +0150 42 00 32 00 4c 00 53 00 52 00 30 00 07 00 08 00 B.2.L.S.R.0.....
      +0160 a0 e8 85 2c e4 c9 ce 01 06 00 04 00 02 00 00 00 ...,............
      +0170 0a 00 10 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
      +0180 00 00 00 00 09 00 26 00 54 00 45 00 52 00 4d 00 ......&.T.E.R.M.
      +0190 53 00 52 00 56 00 2f 00 31 00 39 00 32 00 2e 00 S.R.V./.1.9.2...
      +01a0 31 00 36 00 38 00 2e 00 31 00 2e 00 33 00 00 00 1.6.8...1...3...
      +01b0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 e4 e9 ................
      +01c0 c2 ad 41 02 2f 3c f9 4c 72 84 c5 2a 7c 6f       ..A./<.Lr..*|o
      +
      +ntlm_compute_message_integrity_check: MessageIntegrityCheck (HMAC_MD5(ExportedSessionKey + NegotiateMessage + ChallengeMessage + AuthenticateMessage))
      +0000 d9 e9 bc 9b 6f a5 f9 c8 70 16 10 20 f8 f1 61 42 ....o...p.. ..aB
      +
      +credssp_encrypt_public_key_echo: Server public key (length = 270):
      +recv_seq_num: 0
      +Public key before encryption:
      +0000 30 82 01 0a 02 82 01 01 00 a8 56 65 d3 ce 8a 54 0.........Ve...T
      +0010 4d 9d b0 84 31 19 71 7f dd 42 fb 2a 7a 72 13 a1 M...1.q..B.*zr..
      +0020 b9 72 bb d3 08 ad 7d 6c 15 65 03 d1 c4 54 c5 33 .r....}l.e...T.3
      +0030 6b 7d 69 89 5e fe e0 01 c0 7e 9b cb 5d 65 36 cd k}i.^....~..]e6.
      +0040 77 5d f3 7a 5b 29 44 72 d5 38 e2 cf b1 c7 78 9b w].z[)Dr.8....x.
      +0050 58 b9 17 7c b7 d6 c7 c7 bf 90 4e 7c 39 93 cb 2e X..|......N|9...
      +0060 e0 c2 33 2d a5 7e e0 7b b6 f9 91 32 b7 d4 85 b7 ..3-.~.{...2....
      +0070 35 2d 2b 00 6d f8 ea 8c 97 5f 51 1d 68 04 3c 79 5-+.m...._Q.h.SendRc4Seal, length, data, data_buffer->pvBuffer))
      +0000 15 f7 f2 54 da a9 e5 ad 85 04 67 4d 0b cb f9 b1 ...T......gM....
      +0010 f8 02 8a 77 c2 63 ab d5 74 23 9f 9d 5d 1f d3 b3 ...w.c..t#..]...
      +0020 a0 ac 16 8a 4b 08 f5 47 70 58 10 b4 e7 87 b3 4b ....K..GpX.....K
      +0030 c9 a2 d5 d1 ca 0f d4 e3 8d 76 5a 60 28 f8 06 5d .........vZ`(..]
      +0040 e4 7e 21 c8 bb ac e5 79 85 30 9b 88 13 2f 8f fc .~!....y.0.../..
      +0050 04 52 fe 87 94 cf cb 49 4a da 6f dd ee 57 a5 e4 .R.....IJ.o..W..
      +0060 4d 0e 5c 3d 0b 63 1f f6 3d 1b ae 5a f6 42 2a 46 M.\=.c..=..Z.B*F
      +0070 fa 42 71 67 46 02 71 ea 51 98 f7 d4 43 bf 8e e8 .BqgF.q.Q...C...
      +0080 3c c8 fa 79 9d 8c fc c2 42 c9 bb d0 ab 81 c4 53 <..y....B......S
      +0090 fd 41 da ab 0f 25 79 5f bd a3 8c d3 f5 1b ab 20 .A...%y_....... 
      +00a0 d1 f4 d8 81 9c 18 4a a4 77 ee e1 51 ee 2a c1 94 ......J.w..Q.*..
      +00b0 37 c5 06 7a 3f 0f 25 5b 4e 6a dc 0b 62 6f 12 83 7..z?.%[Nj..bo..
      +00c0 03 ae 4e ce 2b 6e d4 d5 23 27 f6 a6 38 67 ec 95 ..N.+n..#'..8g..
      +00d0 82 c6 ba d4 f6 e6 22 7d b9 e4 81 97 24 ff 40 b2 ......"}....$.@.
      +00e0 42 3c 11 24 d0 3a 96 d9 c1 13 d6 62 45 21 60 5b B<.$.:.....bE!`[
      +00f0 7b 2b 62 44 f7 40 93 29 5b 44 b7 da 9c a6 a9 3b {+bD.@.)[D.....;
      +0100 e1 3b 9d 31 f2 21 53 0f b3 70 55 84 2c b4       .;.1.!S..pU.,.
      +
      +ntlm_EncryptMessage: Checksum ( RC4(&context->SendRc4Seal, 8, digest, checksum), first 8 bytes of digest only!):
      +0000 72 76 1e 57 49 b5 0f ad                         rv.WI...
      +ntlm_EncryptMessage: signature (version + checksum + seq_num)
      +0000 01 00 00 00 72 76 1e 57 49 b5 0f ad 00 00 00 00 ....rv.WI.......
      +
      +ntlm_EncryptMessage: SendSeqNum (after increase): 1, SeqNo: 0.
      +credssp_encrypt_public_key_echo: Server public key (length = 270):
      +recv_seq_num: 0
      +Public key after encryption:
      +0000 15 f7 f2 54 da a9 e5 ad 85 04 67 4d 0b cb f9 b1 ...T......gM....
      +0010 f8 02 8a 77 c2 63 ab d5 74 23 9f 9d 5d 1f d3 b3 ...w.c..t#..]...
      +0020 a0 ac 16 8a 4b 08 f5 47 70 58 10 b4 e7 87 b3 4b ....K..GpX.....K
      +0030 c9 a2 d5 d1 ca 0f d4 e3 8d 76 5a 60 28 f8 06 5d .........vZ`(..]
      +0040 e4 7e 21 c8 bb ac e5 79 85 30 9b 88 13 2f 8f fc .~!....y.0.../..
      +0050 04 52 fe 87 94 cf cb 49 4a da 6f dd ee 57 a5 e4 .R.....IJ.o..W..
      +0060 4d 0e 5c 3d 0b 63 1f f6 3d 1b ae 5a f6 42 2a 46 M.\=.c..=..Z.B*F
      +0070 fa 42 71 67 46 02 71 ea 51 98 f7 d4 43 bf 8e e8 .BqgF.q.Q...C...
      +0080 3c c8 fa 79 9d 8c fc c2 42 c9 bb d0 ab 81 c4 53 <..y....B......S
      +0090 fd 41 da ab 0f 25 79 5f bd a3 8c d3 f5 1b ab 20 .A...%y_....... 
      +00a0 d1 f4 d8 81 9c 18 4a a4 77 ee e1 51 ee 2a c1 94 ......J.w..Q.*..
      +00b0 37 c5 06 7a 3f 0f 25 5b 4e 6a dc 0b 62 6f 12 83 7..z?.%[Nj..bo..
      +00c0 03 ae 4e ce 2b 6e d4 d5 23 27 f6 a6 38 67 ec 95 ..N.+n..#'..8g..
      +00d0 82 c6 ba d4 f6 e6 22 7d b9 e4 81 97 24 ff 40 b2 ......"}....$.@.
      +00e0 42 3c 11 24 d0 3a 96 d9 c1 13 d6 62 45 21 60 5b B<.$.:.....bE!`[
      +00f0 7b 2b 62 44 f7 40 93 29 5b 44 b7 da 9c a6 a9 3b {+bD.@.)[D.....;
      +0100 e1 3b 9d 31 f2 21 53 0f b3 70 55 84 2c b4       .;.1.!S..pU.,.
      +credssp_decrypt_public_key_echo: Server public key (length = 270):
      +recv_seq_num: 0
      +Public key before decryption:
      +0000 03 12 dd ea 47 b3 ff e1 66 08 f6 6b a0 62 42 67 ....G...f..k.bBg
      +0010 bf 3d 59 60 ef 52 b0 26 95 ed 84 48 44 bb 8d 65 .=Y`.R.&...HD..e
      +0020 cf e4 8e 6f 69 ae ed 44 bb 49 1d 2a 40 29 2b 13 ...oi..D.I.*@)+.
      +0030 42 1c eb b1 6c 8a 3b 80 d1 70 fd dd 79 e4 93 0b B...l.;..p..y...
      +0040 47 bd 3a 7e 31 66 4b 65 8d 5c 2a cd c2 09 7a 3b G.:~1fKe.\*...z;
      +0050 b2 fd 09 52 09 47 05 a4 6f 32 d1 76 b2 d4 59 e0 ...R.G..o2.v..Y.
      +0060 85 f1 36 7d 76 50 21 0e 20 22 83 1a 08 c0 85 5d ..6}vP!. ".....]
      +0070 4f 5c 77 68 32 95 a9 a2 59 69 ea 19 34 08 ed 76 O\wh2...Yi..4..v
      +0080 a3 58 37 f2 0a 0c ba 4d bb 6f 82 94 d3 87 de c9 .X7....M.o......
      +0090 8f ef 34 2d 8f d0 0c 91 59 fd ea 6b cb bd a2 20 ..4-....Y..k... 
      +00a0 ed b9 76 d3 64 1b b3 3b f5 9b 61 d7 ab 26 9b 0d ..v.d..;..a..&..
      +00b0 a0 ea bf ad 2c ad 63 65 c6 70 c4 e5 8d 40 aa 08 ....,.ce.p...@..
      +00c0 45 66 e2 4d c9 46 00 33 43 e0 ba d6 80 29 21 5e Ef.M.F.3C....)!^
      +00d0 d1 9a bc 44 fa 4d 46 f9 25 80 40 b5 27 dd c5 02 ...D.MF.%.@.'...
      +00e0 f8 a4 9a cb cf 3f ef c7 cd 71 45 a5 35 b1 21 14 .....?...qE.5.!.
      +00f0 39 57 f8 0a 24 98 ea 15 e1 e3 cb 9d f2 4e ef 89 9W..$........N..
      +0100 97 c0 b2 96 9a 1e ad d0 9a 99 62 9f 13 2e       ..........b...
      +credssp_decrypt_public_key_echo: Signature for decryption:
      +0000 01 00 00 00 25 f8 2d 1e 4e 6a ec 4f 00 00 00 00 ....%.-.Nj.O....
      +ntlm_DecryptMessage: Data Buffer before decryption (length = 270)
      +0000 03 12 dd ea 47 b3 ff e1 66 08 f6 6b a0 62 42 67 ....G...f..k.bBg
      +0010 bf 3d 59 60 ef 52 b0 26 95 ed 84 48 44 bb 8d 65 .=Y`.R.&...HD..e
      +0020 cf e4 8e 6f 69 ae ed 44 bb 49 1d 2a 40 29 2b 13 ...oi..D.I.*@)+.
      +0030 42 1c eb b1 6c 8a 3b 80 d1 70 fd dd 79 e4 93 0b B...l.;..p..y...
      +0040 47 bd 3a 7e 31 66 4b 65 8d 5c 2a cd c2 09 7a 3b G.:~1fKe.\*...z;
      +0050 b2 fd 09 52 09 47 05 a4 6f 32 d1 76 b2 d4 59 e0 ...R.G..o2.v..Y.
      +0060 85 f1 36 7d 76 50 21 0e 20 22 83 1a 08 c0 85 5d ..6}vP!. ".....]
      +0070 4f 5c 77 68 32 95 a9 a2 59 69 ea 19 34 08 ed 76 O\wh2...Yi..4..v
      +0080 a3 58 37 f2 0a 0c ba 4d bb 6f 82 94 d3 87 de c9 .X7....M.o......
      +0090 8f ef 34 2d 8f d0 0c 91 59 fd ea 6b cb bd a2 20 ..4-....Y..k... 
      +00a0 ed b9 76 d3 64 1b b3 3b f5 9b 61 d7 ab 26 9b 0d ..v.d..;..a..&..
      +00b0 a0 ea bf ad 2c ad 63 65 c6 70 c4 e5 8d 40 aa 08 ....,.ce.p...@..
      +00c0 45 66 e2 4d c9 46 00 33 43 e0 ba d6 80 29 21 5e Ef.M.F.3C....)!^
      +00d0 d1 9a bc 44 fa 4d 46 f9 25 80 40 b5 27 dd c5 02 ...D.MF.%.@.'...
      +00e0 f8 a4 9a cb cf 3f ef c7 cd 71 45 a5 35 b1 21 14 .....?...qE.5.!.
      +00f0 39 57 f8 0a 24 98 ea 15 e1 e3 cb 9d f2 4e ef 89 9W..$........N..
      +0100 97 c0 b2 96 9a 1e ad d0 9a 99 62 9f 13 2e       ..........b...
      +
      +ntlm_DecryptMessage: RecvRc4Seal = 0xe
      +ntlm_DecryptMessage: Data Buffer after decryption (RC4(&context->RecvRc4Seal, length, data, data_buffer->pvBuffer))
      +0000 31 82 01 0a 02 82 01 01 00 a8 56 65 d3 ce 8a 54 1.........Ve...T
      +0010 4d 9d b0 84 31 19 71 7f dd 42 fb 2a 7a 72 13 a1 M...1.q..B.*zr..
      +0020 b9 72 bb d3 08 ad 7d 6c 15 65 03 d1 c4 54 c5 33 .r....}l.e...T.3
      +0030 6b 7d 69 89 5e fe e0 01 c0 7e 9b cb 5d 65 36 cd k}i.^....~..]e6.
      +0040 77 5d f3 7a 5b 29 44 72 d5 38 e2 cf b1 c7 78 9b w].z[)Dr.8....x.
      +0050 58 b9 17 7c b7 d6 c7 c7 bf 90 4e 7c 39 93 cb 2e X..|......N|9...
      +0060 e0 c2 33 2d a5 7e e0 7b b6 f9 91 32 b7 d4 85 b7 ..3-.~.{...2....
      +0070 35 2d 2b 00 6d f8 ea 8c 97 5f 51 1d 68 04 3c 79 5-+.m...._Q.h.<..
      +
      +ntlm_DecryptMessage: digest (HMAC_MD5(RecvSigningKey, seq_num + data)), seq_num: 0
      +0000 33 77 62 77 99 a9 14 40 1d 76 17 98 21 65 36 05 3wbw...@.v..!e6.
      +
      +ntlm_DecryptMessage: Checksum (RC4(&context->RecvRc4Seal, 8, digest, checksum), first 8 bytes of digest only!):
      +0000 25 f8 2d 1e 4e 6a ec 4f                         %.-.Nj.O
      +ntlm_DecryptMessage: Expected Signature (version + checksum + seq_num):
      +0000 01 00 00 00 25 f8 2d 1e 4e 6a ec 4f 00 00 00 00 ....%.-.Nj.O....
      +ntlm_DecryptMessage: RecvSeqNum (after increase): 1, SeqNo: 0.
      +credssp_decrypt_public_key_echo: Server public key (length = 270):
      +recv_seq_num: 1
      +Public key after decryption:
      +0000 30 82 01 0a 02 82 01 01 00 a8 56 65 d3 ce 8a 54 0.........Ve...T
      +0010 4d 9d b0 84 31 19 71 7f dd 42 fb 2a 7a 72 13 a1 M...1.q..B.*zr..
      +0020 b9 72 bb d3 08 ad 7d 6c 15 65 03 d1 c4 54 c5 33 .r....}l.e...T.3
      +0030 6b 7d 69 89 5e fe e0 01 c0 7e 9b cb 5d 65 36 cd k}i.^....~..]e6.
      +0040 77 5d f3 7a 5b 29 44 72 d5 38 e2 cf b1 c7 78 9b w].z[)Dr.8....x.
      +0050 58 b9 17 7c b7 d6 c7 c7 bf 90 4e 7c 39 93 cb 2e X..|......N|9...
      +0060 e0 c2 33 2d a5 7e e0 7b b6 f9 91 32 b7 d4 85 b7 ..3-.~.{...2....
      +0070 35 2d 2b 00 6d f8 ea 8c 97 5f 51 1d 68 04 3c 79 5-+.m...._Q.h.SendRc4Seal, length, data, data_buffer->pvBuffer))
      +0000 5a 26 69 b7 70 4b 41 55 82 43 a2 3a 72 6a e0 69 Z&i.pKAU.C.:rj.i
      +0010 9b 53 66 b6 70 75 c4 80 4f 61 e6 85 20 7e 3a 1b .Sf.pu..Oa.. ~:.
      +0020 a9 6a da 69 0b a5 4e 16 d9 da 71 5e ce e4 60 89 .j.i..N...q^..`.
      +0030 98 e6 30 59 d0 43 38 55 4a 97 e4 20 83 cd db 6b ..0Y.C8UJ.. ...k
      +0040 2b ca ac 9d 99 e6 2b ea 47 5f c1 4c 54 67 d1 75 +.....+.G_.LTg.u
      +0050 2c f7 d6 d6 04 8b 28 99 e9                      ,.....(..
      +
      +ntlm_EncryptMessage: Checksum ( RC4(&context->SendRc4Seal, 8, digest, checksum), first 8 bytes of digest only!):
      +0000 7a 7e b7 6c 49 3e 6b 7a                         z~.lI>kz
      +ntlm_EncryptMessage: signature (version + checksum + seq_num)
      +0000 01 00 00 00 7a 7e b7 6c 49 3e 6b 7a 01 00 00 00 ....z~.lI>kz....
      +
      +ntlm_EncryptMessage: SendSeqNum (after increase): 2, SeqNo: 1.
      +Unable to detect time zone
      +Closed from X11
      diff --git a/services/console-proxy-rdp/rdpconsole/src/test/doc/rdp.pfx b/services/console-proxy-rdp/rdpconsole/src/test/doc/rdp.pfx
      new file mode 100755
      index 00000000000..311ca43b71a
      Binary files /dev/null and b/services/console-proxy-rdp/rdpconsole/src/test/doc/rdp.pfx differ
      diff --git a/services/console-proxy-rdp/rdpconsole/src/test/java/rdpclient/MockServerTest.java b/services/console-proxy-rdp/rdpconsole/src/test/java/rdpclient/MockServerTest.java
      old mode 100644
      new mode 100755
      index 283beac3456..a40cdb8ed79
      --- a/services/console-proxy-rdp/rdpconsole/src/test/java/rdpclient/MockServerTest.java
      +++ b/services/console-proxy-rdp/rdpconsole/src/test/java/rdpclient/MockServerTest.java
      @@ -16,9 +16,9 @@
       // under the License.
       package rdpclient;
       
      -import static rdpclient.MockServer.Packet.PacketType.CLIENT;
      -import static rdpclient.MockServer.Packet.PacketType.SERVER;
      -import static rdpclient.MockServer.Packet.PacketType.UPGRADE_TO_SSL;
      +import static streamer.debug.MockServer.Packet.PacketType.CLIENT;
      +import static streamer.debug.MockServer.Packet.PacketType.SERVER;
      +import static streamer.debug.MockServer.Packet.PacketType.UPGRADE_TO_SSL;
       
       import java.io.InputStream;
       import java.io.OutputStream;
      @@ -30,7 +30,8 @@ import javax.net.ssl.SSLSocket;
       import javax.net.ssl.SSLSocketFactory;
       
       import junit.framework.TestCase;
      -import rdpclient.MockServer.Packet;
      +import streamer.debug.MockServer;
      +import streamer.debug.MockServer.Packet;
       
       public class MockServerTest extends TestCase {
       
      diff --git a/services/console-proxy/server/pom.xml b/services/console-proxy/server/pom.xml
      index bc780a70fb5..5d0b3bc9565 100644
      --- a/services/console-proxy/server/pom.xml
      +++ b/services/console-proxy/server/pom.xml
      @@ -44,6 +44,11 @@
             cloud-utils
             ${project.version}
           
      +    
      +      rdpclient
      +      cloudstack-service-console-proxy-rdpclient
      +      ${project.version}
      +    
         
         
           
      diff --git a/services/console-proxy/server/src/com/cloud/consoleproxy/ConsoleProxy.java b/services/console-proxy/server/src/com/cloud/consoleproxy/ConsoleProxy.java
      index e52a751c831..02fda6424be 100644
      --- a/services/console-proxy/server/src/com/cloud/consoleproxy/ConsoleProxy.java
      +++ b/services/console-proxy/server/src/com/cloud/consoleproxy/ConsoleProxy.java
      @@ -36,11 +36,12 @@ import java.util.concurrent.Executor;
       import org.apache.commons.codec.binary.Base64;
       import org.apache.log4j.xml.DOMConfigurator;
       
      -import com.cloud.consoleproxy.util.Logger;
      -import com.cloud.utils.PropertiesUtil;
       import com.google.gson.Gson;
       import com.sun.net.httpserver.HttpServer;
       
      +import com.cloud.consoleproxy.util.Logger;
      +import com.cloud.utils.PropertiesUtil;
      +
       /**
        *
        * ConsoleProxy, singleton class that manages overall activities in console proxy process. To make legacy code work, we still
      @@ -51,7 +52,7 @@ public class ConsoleProxy {
           public static final int KEYBOARD_RAW = 0;
           public static final int KEYBOARD_COOKED = 1;
       
      -    public static int VIEWER_LINGER_SECONDS = 180;
      +    public static final int VIEWER_LINGER_SECONDS = 180;
       
           public static Object context;
       
      @@ -390,7 +391,7 @@ public class ConsoleProxy {
                   } finally {
                       try {
                           confs.close();
      -                }  catch (IOException ioex) {
      +                } catch (IOException ioex) {
                           s_logger.error(ioex.toString(), ioex);
                       }
                   }
      @@ -406,7 +407,7 @@ public class ConsoleProxy {
               synchronized (connectionMap) {
                   viewer = connectionMap.get(clientKey);
                   if (viewer == null) {
      -                viewer = new ConsoleProxyVncClient();
      +                viewer = getClient(param);
                       viewer.initClient(param);
                       connectionMap.put(clientKey, viewer);
                       s_logger.info("Added viewer object " + viewer);
      @@ -441,7 +442,7 @@ public class ConsoleProxy {
                   ConsoleProxyClient viewer = connectionMap.get(clientKey);
                   if (viewer == null) {
                       authenticationExternally(param);
      -                viewer = new ConsoleProxyVncClient();
      +                viewer = getClient(param);
                       viewer.initClient(param);
       
                       connectionMap.put(clientKey, viewer);
      @@ -478,6 +479,14 @@ public class ConsoleProxy {
               }
           }
       
      +    private static ConsoleProxyClient getClient(ConsoleProxyClientParam param) {
      +        if (param.getHypervHost() != null) {
      +            return new ConsoleProxyRdpClient();
      +        } else {
      +            return new ConsoleProxyVncClient();
      +        }
      +    }
      +
           public static void removeViewer(ConsoleProxyClient viewer) {
               synchronized (connectionMap) {
                   for (Map.Entry entry : connectionMap.entrySet()) {
      diff --git a/services/console-proxy/server/src/com/cloud/consoleproxy/ConsoleProxyAjaxHandler.java b/services/console-proxy/server/src/com/cloud/consoleproxy/ConsoleProxyAjaxHandler.java
      index 56e2ea997fa..fa0bd06c09e 100644
      --- a/services/console-proxy/server/src/com/cloud/consoleproxy/ConsoleProxyAjaxHandler.java
      +++ b/services/console-proxy/server/src/com/cloud/consoleproxy/ConsoleProxyAjaxHandler.java
      @@ -79,6 +79,10 @@ public class ConsoleProxyAjaxHandler implements HttpHandler {
               String eventStr = queryMap.get("event");
               String console_url = queryMap.get("consoleurl");
               String console_host_session = queryMap.get("sessionref");
      +        String vm_locale = queryMap.get("locale");
      +        String hypervHost = queryMap.get("hypervHost");
      +        String username = queryMap.get("username");
      +        String password = queryMap.get("password");
       
               if (tag == null)
                   tag = "";
      @@ -126,6 +130,10 @@ public class ConsoleProxyAjaxHandler implements HttpHandler {
                   param.setTicket(ticket);
                   param.setClientTunnelUrl(console_url);
                   param.setClientTunnelSession(console_host_session);
      +            param.setLocale(vm_locale);
      +            param.setHypervHost(hypervHost);
      +            param.setUsername(username);
      +            param.setPassword(password);
       
                   viewer = ConsoleProxy.getAjaxVncViewer(param, ajaxSessionIdStr);
               } catch (Exception e) {
      diff --git a/services/console-proxy/server/src/com/cloud/consoleproxy/ConsoleProxyClientBase.java b/services/console-proxy/server/src/com/cloud/consoleproxy/ConsoleProxyClientBase.java
      index daef040c9b1..eb38007de9a 100644
      --- a/services/console-proxy/server/src/com/cloud/consoleproxy/ConsoleProxyClientBase.java
      +++ b/services/console-proxy/server/src/com/cloud/consoleproxy/ConsoleProxyClientBase.java
      @@ -287,11 +287,11 @@ public abstract class ConsoleProxyClientBase implements ConsoleProxyClient, Cons
               }
       
               return getAjaxViewerPageContent(sbTileSequence.toString(), imgUrl, updateUrl, width, height, tileWidth, tileHeight, title,
      -            ConsoleProxy.keyboardType == ConsoleProxy.KEYBOARD_RAW, languages, guest);
      +            ConsoleProxy.keyboardType == ConsoleProxy.KEYBOARD_RAW, languages, guest, this.clientParam.getLocale());
           }
       
           private String getAjaxViewerPageContent(String tileSequence, String imgUrl, String updateUrl, int width, int height, int tileWidth, int tileHeight, String title,
      -        boolean rawKeyboard, List languages, String guest) {
      +        boolean rawKeyboard, List languages, String guest, String locale) {
       
               StringBuffer sbLanguages = new StringBuffer("");
               if (languages != null) {
      @@ -323,7 +323,7 @@ public abstract class ConsoleProxyClientBase implements ConsoleProxyClient, Cons
                       "
    • Japanese keyboard
    • ", "
    ", "
  • ", "
", "", "", "
", " - - - + + + + + @@ -52,52 +54,25 @@ under the License. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + - - - - - - + diff --git a/ui/tests/test.cloudBrowser.js b/ui/tests/test.cloudBrowser.js deleted file mode 100644 index 4a27821285b..00000000000 --- a/ui/tests/test.cloudBrowser.js +++ /dev/null @@ -1,116 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -(function($) { - var $browser, $breadcrumbs, $browserContainer; - - module('Browser', { - setup: function() { - $.fx.off = true; - $browser = $('
').addClass('browser-test').appendTo('#qunit-fixture'); - $breadcrumbs = $('
').attr('id', 'breadcrumbs').appendTo($browser); - $browserContainer = $('
').addClass('container').appendTo($browser); - ok($browserContainer.cloudBrowser(), 'Browser initialized'); - equal($breadcrumbs.find('ul').size(), 1, 'Breadcrumbs initialized'); - } - }); - - // Browser tests - test('Add panel', function() { - ok($browserContainer.cloudBrowser('addPanel', { title: 'testPanel123' }), 'Add panel'); - equal($browser.find('.panel').size(), 1, 'Browser has 1 panel'); - equal($breadcrumbs.find('ul li').size(), 1, 'Browser has 1 breadcrumb'); - equal($breadcrumbs.find('ul li:first span').html(), 'testPanel123', 'Panel has correct title'); - }); - - test('Add a second panel', function() { - ok($browserContainer.cloudBrowser('addPanel', { title: 'testPanel123' }), 'Add first panel'); - ok($browserContainer.cloudBrowser('addPanel', { title: 'testPanel456' }), 'Add second panel'); - equal($browser.find('.panel').size(), 2, 'Browser has 2 panels'); - equal($breadcrumbs.find('ul li').size(), 2, 'Browser has 2 breadcrumbs'); - equal($breadcrumbs.find('ul li:last span').html(), 'testPanel456', 'New panel has correct title'); - equal($breadcrumbs.find('ul li:first span').html(), 'testPanel123', 'First panel still has correct title'); - }); - - test('Add maximized panel', function() { - var $maximizedPanel, $normalPanel; - - ok($browserContainer.cloudBrowser('addPanel', { title: 'testPanel123' }, 'Add first panel')); - ok($browserContainer.cloudBrowser('addPanel', { title: 'testPanel456' }, 'Add normal-sized-panel')); - ok($browserContainer.cloudBrowser('addPanel', { title: 'testPanel789', maximizeIfSelected: true }), 'Add maximized panel'); - - $maximizedPanel = $browserContainer.find('.panel:last'); - $normalPanel = $browserContainer.find('.panel:first').next(); - - ok($maximizedPanel.hasClass('always-maximized'), 'Maximized panel has maximized class'); - ok(!$normalPanel.hasClass('always-maximized'), 'Normal panel has maximized class'); - equal($maximizedPanel.width(), $browserContainer.width(), 'Maximized panel covers full width of browser container'); - notEqual($normalPanel.width(), $browserContainer.width(), 'Normal panel doesn\'t have maximized appearance'); - }); - - test('Select panel', function() { - ok($browserContainer.cloudBrowser('addPanel', { title: 'testPanel123' }), 'Add first panel'); - ok($browserContainer.cloudBrowser('addPanel', { title: 'testPanel456' }), 'Add second panel'); - ok($browserContainer.cloudBrowser('addPanel', { title: 'testPanel789' }), 'Add third panel'); - - stop(); - $browserContainer.cloudBrowser('selectPanel', { - panel: $browser.find('.panel:first').next(), - complete: function() { - start(); - ok(true, 'Select second panel'); - } - }); - - equal($browser.find('.panel').size(), 2, 'Browser has 2 panels'); - equal($breadcrumbs.find('ul li:first span').html(), 'testPanel123', 'First panel still has correct title'); - equal($breadcrumbs.find('ul li:last span').html(), 'testPanel456', 'Second panel still has correct title'); - equal($breadcrumbs.find('ul li').size(), 2, 'Browser has 2 breadcrumbs'); - - stop(); - $browserContainer.cloudBrowser('selectPanel', { - panel: $browser.find('.panel:first'), - complete: function() { - start(); - ok(true, 'Select first panel'); - } - }); - - equal($browser.find('.panel').size(), 1, 'Browser has 1 panel'); - equal($breadcrumbs.find('ul li:first span').html(), 'testPanel123', 'First panel still has correct title'); - equal($breadcrumbs.find('ul li').size(), 1, 'Browser has 1 breadcrumb'); - }); - - test('Remove all panels', function() { - ok($browserContainer.cloudBrowser('addPanel', { title: 'testPanel123' }), 'Add first panel'); - ok($browserContainer.cloudBrowser('addPanel', { title: 'testPanel456' }), 'Add second panel'); - ok($browserContainer.cloudBrowser('addPanel', { title: 'testPanel789' }), 'Add third panel'); - equal($browserContainer.find('.panel').size(), 3, 'Correct # of panels'); - ok($browserContainer.cloudBrowser('removeAllPanels'), 'Remove all panels'); - equal($browserContainer.find('.panel').size(), 0, 'All panels removed'); - ok($browserContainer.cloudBrowser('addPanel', { title: 'testPanel123' }), 'Add 1 panel'); - equal($browserContainer.find('.panel').size(), 1, 'Correct # of panels'); - }); - - test('Maximize panel', function() { - ok($browserContainer.cloudBrowser('addPanel', { title: 'testPanel123' }), 'Add first panel'); - ok($browserContainer.cloudBrowser('addPanel', { title: 'testPanel456' }), 'Add second panel'); - equal($browserContainer.find('.panel').size(), 2, 'Correct # of panels'); - ok($browserContainer.cloudBrowser('toggleMaximizePanel', { panel: $browserContainer.find('.panel:first')}), 'Maximize first panel'); - ok($browserContainer.find('.panel:first').hasClass('maximized'), 'First panel has maximized style'); - ok(!$browserContainer.find('.panel:last').hasClass('maximized'), 'Last panel has correct style'); - }); -}(jQuery)); diff --git a/ui/tests/test.core.js b/ui/tests/test.core.js deleted file mode 100644 index 8ccab7d9e20..00000000000 --- a/ui/tests/test.core.js +++ /dev/null @@ -1,79 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -(function($) { - var $cloudStack, cloudStack; - - module('Core widget', { - setup: function() { - cloudStack = { - sections: { - home: { - show: function() { return $('
').addClass('test123'); } - }, - sectionA: {}, - sectionB: {}, - sectionC: {} - }, - - home: 'home' - }; - - $cloudStack = $('
'); - ok($cloudStack.cloudStack(cloudStack), 'Basic widget initialized'); - } - }); - - test('Container/wrappers', function() { - equal($cloudStack.find('[cloudStack-container]').size(), 1, 'Main sub-container present'); - equal($cloudStack.find('#main-area').size(), 1, 'Main area present'); - }); - - test('Header', function() { - var $header = $cloudStack.find('#header'); - var $userOptions = $cloudStack.find('#user-options'); - var $notifications = $header.find('.button.notifications'); - var $notificationTotal = $notifications.find('.total span'); - var $viewSwitcher = $header.find('.button.view-switcher'); - - equal($header.size(), 1, 'Header present'); - equal($userOptions.size(), 1, 'User options present'); - equal($userOptions.find('a').size(), 2, 'User options has correct # of options'); - equal($notifications.size(), 1, 'Notifications present'); - equal($notificationTotal.html(), '0', 'Notifications initialized properly'); - equal($viewSwitcher.size(), 1, 'View switcher present'); - }); - - test('Navigation', function() { - var $navigation = $cloudStack.find('#navigation'); - - equal($navigation.size(), 1, 'Navigation present'); - equal($navigation.find('li').size(), 4, 'Navigation has correct # of nav items'); - }); - - test('Browser / page generation', function() { - var $browser = $cloudStack.find('#browser'); - var $browserContainer = $browser.find('.container'); - var $homePage = $browserContainer.find('.panel div.test123'); - var $breadcrumbs = $browser.find('#breadcrumbs li'); - var $homeBreadcrumb = $browser.find('#breadcrumbs .home'); - - equal($browser.size(), 1, 'Browser intialized'); - equal($homePage.size(), 1, 'Home page is visible'); - equal($breadcrumbs.size(), 0, 'No initial breadcrumbs'); - equal($homeBreadcrumb.size(), 1, 'Home breadcrumb active'); - }); -}(jQuery)); diff --git a/ui/tests/test.detailView.js b/ui/tests/test.detailView.js deleted file mode 100644 index 6098300811e..00000000000 --- a/ui/tests/test.detailView.js +++ /dev/null @@ -1,799 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -(function($) { - module('Detail view', { - setup: function() { - cloudStack.dialog.__confirm = cloudStack.dialog.confirm; - cloudStack.ui.notifications.__add = cloudStack.ui.notifications.add; - $.fn.__cloudBrowser = $.fn.cloudBrowser; - $.fn.__listView = $.fn.listView; - $.fn.__dataTable = $.fn.dataTable; - $.fn.__is = $.fn.is; - - $.fn.is = function(args) { - if (args == ':visible') - return true; // No test elems will ever be shown, so just pretend they are visible - - return true; - }; - }, - - teardown: function() { - cloudStack.dialog.confirm = cloudStack.dialog.__confirm; - cloudStack.ui.notifications.add = cloudStack.ui.notifications.__add; - $.fn.cloudBrowser = $.fn.__cloudBrowser; - $.fn.listView = $.fn.__listView; - $.fn.dataTable = $.fn.__dataTable; - $.fn.is = $.fn.__is; - } - }); - - test('Basic', function() { - var detailView = { - tabs: { - tabA: { - title: 'tabA', - fields: [{}], - dataProvider: function() {} - }, - tabB: { - title: 'tabB', - fields: [{}], - dataProvider: function() {} - } - } - }; - - var $detailView = $('
'); - - ok($detailView.detailView(detailView), 'Create detail view'); - equal($detailView.find('.ui-tabs-nav li').size(), 2, 'Detail view has correct tab count'); - equal($detailView.find('.ui-tabs-nav li:first a').html(), 'tabA', 'First tab has correct title'); - equal($detailView.find('.ui-tabs-nav li:last a').html(), 'tabB', 'Last tab has correct title'); - }); - - test('Data provider', function() { - var detailView = { - tabs: { - tabA: { - title: 'tabA', - fields: [{ - fieldA: { label: 'fieldA' }, - fieldB: { label: 'fieldB' } - }], - dataProvider: function(args) { - start(); - ok(args.response.success({ - data: { - fieldA: 'dataProviderFieldA', - fieldB: 'dataProviderFieldB' - } - }), 'Call success'); - equal($detailView.find('tr').size(), 2, 'Correct fields rendered'); - equal($detailView.find('tr:first td:first').html(), 'fieldA', 'First field has correct label'); - equal($detailView.find('tr:first td:last').html(), 'dataProviderFieldA', 'First field has correct content'); - equal($detailView.find('tr:last td:first').html(), 'fieldB', 'Last field has correct label'); - equal($detailView.find('tr:last td:last').html(), 'dataProviderFieldB', 'Last field has correct content'); - } - } - } - }; - var $detailView = $('
'); - - stop(); - - // Test first tab - $detailView = $detailView.detailView(detailView); - - // Test last tab - $detailView.find('.ui-tabs-nav li:last').click(); - }); - - test('Data provider, multiple tabs', function() { - var detailView = { - tabs: { - tabA: { - title: 'tabA', - fields: [{ - fieldA: { label: 'fieldA' }, - fieldB: { label: 'fieldB' } - }], - dataProvider: function(args) { - start(); - ok(args.response.success({ - data: { - fieldA: 'dataProviderFieldA', - fieldB: 'dataProviderFieldB' - } - }), 'Call success'); - equal($detailView.find('tr').size(), 2, 'Correct fields rendered'); - equal($detailView.find('tr:first td:first').html(), 'fieldA', 'First field has correct label'); - equal($detailView.find('tr:first td:last').html(), 'dataProviderFieldA', 'First field has correct content'); - equal($detailView.find('tr:last td:first').html(), 'fieldB', 'Last field has correct label'); - equal($detailView.find('tr:last td:last').html(), 'dataProviderFieldB', 'Last field has correct content'); - } - }, - - tabB: { - title: 'tabB', - fields: [{ - fieldC: { label: 'fieldC' }, - fieldD: { label: 'fieldD' }, - fieldC: { label: 'fieldE' }, - fieldD: { label: 'fieldF' } - }], - dataProvider: function(args) { - start(); - ok(args.response.success({ - data: { - fieldC: 'dataProviderFieldC', - fieldD: 'dataProviderFieldD', - fieldE: 'dataProviderFieldE', - fieldF: 'dataProviderFieldF' - } - }), 'Call success'); - equal($detailView.find('tr').size(), 4, 'Correct fields rendered'); - equal($detailView.find('tr:first td:first').html(), 'fieldC', 'First field has correct label'); - equal($detailView.find('tr:first td:last').html(), 'dataProviderFieldC', 'First field has correct content'); - equal($detailView.find('tr:last td:first').html(), 'fieldF', 'Last field has correct label'); - equal($detailView.find('tr:last td:last').html(), 'dataProviderFieldF', 'Last field has correct content'); - } - } - } - }; - var $detailView = $('
'); - - stop(); - - // Test first tab - $detailView = $detailView.detailView(detailView); - - // Test last tab - $detailView.find('.ui-tabs-nav li:last').click(); - }); - - test('Field pre-filter', function() { - var detailView = { - tabs: { - tabA: { - title: 'tabA', - fields: { - fieldA: { label: 'fieldA' }, - fieldB: { label: 'fieldB' }, - fieldC: { label: 'fieldC' }, - fieldD: { label: 'fieldD' } - }, - preFilter: function(args) { - return ['fieldB', 'fieldC']; - }, - dataProvider: function (args) { - args.response.success({ - data: { - fieldA: 'fieldAContent', - fieldB: 'fieldBContent', - fieldC: 'fieldCContent', - fieldD: 'fieldDContent' - } - }); - - start(); - equal($detailView.find('tr').size(), 2, 'Correct fields rendered'); - equal($detailView.find('tr:first td:first').html(), 'fieldA', 'First field has correct label'); - equal($detailView.find('tr:first td:last').html(), 'fieldAContent', 'First field has correct content'); - equal($detailView.find('tr:last td:first').html(), 'fieldD', 'Last field has correct label'); - equal($detailView.find('tr:last td:last').html(), 'fieldDContent', 'Last field has correct content'); - } - } - } - }; - var $detailView = $('
'); - - stop(); - - $detailView.detailView(detailView); - }); - - test('Action', function() { - var detailView = { - actions: { - actionA: { - label: 'testActionA', - action: function(args) { - start(); - ok(args.response.success(), 'Call success from action A'); - }, - messages: { - confirm: function() { return 'testActionAConfirm'; }, - notification: function() { return 'testActionANotification'; } - } - }, - actionB: { - label: 'testActionB', - action: function(args) { - start(); - ok(args.response.success(), 'Call success from action B'); - }, - messages: { - confirm: function() { return 'testActionBConfirm'; }, - notification: function() { return 'testActionBNotification'; } - }, - notification: { - poll: function(args) { - start(); - ok(args.complete(), 'Call complete from async action B'); - } - } - } - }, - tabs: { - tabA: { - title: 'tabA', - fields: { - fieldA: { label: 'fieldA' }, - fieldB: { label: 'fieldB' } - }, - dataProvider: function(args) { - args.response.success({ - data: { - fieldA: 'fieldAContent', - fieldB: 'fieldBContent' - } - }); - } - } - } - }; - var $detailView = $('
'); - - $detailView.detailView(detailView).appendTo('#qunit-fixture'); - - equal($detailView.find('.detail-actions').size(), 1, 'Action container present'); - equal($detailView.find('.detail-actions .action').size(), 2, 'Correct action count'); - equal($detailView.find('.detail-actions .action.actionA').size(), 1, 'actionA present'); - equal($detailView.find('.detail-actions .action.actionB').size(), 1, 'actionB present'); - - cloudStack.dialog.confirm = function(args) { - start(); - equal(args.message, 'testActionAConfirm', 'Correct confirmation message for action A'); - stop(); - - args.action(); // Perform action - }; - - cloudStack.ui.notifications.add = function(notification, success, successArgs) { - stop(); - equal(notification.desc, 'testActionANotification', 'Correct notification message for action A'); - start(); - }; - - $detailView.find('.detail-actions .action.actionA a').click(); // triggers action, not action's container - - cloudStack.dialog.confirm = function(args) { - start(); - equal(args.message, 'testActionBConfirm', 'Correct confirmation message for action B'); - stop(); - - args.action(); // Perform action - }; - - cloudStack.ui.notifications.add = function(notification, success, successArgs) { - start(); - equal(notification.desc, 'testActionBNotification', 'Correct notification message for action B'); - stop(); - notification.poll({ complete: function() { return true; } }); - }; - - $detailView.find('.detail-actions .action.actionB a').click(); // triggers action, not action's container - }); - - test('Action filter', function() { - var detailView = { - actions: { - actionA: { - label: 'testActionA', - action: function(args) {} - }, - actionB: { - label: 'testActionB', - action: function(args) {} - } - }, - tabs: { - tabA: { - title: 'tabA', - fields: { - fieldA: { label: 'fieldA' }, - fieldB: { label: 'fieldB' } - }, - dataProvider: function(args) { - args.response.success({ - actionFilter: function() { - return ['actionA']; - }, - data: { - fieldA: 'fieldAContent', - fieldB: 'fieldBContent' - } - }); - } - } - } - }; - var $detailView = $('
'); - - $detailView.detailView(detailView).appendTo('#qunit-fixture'); - - equal($detailView.find('.detail-actions .action').size(), 1, 'Correct action count'); - equal($detailView.find('.detail-actions .action.actionA').size(), 1, 'actionA present'); - notEqual($detailView.find('.detail-actions .action.actionB').size(), 1, 'actionB not present'); - }); - - test('Refresh', function() { - var dataA = ['dataLoad1A', 'dataLoad2A']; - var dataB = ['dataLoad1B', 'dataLoad2B']; - var index = 0; - - var detailView = { - tabs: { - tabA: { - title: 'tabA', - fields: { - fieldA: { label: 'fieldA' } - }, - dataProvider: function(args) { - args.response.success({ data: { fieldA: dataA[index] }}); - start(); - equal($detailView.find('tr td:last').html(), dataA[index], 'Tab A data correct for load ' + (index + 1)); - index++; - } - }, - tabB: { - title: 'tabB', - fields: { - fieldB: { label: 'fieldB' } - }, - dataProvider: function(args) { - args.response.success({ data: { fieldB: dataB[index] }}); - start(); - equal($detailView.find('tr td:last').html(), dataB[index], 'Tab B data correct for load ' + (index + 1)); - index++; - } - } - } - }; - var $detailView = $('
'); - - stop(); - $detailView.detailView(detailView).appendTo('#qunit-fixture'); - - stop(); - $detailView.find('.button.refresh').click(); - - stop(); - index = 0; - $detailView.find('.ui-tabs-nav li.last a').click(); - - stop(); - $detailView.find('.button.refresh').click(); - }); - - test('View all, 1 section', function() { - var $browser = $('
').appendTo('#qunit-fixture'); - var detailView = { - $browser: $browser, - context: {}, - viewAll: { label: 'testListView', path: 'testListView' }, - tabs: { - tabA: { - title: 'tabA', - fields: [{ fieldA: { label: 'fieldA' }}], - dataProvider: function(args) { args.response.success({ data: { fieldA: 'fieldAContent' } }); start(); } - } - } - }; - var testListView = {}; - var $detailView = $('
').appendTo('#qunit-fixture'); - - $('
').attr('cloudStack-container', true).data('cloudStack-args', { - sections: { - testListView: testListView - } - }).appendTo('#qunit-fixture'); - - stop(); - - $.fn.cloudBrowser = function(cmd, args) {}; - $browser.cloudBrowser(); - $detailView.detailView(detailView); - - equal($detailView.find('.detail-group.actions td.view-all').size(), 1, 'Detail view has view all button'); - - stop(); - - $.fn.listView = function(args, options) { - start(); - ok(true, 'List view called'); - equal(args, testListView, 'Correct list view passed'); - ok(args.$browser.size(), 'Browser passed in args'); - ok($.isPlainObject(args.ref), 'Ref passed in args'); - equal(args.id, 'testListView', 'Correct section ID'); - - return this; - }; - - $.fn.cloudBrowser = function(cmd, args) { - start(); - equal(cmd, 'addPanel', 'Browser add panel called'); - stop(); - args.complete($('
')); - }; - - $detailView.find('.view-all a').click(); - }); - - test('View all, subsections', function() { - var $browser = $('
').appendTo('#qunit-fixture'); - var detailView = { - $browser: $browser, - context: {}, - viewAll: { label: 'testListView', path: 'testSection.listViewB' }, - tabs: { - tabA: { - title: 'tabA', - fields: [{ fieldA: { label: 'fieldA' }}], - dataProvider: function(args) { args.response.success({ data: { fieldA: 'fieldAContent' } }); start(); } - } - } - }; - var listViewA = {}; - var listViewB = {}; - var $detailView = $('
').appendTo('#qunit-fixture'); - - $('
').attr('cloudStack-container', true).data('cloudStack-args', { - sections: { - testSection: { - sections: { - listViewA: { listView: listViewA }, - listViewB: { listView: listViewB } - } - } - } - }).appendTo('#qunit-fixture'); - - stop(); - - $.fn.cloudBrowser = function(cmd, args) {}; - $browser.cloudBrowser(); - $detailView.detailView(detailView); - - equal($detailView.find('.detail-group.actions td.view-all').size(), 1, 'Detail view has view all button'); - - stop(); - - $.fn.listView = function(args, options) { - start(); - ok(true, 'List view called'); - equal(args.listView, listViewB, 'Correct list view passed'); - ok(args.$browser.size(), 'Browser passed in args'); - ok($.isPlainObject(args.ref), 'Ref passed in args'); - equal(args.id, 'testSection', 'Correct section ID'); - - return this; - }; - - $.fn.cloudBrowser = function(cmd, args) { - start(); - equal(cmd, 'addPanel', 'Browser add panel called'); - stop(); - args.complete($('
')); - }; - - $detailView.find('.view-all a').click(); - }); - - test('Pre-action', function() { - var detailView = { - actions: { - test: { - label: 'test', - preAction: function() { - start(); - ok(true, 'Pre-action called'); - - return false; - }, - action: function() { - ok(false, 'Action called; pre-action should have blocked it'); - }, - messages: { notification: function() { return 'notification'; }} - } - }, - tabs: { - test: { - title: 'test', - label: 'testAction', - fields: [{ - fieldA: { label: 'fieldA' }, - fieldB: { label: 'fieldB' } - }], - dataProvider: function(args) { args.response.success({ data: {} }); } - } - } - }; - var $detailView = $('
'); - - stop(); - $detailView.detailView(detailView); - $detailView.find('.action.test a').click(); - }); - - test('Update data, from list view row', function() { - var detailView = { - section: 'testListView', - context: { - testListView: [{ - fieldA: 'fieldA-1', - fieldB: 'fieldB-1', - fieldC: 'fieldC-1' - }] - }, - actions: { - updateDataTestSync: { - label: 'updateDataTestSync', - preAction: function(args) { return true; }, - action: function(args) { - args.response.success({ - data: { - fieldA: 'fieldA-2', - fieldB: 'fieldB-2' - } - }); - - start(); - equal($detailView.data('view-args').context.testListView[0].fieldA, 'fieldA-2', 'Correct context value for fieldA'); - equal($detailView.data('view-args').context.testListView[0].fieldB, 'fieldB-2', 'Correct context value for fieldB'); - equal($detailView.data('view-args').context.testListView[0].fieldC, 'fieldC-1', 'Correct context value for fieldC'); - equal($detailView.find('tr.fieldA .value').html(), 'fieldA-2', 'Correct table value for fieldA'); - equal($detailView.find('tr.fieldB .value').html(), 'fieldB-2', 'Correct table value for fieldB'); - equal($detailView.find('tr.fieldC .value').html(), 'fieldC-1', 'Correct table value for fieldC'); - }, - messages: { notification: function() { return 'notification'; }} - } - }, - tabs: { - test: { - title: 'test', - fields: [{ - fieldA: { label: 'fieldA' }, - fieldB: { label: 'fieldB' }, - fieldC: { label: 'fieldC' } - }], - dataProvider: function(args) { - args.response.success({ - data: args.context.testListView[0] - }); - } - } - } - }; - var $detailView = $('
'); - var $listView = $('
').addClass('list-view'); - var $listViewRow = $('
').data('json-obj', detailView.context.testListView[0]).appendTo($listView); - var $cloudStackContainer = $('
').attr('cloudStack-container', true).data('cloudStack-args', { - sections: { - testListView: {} - } - }).appendTo('#qunit-fixture'); - - $.fn.dataTable = function() { return this; }; - $.fn.listView = function(args1, args2) { - if (args1 == 'replaceItem') - args2.after(args2.$row.data('json-obj', args2.data)); - - return this; - }; - - cloudStack.ui.notifications.add = function(notification, complete) { - complete(); - }; - cloudStack.dialog.confirm = function(args) { - args.action(); - }; - $detailView.data('list-view-row', $listViewRow); - $detailView.detailView(detailView); - - stop(); - $detailView.find('.action.updateDataTestSync a').click(); - }); - - - test('Update data async, from list view row', function() { - var detailView = { - section: 'testListView', - context: { - testListView: [{ - fieldA: 'fieldA-1', - fieldB: 'fieldB-1', - fieldC: 'fieldC-1', - state: 'on' - }] - }, - actions: { - updateDataTestAsync: { - label: 'updateDataTestAsync', - preAction: function(args) { - start(); - ok(true, 'Pre-action called'); - equal($detailView.data('view-args').context.testListView[0].fieldA, 'fieldA-1', 'Pre-action: Correct context value for fieldA'); - equal($detailView.data('view-args').context.testListView[0].fieldB, 'fieldB-1', 'Pre-action: Correct context value for fieldB'); - equal($detailView.data('view-args').context.testListView[0].fieldC, 'fieldC-1', 'Pre-action: Correct context value for fieldC'); - stop(); - - return true; - }, - action: function(args) { - args.response.success(); - }, - messages: { notification: function() { return 'notification'; }}, - notification: { - poll: function(args) { - args.complete({ - data: { - fieldA: 'fieldA-2', - fieldB: 'fieldB-2', - state: 'off' - } - }); - - start(); - equal($detailView.data('view-args').context.testListView[0].fieldA, 'fieldA-2', 'Correct context value for fieldA'); - equal($detailView.data('view-args').context.testListView[0].fieldB, 'fieldB-2', 'Correct context value for fieldB'); - equal($detailView.data('view-args').context.testListView[0].fieldC, 'fieldC-1', 'Correct context value for fieldC'); - equal($detailView.find('tr.fieldA .value').html(), 'fieldA-2', 'Correct table value for fieldA'); - equal($detailView.find('tr.fieldB .value').html(), 'fieldB-2', 'Correct table value for fieldB'); - equal($detailView.find('tr.fieldC .value').html(), 'fieldC-1', 'Correct table value for fieldC'); - - equal($detailView.find('.action').size(), 1, 'Correct action count'); - equal($detailView.find('.action.updateDataTestAsync').size(), 1, 'updateDataTestAsync present'); - equal($detailView.find('.action.filteredAction').size(), 0, 'filteredAction not present'); - stop(); - } - } - }, - - filteredAction: { - label: 'filteredAction', - action: function() {}, - messages: { notification: function() { return 'notification'; } } - } - }, - tabs: { - test: { - title: 'test', - fields: [{ - fieldA: { label: 'fieldA' }, - fieldB: { label: 'fieldB' }, - fieldC: { label: 'fieldC' } - }], - dataProvider: function(args) { - args.response.success({ - data: args.context.testListView[0], - actionFilter: function(args) { - if (args.context.testListView[0].state == 'on') { - return ['updateDataTestAsync', 'filteredAction']; - } - - return ['updateDataTestAsync']; - } - }); - } - } - } - }; - var $detailView = $('
'); - var $listView = $('
').addClass('list-view'); - var $listViewRow = $('
').data('json-obj', detailView.context.testListView[0]).appendTo($listView); - var $cloudStackContainer = $('
').attr('cloudStack-container', true).data('cloudStack-args', { - sections: { - testListView: {} - } - }).appendTo('#qunit-fixture'); - - $.fn.dataTable = function() { return this; }; - $.fn.listView = function(args1, args2) { - if (args1 == 'replaceItem') - args2.after(args2.$row.data('json-obj', args2.data)); - - return this; - }; - - cloudStack.ui.notifications.add = function(notification, complete) { - notification.poll({ complete: complete }); - }; - cloudStack.dialog.confirm = function(args) { - args.action(); - }; - $detailView.data('list-view-row', $listViewRow); - $detailView.detailView(detailView); - - equal($detailView.find('.action').size(), 2, 'Correct action count'); - equal($detailView.find('.action.updateDataTestAsync').size(), 1, 'updateDataTestAsync present'); - equal($detailView.find('.action.filteredAction').size(), 1, 'filteredAction present'); - - stop(); - $detailView.find('.action.updateDataTestAsync a').click(); - $detailView.data('view-args').actions.updateDataTestAsync.preAction = function(args) { - start(); - equal($detailView.data('view-args').context.testListView[0].fieldA, 'fieldA-2', 'Pre-action: Correct context value for fieldA'); - equal($detailView.data('view-args').context.testListView[0].fieldB, 'fieldB-2', 'Pre-action: Correct context value for fieldB'); - equal($detailView.data('view-args').context.testListView[0].fieldC, 'fieldC-1', 'Pre-action: Correct context value for fieldC'); - ok(true, 'Pre-action called'); - - return false; - }; - $detailView.find('.action.updateDataTestAsync a').click(); - }); - - test('Update context', function() { - var detailView = { - context: { - listViewItemA: [ - { fieldA: 'fieldAContent' } - ] - // listViewItemB [not stored yet] - }, - - tabFilter: function(args) { - start(); - ok($.isArray(args.context.listViewItemB), 'updateContext called before tabFilter'); - stop(); - - return []; - }, - - // updateContext is executed every time a data provider is called - updateContext: function(args) { - start(); - ok(true, 'updateContext called'); - equal(args.context.listViewItemA[0].fieldA, 'fieldAContent', 'updateContext: Item A present in context'); - stop(); - - return { - listViewItemB: [ - { fieldB: 'fieldBContent' } - ] - }; - }, - - tabs: { - test: { - title: 'test', - fields: { fieldA: { label: 'fieldA'}, fieldB: { label: 'fieldB' }}, - dataProvider: function(args) { - start(); - equal(args.context.listViewItemA[0].fieldA, 'fieldAContent', 'dataProvider: Item A present in context'); - equal(args.context.listViewItemB[0].fieldB, 'fieldBContent', 'dataProvider: Item B present in context'); - } - } - } - }; - var $detailView = $('
'); - - stop(); - $detailView.detailView(detailView); - }); -}(jQuery)); diff --git a/ui/tests/test.listView.js b/ui/tests/test.listView.js deleted file mode 100644 index 3449ab29234..00000000000 --- a/ui/tests/test.listView.js +++ /dev/null @@ -1,527 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -(function($) { - module('List view', { - setup: function() { - $.fx.off = true; - cloudStack.debug = true; - }, - teardown: function() { - // Cleanup notification box - $('.notification-box').remove(); - } - }); - - test('Basic', function() { - var listView = { - listView: { - section: 'test123', - fields: { - fieldA: { label: 'testFieldA' }, - fieldB: { label: 'testFieldB' } - }, - dataProvider: function(args) { - args.response.success({ - data: [] - }); - } - } - }; - var $listView; - - ok($listView = $('
').listView(listView), 'Initialize list view'); - equal($listView.find('.list-view').size(), 1, 'List view has container div'); - equal($listView.find('.list-view.test123').size(), 1, 'Container div has section ID as CSS class'); - equal($listView.find('.list-view table').size(), 2, 'List view has split tables'); - equal($listView.find('.list-view .fixed-header table thead tr').size(), 1, 'List view has fixed table header'); - equal($listView.find('.list-view .fixed-header table thead th').size(), 2, 'List view has correct column headers'); - equal($listView.find('.list-view .fixed-header table thead th:first').html(), 'testFieldA', 'First header has correct label'); - ok($listView.find('.list-view .fixed-header table thead th:first').hasClass('fieldA'), 'First header has correct class'); - ok($listView.find('.list-view .fixed-header table thead th:last').hasClass('fieldB'), 'First header has correct class'); - equal($listView.find('.list-view .fixed-header table thead th:last').html(), 'testFieldB', 'First header has correct label'); - equal($listView.find('.list-view table tbody tr').size(), 1, 'List view has table body'); - equal($listView.find('.toolbar').size(), 1, 'List view has toolbar'); - equal($listView.find('.toolbar .text-search .search-bar input[type=text]').size(), 1, 'Toolbar has search box'); - equal($listView.find('.toolbar .text-search .search-bar input[type=text]').size(), 1, 'Toolbar has search box'); - equal($listView.find('.toolbar .text-search .button.search').size(), 1, 'Toolbar has search button'); - ok(!$listView.find('.toolbar .filters').size(), 'Toolbar doesn\'t have filters'); - }); - - test('Data provider', function() { - var $listView = $('
'); - - stop(); - $listView.listView({ - context: { - tests: [] - }, - listView: { - section: 'test', - fields: { - fieldA: { label: 'testFieldA' }, - fieldB: { label: 'testFieldB' } - }, - dataProvider: function(args) { - start(); - equal(args.page, 1, 'Correct page # passed'); - equal(args.filterBy.search.value, '', 'No search params specified'); - ok($.isArray(args.context.tests), 'Context passed'); - args.response.success({ - data: [ - { - fieldA: '1A', - fieldB: '1B' - }, - { - fieldA: '2A', - fieldB: '2B' - }, - { - fieldA: '3A', - fieldB: '3B' - } - ] - }); - stop(); - setTimeout(function() { - start(); - equal($listView.find('tbody tr').size(), 3, 'Data row count is correct'); - equal($listView.find('tbody tr:first td.fieldA span').html(), '1A', 'Correct table item value for first row'); - equal($listView.find('tbody tr:first td.fieldB span').html(), '1B', 'Correct table item value for first row'); - equal($listView.find('tbody tr:last td.fieldA span').html(), '3A', 'Correct table item value for last row'); - equal($listView.find('tbody tr:last td.fieldB span').html(), '3B', 'Correct table item value for last row'); - }); - } - } - }); - }); - - test('Pre-filter', function() { - var $listView = $('
'); - - stop(); - $listView.listView({ - listView: { - section: 'test', - fields: { - fieldA: { label: 'testFieldA' }, - fieldB: { label: 'testFieldB' }, - fieldC: { label: 'testFieldC' } - }, - preFilter: function(args) { - return ['fieldC']; - }, - dataProvider: function(args) { - args.response.success({ - data: [ - { - fieldA: '1A', - fieldB: '1B', - fieldC: '1C' - } - ] - }); - setTimeout(function() { - start(); - equal($listView.find('thead th').size(), 2, 'Correct # of filtered columns present'); - equal($listView.find('tbody tr:first td').size(), 2, 'Correct # of body columns present'); - equal($listView.find('tbody tr:first td.fieldA span').html(), '1A', 'Correct table item value for data row'); - equal($listView.find('tbody tr:first td.fieldB span').html(), '1B', 'Correct table item value for data row'); - }); - } - } - }); - }); - - test('Section select', function() { - var $listView = $('
'); - - ok($listView.listView({ - sectionSelect: { - label: 'testSectionSelect' - }, - sections: { - sectionA: { - type: 'select', - title: 'sectionA', - listView: { - fields: { - fieldA: { label: 'testFieldA' }, - fieldB: { label: 'testFieldB' } - }, - dataProvider: function(args) { - args.response.success({ - data: [ - { - fieldA: '1A', - fieldB: '1B' - }, - { - fieldA: '2A', - fieldB: '2B' - } - ] - }); - } - } - }, - - sectionB: { - type: 'select', - title: 'sectionB', - listView: { - fields: { - fieldC: { label: 'testFieldC' }, - fieldD: { label: 'testFieldD' }, - fieldE: { label: 'testFieldE' } - }, - dataProvider: function(args) { - args.response.success({ - data: [ - { - fieldC: '1C', - fieldD: '1D', - fieldE: '1E' - }, - { - fieldC: '2C', - fieldD: '2D', - fieldE: '2E' - }, - { - fieldC: '3C', - fieldD: '3D', - fieldE: '3E' - }, - { - fieldC: '4C', - fieldD: '4D', - fieldE: '4E' - } - ] - }); - } - } - } - } - })); - - equal($listView.find('.toolbar .section-switcher').size(), 1, - 'Section switcher present in toolbar'); - equal($listView.find('.toolbar .section-switcher .section-select select').size(), 1, - 'Section select present'); - equal($listView.find('.toolbar .section-switcher .section-select label').html(), - 'testSectionSelect' + ':', - 'Section select label is correct'); - equal($listView.find('.toolbar .section-switcher .section-select select option').size(), 2, - 'Selectable sections present as options'); - equal($listView.find('.toolbar .section-switcher .section-select select option:first').html(), 'sectionA', - 'First select has correct title'); - equal($listView.find('.toolbar .section-switcher .section-select select option:selected')[0], - $listView.find('.toolbar .section-switcher .section-select select option:first')[0], - 'First section option is selected by default'); - equal($listView.find('.toolbar .section-switcher .section-select select option:last').html(), 'sectionB', 'Last select has correct title'); - equal($listView.find('.list-view thead th').size(), 2, 'Correct list view column count present'); - equal($listView.find('.list-view thead th:first').html(), 'testFieldA', 'Column 1 is labeled correctly'); - equal($listView.find('.list-view thead th:last').html(), 'testFieldB', 'Column 2 is labeled correctly'); - equal($listView.find('.list-view tbody tr').size(), 2, 'Correct # of data rows present'); - equal($listView.find('.list-view tbody tr:first td').size(), 2, 'Correct # of data columns present'); - - $listView.find('.toolbar .section-switcher select').val('sectionB'); - stop(); - ok($listView.find('.toolbar .section-switcher select').change(), 'Change section'); - start(); - - equal($listView.find('.list-view thead th').size(), 3, 'Correct list view column count present'); - equal($listView.find('.list-view thead th:first').html(), 'testFieldC', 'Column 1 is labeled correctly'); - equal($($listView.find('.list-view thead th')[1]).html(), 'testFieldD', 'Column 2 is labeled correctly'); - equal($listView.find('.list-view thead th:last').html(), 'testFieldE', 'Column 3 is labeled correctly'); - equal($listView.find('.list-view tbody tr').size(), 4, 'Correct # of data rows present'); - equal($listView.find('.list-view tbody tr:first td').size(), 3, 'Correct # of data columns present'); - equal($listView.find('.list-view tbody tr:first td:first span').html(), '1C', 'First table cell has correct data'); - equal($listView.find('.list-view tbody tr:last td:last span').html(), '4E', 'Last table cell has correct data'); - - $listView.find('.toolbar .section-switcher select').val('sectionA'); - stop(); - ok($listView.find('.toolbar .section-switcher select').change(), 'Change section'); - start(); - equal($listView.find('.toolbar .section-switcher .section-select select option:last').html(), 'sectionB', 'Last select has correct title'); - equal($listView.find('.list-view thead th').size(), 2, 'Correct list view column count present'); - equal($listView.find('.list-view thead th:first').html(), 'testFieldA', 'Column 1 is labeled correctly'); - equal($listView.find('.list-view thead th:last').html(), 'testFieldB', 'Column 2 is labeled correctly'); - equal($listView.find('.list-view tbody tr').size(), 2, 'Correct # of data rows present'); - equal($listView.find('.list-view tbody tr:first td').size(), 2, 'Correct # of data columns present'); - equal($listView.find('.list-view tbody tr:first td:first span').html(), '1A', 'First table cell has correct data'); - equal($listView.find('.list-view tbody tr:last td:last span').html(), '2B', 'Last table cell has correct data'); - }); - - test('Basic sync action', function() { - var $cloudStack = $('
').appendTo('#qunit-fixture'); - var listView = { - listView: { - section: 'test123', - fields: { - fieldA: { label: 'testFieldA' }, - fieldB: { label: 'testFieldB' } - }, - actions: { - basicSync: { - label: 'basicAction', - messages: { - confirm: function() { - return 'basicActionConfirm'; - }, - notification: function() { - return 'basicActionNotification'; - } - }, - action: function(args) { - args.response.success(); - } - } - }, - dataProvider: function(args) { - args.response.success({ - data: [ - { - fieldA: '1A', - fieldB: '1B', - fieldC: '1C' - }, - { - fieldA: '2A', - fieldB: '2B', - fieldC: '2C' - } - ] - }); - } - } - }; - - // CloudStack object is needed for notification handling for actions - var cloudStack = { - sections: { - testActions: listView - }, - - home: 'testActions' - }; - - ok($cloudStack.cloudStack(cloudStack), 'Initialize cloudStack widget w/ list view'); - - var $listView = $cloudStack.find('.list-view'); - - equal($listView.find('table thead th').size(), 3, 'Correct header column count'); - equal($listView.find('table thead th.actions').size(), 1, 'Action header column present'); - equal($listView.find('table tbody tr:first td').size(), 3, 'Correct data column count'); - equal($listView.find('table tbody tr:first td.actions').size(), 1, 'Action data column present'); - equal($listView.find('table tbody tr:first td.actions .action').size(), 1, 'Correct action count'); - equal($listView.find('table tbody tr:first td.actions .action:first .icon').size(), 1, 'Action has icon'); - ok($listView.find('table tbody tr:first td.actions .action:first').hasClass('basicSync'), - 'First action has ID as CSS class'); - ok($listView.find('td.actions .action:first').click(), 'Click first action'); - equal($('.ui-dialog.confirm .message').html(), 'basicActionConfirm', 'Confirmation message present'); - - // Make sure dialog is cleaned up -- always put below all confirm tests - $(':ui-dialog, .overlay').appendTo('#qunit-fixture'); - - ok($('.ui-dialog.confirm .ui-button.ok').click(), 'Confirm action'); - equal($cloudStack.find('.notifications .total span').html(), '1', 'Notification total increased'); - equal($('.notification-box ul li').size(), 1, 'Notification list has 1 item'); - equal($('.notification-box ul li span').html(), 'basicActionNotification', 'Notification list item has correct label'); - ok($('.notification-box ul li').hasClass('pending'), 'Notification has pending state'); - stop(); - setTimeout(function() { - start(); - ok(!$('.notification-box ul li').hasClass('pending'), 'Notification has completed state'); - }); - }); - - test('Async action', function() { - var $cloudStack = $('
').appendTo('#qunit-fixture'); - var listView = { - listView: { - id: 'testAsyncListView', - fields: { - fieldA: { label: 'testFieldA' }, - fieldB: { label: 'testFieldB' } - }, - actions: { - asyncTest: { - label: 'asyncAction', - messages: { - confirm: function() { - return 'asyncActionConfirm'; - }, - notification: function() { - return 'asyncActionNotification'; - } - }, - action: function(args) { - ok($.isArray(args.context.testAsyncListView), 'List view context passed'); - args.response.success({ - _custom: { - jobId: 'job123' - } - }); - }, - notification: { - interval: 0, - poll: function(args) { - start(); - equal(args._custom.jobId, 'job123', 'Job ID passed correctly'); - args.complete(); - } - } - } - }, - dataProvider: function(args) { - args.response.success({ - data: [ - { - fieldA: '1A', - fieldB: '1B', - fieldC: '1C' - }, - { - fieldA: '2A', - fieldB: '2B', - fieldC: '2C' - } - ] - }); - } - } - }; - - // CloudStack object is needed for notification handling for actions - var cloudStack = { - sections: { - testActions: listView - }, - - home: 'testActions' - }; - - ok($cloudStack.cloudStack(cloudStack), 'Initialize cloudStack widget w/ list view'); - - var $listView = $cloudStack.find('.list-view'); - - equal($listView.find('table thead th').size(), 3, 'Correct header column count'); - equal($listView.find('table thead th.actions').size(), 1, 'Action header column present'); - equal($listView.find('table tbody tr:first td').size(), 3, 'Correct data column count'); - equal($listView.find('table tbody tr:first td.actions').size(), 1, 'Action data column present'); - equal($listView.find('table tbody tr:first td.actions .action').size(), 1, 'Correct action count'); - equal($listView.find('table tbody tr:first td.actions .action:first .icon').size(), 1, 'Action has icon'); - ok($listView.find('table tbody tr:first td.actions .action:first').hasClass('asyncTest'), - 'First action has ID as CSS class'); - ok($listView.find('td.actions .action:first').click(), 'Click first action'); - equal($('.ui-dialog.confirm .message').html(), 'asyncActionConfirm', 'Confirmation message present'); - - // Make sure dialog is cleaned up -- always put below all confirm tests - $(':ui-dialog, .overlay').appendTo('#qunit-fixture'); - - ok($('.ui-dialog.confirm .ui-button.ok').click(), 'Confirm action'); - equal($cloudStack.find('.notifications .total span').html(), '1', 'Notification total increased'); - equal($('.notification-box ul li').size(), 1, 'Notification list has 1 item'); - equal($('.notification-box ul li span').html(), 'asyncActionNotification', 'Notification list item has correct label'); - ok($('.notification-box ul li').hasClass('pending'), 'Notification has pending state'); - stop(); - }); - - test('Action filter', function() { - var $cloudStack = $('
').appendTo('#qunit-fixture'); - var listView = { - listView: { - id: 'testAsyncListView', - fields: { - fieldA: { label: 'testFieldA' }, - fieldB: { label: 'testFieldB' } - }, - actions: { - actionA: { - label: 'actionA', - messages: { - confirm: function() { return ''; }, - notification: function() { return ''; } - }, - action: function(args) { args.response.success(); } - }, - actionB: { - label: 'actionB [HIDDEN]', - messages: { - confirm: function() { return ''; }, - notification: function() { return ''; } - }, - action: function(args) { args.response.success(); } - }, - actionC: { - label: 'actionC', - messages: { - confirm: function() { return ''; }, - notification: function() { return ''; } - }, - action: function(args) { args.response.success(); } - } - }, - dataProvider: function(args) { - args.response.success({ - actionFilter: function() { - return ['actionA', 'actionC']; - }, - data: [ - { - fieldA: '1A', - fieldB: '1B', - fieldC: '1C' - }, - { - fieldA: '2A', - fieldB: '2B', - fieldC: '2C' - } - ] - }); - } - } - }; - - // CloudStack object is needed for notification handling for actions - var cloudStack = { - sections: { - testActions: listView - }, - - home: 'testActions' - }; - - ok($cloudStack.cloudStack(cloudStack), 'Initialize cloudStack widget w/ list view'); - - var $listView = $cloudStack.find('.list-view'); - - equal($listView.find('table thead th').size(), 3, 'Correct header column count'); - equal($listView.find('table thead th.actions').size(), 1, 'Action header column present'); - equal($listView.find('table tbody tr:first td.actions').size(), 1, 'Action data column present'); - equal($listView.find('table tbody tr:first td.actions .action').size(), 3, 'Correct action count (all)'); - equal($listView.find('table tbody tr:first td.actions .action:not(.disabled)').size(), 2, 'Correct action count (enabled)'); - ok($listView.find('table tbody tr:first td.actions .action:first').hasClass('actionA'), - 'First action has correct ID'); - ok($listView.find('table tbody tr:first td.actions .action:last').hasClass('actionC'), - 'Last action has correct ID'); - }); -}(jQuery)); diff --git a/ui/tests/test.multiEdit.js b/ui/tests/test.multiEdit.js deleted file mode 100644 index aea072935fe..00000000000 --- a/ui/tests/test.multiEdit.js +++ /dev/null @@ -1,55 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -(function($) { - module('Mutli-edit'); - - test('Basic', function() { - var multiEdit = { - fields: { - fieldA: { edit: true, label: 'fieldA' }, - fieldB: { edit: true, label: 'fieldB' }, - add: { label: 'add', addButton: true } - }, - add: { - label: 'addAction', - action: function() {} - }, - dataProvider: function() {} - }; - var $multiEdit = $('
'); - - ok($multiEdit.multiEdit(multiEdit), 'Initialize multi-edit'); - equal($multiEdit.find('div.multi-edit').size(), 1, 'Main container div correct'); - equal($multiEdit.find('.multi-edit form').size(), 1, 'Multi-edit has form'); - equal($multiEdit.find('.multi-edit form table.multi-edit').size(), 1, 'Form has table'); - equal($multiEdit.find('.multi-edit form table thead tr').size(), 1, 'Header present'); - equal($multiEdit.find('.multi-edit form table tbody tr').size(), 1, 'Form body present'); - equal($multiEdit.find('.multi-edit .data .data-body').size(), 1, 'Data body present'); - - // Header items - equal($multiEdit.find('.multi-edit form table thead th.fieldA[rel=fieldA]').html(), 'fieldA', 'fieldA has correct header'); - equal($multiEdit.find('.multi-edit form table thead th.fieldB[rel=fieldB]').html(), 'fieldB', 'fieldB has correct header'); - equal($multiEdit.find('.multi-edit form table thead th.add[rel=add]').html(), 'add', 'Add action column has correct header'); - - // Form items - equal($multiEdit.find('.multi-edit form table tbody td.fieldA[rel=fieldA] input[name=fieldA]').size(), 1, 'fieldA has correct input'); - equal($multiEdit.find('.multi-edit form table tbody td.fieldA[rel=fieldA] input[type=text]').size(), 1, 'fieldA has text-based input'); - equal($multiEdit.find('.multi-edit form table tbody td.fieldB[rel=fieldB] input[name=fieldB]').size(), 1, 'fieldB has correct input'); - equal($multiEdit.find('.multi-edit form table tbody td.fieldB[rel=fieldB] input[type=text]').size(), 1, 'fieldB has text-based input'); - equal($multiEdit.find('.multi-edit form table tbody td.add[rel=add] .button.add-vm').html(), 'addAction', 'Add action column has correct content'); - }); -}(jQuery)); diff --git a/ui/tests/test.notifications.js b/ui/tests/test.notifications.js deleted file mode 100644 index b0ce313e5cd..00000000000 --- a/ui/tests/test.notifications.js +++ /dev/null @@ -1,107 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -(function($) { - var $notifications, $notificationBox, - $cloudStack, cloudStack; - - module('Notifications', { - setup: function() { - $.fx.off = true; - - cloudStack = { - sections: { - home: { - show: function() { return $('
').addClass('test123'); } - }, - sectionA: { - show: function() { return $('
').addClass('notification123'); } - } - }, - - home: 'home' - }; - - $cloudStack = $('
').appendTo($('#qunit-fixture')); - ok($cloudStack.cloudStack(cloudStack), 'Basic widget initialized'); - - // Need to cleanup here -- not handled by widget - $('.notification-box').remove(); - - $notifications = $('
').appendTo($cloudStack); - ok($notifications.notifications(), 'Initialize notifications widget'); - $notificationBox = $('.notification-box'); - } - }); - - test('Widget setup', function() { - ok($notifications.hasClass('notifications'), 'Correct styling assigned'); - equal($notificationBox.size(), 1, 'Notification box present'); - }); - - test('Add notification via widget', function() { - stop(); - $notifications.notifications('add', { // Basic notification - desc: 'testNotification123', - interval: 0, - poll: function(args) { - var $li = $notificationBox.find('li'); - - start(); - equal($li.size(), 1, 'Notification added to list'); - equal($li.find('span').html(), 'testNotification123', 'Notification description correct'); - ok($li.hasClass('pending'), 'Notification item has pending state'); - ok($notificationBox.find('.button.clear-list').click(), 'Clear list button click'); - equal($notificationBox.find('li').size(), 1, 'Notification list still has correct number of items'); - args.complete(); - ok(!$li.hasClass('pending'), 'Notification item has non-pending (complete) state'); - - stop(); - $notifications.notifications('add', { // More comprehensive notification - desc: 'testNotification456', - interval: 0, - _custom: { - attrA: '123', - attrB: '456' - }, - section: 'sectionA', - poll: function(args) { - var $li = $notificationBox.find('li'); - - start(); - equal($li.size(), 2, 'Notification list is correct'); - ok($.isPlainObject(args._custom), '_custom present'); - equal(args._custom.attrA, '123', '_custom attr A correct'); - equal(args._custom.attrB, '456', '_custom attr B correct'); - ok($li.filter(':last').hasClass('pending'), 'New notification item has pending state'); - ok(!$li.filter(':first').hasClass('pending'), 'First notification item still has non-pending (complete) state'); - ok($notificationBox.find('.button.clear-list').click(), 'Clear list button click'); - ok(!$notificationBox.find('li:first').is(':visible'), 'First (completed) notification item cleared'); - args.complete(); - ok(!$li.hasClass('pending'), 'All notifications item has non-pending (complete) state'); - equal($li.filter(':last').data('notification-section'), 'sectionA', 'Section data is correct in last notification'); - equal($li.filter(':first').find('span').html(), 'testNotification123', 'First notification description correct'); - equal($li.filter(':last').find('span').html(), 'testNotification456', 'Second notification description correct'); - $li.filter(':last').find('span').click(); - equal($cloudStack.find('.notification123').size(), 1, 'Notification item text goes to correct section on click'); - ok($li.filter(':last').find('.remove').click(), 'Remove first item'); - equal($notificationBox.find('li').size(), 0, 'Notification list has no items anymore'); - } - }); - } - }); - }); -}(jQuery)); diff --git a/ui/tests/test.widget.listView.js b/ui/tests/test.widget.listView.js new file mode 100644 index 00000000000..43c42f9d16a --- /dev/null +++ b/ui/tests/test.widget.listView.js @@ -0,0 +1,245 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +(function() { + var listView = function(args) { + var basicArgs = { + listView: { + fields: {}, + dataProvider: function() {} + } + }; + + return $('
').listView( + $.extend(true, {}, basicArgs, args) + ).find('.list-view'); + }; + + module('List view', { + setup: function() { + window.pageSize = 20; + }, + teardown: function() { + delete window.pageSize; + } + }); + + test('Basic', function() { + var $listView = listView(); + var $toolbar = $listView.find('> .toolbar'); + var $table = $listView.find('> .data-table'); + + equal($listView.size(), 1, 'List view present'); + equal($toolbar.size(), 1, 'Toolbar present'); + equal($table.size(), 1, 'Data table div present'); + equal($table.find('> .fixed-header table thead tr').size(), 1, 'Fixed header present'); + equal($table.find('> table.body tbody').size(), 1, 'Body table present'); + }); + + test('Fields: basic', function() { + var $listView = listView({ + listView: { + fields: { + fieldA: { label: 'TestFieldA' } + } + } + }); + var $fields = $listView.find('.fixed-header table thead tr th'); + + equal($fields.size(), 1, 'Column present'); + ok($fields.hasClass('fieldA'), 'Has ID as classname'); + equal($fields.html(), 'TestFieldA', 'Has correct label'); + }); + + test('Fields: n columns', function() { + var testFields = { + fieldA: { label: 'TestFieldA' }, + fieldB: { label: 'TestFieldB' }, + fieldC: { label: 'TestFieldC' } + }; + + var $listView = listView({ + listView: { + fields: testFields + } + }); + var $fields = $listView.find('.fixed-header table thead tr th'); + + $.each(testFields, function(k, v) { + var $field = $fields.filter('.' + k); + + equal($field.size(), 1, k + '-> Column present'); + equal($field.html(), v.label, k + '-> Has correct label'); + }); + }); + + test('Data loading state', function() { + var $listView = listView(); + + equal($listView.find('table.body tr.loading').size(), 1, 'Row has loading state'); + equal($listView.find('table.body tr.loading td.loading.icon').size(), 1, 'Row cell has loading icon'); + }); + + asyncTest('Data provider: basic', function() { + expect(3); + var $listView = listView({ + listView: { + fields: { + fieldA: { label: 'TestFieldA' }, + fieldB: { label: 'TestFieldB' } + }, + dataProvider: function(args) { + args.response.success({ data: [] }); + + ok(true, 'Data provider called'); + start(); + } + } + }); + + equal($listView.find('.data-table table.body tbody tr.empty td').size(), 1, 'Body table has empty table row'); + equal($listView.find('.data-table table.body tbody tr.empty td').html(), 'label.no.data', 'Empty contents notice displayed'); + }); + + asyncTest('Data provider: load data', function() { + var $listView = listView({ + listView: { + fields: { + fieldA: { label: 'TestFieldA' }, + fieldB: { label: 'TestFieldB' } + }, + dataProvider: function(args) { + args.response.success({ + data: [ + { fieldA: 'FieldDataA', fieldB: 'FieldDataB' } + ] + }); + + start(); + } + } + }); + + equal($listView.find('table.body tbody tr').size(), 1, 'Body table has table row'); + equal($listView.find('table.body tbody tr td').size(), 2, 'Body table has table cells'); + equal($listView.find('table.body tbody tr td.fieldA > span').html(), 'FieldDataA', 'FieldDataA content present'); + equal($listView.find('table.body tbody tr td.fieldB > span').html(), 'FieldDataB', 'FieldDataB content present'); + }); + + asyncTest('Data provider: multiple rows of data', function() { + var testData = [ + { fieldA: 'FieldDataA1', fieldB: 'FieldDataB1' }, + { fieldA: 'FieldDataA2', fieldB: 'FieldDataB2' }, + { fieldA: 'FieldDataA3', fieldB: 'FieldDataB3' } + ]; + + var $listView = listView({ + listView: { + fields: { + fieldA: { label: 'TestFieldA' }, + fieldB: { label: 'TestFieldB' } + }, + dataProvider: function(args) { + args.response.success({ + data: testData + }); + + start(); + } + } + }); + + equal($listView.find('table.body tbody tr').size(), 3, 'Body table has correct # of table rows'); + + $(testData).map(function(index, data) { + var $tr = $listView.find('table.body tbody tr').filter(function() { + return $(this).index() === index; + }); + + equal($tr.find('td.fieldA > span').html(), 'FieldDataA' + (index + 1), 'FieldDataA' + (index + 1) + ' present'); + equal($tr.find('td.fieldB > span').html(), 'FieldDataB' + (index + 1), 'FieldDataB' + (index + 1) + ' present'); + }); + }); + + test('Field pre-filter', function() { + var $listView = listView({ + listView: { + fields: { + fieldA: { label: 'TestFieldA' }, + fieldB: { label: 'TestFieldB' }, + fieldHidden: { label: 'TestFieldHidden' } + }, + preFilter: function(args) { + return ['fieldHidden']; + }, + dataProvider: function(args) { + args.response.success({ + data: [ + { fieldA: 'FieldDataA', fieldB: 'FieldDataB', fieldHidden: 'FieldDataHidden' } + ] + }); + + start(); + } + } + }); + + equal($listView.find('table tr th').size(), 2, 'Correct number of header columns present'); + equal($listView.find('table.body tbody tr td').size(), 2, 'Correct number of data body columns present'); + ok(!$listView.find('table.body tbody td.fieldHidden').size(), 'Hidden field not present'); + }); + + test('Filter dropdown', function() { + var $listView = listView({ + listView: { + fields: { + state: { label: 'State' } + }, + filters: { + on: { label: 'FilterOnLabel' }, + off: { label: 'FilterOffLabel' } + }, + dataProvider: function(args) { + var filterBy = args.filterBy.kind; + var data = filterBy === 'on' ? [{ state: 'on' }] : [{ state: 'off' }]; + + args.response.success({ + data: data + }); + + start(); + } + } + }); + + var $filters = $listView.find('.filters select'); + + var testFilterDropdownContent = function() { + equal($filters.find('option').size(), 2, 'Correct # of filters present'); + equal($filters.find('option:first').html(), 'FilterOnLabel', 'Filter on label present'); + equal($filters.find('option:last').html(), 'FilterOffLabel', 'Filter off label present'); + }; + + testFilterDropdownContent(); + equal($filters.find('option').val(), 'on', 'Correct default filter active'); + equal($listView.find('tbody td.state span').html(), 'on', '"on" data item visible'); + ok($filters.val('off').trigger('change'), 'Change filter to "off"'); + equal($listView.find('tbody td.state span').html(), 'off', '"off" data item visible'); + equal($filters.val(), 'off', 'Correct filter active'); + testFilterDropdownContent(); + }); +}()); diff --git a/usage/pom.xml b/usage/pom.xml index a0055ccc12c..70575d40065 100644 --- a/usage/pom.xml +++ b/usage/pom.xml @@ -44,6 +44,12 @@ commons-daemon commons-daemon + + org.dbunit + dbunit + 2.4.9 + test + @@ -119,39 +125,6 @@ - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - - org.apache.maven.plugins - - - maven-antrun-plugin - - [1.7,) - - run - - - - - - - - - - - - @@ -213,5 +186,24 @@ + + integration + + + + org.apache.maven.plugins + maven-failsafe-plugin + + + + integration-test + verify + + + + + + + diff --git a/usage/src/com/cloud/usage/UsageAlertManagerImpl.java b/usage/src/com/cloud/usage/UsageAlertManagerImpl.java index 0f86e857c5a..67bb7020d20 100644 --- a/usage/src/com/cloud/usage/UsageAlertManagerImpl.java +++ b/usage/src/com/cloud/usage/UsageAlertManagerImpl.java @@ -175,7 +175,8 @@ public class UsageAlertManagerImpl extends ManagerBase implements AlertManager { } // TODO: make sure this handles SSL transport (useAuth is true) and regular - protected void sendAlert(AlertType alertType, long dataCenterId, Long podId, String subject, String content) throws MessagingException, UnsupportedEncodingException { + protected void sendAlert(AlertType alertType, long dataCenterId, Long podId, String subject, String content) throws MessagingException, + UnsupportedEncodingException { s_alertsLogger.warn(" alertType:: " + alertType + " // dataCenterId:: " + dataCenterId + " // podId:: " + podId + " // clusterId:: " + null + " // message:: " + subject); AlertVO alert = null; @@ -249,7 +250,6 @@ public class UsageAlertManagerImpl extends ManagerBase implements AlertManager { } - @Override public boolean generateAlert(AlertType alertType, long dataCenterId, Long podId, String msg) { try { @@ -258,6 +258,6 @@ public class UsageAlertManagerImpl extends ManagerBase implements AlertManager { } catch (Exception ex) { s_logger.warn("Failed to generate an alert of type=" + alertType + "; msg=" + msg); return false; - } + } } } diff --git a/usage/src/com/cloud/usage/UsageManagerImpl.java b/usage/src/com/cloud/usage/UsageManagerImpl.java index b6c9ea6d064..6ce69017993 100644 --- a/usage/src/com/cloud/usage/UsageManagerImpl.java +++ b/usage/src/com/cloud/usage/UsageManagerImpl.java @@ -44,7 +44,9 @@ import org.apache.cloudstack.usage.UsageTypes; import com.cloud.alert.AlertManager; import com.cloud.event.EventTypes; import com.cloud.event.UsageEventVO; +import com.cloud.event.UsageEventDetailsVO; import com.cloud.event.dao.UsageEventDao; +import com.cloud.event.dao.UsageEventDetailsDao; import com.cloud.usage.dao.UsageDao; import com.cloud.usage.dao.UsageIPAddressDao; import com.cloud.usage.dao.UsageJobDao; @@ -85,7 +87,6 @@ import com.cloud.utils.db.Filter; import com.cloud.utils.db.GlobalLock; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.TransactionLegacy; -import com.cloud.event.dao.UsageEventDetailsDao; @Component @Local(value = {UsageManager.class}) @@ -102,37 +103,37 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna private static final int USAGE_AGGREGATION_RANGE_MIN = 10; @Inject - private AccountDao m_accountDao; + private AccountDao _accountDao; @Inject - private UserStatisticsDao m_userStatsDao; + private UserStatisticsDao _userStatsDao; @Inject - private UsageDao m_usageDao; + private UsageDao _usageDao; @Inject - private UsageVMInstanceDao m_usageInstanceDao; + private UsageVMInstanceDao _usageInstanceDao; @Inject - private UsageIPAddressDao m_usageIPAddressDao; + private UsageIPAddressDao _usageIPAddressDao; @Inject - private UsageNetworkDao m_usageNetworkDao; + private UsageNetworkDao _usageNetworkDao; @Inject - private UsageVolumeDao m_usageVolumeDao; + private UsageVolumeDao _usageVolumeDao; @Inject - private UsageStorageDao m_usageStorageDao; + private UsageStorageDao _usageStorageDao; @Inject - private UsageLoadBalancerPolicyDao m_usageLoadBalancerPolicyDao; + private UsageLoadBalancerPolicyDao _usageLoadBalancerPolicyDao; @Inject - private UsagePortForwardingRuleDao m_usagePortForwardingRuleDao; + private UsagePortForwardingRuleDao _usagePortForwardingRuleDao; @Inject - private UsageNetworkOfferingDao m_usageNetworkOfferingDao; + private UsageNetworkOfferingDao _usageNetworkOfferingDao; @Inject - private UsageVPNUserDao m_usageVPNUserDao; + private UsageVPNUserDao _usageVPNUserDao; @Inject - private UsageSecurityGroupDao m_usageSecurityGroupDao; + private UsageSecurityGroupDao _usageSecurityGroupDao; @Inject - private UsageJobDao m_usageJobDao; + private UsageJobDao _usageJobDao; @Inject - private VmDiskStatisticsDao m_vmDiskStatsDao; + private VmDiskStatisticsDao _vmDiskStatsDao; @Inject - private UsageVmDiskDao m_usageVmDiskDao; + private UsageVmDiskDao _usageVmDiskDao; @Inject protected AlertManager _alertMgr; @Inject @@ -142,25 +143,25 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna @Inject ConfigurationDao _configDao; @Inject - private UsageVMSnapshotDao m_usageVMSnapshotDao; + private UsageVMSnapshotDao _usageVMSnapshotDao; - private String m_version = null; - private final Calendar m_jobExecTime = Calendar.getInstance(); - private int m_aggregationDuration = 0; - private int m_sanityCheckInterval = 0; - String m_hostname = null; - int m_pid = 0; - TimeZone m_usageTimezone = TimeZone.getTimeZone("GMT");; - private final GlobalLock m_heartbeatLock = GlobalLock.getInternLock("usage.job.heartbeat.check"); - private List usageNetworks = new ArrayList(); - private List usageVmDisks = new ArrayList(); + private String _version = null; + private final Calendar _jobExecTime = Calendar.getInstance(); + private int _aggregationDuration = 0; + private int _sanityCheckInterval = 0; + String _hostname = null; + int _pid = 0; + TimeZone _usageTimezone = TimeZone.getTimeZone("GMT");; + private final GlobalLock _heartbeatLock = GlobalLock.getInternLock("usage.job.heartbeat.check"); + private final List usageNetworks = new ArrayList(); + private final List usageVmDisks = new ArrayList(); - private final ScheduledExecutorService m_executor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Usage-Job")); - private final ScheduledExecutorService m_heartbeatExecutor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Usage-HB")); - private final ScheduledExecutorService m_sanityExecutor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Usage-Sanity")); - private Future m_scheduledFuture = null; - private Future m_heartbeat = null; - private Future m_sanity = null; + private final ScheduledExecutorService _executor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Usage-Job")); + private final ScheduledExecutorService _heartbeatExecutor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Usage-HB")); + private final ScheduledExecutorService _sanityExecutor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Usage-Sanity")); + private Future _scheduledFuture = null; + private Future _heartbeat = null; + private Future _sanity = null; public UsageManagerImpl() { } @@ -180,14 +181,14 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna } final Class c = UsageServer.class; - m_version = c.getPackage().getImplementationVersion(); - if (m_version == null) { + _version = c.getPackage().getImplementationVersion(); + if (_version == null) { // TODO // throw new CloudRuntimeException("Unable to find the implementation version of this usage server"); } if (s_logger.isInfoEnabled()) { - s_logger.info("Implementation Version is " + m_version); + s_logger.info("Implementation Version is " + _version); } Map configs = _configDao.getConfiguration(params); @@ -202,11 +203,11 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna String aggreagationTimeZone = configs.get("usage.aggregation.timezone"); String sanityCheckInterval = configs.get("usage.sanity.check.interval"); if (sanityCheckInterval != null) { - m_sanityCheckInterval = Integer.parseInt(sanityCheckInterval); + _sanityCheckInterval = Integer.parseInt(sanityCheckInterval); } if (aggreagationTimeZone != null && !aggreagationTimeZone.isEmpty()) { - m_usageTimezone = TimeZone.getTimeZone(aggreagationTimeZone); + _usageTimezone = TimeZone.getTimeZone(aggreagationTimeZone); } s_logger.debug("Usage stats aggregation time zone: " + aggreagationTimeZone); @@ -224,32 +225,32 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna } int hourOfDay = Integer.parseInt(execTimeSegments[0]); int minutes = Integer.parseInt(execTimeSegments[1]); - m_jobExecTime.setTime(new Date()); + _jobExecTime.setTime(new Date()); - m_jobExecTime.set(Calendar.HOUR_OF_DAY, hourOfDay); - m_jobExecTime.set(Calendar.MINUTE, minutes); - m_jobExecTime.set(Calendar.SECOND, 0); - m_jobExecTime.set(Calendar.MILLISECOND, 0); + _jobExecTime.set(Calendar.HOUR_OF_DAY, hourOfDay); + _jobExecTime.set(Calendar.MINUTE, minutes); + _jobExecTime.set(Calendar.SECOND, 0); + _jobExecTime.set(Calendar.MILLISECOND, 0); if (execTimeZone != null && !execTimeZone.isEmpty()) { - m_jobExecTime.setTimeZone(TimeZone.getTimeZone(execTimeZone)); + _jobExecTime.setTimeZone(TimeZone.getTimeZone(execTimeZone)); } // if the hour to execute the job has already passed, roll the day forward to the next day - Date execDate = m_jobExecTime.getTime(); + Date execDate = _jobExecTime.getTime(); if (execDate.before(new Date())) { - m_jobExecTime.roll(Calendar.DAY_OF_YEAR, true); + _jobExecTime.roll(Calendar.DAY_OF_YEAR, true); } s_logger.debug("Execution Time: " + execDate.toString()); Date currentDate = new Date(System.currentTimeMillis()); s_logger.debug("Current Time: " + currentDate.toString()); - m_aggregationDuration = Integer.parseInt(aggregationRange); - if (m_aggregationDuration < USAGE_AGGREGATION_RANGE_MIN) { + _aggregationDuration = Integer.parseInt(aggregationRange); + if (_aggregationDuration < USAGE_AGGREGATION_RANGE_MIN) { s_logger.warn("Usage stats job aggregation range is to small, using the minimum value of " + USAGE_AGGREGATION_RANGE_MIN); - m_aggregationDuration = USAGE_AGGREGATION_RANGE_MIN; + _aggregationDuration = USAGE_AGGREGATION_RANGE_MIN; } - m_hostname = InetAddress.getLocalHost().getHostName() + "/" + InetAddress.getLocalHost().getHostAddress(); + _hostname = InetAddress.getLocalHost().getHostName() + "/" + InetAddress.getLocalHost().getHostAddress(); } catch (NumberFormatException ex) { throw new ConfigurationException("Unable to parse usage.stats.job.exec.time '" + execTime + "' or usage.stats.job.aggregation.range '" + aggregationRange + "', please check configuration values"); @@ -257,7 +258,7 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna s_logger.error("Unhandled exception configuring UsageManger", e); throw new ConfigurationException("Unhandled exception configuring UsageManager " + e.toString()); } - m_pid = Integer.parseInt(System.getProperty("pid")); + _pid = Integer.parseInt(System.getProperty("pid")); return true; } @@ -268,27 +269,27 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna } // use the configured exec time and aggregation duration for scheduling the job - m_scheduledFuture = - m_executor.scheduleAtFixedRate(this, m_jobExecTime.getTimeInMillis() - System.currentTimeMillis(), m_aggregationDuration * 60 * 1000, TimeUnit.MILLISECONDS); + _scheduledFuture = + _executor.scheduleAtFixedRate(this, _jobExecTime.getTimeInMillis() - System.currentTimeMillis(), _aggregationDuration * 60 * 1000, TimeUnit.MILLISECONDS); - m_heartbeat = - m_heartbeatExecutor.scheduleAtFixedRate(new Heartbeat(), /* start in 15 seconds...*/15 * 1000, /* check database every minute*/60 * 1000, + _heartbeat = + _heartbeatExecutor.scheduleAtFixedRate(new Heartbeat(), /* start in 15 seconds...*/15 * 1000, /* check database every minute*/60 * 1000, TimeUnit.MILLISECONDS); - if (m_sanityCheckInterval > 0) { - m_sanity = m_sanityExecutor.scheduleAtFixedRate(new SanityCheck(), 1, m_sanityCheckInterval, TimeUnit.DAYS); + if (_sanityCheckInterval > 0) { + _sanity = _sanityExecutor.scheduleAtFixedRate(new SanityCheck(), 1, _sanityCheckInterval, TimeUnit.DAYS); } TransactionLegacy usageTxn = TransactionLegacy.open(TransactionLegacy.USAGE_DB); try { - if (m_heartbeatLock.lock(3)) { // 3 second timeout + if (_heartbeatLock.lock(3)) { // 3 second timeout try { - UsageJobVO job = m_usageJobDao.getLastJob(); + UsageJobVO job = _usageJobDao.getLastJob(); if (job == null) { - m_usageJobDao.createNewJob(m_hostname, m_pid, UsageJobVO.JOB_TYPE_RECURRING); + _usageJobDao.createNewJob(_hostname, _pid, UsageJobVO.JOB_TYPE_RECURRING); } } finally { - m_heartbeatLock.unlock(); + _heartbeatLock.unlock(); } } else { if (s_logger.isTraceEnabled()) @@ -303,10 +304,10 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna @Override public boolean stop() { - m_heartbeat.cancel(true); - m_scheduledFuture.cancel(true); - if (m_sanity != null) { - m_sanity.cancel(true); + _heartbeat.cancel(true); + _scheduledFuture.cancel(true); + if (_sanity != null) { + _sanity.cancel(true); } return true; } @@ -327,27 +328,27 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna } // how about we update the job exec time when the job starts??? - long execTime = m_jobExecTime.getTimeInMillis(); + long execTime = _jobExecTime.getTimeInMillis(); long now = System.currentTimeMillis() + 2000; // 2 second buffer since jobs can run a little early (though usually just by milliseconds) if (execTime < now) { // if exec time is in the past, calculate the next time the job will execute...if this is a one-off job that is a result // of scheduleParse() then don't update the next exec time... - m_jobExecTime.add(Calendar.MINUTE, m_aggregationDuration); + _jobExecTime.add(Calendar.MINUTE, _aggregationDuration); } - UsageJobVO job = m_usageJobDao.isOwner(m_hostname, m_pid); + UsageJobVO job = _usageJobDao.isOwner(_hostname, _pid); if (job != null) { // FIXME: we really need to do a better job of not missing any events...so we should some how // keep track of the last time usage was run, then go from there... // For executing the job, we treat hourly and daily as special time ranges, using the previous full hour or the previous // full day. Otherwise we just subtract off the aggregation range from the current time and use that as start date with // current time as end date. - Calendar cal = Calendar.getInstance(m_usageTimezone); + Calendar cal = Calendar.getInstance(_usageTimezone); cal.setTime(new Date()); long startDate = 0; long endDate = 0; - if (m_aggregationDuration == DAILY_TIME) { + if (_aggregationDuration == DAILY_TIME) { cal.roll(Calendar.DAY_OF_YEAR, false); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); @@ -358,7 +359,7 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna cal.roll(Calendar.DAY_OF_YEAR, true); cal.add(Calendar.MILLISECOND, -1); endDate = cal.getTime().getTime(); - } else if (m_aggregationDuration == HOURLY_TIME) { + } else if (_aggregationDuration == HOURLY_TIME) { cal.roll(Calendar.HOUR_OF_DAY, false); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); @@ -370,7 +371,7 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna endDate = cal.getTime().getTime(); } else { endDate = cal.getTime().getTime(); // current time - cal.add(Calendar.MINUTE, -1 * m_aggregationDuration); + cal.add(Calendar.MINUTE, -1 * _aggregationDuration); startDate = cal.getTime().getTime(); } @@ -390,7 +391,7 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna if (s_logger.isDebugEnabled()) { s_logger.debug("Scheduling Usage job..."); } - m_executor.schedule(this, 0, TimeUnit.MILLISECONDS); + _executor.schedule(this, 0, TimeUnit.MILLISECONDS); } @Override @@ -405,7 +406,7 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna endDateMillis = timeStart; } - long lastSuccess = m_usageJobDao.getLastJobSuccessDateMillis(); + long lastSuccess = _usageJobDao.getLastJobSuccessDateMillis(); if (lastSuccess != 0) { startDateMillis = lastSuccess + 1; // 1 millisecond after } @@ -419,11 +420,11 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna try { jobUpdateTxn.start(); // everything seemed to work...set endDate as the last success date - m_usageJobDao.updateJobSuccess(job.getId(), startDateMillis, endDateMillis, System.currentTimeMillis() - timeStart, success); + _usageJobDao.updateJobSuccess(job.getId(), startDateMillis, endDateMillis, System.currentTimeMillis() - timeStart, success); // create a new job if this is a recurring job if (job.getJobType() == UsageJobVO.JOB_TYPE_RECURRING) { - m_usageJobDao.createNewJob(m_hostname, m_pid, UsageJobVO.JOB_TYPE_RECURRING); + _usageJobDao.createNewJob(_hostname, _pid, UsageJobVO.JOB_TYPE_RECURRING); } jobUpdateTxn.commit(); } finally { @@ -449,7 +450,7 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna try { Long limit = Long.valueOf(500); Long offset = Long.valueOf(0); - Long lastAccountId = m_usageDao.getLastAccountId(); + Long lastAccountId = _usageDao.getLastAccountId(); if (lastAccountId == null) { lastAccountId = Long.valueOf(0); } @@ -457,11 +458,11 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna do { Filter filter = new Filter(AccountVO.class, "id", true, offset, limit); - accounts = m_accountDao.findActiveAccounts(lastAccountId, filter); + accounts = _accountDao.findActiveAccounts(lastAccountId, filter); if ((accounts != null) && !accounts.isEmpty()) { // now update the accounts in the cloud_usage db - m_usageDao.updateAccounts(accounts); + _usageDao.updateAccounts(accounts); } offset = new Long(offset.longValue() + limit.longValue()); } while ((accounts != null) && !accounts.isEmpty()); @@ -472,11 +473,11 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna do { Filter filter = new Filter(AccountVO.class, "id", true, offset, limit); - accounts = m_accountDao.findRecentlyDeletedAccounts(lastAccountId, startDate, filter); + accounts = _accountDao.findRecentlyDeletedAccounts(lastAccountId, startDate, filter); if ((accounts != null) && !accounts.isEmpty()) { // now update the accounts in the cloud_usage db - m_usageDao.updateAccounts(accounts); + _usageDao.updateAccounts(accounts); } offset = new Long(offset.longValue() + limit.longValue()); } while ((accounts != null) && !accounts.isEmpty()); @@ -487,11 +488,11 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna do { Filter filter = new Filter(AccountVO.class, "id", true, offset, limit); - accounts = m_accountDao.findNewAccounts(lastAccountId, filter); + accounts = _accountDao.findNewAccounts(lastAccountId, filter); if ((accounts != null) && !accounts.isEmpty()) { // now copy the accounts to cloud_usage db - m_usageDao.saveAccounts(accounts); + _usageDao.saveAccounts(accounts); } offset = new Long(offset.longValue() + limit.longValue()); } while ((accounts != null) && !accounts.isEmpty()); @@ -500,21 +501,21 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna offset = Long.valueOf(0); // get all the user stats to create usage records for the network usage - Long lastUserStatsId = m_usageDao.getLastUserStatsId(); + Long lastUserStatsId = _usageDao.getLastUserStatsId(); if (lastUserStatsId == null) { lastUserStatsId = Long.valueOf(0); } - SearchCriteria sc2 = m_userStatsDao.createSearchCriteria(); + SearchCriteria sc2 = _userStatsDao.createSearchCriteria(); sc2.addAnd("id", SearchCriteria.Op.LTEQ, lastUserStatsId); do { Filter filter = new Filter(UserStatisticsVO.class, "id", true, offset, limit); - userStats = m_userStatsDao.search(sc2, filter); + userStats = _userStatsDao.search(sc2, filter); if ((userStats != null) && !userStats.isEmpty()) { // now copy the accounts to cloud_usage db - m_usageDao.updateUserStats(userStats); + _usageDao.updateUserStats(userStats); } offset = new Long(offset.longValue() + limit.longValue()); } while ((userStats != null) && !userStats.isEmpty()); @@ -522,16 +523,16 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna // reset offset offset = Long.valueOf(0); - sc2 = m_userStatsDao.createSearchCriteria(); + sc2 = _userStatsDao.createSearchCriteria(); sc2.addAnd("id", SearchCriteria.Op.GT, lastUserStatsId); do { Filter filter = new Filter(UserStatisticsVO.class, "id", true, offset, limit); - userStats = m_userStatsDao.search(sc2, filter); + userStats = _userStatsDao.search(sc2, filter); if ((userStats != null) && !userStats.isEmpty()) { // now copy the accounts to cloud_usage db - m_usageDao.saveUserStats(userStats); + _usageDao.saveUserStats(userStats); } offset = new Long(offset.longValue() + limit.longValue()); } while ((userStats != null) && !userStats.isEmpty()); @@ -539,21 +540,21 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna // reset offset offset = Long.valueOf(0); - // get all the vm network stats to create usage_vm_network records for the vm network usage - Long lastVmDiskStatsId = m_usageDao.getLastVmDiskStatsId(); + // get all the vm network stats to create usage_VM_network records for the vm network usage + Long lastVmDiskStatsId = _usageDao.getLastVmDiskStatsId(); if (lastVmDiskStatsId == null) { lastVmDiskStatsId = Long.valueOf(0); } - SearchCriteria sc4 = m_vmDiskStatsDao.createSearchCriteria(); + SearchCriteria sc4 = _vmDiskStatsDao.createSearchCriteria(); sc4.addAnd("id", SearchCriteria.Op.LTEQ, lastVmDiskStatsId); do { Filter filter = new Filter(VmDiskStatisticsVO.class, "id", true, offset, limit); - vmDiskStats = m_vmDiskStatsDao.search(sc4, filter); + vmDiskStats = _vmDiskStatsDao.search(sc4, filter); if ((vmDiskStats != null) && !vmDiskStats.isEmpty()) { // now copy the accounts to cloud_usage db - m_usageDao.updateVmDiskStats(vmDiskStats); + _usageDao.updateVmDiskStats(vmDiskStats); } offset = new Long(offset.longValue() + limit.longValue()); } while ((vmDiskStats != null) && !vmDiskStats.isEmpty()); @@ -561,16 +562,16 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna // reset offset offset = Long.valueOf(0); - sc4 = m_vmDiskStatsDao.createSearchCriteria(); + sc4 = _vmDiskStatsDao.createSearchCriteria(); sc4.addAnd("id", SearchCriteria.Op.GT, lastVmDiskStatsId); do { Filter filter = new Filter(VmDiskStatisticsVO.class, "id", true, offset, limit); - vmDiskStats = m_vmDiskStatsDao.search(sc4, filter); + vmDiskStats = _vmDiskStatsDao.search(sc4, filter); if ((vmDiskStats != null) && !vmDiskStats.isEmpty()) { // now copy the accounts to cloud_usage db - m_usageDao.saveVmDiskStats(vmDiskStats); + _usageDao.saveVmDiskStats(vmDiskStats); } offset = new Long(offset.longValue() + limit.longValue()); } while ((vmDiskStats != null) && !vmDiskStats.isEmpty()); @@ -610,9 +611,9 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna // TODO: Fetch a maximum number of user stats and process them before moving on to the next range of user stats // get user stats in order to compute network usage - networkStats = m_usageNetworkDao.getRecentNetworkStats(); + networkStats = _usageNetworkDao.getRecentNetworkStats(); - Calendar recentlyDeletedCal = Calendar.getInstance(m_usageTimezone); + Calendar recentlyDeletedCal = Calendar.getInstance(_usageTimezone); recentlyDeletedCal.setTimeInMillis(startDateMillis); recentlyDeletedCal.add(Calendar.MINUTE, -1 * THREE_DAYS_IN_MINUTES); Date recentlyDeletedDate = recentlyDeletedCal.getTime(); @@ -621,7 +622,7 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna Map aggregatedStats = new HashMap(); int startIndex = 0; do { - userStats = m_userStatsDao.listActiveAndRecentlyDeleted(recentlyDeletedDate, startIndex, 500); + userStats = _userStatsDao.listActiveAndRecentlyDeleted(recentlyDeletedDate, startIndex, 500); if (userStats != null) { for (UserStatisticsVO userStat : userStats) { @@ -655,20 +656,20 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna createNetworkHelperEntry(aggregatedStats.get(key), currentNetworkStats, endDateMillis); numAcctsProcessed++; } - m_usageNetworkDao.saveUsageNetworks(usageNetworks); + _usageNetworkDao.saveUsageNetworks(usageNetworks); if (s_logger.isDebugEnabled()) { s_logger.debug("created network stats helper entries for " + numAcctsProcessed + " accts"); } // get vm disk stats in order to compute vm disk usage - vmDiskUsages = m_usageVmDiskDao.getRecentVmDiskStats(); + vmDiskUsages = _usageVmDiskDao.getRecentVmDiskStats(); // Keep track of user stats for an account, across all of its public IPs Map aggregatedDiskStats = new HashMap(); startIndex = 0; do { - vmDiskStats = m_vmDiskStatsDao.listActiveAndRecentlyDeleted(recentlyDeletedDate, startIndex, 500); + vmDiskStats = _vmDiskStatsDao.listActiveAndRecentlyDeleted(recentlyDeletedDate, startIndex, 500); if (vmDiskUsages != null) { for (VmDiskStatisticsVO vmDiskStat : vmDiskStats) { @@ -704,7 +705,7 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna createVmDiskHelperEntry(aggregatedDiskStats.get(key), currentVmDiskStats, endDateMillis); numAcctsProcessed++; } - m_usageVmDiskDao.saveUsageVmDisks(usageVmDisks); + _usageVmDiskDao.saveUsageVmDisks(usageVmDisks); if (s_logger.isDebugEnabled()) { s_logger.debug("created vm disk stats helper entries for " + numAcctsProcessed + " accts"); @@ -721,12 +722,12 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna Date currentEndDate = endDate; Date tempDate = endDate; - Calendar aggregateCal = Calendar.getInstance(m_usageTimezone); + Calendar aggregateCal = Calendar.getInstance(_usageTimezone); while ((tempDate.after(startDate)) && ((tempDate.getTime() - startDate.getTime()) > 60000)) { currentEndDate = tempDate; aggregateCal.setTime(tempDate); - aggregateCal.add(Calendar.MINUTE, -m_aggregationDuration); + aggregateCal.add(Calendar.MINUTE, -_aggregationDuration); tempDate = aggregateCal.getTime(); } @@ -736,7 +737,7 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna do { Filter filter = new Filter(AccountVO.class, "id", true, offset, limit); - accounts = m_accountDao.listAll(filter); + accounts = _accountDao.listAll(filter); if ((accounts != null) && !accounts.isEmpty()) { for (AccountVO account : accounts) { parsed = parseHelperTables(account, currentStartDate, currentEndDate); @@ -757,15 +758,15 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna do { Filter filter = new Filter(AccountVO.class, "id", true, offset, limit); - accounts = m_accountDao.findRecentlyDeletedAccounts(null, recentlyDeletedDate, filter); + accounts = _accountDao.findRecentlyDeletedAccounts(null, recentlyDeletedDate, filter); if ((accounts != null) && !accounts.isEmpty()) { for (AccountVO account : accounts) { parsed = parseHelperTables(account, currentStartDate, currentEndDate); - List publicTemplates = m_usageDao.listPublicTemplatesByAccount(account.getId()); + List publicTemplates = _usageDao.listPublicTemplatesByAccount(account.getId()); for (Long templateId : publicTemplates) { //mark public templates owned by deleted accounts as deleted - List storageVOs = m_usageStorageDao.listById(account.getId(), templateId, StorageTypes.TEMPLATE); + List storageVOs = _usageStorageDao.listById(account.getId(), templateId, StorageTypes.TEMPLATE); if (storageVOs.size() > 1) { s_logger.warn("More that one usage entry for storage: " + templateId + " assigned to account: " + account.getId() + "; marking them all as deleted..."); @@ -775,7 +776,7 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna s_logger.debug("deleting template: " + storageVO.getId() + " from account: " + storageVO.getAccountId()); } storageVO.setDeleted(account.getRemoved()); - m_usageStorageDao.update(storageVO); + _usageStorageDao.update(storageVO); } } numAcctsProcessed++; @@ -786,7 +787,7 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna currentStartDate = new Date(currentEndDate.getTime() + 1); aggregateCal.setTime(currentEndDate); - aggregateCal.add(Calendar.MINUTE, m_aggregationDuration); + aggregateCal.add(Calendar.MINUTE, _aggregationDuration); currentEndDate = aggregateCal.getTime(); } @@ -806,11 +807,11 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna usageTxn.rollback(); } finally { // everything seemed to work...set endDate as the last success date - m_usageJobDao.updateJobSuccess(job.getId(), startDateMillis, endDateMillis, System.currentTimeMillis() - timeStart, success); + _usageJobDao.updateJobSuccess(job.getId(), startDateMillis, endDateMillis, System.currentTimeMillis() - timeStart, success); // create a new job if this is a recurring job if (job.getJobType() == UsageJobVO.JOB_TYPE_RECURRING) { - m_usageJobDao.createNewJob(m_hostname, m_pid, UsageJobVO.JOB_TYPE_RECURRING); + _usageJobDao.createNewJob(_hostname, _pid, UsageJobVO.JOB_TYPE_RECURRING); } usageTxn.commit(); usageTxn.close(); @@ -1032,29 +1033,29 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna String vmName = event.getResourceName(); if (EventTypes.EVENT_VM_START.equals(event.getType())) { - // create a new usage_vm_instance row for this VM + // create a new usage_VM_instance row for this VM try { - SearchCriteria sc = m_usageInstanceDao.createSearchCriteria(); + SearchCriteria sc = _usageInstanceDao.createSearchCriteria(); sc.addAnd("vmInstanceId", SearchCriteria.Op.EQ, Long.valueOf(vmId)); sc.addAnd("endDate", SearchCriteria.Op.NULL); sc.addAnd("usageType", SearchCriteria.Op.EQ, UsageTypes.RUNNING_VM); - List usageInstances = m_usageInstanceDao.search(sc, null); + List usageInstances = _usageInstanceDao.search(sc, null); if (usageInstances != null) { if (usageInstances.size() > 0) { s_logger.error("found entries for a vm running with id: " + vmId + ", which are not stopped. Ending them all..."); for (UsageVMInstanceVO usageInstance : usageInstances) { usageInstance.setEndDate(event.getCreateDate()); - m_usageInstanceDao.update(usageInstance); + _usageInstanceDao.update(usageInstance); } } } - sc = m_usageInstanceDao.createSearchCriteria(); + sc = _usageInstanceDao.createSearchCriteria(); sc.addAnd("vmInstanceId", SearchCriteria.Op.EQ, Long.valueOf(vmId)); sc.addAnd("endDate", SearchCriteria.Op.NULL); sc.addAnd("usageType", SearchCriteria.Op.EQ, UsageTypes.ALLOCATED_VM); - usageInstances = m_usageInstanceDao.search(sc, null); + usageInstances = _usageInstanceDao.search(sc, null); if (usageInstances == null || (usageInstances.size() == 0)) { s_logger.error("Cannot find allocated vm entry for a vm running with id: " + vmId); } else if (usageInstances.size() == 1) { @@ -1063,11 +1064,11 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna //Service Offering changed after Vm creation //End current Allocated usage and create new Allocated Vm entry with new soId usageInstance.setEndDate(event.getCreateDate()); - m_usageInstanceDao.update(usageInstance); + _usageInstanceDao.update(usageInstance); usageInstance.setServiceOfferingId(soId); usageInstance.setStartDate(event.getCreateDate()); usageInstance.setEndDate(null); - m_usageInstanceDao.persist(usageInstance); + populateDynamicComputeOfferingDetailsAndPersist(usageInstance, event.getId()); } } @@ -1078,18 +1079,18 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna UsageVMInstanceVO usageInstanceNew = new UsageVMInstanceVO(UsageTypes.RUNNING_VM, zoneId, event.getAccountId(), vmId, vmName, soId, templateId, hypervisorType, event.getCreateDate(), null); - m_usageInstanceDao.persist(usageInstanceNew); + populateDynamicComputeOfferingDetailsAndPersist(usageInstanceNew, event.getId()); } catch (Exception ex) { s_logger.error("Error saving usage instance for vm: " + vmId, ex); } } else if (EventTypes.EVENT_VM_STOP.equals(event.getType())) { - // find the latest usage_vm_instance row, update the stop date (should be null) to the event date + // find the latest usage_VM_instance row, update the stop date (should be null) to the event date // FIXME: search criteria needs to have some kind of type information so we distinguish between START/STOP and CREATE/DESTROY - SearchCriteria sc = m_usageInstanceDao.createSearchCriteria(); + SearchCriteria sc = _usageInstanceDao.createSearchCriteria(); sc.addAnd("vmInstanceId", SearchCriteria.Op.EQ, Long.valueOf(vmId)); sc.addAnd("endDate", SearchCriteria.Op.NULL); sc.addAnd("usageType", SearchCriteria.Op.EQ, UsageTypes.RUNNING_VM); - List usageInstances = m_usageInstanceDao.search(sc, null); + List usageInstances = _usageInstanceDao.search(sc, null); if (usageInstances != null) { if (usageInstances.size() > 1) { s_logger.warn("found multiple entries for a vm running with id: " + vmId + ", ending them all..."); @@ -1098,76 +1099,49 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna usageInstance.setEndDate(event.getCreateDate()); // TODO: UsageVMInstanceVO should have an ID field and we should do updates through that field since we are really // updating one row at a time here - m_usageInstanceDao.update(usageInstance); + _usageInstanceDao.update(usageInstance); } } } else if (EventTypes.EVENT_VM_CREATE.equals(event.getType())) { try { Long templateId = event.getTemplateId(); String hypervisorType = event.getResourceType(); - Long cpuCores= null; - Long memory = null; - Long cpuSpeed = null; - - //populate the cpu, memory and cpuSpeed of the vm when created from a dynamic offering. - Map usageDetails = _usageEventDetailsDao.findDetails(event.getId()); - - if (usageDetails != null && usageDetails.size() != 0) { - if (usageDetails.get(UsageEventVO.DynamicParameters.cpuNumber.name()) != null) { - cpuCores = Long.parseLong(usageDetails.get(UsageEventVO.DynamicParameters.cpuNumber.name())); - } - if (usageDetails.get(UsageEventVO.DynamicParameters.cpuSpeed.name()) != null) { - cpuSpeed = Long.parseLong(usageDetails.get(UsageEventVO.DynamicParameters.cpuSpeed.name())); - } - if (usageDetails.get(UsageEventVO.DynamicParameters.memory.name()) != null) { - memory = Long.parseLong(usageDetails.get(UsageEventVO.DynamicParameters.memory.name())); - } - } // add this VM to the usage helper table UsageVMInstanceVO usageInstanceNew = new UsageVMInstanceVO(UsageTypes.ALLOCATED_VM, zoneId, event.getAccountId(), vmId, vmName, - soId, templateId, hypervisorType, event.getCreateDate(), null); - if (cpuCores != null) { - usageInstanceNew.setCpuCores(cpuCores); - } - if (cpuSpeed != null) { - usageInstanceNew.setCpuSpeed(cpuSpeed); - } - if (memory != null) { - usageInstanceNew.setMemory(memory); - } - m_usageInstanceDao.persist(usageInstanceNew); + soId, templateId, hypervisorType, event.getCreateDate(), null); + populateDynamicComputeOfferingDetailsAndPersist(usageInstanceNew, event.getId()); } catch (Exception ex) { s_logger.error("Error saving usage instance for vm: " + vmId, ex); } } else if (EventTypes.EVENT_VM_DESTROY.equals(event.getType())) { - SearchCriteria sc = m_usageInstanceDao.createSearchCriteria(); + SearchCriteria sc = _usageInstanceDao.createSearchCriteria(); sc.addAnd("vmInstanceId", SearchCriteria.Op.EQ, Long.valueOf(vmId)); sc.addAnd("endDate", SearchCriteria.Op.NULL); sc.addAnd("usageType", SearchCriteria.Op.EQ, UsageTypes.ALLOCATED_VM); - List usageInstances = m_usageInstanceDao.search(sc, null); + List usageInstances = _usageInstanceDao.search(sc, null); if (usageInstances != null) { if (usageInstances.size() > 1) { s_logger.warn("found multiple entries for a vm allocated with id: " + vmId + ", detroying them all..."); } for (UsageVMInstanceVO usageInstance : usageInstances) { usageInstance.setEndDate(event.getCreateDate()); - m_usageInstanceDao.update(usageInstance); + _usageInstanceDao.update(usageInstance); } } } else if (EventTypes.EVENT_VM_UPGRADE.equals(event.getType())) { - SearchCriteria sc = m_usageInstanceDao.createSearchCriteria(); + SearchCriteria sc = _usageInstanceDao.createSearchCriteria(); sc.addAnd("vmInstanceId", SearchCriteria.Op.EQ, Long.valueOf(vmId)); sc.addAnd("endDate", SearchCriteria.Op.NULL); sc.addAnd("usageType", SearchCriteria.Op.EQ, UsageTypes.ALLOCATED_VM); - List usageInstances = m_usageInstanceDao.search(sc, null); + List usageInstances = _usageInstanceDao.search(sc, null); if (usageInstances != null) { if (usageInstances.size() > 1) { s_logger.warn("found multiple entries for a vm allocated with id: " + vmId + ", updating end_date for all of them..."); } for (UsageVMInstanceVO usageInstance : usageInstances) { usageInstance.setEndDate(event.getCreateDate()); - m_usageInstanceDao.update(usageInstance); + _usageInstanceDao.update(usageInstance); } } @@ -1176,29 +1150,29 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna // add this VM to the usage helper table UsageVMInstanceVO usageInstanceNew = new UsageVMInstanceVO(UsageTypes.ALLOCATED_VM, zoneId, event.getAccountId(), vmId, vmName, soId, templateId, hypervisorType, event.getCreateDate(), null); - m_usageInstanceDao.persist(usageInstanceNew); + populateDynamicComputeOfferingDetailsAndPersist(usageInstanceNew, event.getId()); } else if (EventTypes.EVENT_VM_DYNAMIC_SCALE.equals(event.getType())) { // Ending the running vm event - SearchCriteria sc = m_usageInstanceDao.createSearchCriteria(); + SearchCriteria sc = _usageInstanceDao.createSearchCriteria(); sc.addAnd("vmInstanceId", SearchCriteria.Op.EQ, Long.valueOf(vmId)); sc.addAnd("endDate", SearchCriteria.Op.NULL); sc.addAnd("usageType", SearchCriteria.Op.EQ, UsageTypes.RUNNING_VM); - List usageInstances = m_usageInstanceDao.search(sc, null); + List usageInstances = _usageInstanceDao.search(sc, null); if (usageInstances != null) { if (usageInstances.size() > 1) { s_logger.warn("found multiple entries for a vm running with id: " + vmId + ", ending them all..."); } for (UsageVMInstanceVO usageInstance : usageInstances) { usageInstance.setEndDate(event.getCreateDate()); - m_usageInstanceDao.update(usageInstance); + _usageInstanceDao.update(usageInstance); } } - sc = m_usageInstanceDao.createSearchCriteria(); + sc = _usageInstanceDao.createSearchCriteria(); sc.addAnd("vmInstanceId", SearchCriteria.Op.EQ, Long.valueOf(vmId)); sc.addAnd("endDate", SearchCriteria.Op.NULL); sc.addAnd("usageType", SearchCriteria.Op.EQ, UsageTypes.ALLOCATED_VM); - usageInstances = m_usageInstanceDao.search(sc, null); + usageInstances = _usageInstanceDao.search(sc, null); if (usageInstances == null || (usageInstances.size() == 0)) { s_logger.error("Cannot find allocated vm entry for a vm running with id: " + vmId); } else if (usageInstances.size() == 1) { @@ -1207,11 +1181,11 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna //Service Offering changed after Vm creation //End current Allocated usage and create new Allocated Vm entry with new soId usageInstance.setEndDate(event.getCreateDate()); - m_usageInstanceDao.update(usageInstance); + _usageInstanceDao.update(usageInstance); usageInstance.setServiceOfferingId(soId); usageInstance.setStartDate(event.getCreateDate()); usageInstance.setEndDate(null); - m_usageInstanceDao.persist(usageInstance); + populateDynamicComputeOfferingDetailsAndPersist(usageInstance, event.getId()); } } @@ -1221,10 +1195,30 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna // add this VM to the usage helper table with new service offering Id UsageVMInstanceVO usageInstanceNew = new UsageVMInstanceVO(UsageTypes.RUNNING_VM, zoneId, event.getAccountId(), vmId, vmName, soId, templateId, hypervisorType, event.getCreateDate(), null); - m_usageInstanceDao.persist(usageInstanceNew); + populateDynamicComputeOfferingDetailsAndPersist(usageInstanceNew, event.getId()); } } + private void populateDynamicComputeOfferingDetailsAndPersist(UsageVMInstanceVO usageInstance, Long eventId) { + + //populate the cpu, memory and cpuSpeed of the vm when created from a dynamic offering. + UsageEventDetailsVO cpuNumber = _usageEventDetailsDao.findDetail(eventId, UsageEventVO.DynamicParameters.cpuNumber.name()); + if (cpuNumber != null) { + usageInstance.setCpuCores(Long.parseLong(cpuNumber.getValue())); + } + + UsageEventDetailsVO cpuSpeed = _usageEventDetailsDao.findDetail(eventId, UsageEventVO.DynamicParameters.cpuSpeed.name()); + if (cpuSpeed != null) { + usageInstance.setCpuSpeed(Long.parseLong(cpuSpeed.getValue())); + } + + UsageEventDetailsVO memory = _usageEventDetailsDao.findDetail(eventId, UsageEventVO.DynamicParameters.memory.name()); + if (memory != null) { + usageInstance.setMemory(Long.parseLong(memory.getValue())); + } + _usageInstanceDao.persist(usageInstance); + } + private void createNetworkHelperEntry(UserStatisticsVO userStat, UsageNetworkVO usageNetworkStats, long timestamp) { long currentAccountedBytesSent = 0L; long currentAccountedBytesReceived = 0L; @@ -1335,7 +1329,7 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna if (s_logger.isDebugEnabled()) { s_logger.debug("assigning ip address: " + ipAddress + " to account: " + event.getAccountId()); } - Account acct = m_accountDao.findByIdIncludingRemoved(event.getAccountId()); + Account acct = _accountDao.findByIdIncludingRemoved(event.getAccountId()); long zoneId = event.getZoneId(); long id = event.getResourceId(); long sourceNat = event.getSize(); @@ -1343,13 +1337,13 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna boolean isSystem = (event.getTemplateId() == null || event.getTemplateId() == 0) ? false : true; UsageIPAddressVO ipAddressVO = new UsageIPAddressVO(id, event.getAccountId(), acct.getDomainId(), zoneId, ipAddress, isSourceNat, isSystem, event.getCreateDate(), null); - m_usageIPAddressDao.persist(ipAddressVO); + _usageIPAddressDao.persist(ipAddressVO); } else if (EventTypes.EVENT_NET_IP_RELEASE.equals(event.getType())) { - SearchCriteria sc = m_usageIPAddressDao.createSearchCriteria(); + SearchCriteria sc = _usageIPAddressDao.createSearchCriteria(); sc.addAnd("accountId", SearchCriteria.Op.EQ, event.getAccountId()); sc.addAnd("address", SearchCriteria.Op.EQ, ipAddress); sc.addAnd("released", SearchCriteria.Op.NULL); - List ipAddressVOs = m_usageIPAddressDao.search(sc, null); + List ipAddressVOs = _usageIPAddressDao.search(sc, null); if (ipAddressVOs.size() > 1) { s_logger.warn("More that one usage entry for ip address: " + ipAddress + " assigned to account: " + event.getAccountId() + "; marking them all as released..."); @@ -1359,7 +1353,7 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna s_logger.debug("releasing ip address: " + ipAddressVO.getAddress() + " from account: " + ipAddressVO.getAccountId()); } ipAddressVO.setReleased(event.getCreateDate()); // there really shouldn't be more than one - m_usageIPAddressDao.update(ipAddressVO); + _usageIPAddressDao.update(ipAddressVO); } } } @@ -1380,11 +1374,11 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna } if (EventTypes.EVENT_VOLUME_CREATE.equals(event.getType())) { - SearchCriteria sc = m_usageVolumeDao.createSearchCriteria(); + SearchCriteria sc = _usageVolumeDao.createSearchCriteria(); sc.addAnd("accountId", SearchCriteria.Op.EQ, event.getAccountId()); sc.addAnd("id", SearchCriteria.Op.EQ, volId); sc.addAnd("deleted", SearchCriteria.Op.NULL); - List volumesVOs = m_usageVolumeDao.search(sc, null); + List volumesVOs = _usageVolumeDao.search(sc, null); if (volumesVOs.size() > 0) { //This is a safeguard to avoid double counting of volumes. s_logger.error("Found duplicate usage entry for volume: " + volId + " assigned to account: " + event.getAccountId() + "; marking as deleted..."); @@ -1394,20 +1388,20 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna s_logger.debug("deleting volume: " + volumesVO.getId() + " from account: " + volumesVO.getAccountId()); } volumesVO.setDeleted(event.getCreateDate()); - m_usageVolumeDao.update(volumesVO); + _usageVolumeDao.update(volumesVO); } if (s_logger.isDebugEnabled()) { s_logger.debug("create volume with id : " + volId + " for account: " + event.getAccountId()); } - Account acct = m_accountDao.findByIdIncludingRemoved(event.getAccountId()); + Account acct = _accountDao.findByIdIncludingRemoved(event.getAccountId()); UsageVolumeVO volumeVO = new UsageVolumeVO(volId, zoneId, event.getAccountId(), acct.getDomainId(), doId, templateId, size, event.getCreateDate(), null); - m_usageVolumeDao.persist(volumeVO); + _usageVolumeDao.persist(volumeVO); } else if (EventTypes.EVENT_VOLUME_DELETE.equals(event.getType())) { - SearchCriteria sc = m_usageVolumeDao.createSearchCriteria(); + SearchCriteria sc = _usageVolumeDao.createSearchCriteria(); sc.addAnd("accountId", SearchCriteria.Op.EQ, event.getAccountId()); sc.addAnd("id", SearchCriteria.Op.EQ, volId); sc.addAnd("deleted", SearchCriteria.Op.NULL); - List volumesVOs = m_usageVolumeDao.search(sc, null); + List volumesVOs = _usageVolumeDao.search(sc, null); if (volumesVOs.size() > 1) { s_logger.warn("More that one usage entry for volume: " + volId + " assigned to account: " + event.getAccountId() + "; marking them all as deleted..."); } @@ -1416,7 +1410,7 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna s_logger.debug("deleting volume: " + volumesVO.getId() + " from account: " + volumesVO.getAccountId()); } volumesVO.setDeleted(event.getCreateDate()); // there really shouldn't be more than one - m_usageVolumeDao.update(volumesVO); + _usageVolumeDao.update(volumesVO); } } } @@ -1445,22 +1439,22 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna if (s_logger.isDebugEnabled()) { s_logger.debug("create template with id : " + templateId + " for account: " + event.getAccountId()); } - List storageVOs = m_usageStorageDao.listByIdAndZone(event.getAccountId(), templateId, StorageTypes.TEMPLATE, zoneId); + List storageVOs = _usageStorageDao.listByIdAndZone(event.getAccountId(), templateId, StorageTypes.TEMPLATE, zoneId); if (storageVOs.size() > 0) { s_logger.warn("Usage entry for Template: " + templateId + " assigned to account: " + event.getAccountId() + "already exists in zone " + zoneId); return; } - Account acct = m_accountDao.findByIdIncludingRemoved(event.getAccountId()); + Account acct = _accountDao.findByIdIncludingRemoved(event.getAccountId()); UsageStorageVO storageVO = new UsageStorageVO(templateId, zoneId, event.getAccountId(), acct.getDomainId(), StorageTypes.TEMPLATE, event.getTemplateId(), templateSize, event.getVirtualSize(), event.getCreateDate(), null); - m_usageStorageDao.persist(storageVO); + _usageStorageDao.persist(storageVO); } else if (EventTypes.EVENT_TEMPLATE_DELETE.equals(event.getType())) { List storageVOs; if (zoneId != -1L) { - storageVOs = m_usageStorageDao.listByIdAndZone(event.getAccountId(), templateId, StorageTypes.TEMPLATE, zoneId); + storageVOs = _usageStorageDao.listByIdAndZone(event.getAccountId(), templateId, StorageTypes.TEMPLATE, zoneId); } else { - storageVOs = m_usageStorageDao.listById(event.getAccountId(), templateId, StorageTypes.TEMPLATE); + storageVOs = _usageStorageDao.listById(event.getAccountId(), templateId, StorageTypes.TEMPLATE); } if (storageVOs.size() > 1) { s_logger.warn("More that one usage entry for storage: " + templateId + " assigned to account: " + event.getAccountId() + @@ -1471,7 +1465,7 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna s_logger.debug("deleting template: " + storageVO.getId() + " from account: " + storageVO.getAccountId()); } storageVO.setDeleted(event.getCreateDate()); // there really shouldn't be more than one - m_usageStorageDao.update(storageVO); + _usageStorageDao.update(storageVO); } } } @@ -1489,21 +1483,21 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna if (s_logger.isDebugEnabled()) { s_logger.debug("create iso with id : " + isoId + " for account: " + event.getAccountId()); } - List storageVOs = m_usageStorageDao.listByIdAndZone(event.getAccountId(), isoId, StorageTypes.ISO, zoneId); + List storageVOs = _usageStorageDao.listByIdAndZone(event.getAccountId(), isoId, StorageTypes.ISO, zoneId); if (storageVOs.size() > 0) { s_logger.warn("Usage entry for ISO: " + isoId + " assigned to account: " + event.getAccountId() + "already exists in zone " + zoneId); return; } - Account acct = m_accountDao.findByIdIncludingRemoved(event.getAccountId()); + Account acct = _accountDao.findByIdIncludingRemoved(event.getAccountId()); UsageStorageVO storageVO = new UsageStorageVO(isoId, zoneId, event.getAccountId(), acct.getDomainId(), StorageTypes.ISO, null, isoSize, isoSize, event.getCreateDate(), null); - m_usageStorageDao.persist(storageVO); + _usageStorageDao.persist(storageVO); } else if (EventTypes.EVENT_ISO_DELETE.equals(event.getType())) { List storageVOs; if (zoneId != -1L) { - storageVOs = m_usageStorageDao.listByIdAndZone(event.getAccountId(), isoId, StorageTypes.ISO, zoneId); + storageVOs = _usageStorageDao.listByIdAndZone(event.getAccountId(), isoId, StorageTypes.ISO, zoneId); } else { - storageVOs = m_usageStorageDao.listById(event.getAccountId(), isoId, StorageTypes.ISO); + storageVOs = _usageStorageDao.listById(event.getAccountId(), isoId, StorageTypes.ISO); } if (storageVOs.size() > 1) { @@ -1514,7 +1508,7 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna s_logger.debug("deleting iso: " + storageVO.getId() + " from account: " + storageVO.getAccountId()); } storageVO.setDeleted(event.getCreateDate()); // there really shouldn't be more than one - m_usageStorageDao.update(storageVO); + _usageStorageDao.update(storageVO); } } } @@ -1533,12 +1527,12 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna if (s_logger.isDebugEnabled()) { s_logger.debug("create snapshot with id : " + snapId + " for account: " + event.getAccountId()); } - Account acct = m_accountDao.findByIdIncludingRemoved(event.getAccountId()); + Account acct = _accountDao.findByIdIncludingRemoved(event.getAccountId()); UsageStorageVO storageVO = new UsageStorageVO(snapId, zoneId, event.getAccountId(), acct.getDomainId(), StorageTypes.SNAPSHOT, null, snapSize, event.getCreateDate(), null); - m_usageStorageDao.persist(storageVO); + _usageStorageDao.persist(storageVO); } else if (EventTypes.EVENT_SNAPSHOT_DELETE.equals(event.getType())) { - List storageVOs = m_usageStorageDao.listById(event.getAccountId(), snapId, StorageTypes.SNAPSHOT); + List storageVOs = _usageStorageDao.listById(event.getAccountId(), snapId, StorageTypes.SNAPSHOT); if (storageVOs.size() > 1) { s_logger.warn("More that one usage entry for storage: " + snapId + " assigned to account: " + event.getAccountId() + "; marking them all as deleted..."); } @@ -1547,7 +1541,7 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna s_logger.debug("deleting snapshot: " + storageVO.getId() + " from account: " + storageVO.getAccountId()); } storageVO.setDeleted(event.getCreateDate()); // there really shouldn't be more than one - m_usageStorageDao.update(storageVO); + _usageStorageDao.update(storageVO); } } } @@ -1563,15 +1557,15 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna s_logger.debug("Creating load balancer : " + id + " for account: " + event.getAccountId()); } zoneId = event.getZoneId(); - Account acct = m_accountDao.findByIdIncludingRemoved(event.getAccountId()); + Account acct = _accountDao.findByIdIncludingRemoved(event.getAccountId()); UsageLoadBalancerPolicyVO lbVO = new UsageLoadBalancerPolicyVO(id, zoneId, event.getAccountId(), acct.getDomainId(), event.getCreateDate(), null); - m_usageLoadBalancerPolicyDao.persist(lbVO); + _usageLoadBalancerPolicyDao.persist(lbVO); } else if (EventTypes.EVENT_LOAD_BALANCER_DELETE.equals(event.getType())) { - SearchCriteria sc = m_usageLoadBalancerPolicyDao.createSearchCriteria(); + SearchCriteria sc = _usageLoadBalancerPolicyDao.createSearchCriteria(); sc.addAnd("accountId", SearchCriteria.Op.EQ, event.getAccountId()); sc.addAnd("id", SearchCriteria.Op.EQ, id); sc.addAnd("deleted", SearchCriteria.Op.NULL); - List lbVOs = m_usageLoadBalancerPolicyDao.search(sc, null); + List lbVOs = _usageLoadBalancerPolicyDao.search(sc, null); if (lbVOs.size() > 1) { s_logger.warn("More that one usage entry for load balancer policy: " + id + " assigned to account: " + event.getAccountId() + "; marking them all as deleted..."); @@ -1581,7 +1575,7 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna s_logger.debug("deleting load balancer policy: " + lbVO.getId() + " from account: " + lbVO.getAccountId()); } lbVO.setDeleted(event.getCreateDate()); // there really shouldn't be more than one - m_usageLoadBalancerPolicyDao.update(lbVO); + _usageLoadBalancerPolicyDao.update(lbVO); } } } @@ -1597,15 +1591,15 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna s_logger.debug("Creating port forwarding rule : " + id + " for account: " + event.getAccountId()); } zoneId = event.getZoneId(); - Account acct = m_accountDao.findByIdIncludingRemoved(event.getAccountId()); + Account acct = _accountDao.findByIdIncludingRemoved(event.getAccountId()); UsagePortForwardingRuleVO pfVO = new UsagePortForwardingRuleVO(id, zoneId, event.getAccountId(), acct.getDomainId(), event.getCreateDate(), null); - m_usagePortForwardingRuleDao.persist(pfVO); + _usagePortForwardingRuleDao.persist(pfVO); } else if (EventTypes.EVENT_NET_RULE_DELETE.equals(event.getType())) { - SearchCriteria sc = m_usagePortForwardingRuleDao.createSearchCriteria(); + SearchCriteria sc = _usagePortForwardingRuleDao.createSearchCriteria(); sc.addAnd("accountId", SearchCriteria.Op.EQ, event.getAccountId()); sc.addAnd("id", SearchCriteria.Op.EQ, id); sc.addAnd("deleted", SearchCriteria.Op.NULL); - List pfVOs = m_usagePortForwardingRuleDao.search(sc, null); + List pfVOs = _usagePortForwardingRuleDao.search(sc, null); if (pfVOs.size() > 1) { s_logger.warn("More that one usage entry for port forwarding rule: " + id + " assigned to account: " + event.getAccountId() + "; marking them all as deleted..."); @@ -1615,7 +1609,7 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna s_logger.debug("deleting port forwarding rule: " + pfVO.getId() + " from account: " + pfVO.getAccountId()); } pfVO.setDeleted(event.getCreateDate()); // there really shouldn't be more than one - m_usagePortForwardingRuleDao.update(pfVO); + _usagePortForwardingRuleDao.update(pfVO); } } } @@ -1638,19 +1632,19 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna s_logger.debug("Creating networking offering: " + networkOfferingId + " for Vm: " + vmId + " for account: " + event.getAccountId()); } zoneId = event.getZoneId(); - Account acct = m_accountDao.findByIdIncludingRemoved(event.getAccountId()); + Account acct = _accountDao.findByIdIncludingRemoved(event.getAccountId()); boolean isDefault = (event.getSize() == 1) ? true : false; UsageNetworkOfferingVO networkOffering = new UsageNetworkOfferingVO(zoneId, event.getAccountId(), acct.getDomainId(), vmId, networkOfferingId, nicId, isDefault, event.getCreateDate(), null); - m_usageNetworkOfferingDao.persist(networkOffering); + _usageNetworkOfferingDao.persist(networkOffering); } else if (EventTypes.EVENT_NETWORK_OFFERING_DELETE.equals(event.getType()) || EventTypes.EVENT_NETWORK_OFFERING_REMOVE.equals(event.getType())) { - SearchCriteria sc = m_usageNetworkOfferingDao.createSearchCriteria(); + SearchCriteria sc = _usageNetworkOfferingDao.createSearchCriteria(); sc.addAnd("accountId", SearchCriteria.Op.EQ, event.getAccountId()); sc.addAnd("vmInstanceId", SearchCriteria.Op.EQ, vmId); sc.addAnd("nicId", SearchCriteria.Op.EQ, nicId); sc.addAnd("networkOfferingId", SearchCriteria.Op.EQ, networkOfferingId); sc.addAnd("deleted", SearchCriteria.Op.NULL); - List noVOs = m_usageNetworkOfferingDao.search(sc, null); + List noVOs = _usageNetworkOfferingDao.search(sc, null); if (noVOs.size() > 1) { s_logger.warn("More that one usage entry for networking offering: " + networkOfferingId + " for Vm: " + vmId + " assigned to account: " + event.getAccountId() + "; marking them all as deleted..."); @@ -1660,7 +1654,7 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna s_logger.debug("deleting network offering: " + noVO.getNetworkOfferingId() + " from Vm: " + noVO.getVmInstanceId()); } noVO.setDeleted(event.getCreateDate()); // there really shouldn't be more than one - m_usageNetworkOfferingDao.update(noVO); + _usageNetworkOfferingDao.update(noVO); } } } @@ -1675,16 +1669,16 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna if (s_logger.isDebugEnabled()) { s_logger.debug("Creating VPN user: " + userId + " for account: " + event.getAccountId()); } - Account acct = m_accountDao.findByIdIncludingRemoved(event.getAccountId()); + Account acct = _accountDao.findByIdIncludingRemoved(event.getAccountId()); String userName = event.getResourceName(); UsageVPNUserVO vpnUser = new UsageVPNUserVO(zoneId, event.getAccountId(), acct.getDomainId(), userId, userName, event.getCreateDate(), null); - m_usageVPNUserDao.persist(vpnUser); + _usageVPNUserDao.persist(vpnUser); } else if (EventTypes.EVENT_VPN_USER_REMOVE.equals(event.getType())) { - SearchCriteria sc = m_usageVPNUserDao.createSearchCriteria(); + SearchCriteria sc = _usageVPNUserDao.createSearchCriteria(); sc.addAnd("accountId", SearchCriteria.Op.EQ, event.getAccountId()); sc.addAnd("userId", SearchCriteria.Op.EQ, userId); sc.addAnd("deleted", SearchCriteria.Op.NULL); - List vuVOs = m_usageVPNUserDao.search(sc, null); + List vuVOs = _usageVPNUserDao.search(sc, null); if (vuVOs.size() > 1) { s_logger.warn("More that one usage entry for vpn user: " + userId + " assigned to account: " + event.getAccountId() + "; marking them all as deleted..."); } @@ -1693,7 +1687,7 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna s_logger.debug("deleting vpn user: " + vuVO.getUserId()); } vuVO.setDeleted(event.getCreateDate()); // there really shouldn't be more than one - m_usageVPNUserDao.update(vuVO); + _usageVPNUserDao.update(vuVO); } } } @@ -1710,16 +1704,16 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna s_logger.debug("Assigning : security group" + sgId + " to Vm: " + vmId + " for account: " + event.getAccountId()); } zoneId = event.getZoneId(); - Account acct = m_accountDao.findByIdIncludingRemoved(event.getAccountId()); + Account acct = _accountDao.findByIdIncludingRemoved(event.getAccountId()); UsageSecurityGroupVO securityGroup = new UsageSecurityGroupVO(zoneId, event.getAccountId(), acct.getDomainId(), vmId, sgId, event.getCreateDate(), null); - m_usageSecurityGroupDao.persist(securityGroup); + _usageSecurityGroupDao.persist(securityGroup); } else if (EventTypes.EVENT_SECURITY_GROUP_REMOVE.equals(event.getType())) { - SearchCriteria sc = m_usageSecurityGroupDao.createSearchCriteria(); + SearchCriteria sc = _usageSecurityGroupDao.createSearchCriteria(); sc.addAnd("accountId", SearchCriteria.Op.EQ, event.getAccountId()); sc.addAnd("vmInstanceId", SearchCriteria.Op.EQ, vmId); sc.addAnd("securityGroupId", SearchCriteria.Op.EQ, sgId); sc.addAnd("deleted", SearchCriteria.Op.NULL); - List sgVOs = m_usageSecurityGroupDao.search(sc, null); + List sgVOs = _usageSecurityGroupDao.search(sc, null); if (sgVOs.size() > 1) { s_logger.warn("More that one usage entry for security group: " + sgId + " for Vm: " + vmId + " assigned to account: " + event.getAccountId() + "; marking them all as deleted..."); @@ -1729,7 +1723,7 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna s_logger.debug("deleting security group: " + sgVO.getSecurityGroupId() + " from Vm: " + sgVO.getVmInstanceId()); } sgVO.setDeleted(event.getCreateDate()); // there really shouldn't be more than one - m_usageSecurityGroupDao.update(sgVO); + _usageSecurityGroupDao.update(sgVO); } } } @@ -1742,10 +1736,10 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna Long accountId = event.getAccountId(); long size = event.getSize(); Date created = event.getCreateDate(); - Account acct = m_accountDao.findByIdIncludingRemoved(event.getAccountId()); + Account acct = _accountDao.findByIdIncludingRemoved(event.getAccountId()); Long domainId = acct.getDomainId(); UsageVMSnapshotVO vsVO = new UsageVMSnapshotVO(volumeId, zoneId, accountId, domainId, vmId, offeringId, size, created, null); - m_usageVMSnapshotDao.persist(vsVO); + _usageVMSnapshotDao.persist(vsVO); } private class Heartbeat extends ManagedContextRunnable { @@ -1753,7 +1747,7 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna protected void runInContext() { TransactionLegacy usageTxn = TransactionLegacy.open(TransactionLegacy.USAGE_DB); try { - if (!m_heartbeatLock.lock(3)) { // 3 second timeout + if (!_heartbeatLock.lock(3)) { // 3 second timeout if (s_logger.isTraceEnabled()) s_logger.trace("Heartbeat lock is in use by others, returning true as someone else will take over the job if required"); return; @@ -1761,24 +1755,24 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna try { // check for one-off jobs - UsageJobVO nextJob = m_usageJobDao.getNextImmediateJob(); + UsageJobVO nextJob = _usageJobDao.getNextImmediateJob(); if (nextJob != null) { - if (m_hostname.equals(nextJob.getHost()) && (m_pid == nextJob.getPid().intValue())) { + if (_hostname.equals(nextJob.getHost()) && (_pid == nextJob.getPid().intValue())) { updateJob(nextJob.getId(), null, null, null, UsageJobVO.JOB_SCHEDULED); scheduleParse(); } } - Long jobId = m_usageJobDao.checkHeartbeat(m_hostname, m_pid, m_aggregationDuration); + Long jobId = _usageJobDao.checkHeartbeat(_hostname, _pid, _aggregationDuration); if (jobId != null) { // if I'm taking over the job...see how long it's been since the last job, and if it's more than the // aggregation range...do a one off job to catch up. However, only do this if we are more than half // the aggregation range away from executing the next job long now = System.currentTimeMillis(); - long timeToJob = m_jobExecTime.getTimeInMillis() - now; + long timeToJob = _jobExecTime.getTimeInMillis() - now; long timeSinceJob = 0; - long aggregationDurationMillis = m_aggregationDuration * 60 * 1000; - long lastSuccess = m_usageJobDao.getLastJobSuccessDateMillis(); + long aggregationDurationMillis = _aggregationDuration * 60 * 1000; + long lastSuccess = _usageJobDao.getLastJobSuccessDateMillis(); if (lastSuccess > 0) { timeSinceJob = now - lastSuccess; } @@ -1787,19 +1781,19 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna if (timeToJob > (aggregationDurationMillis / 2)) { if (s_logger.isDebugEnabled()) { s_logger.debug("it's been " + timeSinceJob + " ms since last usage job and " + timeToJob + - " ms until next job, scheduling an immediate job to catch up (aggregation duration is " + m_aggregationDuration + " minutes)"); + " ms until next job, scheduling an immediate job to catch up (aggregation duration is " + _aggregationDuration + " minutes)"); } scheduleParse(); } } - boolean changeOwner = updateJob(jobId, m_hostname, Integer.valueOf(m_pid), new Date(), UsageJobVO.JOB_NOT_SCHEDULED); + boolean changeOwner = updateJob(jobId, _hostname, Integer.valueOf(_pid), new Date(), UsageJobVO.JOB_NOT_SCHEDULED); if (changeOwner) { - deleteOneOffJobs(m_hostname, m_pid); + deleteOneOffJobs(_hostname, _pid); } } } finally { - m_heartbeatLock.unlock(); + _heartbeatLock.unlock(); } } catch (Exception ex) { s_logger.error("error in heartbeat", ex); @@ -1816,12 +1810,12 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna txn.start(); // take over the job, setting our hostname/pid/heartbeat time - UsageJobVO job = m_usageJobDao.lockRow(jobId, Boolean.TRUE); + UsageJobVO job = _usageJobDao.lockRow(jobId, Boolean.TRUE); if (!job.getHost().equals(hostname) || !job.getPid().equals(pid)) { changeOwner = true; } - UsageJobVO jobForUpdate = m_usageJobDao.createForUpdate(); + UsageJobVO jobForUpdate = _usageJobDao.createForUpdate(); if (hostname != null) { jobForUpdate.setHost(hostname); } @@ -1832,7 +1826,7 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna jobForUpdate.setHeartbeat(heartbeat); } jobForUpdate.setScheduled(scheduled); - m_usageJobDao.update(job.getId(), jobForUpdate); + _usageJobDao.update(job.getId(), jobForUpdate); txn.commit(); } catch (Exception dbEx) { @@ -1844,15 +1838,15 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna @DB protected void deleteOneOffJobs(String hostname, int pid) { - SearchCriteria sc = m_usageJobDao.createSearchCriteria(); - SearchCriteria ssc = m_usageJobDao.createSearchCriteria(); + SearchCriteria sc = _usageJobDao.createSearchCriteria(); + SearchCriteria ssc = _usageJobDao.createSearchCriteria(); ssc.addOr("host", SearchCriteria.Op.NEQ, hostname); ssc.addOr("pid", SearchCriteria.Op.NEQ, pid); sc.addAnd("host", SearchCriteria.Op.SC, ssc); sc.addAnd("endMillis", SearchCriteria.Op.EQ, Long.valueOf(0)); sc.addAnd("jobType", SearchCriteria.Op.EQ, Integer.valueOf(UsageJobVO.JOB_TYPE_SINGLE)); sc.addAnd("scheduled", SearchCriteria.Op.EQ, Integer.valueOf(0)); - m_usageJobDao.expunge(sc); + _usageJobDao.expunge(sc); } } diff --git a/usage/src/com/cloud/usage/UsageSanityChecker.java b/usage/src/com/cloud/usage/UsageSanityChecker.java index 34032bcbd74..5e6123bc777 100644 --- a/usage/src/com/cloud/usage/UsageSanityChecker.java +++ b/usage/src/com/cloud/usage/UsageSanityChecker.java @@ -25,191 +25,182 @@ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.Logger; import com.cloud.utils.db.TransactionLegacy; +/** + * This class must not be used concurrently because its state changes often during + * execution in a non synchronized way + */ public class UsageSanityChecker { - private StringBuffer errors; - private String lastCheckId = ""; - private final String lastCheckFile = "/usr/local/libexec/sanity-check-last-id"; + protected static final Logger s_logger = Logger.getLogger(UsageSanityChecker.class); + protected static final int DEFAULT_AGGREGATION_RANGE = 1440; + protected StringBuilder errors; + protected List checkCases; + protected String lastCheckFile = "/usr/local/libexec/sanity-check-last-id"; + protected String lastCheckId = ""; + protected int lastId = -1; + protected int maxId = -1; + protected Connection conn; - private boolean checkMaxUsage(Connection conn) throws SQLException { + protected void reset() { + errors = new StringBuilder(); + checkCases = new ArrayList(); + } - PreparedStatement pstmt = conn.prepareStatement("SELECT value FROM `cloud`.`configuration` where name = 'usage.stats.job.aggregation.range'"); - ResultSet rs = pstmt.executeQuery(); + protected boolean checkItemCountByPstmt() throws SQLException { + boolean checkOk = true; - int aggregationRange = 1440; - if (rs.next()) { - aggregationRange = rs.getInt(1); - } else { - System.out.println("Failed to retrieve aggregation range. Using default : " + aggregationRange); + for(CheckCase check : checkCases) { + checkOk &= checkItemCountByPstmt(check); + } + + return checkOk; + } + + protected boolean checkItemCountByPstmt(CheckCase checkCase) throws SQLException { + List pstmt2Close = new ArrayList(); + boolean checkOk = true; + + /* + * Check for item usage records which are created after it is removed + */ + PreparedStatement pstmt; + try { + pstmt = conn.prepareStatement(checkCase.sqlTemplate); + if(checkCase.checkId) { + pstmt.setInt(1, lastId); + pstmt.setInt(2, maxId); + } + + pstmt2Close.add(pstmt); + ResultSet rs = pstmt.executeQuery(); + if (rs.next() && (rs.getInt(1) > 0)) { + errors.append(String.format("Error: Found %s %s\n", rs.getInt(1), checkCase.itemName)); + checkOk = false; + } + } catch (SQLException e) { + throw e; + } finally { + TransactionLegacy.closePstmts(pstmt2Close); + } + return checkOk; + } + + protected void checkMaxUsage() throws SQLException { + int aggregationRange = DEFAULT_AGGREGATION_RANGE; + List pstmt2Close = new ArrayList(); + try { + PreparedStatement pstmt = conn.prepareStatement( + "SELECT value FROM `cloud`.`configuration` where name = 'usage.stats.job.aggregation.range'"); + pstmt2Close.add(pstmt); + ResultSet rs = pstmt.executeQuery(); + + if (rs.next()) { + aggregationRange = rs.getInt(1); + } else { + s_logger.debug("Failed to retrieve aggregation range. Using default : " + aggregationRange); + } + } catch (SQLException e) { + throw e; + } finally { + TransactionLegacy.closePstmts(pstmt2Close); } int aggregationHours = aggregationRange / 60; - /* - * Check for usage records with raw_usage > aggregationHours - */ - pstmt = - conn.prepareStatement("SELECT count(*) FROM `cloud_usage`.`cloud_usage` cu where usage_type not in (4,5) and raw_usage > " + aggregationHours + lastCheckId); - rs = pstmt.executeQuery(); - if (rs.next() && (rs.getInt(1) > 0)) { - errors.append("Error: Found " + rs.getInt(1) + " usage records with raw_usage > " + aggregationHours); - errors.append("\n"); - return false; - } - return true; + addCheckCase("SELECT count(*) FROM `cloud_usage`.`cloud_usage` cu where usage_type not in (4,5) and raw_usage > " + + aggregationHours, + "usage records with raw_usage > " + aggregationHours, + lastCheckId); } - private boolean checkVmUsage(Connection conn) throws SQLException { - boolean success = true; - /* - * Check for Vm usage records which are created after the vm is destroyed - */ - PreparedStatement pstmt = - conn.prepareStatement("select count(*) from cloud_usage.cloud_usage cu inner join cloud.vm_instance vm where vm.type = 'User' " + - "and cu.usage_type in (1 , 2) and cu.usage_id = vm.id and cu.start_date > vm.removed" + lastCheckId); - ResultSet rs = pstmt.executeQuery(); - if (rs.next() && (rs.getInt(1) > 0)) { - errors.append("Error: Found " + rs.getInt(1) + " Vm usage records which are created after Vm is destroyed"); - errors.append("\n"); - success = false; - } + protected void checkVmUsage() { + addCheckCase("select count(*) from cloud_usage.cloud_usage cu inner join cloud.vm_instance vm " + + "where vm.type = 'User' and cu.usage_type in (1 , 2) " + + "and cu.usage_id = vm.id and cu.start_date > vm.removed ", + "Vm usage records which are created after Vm is destroyed", + lastCheckId); - /* - * Check for Vms which have multiple running vm records in helper table - */ - pstmt = - conn.prepareStatement("select sum(cnt) from (select count(*) as cnt from cloud_usage.usage_vm_instance where usage_type =1 " - + "and end_date is null group by vm_instance_id having count(vm_instance_id) > 1) c ;"); - rs = pstmt.executeQuery(); - if (rs.next() && (rs.getInt(1) > 0)) { - errors.append("Error: Found " + rs.getInt(1) + " duplicate running Vm entries in vm usage helper table"); - errors.append("\n"); - success = false; - } + addCheckCase("select sum(cnt) from (select count(*) as cnt from cloud_usage.usage_vm_instance " + + "where usage_type =1 and end_date is null group by vm_instance_id " + + "having count(vm_instance_id) > 1) c ;", + "duplicate running Vm entries in vm usage helper table"); - /* - * Check for Vms which have multiple allocated vm records in helper table - */ - pstmt = - conn.prepareStatement("select sum(cnt) from (select count(*) as cnt from cloud_usage.usage_vm_instance where usage_type =2 " - + "and end_date is null group by vm_instance_id having count(vm_instance_id) > 1) c ;"); - rs = pstmt.executeQuery(); - if (rs.next() && (rs.getInt(1) > 0)) { - errors.append("Error: Found " + rs.getInt(1) + " duplicate allocated Vm entries in vm usage helper table"); - errors.append("\n"); - success = false; - } + addCheckCase("select sum(cnt) from (select count(*) as cnt from cloud_usage.usage_vm_instance " + + "where usage_type =2 and end_date is null group by vm_instance_id " + + "having count(vm_instance_id) > 1) c ;", + "duplicate allocated Vm entries in vm usage helper table"); - /* - * Check for Vms which have running vm entry without allocated vm entry in helper table - */ - pstmt = - conn.prepareStatement("select count(vm_instance_id) from cloud_usage.usage_vm_instance o where o.end_date is null and o.usage_type=1 and not exists " - + "(select 1 from cloud_usage.usage_vm_instance i where i.vm_instance_id=o.vm_instance_id and usage_type=2 and i.end_date is null)"); - rs = pstmt.executeQuery(); - if (rs.next() && (rs.getInt(1) > 0)) { - errors.append("Error: Found " + rs.getInt(1) + " running Vm entries without corresponding allocated entries in vm usage helper table"); - errors.append("\n"); - success = false; - } - return success; + addCheckCase("select count(vm_instance_id) from cloud_usage.usage_vm_instance o " + + "where o.end_date is null and o.usage_type=1 and not exists " + + "(select 1 from cloud_usage.usage_vm_instance i where " + + "i.vm_instance_id=o.vm_instance_id and usage_type=2 and i.end_date is null)", + "running Vm entries without corresponding allocated entries in vm usage helper table"); } - private boolean checkVolumeUsage(Connection conn) throws SQLException { - boolean success = true; - /* - * Check for Volume usage records which are created after the volume is removed - */ - PreparedStatement pstmt = - conn.prepareStatement("select count(*) from cloud_usage.cloud_usage cu inner join cloud.volumes v " + - "where cu.usage_type = 6 and cu.usage_id = v.id and cu.start_date > v.removed" + lastCheckId); - ResultSet rs = pstmt.executeQuery(); - if (rs.next() && (rs.getInt(1) > 0)) { - errors.append("Error: Found " + rs.getInt(1) + " volume usage records which are created after volume is removed"); - errors.append("\n"); - success = false; - } + protected void checkVolumeUsage() { + addCheckCase("select count(*) from cloud_usage.cloud_usage cu inner join cloud.volumes v where " + + "cu.usage_type = 6 and cu.usage_id = v.id and cu.start_date > v.removed ", + "volume usage records which are created after volume is removed", + lastCheckId); - /* - * Check for duplicate records in volume usage helper table - */ - pstmt = - conn.prepareStatement("select sum(cnt) from (select count(*) as cnt from cloud_usage.usage_volume " - + "where deleted is null group by id having count(id) > 1) c;"); - rs = pstmt.executeQuery(); - if (rs.next() && (rs.getInt(1) > 0)) { - errors.append("Error: Found " + rs.getInt(1) + " duplicate records is volume usage helper table"); - errors.append("\n"); - success = false; - } - return success; + addCheckCase("select sum(cnt) from (select count(*) as cnt from cloud_usage.usage_volume " + + "where deleted is null group by id having count(id) > 1) c;", + "duplicate records in volume usage helper table"); } - private boolean checkTemplateISOUsage(Connection conn) throws SQLException { - /* - * Check for Template/ISO usage records which are created after it is removed - */ - PreparedStatement pstmt = - conn.prepareStatement("select count(*) from cloud_usage.cloud_usage cu inner join cloud.template_zone_ref tzr " + - "where cu.usage_id = tzr.template_id and cu.zone_id = tzr.zone_id and cu.usage_type in (7,8) and cu.start_date > tzr.removed" + lastCheckId); - ResultSet rs = pstmt.executeQuery(); - if (rs.next() && (rs.getInt(1) > 0)) { - errors.append("Error: Found " + rs.getInt(1) + " template/ISO usage records which are created after it is removed"); - errors.append("\n"); - return false; - } - return true; + protected void checkTemplateISOUsage() { + addCheckCase("select count(*) from cloud_usage.cloud_usage cu inner join cloud.template_zone_ref tzr where " + + "cu.usage_id = tzr.template_id and cu.zone_id = tzr.zone_id and cu.usage_type in (7,8) and cu.start_date > tzr.removed ", + "template/ISO usage records which are created after it is removed", + lastCheckId); } - private boolean checkSnapshotUsage(Connection conn) throws SQLException { - /* - * Check for snapshot usage records which are created after snapshot is removed - */ - PreparedStatement pstmt = - conn.prepareStatement("select count(*) from cloud_usage.cloud_usage cu inner join cloud.snapshots s " + - "where cu.usage_id = s.id and cu.usage_type = 9 and cu.start_date > s.removed" + lastCheckId); - ResultSet rs = pstmt.executeQuery(); - if (rs.next() && (rs.getInt(1) > 0)) { - errors.append("Error: Found " + rs.getInt(1) + " snapshot usage records which are created after snapshot is removed"); - errors.append("\n"); - return false; - } - return true; + protected void checkSnapshotUsage() { + addCheckCase("select count(*) from cloud_usage.cloud_usage cu inner join cloud.snapshots s where " + + "cu.usage_id = s.id and cu.usage_type = 9 and cu.start_date > s.removed ", + "snapshot usage records which are created after it is removed", + lastCheckId); } - public String runSanityCheck() throws SQLException { + protected void readLastCheckId(){ + BufferedReader reader = null; try { - BufferedReader reader = new BufferedReader(new FileReader(lastCheckFile)); - String last_id = null; - if ((reader != null) && (last_id = reader.readLine()) != null) { - int lastId = Integer.parseInt(last_id); - if (lastId > 0) { - lastCheckId = " and cu.id > " + last_id; - } + reader = new BufferedReader(new FileReader(lastCheckFile)); + String lastIdText = null; + lastId = -1; + if ((reader != null) && (lastIdText = reader.readLine()) != null) { + lastId = Integer.parseInt(lastIdText); + } + } catch (IOException e) { + s_logger.error(e); + } finally { + try { + reader.close(); + } catch (IOException e) { + s_logger.error(e); } - reader.close(); - } catch (Exception e) { - // Error while reading last check id } + } - Connection conn = TransactionLegacy.getStandaloneConnection(); - int maxId = 0; + protected void readMaxId() throws SQLException { PreparedStatement pstmt = conn.prepareStatement("select max(id) from cloud_usage.cloud_usage"); ResultSet rs = pstmt.executeQuery(); + maxId = -1; if (rs.next() && (rs.getInt(1) > 0)) { maxId = rs.getInt(1); - lastCheckId += " and cu.id <= " + maxId; + lastCheckId += " and cu.id <= ?"; } - errors = new StringBuffer(); - checkMaxUsage(conn); - checkVmUsage(conn); - checkVolumeUsage(conn); - checkTemplateISOUsage(conn); - checkSnapshotUsage(conn); - FileWriter fstream; + } + + protected void updateNewMaxId() { + FileWriter fstream = null; try { fstream = new FileWriter(lastCheckFile); BufferedWriter out = new BufferedWriter(fstream); @@ -217,20 +208,89 @@ public class UsageSanityChecker { out.close(); } catch (IOException e) { // Error while writing last check id + } finally { + if (fstream != null) { + try { + fstream.close(); + } catch (IOException e) { + s_logger.error(e); + } + } } + } + + public String runSanityCheck() throws SQLException { + + readLastCheckId(); + if (lastId > 0) { + lastCheckId = " and cu.id > ?"; + } + + conn = getConnection(); + readMaxId(); + + reset(); + + checkMaxUsage(); + checkVmUsage(); + checkVolumeUsage(); + checkTemplateISOUsage(); + checkSnapshotUsage(); + + checkItemCountByPstmt(); + return errors.toString(); } + /** + * Local acquisition of {@link Connection} to remove static cling + * @return + */ + protected Connection getConnection() { + return TransactionLegacy.getStandaloneConnection(); + } + public static void main(String args[]) { UsageSanityChecker usc = new UsageSanityChecker(); String sanityErrors; try { sanityErrors = usc.runSanityCheck(); if (sanityErrors.length() > 0) { - System.out.println(sanityErrors.toString()); + s_logger.error(sanityErrors.toString()); } } catch (SQLException e) { e.printStackTrace(); } } + + protected void addCheckCase(String sqlTemplate, String itemName, String lastCheckId) { + checkCases.add(new CheckCase(sqlTemplate, itemName, lastCheckId)); + } + + protected void addCheckCase(String sqlTemplate, String itemName) { + checkCases.add(new CheckCase(sqlTemplate, itemName)); + } } + + +/** + * Just an abstraction of the kind of check to repeat across these cases + * encapsulating what change for each specific case + */ +class CheckCase { + public String sqlTemplate; + public String itemName; + public boolean checkId = false; + + public CheckCase(String sqlTemplate, String itemName, String lastCheckId) { + checkId = true; + this.sqlTemplate = sqlTemplate + lastCheckId; + this.itemName = itemName; + } + + public CheckCase(String sqlTemplate, String itemName) { + checkId = false; + this.sqlTemplate = sqlTemplate; + this.itemName = itemName; + } +} \ No newline at end of file diff --git a/usage/src/com/cloud/usage/parser/IPAddressUsageParser.java b/usage/src/com/cloud/usage/parser/IPAddressUsageParser.java index 6715bc84245..adeff01dae4 100644 --- a/usage/src/com/cloud/usage/parser/IPAddressUsageParser.java +++ b/usage/src/com/cloud/usage/parser/IPAddressUsageParser.java @@ -41,8 +41,8 @@ import com.cloud.utils.Pair; public class IPAddressUsageParser { public static final Logger s_logger = Logger.getLogger(IPAddressUsageParser.class.getName()); - private static UsageDao m_usageDao; - private static UsageIPAddressDao m_usageIPAddressDao; + private static UsageDao s_usageDao; + private static UsageIPAddressDao s_usageIPAddressDao; @Inject private UsageDao _usageDao; @@ -51,8 +51,8 @@ public class IPAddressUsageParser { @PostConstruct void init() { - m_usageDao = _usageDao; - m_usageIPAddressDao = _usageIPAddressDao; + s_usageDao = _usageDao; + s_usageIPAddressDao = _usageIPAddressDao; } public static boolean parse(AccountVO account, Date startDate, Date endDate) { @@ -68,7 +68,7 @@ public class IPAddressUsageParser { // - look for an entry for accountId with end date in the given range // - look for an entry for accountId with end date null (currently running vm or owned IP) // - look for an entry for accountId with start date before given range *and* end date after given range - List usageIPAddress = m_usageIPAddressDao.getUsageRecords(account.getId(), account.getDomainId(), startDate, endDate); + List usageIPAddress = s_usageIPAddressDao.getUsageRecords(account.getId(), account.getDomainId(), startDate, endDate); if (usageIPAddress.isEmpty()) { s_logger.debug("No IP Address usage for this period"); @@ -132,7 +132,7 @@ public class IPAddressUsageParser { usageDataMap.put(key, ipUsageInfo); } - private static void createUsageRecord(long zoneId, long runningTime, Date startDate, Date endDate, AccountVO account, long IpId, String IPAddress, + private static void createUsageRecord(long zoneId, long runningTime, Date startDate, Date endDate, AccountVO account, long ipId, String ipAddress, boolean isSourceNat, boolean isSystem) { if (s_logger.isDebugEnabled()) { s_logger.debug("Total usage time " + runningTime + "ms"); @@ -144,31 +144,31 @@ public class IPAddressUsageParser { String usageDisplay = dFormat.format(usage); if (s_logger.isDebugEnabled()) { - s_logger.debug("Creating IP usage record with id: " + IpId + ", usage: " + usageDisplay + ", startDate: " + startDate + ", endDate: " + endDate + + s_logger.debug("Creating IP usage record with id: " + ipId + ", usage: " + usageDisplay + ", startDate: " + startDate + ", endDate: " + endDate + ", for account: " + account.getId()); } - String usageDesc = "IPAddress: " + IPAddress; + String usageDesc = "IPAddress: " + ipAddress; // Create the usage record UsageVO usageRecord = - new UsageVO(zoneId, account.getAccountId(), account.getDomainId(), usageDesc, usageDisplay + " Hrs", UsageTypes.IP_ADDRESS, new Double(usage), IpId, + new UsageVO(zoneId, account.getAccountId(), account.getDomainId(), usageDesc, usageDisplay + " Hrs", UsageTypes.IP_ADDRESS, new Double(usage), ipId, (isSystem ? 1 : 0), (isSourceNat ? "SourceNat" : ""), startDate, endDate); - m_usageDao.persist(usageRecord); + s_usageDao.persist(usageRecord); } private static class IpInfo { private long zoneId; - private long IpId; - private String IPAddress; + private long ipId; + private String ipAddress; private boolean isSourceNat; private boolean isSystem; - public IpInfo(long zoneId, long IpId, String IPAddress, boolean isSourceNat, boolean isSystem) { + public IpInfo(long zoneId, long ipId, String ipAddress, boolean isSourceNat, boolean isSystem) { this.zoneId = zoneId; - this.IpId = IpId; - this.IPAddress = IPAddress; + this.ipId = ipId; + this.ipAddress = ipAddress; this.isSourceNat = isSourceNat; this.isSystem = isSystem; } @@ -178,11 +178,11 @@ public class IPAddressUsageParser { } public long getIpId() { - return IpId; + return ipId; } public String getIPAddress() { - return IPAddress; + return ipAddress; } public boolean isSourceNat() { diff --git a/usage/src/com/cloud/usage/parser/LoadBalancerUsageParser.java b/usage/src/com/cloud/usage/parser/LoadBalancerUsageParser.java index 387cae3606d..1b813b7a845 100644 --- a/usage/src/com/cloud/usage/parser/LoadBalancerUsageParser.java +++ b/usage/src/com/cloud/usage/parser/LoadBalancerUsageParser.java @@ -41,8 +41,8 @@ import com.cloud.utils.Pair; public class LoadBalancerUsageParser { public static final Logger s_logger = Logger.getLogger(LoadBalancerUsageParser.class.getName()); - private static UsageDao m_usageDao; - private static UsageLoadBalancerPolicyDao m_usageLoadBalancerPolicyDao; + private static UsageDao s_usageDao; + private static UsageLoadBalancerPolicyDao s_usageLoadBalancerPolicyDao; @Inject private UsageDao _usageDao; @@ -51,8 +51,8 @@ public class LoadBalancerUsageParser { @PostConstruct void init() { - m_usageDao = _usageDao; - m_usageLoadBalancerPolicyDao = _usageLoadBalancerPolicyDao; + s_usageDao = _usageDao; + s_usageLoadBalancerPolicyDao = _usageLoadBalancerPolicyDao; } public static boolean parse(AccountVO account, Date startDate, Date endDate) { @@ -68,7 +68,7 @@ public class LoadBalancerUsageParser { // - look for an entry for accountId with end date in the given range // - look for an entry for accountId with end date null (currently running vm or owned IP) // - look for an entry for accountId with start date before given range *and* end date after given range - List usageLBs = m_usageLoadBalancerPolicyDao.getUsageRecords(account.getId(), account.getDomainId(), startDate, endDate, false, 0); + List usageLBs = s_usageLoadBalancerPolicyDao.getUsageRecords(account.getId(), account.getDomainId(), startDate, endDate, false, 0); if (usageLBs.isEmpty()) { s_logger.debug("No load balancer usage events for this period"); @@ -152,7 +152,7 @@ public class LoadBalancerUsageParser { UsageVO usageRecord = new UsageVO(zoneId, account.getId(), account.getDomainId(), usageDesc, usageDisplay + " Hrs", type, new Double(usage), null, null, null, null, lbId, null, startDate, endDate); - m_usageDao.persist(usageRecord); + s_usageDao.persist(usageRecord); } private static class LBInfo { diff --git a/usage/src/com/cloud/usage/parser/NetworkOfferingUsageParser.java b/usage/src/com/cloud/usage/parser/NetworkOfferingUsageParser.java index 6aa61d6f608..4a5a1d2e58c 100644 --- a/usage/src/com/cloud/usage/parser/NetworkOfferingUsageParser.java +++ b/usage/src/com/cloud/usage/parser/NetworkOfferingUsageParser.java @@ -41,8 +41,8 @@ import com.cloud.utils.Pair; public class NetworkOfferingUsageParser { public static final Logger s_logger = Logger.getLogger(NetworkOfferingUsageParser.class.getName()); - private static UsageDao m_usageDao; - private static UsageNetworkOfferingDao m_usageNetworkOfferingDao; + private static UsageDao s_usageDao; + private static UsageNetworkOfferingDao s_usageNetworkOfferingDao; @Inject private UsageDao _usageDao; @@ -51,8 +51,8 @@ public class NetworkOfferingUsageParser { @PostConstruct void init() { - m_usageDao = _usageDao; - m_usageNetworkOfferingDao = _usageNetworkOfferingDao; + s_usageDao = _usageDao; + s_usageNetworkOfferingDao = _usageNetworkOfferingDao; } public static boolean parse(AccountVO account, Date startDate, Date endDate) { @@ -68,7 +68,7 @@ public class NetworkOfferingUsageParser { // - look for an entry for accountId with end date in the given range // - look for an entry for accountId with end date null (currently running vm or owned IP) // - look for an entry for accountId with start date before given range *and* end date after given range - List usageNOs = m_usageNetworkOfferingDao.getUsageRecords(account.getId(), account.getDomainId(), startDate, endDate, false, 0); + List usageNOs = s_usageNetworkOfferingDao.getUsageRecords(account.getId(), account.getDomainId(), startDate, endDate, false, 0); if (usageNOs.isEmpty()) { s_logger.debug("No NetworkOffering usage events for this period"); @@ -154,14 +154,14 @@ public class NetworkOfferingUsageParser { UsageVO usageRecord = new UsageVO(zoneId, account.getId(), account.getDomainId(), usageDesc, usageDisplay + " Hrs", type, new Double(usage), vmId, null, noId, null, defaultNic, null, startDate, endDate); - m_usageDao.persist(usageRecord); + s_usageDao.persist(usageRecord); } private static class NOInfo { - private long vmId; - private long zoneId; - private long noId; - private boolean isDefault; + private final long vmId; + private final long zoneId; + private final long noId; + private final boolean isDefault; public NOInfo(long vmId, long zoneId, long noId, boolean isDefault) { this.vmId = vmId; diff --git a/usage/src/com/cloud/usage/parser/NetworkUsageParser.java b/usage/src/com/cloud/usage/parser/NetworkUsageParser.java index 5dec1e01420..a54cb3e466b 100644 --- a/usage/src/com/cloud/usage/parser/NetworkUsageParser.java +++ b/usage/src/com/cloud/usage/parser/NetworkUsageParser.java @@ -41,8 +41,8 @@ import com.cloud.utils.db.SearchCriteria; public class NetworkUsageParser { public static final Logger s_logger = Logger.getLogger(NetworkUsageParser.class.getName()); - private static UsageDao m_usageDao; - private static UsageNetworkDao m_usageNetworkDao; + private static UsageDao s_usageDao; + private static UsageNetworkDao s_usageNetworkDao; @Inject private UsageDao _usageDao; @@ -51,8 +51,8 @@ public class NetworkUsageParser { @PostConstruct void init() { - m_usageDao = _usageDao; - m_usageNetworkDao = _usageNetworkDao; + s_usageDao = _usageDao; + s_usageNetworkDao = _usageNetworkDao; } public static boolean parse(AccountVO account, Date startDate, Date endDate) { @@ -66,10 +66,10 @@ public class NetworkUsageParser { // - query usage_network table for all entries for userId with // event_date in the given range - SearchCriteria sc = m_usageNetworkDao.createSearchCriteria(); + SearchCriteria sc = s_usageNetworkDao.createSearchCriteria(); sc.addAnd("accountId", SearchCriteria.Op.EQ, account.getId()); sc.addAnd("eventTimeMillis", SearchCriteria.Op.BETWEEN, startDate.getTime(), endDate.getTime()); - List usageNetworkVOs = m_usageNetworkDao.search(sc, null); + List usageNetworkVOs = s_usageNetworkDao.search(sc, null); Map networkUsageByZone = new HashMap(); @@ -136,7 +136,7 @@ public class NetworkUsageParser { } } - m_usageDao.saveUsageRecords(usageRecords); + s_usageDao.saveUsageRecords(usageRecords); return true; } diff --git a/usage/src/com/cloud/usage/parser/PortForwardingUsageParser.java b/usage/src/com/cloud/usage/parser/PortForwardingUsageParser.java index dd12d575149..37c7751cff4 100644 --- a/usage/src/com/cloud/usage/parser/PortForwardingUsageParser.java +++ b/usage/src/com/cloud/usage/parser/PortForwardingUsageParser.java @@ -41,8 +41,8 @@ import com.cloud.utils.Pair; public class PortForwardingUsageParser { public static final Logger s_logger = Logger.getLogger(PortForwardingUsageParser.class.getName()); - private static UsageDao m_usageDao; - private static UsagePortForwardingRuleDao m_usagePFRuleDao; + private static UsageDao s_usageDao; + private static UsagePortForwardingRuleDao s_usagePFRuleDao; @Inject private UsageDao _usageDao; @@ -51,8 +51,8 @@ public class PortForwardingUsageParser { @PostConstruct void init() { - m_usageDao = _usageDao; - m_usagePFRuleDao = _usagePFRuleDao; + s_usageDao = _usageDao; + s_usagePFRuleDao = _usagePFRuleDao; } public static boolean parse(AccountVO account, Date startDate, Date endDate) { @@ -68,7 +68,7 @@ public class PortForwardingUsageParser { // - look for an entry for accountId with end date in the given range // - look for an entry for accountId with end date null (currently running vm or owned IP) // - look for an entry for accountId with start date before given range *and* end date after given range - List usagePFs = m_usagePFRuleDao.getUsageRecords(account.getId(), account.getDomainId(), startDate, endDate, false, 0); + List usagePFs = s_usagePFRuleDao.getUsageRecords(account.getId(), account.getDomainId(), startDate, endDate, false, 0); if (usagePFs.isEmpty()) { s_logger.debug("No port forwarding usage events for this period"); @@ -152,7 +152,7 @@ public class PortForwardingUsageParser { UsageVO usageRecord = new UsageVO(zoneId, account.getId(), account.getDomainId(), usageDesc, usageDisplay + " Hrs", type, new Double(usage), null, null, null, null, pfId, null, startDate, endDate); - m_usageDao.persist(usageRecord); + s_usageDao.persist(usageRecord); } private static class PFInfo { diff --git a/usage/src/com/cloud/usage/parser/SecurityGroupUsageParser.java b/usage/src/com/cloud/usage/parser/SecurityGroupUsageParser.java index cb1d72ec5a6..ea86d49f14f 100644 --- a/usage/src/com/cloud/usage/parser/SecurityGroupUsageParser.java +++ b/usage/src/com/cloud/usage/parser/SecurityGroupUsageParser.java @@ -41,8 +41,8 @@ import com.cloud.utils.Pair; public class SecurityGroupUsageParser { public static final Logger s_logger = Logger.getLogger(SecurityGroupUsageParser.class.getName()); - private static UsageDao m_usageDao; - private static UsageSecurityGroupDao m_usageSecurityGroupDao; + private static UsageDao s_usageDao; + private static UsageSecurityGroupDao s_usageSecurityGroupDao; @Inject private UsageDao _usageDao; @@ -51,8 +51,8 @@ public class SecurityGroupUsageParser { @PostConstruct void init() { - m_usageDao = _usageDao; - m_usageSecurityGroupDao = _usageSecurityGroupDao; + s_usageDao = _usageDao; + s_usageSecurityGroupDao = _usageSecurityGroupDao; } public static boolean parse(AccountVO account, Date startDate, Date endDate) { @@ -68,7 +68,7 @@ public class SecurityGroupUsageParser { // - look for an entry for accountId with end date in the given range // - look for an entry for accountId with end date null (currently running vm or owned IP) // - look for an entry for accountId with start date before given range *and* end date after given range - List usageSGs = m_usageSecurityGroupDao.getUsageRecords(account.getId(), account.getDomainId(), startDate, endDate, false, 0); + List usageSGs = s_usageSecurityGroupDao.getUsageRecords(account.getId(), account.getDomainId(), startDate, endDate, false, 0); if (usageSGs.isEmpty()) { s_logger.debug("No SecurityGroup usage events for this period"); @@ -152,7 +152,7 @@ public class SecurityGroupUsageParser { UsageVO usageRecord = new UsageVO(zoneId, account.getId(), account.getDomainId(), usageDesc, usageDisplay + " Hrs", type, new Double(usage), vmId, null, null, null, sgId, null, startDate, endDate); - m_usageDao.persist(usageRecord); + s_usageDao.persist(usageRecord); } private static class SGInfo { diff --git a/usage/src/com/cloud/usage/parser/StorageUsageParser.java b/usage/src/com/cloud/usage/parser/StorageUsageParser.java index 560f6b09081..f1091a17643 100644 --- a/usage/src/com/cloud/usage/parser/StorageUsageParser.java +++ b/usage/src/com/cloud/usage/parser/StorageUsageParser.java @@ -42,8 +42,8 @@ import com.cloud.utils.Pair; public class StorageUsageParser { public static final Logger s_logger = Logger.getLogger(StorageUsageParser.class.getName()); - private static UsageDao m_usageDao; - private static UsageStorageDao m_usageStorageDao; + private static UsageDao s_usageDao; + private static UsageStorageDao s_usageStorageDao; @Inject private UsageDao _usageDao; @@ -52,8 +52,8 @@ public class StorageUsageParser { @PostConstruct void init() { - m_usageDao = _usageDao; - m_usageStorageDao = _usageStorageDao; + s_usageDao = _usageDao; + s_usageStorageDao = _usageStorageDao; } public static boolean parse(AccountVO account, Date startDate, Date endDate) { @@ -69,7 +69,7 @@ public class StorageUsageParser { // - look for an entry for accountId with end date in the given range // - look for an entry for accountId with end date null (currently running vm or owned IP) // - look for an entry for accountId with start date before given range *and* end date after given range - List usageUsageStorages = m_usageStorageDao.getUsageRecords(account.getId(), account.getDomainId(), startDate, endDate, false, 0); + List usageUsageStorages = s_usageStorageDao.getUsageRecords(account.getId(), account.getDomainId(), startDate, endDate, false, 0); if (usageUsageStorages.isEmpty()) { s_logger.debug("No Storage usage events for this period"); @@ -183,7 +183,7 @@ public class StorageUsageParser { UsageVO usageRecord = new UsageVO(zoneId, account.getId(), account.getDomainId(), usageDesc, usageDisplay + " Hrs", usage_type, new Double(usage), null, null, null, tmplSourceId, storageId, size, virtualSize, startDate, endDate); - m_usageDao.persist(usageRecord); + s_usageDao.persist(usageRecord); } private static class StorageInfo { diff --git a/usage/src/com/cloud/usage/parser/VMInstanceUsageParser.java b/usage/src/com/cloud/usage/parser/VMInstanceUsageParser.java index 78cafed9792..ba0d4bf9cd4 100644 --- a/usage/src/com/cloud/usage/parser/VMInstanceUsageParser.java +++ b/usage/src/com/cloud/usage/parser/VMInstanceUsageParser.java @@ -41,8 +41,8 @@ import com.cloud.utils.Pair; public class VMInstanceUsageParser { public static final Logger s_logger = Logger.getLogger(VMInstanceUsageParser.class.getName()); - private static UsageDao m_usageDao; - private static UsageVMInstanceDao m_usageInstanceDao; + private static UsageDao s_usageDao; + private static UsageVMInstanceDao s_usageInstanceDao; @Inject private UsageDao _usageDao;; @@ -51,8 +51,8 @@ public class VMInstanceUsageParser { @PostConstruct void init() { - m_usageDao = _usageDao; - m_usageInstanceDao = _usageInstanceDao; + s_usageDao = _usageDao; + s_usageInstanceDao = _usageInstanceDao; } public static boolean parse(AccountVO account, Date startDate, Date endDate) { @@ -68,7 +68,7 @@ public class VMInstanceUsageParser { // - look for an entry for accountId with end date in the given range // - look for an entry for accountId with end date null (currently running vm or owned IP) // - look for an entry for accountId with start date before given range *and* end date after given range - List usageInstances = m_usageInstanceDao.getUsageRecords(account.getId(), startDate, endDate); + List usageInstances = s_usageInstanceDao.getUsageRecords(account.getId(), startDate, endDate); //ToDo: Add domainID for getting usage records // This map has both the running time *and* the usage amount. @@ -180,7 +180,7 @@ public class VMInstanceUsageParser { UsageVO usageRecord = new UsageVO(Long.valueOf(zoneId), account.getId(), account.getDomainId(), usageDesc, usageDisplay + " Hrs", type, new Double(usage), Long.valueOf(vmId), vmName, Long.valueOf(serviceOfferingId), Long.valueOf(templateId), Long.valueOf(vmId), startDate, endDate, hypervisorType); - m_usageDao.persist(usageRecord); + s_usageDao.persist(usageRecord); } private static class VMInfo { diff --git a/usage/src/com/cloud/usage/parser/VMSnapshotUsageParser.java b/usage/src/com/cloud/usage/parser/VMSnapshotUsageParser.java index 0d2b0c1facc..9af81374437 100644 --- a/usage/src/com/cloud/usage/parser/VMSnapshotUsageParser.java +++ b/usage/src/com/cloud/usage/parser/VMSnapshotUsageParser.java @@ -40,8 +40,8 @@ import com.cloud.user.AccountVO; public class VMSnapshotUsageParser { public static final Logger s_logger = Logger.getLogger(VMSnapshotUsageParser.class.getName()); - private static UsageDao m_usageDao; - private static UsageVMSnapshotDao m_usageVMSnapshotDao; + private static UsageDao s_usageDao; + private static UsageVMSnapshotDao s_usageVMSnapshotDao; @Inject private UsageDao _usageDao; @@ -50,8 +50,8 @@ public class VMSnapshotUsageParser { @PostConstruct void init() { - m_usageDao = _usageDao; - m_usageVMSnapshotDao = _usageVMSnapshotDao; + s_usageDao = _usageDao; + s_usageVMSnapshotDao = _usageVMSnapshotDao; } public static boolean parse(AccountVO account, Date startDate, Date endDate) { @@ -62,7 +62,7 @@ public class VMSnapshotUsageParser { endDate = new Date(); } - List usageUsageVMSnapshots = m_usageVMSnapshotDao.getUsageRecords(account.getId(), account.getDomainId(), startDate, endDate); + List usageUsageVMSnapshots = s_usageVMSnapshotDao.getUsageRecords(account.getId(), account.getDomainId(), startDate, endDate); if (usageUsageVMSnapshots.isEmpty()) { s_logger.debug("No VM snapshot usage events for this period"); @@ -79,7 +79,7 @@ public class VMSnapshotUsageParser { unprocessedUsage.put(key, usageRec); continue; } - UsageVMSnapshotVO previousEvent = m_usageVMSnapshotDao.getPreviousUsageRecord(usageRec); + UsageVMSnapshotVO previousEvent = s_usageVMSnapshotDao.getPreviousUsageRecord(usageRec); if (previousEvent == null || previousEvent.getSize() == 0) { unprocessedUsage.put(key, usageRec); continue; @@ -96,11 +96,11 @@ public class VMSnapshotUsageParser { createUsageRecord(UsageTypes.VM_SNAPSHOT, duration, previousCreated, createDate, account, volId, zoneId, previousEvent.getDiskOfferingId(), vmId, previousEvent.getSize()); previousEvent.setProcessed(new Date()); - m_usageVMSnapshotDao.update(previousEvent); + s_usageVMSnapshotDao.update(previousEvent); if (usageRec.getSize() == 0) { usageRec.setProcessed(new Date()); - m_usageVMSnapshotDao.update(usageRec); + s_usageVMSnapshotDao.update(usageRec); } else unprocessedUsage.put(key, usageRec); } @@ -148,7 +148,7 @@ public class VMSnapshotUsageParser { UsageVO usageRecord = new UsageVO(zoneId, account.getId(), account.getDomainId(), usageDesc, usageDisplay + " Hrs", type, new Double(usage), vmId, null, doId, null, volId, size, startDate, endDate); - m_usageDao.persist(usageRecord); + s_usageDao.persist(usageRecord); } } diff --git a/usage/src/com/cloud/usage/parser/VPNUserUsageParser.java b/usage/src/com/cloud/usage/parser/VPNUserUsageParser.java index a6f4a69dcee..619c8619398 100644 --- a/usage/src/com/cloud/usage/parser/VPNUserUsageParser.java +++ b/usage/src/com/cloud/usage/parser/VPNUserUsageParser.java @@ -41,8 +41,8 @@ import com.cloud.utils.Pair; public class VPNUserUsageParser { public static final Logger s_logger = Logger.getLogger(VPNUserUsageParser.class.getName()); - private static UsageDao m_usageDao; - private static UsageVPNUserDao m_usageVPNUserDao; + private static UsageDao s_usageDao; + private static UsageVPNUserDao s_usageVPNUserDao; @Inject private UsageDao _usageDao; @@ -51,8 +51,8 @@ public class VPNUserUsageParser { @PostConstruct void init() { - m_usageDao = _usageDao; - m_usageVPNUserDao = _usageVPNUserDao; + s_usageDao = _usageDao; + s_usageVPNUserDao = _usageVPNUserDao; } public static boolean parse(AccountVO account, Date startDate, Date endDate) { @@ -63,7 +63,7 @@ public class VPNUserUsageParser { endDate = new Date(); } - List usageVUs = m_usageVPNUserDao.getUsageRecords(account.getId(), account.getDomainId(), startDate, endDate, false, 0); + List usageVUs = s_usageVPNUserDao.getUsageRecords(account.getId(), account.getDomainId(), startDate, endDate, false, 0); if (usageVUs.isEmpty()) { s_logger.debug("No VPN user usage events for this period"); @@ -147,7 +147,7 @@ public class VPNUserUsageParser { UsageVO usageRecord = new UsageVO(zoneId, account.getId(), account.getDomainId(), usageDesc, usageDisplay + " Hrs", type, new Double(usage), null, null, null, null, userId, null, startDate, endDate); - m_usageDao.persist(usageRecord); + s_usageDao.persist(usageRecord); } private static class VUInfo { diff --git a/usage/src/com/cloud/usage/parser/VmDiskUsageParser.java b/usage/src/com/cloud/usage/parser/VmDiskUsageParser.java index 8ab216dd08a..6022a3e7004 100644 --- a/usage/src/com/cloud/usage/parser/VmDiskUsageParser.java +++ b/usage/src/com/cloud/usage/parser/VmDiskUsageParser.java @@ -41,8 +41,8 @@ import com.cloud.utils.db.SearchCriteria; public class VmDiskUsageParser { public static final Logger s_logger = Logger.getLogger(VmDiskUsageParser.class.getName()); - private static UsageDao m_usageDao; - private static UsageVmDiskDao m_usageVmDiskDao; + private static UsageDao s_usageDao; + private static UsageVmDiskDao s_usageVmDiskDao; @Inject private UsageDao _usageDao; @@ -51,8 +51,8 @@ public class VmDiskUsageParser { @PostConstruct void init() { - m_usageDao = _usageDao; - m_usageVmDiskDao = _usageVmDiskDao; + s_usageDao = _usageDao; + s_usageVmDiskDao = _usageVmDiskDao; } public static boolean parse(AccountVO account, Date startDate, Date endDate) { @@ -66,10 +66,10 @@ public class VmDiskUsageParser { // - query usage_disk table for all entries for userId with // event_date in the given range - SearchCriteria sc = m_usageVmDiskDao.createSearchCriteria(); + SearchCriteria sc = s_usageVmDiskDao.createSearchCriteria(); sc.addAnd("accountId", SearchCriteria.Op.EQ, account.getId()); sc.addAnd("eventTimeMillis", SearchCriteria.Op.BETWEEN, startDate.getTime(), endDate.getTime()); - List usageVmDiskVOs = m_usageVmDiskDao.search(sc, null); + List usageVmDiskVOs = s_usageVmDiskDao.search(sc, null); Map vmDiskUsageByZone = new HashMap(); @@ -164,7 +164,7 @@ public class VmDiskUsageParser { } } - m_usageDao.saveUsageRecords(usageRecords); + s_usageDao.saveUsageRecords(usageRecords); return true; } diff --git a/usage/src/com/cloud/usage/parser/VolumeUsageParser.java b/usage/src/com/cloud/usage/parser/VolumeUsageParser.java index adcf468ffdc..cd092a970d9 100644 --- a/usage/src/com/cloud/usage/parser/VolumeUsageParser.java +++ b/usage/src/com/cloud/usage/parser/VolumeUsageParser.java @@ -41,8 +41,8 @@ import com.cloud.utils.Pair; public class VolumeUsageParser { public static final Logger s_logger = Logger.getLogger(VolumeUsageParser.class.getName()); - private static UsageDao m_usageDao; - private static UsageVolumeDao m_usageVolumeDao; + private static UsageDao s_usageDao; + private static UsageVolumeDao s_usageVolumeDao; @Inject private UsageDao _usageDao; @@ -51,8 +51,8 @@ public class VolumeUsageParser { @PostConstruct void init() { - m_usageDao = _usageDao; - m_usageVolumeDao = _usageVolumeDao; + s_usageDao = _usageDao; + s_usageVolumeDao = _usageVolumeDao; } public static boolean parse(AccountVO account, Date startDate, Date endDate) { @@ -68,7 +68,7 @@ public class VolumeUsageParser { // - look for an entry for accountId with end date in the given range // - look for an entry for accountId with end date null (currently running vm or owned IP) // - look for an entry for accountId with start date before given range *and* end date after given range - List usageUsageVols = m_usageVolumeDao.getUsageRecords(account.getId(), account.getDomainId(), startDate, endDate, false, 0); + List usageUsageVols = s_usageVolumeDao.getUsageRecords(account.getId(), account.getDomainId(), startDate, endDate, false, 0); if (usageUsageVols.isEmpty()) { s_logger.debug("No volume usage events for this period"); @@ -164,7 +164,7 @@ public class VolumeUsageParser { UsageVO usageRecord = new UsageVO(zoneId, account.getId(), account.getDomainId(), usageDesc, usageDisplay + " Hrs", type, new Double(usage), null, null, doId, templateId, volId, size, startDate, endDate); - m_usageDao.persist(usageRecord); + s_usageDao.persist(usageRecord); } private static class VolInfo { diff --git a/usage/test/com/cloud/usage/UsageManagerTestConfiguration.java b/usage/test/com/cloud/usage/UsageManagerTestConfiguration.java index 85b6cec03be..26b610656c7 100644 --- a/usage/test/com/cloud/usage/UsageManagerTestConfiguration.java +++ b/usage/test/com/cloud/usage/UsageManagerTestConfiguration.java @@ -64,12 +64,12 @@ import com.cloud.user.dao.UserStatisticsDaoImpl; @Configuration @ComponentScan(basePackageClasses = {AccountDaoImpl.class, UsageDaoImpl.class, UsageJobDaoImpl.class, UsageVMInstanceDaoImpl.class, UsageIPAddressDaoImpl.class, - UsageNetworkDaoImpl.class, UsageVolumeDaoImpl.class, UsageStorageDaoImpl.class, UsageLoadBalancerPolicyDaoImpl.class, - UsagePortForwardingRuleDaoImpl.class, UsageNetworkOfferingDaoImpl.class, UsageVPNUserDaoImpl.class, UsageVmDiskDaoImpl.class, - UsageSecurityGroupDaoImpl.class, ConfigurationDaoImpl.class, UsageManagerImpl.class, VMInstanceUsageParser.class, IPAddressUsageParser.class, - LoadBalancerUsageParser.class, NetworkOfferingUsageParser.class, NetworkUsageParser.class, PortForwardingUsageParser.class, - SecurityGroupUsageParser.class, StorageUsageParser.class, VmDiskUsageParser.class, VolumeUsageParser.class, VPNUserUsageParser.class, - UserStatisticsDaoImpl.class}, + UsageNetworkDaoImpl.class, UsageVolumeDaoImpl.class, UsageStorageDaoImpl.class, UsageLoadBalancerPolicyDaoImpl.class, + UsagePortForwardingRuleDaoImpl.class, UsageNetworkOfferingDaoImpl.class, UsageVPNUserDaoImpl.class, UsageVmDiskDaoImpl.class, + UsageSecurityGroupDaoImpl.class, ConfigurationDaoImpl.class, UsageManagerImpl.class, VMInstanceUsageParser.class, IPAddressUsageParser.class, + LoadBalancerUsageParser.class, NetworkOfferingUsageParser.class, NetworkUsageParser.class, PortForwardingUsageParser.class, + SecurityGroupUsageParser.class, StorageUsageParser.class, VmDiskUsageParser.class, VolumeUsageParser.class, VPNUserUsageParser.class, + UserStatisticsDaoImpl.class}, includeFilters = {@Filter(value = Library.class, type = FilterType.CUSTOM)}, useDefaultFilters = false) public class UsageManagerTestConfiguration { diff --git a/usage/test/com/cloud/usage/UsageSanityCheckerIT.java b/usage/test/com/cloud/usage/UsageSanityCheckerIT.java new file mode 100644 index 00000000000..d8a65800018 --- /dev/null +++ b/usage/test/com/cloud/usage/UsageSanityCheckerIT.java @@ -0,0 +1,159 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.usage; + +import static org.junit.Assert.assertEquals; + +import java.io.FileNotFoundException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.Arrays; +import java.util.Collection; +import java.util.Properties; + +import org.dbunit.DatabaseUnitException; +import org.dbunit.dataset.DataSetException; +import org.dbunit.dataset.IDataSet; +import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; +import org.dbunit.ext.mysql.MySqlConnection; +import org.dbunit.operation.DatabaseOperation; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; +import org.mockito.Mockito; + +import com.cloud.utils.PropertiesUtil; + +@RunWith(Parameterized.class) +public class UsageSanityCheckerIT{ + + protected Connection cloudConn; + + protected Connection usageConn; + + protected MySqlConnection dbuUsageConn; + + protected MySqlConnection dbuCloudConn; + + protected Properties properties = new Properties(); + + protected IDataSet cloudDataSet; + + protected IDataSet usageDataSet; + + protected String cloudDbuFileName; + + protected String usageDbuFileName; + + protected String expectedErrors; + + protected static final String EXPECTED_ERRORS_1 = "Error: Found 2 usage records with raw_usage > 10\n" + + "Error: Found 1 Vm usage records which are created after Vm is destroyed\n" + + "Error: Found 2 duplicate allocated Vm entries in vm usage helper table\n" + + "Error: Found 1 running Vm entries without corresponding allocated entries in vm usage helper table\n" + + "Error: Found 1 volume usage records which are created after volume is removed\n" + + "Error: Found 1 template/ISO usage records which are created after it is removed\n" + + "Error: Found 1 snapshot usage records which are created after it is removed\n"; + + protected static final String EXPECTED_ERRORS_2 = "Error: Found 3 usage records with raw_usage > 10\n" + + "Error: Found 1 Vm usage records which are created after Vm is destroyed\n" + + "Error: Found 8 duplicate running Vm entries in vm usage helper table\n" + + "Error: Found 4 duplicate allocated Vm entries in vm usage helper table\n" + + "Error: Found 4 running Vm entries without corresponding allocated entries in vm usage helper table\n" + + "Error: Found 2 volume usage records which are created after volume is removed\n" + + "Error: Found 6 duplicate records in volume usage helper table\n" + + "Error: Found 2 template/ISO usage records which are created after it is removed\n" + + "Error: Found 1 snapshot usage records which are created after it is removed\n"; + + protected static final String EXPECTED_ERRORS_3 = ""; + + + public UsageSanityCheckerIT(String cloudDbuFileName, String usageDbuFileName, + String expectedErrors) { + this.cloudDbuFileName = cloudDbuFileName; + this.usageDbuFileName = usageDbuFileName; + this.expectedErrors = expectedErrors; + } + + @Parameters + public static Collection data() { + Object [][] data = new Object[][] { + {"cloud1.xml", "cloud_usage1.xml", EXPECTED_ERRORS_1}, + {"cloud2.xml", "cloud_usage2.xml", EXPECTED_ERRORS_2}, + {"cloud3.xml", "cloud_usage3.xml", EXPECTED_ERRORS_3} + }; + return Arrays.asList(data); + } + + protected Connection createConnection(String dbSchema) throws SQLException { + String cloudDbUrl = "jdbc:mysql://"+properties.getProperty("db."+dbSchema+".host") + + ":" + properties.getProperty("db."+dbSchema+".port") + "/" + + properties.getProperty("db."+dbSchema+".name"); + return DriverManager.getConnection(cloudDbUrl, properties.getProperty("db."+dbSchema+".username"), + properties.getProperty("db."+dbSchema+".password")); + } + + @Before + public void setUp() throws Exception { + PropertiesUtil.loadFromFile(properties, PropertiesUtil.findConfigFile("db.properties")); + + Class.forName("com.mysql.jdbc.Driver"); + cloudConn = createConnection("cloud"); + usageConn = createConnection("usage"); + + dbuCloudConn = new MySqlConnection(cloudConn, properties.getProperty("db.cloud.name")); + dbuUsageConn = new MySqlConnection(usageConn, properties.getProperty("db.usage.name")); + cloudDataSet = getCloudDataSet(); + usageDataSet = getUsageDataSet(); + DatabaseOperation.CLEAN_INSERT.execute(dbuCloudConn, cloudDataSet); + DatabaseOperation.CLEAN_INSERT.execute(dbuUsageConn, usageDataSet); + } + + @After + public void tearDown() throws DataSetException, FileNotFoundException, DatabaseUnitException, SQLException { + DatabaseOperation.DELETE_ALL.execute(dbuCloudConn, getCloudDataSet()); + DatabaseOperation.DELETE_ALL.execute(dbuUsageConn, getUsageDataSet()); + } + + @Test + public void testRunSanityCheck() throws SQLException, ClassNotFoundException, FileNotFoundException, DatabaseUnitException { + // Prepare + UsageSanityChecker checker = Mockito.spy(new UsageSanityChecker()); + Mockito.doReturn(cloudConn).when(checker).getConnection(); + Mockito.doNothing().when(checker).readLastCheckId(); + Mockito.doNothing().when(checker).updateNewMaxId(); + checker.lastId = 2; + + // Execute + String actualErrors = checker.runSanityCheck(); + + // Assert + assertEquals("Expected errors not found", expectedErrors, actualErrors); + } + + protected IDataSet getCloudDataSet() throws DataSetException, FileNotFoundException { + return new FlatXmlDataSetBuilder().build(PropertiesUtil.openStreamFromURL(cloudDbuFileName)); + } + + protected IDataSet getUsageDataSet() throws DataSetException, FileNotFoundException { + return new FlatXmlDataSetBuilder().build(PropertiesUtil.openStreamFromURL(usageDbuFileName)); + } +} diff --git a/usage/test/com/cloud/usage/UsageSanityCheckerTest.java b/usage/test/com/cloud/usage/UsageSanityCheckerTest.java new file mode 100644 index 00000000000..69e3ea18acc --- /dev/null +++ b/usage/test/com/cloud/usage/UsageSanityCheckerTest.java @@ -0,0 +1,68 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.usage; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import junit.framework.TestCase; + +import org.junit.Test; +import org.mockito.Mockito; + +public class UsageSanityCheckerTest extends TestCase { + + @Test + public void testCheckItemCountByPstmt() throws SQLException { + // Prepare + // Mock dependencies to exclude from the test + String sqlTemplate1 = "SELECT * FROM mytable1"; + String sqlTemplate2 = "SELECT * FROM mytable2"; + + Connection conn = Mockito.mock(Connection.class); + PreparedStatement pstmt = Mockito.mock(PreparedStatement.class); + ResultSet rs = Mockito.mock(ResultSet.class); + + Mockito.when(conn.prepareStatement(sqlTemplate1)).thenReturn(pstmt); + Mockito.when(conn.prepareStatement(sqlTemplate2)).thenReturn(pstmt); + Mockito.when(pstmt.executeQuery()).thenReturn(rs, rs); + + // First if: true -> 8 + // Second loop: true -> 16 + Mockito.when(rs.next()).thenReturn(true, true); + Mockito.when(rs.getInt(1)).thenReturn(8, 8, 16, 16); + + // Prepare class under test + UsageSanityChecker checker = new UsageSanityChecker(); + checker.conn = conn; + checker.reset(); + checker.addCheckCase(sqlTemplate1, "item1"); + checker.addCheckCase(sqlTemplate2, "item2"); + + // Execute + checker.checkItemCountByPstmt(); + + // Verify + Pattern pattern = Pattern.compile(".*8.*item1.*\n.*16.*item2.*"); + Matcher matcher = pattern.matcher(checker.errors); + assertTrue("Didn't create complete errors. It should create 2 errors: 8 item1 and 16 item2", matcher.find()); + } +} diff --git a/usage/test/resources/UsageManagerTestContext.xml b/usage/test/resources/UsageManagerTestContext.xml index ad4757a5910..52f9bf0072f 100644 --- a/usage/test/resources/UsageManagerTestContext.xml +++ b/usage/test/resources/UsageManagerTestContext.xml @@ -1,19 +1,19 @@ - + + + + + + + + + + + + + + + diff --git a/usage/test/resources/cloud2.xml b/usage/test/resources/cloud2.xml new file mode 100644 index 00000000000..2b139fd3c40 --- /dev/null +++ b/usage/test/resources/cloud2.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + diff --git a/usage/test/resources/cloud3.xml b/usage/test/resources/cloud3.xml new file mode 100644 index 00000000000..a4687ff9a9c --- /dev/null +++ b/usage/test/resources/cloud3.xml @@ -0,0 +1,13 @@ + + + + + diff --git a/usage/test/resources/cloud_usage1.xml b/usage/test/resources/cloud_usage1.xml new file mode 100644 index 00000000000..20528bf2aab --- /dev/null +++ b/usage/test/resources/cloud_usage1.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + diff --git a/usage/test/resources/cloud_usage2.xml b/usage/test/resources/cloud_usage2.xml new file mode 100644 index 00000000000..7cc3991ed1a --- /dev/null +++ b/usage/test/resources/cloud_usage2.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/usage/test/resources/cloud_usage3.xml b/usage/test/resources/cloud_usage3.xml new file mode 100644 index 00000000000..d8922e1f01e --- /dev/null +++ b/usage/test/resources/cloud_usage3.xml @@ -0,0 +1,13 @@ + + + + + diff --git a/utils/src/com/cloud/utils/DateUtil.java b/utils/src/com/cloud/utils/DateUtil.java index 510afd28fbd..560c92bb4fc 100644 --- a/utils/src/com/cloud/utils/DateUtil.java +++ b/utils/src/com/cloud/utils/DateUtil.java @@ -28,7 +28,7 @@ import com.cloud.utils.exception.CloudRuntimeException; public class DateUtil { public static final TimeZone GMT_TIMEZONE = TimeZone.getTimeZone("GMT"); public static final String YYYYMMDD_FORMAT = "yyyyMMddHHmmss"; - private static final DateFormat _outputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); + private static final DateFormat s_outputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); public static Date currentGMTTime() { // Date object always stores miliseconds offset based on GMT internally @@ -76,8 +76,8 @@ public class DateUtil { return ""; } String formattedString = null; - synchronized (_outputFormat) { - formattedString = _outputFormat.format(date); + synchronized (s_outputFormat) { + formattedString = s_outputFormat.format(date); } return formattedString; } diff --git a/utils/src/com/cloud/utils/ExecutionResult.java b/utils/src/com/cloud/utils/ExecutionResult.java new file mode 100644 index 00000000000..8edb55b93f3 --- /dev/null +++ b/utils/src/com/cloud/utils/ExecutionResult.java @@ -0,0 +1,44 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package com.cloud.utils; + +public class ExecutionResult { + private Boolean success; + private String details; + + public ExecutionResult(Boolean success, String details) { + this.success = success; + this.details = details; + } + + public Boolean isSuccess() { + return success; + } + + public void setSuccess(Boolean success) { + this.success = success; + } + + public String getDetails() { + return details; + } + + public void setDetails(String details) { + this.details = details; + } +} diff --git a/utils/src/com/cloud/utils/StringUtils.java b/utils/src/com/cloud/utils/StringUtils.java index 6b4c8f8eb95..38d1369432e 100644 --- a/utils/src/com/cloud/utils/StringUtils.java +++ b/utils/src/com/cloud/utils/StringUtils.java @@ -189,25 +189,23 @@ public class StringUtils { return found > 0 ? found : end - start; } - - public static Map stringToMap(String s){ - Map map=new HashMap(); + public static Map stringToMap(String s) { + Map map = new HashMap(); String[] elements = s.split(";"); - for (String parts: elements) { + for (String parts : elements) { String[] keyValue = parts.split(":"); map.put(keyValue[0], keyValue[1]); } return map; } - - public static String mapToString(Map map){ + public static String mapToString(Map map) { String s = ""; - for (Map.Entry entry: map.entrySet()) { - s += entry.getKey() + ":" + entry.getValue() +";"; + for (Map.Entry entry : map.entrySet()) { + s += entry.getKey() + ":" + entry.getValue() + ";"; } if (s.length() > 0) { - s = s.substring(0, s.length()-1); + s = s.substring(0, s.length() - 1); } return s; } diff --git a/utils/src/com/cloud/utils/SwiftUtil.java b/utils/src/com/cloud/utils/SwiftUtil.java index c920e1f2c6a..829159f8fcb 100644 --- a/utils/src/com/cloud/utils/SwiftUtil.java +++ b/utils/src/com/cloud/utils/SwiftUtil.java @@ -29,7 +29,7 @@ import com.cloud.utils.script.Script; public class SwiftUtil { private static Logger logger = Logger.getLogger(SwiftUtil.class); - private static long SWIFT_MAX_SIZE = 5L * 1024L * 1024L * 1024L; + private static final long SWIFT_MAX_SIZE = 5L * 1024L * 1024L * 1024L; public interface SwiftClientCfg { String getAccount(); diff --git a/utils/src/com/cloud/utils/UriUtils.java b/utils/src/com/cloud/utils/UriUtils.java index 4f9db854089..1d5a5138644 100644 --- a/utils/src/com/cloud/utils/UriUtils.java +++ b/utils/src/com/cloud/utils/UriUtils.java @@ -147,6 +147,8 @@ public class UriUtils { URI uri = new URI(url); if (uri.getScheme().equalsIgnoreCase("http")) { httpConn = (HttpURLConnection)uri.toURL().openConnection(); + httpConn.setConnectTimeout(2000); + httpConn.setReadTimeout(5000); if (httpConn != null) { String contentLength = httpConn.getHeaderField("content-length"); if (contentLength != null) { diff --git a/utils/src/com/cloud/utils/events/EventArgs.java b/utils/src/com/cloud/utils/events/EventArgs.java index 0f3dcdd8aa0..4bfe206da5a 100644 --- a/utils/src/com/cloud/utils/events/EventArgs.java +++ b/utils/src/com/cloud/utils/events/EventArgs.java @@ -20,7 +20,7 @@ import java.io.Serializable; public class EventArgs implements Serializable { private static final long serialVersionUID = 30659016120504139L; - public static EventArgs Empty = new EventArgs(); + public static final EventArgs Empty = new EventArgs(); private String subject; diff --git a/utils/src/com/cloud/utils/exception/CloudRuntimeException.java b/utils/src/com/cloud/utils/exception/CloudRuntimeException.java index f2608ed61a5..148c25b8955 100755 --- a/utils/src/com/cloud/utils/exception/CloudRuntimeException.java +++ b/utils/src/com/cloud/utils/exception/CloudRuntimeException.java @@ -16,6 +16,9 @@ // under the License. package com.cloud.utils.exception; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.List; @@ -30,9 +33,9 @@ public class CloudRuntimeException extends RuntimeException implements ErrorCont private static final long serialVersionUID = SerialVersionUID.CloudRuntimeException; // This holds a list of uuids and their descriptive names. - protected ArrayList idList = new ArrayList(); + transient protected ArrayList idList = new ArrayList(); - protected ArrayList, String>> uuidList = new ArrayList, String>>(); + transient protected ArrayList, String>> uuidList = new ArrayList, String>>(); protected int csErrorCode; @@ -48,6 +51,7 @@ public class CloudRuntimeException extends RuntimeException implements ErrorCont protected CloudRuntimeException() { super(); + setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName())); } @@ -90,4 +94,45 @@ public class CloudRuntimeException extends RuntimeException implements ErrorCont public List, String>> getEntitiesInError() { return uuidList; } + + private void writeObject(ObjectOutputStream out) throws IOException { + out.defaultWriteObject(); + + int idListSize = idList.size(); + out.writeInt(idListSize); + for (ExceptionProxyObject proxy : idList) { + out.writeObject(proxy); + } + + int uuidListSize = uuidList.size(); + out.writeInt(uuidListSize); + for (Pair, String> entry : uuidList) { + out.writeObject(entry.first().getCanonicalName()); + out.writeObject(entry.second()); + } + } + + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + in.defaultReadObject(); + + int idListSize = in.readInt(); + if (idList == null) + idList = new ArrayList(); + if (uuidList == null) + uuidList = new ArrayList, String>>(); + + for (int i = 0; i < idListSize; i++) { + ExceptionProxyObject proxy = (ExceptionProxyObject)in.readObject(); + + idList.add(proxy); + } + + int uuidListSize = in.readInt(); + for (int i = 0; i < uuidListSize; i++) { + String clzName = (String)in.readObject(); + String val = (String)in.readObject(); + + uuidList.add(new Pair, String>(Class.forName(clzName), val)); + } + } } diff --git a/utils/src/com/cloud/utils/exception/ExceptionProxyObject.java b/utils/src/com/cloud/utils/exception/ExceptionProxyObject.java index ef84a14fcae..0f1b4e0de01 100644 --- a/utils/src/com/cloud/utils/exception/ExceptionProxyObject.java +++ b/utils/src/com/cloud/utils/exception/ExceptionProxyObject.java @@ -16,17 +16,22 @@ // under the License. package com.cloud.utils.exception; -public class ExceptionProxyObject { +import java.io.Serializable; + + +public class ExceptionProxyObject implements Serializable { + private static final long serialVersionUID = -7514266713085362352L; + private String uuid; private String description; - public ExceptionProxyObject() { + public ExceptionProxyObject(){ } - public ExceptionProxyObject(String uuid, String desc) { + public ExceptionProxyObject(String uuid, String desc){ this.uuid = uuid; - this.description = desc; + description = desc; } public String getUuid() { @@ -44,5 +49,4 @@ public class ExceptionProxyObject { public void setDescription(String description) { this.description = description; } - } diff --git a/utils/src/com/cloud/utils/net/NetUtils.java b/utils/src/com/cloud/utils/net/NetUtils.java index c0c792fcb0d..f64b2302a5b 100755 --- a/utils/src/com/cloud/utils/net/NetUtils.java +++ b/utils/src/com/cloud/utils/net/NetUtils.java @@ -72,10 +72,10 @@ public class NetUtils { public final static int DEFAULT_AUTOSCALE_VM_DESTROY_TIME = 2 * 60; // Grace period before Vm is destroyed public final static int DEFAULT_AUTOSCALE_POLICY_INTERVAL_TIME = 30; public final static int DEFAULT_AUTOSCALE_POLICY_QUIET_TIME = 5 * 60; - private final static Random _rand = new Random(System.currentTimeMillis()); + private final static Random s_rand = new Random(System.currentTimeMillis()); public static long createSequenceBasedMacAddress(long macAddress) { - return macAddress | 0x060000000000l | (((long)_rand.nextInt(32768) << 25) & 0x00fffe000000l); + return macAddress | 0x060000000000l | (((long)s_rand.nextInt(32768) << 25) & 0x00fffe000000l); } public static String getHostName() { @@ -458,7 +458,7 @@ public class NetUtils { StringBuilder result = new StringBuilder(17); Formatter formatter = new Formatter(result); formatter.format("%02x:%02x:%02x:%02x:%02x:%02x", (macAddress >> 40) & 0xff, (macAddress >> 32) & 0xff, (macAddress >> 24) & 0xff, (macAddress >> 16) & 0xff, - (macAddress >> 8) & 0xff, (macAddress & 0xff)); + (macAddress >> 8) & 0xff, (macAddress & 0xff)); return result.toString(); } @@ -702,7 +702,7 @@ public class NetUtils { //e.g., cidr = 192.168.10.0, size = /24, avoid = 192.168.10.1, 192.168.10.20, 192.168.10.254 // range = 2^8 - 1 - 3 = 252 range = range - avoid.size(); - int next = _rand.nextInt(range); //note: nextInt excludes last value + int next = s_rand.nextInt(range); //note: nextInt excludes last value long ip = startIp + next; for (Long avoidable : avoid) { if (ip >= avoidable) { @@ -768,6 +768,14 @@ public class NetUtils { } public static String ipAndNetMaskToCidr(String ip, String netmask) { + if (!isValidIp(ip)) { + return null; + } + + if (!isValidNetmask(netmask)) { + return null; + } + long ipAddr = ip2Long(ip); long subnet = ip2Long(netmask); long result = ipAddr & subnet; @@ -825,7 +833,7 @@ public class NetUtils { if (cidrALong[1] < cidrBLong[1]) { //this implies cidrA is super set of cidrB return supersetOrSubset.isSuperset; - } else if (cidrALong[1] == cidrBLong[1]) { + } else if (cidrALong[1].equals(cidrBLong[1])) { //this implies both the cidrs are equal return supersetOrSubset.sameSubnet; } @@ -1202,7 +1210,7 @@ public class NetUtils { public static boolean isValidIpv6(String ip) { try { - IPv6Address address = IPv6Address.fromString(ip); + IPv6Address.fromString(ip); } catch (IllegalArgumentException ex) { return false; } @@ -1211,7 +1219,7 @@ public class NetUtils { public static boolean isValidIp6Cidr(String ip6Cidr) { try { - IPv6Network network = IPv6Network.fromString(ip6Cidr); + IPv6Network.fromString(ip6Cidr); } catch (IllegalArgumentException ex) { return false; } @@ -1234,9 +1242,9 @@ public class NetUtils { String startIp = ips[0]; IPv6Address start = IPv6Address.fromString(startIp); BigInteger gap = countIp6InRange(ip6Range); - BigInteger next = new BigInteger(gap.bitLength(), _rand); + BigInteger next = new BigInteger(gap.bitLength(), s_rand); while (next.compareTo(gap) >= 0) { - next = new BigInteger(gap.bitLength(), _rand); + next = new BigInteger(gap.bitLength(), s_rand); } BigInteger startInt = convertIPv6AddressToBigInteger(start); BigInteger resultInt = startInt.add(next); @@ -1367,10 +1375,17 @@ public class NetUtils { return resultIp; } + static final String VLAN_PREFIX = "vlan://"; + static final int VLAN_PREFIX_LENGTH = VLAN_PREFIX.length(); + public static boolean isValidVlan(String vlan) { + if (null == vlan || "".equals(vlan)) + return false; + if (vlan.startsWith(VLAN_PREFIX)) + vlan = vlan.substring(VLAN_PREFIX_LENGTH); try { int vnet = Integer.parseInt(vlan); - if (vnet < 0 || vnet > 4096) { + if (vnet <= 0 || vnet >= 4095) { // the valid range is 1- 4094 return false; } return true; @@ -1379,6 +1394,36 @@ public class NetUtils { } } + static final String VLAN_UNTAGGED = "untagged"; + + public static boolean isSameIsolationId(String one, String other) { + // check nulls + // check empty strings + if ((one == null || one.equals("")) && (other == null || other.equals(""))) { + return true; + } + if ((one == null || other == null) && !(one == null && other == null)) { + return false; + } + // check 'untagged' + if (one.contains(VLAN_UNTAGGED) && other.contains(VLAN_UNTAGGED)) { + return true; + } + // if one is a number check the other as number and as 'vlan://' + number + if (one.startsWith(VLAN_PREFIX)) { + one = one.substring(VLAN_PREFIX_LENGTH); + } + if (other.startsWith(VLAN_PREFIX)) { + other = other.substring(VLAN_PREFIX_LENGTH); + } + // check valid uris or numbers + if (one.equalsIgnoreCase(other)) { + return true; + } + + return false; + } + // Attention maintainers: these pvlan functions should take into account code // in Networks.BroadcastDomainType, where URI construction is done for other // types of BroadcastDomainTypes diff --git a/utils/src/com/cloud/utils/nio/Link.java b/utils/src/com/cloud/utils/nio/Link.java index e20210db71a..613480e46c3 100755 --- a/utils/src/com/cloud/utils/nio/Link.java +++ b/utils/src/com/cloud/utils/nio/Link.java @@ -21,8 +21,11 @@ import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetSocketAddress; +import java.net.SocketTimeoutException; import java.nio.ByteBuffer; +import java.nio.channels.Channels; import java.nio.channels.ClosedChannelException; +import java.nio.channels.ReadableByteChannel; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import java.security.KeyStore; @@ -150,7 +153,7 @@ public class Link { pkgBuf.clear(); engResult = sslEngine.wrap(buffers, pkgBuf); if (engResult.getHandshakeStatus() != HandshakeStatus.FINISHED && engResult.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING && - engResult.getStatus() != SSLEngineResult.Status.OK) { + engResult.getStatus() != SSLEngineResult.Status.OK) { throw new IOException("SSL: SSLEngine return bad result! " + engResult); } @@ -276,7 +279,7 @@ public class Link { appBuf = ByteBuffer.allocate(sslSession.getApplicationBufferSize() + 40); engResult = _sslEngine.unwrap(_readBuffer, appBuf); if (engResult.getHandshakeStatus() != HandshakeStatus.FINISHED && engResult.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING && - engResult.getStatus() != SSLEngineResult.Status.OK) { + engResult.getStatus() != SSLEngineResult.Status.OK) { throw new IOException("SSL: SSLEngine return bad result! " + engResult); } if (remaining == _readBuffer.remaining()) { @@ -449,6 +452,10 @@ public class Link { ByteBuffer out_pkgBuf = ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40); ByteBuffer out_appBuf = ByteBuffer.allocate(sslSession.getApplicationBufferSize() + 40); int count; + ch.socket().setSoTimeout(10 * 1000); + InputStream inStream = ch.socket().getInputStream(); + // Use readCh to make sure the timeout on reading is working + ReadableByteChannel readCh = Channels.newChannel(inStream); if (isClient) { hsStatus = SSLEngineResult.HandshakeStatus.NEED_WRAP; @@ -479,7 +486,15 @@ public class Link { // One packet may contained multiply operation if (in_pkgBuf.position() == 0 || !in_pkgBuf.hasRemaining()) { in_pkgBuf.clear(); - count = ch.read(in_pkgBuf); + count = 0; + try { + count = readCh.read(in_pkgBuf); + } catch (SocketTimeoutException ex) { + if (s_logger.isTraceEnabled()) { + s_logger.trace("Handshake reading time out! Cut the connection"); + } + count = -1; + } if (count == -1) { throw new IOException("Connection closed with -1 on reading size."); } diff --git a/utils/src/com/cloud/utils/script/OutputInterpreter.java b/utils/src/com/cloud/utils/script/OutputInterpreter.java index 5af607e4590..5845c9ca0ff 100755 --- a/utils/src/com/cloud/utils/script/OutputInterpreter.java +++ b/utils/src/com/cloud/utils/script/OutputInterpreter.java @@ -16,11 +16,11 @@ // under the License. package com.cloud.utils.script; +import org.apache.log4j.Logger; + import java.io.BufferedReader; import java.io.IOException; -import org.apache.log4j.Logger; - /** */ public abstract class OutputInterpreter { diff --git a/utils/src/com/cloud/utils/script/Script.java b/utils/src/com/cloud/utils/script/Script.java index 91f32dedeb7..8dad697feae 100755 --- a/utils/src/com/cloud/utils/script/Script.java +++ b/utils/src/com/cloud/utils/script/Script.java @@ -16,6 +16,11 @@ // under the License. package com.cloud.utils.script; +import com.cloud.utils.PropertiesUtil; +import com.cloud.utils.concurrency.NamedThreadFactory; +import com.cloud.utils.script.OutputInterpreter.TimedOutLogger; +import org.apache.log4j.Logger; + import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; @@ -35,12 +40,6 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; -import org.apache.log4j.Logger; - -import com.cloud.utils.PropertiesUtil; -import com.cloud.utils.concurrency.NamedThreadFactory; -import com.cloud.utils.script.OutputInterpreter.TimedOutLogger; - public class Script implements Callable { private static final Logger s_logger = Logger.getLogger(Script.class); @@ -61,6 +60,10 @@ public class Script implements Callable { Process _process; Thread _thread; + public int getExitValue() { + return _process.exitValue(); + } + public Script(String command, long timeout, Logger logger) { _command = new ArrayList(); _command.add(command); diff --git a/utils/src/com/cloud/utils/security/CertificateHelper.java b/utils/src/com/cloud/utils/security/CertificateHelper.java index 5d8f6ad310d..64ba8bffa02 100644 --- a/utils/src/com/cloud/utils/security/CertificateHelper.java +++ b/utils/src/com/cloud/utils/security/CertificateHelper.java @@ -114,7 +114,7 @@ public class CertificateHelper { return kf.generatePrivate(keysp); } - public static List parseChain(String chain) throws IOException { + public static List parseChain(String chain) throws IOException { List certs = new ArrayList(); PEMReader reader = new PEMReader(new StringReader(chain)); @@ -160,6 +160,4 @@ public class CertificateHelper { return buffer.toString(); } - - } diff --git a/utils/src/com/cloud/utils/ssh/SSHCmdHelper.java b/utils/src/com/cloud/utils/ssh/SSHCmdHelper.java index 8b63c51e3cd..ebd65f56683 100644 --- a/utils/src/com/cloud/utils/ssh/SSHCmdHelper.java +++ b/utils/src/com/cloud/utils/ssh/SSHCmdHelper.java @@ -62,7 +62,7 @@ public class SSHCmdHelper { try { if (sshExecuteCmdOneShot(sshConnection, cmd)) return true; - } catch (sshException e) { + } catch (SshException e) { continue; } } @@ -77,7 +77,7 @@ public class SSHCmdHelper { for (int i = 0; i < nTimes; i++) { try { return sshExecuteCmdOneShotWithExitCode(sshConnection, cmd); - } catch (sshException e) { + } catch (SshException e) { continue; } } @@ -88,7 +88,7 @@ public class SSHCmdHelper { return sshExecuteCmd(sshConnection, cmd, 3); } - public static int sshExecuteCmdOneShotWithExitCode(com.trilead.ssh2.Connection sshConnection, String cmd) throws sshException { + public static int sshExecuteCmdOneShotWithExitCode(com.trilead.ssh2.Connection sshConnection, String cmd) throws SshException { s_logger.debug("Executing cmd: " + cmd); Session sshSession = null; try { @@ -98,7 +98,7 @@ public class SSHCmdHelper { Thread.sleep(1000); if (sshSession == null) { - throw new sshException("Cannot open ssh session"); + throw new SshException("Cannot open ssh session"); } sshSession.execCommand(cmd); @@ -109,7 +109,7 @@ public class SSHCmdHelper { byte[] buffer = new byte[8192]; while (true) { if (stdout == null || stderr == null) { - throw new sshException("stdout or stderr of ssh session is null"); + throw new SshException("stdout or stderr of ssh session is null"); } if ((stdout.available() == 0) && (stderr.available() == 0)) { @@ -143,14 +143,14 @@ public class SSHCmdHelper { return sshSession.getExitStatus(); } catch (Exception e) { s_logger.debug("Ssh executed failed", e); - throw new sshException("Ssh executed failed " + e.getMessage()); + throw new SshException("Ssh executed failed " + e.getMessage()); } finally { if (sshSession != null) sshSession.close(); } } - public static boolean sshExecuteCmdOneShot(com.trilead.ssh2.Connection sshConnection, String cmd) throws sshException { + public static boolean sshExecuteCmdOneShot(com.trilead.ssh2.Connection sshConnection, String cmd) throws SshException { return sshExecuteCmdOneShotWithExitCode(sshConnection, cmd) == 0; } } diff --git a/utils/src/com/cloud/utils/ssh/sshException.java b/utils/src/com/cloud/utils/ssh/SshException.java similarity index 92% rename from utils/src/com/cloud/utils/ssh/sshException.java rename to utils/src/com/cloud/utils/ssh/SshException.java index ca3cbb67b40..7c9d35c647e 100644 --- a/utils/src/com/cloud/utils/ssh/sshException.java +++ b/utils/src/com/cloud/utils/ssh/SshException.java @@ -18,10 +18,10 @@ package com.cloud.utils.ssh; import com.cloud.utils.SerialVersionUID; -public class sshException extends Exception { +public class SshException extends Exception { private static final long serialVersionUID = SerialVersionUID.sshException; - public sshException(String msg) { + public SshException(String msg) { super(msg); } } diff --git a/utils/src/com/cloud/utils/ssh/SshHelper.java b/utils/src/com/cloud/utils/ssh/SshHelper.java index e482a803e44..41625eb54c9 100755 --- a/utils/src/com/cloud/utils/ssh/SshHelper.java +++ b/utils/src/com/cloud/utils/ssh/SshHelper.java @@ -27,8 +27,8 @@ import com.trilead.ssh2.ChannelCondition; import com.cloud.utils.Pair; public class SshHelper { - private static int DEFAULT_CONNECT_TIMEOUT = 60000; - private static int DEFAULT_KEX_TIMEOUT = 60000; + private static final int DEFAULT_CONNECT_TIMEOUT = 60000; + private static final int DEFAULT_KEX_TIMEOUT = 60000; private static final Logger s_logger = Logger.getLogger(SshHelper.class); diff --git a/utils/src/org/apache/cloudstack/utils/identity/ManagementServerNode.java b/utils/src/org/apache/cloudstack/utils/identity/ManagementServerNode.java index 6149eaf2e8e..7dee8461f47 100755 --- a/utils/src/org/apache/cloudstack/utils/identity/ManagementServerNode.java +++ b/utils/src/org/apache/cloudstack/utils/identity/ManagementServerNode.java @@ -28,7 +28,7 @@ import com.cloud.utils.net.MacAddress; @Local(value = {SystemIntegrityChecker.class}) public class ManagementServerNode extends AdapterBase implements SystemIntegrityChecker { - private final Logger s_logger = Logger.getLogger(ManagementServerNode.class); + private static final Logger s_logger = Logger.getLogger(ManagementServerNode.class); private static final long s_nodeId = MacAddress.getMacAddress().toLong(); diff --git a/utils/test/com/cloud/utils/net/NetUtilsTest.java b/utils/test/com/cloud/utils/net/NetUtilsTest.java index c7407bf05fb..600b69ee5b2 100644 --- a/utils/test/com/cloud/utils/net/NetUtilsTest.java +++ b/utils/test/com/cloud/utils/net/NetUtilsTest.java @@ -174,4 +174,14 @@ public class NetUtilsTest extends TestCase { public void testGetLocalIPString() { assertNotNull(NetUtils.getLocalIPString()); } + + @Test + public void testSameIsolationId() { + assertTrue(NetUtils.isSameIsolationId("1", "vlan://1")); + assertTrue(NetUtils.isSameIsolationId("", null)); + assertTrue(NetUtils.isSameIsolationId("UnTagged", "vlan://uNtAGGED")); + assertFalse(NetUtils.isSameIsolationId("2", "vlan://uNtAGGED")); + assertFalse(NetUtils.isSameIsolationId("2", "vlan://3")); + assertFalse(NetUtils.isSameIsolationId("bla", null)); + } } diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/ClusterMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/ClusterMO.java index b9fdd01f573..49ee7c4ec51 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/ClusterMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/ClusterMO.java @@ -125,7 +125,7 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost { public ObjectContent[] getVmPropertiesOnHyperHost(String[] propertyPaths) throws Exception { if (s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - retrieveProperties() for VM properties. target MOR: " + _mor.getValue() + ", properties: " + - new Gson().toJson(propertyPaths)); + new Gson().toJson(propertyPaths)); PropertySpec pSpec = new PropertySpec(); pSpec.setType("VirtualMachine"); @@ -164,7 +164,7 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost { public ObjectContent[] getDatastorePropertiesOnHyperHost(String[] propertyPaths) throws Exception { if (s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - retrieveProperties() on Datastore properties. target MOR: " + _mor.getValue() + ", properties: " + - new Gson().toJson(propertyPaths)); + new Gson().toJson(propertyPaths)); PropertySpec pSpec = new PropertySpec(); pSpec.setType("Datastore"); @@ -196,7 +196,7 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost { private ObjectContent[] getHostPropertiesOnCluster(String[] propertyPaths) throws Exception { if (s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - retrieveProperties() on Host properties. target MOR: " + _mor.getValue() + ", properties: " + - new Gson().toJson(propertyPaths)); + new Gson().toJson(propertyPaths)); PropertySpec pSpec = new PropertySpec(); pSpec.setType("HostSystem"); @@ -257,7 +257,7 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost { public void importVmFromOVF(String ovfFilePath, String vmName, DatastoreMO dsMo, String diskOption) throws Exception { if (s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - importVmFromOVF(). target MOR: " + _mor.getValue() + ", ovfFilePath: " + ovfFilePath + ", vmName: " + vmName + - ", datastore: " + dsMo.getMor().getValue() + ", diskOption: " + diskOption); + ", datastore: " + dsMo.getMor().getValue() + ", diskOption: " + diskOption); ManagedObjectReference morRp = getHyperHostOwnerResourcePool(); assert (morRp != null); @@ -273,16 +273,16 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost { @Override public boolean createBlankVm(String vmName, String vmInternalCSName, int cpuCount, int cpuSpeedMHz, int cpuReservedMHz, boolean limitCpuUse, int memoryMB, - int memoryReserveMB, String guestOsIdentifier, ManagedObjectReference morDs, boolean snapshotDirToParent) throws Exception { + int memoryReserveMB, String guestOsIdentifier, ManagedObjectReference morDs, boolean snapshotDirToParent) throws Exception { if (s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - createBlankVm(). target MOR: " + _mor.getValue() + ", vmName: " + vmName + ", cpuCount: " + cpuCount + ", cpuSpeedMhz: " + - cpuSpeedMHz + ", cpuReservedMHz: " + cpuReservedMHz + ", limitCpu: " + limitCpuUse + ", memoryMB: " + memoryMB + ", guestOS: " + guestOsIdentifier + - ", datastore: " + morDs.getValue() + ", snapshotDirToParent: " + snapshotDirToParent); + cpuSpeedMHz + ", cpuReservedMHz: " + cpuReservedMHz + ", limitCpu: " + limitCpuUse + ", memoryMB: " + memoryMB + ", guestOS: " + guestOsIdentifier + + ", datastore: " + morDs.getValue() + ", snapshotDirToParent: " + snapshotDirToParent); boolean result = - HypervisorHostHelper.createBlankVm(this, vmName, vmInternalCSName, cpuCount, cpuSpeedMHz, cpuReservedMHz, limitCpuUse, memoryMB, memoryReserveMB, - guestOsIdentifier, morDs, snapshotDirToParent); + HypervisorHostHelper.createBlankVm(this, vmName, vmInternalCSName, cpuCount, cpuSpeedMHz, cpuReservedMHz, limitCpuUse, memoryMB, memoryReserveMB, + guestOsIdentifier, morDs, snapshotDirToParent); if (s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - createBlankVm() done"); @@ -295,11 +295,11 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost { if (s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - mountDatastore(). target MOR: " + _mor.getValue() + ", vmfs: " + vmfsDatastore + ", poolHost: " + poolHostAddress + - ", poolHostPort: " + poolHostPort + ", poolPath: " + poolPath + ", poolUuid: " + poolUuid); + ", poolHostPort: " + poolHostPort + ", poolPath: " + poolPath + ", poolUuid: " + poolUuid); ManagedObjectReference morDs = null; ManagedObjectReference morDsFirst = null; - List hosts = (List)_context.getVimClient().getDynamicProperty(_mor, "host"); + List hosts = _context.getVimClient().getDynamicProperty(_mor, "host"); if (hosts != null && hosts.size() > 0) { for (ManagedObjectReference morHost : hosts) { HostMO hostMo = new HostMO(_context, morHost); @@ -332,7 +332,7 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost { if (s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - unmountDatastore(). target MOR: " + _mor.getValue() + ", poolUuid: " + poolUuid); - List hosts = (List)_context.getVimClient().getDynamicProperty(_mor, "host"); + List hosts = _context.getVimClient().getDynamicProperty(_mor, "host"); if (hosts != null && hosts.size() > 0) { for (ManagedObjectReference morHost : hosts) { HostMO hostMo = new HostMO(_context, morHost); @@ -382,6 +382,11 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost { return null; } + @Override + public ManagedObjectReference findDatastoreByName(String datastoreName) throws Exception { + throw new UnsupportedOperationException(); + } + @Override public ManagedObjectReference findDatastoreByExportPath(String exportPath) throws Exception { if (s_logger.isTraceEnabled()) @@ -475,7 +480,7 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost { // TODO, need to use traversal to optimize retrieve of int cpuNumInCpuThreads = 1; - List hosts = (List)_context.getVimClient().getDynamicProperty(_mor, "host"); + List hosts = _context.getVimClient().getDynamicProperty(_mor, "host"); if (hosts != null && hosts.size() > 0) { for (ManagedObjectReference morHost : hosts) { HostMO hostMo = new HostMO(_context, morHost); @@ -500,7 +505,7 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost { if (s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - getHyperHostNetworkSummary(). target MOR: " + _mor.getValue() + ", mgmtPortgroup: " + esxServiceConsolePort); - List hosts = (List)_context.getVimClient().getDynamicProperty(_mor, "host"); + List hosts = _context.getVimClient().getDynamicProperty(_mor, "host"); if (hosts != null && hosts.size() > 0) { VmwareHypervisorHostNetworkSummary summary = new HostMO(_context, hosts.get(0)).getHyperHostNetworkSummary(esxServiceConsolePort); diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/CustomFieldsManagerMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/CustomFieldsManagerMO.java index dbc742911e4..78ce9a83c68 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/CustomFieldsManagerMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/CustomFieldsManagerMO.java @@ -51,7 +51,7 @@ public class CustomFieldsManagerMO extends BaseMO { } public List getFields() throws Exception { - return (List)_context.getVimClient().getDynamicProperty(getMor(), "field"); + return _context.getVimClient().getDynamicProperty(getMor(), "field"); } @Override diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatastoreMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatastoreMO.java index 21b3026154b..363b91f9c68 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatastoreMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatastoreMO.java @@ -32,6 +32,7 @@ import com.vmware.vim25.PropertySpec; import com.vmware.vim25.SelectionSpec; import com.vmware.vim25.TraversalSpec; +import com.cloud.exception.CloudException; import com.cloud.hypervisor.vmware.util.VmwareContext; import com.cloud.utils.Pair; @@ -181,7 +182,7 @@ public class DatastoreMO extends BaseMO { } public boolean copyDatastoreFile(String srcFilePath, ManagedObjectReference morSrcDc, ManagedObjectReference morDestDs, String destFilePath, - ManagedObjectReference morDestDc, boolean forceOverwrite) throws Exception { + ManagedObjectReference morDestDc, boolean forceOverwrite) throws Exception { String srcDsName = getName(); DatastoreMO destDsMo = new DatastoreMO(_context, morDestDs); @@ -209,7 +210,7 @@ public class DatastoreMO extends BaseMO { } public boolean moveDatastoreFile(String srcFilePath, ManagedObjectReference morSrcDc, ManagedObjectReference morDestDs, String destFilePath, - ManagedObjectReference morDestDc, boolean forceOverwrite) throws Exception { + ManagedObjectReference morDestDc, boolean forceOverwrite) throws Exception { String srcDsName = getName(); DatastoreMO destDsMo = new DatastoreMO(_context, morDestDs); @@ -342,6 +343,10 @@ public class DatastoreMO extends BaseMO { ArrayList results = browserMo.searchDatastoreSubFolders("[" + getName() + "]", fileName, caseInsensitive); if (results != null && results.size() > 1) { s_logger.warn("Multiple files with name " + fileName + " exists in datastore " + datastorePath + ". Trying to choose first file found in search attempt."); + } else if (results == null) { + String msg = "No file found with name " + fileName + " found in datastore " + datastorePath; + s_logger.error(msg); + throw new CloudException(msg); } for (HostDatastoreBrowserSearchResults result : results) { List info = result.getFile(); diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/DistributedVirtualSwitchMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/DistributedVirtualSwitchMO.java index 220c5a132aa..9e19d655e7a 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/DistributedVirtualSwitchMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/DistributedVirtualSwitchMO.java @@ -34,6 +34,7 @@ import com.vmware.vim25.VMwareDVSPvlanMapEntry; import com.cloud.hypervisor.vmware.util.VmwareContext; public class DistributedVirtualSwitchMO extends BaseMO { + @SuppressWarnings("unused") private static final Logger s_logger = Logger.getLogger(DistributedVirtualSwitchMO.class); public DistributedVirtualSwitchMO(VmwareContext context, ManagedObjectReference morDvs) { @@ -62,7 +63,7 @@ public class DistributedVirtualSwitchMO extends BaseMO { public TaskInfo updateVMWareDVSwitchGetTask(ManagedObjectReference dvSwitchMor, VMwareDVSConfigSpec dvsSpec) throws Exception { ManagedObjectReference task = _context.getService().reconfigureDvsTask(dvSwitchMor, dvsSpec); TaskInfo info = (TaskInfo)(_context.getVimClient().getDynamicProperty(task, "info")); - boolean waitvalue = _context.getVimClient().waitForTask(task); + _context.getVimClient().waitForTask(task); return info; } diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostDatastoreSystemMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostDatastoreSystemMO.java index 2392347f8f8..9af845b143f 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostDatastoreSystemMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostDatastoreSystemMO.java @@ -181,7 +181,7 @@ public class HostDatastoreSystemMO extends BaseMO { } public List getDatastores() throws Exception { - return (List)_context.getVimClient().getDynamicProperty(_mor, "datastore"); + return _context.getVimClient().getDynamicProperty(_mor, "datastore"); } public DatastoreInfo getDatastoreInfo(ManagedObjectReference morDatastore) throws Exception { diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostFirewallSystemMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostFirewallSystemMO.java index 4c0a9957aa8..78e98db3c4a 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostFirewallSystemMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostFirewallSystemMO.java @@ -25,6 +25,7 @@ import com.vmware.vim25.ManagedObjectReference; import com.cloud.hypervisor.vmware.util.VmwareContext; public class HostFirewallSystemMO extends BaseMO { + @SuppressWarnings("unused") private static final Logger s_logger = Logger.getLogger(HostFirewallSystemMO.class); public HostFirewallSystemMO(VmwareContext context, ManagedObjectReference morFirewallSystem) { diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostMO.java index 1b2a102d63c..a32992aeb33 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostMO.java @@ -91,11 +91,11 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { } public List getHostVirtualNicManagerNetConfig() throws Exception { - return (List)_context.getVimClient().getDynamicProperty(_mor, "config.virtualNicManagerInfo.netConfig"); + return _context.getVimClient().getDynamicProperty(_mor, "config.virtualNicManagerInfo.netConfig"); } public List getHostIpRouteEntries() throws Exception { - return (List)_context.getVimClient().getDynamicProperty(_mor, "config.network.routeTableInfo.ipRoute"); + return _context.getVimClient().getDynamicProperty(_mor, "config.network.routeTableInfo.ipRoute"); } public HostListSummaryQuickStats getHostQuickStats() throws Exception { @@ -222,7 +222,7 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { } public ManagedObjectReference[] getHostLocalDatastore() throws Exception { - List datastores = (List)_context.getVimClient().getDynamicProperty(_mor, "datastore"); + List datastores = _context.getVimClient().getDynamicProperty(_mor, "datastore"); List l = new ArrayList(); if (datastores != null) { for (ManagedObjectReference mor : datastores) { @@ -235,7 +235,7 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { } public HostVirtualSwitch getHostVirtualSwitchByName(String name) throws Exception { - List switches = (List)_context.getVimClient().getDynamicProperty(_mor, "config.network.vswitch"); + List switches = _context.getVimClient().getDynamicProperty(_mor, "config.network.vswitch"); if (switches != null) { for (HostVirtualSwitch vswitch : switches) { @@ -247,7 +247,7 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { } public List getHostVirtualSwitch() throws Exception { - return (List)_context.getVimClient().getDynamicProperty(_mor, "config.network.vswitch"); + return _context.getVimClient().getDynamicProperty(_mor, "config.network.vswitch"); } public AboutInfo getHostAboutInfo() throws Exception { @@ -326,7 +326,7 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { assert (nicType != null); List netConfigs = - (List)_context.getVimClient().getDynamicProperty(_mor, "config.virtualNicManagerInfo.netConfig"); + _context.getVimClient().getDynamicProperty(_mor, "config.virtualNicManagerInfo.netConfig"); if (netConfigs != null) { for (VirtualNicManagerNetConfig netConfig : netConfigs) { @@ -364,7 +364,7 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { } public void createPortGroup(HostVirtualSwitch vSwitch, String portGroupName, Integer vlanId, HostNetworkSecurityPolicy secPolicy, - HostNetworkTrafficShapingPolicy shapingPolicy) throws Exception { + HostNetworkTrafficShapingPolicy shapingPolicy) throws Exception { assert (portGroupName != null); HostNetworkSystemMO hostNetMo = getHostNetworkSystemMO(); assert (hostNetMo != null); @@ -384,7 +384,7 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { } public void updatePortGroup(HostVirtualSwitch vSwitch, String portGroupName, Integer vlanId, HostNetworkSecurityPolicy secPolicy, - HostNetworkTrafficShapingPolicy shapingPolicy) throws Exception { + HostNetworkTrafficShapingPolicy shapingPolicy) throws Exception { assert (portGroupName != null); HostNetworkSystemMO hostNetMo = getHostNetworkSystemMO(); assert (hostNetMo != null); @@ -450,7 +450,7 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { public List getVmMorsOnNetwork(String portGroupName) throws Exception { ManagedObjectReference morNetwork = getNetworkMor(portGroupName); if (morNetwork != null) - return (List)_context.getVimClient().getDynamicProperty(morNetwork, "vm"); + return _context.getVimClient().getDynamicProperty(morNetwork, "vm"); return null; } @@ -612,7 +612,7 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { public ObjectContent[] getVmPropertiesOnHyperHost(String[] propertyPaths) throws Exception { if (s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - retrieveProperties() for VM properties. target MOR: " + _mor.getValue() + ", properties: " + - new Gson().toJson(propertyPaths)); + new Gson().toJson(propertyPaths)); PropertySpec pSpec = new PropertySpec(); pSpec.setType("VirtualMachine"); @@ -645,7 +645,7 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { public ObjectContent[] getDatastorePropertiesOnHyperHost(String[] propertyPaths) throws Exception { if (s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - retrieveProperties() on Datastore properties. target MOR: " + _mor.getValue() + ", properties: " + - new Gson().toJson(propertyPaths)); + new Gson().toJson(propertyPaths)); PropertySpec pSpec = new PropertySpec(); pSpec.setType("Datastore"); @@ -698,7 +698,9 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { ManagedObjectReference morDs = oc.getObj(); String name = (String)VmwareHelper.getPropValue(oc, "name"); - dsList.add(new Pair(morDs, name)); + if (!name.startsWith("-iqn.")) { + dsList.add(new Pair(morDs, name)); + } } } } @@ -708,7 +710,7 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { public void importVmFromOVF(String ovfFilePath, String vmName, String datastoreName, String diskOption) throws Exception { if (s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - importVmFromOVF(). target MOR: " + _mor.getValue() + ", ovfFilePath: " + ovfFilePath + ", vmName: " + vmName + - ",datastoreName: " + datastoreName + ", diskOption: " + diskOption); + ",datastoreName: " + datastoreName + ", diskOption: " + diskOption); DatastoreMO dsMo = getHostDatastoreMO(datastoreName); if (dsMo == null) @@ -731,16 +733,16 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { @Override public boolean createBlankVm(String vmName, String vmInternalCSName, int cpuCount, int cpuSpeedMHz, int cpuReservedMHz, boolean limitCpuUse, int memoryMB, - int memoryReserveMB, String guestOsIdentifier, ManagedObjectReference morDs, boolean snapshotDirToParent) throws Exception { + int memoryReserveMB, String guestOsIdentifier, ManagedObjectReference morDs, boolean snapshotDirToParent) throws Exception { if (s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - createBlankVm(). target MOR: " + _mor.getValue() + ", vmName: " + vmName + ", cpuCount: " + cpuCount + ", cpuSpeedMhz: " + - cpuSpeedMHz + ", cpuReservedMHz: " + cpuReservedMHz + ", limitCpu: " + limitCpuUse + ", memoryMB: " + memoryMB + ", guestOS: " + guestOsIdentifier + - ", datastore: " + morDs.getValue() + ", snapshotDirToParent: " + snapshotDirToParent); + cpuSpeedMHz + ", cpuReservedMHz: " + cpuReservedMHz + ", limitCpu: " + limitCpuUse + ", memoryMB: " + memoryMB + ", guestOS: " + guestOsIdentifier + + ", datastore: " + morDs.getValue() + ", snapshotDirToParent: " + snapshotDirToParent); boolean result = - HypervisorHostHelper.createBlankVm(this, vmName, vmInternalCSName, cpuCount, cpuSpeedMHz, cpuReservedMHz, limitCpuUse, memoryMB, memoryReserveMB, - guestOsIdentifier, morDs, snapshotDirToParent); + HypervisorHostHelper.createBlankVm(this, vmName, vmInternalCSName, cpuCount, cpuSpeedMHz, cpuReservedMHz, limitCpuUse, memoryMB, memoryReserveMB, + guestOsIdentifier, morDs, snapshotDirToParent); if (s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - createBlankVm() done"); @@ -748,7 +750,7 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { } public ManagedObjectReference getExistingDataStoreOnHost(boolean vmfsDatastore, String hostAddress, int hostPort, String path, String uuid, - HostDatastoreSystemMO hostDatastoreSystemMo) { + HostDatastoreSystemMO hostDatastoreSystemMo) { // First retrieve the list of Datastores on the host. List morArray; try { @@ -784,7 +786,7 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { if (s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - mountDatastore(). target MOR: " + _mor.getValue() + ", vmfs: " + vmfsDatastore + ", poolHost: " + poolHostAddress + - ", poolHostPort: " + poolHostPort + ", poolPath: " + poolPath + ", poolUuid: " + poolUuid); + ", poolHostPort: " + poolHostPort + ", poolPath: " + poolPath + ", poolUuid: " + poolUuid); HostDatastoreSystemMO hostDatastoreSystemMo = getHostDatastoreSystemMO(); ManagedObjectReference morDatastore = hostDatastoreSystemMo.findDatastore(poolUuid); @@ -794,14 +796,14 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { morDatastore = hostDatastoreSystemMo.createNfsDatastore(poolHostAddress, poolHostPort, poolPath, poolUuid); } catch (AlreadyExistsFaultMsg e) { s_logger.info("Creation of NFS datastore on vCenter failed since datastore already exists." + - " Details: vCenter API trace - mountDatastore(). target MOR: " + _mor.getValue() + ", vmfs: " + vmfsDatastore + ", poolHost: " + poolHostAddress + - ", poolHostPort: " + poolHostPort + ", poolPath: " + poolPath + ", poolUuid: " + poolUuid); + " Details: vCenter API trace - mountDatastore(). target MOR: " + _mor.getValue() + ", vmfs: " + vmfsDatastore + ", poolHost: " + poolHostAddress + + ", poolHostPort: " + poolHostPort + ", poolPath: " + poolPath + ", poolUuid: " + poolUuid); // Retrieve the morDatastore and return it. return (getExistingDataStoreOnHost(vmfsDatastore, poolHostAddress, poolHostPort, poolPath, poolUuid, hostDatastoreSystemMo)); } catch (Exception e) { s_logger.info("Creation of NFS datastore on vCenter failed. " + " Details: vCenter API trace - mountDatastore(). target MOR: " + _mor.getValue() + - ", vmfs: " + vmfsDatastore + ", poolHost: " + poolHostAddress + ", poolHostPort: " + poolHostPort + ", poolPath: " + poolPath + ", poolUuid: " + - poolUuid + ". Exception mesg: " + e.getMessage()); + ", vmfs: " + vmfsDatastore + ", poolHost: " + poolHostAddress + ", poolHostPort: " + poolHostPort + ", poolPath: " + poolPath + ", poolUuid: " + + poolUuid + ". Exception mesg: " + e.getMessage()); throw new Exception("Creation of NFS datastore on vCenter failed."); } if (morDatastore == null) { @@ -866,6 +868,12 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { return datastoreSystemMo.findDatastoreByExportPath(exportPath); } + @Override + public ManagedObjectReference findDatastoreByName(String datastoreName) throws Exception { + HostDatastoreSystemMO hostDsMo = getHostDatastoreSystemMO(); + return hostDsMo.findDatastoreByName(datastoreName); + } + @Override public ManagedObjectReference findMigrationTarget(VirtualMachineMO vmMo) throws Exception { return _mor; @@ -897,9 +905,9 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { VmwareHypervisorHostNetworkSummary summary = new VmwareHypervisorHostNetworkSummary(); - if (this.getHostType() == VmwareHostType.ESXi) { + if (getHostType() == VmwareHostType.ESXi) { List netConfigs = - (List)_context.getVimClient().getDynamicProperty(_mor, "config.virtualNicManagerInfo.netConfig"); + _context.getVimClient().getDynamicProperty(_mor, "config.virtualNicManagerInfo.netConfig"); assert (netConfigs != null); for (VirtualNicManagerNetConfig netConfig : netConfigs) { @@ -919,7 +927,7 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { } } else { // try with ESX path - List hostVNics = (List)_context.getVimClient().getDynamicProperty(_mor, "config.network.consoleVnic"); + List hostVNics = _context.getVimClient().getDynamicProperty(_mor, "config.network.consoleVnic"); if (hostVNics != null) { for (HostVirtualNic vnic : hostVNics) { diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostNetworkSystemMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostNetworkSystemMO.java index 806b0e2c296..acac689b350 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostNetworkSystemMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostNetworkSystemMO.java @@ -25,6 +25,7 @@ import com.vmware.vim25.ManagedObjectReference; import com.cloud.hypervisor.vmware.util.VmwareContext; public class HostNetworkSystemMO extends BaseMO { + @SuppressWarnings("unused") private static final Logger s_logger = Logger.getLogger(HostNetworkSystemMO.class); public HostNetworkSystemMO(VmwareContext context, ManagedObjectReference morNetworkSystem) { diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HypervisorHostHelper.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HypervisorHostHelper.java index 9f5d4f90978..38b68b3c847 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HypervisorHostHelper.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HypervisorHostHelper.java @@ -68,6 +68,7 @@ import com.vmware.vim25.VmwareDistributedVirtualSwitchPvlanSpec; import com.vmware.vim25.VmwareDistributedVirtualSwitchVlanIdSpec; import com.vmware.vim25.VmwareDistributedVirtualSwitchVlanSpec; +import com.cloud.exception.CloudException; import com.cloud.hypervisor.vmware.util.VmwareContext; import com.cloud.hypervisor.vmware.util.VmwareHelper; import com.cloud.network.Networks.BroadcastDomainType; @@ -194,7 +195,7 @@ public class HypervisorHostHelper { } public static void createPortProfile(VmwareContext context, String ethPortProfileName, String networkName, Integer vlanId, Integer networkRateMbps, - long peakBandwidth, long burstSize, String gateway, boolean configureVServiceInNexus) throws Exception { + long peakBandwidth, long burstSize, String gateway, boolean configureVServiceInNexus) throws Exception { Map vsmCredentials = getValidatedVsmCredentials(context); String vsmIp = vsmCredentials.get("vsmip"); String vsmUserName = vsmCredentials.get("vsmusername"); @@ -228,7 +229,7 @@ public class HypervisorHostHelper { } } catch (CloudRuntimeException e) { msg = - "Failed to add policy map of " + policyName + " with parameters " + "committed rate = " + averageBandwidth + "peak bandwidth = " + peakBandwidth + + "Failed to add policy map of " + policyName + " with parameters " + "committed rate = " + averageBandwidth + "peak bandwidth = " + peakBandwidth + "burst size = " + burstSize + ". Exception: " + e.toString(); s_logger.error(msg); if (netconfClient != null) { @@ -273,7 +274,7 @@ public class HypervisorHostHelper { netconfClient.addVServiceNode(vlanId.toString(), gateway); s_logger.info("Adding port profile with vservice details configured over VLAN : " + vlanId.toString()); netconfClient.addPortProfile(networkName, PortProfileType.vethernet, BindingType.portbindingstatic, SwitchPortMode.access, vlanId.intValue(), vdc, - esp); + esp); } } } catch (CloudRuntimeException e) { @@ -304,7 +305,7 @@ public class HypervisorHostHelper { } public static void updatePortProfile(VmwareContext context, String ethPortProfileName, String vethPortProfileName, Integer vlanId, Integer networkRateMbps, - long peakBandwidth, long burstRate) throws Exception { + long peakBandwidth, long burstRate) throws Exception { NetconfHelper netconfClient = null; Map vsmCredentials = getValidatedVsmCredentials(context); String vsmIp = vsmCredentials.get("vsmip"); @@ -345,7 +346,7 @@ public class HypervisorHostHelper { netconfClient.addPolicyMap(policyName, averageBandwidth, (int)peakBandwidth, (int)burstRate); } catch (CloudRuntimeException e) { msg = - "Failed to add policy map of " + policyName + " with parameters " + "committed rate = " + averageBandwidth + "peak bandwidth = " + peakBandwidth + + "Failed to add policy map of " + policyName + " with parameters " + "committed rate = " + averageBandwidth + "peak bandwidth = " + peakBandwidth + "burst size = " + burstRate + ". Exception: " + e.toString(); s_logger.error(msg); if (netconfClient != null) { @@ -432,8 +433,8 @@ public class HypervisorHostHelper { */ public static Pair prepareNetwork(String physicalNetwork, String namePrefix, HostMO hostMo, String vlanId, String secondaryvlanId, - Integer networkRateMbps, Integer networkRateMulticastMbps, long timeOutMs, VirtualSwitchType vSwitchType, int numPorts, String gateway, - boolean configureVServiceInNexus, BroadcastDomainType broadcastDomainType) throws Exception { + Integer networkRateMbps, Integer networkRateMulticastMbps, long timeOutMs, VirtualSwitchType vSwitchType, int numPorts, String gateway, + boolean configureVServiceInNexus, BroadcastDomainType broadcastDomainType) throws Exception { ManagedObjectReference morNetwork = null; VmwareContext context = hostMo.getContext(); ManagedObjectReference dcMor = hostMo.getHyperHostDatacenter(); @@ -456,7 +457,7 @@ public class HypervisorHostHelper { * prepare networks for in this function. */ BroadcastDomainType[] supportedBroadcastTypes = - new BroadcastDomainType[] {BroadcastDomainType.Lswitch, BroadcastDomainType.LinkLocal, BroadcastDomainType.Native, BroadcastDomainType.Pvlan, + new BroadcastDomainType[] {BroadcastDomainType.Lswitch, BroadcastDomainType.LinkLocal, BroadcastDomainType.Native, BroadcastDomainType.Pvlan, BroadcastDomainType.Storage, BroadcastDomainType.UnDecided, BroadcastDomainType.Vlan}; if (!Arrays.asList(supportedBroadcastTypes).contains(broadcastDomainType)) { @@ -503,11 +504,11 @@ public class HypervisorHostHelper { } morDvSwitch = dataCenterMo.getDvSwitchMor(dvSwitchName); if (morDvSwitch == null) { - String msg = "Unable to find distributed vSwitch " + morDvSwitch; + String msg = "Unable to find distributed vSwitch " + dvSwitchName; s_logger.error(msg); throw new Exception(msg); } else { - s_logger.info("Found distributed vSwitch " + morDvSwitch); + s_logger.debug("Found distributed vSwitch " + dvSwitchName); } if (broadcastDomainType == BroadcastDomainType.Lswitch) { @@ -663,8 +664,8 @@ public class HypervisorHostHelper { } private static void createPortGroup(String physicalNetwork, String networkName, Integer vid, Integer spvlanid, DatacenterMO dataCenterMo, - DVSTrafficShapingPolicy shapingPolicy, DVSSecurityPolicy secPolicy, DistributedVirtualSwitchMO dvSwitchMo, int numPorts, boolean autoExpandSupported) - throws Exception { + DVSTrafficShapingPolicy shapingPolicy, DVSSecurityPolicy secPolicy, DistributedVirtualSwitchMO dvSwitchMo, int numPorts, boolean autoExpandSupported) + throws Exception { VmwareDistributedVirtualSwitchVlanSpec vlanSpec = null; VmwareDistributedVirtualSwitchPvlanSpec pvlanSpec = null; VMwareDVSPortSetting dvsPortSetting = null; @@ -783,7 +784,7 @@ public class HypervisorHostHelper { } public static VMwareDVSPortSetting createVmwareDVPortSettingSpec(DVSTrafficShapingPolicy shapingPolicy, DVSSecurityPolicy secPolicy, - VmwareDistributedVirtualSwitchVlanSpec vlanSpec) { + VmwareDistributedVirtualSwitchVlanSpec vlanSpec) { VMwareDVSPortSetting dvsPortSetting = new VMwareDVSPortSetting(); dvsPortSetting.setVlan(vlanSpec); dvsPortSetting.setSecurityPolicy(secPolicy); @@ -863,7 +864,7 @@ public class HypervisorHostHelper { } public static Pair prepareNetwork(String vSwitchName, String namePrefix, HostMO hostMo, String vlanId, Integer networkRateMbps, - Integer networkRateMulticastMbps, long timeOutMs, boolean syncPeerHosts, BroadcastDomainType broadcastDomainType, String nicUuid) throws Exception { + Integer networkRateMulticastMbps, long timeOutMs, boolean syncPeerHosts, BroadcastDomainType broadcastDomainType, String nicUuid) throws Exception { HostVirtualSwitch vSwitch; if (vSwitchName == null) { @@ -886,7 +887,7 @@ public class HypervisorHostHelper { * prepare networks for in this function. */ BroadcastDomainType[] supportedBroadcastTypes = - new BroadcastDomainType[] {BroadcastDomainType.Lswitch, BroadcastDomainType.LinkLocal, BroadcastDomainType.Native, BroadcastDomainType.Pvlan, + new BroadcastDomainType[] {BroadcastDomainType.Lswitch, BroadcastDomainType.LinkLocal, BroadcastDomainType.Native, BroadcastDomainType.Pvlan, BroadcastDomainType.Storage, BroadcastDomainType.UnDecided, BroadcastDomainType.Vlan}; if (!Arrays.asList(supportedBroadcastTypes).contains(broadcastDomainType)) { @@ -980,7 +981,7 @@ public class HypervisorHostHelper { try { if (lock.lock(DEFAULT_LOCK_TIMEOUT_SECONDS)) { try { - List hosts = (List)hostMo.getContext().getVimClient().getDynamicProperty(morParent, "host"); + List hosts = hostMo.getContext().getVimClient().getDynamicProperty(morParent, "host"); if (hosts != null) { for (ManagedObjectReference otherHost : hosts) { if (!otherHost.getValue().equals(hostMo.getMor().getValue())) { @@ -989,7 +990,7 @@ public class HypervisorHostHelper { if (s_logger.isDebugEnabled()) s_logger.debug("Prepare network on other host, vlan: " + vlanId + ", host: " + otherHostMo.getHostName()); prepareNetwork(vSwitchName, namePrefix, otherHostMo, vlanId, networkRateMbps, networkRateMulticastMbps, timeOutMs, false, - broadcastDomainType, nicUuid); + broadcastDomainType, nicUuid); } catch (Exception e) { s_logger.warn("Unable to prepare network on other host, vlan: " + vlanId + ", host: " + otherHostMo.getHostName()); } @@ -1108,7 +1109,7 @@ public class HypervisorHostHelper { } public static boolean createBlankVm(VmwareHypervisorHost host, String vmName, String vmInternalCSName, int cpuCount, int cpuSpeedMHz, int cpuReservedMHz, - boolean limitCpuUse, int memoryMB, int memoryReserveMB, String guestOsIdentifier, ManagedObjectReference morDs, boolean snapshotDirToParent) throws Exception { + boolean limitCpuUse, int memoryMB, int memoryReserveMB, String guestOsIdentifier, ManagedObjectReference morDs, boolean snapshotDirToParent) throws Exception { if (s_logger.isInfoEnabled()) s_logger.info("Create blank VM. cpuCount: " + cpuCount + ", cpuSpeed(MHz): " + cpuSpeedMHz + ", mem(Mb): " + memoryMB); @@ -1273,7 +1274,7 @@ public class HypervisorHostHelper { } public static void importVmFromOVF(VmwareHypervisorHost host, String ovfFilePath, String vmName, DatastoreMO dsMo, String diskOption, ManagedObjectReference morRp, - ManagedObjectReference morHost) throws Exception { + ManagedObjectReference morHost) throws Exception { assert (morRp != null); @@ -1288,7 +1289,7 @@ public class HypervisorHostHelper { String ovfDescriptor = HttpNfcLeaseMO.readOvfContent(ovfFilePath); VmwareContext context = host.getContext(); OvfCreateImportSpecResult ovfImportResult = - context.getService().createImportSpec(context.getServiceContent().getOvfManager(), ovfDescriptor, morRp, dsMo.getMor(), importSpecParams); + context.getService().createImportSpec(context.getServiceContent().getOvfManager(), ovfDescriptor, morRp, dsMo.getMor(), importSpecParams); if (ovfImportResult == null) { String msg = "createImportSpec() failed. ovfFilePath: " + ovfFilePath + ", vmName: " + vmName + ", diskOption: " + diskOption; @@ -1296,6 +1297,19 @@ public class HypervisorHostHelper { throw new Exception(msg); } + if(!ovfImportResult.getError().isEmpty()) { + for (LocalizedMethodFault fault : ovfImportResult.getError()) { + s_logger.error("createImportSpec error: " + fault.getLocalizedMessage()); + } + throw new CloudException("Failed to create an import spec from " + ovfFilePath + ". Check log for details."); + } + + if (!ovfImportResult.getWarning().isEmpty()) { + for (LocalizedMethodFault fault : ovfImportResult.getError()) { + s_logger.warn("createImportSpec warning: " + fault.getLocalizedMessage()); + } + } + DatacenterMO dcMo = new DatacenterMO(context, host.getHyperHostDatacenter()); ManagedObjectReference morLease = context.getService().importVApp(morRp, ovfImportResult.getImportSpec(), dcMo.getVmFolder(), morHost); if (morLease == null) { diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/LicenseAssignmentManagerMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/LicenseAssignmentManagerMO.java index 0a86b978305..b5e11663b70 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/LicenseAssignmentManagerMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/LicenseAssignmentManagerMO.java @@ -30,10 +30,8 @@ import com.cloud.hypervisor.vmware.util.VmwareContext; public class LicenseAssignmentManagerMO extends BaseMO { + @SuppressWarnings("unused") private static final Logger s_logger = Logger.getLogger(LicenseAssignmentManagerMO.class); - private static final String LICENSE_INFO_PRODUCT_VERSION = "ProductVersion"; - private static final String LICENSE_INFO_PRODUCT_NAME = "ProductName"; - private static final String LICENSE_INFO_NAME = "Name"; private static final String LICENSE_INFO_FEATURE = "feature"; public LicenseAssignmentManagerMO(VmwareContext context, ManagedObjectReference mor) { diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/LicenseManagerMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/LicenseManagerMO.java index 7ba046dd98e..1096fabc8ec 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/LicenseManagerMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/LicenseManagerMO.java @@ -24,6 +24,7 @@ import com.cloud.hypervisor.vmware.util.VmwareContext; public class LicenseManagerMO extends BaseMO { + @SuppressWarnings("unused") private static final Logger s_logger = Logger.getLogger(LicenseManagerMO.class); private ManagedObjectReference _licenseAssignmentManager = null; diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/NetworkMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/NetworkMO.java index 43ffa25ceae..e2797d39c1e 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/NetworkMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/NetworkMO.java @@ -36,6 +36,6 @@ public class NetworkMO extends BaseMO { } public List getVMsOnNetwork() throws Exception { - return (List)_context.getVimClient().getDynamicProperty(_mor, "vm"); + return _context.getVimClient().getDynamicProperty(_mor, "vm"); } } diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/PerfManagerMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/PerfManagerMO.java index 205f23a6e0c..9ce028d7915 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/PerfManagerMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/PerfManagerMO.java @@ -76,7 +76,7 @@ public class PerfManagerMO extends BaseMO { public List queryAvailablePerfMetric(ManagedObjectReference morEntity, Calendar beginTime, Calendar endTime, Integer intervalId) throws Exception { return _context.getService().queryAvailablePerfMetric(_mor, morEntity, calendarToXMLGregorianCalendar(beginTime), calendarToXMLGregorianCalendar(endTime), - intervalId); + intervalId); } public PerfCompositeMetric queryPerfComposite(PerfQuerySpec spec) throws Exception { @@ -114,10 +114,10 @@ public class PerfManagerMO extends BaseMO { } public List getCounterInfo() throws Exception { - return (List)_context.getVimClient().getDynamicProperty(_mor, "perfCounter"); + return _context.getVimClient().getDynamicProperty(_mor, "perfCounter"); } public List getIntervalInfo() throws Exception { - return (List)_context.getVimClient().getDynamicProperty(_mor, "historicalInterval"); + return _context.getVimClient().getDynamicProperty(_mor, "historicalInterval"); } } diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualDiskManagerMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualDiskManagerMO.java index 34d593fb6e5..32f5c00a8dd 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualDiskManagerMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualDiskManagerMO.java @@ -25,6 +25,7 @@ import com.vmware.vim25.VirtualDiskSpec; import com.cloud.hypervisor.vmware.util.VmwareContext; public class VirtualDiskManagerMO extends BaseMO { + @SuppressWarnings("unused") private static final Logger s_logger = Logger.getLogger(VirtualDiskManagerMO.class); public VirtualDiskManagerMO(VmwareContext context) { @@ -40,7 +41,7 @@ public class VirtualDiskManagerMO extends BaseMO { } public void copyVirtualDisk(String srcName, ManagedObjectReference morSrcDc, String destName, ManagedObjectReference morDestDc, VirtualDiskSpec diskSpec, - boolean force) throws Exception { + boolean force) throws Exception { ManagedObjectReference morTask = _context.getService().copyVirtualDiskTask(_mor, srcName, morSrcDc, destName, morDestDc, diskSpec, force); diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java index 20e5b26ae41..99a7425a1c2 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java @@ -111,7 +111,7 @@ import com.cloud.utils.script.Script; public class VirtualMachineMO extends BaseMO { private static final Logger s_logger = Logger.getLogger(VirtualMachineMO.class); - private static final ExecutorService _monitorServiceExecutor = Executors.newCachedThreadPool(new NamedThreadFactory("VM-Question-Monitor")); + private static final ExecutorService MonitorServiceExecutor = Executors.newCachedThreadPool(new NamedThreadFactory("VM-Question-Monitor")); private ManagedObjectReference _vmEnvironmentBrowser = null; public VirtualMachineMO(VmwareContext context, ManagedObjectReference morVm) { @@ -489,7 +489,7 @@ public class VirtualMachineMO extends BaseMO { } public String - getSnapshotDiskFileDatastorePath(VirtualMachineFileInfo vmFileInfo, List> datastoreMounts, String snapshotDiskFile) + getSnapshotDiskFileDatastorePath(VirtualMachineFileInfo vmFileInfo, List> datastoreMounts, String snapshotDiskFile) throws Exception { // if file path start with "/", need to search all datastore mounts on the host in order @@ -597,7 +597,7 @@ public class VirtualMachineMO extends BaseMO { } public boolean createFullClone(String cloneName, ManagedObjectReference morFolder, ManagedObjectReference morResourcePool, ManagedObjectReference morDs) - throws Exception { + throws Exception { VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec(); VirtualMachineRelocateSpec relocSpec = new VirtualMachineRelocateSpec(); @@ -621,7 +621,7 @@ public class VirtualMachineMO extends BaseMO { } public boolean createLinkedClone(String cloneName, ManagedObjectReference morBaseSnapshot, ManagedObjectReference morFolder, ManagedObjectReference morResourcePool, - ManagedObjectReference morDs) throws Exception { + ManagedObjectReference morDs) throws Exception { assert (morBaseSnapshot != null); assert (morFolder != null); @@ -772,8 +772,8 @@ public class VirtualMachineMO extends BaseMO { } NetworkDetails details = - new NetworkDetails(name, oc.getObj(), (morVms != null ? morVms.getManagedObjectReference().toArray( - new ManagedObjectReference[morVms.getManagedObjectReference().size()]) : null), gcTagValue); + new NetworkDetails(name, oc.getObj(), (morVms != null ? morVms.getManagedObjectReference().toArray( + new ManagedObjectReference[morVms.getManagedObjectReference().size()]) : null), gcTagValue); networks.add(details); } @@ -811,13 +811,13 @@ public class VirtualMachineMO extends BaseMO { String vmxPathTokens[] = vmxFilePath.split("\\[|\\]|/"); StringBuffer sb = new StringBuffer("https://" + _context.getServerAddress() + "/folder/"); - sb.append(URLEncoder.encode(vmxPathTokens[2].trim())); + sb.append(URLEncoder.encode(vmxPathTokens[2].trim(), "UTF-8")); sb.append("/"); - sb.append(URLEncoder.encode(vmxPathTokens[3].trim())); + sb.append(URLEncoder.encode(vmxPathTokens[3].trim(), "UTF-8")); sb.append("?dcPath="); - sb.append(URLEncoder.encode(dcInfo.second())); + sb.append(URLEncoder.encode(dcInfo.second(), "UTF-8")); sb.append("&dsName="); - sb.append(URLEncoder.encode(vmxPathTokens[1].trim())); + sb.append(URLEncoder.encode(vmxPathTokens[1].trim(), "UTF-8")); return sb.toString(); } @@ -906,12 +906,12 @@ public class VirtualMachineMO extends BaseMO { // vmdkDatastorePath: [datastore name] vmdkFilePath public void createDisk(String vmdkDatastorePath, VirtualDiskType diskType, VirtualDiskMode diskMode, String rdmDeviceName, int sizeInMb, - ManagedObjectReference morDs, int controllerKey) throws Exception { + ManagedObjectReference morDs, int controllerKey) throws Exception { if (s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - createDisk(). target MOR: " + _mor.getValue() + ", vmdkDatastorePath: " + vmdkDatastorePath + ", sizeInMb: " + sizeInMb + - ", diskType: " + diskType + ", diskMode: " + diskMode + ", rdmDeviceName: " + rdmDeviceName + ", datastore: " + morDs.getValue() + ", controllerKey: " + - controllerKey); + ", diskType: " + diskType + ", diskMode: " + diskMode + ", rdmDeviceName: " + rdmDeviceName + ", datastore: " + morDs.getValue() + ", controllerKey: " + + controllerKey); assert (vmdkDatastorePath != null); assert (morDs != null); @@ -995,7 +995,7 @@ public class VirtualMachineMO extends BaseMO { if (s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - attachDisk(). target MOR: " + _mor.getValue() + ", vmdkDatastorePath: " + new Gson().toJson(vmdkDatastorePathChain) + - ", datastore: " + morDs.getValue()); + ", datastore: " + morDs.getValue()); VirtualDevice newDisk = VmwareHelper.prepareDiskDevice(this, null, getScsiDeviceControllerKey(), vmdkDatastorePathChain, morDs, -1, 1); VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec(); @@ -1055,7 +1055,7 @@ public class VirtualMachineMO extends BaseMO { if (s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - detachDisk(). target MOR: " + _mor.getValue() + ", vmdkDatastorePath: " + vmdkDatastorePath + ", deleteBacking: " + - deleteBackingFile); + deleteBackingFile); // Note: if VM has been taken snapshot, original backing file will be renamed, therefore, when we try to find the matching // VirtualDisk, we only perform prefix matching @@ -1152,7 +1152,7 @@ public class VirtualMachineMO extends BaseMO { if (s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - attachIso(). target MOR: " + _mor.getValue() + ", isoDatastorePath: " + isoDatastorePath + ", datastore: " + - morDs.getValue() + ", connect: " + connect + ", connectAtBoot: " + connectAtBoot); + morDs.getValue() + ", connect: " + connect + ", connectAtBoot: " + connectAtBoot); assert (isoDatastorePath != null); assert (morDs != null); @@ -1238,7 +1238,7 @@ public class VirtualMachineMO extends BaseMO { // Monitor VM questions final Boolean[] flags = {false}; final VirtualMachineMO vmMo = this; - Future future = _monitorServiceExecutor.submit(new Runnable() { + Future future = MonitorServiceExecutor.submit(new Runnable() { @Override public void run() { s_logger.info("VM Question monitor started..."); @@ -1260,7 +1260,7 @@ public class VirtualMachineMO extends BaseMO { } if ("msg.cdromdisconnect.locked".equalsIgnoreCase(msg.getId())) { s_logger.info("Found that VM has a pending question that we need to answer programmatically, question id: " + msg.getId() + - ", for safe operation we will automatically decline it"); + ", for safe operation we will automatically decline it"); vmMo.answerVM(question.getId(), "1"); break; } @@ -1277,7 +1277,7 @@ public class VirtualMachineMO extends BaseMO { msgText = tokens[1]; if ("msg.cdromdisconnect.locked".equalsIgnoreCase(msgId)) { s_logger.info("Found that VM has a pending question that we need to answer programmatically, question id: " + question.getId() + - ". Message id : " + msgId + ". Message text : " + msgText + ", for safe operation we will automatically decline it."); + ". Message id : " + msgId + ". Message text : " + msgText + ", for safe operation we will automatically decline it."); vmMo.answerVM(question.getId(), "1"); } } @@ -1609,7 +1609,7 @@ public class VirtualMachineMO extends BaseMO { // return the disk chain (VMDK datastore paths) for cloned snapshot public Pair cloneFromCurrentSnapshot(String clonedVmName, int cpuSpeedMHz, int memoryMb, String diskDevice, ManagedObjectReference morDs) - throws Exception { + throws Exception { assert (morDs != null); String[] disks = getCurrentSnapshotDiskChainDatastorePaths(diskDevice); VirtualMachineMO clonedVm = cloneFromDiskChain(clonedVmName, cpuSpeedMHz, memoryMb, disks, morDs); @@ -1737,6 +1737,22 @@ public class VirtualMachineMO extends BaseMO { } } + public List getVmdkFileBaseNames() throws Exception { + List vmdkFileBaseNames = new ArrayList(); + VirtualDevice[] devices = getAllDiskDevice(); + for(VirtualDevice device : devices) { + if(device instanceof VirtualDisk) { + VirtualDeviceBackingInfo backingInfo = ((VirtualDisk)device).getBacking(); + if(backingInfo instanceof VirtualDiskFlatVer2BackingInfo) { + VirtualDiskFlatVer2BackingInfo diskBackingInfo = (VirtualDiskFlatVer2BackingInfo)backingInfo; + DatastoreFile dsBackingFile = new DatastoreFile(diskBackingInfo.getFileName()); + vmdkFileBaseNames.add(dsBackingFile.getFileBaseName()); + } + } + } + return vmdkFileBaseNames; + } + // this method relies on un-offical VMware API @Deprecated public void moveAllVmDiskFiles(DatastoreMO destDsMo, String destDsDir, boolean followDiskChain) throws Exception { @@ -1780,7 +1796,7 @@ public class VirtualMachineMO extends BaseMO { } public int getScsiDeviceControllerKey() throws Exception { - List devices = (List)_context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); + List devices = _context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); if (devices != null && devices.size() > 0) { for (VirtualDevice device : devices) { @@ -1795,7 +1811,7 @@ public class VirtualMachineMO extends BaseMO { } public int getScsiDeviceControllerKeyNoException() throws Exception { - List devices = (List)_context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); + List devices = _context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); if (devices != null && devices.size() > 0) { for (VirtualDevice device : devices) { @@ -1831,7 +1847,7 @@ public class VirtualMachineMO extends BaseMO { // return pair of VirtualDisk and disk device bus name(ide0:0, etc) public Pair getDiskDevice(String vmdkDatastorePath, boolean matchExactly) throws Exception { - List devices = (List)_context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); + List devices = _context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); s_logger.info("Look for disk device info from volume : " + vmdkDatastorePath); DatastoreFile dsSrcFile = new DatastoreFile(vmdkDatastorePath); @@ -1877,7 +1893,7 @@ public class VirtualMachineMO extends BaseMO { } public String getDiskCurrentTopBackingFileInChain(String deviceBusName) throws Exception { - List devices = (List)_context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); + List devices = _context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); if (devices != null && devices.size() > 0) { for (VirtualDevice device : devices) { if (device instanceof VirtualDisk) { @@ -1899,7 +1915,7 @@ public class VirtualMachineMO extends BaseMO { } public VirtualDisk getDiskDeviceByDeviceBusName(String deviceBusName) throws Exception { - List devices = (List)_context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); + List devices = _context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); if (devices != null && devices.size() > 0) { for (VirtualDevice device : devices) { @@ -1917,7 +1933,7 @@ public class VirtualMachineMO extends BaseMO { public VirtualMachineDiskInfoBuilder getDiskInfoBuilder() throws Exception { VirtualMachineDiskInfoBuilder builder = new VirtualMachineDiskInfoBuilder(); - List devices = (List)_context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); + List devices = _context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); if (devices != null && devices.size() > 0) { for (VirtualDevice device : devices) { @@ -2033,7 +2049,7 @@ public class VirtualMachineMO extends BaseMO { public List getVirtualDisks() throws Exception { List virtualDisks = new ArrayList(); - List devices = (List)_context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); + List devices = _context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); for (VirtualDevice device : devices) { if (device instanceof VirtualDisk) { @@ -2045,7 +2061,7 @@ public class VirtualMachineMO extends BaseMO { } public List detachAllDisksExcept(String vmdkBaseName, String deviceBusName) throws Exception { - List devices = (List)_context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); + List devices = _context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec(); List detachedDiskFiles = new ArrayList(); @@ -2089,12 +2105,12 @@ public class VirtualMachineMO extends BaseMO { } public List getAllDeviceList() throws Exception { - return (List)_context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); + return _context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); } public VirtualDisk[] getAllDiskDevice() throws Exception { List deviceList = new ArrayList(); - List devices = (List)_context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); + List devices = _context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); if (devices != null && devices.size() > 0) { for (VirtualDevice device : devices) { if (device instanceof VirtualDisk) { @@ -2147,7 +2163,7 @@ public class VirtualMachineMO extends BaseMO { } public int tryGetIDEDeviceControllerKey() throws Exception { - List devices = (List)_context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); + List devices = _context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); if (devices != null && devices.size() > 0) { for (VirtualDevice device : devices) { @@ -2161,7 +2177,7 @@ public class VirtualMachineMO extends BaseMO { } public int getIDEDeviceControllerKey() throws Exception { - List devices = (List)_context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); + List devices = _context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); if (devices != null && devices.size() > 0) { for (VirtualDevice device : devices) { @@ -2181,7 +2197,7 @@ public class VirtualMachineMO extends BaseMO { } public VirtualDevice getIsoDevice() throws Exception { - List devices = (List)_context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); + List devices = _context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); if (devices != null && devices.size() > 0) { for (VirtualDevice device : devices) { if (device instanceof VirtualCdrom) { @@ -2193,7 +2209,7 @@ public class VirtualMachineMO extends BaseMO { } public int getPCIDeviceControllerKey() throws Exception { - List devices = (List)_context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); + List devices = _context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); if (devices != null && devices.size() > 0) { for (VirtualDevice device : devices) { @@ -2213,7 +2229,7 @@ public class VirtualMachineMO extends BaseMO { } public int getNextDeviceNumber(int controllerKey) throws Exception { - List devices = (List)_context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); + List devices = _context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); int deviceNumber = -1; if (devices != null && devices.size() > 0) { @@ -2229,7 +2245,7 @@ public class VirtualMachineMO extends BaseMO { } private List getNicDevices(boolean sorted) throws Exception { - List devices = (List)_context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); + List devices = _context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); List nics = new ArrayList(); if (devices != null) { @@ -2309,7 +2325,7 @@ public class VirtualMachineMO extends BaseMO { List returnList = new ArrayList(); - List devices = (List)_context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); + List devices = _context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); if (devices != null) { for (VirtualDevice device : devices) { @@ -2329,12 +2345,13 @@ public class VirtualMachineMO extends BaseMO { _context.getService().mountToolsInstaller(_mor); } - public void unmountToolsInstaller() throws Exception { - int i = 1; + public boolean unmountToolsInstaller() throws Exception { // Monitor VM questions final Boolean[] flags = {false}; final VirtualMachineMO vmMo = this; - Future future = _monitorServiceExecutor.submit(new Runnable() { + final boolean[] encounterQuestion = new boolean[1]; + encounterQuestion[0] = false; + Future future = MonitorServiceExecutor.submit(new Runnable() { @Override public void run() { s_logger.info("VM Question monitor started..."); @@ -2344,6 +2361,7 @@ public class VirtualMachineMO extends BaseMO { VirtualMachineRuntimeInfo runtimeInfo = vmMo.getRuntimeInfo(); VirtualMachineQuestionInfo question = runtimeInfo.getQuestion(); if (question != null) { + encounterQuestion[0] = true; if (s_logger.isTraceEnabled()) { s_logger.trace("Question id: " + question.getId()); s_logger.trace("Question text: " + question.getText()); @@ -2357,7 +2375,7 @@ public class VirtualMachineMO extends BaseMO { } if ("msg.cdromdisconnect.locked".equalsIgnoreCase(msg.getId())) { s_logger.info("Found that VM has a pending question that we need to answer programmatically, question id: " + msg.getId() + - ", for safe operation we will automatically decline it"); + ", for safe operation we will automatically decline it"); vmMo.answerVM(question.getId(), "1"); break; } @@ -2374,7 +2392,7 @@ public class VirtualMachineMO extends BaseMO { msgText = tokens[1]; if ("msg.cdromdisconnect.locked".equalsIgnoreCase(msgId)) { s_logger.info("Found that VM has a pending question that we need to answer programmatically, question id: " + question.getId() + - ". Message id : " + msgId + ". Message text : " + msgText + ", for safe operation we will automatically decline it."); + ". Message id : " + msgId + ". Message text : " + msgText + ", for safe operation we will automatically decline it."); vmMo.answerVM(question.getId(), "1"); } } @@ -2409,6 +2427,13 @@ public class VirtualMachineMO extends BaseMO { flags[0] = true; future.cancel(true); } + if (encounterQuestion[0]) { + s_logger.warn("cdrom is locked by VM. Failed to detach the ISO."); + return false; + } else { + s_logger.info("Successfully unmounted tools installer from VM."); + return true; + } } public void redoRegistration(ManagedObjectReference morHost) throws Exception { diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VmwareHypervisorHost.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VmwareHypervisorHost.java index 5588a6abf9c..9727e173316 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VmwareHypervisorHost.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VmwareHypervisorHost.java @@ -67,6 +67,8 @@ public interface VmwareHypervisorHost { ManagedObjectReference findDatastore(String poolUuid) throws Exception; + ManagedObjectReference findDatastoreByName(String datastoreName) throws Exception; + @Deprecated ManagedObjectReference findDatastoreByExportPath(String exportPath) throws Exception; diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java index 9ecd9879045..9284569da32 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java @@ -27,8 +27,11 @@ import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; import javax.xml.ws.BindingProvider; +import javax.xml.ws.WebServiceException; import javax.xml.ws.handler.MessageContext; +import org.apache.log4j.Logger; + import com.vmware.vim25.DynamicProperty; import com.vmware.vim25.InvalidCollectorVersionFaultMsg; import com.vmware.vim25.InvalidPropertyFaultMsg; @@ -59,6 +62,7 @@ import com.vmware.vim25.VimService; * */ public class VmwareClient { + private static final Logger s_logger = Logger.getLogger(VmwareClient.class); private static class TrustAllTrustManager implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager { @@ -79,19 +83,19 @@ public class VmwareClient { } static { - try { - trustAllHttpsCertificates(); - HostnameVerifier hv = new HostnameVerifier() { - @Override - public boolean verify(String urlHostName, SSLSession session) { - return true; - } - }; - HttpsURLConnection.setDefaultHostnameVerifier(hv); - - vimService = new VimService(); - } catch (Exception e) { - } + try { + trustAllHttpsCertificates(); + HostnameVerifier hv = new HostnameVerifier() { + @Override + public boolean verify(String urlHostName, SSLSession session) { + return true; + } + }; + HttpsURLConnection.setDefaultHostnameVerifier(hv); + + vimService = new VimService(); + } catch (Exception e) { + } } private static void trustAllHttpsCertificates() throws Exception { @@ -106,11 +110,11 @@ public class VmwareClient { javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } - private ManagedObjectReference SVC_INST_REF = new ManagedObjectReference(); + private final ManagedObjectReference svcInstRef = new ManagedObjectReference(); private static VimService vimService; private VimPortType vimPort; private String serviceCookie; - private final String SVC_INST_NAME = "ServiceInstance"; + private final static String SVC_INST_NAME = "ServiceInstance"; private int vCenterSessionTimeout = 1200000; // Timeout in milliseconds private boolean isConnected = false; @@ -125,8 +129,8 @@ public class VmwareClient { * the exception */ public void connect(String url, String userName, String password) throws Exception { - SVC_INST_REF.setType(SVC_INST_NAME); - SVC_INST_REF.setValue(SVC_INST_NAME); + svcInstRef.setType(SVC_INST_NAME); + svcInstRef.setValue(SVC_INST_NAME); vimPort = vimService.getVimPort(); Map ctxt = ((BindingProvider)vimPort).getRequestContext(); @@ -137,9 +141,10 @@ public class VmwareClient { ctxt.put("com.sun.xml.internal.ws.request.timeout", vCenterSessionTimeout); ctxt.put("com.sun.xml.internal.ws.connect.timeout", vCenterSessionTimeout); - ServiceContent serviceContent = vimPort.retrieveServiceContent(SVC_INST_REF); + ServiceContent serviceContent = vimPort.retrieveServiceContent(svcInstRef); // Extract a cookie. See vmware sample program com.vmware.httpfileaccess.GetVMFiles + @SuppressWarnings("unchecked") Map> headers = (Map>)((BindingProvider)vimPort).getResponseContext().get(MessageContext.HTTP_RESPONSE_HEADERS); List cookies = headers.get("Set-cookie"); String cookieValue = cookies.get(0); @@ -177,7 +182,7 @@ public class VmwareClient { public ServiceContent getServiceContent() { try { - return vimPort.retrieveServiceContent(SVC_INST_REF); + return vimPort.retrieveServiceContent(svcInstRef); } catch (RuntimeFaultFaultMsg e) { } return null; @@ -252,7 +257,8 @@ public class VmwareClient { * @throws Exception * in case of error. */ - public Object getDynamicProperty(ManagedObjectReference mor, String propertyName) throws Exception { + @SuppressWarnings("unchecked") + public T getDynamicProperty(ManagedObjectReference mor, String propertyName) throws Exception { List props = new ArrayList(); props.add(propertyName); List objContent = retrieveMoRefProperties(mor, props); @@ -280,7 +286,7 @@ public class VmwareClient { } } } - return propertyValue; + return (T)propertyValue; } private List retrieveMoRefProperties(ManagedObjectReference mObj, List props) throws Exception { @@ -313,20 +319,25 @@ public class VmwareClient { * @throws RuntimeFaultFaultMsg * @throws InvalidPropertyFaultMsg */ - public boolean waitForTask(ManagedObjectReference task) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, InvalidCollectorVersionFaultMsg { + public boolean waitForTask(ManagedObjectReference task) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, InvalidCollectorVersionFaultMsg, Exception { boolean retVal = false; - // info has a property - state for state of the task - Object[] result = - waitForValues(task, new String[] {"info.state", "info.error"}, new String[] {"state"}, new Object[][] {new Object[] {TaskInfoState.SUCCESS, - TaskInfoState.ERROR}}); + try { + // info has a property - state for state of the task + Object[] result = waitForValues(task, new String[] { "info.state", "info.error" }, new String[] { "state" }, new Object[][] { new Object[] { + TaskInfoState.SUCCESS, TaskInfoState.ERROR } }); - if (result[0].equals(TaskInfoState.SUCCESS)) { - retVal = true; - } - if (result[1] instanceof LocalizedMethodFault) { - throw new RuntimeException(((LocalizedMethodFault)result[1]).getLocalizedMessage()); + if (result[0].equals(TaskInfoState.SUCCESS)) { + retVal = true; + } + if (result[1] instanceof LocalizedMethodFault) { + throw new RuntimeException(((LocalizedMethodFault) result[1]).getLocalizedMessage()); + } + } catch(WebServiceException we) { + s_logger.debug("Cancelling vCenter task because task failed with " + we.getLocalizedMessage()); + getService().cancelTask(task); + throw new RuntimeException("vCenter task failed due to " + we.getLocalizedMessage()); } return retVal; } @@ -350,7 +361,7 @@ public class VmwareClient { * @throws InvalidCollectorVersionFaultMsg */ private Object[] waitForValues(ManagedObjectReference objmor, String[] filterProps, String[] endWaitProps, Object[][] expectedVals) throws InvalidPropertyFaultMsg, - RuntimeFaultFaultMsg, InvalidCollectorVersionFaultMsg { + RuntimeFaultFaultMsg, InvalidCollectorVersionFaultMsg { // version string is initially null String version = ""; Object[] endVals = new Object[endWaitProps.length]; diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareContext.java b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareContext.java index 44d9f0cc9f5..08456c4b782 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareContext.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareContext.java @@ -26,6 +26,7 @@ import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; +import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; @@ -37,6 +38,7 @@ import java.util.Map; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; +import javax.xml.ws.soap.SOAPFaultException; import org.apache.log4j.Logger; @@ -57,10 +59,10 @@ import com.cloud.utils.ActionDelegate; public class VmwareContext { private static final Logger s_logger = Logger.getLogger(VmwareContext.class); - private static int MAX_CONNECT_RETRY = 5; - private static int CONNECT_RETRY_INTERVAL = 1000; + private static final int MAX_CONNECT_RETRY = 5; + private static final int CONNECT_RETRY_INTERVAL = 1000; - private final int _CHUNKSIZE = 1 * 1024 * 1024; // 1M + private static final int ChunkSize = 1 * 1024 * 1024; // 1M private final VmwareClient _vimClient; private final String _serverAddress; @@ -327,7 +329,7 @@ public class VmwareContext { InputStream in = conn.getInputStream(); OutputStream out = new FileOutputStream(new File(localFileFullName)); - byte[] buf = new byte[_CHUNKSIZE]; + byte[] buf = new byte[ChunkSize]; int len = 0; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); @@ -349,7 +351,7 @@ public class VmwareContext { try { out = conn.getOutputStream(); in = new FileInputStream(localFile); - byte[] buf = new byte[_CHUNKSIZE]; + byte[] buf = new byte[ChunkSize]; int len = 0; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); @@ -374,14 +376,14 @@ public class VmwareContext { } } - public void uploadVmdkFile(String httpMethod, String urlString, String localFileName, long totalBytesUpdated, ActionDelegate progressUpdater) throws Exception { + public void uploadVmdkFile(String httpMethod, String urlString, String localFileName, long totalBytesUpdated, ActionDelegate progressUpdater) throws Exception { HttpURLConnection conn = getRawHTTPConnection(urlString); conn.setDoOutput(true); conn.setUseCaches(false); - conn.setChunkedStreamingMode(_CHUNKSIZE); + conn.setChunkedStreamingMode(ChunkSize); conn.setRequestMethod(httpMethod); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "application/x-vnd.vmware-streamVmdk"); @@ -393,7 +395,7 @@ public class VmwareContext { try { bos = new BufferedOutputStream(conn.getOutputStream()); is = new BufferedInputStream(new FileInputStream(localFileName)); - int bufferSize = _CHUNKSIZE; + int bufferSize = ChunkSize; byte[] buffer = new byte[bufferSize]; while (true) { int bytesRead = is.read(buffer, 0, bufferSize); @@ -417,7 +419,7 @@ public class VmwareContext { } } - public long downloadVmdkFile(String urlString, String localFileName, long totalBytesDownloaded, ActionDelegate progressUpdater) throws Exception { + public long downloadVmdkFile(String urlString, String localFileName, long totalBytesDownloaded, ActionDelegate progressUpdater) throws Exception { HttpURLConnection conn = getRawHTTPConnection(urlString); String cookie = _vimClient.getServiceCookie(); @@ -438,7 +440,7 @@ public class VmwareContext { in = conn.getInputStream(); out = new FileOutputStream(new File(localFileName)); - byte[] buf = new byte[_CHUNKSIZE]; + byte[] buf = new byte[ChunkSize]; int len = 0; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); @@ -464,7 +466,7 @@ public class VmwareContext { InputStream in = conn.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); - byte[] buf = new byte[_CHUNKSIZE]; + byte[] buf = new byte[ChunkSize]; int len = 0; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); @@ -546,7 +548,7 @@ public class VmwareContext { - */ + */ public String[] listDatastoreDirContent(String urlString) throws Exception { List fileList = new ArrayList(); String content = new String(getResourceContent(urlString)); @@ -582,8 +584,12 @@ public class VmwareContext { sb.append(_serverAddress); sb.append("/folder/"); sb.append(relativePath); - sb.append("?dcPath=").append(URLEncoder.encode(dcName)).append("&dsName="); - sb.append(URLEncoder.encode(datastoreName)); + try { + sb.append("?dcPath=").append(URLEncoder.encode(dcName, "UTF-8")); + sb.append("&dsName=").append(URLEncoder.encode(datastoreName, "UTF-8")); + } catch (UnsupportedEncodingException e) { + s_logger.error("Unable to encode URL. dcPath : " + dcName + ", dsName :" + datastoreName, e); + } return sb.toString(); } @@ -638,16 +644,18 @@ public class VmwareContext { public void close() { clearStockObjects(); try { + s_logger.info("Disconnecting VMware session"); _vimClient.disconnect(); + } catch(SOAPFaultException sfe) { + s_logger.debug("Tried to disconnect a session that is no longer valid"); } catch (Exception e) { s_logger.warn("Unexpected exception: ", e); + } finally { + if (_pool != null) { + _pool.unregisterOutstandingContext(this); + } + unregisterOutstandingContext(); } - - if (_pool != null) { - _pool.unregisterOutstandingContext(this); - } - - unregisterOutstandingContext(); } public static class TrustAllManager implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager { diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareContextPool.java b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareContextPool.java index e744cbfd4b0..c97c01f32c3 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareContextPool.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareContextPool.java @@ -134,41 +134,6 @@ public class VmwareContextPool { }; } - private void getIdleCheckContexts(List l, int batchSize) { - synchronized (this) { - for (Map.Entry> entry : _pool.entrySet()) { - if (entry.getValue() != null) { - int count = 0; - while (entry.getValue().size() > 0 && count < batchSize) { - VmwareContext context = entry.getValue().remove(0); - context.setPoolInfo(this, entry.getKey()); - l.add(context); - count++; - } - } - } - } - } - - private void doIdleCheck() { - List l = new ArrayList(); - int batchSize = (int)(_idleCheckIntervalMs / 1000); // calculate batch size at 1 request/sec rate - getIdleCheckContexts(l, batchSize); - - for (VmwareContext context : l) { - try { - context.idleCheck(); - - if (s_logger.isTraceEnabled()) - s_logger.trace("Recyle context after idle check"); - returnContext(context); - } catch (Throwable e) { - s_logger.warn("Exception caught during VmwareContext idle check, close and discard the context", e); - context.close(); - } - } - } - private void getKeepAliveCheckContexts(List l, int batchSize) { synchronized (this) { int size = Math.min(_outstandingRegistry.size(), batchSize); diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareGuestOsMapper.java b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareGuestOsMapper.java index 1f3d28b7ca1..dd68737c3f6 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareGuestOsMapper.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareGuestOsMapper.java @@ -148,6 +148,7 @@ public class VmwareGuestOsMapper { s_mapper.put("Red Hat Enterprise Linux 5.3 (64-bit)", VirtualMachineGuestOsIdentifier.RHEL_5_64_GUEST); s_mapper.put("Red Hat Enterprise Linux 5.4 (32-bit)", VirtualMachineGuestOsIdentifier.RHEL_5_GUEST); s_mapper.put("Red Hat Enterprise Linux 5.4 (64-bit)", VirtualMachineGuestOsIdentifier.RHEL_5_64_GUEST); + s_mapper.put("Red Hat Enterprise Linux 6.0 (32-bit)", VirtualMachineGuestOsIdentifier.RHEL_6_GUEST); s_mapper.put("Red Hat Enterprise Linux 6.0 (64-bit)", VirtualMachineGuestOsIdentifier.RHEL_6_64_GUEST); s_mapper.put("Red Hat Enterprise Linux 6.1 (32-bit)", VirtualMachineGuestOsIdentifier.RHEL_6_GUEST); s_mapper.put("Red Hat Enterprise Linux 6.1 (64-bit)", VirtualMachineGuestOsIdentifier.RHEL_6_64_GUEST); @@ -170,6 +171,8 @@ public class VmwareGuestOsMapper { s_mapper.put("Ubuntu 10.04 (64-bit)", VirtualMachineGuestOsIdentifier.UBUNTU_64_GUEST); s_mapper.put("Ubuntu 10.10 (32-bit)", VirtualMachineGuestOsIdentifier.UBUNTU_GUEST); s_mapper.put("Ubuntu 10.10 (64-bit)", VirtualMachineGuestOsIdentifier.UBUNTU_64_GUEST); + s_mapper.put("Ubuntu 12.04 (32-bit)", VirtualMachineGuestOsIdentifier.UBUNTU_GUEST); + s_mapper.put("Ubuntu 12.04 (64-bit)", VirtualMachineGuestOsIdentifier.UBUNTU_64_GUEST); s_mapper.put("Other Ubuntu (32-bit)", VirtualMachineGuestOsIdentifier.UBUNTU_GUEST); s_mapper.put("Other Ubuntu (64-bit)", VirtualMachineGuestOsIdentifier.UBUNTU_64_GUEST); @@ -185,4 +188,5 @@ public class VmwareGuestOsMapper { public static VirtualMachineGuestOsIdentifier getGuestOsIdentifier(String guestOsName) { return s_mapper.get(guestOsName); } + } diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareHelper.java b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareHelper.java index c1658b04c87..d29e0f27237 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareHelper.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareHelper.java @@ -71,6 +71,7 @@ import com.cloud.utils.Ternary; import com.cloud.utils.exception.ExceptionUtil; public class VmwareHelper { + @SuppressWarnings("unused") private static final Logger s_logger = Logger.getLogger(VmwareHelper.class); public static boolean isReservedScsiDeviceNumber(int deviceNumber) { @@ -78,29 +79,29 @@ public class VmwareHelper { } public static VirtualDevice prepareNicDevice(VirtualMachineMO vmMo, ManagedObjectReference morNetwork, VirtualEthernetCardType deviceType, String portGroupName, - String macAddress, int deviceNumber, int contextNumber, boolean conntected, boolean connectOnStart) throws Exception { + String macAddress, int deviceNumber, int contextNumber, boolean conntected, boolean connectOnStart) throws Exception { VirtualEthernetCard nic; switch (deviceType) { - case E1000: - nic = new VirtualE1000(); - break; + case E1000: + nic = new VirtualE1000(); + break; - case PCNet32: - nic = new VirtualPCNet32(); - break; + case PCNet32: + nic = new VirtualPCNet32(); + break; - case Vmxnet2: - nic = new VirtualVmxnet2(); - break; + case Vmxnet2: + nic = new VirtualVmxnet2(); + break; - case Vmxnet3: - nic = new VirtualVmxnet3(); - break; + case Vmxnet3: + nic = new VirtualVmxnet3(); + break; - default: - assert (false); - nic = new VirtualE1000(); + default: + assert (false); + nic = new VirtualE1000(); } VirtualEthernetCardNetworkBackingInfo nicBacking = new VirtualEthernetCardNetworkBackingInfo(); @@ -121,29 +122,29 @@ public class VmwareHelper { } public static VirtualDevice prepareDvNicDevice(VirtualMachineMO vmMo, ManagedObjectReference morNetwork, VirtualEthernetCardType deviceType, String dvPortGroupName, - String dvSwitchUuid, String macAddress, int deviceNumber, int contextNumber, boolean conntected, boolean connectOnStart) throws Exception { + String dvSwitchUuid, String macAddress, int deviceNumber, int contextNumber, boolean conntected, boolean connectOnStart) throws Exception { VirtualEthernetCard nic; switch (deviceType) { - case E1000: - nic = new VirtualE1000(); - break; + case E1000: + nic = new VirtualE1000(); + break; - case PCNet32: - nic = new VirtualPCNet32(); - break; + case PCNet32: + nic = new VirtualPCNet32(); + break; - case Vmxnet2: - nic = new VirtualVmxnet2(); - break; + case Vmxnet2: + nic = new VirtualVmxnet2(); + break; - case Vmxnet3: - nic = new VirtualVmxnet3(); - break; + case Vmxnet3: + nic = new VirtualVmxnet3(); + break; - default: - assert (false); - nic = new VirtualE1000(); + default: + assert (false); + nic = new VirtualE1000(); } final VirtualEthernetCardDistributedVirtualPortBackingInfo dvPortBacking = new VirtualEthernetCardDistributedVirtualPortBackingInfo(); @@ -170,7 +171,7 @@ public class VmwareHelper { // vmdkDatastorePath: [datastore name] vmdkFilePath public static VirtualDevice prepareDiskDevice(VirtualMachineMO vmMo, int controllerKey, String vmdkDatastorePath, int sizeInMb, ManagedObjectReference morDs, - int deviceNumber, int contextNumber) throws Exception { + int deviceNumber, int contextNumber) throws Exception { VirtualDisk disk = new VirtualDisk(); @@ -206,7 +207,7 @@ public class VmwareHelper { // vmdkDatastorePath: [datastore name] vmdkFilePath, create delta disk based on disk from template public static VirtualDevice prepareDiskDevice(VirtualMachineMO vmMo, int controllerKey, String vmdkDatastorePath, int sizeInMb, ManagedObjectReference morDs, - VirtualDisk templateDisk, int deviceNumber, int contextNumber) throws Exception { + VirtualDisk templateDisk, int deviceNumber, int contextNumber) throws Exception { assert (templateDisk != null); VirtualDeviceBackingInfo parentBacking = templateDisk.getBacking(); @@ -277,7 +278,7 @@ public class VmwareHelper { // vmdkDatastorePath: [datastore name] vmdkFilePath public static VirtualDevice prepareDiskDevice(VirtualMachineMO vmMo, VirtualDisk device, int controllerKey, String vmdkDatastorePathChain[], - ManagedObjectReference morDs, int deviceNumber, int contextNumber) throws Exception { + ManagedObjectReference morDs, int deviceNumber, int contextNumber) throws Exception { assert (vmdkDatastorePathChain != null); assert (vmdkDatastorePathChain.length >= 1); @@ -325,8 +326,9 @@ public class VmwareHelper { return disk; } + @SuppressWarnings("unchecked") public static VirtualDevice prepareDiskDevice(VirtualMachineMO vmMo, int controllerKey, Pair[] vmdkDatastorePathChain, - int deviceNumber, int contextNumber) throws Exception { + int deviceNumber, int contextNumber) throws Exception { assert (vmdkDatastorePathChain != null); assert (vmdkDatastorePathChain.length >= 1); @@ -385,6 +387,7 @@ public class VmwareHelper { backingInfo.setParent(parentBacking); } + @SuppressWarnings("unchecked") private static void setParentBackingInfo(VirtualDiskFlatVer2BackingInfo backingInfo, Pair[] parentDatastorePathList) { VirtualDiskFlatVer2BackingInfo parentBacking = new VirtualDiskFlatVer2BackingInfo(); @@ -403,7 +406,7 @@ public class VmwareHelper { } public static Pair prepareIsoDevice(VirtualMachineMO vmMo, String isoDatastorePath, ManagedObjectReference morDs, boolean connect, - boolean connectAtBoot, int deviceNumber, int contextNumber) throws Exception { + boolean connectAtBoot, int deviceNumber, int contextNumber) throws Exception { boolean newCdRom = false; VirtualCdrom cdRom = (VirtualCdrom)vmMo.getIsoDevice(); @@ -549,7 +552,7 @@ public class VmwareHelper { } public static void setVmScaleUpConfig(VirtualMachineConfigSpec vmConfig, int cpuCount, int cpuSpeedMHz, int cpuReservedMhz, int memoryMB, int memoryReserveMB, - boolean limitCpuUse) { + boolean limitCpuUse) { // VM config for scaling up vmConfig.setMemoryMB((long)memoryMB); @@ -573,7 +576,7 @@ public class VmwareHelper { } public static void setBasicVmConfig(VirtualMachineConfigSpec vmConfig, int cpuCount, int cpuSpeedMHz, int cpuReservedMhz, int memoryMB, int memoryReserveMB, - String guestOsIdentifier, boolean limitCpuUse) { + String guestOsIdentifier, boolean limitCpuUse) { // VM config basics vmConfig.setMemoryMB((long)memoryMB); @@ -640,10 +643,10 @@ public class VmwareHelper { //TODO: in vim 5.1, exceptions do not have a base exception class, MethodFault becomes a FaultInfo that we can only get // from individual exception through getFaultInfo, so we have to use reflection here to get MethodFault information. try { - Class cls = e.getClass(); - Method mth = cls.getDeclaredMethod("getFaultInfo", null); + Class cls = e.getClass(); + Method mth = cls.getDeclaredMethod("getFaultInfo", (Class)null); if (mth != null) { - Object fault = mth.invoke(e, null); + Object fault = mth.invoke(e, (Object[])null); if (fault instanceof MethodFault) { final StringWriter writer = new StringWriter(); writer.append("Exception: " + fault.getClass().getName() + "\n");