diff --git a/.gitignore b/.gitignore index 15f7f91c864..f41862895ec 100644 --- a/.gitignore +++ b/.gitignore @@ -75,3 +75,11 @@ docs/runbook/tmp docs/runbook/publish .project Gemfile.lock +debian/tmp +debian/files +debian/cloudstack-*/* +debian/*.substvars +debian/*.debhelper +replace.properties.tmp +build-indep-stamp +configure-stamp diff --git a/agent/conf/agent.properties b/agent/conf/agent.properties index f7eac674712..e49afbf2aaf 100644 --- a/agent/conf/agent.properties +++ b/agent/conf/agent.properties @@ -80,3 +80,12 @@ domr.scripts.dir=scripts/network/domr/kvm # native = com.cloud.hypervisor.kvm.resource.BridgeVifDriver # openvswitch = com.cloud.hypervisor.kvm.resource.OvsBridgeDriver #libvirt.vif.driver=com.cloud.hypervisor.kvm.resource.BridgeVifDriver + +# set the hypervisor type, values are: kvm, lxc +# hypervisor.type=kvm + +# settings to enable direct networking in libvirt, should not be used +# on hosts that run system vms, values for mode are: private, bridge, vepa +# libvirt.vif.driver=com.cloud.hypervisor.kvm.resource.DirectVifDriver +# network.direct.source.mode=private +# network.direct.device=eth0 diff --git a/api/src/com/cloud/agent/api/Command.java b/api/src/com/cloud/agent/api/Command.java index 9cd67495e04..aadbeaf0def 100755 --- a/api/src/com/cloud/agent/api/Command.java +++ b/api/src/com/cloud/agent/api/Command.java @@ -27,6 +27,8 @@ import com.cloud.agent.api.LogLevel.Log4jLevel; */ public abstract class Command { + public static final String HYPERVISOR_TYPE = "hypervisorType"; + // allow command to carry over hypervisor or other environment related context info @LogLevel(Log4jLevel.Trace) protected Map contextMap = new HashMap(); diff --git a/api/src/com/cloud/agent/api/RebootCommand.java b/api/src/com/cloud/agent/api/RebootCommand.java index 299e61b76af..49712b6fce5 100755 --- a/api/src/com/cloud/agent/api/RebootCommand.java +++ b/api/src/com/cloud/agent/api/RebootCommand.java @@ -16,6 +16,7 @@ // under the License. package com.cloud.agent.api; +import com.cloud.hypervisor.Hypervisor; import com.cloud.vm.VirtualMachine; public class RebootCommand extends Command { diff --git a/api/src/com/cloud/agent/api/StopCommand.java b/api/src/com/cloud/agent/api/StopCommand.java index 9ee7ce3c874..1c67f3816ca 100755 --- a/api/src/com/cloud/agent/api/StopCommand.java +++ b/api/src/com/cloud/agent/api/StopCommand.java @@ -38,10 +38,9 @@ public class StopCommand extends RebootCommand { super(vm); this.vnet = vnet; } - - public StopCommand(VirtualMachine vm, String vmName, String vnet) { - super(vmName); - this.vnet = vnet; + + public StopCommand(VirtualMachine vm) { + super(vm); } public StopCommand(String vmName) { diff --git a/api/src/com/cloud/event/EventTypes.java b/api/src/com/cloud/event/EventTypes.java index ea7781671dc..b995e481286 100755 --- a/api/src/com/cloud/event/EventTypes.java +++ b/api/src/com/cloud/event/EventTypes.java @@ -122,9 +122,11 @@ public class EventTypes { public static final String EVENT_GLOBAL_LOAD_BALANCER_DELETE = "GLOBAL.LB.DELETE"; // Account events + public static final String EVENT_ACCOUNT_ENABLE = "ACCOUNT.ENABLE"; public static final String EVENT_ACCOUNT_DISABLE = "ACCOUNT.DISABLE"; public static final String EVENT_ACCOUNT_CREATE = "ACCOUNT.CREATE"; public static final String EVENT_ACCOUNT_DELETE = "ACCOUNT.DELETE"; + public static final String EVENT_ACCOUNT_UPDATE = "ACCOUNT.UPDATE"; public static final String EVENT_ACCOUNT_MARK_DEFAULT_ZONE = "ACCOUNT.MARK.DEFAULT.ZONE"; // UserVO Events @@ -137,6 +139,9 @@ public class EventTypes { public static final String EVENT_USER_ENABLE = "USER.ENABLE"; public static final String EVENT_USER_LOCK = "USER.LOCK"; + //registering SSH keypair events + public static final String EVENT_REGISTER_SSH_KEYPAIR = "REGISTER.SSH.KEYPAIR"; + // Template Events public static final String EVENT_TEMPLATE_CREATE = "TEMPLATE.CREATE"; public static final String EVENT_TEMPLATE_DELETE = "TEMPLATE.DELETE"; diff --git a/api/src/com/cloud/exception/AffinityConflictException.java b/api/src/com/cloud/exception/AffinityConflictException.java index da7148f1e2d..8b187783f24 100644 --- a/api/src/com/cloud/exception/AffinityConflictException.java +++ b/api/src/com/cloud/exception/AffinityConflictException.java @@ -1,3 +1,19 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. package com.cloud.exception; import com.cloud.utils.SerialVersionUID; diff --git a/api/src/com/cloud/hypervisor/Hypervisor.java b/api/src/com/cloud/hypervisor/Hypervisor.java index 2e0012dca6f..a4ee5b98fd9 100644 --- a/api/src/com/cloud/hypervisor/Hypervisor.java +++ b/api/src/com/cloud/hypervisor/Hypervisor.java @@ -29,6 +29,7 @@ public class Hypervisor { BareMetal, Simulator, Ovm, + LXC, Any; /*If you don't care about the hypervisor type*/ @@ -54,6 +55,8 @@ public class Hypervisor { return HypervisorType.Simulator; } else if (hypervisor.equalsIgnoreCase("Ovm")) { return HypervisorType.Ovm; + } else if (hypervisor.equalsIgnoreCase("LXC")) { + return HypervisorType.LXC; } else if (hypervisor.equalsIgnoreCase("Any")) { return HypervisorType.Any; } else { diff --git a/api/src/com/cloud/network/Network.java b/api/src/com/cloud/network/Network.java index c2ab655b103..c0b0117fc7e 100644 --- a/api/src/com/cloud/network/Network.java +++ b/api/src/com/cloud/network/Network.java @@ -136,8 +136,7 @@ public interface Network extends ControlledEntity, StateObject, I public static final Provider VPCVirtualRouter = new Provider("VpcVirtualRouter", false); public static final Provider None = new Provider("None", false); // NiciraNvp is not an "External" provider, otherwise we get in trouble with NetworkServiceImpl.providersConfiguredForExternalNetworking - public static final Provider NiciraNvp = new Provider("NiciraNvp", false); - public static final Provider MidokuraMidonet = new Provider("MidokuraMidonet", true); + public static final Provider NiciraNvp = new Provider("NiciraNvp", false); private String name; private boolean isExternal; diff --git a/api/src/com/cloud/network/NetworkModel.java b/api/src/com/cloud/network/NetworkModel.java index 916f28a00f2..4d7d714a7ae 100644 --- a/api/src/com/cloud/network/NetworkModel.java +++ b/api/src/com/cloud/network/NetworkModel.java @@ -260,5 +260,7 @@ public interface NetworkModel { String getStartIpv6Address(long id); - Nic getPlaceholderNic(Network network, Long podId); + boolean isProviderEnabledInZone(long zoneId, String provider); + + Nic getPlaceholderNicForRouter(Network network, Long podId); } \ No newline at end of file diff --git a/api/src/com/cloud/network/Networks.java b/api/src/com/cloud/network/Networks.java index e3d21584ad8..f085e9f3029 100755 --- a/api/src/com/cloud/network/Networks.java +++ b/api/src/com/cloud/network/Networks.java @@ -62,6 +62,7 @@ public class Networks { Vnet("vnet", Long.class), Storage("storage", Integer.class), Lswitch("lswitch", String.class), + Mido("mido", String.class), UnDecided(null, null); private String scheme; diff --git a/api/src/com/cloud/network/PhysicalNetwork.java b/api/src/com/cloud/network/PhysicalNetwork.java index 343a2b14e33..a2044a61047 100644 --- a/api/src/com/cloud/network/PhysicalNetwork.java +++ b/api/src/com/cloud/network/PhysicalNetwork.java @@ -36,7 +36,8 @@ public interface PhysicalNetwork extends Identity, InternalIdentity { L3, GRE, STT, - VNS; + VNS, + MIDO; } public enum BroadcastDomainRange { diff --git a/api/src/com/cloud/network/RemoteAccessVpn.java b/api/src/com/cloud/network/RemoteAccessVpn.java index 1b463309a5f..058b2f486e6 100644 --- a/api/src/com/cloud/network/RemoteAccessVpn.java +++ b/api/src/com/cloud/network/RemoteAccessVpn.java @@ -17,8 +17,10 @@ package com.cloud.network; import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface RemoteAccessVpn extends ControlledEntity { +public interface RemoteAccessVpn extends ControlledEntity, InternalIdentity, Identity { enum State { Added, Running, diff --git a/api/src/com/cloud/network/vpc/Vpc.java b/api/src/com/cloud/network/vpc/Vpc.java index c07077f7b7e..249e80f1aff 100644 --- a/api/src/com/cloud/network/vpc/Vpc.java +++ b/api/src/com/cloud/network/vpc/Vpc.java @@ -20,32 +20,63 @@ import org.apache.cloudstack.acl.ControlledEntity; import org.apache.cloudstack.api.Identity; import org.apache.cloudstack.api.InternalIdentity; -import com.cloud.network.Network; - public interface Vpc extends ControlledEntity, Identity, InternalIdentity { + public enum State { Enabled, Inactive } - public static final String _supportedProviders = Network.Provider.VPCVirtualRouter.getName(); - - boolean readyToUse(); - + /** + * + * @return VPC name + */ String getName(); + + /** + * @return the id of the zone the VPC belongs to + */ long getZoneId(); + + /** + * @return super CIDR of the VPC. All the networks participating in VPC, should have CIDRs that are the part of the super cidr + */ String getCidr(); + /** + * + * @return VPC state + */ State getState(); + + /** + * + * @return VPC offering id - the offering that VPC is created from + */ long getVpcOfferingId(); + + /** + * + * @return VPC display text + */ String getDisplayText(); + + /** + * + * @return VPC network domain. All networks participating in the VPC, become the part of the same network domain + */ String getNetworkDomain(); + + /** + * + * @return true if restart is required for the VPC; false otherwise + */ boolean isRestartRequired(); } diff --git a/api/src/com/cloud/network/vpc/VpcOffering.java b/api/src/com/cloud/network/vpc/VpcOffering.java index 1acfcd21418..3961d0aaba7 100644 --- a/api/src/com/cloud/network/vpc/VpcOffering.java +++ b/api/src/com/cloud/network/vpc/VpcOffering.java @@ -27,18 +27,33 @@ public interface VpcOffering extends InternalIdentity, Identity { public static final String defaultVPCOfferingName = "Default VPC offering"; + /** + * + * @return VPC offering name + */ String getName(); - String getUniqueName(); - + + /** + * @return VPC offering display text + */ String getDisplayText(); + + /** + * + * @return VPC offering state + */ State getState(); + /** + * + * @return true if offering is default - came with the cloudStack fresh install; false otherwise + */ boolean isDefault(); /** - * @return + * @return service offering id used by VPC virutal router */ Long getServiceOfferingId(); diff --git a/api/src/com/cloud/network/vpc/VpcProvisioningService.java b/api/src/com/cloud/network/vpc/VpcProvisioningService.java new file mode 100644 index 00000000000..70676ce07ab --- /dev/null +++ b/api/src/com/cloud/network/vpc/VpcProvisioningService.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.network.vpc; + +import java.util.List; +import java.util.Map; + +public interface VpcProvisioningService { + + public VpcOffering getVpcOffering(long vpcOfferingId); + + public VpcOffering createVpcOffering(String name, String displayText, List supportedServices, Map> serviceProviders); + + List listVpcOfferings(Long id, String name, String displayText, List supportedServicesStr, + Boolean isDefault, String keyword, String state, Long startIndex, Long pageSizeVal); + + /** + * @param offId + * @return + */ + public boolean deleteVpcOffering(long offId); + + /** + * @param vpcOffId + * @param vpcOfferingName + * @param displayText + * @param state + * @return + */ + public VpcOffering updateVpcOffering(long vpcOffId, String vpcOfferingName, String displayText, String state); + +} diff --git a/api/src/com/cloud/network/vpc/VpcService.java b/api/src/com/cloud/network/vpc/VpcService.java index 9bf1beea5f0..07ce89b0a3f 100644 --- a/api/src/com/cloud/network/vpc/VpcService.java +++ b/api/src/com/cloud/network/vpc/VpcService.java @@ -18,7 +18,6 @@ package com.cloud.network.vpc; import java.util.List; import java.util.Map; -import java.util.Set; import org.apache.cloudstack.api.command.user.vpc.ListPrivateGatewaysCmd; import org.apache.cloudstack.api.command.user.vpc.ListStaticRoutesCmd; @@ -31,45 +30,29 @@ import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.IpAddress; import com.cloud.network.Network; -import com.cloud.network.Network.Provider; -import com.cloud.network.Network.Service; -import com.cloud.user.Account; -import com.cloud.user.User; import com.cloud.utils.Pair; public interface VpcService { - public VpcOffering getVpcOffering(long vpcOfferingId); - - public VpcOffering createVpcOffering(String name, String displayText, List supportedServices, Map> serviceProviders); - + /**Returns existing VPC found by id + * + * @param vpcId + * @return + */ public Vpc getVpc(long vpcId); - public Vpc getActiveVpc(long vpcId); - + + /** + * Returns all the Guest networks that are part of VPC + * + * @param vpcId + * @return + */ public List getVpcNetworks(long vpcId); - Map> getVpcOffSvcProvidersMap(long vpcOffId); - - List listVpcOfferings(Long id, String name, String displayText, List supportedServicesStr, - Boolean isDefault, String keyword, String state, Long startIndex, Long pageSizeVal); - - /** - * @param offId - * @return - */ - public boolean deleteVpcOffering(long offId); - - /** - * @param vpcOffId - * @param vpcOfferingName - * @param displayText - * @param state - * @return - */ - public VpcOffering updateVpcOffering(long vpcOffId, String vpcOfferingName, String displayText, String state); - /** + * Persists VPC record in the database + * * @param zoneId * @param vpcOffId * @param vpcOwnerId @@ -83,7 +66,10 @@ public interface VpcService { public Vpc createVpc(long zoneId, long vpcOffId, long vpcOwnerId, String vpcName, String displayText, String cidr, String networkDomain) throws ResourceAllocationException; + /** + * Deletes a VPC + * * @param vpcId * @return * @throws InsufficientCapacityException @@ -92,7 +78,10 @@ public interface VpcService { */ public boolean deleteVpc(long vpcId) throws ConcurrentOperationException, ResourceUnavailableException; + /** + * Updates VPC with new name/displayText + * * @param vpcId * @param vpcName * @param displayText @@ -100,7 +89,10 @@ public interface VpcService { */ public Vpc updateVpc(long vpcId, String vpcName, String displayText); + /** + * Lists VPC(s) based on the parameters passed to the method call + * * @param id * @param vpcName * @param displayText @@ -127,6 +119,8 @@ public interface VpcService { Boolean restartRequired, Map tags, Long projectId); /** + * Starts VPC which includes starting VPC provider and applying all the neworking rules on the backend + * * @param vpcId * @param destroyOnFailure TODO * @return @@ -138,6 +132,8 @@ public interface VpcService { ResourceUnavailableException, InsufficientCapacityException; /** + * Shuts down the VPC which includes shutting down all VPC provider and rules cleanup on the backend + * * @param vpcId * @return * @throws ConcurrentOperationException @@ -145,16 +141,28 @@ public interface VpcService { */ boolean shutdownVpc(long vpcId) throws ConcurrentOperationException, ResourceUnavailableException; + /** + * Restarts the VPC. VPC gets shutdown and started as a part of it + * * @param id * @return * @throws InsufficientCapacityException */ boolean restartVpc(long id) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; + /** + * Returns a Private gateway found in the VPC by id + * + * @param id + * @return + */ PrivateGateway getVpcPrivateGateway(long id); + /** + * Persists VPC private gateway in the Database. + * * @param vpcId TODO * @param physicalNetworkId * @param vlan @@ -172,6 +180,8 @@ public interface VpcService { ConcurrentOperationException, InsufficientCapacityException; /** + * Applies VPC private gateway on the backend, so it becomes functional + * * @param gatewayId * @param destroyOnFailure TODO * @return @@ -180,7 +190,10 @@ public interface VpcService { */ public PrivateGateway applyVpcPrivateGateway(long gatewayId, boolean destroyOnFailure) throws ConcurrentOperationException, ResourceUnavailableException; + /** + * Deletes VPC private gateway + * * @param id * @return * @throws ResourceUnavailableException @@ -188,52 +201,76 @@ public interface VpcService { */ boolean deleteVpcPrivateGateway(long gatewayId) throws ConcurrentOperationException, ResourceUnavailableException; + /** + * Returns the list of Private gateways existing in the VPC + * * @param listPrivateGatewaysCmd * @return */ public Pair, Integer> listPrivateGateway(ListPrivateGatewaysCmd listPrivateGatewaysCmd); + /** + * Returns Static Route found by Id + * * @param routeId * @return */ StaticRoute getStaticRoute(long routeId); + /** + * Applies existing Static Routes to the VPC elements + * * @param vpcId * @return * @throws ResourceUnavailableException */ public boolean applyStaticRoutes(long vpcId) throws ResourceUnavailableException; + /** + * Deletes static route from the backend and the database + * * @param routeId * @return TODO * @throws ResourceUnavailableException */ public boolean revokeStaticRoute(long routeId) throws ResourceUnavailableException; + /** + * Persists static route entry in the Database + * * @param gatewayId * @param cidr * @return */ public StaticRoute createStaticRoute(long gatewayId, String cidr) throws NetworkRuleConflictException; + /** + * Lists static routes based on parameters passed to the call + * * @param listStaticRoutesCmd * @return */ public Pair, Integer> listStaticRoutes(ListStaticRoutesCmd cmd); + /** + * Returns gateway (VPN or Public) existign in the VPC + * * @param id * @return */ VpcGateway getVpcGateway(long id); + /** + * Associates IP address from the Public network, to the VPC + * * @param ipId * @param vpcId * @return @@ -245,6 +282,4 @@ public interface VpcService { IpAddress associateIPToVpc(long ipId, long vpcId) throws ResourceAllocationException, ResourceUnavailableException, InsufficientAddressCapacityException, ConcurrentOperationException; - public Network updateVpcGuestNetwork(long networkId, String name, String displayText, Account callerAccount, - User callerUser, String domainSuffix, Long ntwkOffId, Boolean changeCidr, String guestVmCidr); } diff --git a/api/src/com/cloud/network/vpn/RemoteAccessVpnService.java b/api/src/com/cloud/network/vpn/RemoteAccessVpnService.java index bfd2c892ca1..d637da638ac 100644 --- a/api/src/com/cloud/network/vpn/RemoteAccessVpnService.java +++ b/api/src/com/cloud/network/vpn/RemoteAccessVpnService.java @@ -45,6 +45,6 @@ public interface RemoteAccessVpnService { List listRemoteAccessVpns(long networkId); - RemoteAccessVpn getRemoteAccessVpn(long vpnId); + RemoteAccessVpn getRemoteAccessVpn(long vpnAddrId); } diff --git a/api/src/com/cloud/server/ResourceTag.java b/api/src/com/cloud/server/ResourceTag.java index ee56748640c..9006e305d81 100644 --- a/api/src/com/cloud/server/ResourceTag.java +++ b/api/src/com/cloud/server/ResourceTag.java @@ -38,7 +38,8 @@ public interface ResourceTag extends ControlledEntity, Identity, InternalIdentit Vpc, NetworkACL, StaticRoute, - VMSnapshot + VMSnapshot, + RemoteAccessVpn } /** diff --git a/api/src/com/cloud/storage/Storage.java b/api/src/com/cloud/storage/Storage.java index fba12b62d3d..c130fe222bf 100755 --- a/api/src/com/cloud/storage/Storage.java +++ b/api/src/com/cloud/storage/Storage.java @@ -26,7 +26,8 @@ public class Storage { VHD(true, true, true), ISO(false, false, false), OVA(true, true, true, "ova"), - BAREMETAL(false, false, false); + BAREMETAL(false, false, false), + TAR(false, false, false); private final boolean thinProvisioned; private final boolean supportSparse; diff --git a/api/src/org/apache/cloudstack/affinity/AffinityGroup.java b/api/src/org/apache/cloudstack/affinity/AffinityGroup.java index b8215a279a8..ac2eb613370 100644 --- a/api/src/org/apache/cloudstack/affinity/AffinityGroup.java +++ b/api/src/org/apache/cloudstack/affinity/AffinityGroup.java @@ -1,3 +1,19 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES 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.affinity; import org.apache.cloudstack.acl.ControlledEntity; diff --git a/api/src/org/apache/cloudstack/affinity/AffinityGroupProcessor.java b/api/src/org/apache/cloudstack/affinity/AffinityGroupProcessor.java index 9bdd0515f47..60b8e4c554f 100644 --- a/api/src/org/apache/cloudstack/affinity/AffinityGroupProcessor.java +++ b/api/src/org/apache/cloudstack/affinity/AffinityGroupProcessor.java @@ -1,3 +1,19 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES 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.affinity; import com.cloud.deploy.DeploymentPlan; diff --git a/api/src/org/apache/cloudstack/affinity/AffinityGroupService.java b/api/src/org/apache/cloudstack/affinity/AffinityGroupService.java index b6bf2ab1d78..26c32c89c1f 100644 --- a/api/src/org/apache/cloudstack/affinity/AffinityGroupService.java +++ b/api/src/org/apache/cloudstack/affinity/AffinityGroupService.java @@ -1,3 +1,19 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES 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.affinity; import java.util.List; diff --git a/api/src/org/apache/cloudstack/api/BaseCmd.java b/api/src/org/apache/cloudstack/api/BaseCmd.java index 7aeb6a6503d..179dc655fbf 100644 --- a/api/src/org/apache/cloudstack/api/BaseCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseCmd.java @@ -53,6 +53,7 @@ import com.cloud.network.firewall.NetworkACLService; import com.cloud.network.lb.LoadBalancingRulesService; import com.cloud.network.rules.RulesService; import com.cloud.network.security.SecurityGroupService; +import com.cloud.network.vpc.VpcProvisioningService; import com.cloud.network.vpc.VpcService; import com.cloud.network.vpn.RemoteAccessVpnService; import com.cloud.network.vpn.Site2SiteVpnService; @@ -134,6 +135,7 @@ public abstract class BaseCmd { @Inject public VMSnapshotService _vmSnapshotService; @Inject public DataStoreProviderApiService dataStoreProviderApiService; @Inject public AffinityGroupService _affinityGroupService; + @Inject public VpcProvisioningService _vpcProvSvc; public abstract void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException; diff --git a/api/src/org/apache/cloudstack/api/command/admin/account/CreateAccountCmd.java b/api/src/org/apache/cloudstack/api/command/admin/account/CreateAccountCmd.java index 89673ea6123..95d0d07d9ce 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/account/CreateAccountCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/account/CreateAccountCmd.java @@ -63,7 +63,7 @@ public class CreateAccountCmd extends BaseCmd { @Parameter(name=ApiConstants.LASTNAME, type=CommandType.STRING, required=true, description="lastname") private String lastName; - @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required=true, description="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.") + @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required=true, description="Clear text password (Default hashed to SHA256SALT). If you wish to use any other hashing algorithm, you would need to write a custom authentication adapter See Docs section.") private String password; @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.") diff --git a/api/src/org/apache/cloudstack/api/command/admin/user/CreateUserCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/CreateUserCmd.java index fb29e1a2629..7b3f230d1ec 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/user/CreateUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/CreateUserCmd.java @@ -56,7 +56,7 @@ public class CreateUserCmd extends BaseCmd { @Parameter(name=ApiConstants.LASTNAME, type=CommandType.STRING, required=true, description="lastname") private String lastname; - @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required=true, description="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.") + @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required=true, description="Clear text password (Default hashed to SHA256SALT). If you wish to use any other hashing algorithm, you would need to write a custom authentication adapter See Docs section.") private String password; @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.") diff --git a/api/src/org/apache/cloudstack/api/command/admin/user/UpdateUserCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/UpdateUserCmd.java index 1f31662e8ca..5ea2dbdef55 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/user/UpdateUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/UpdateUserCmd.java @@ -59,7 +59,7 @@ public class UpdateUserCmd extends BaseCmd { @Parameter(name=ApiConstants.LASTNAME, type=CommandType.STRING, description="last name") private String lastname; - @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, description="Hashed password (default is MD5). If you wish to use any other hasing algorithm, you would need to write a custom authentication adapter") + @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, description="Clear text password (default hashed to SHA256SALT). If you wish to use any other hasing algorithm, you would need to write a custom authentication adapter") private String password; @Parameter(name=ApiConstants.SECRET_KEY, type=CommandType.STRING, description="The secret key for the user. Must be specified with userApiKey") 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 3c7956b7d7e..4a3a92a211c 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 @@ -98,7 +98,7 @@ public class CreateVPCOfferingCmd extends BaseAsyncCreateCmd{ @Override public void create() throws ResourceAllocationException { - VpcOffering vpcOff = _vpcService.createVpcOffering(getVpcOfferingName(), getDisplayText(), getSupportedServices(), getServiceProviders()); + VpcOffering vpcOff = _vpcProvSvc.createVpcOffering(getVpcOfferingName(), getDisplayText(), getSupportedServices(), getServiceProviders()); if (vpcOff != null) { this.setEntityId(vpcOff.getId()); this.setEntityUuid(vpcOff.getUuid()); @@ -109,7 +109,7 @@ public class CreateVPCOfferingCmd extends BaseAsyncCreateCmd{ @Override public void execute() { - VpcOffering vpc = _vpcService.getVpcOffering(this.getEntityId()); + VpcOffering vpc = _vpcProvSvc.getVpcOffering(this.getEntityId()); if (vpc != null) { VpcOfferingResponse response = _responseGenerator.createVpcOfferingResponse(vpc); response.setResponseName(getCommandName()); diff --git a/api/src/org/apache/cloudstack/api/command/admin/vpc/DeleteVPCOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vpc/DeleteVPCOfferingCmd.java index 9e2968e66fe..4b16fa5fcb9 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/vpc/DeleteVPCOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vpc/DeleteVPCOfferingCmd.java @@ -66,7 +66,7 @@ public class DeleteVPCOfferingCmd extends BaseAsyncCmd{ @Override public void execute(){ - boolean result = _vpcService.deleteVpcOffering(getId()); + boolean result = _vpcProvSvc.deleteVpcOffering(getId()); if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); 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 de61ee74b31..9bbae064376 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 @@ -88,7 +88,7 @@ public class UpdateVPCOfferingCmd extends BaseAsyncCmd{ @Override public void execute(){ - VpcOffering result = _vpcService.updateVpcOffering(getId(), getVpcOfferingName(), getDisplayText(), getState()); + VpcOffering result = _vpcProvSvc.updateVpcOffering(getId(), getVpcOfferingName(), getDisplayText(), getState()); if (result != null) { VpcOfferingResponse response = _responseGenerator.createVpcOfferingResponse(result); response.setResponseName(getCommandName()); diff --git a/api/src/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java index 41aaaaada12..a61474e69d0 100644 --- a/api/src/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java @@ -129,14 +129,9 @@ public class UpdateNetworkCmd extends BaseAsyncCmd { throw new InvalidParameterValueException("Couldn't find network by id"); } - Network result = null; - if (network.getVpcId() != null) { - result = _vpcService.updateVpcGuestNetwork(getId(), getNetworkName(), getDisplayText(), callerAccount, + Network result = _networkService.updateGuestNetwork(getId(), getNetworkName(), getDisplayText(), callerAccount, callerUser, getNetworkDomain(), getNetworkOfferingId(), getChangeCidr(), getGuestVmCidr()); - } else { - result = _networkService.updateGuestNetwork(getId(), getNetworkName(), getDisplayText(), callerAccount, - callerUser, getNetworkDomain(), getNetworkOfferingId(), getChangeCidr(), getGuestVmCidr()); - } + if (result != null) { NetworkResponse response = _responseGenerator.createNetworkResponse(result); 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 9af044ebb70..4c4e1f71441 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 @@ -44,7 +44,7 @@ import com.cloud.vm.NicSecondaryIp; @APICommand(name = "listNics", description = "list the vm nics IP to NIC", responseObject = NicResponse.class) public class ListNicsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListNicsCmd.class.getName()); - private static final String s_name = "listnics"; + private static final String s_name = "listnicsresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// 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 9aef26f016c..ddae7998784 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 @@ -92,7 +92,7 @@ public class ListVPCOfferingsCmd extends BaseListCmd{ @Override public void execute(){ - List offerings = _vpcService.listVpcOfferings(getId(), getVpcOffName(), getDisplayText(), + List offerings = _vpcProvSvc.listVpcOfferings(getId(), getVpcOffName(), getDisplayText(), getSupportedServices(), isDefault, this.getKeyword(), getState(), this.getStartIndex(), this.getPageSizeVal()); ListResponse response = new ListResponse(); List offeringResponses = new ArrayList(); diff --git a/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteRemoteAccessVpnCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteRemoteAccessVpnCmd.java index 7ddd7952172..5b1c5c6b4e6 100644 --- a/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteRemoteAccessVpnCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteRemoteAccessVpnCmd.java @@ -63,7 +63,7 @@ public class DeleteRemoteAccessVpnCmd extends BaseAsyncCmd { @Override public long getEntityOwnerId() { if (ownerId == null) { - RemoteAccessVpn vpnEntity = _entityMgr.findById(RemoteAccessVpn.class, publicIpId); + RemoteAccessVpn vpnEntity = _ravService.getRemoteAccessVpn(publicIpId); if(vpnEntity != null) return vpnEntity.getAccountId(); diff --git a/api/src/org/apache/cloudstack/api/response/RemoteAccessVpnResponse.java b/api/src/org/apache/cloudstack/api/response/RemoteAccessVpnResponse.java index 7db56630bc0..5e08bca6af2 100644 --- a/api/src/org/apache/cloudstack/api/response/RemoteAccessVpnResponse.java +++ b/api/src/org/apache/cloudstack/api/response/RemoteAccessVpnResponse.java @@ -57,6 +57,9 @@ public class RemoteAccessVpnResponse extends BaseResponse implements ControlledE @SerializedName(ApiConstants.STATE) @Param(description="the state of the rule") private String state; + + @SerializedName(ApiConstants.ID) @Param(description="the id of the remote access vpn") + private String id; public void setPublicIp(String publicIp) { this.publicIp = publicIp; @@ -100,5 +103,9 @@ public class RemoteAccessVpnResponse extends BaseResponse implements ControlledE public void setProjectName(String projectName) { this.projectName = projectName; } + + public void setId(String id) { + this.id = id; + } } diff --git a/api/src/org/apache/cloudstack/api/response/ServiceResponse.java b/api/src/org/apache/cloudstack/api/response/ServiceResponse.java index 445afcfcf5b..c93c55ee16a 100644 --- a/api/src/org/apache/cloudstack/api/response/ServiceResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ServiceResponse.java @@ -16,13 +16,12 @@ // under the License. package org.apache.cloudstack.api.response; -import java.util.List; - +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseResponse; -import com.cloud.serializer.Param; -import com.google.gson.annotations.SerializedName; +import java.util.List; @SuppressWarnings("unused") public class ServiceResponse extends BaseResponse { @@ -30,7 +29,7 @@ public class ServiceResponse extends BaseResponse { @SerializedName(ApiConstants.NAME) @Param(description="the service name") private String name; - @SerializedName(ApiConstants.PROVIDER) @Param(description="the service provider name") + @SerializedName(ApiConstants.PROVIDER) @Param(description="the service provider name", responseObject = ProviderResponse.class) private List providers; @SerializedName("capability") @Param(description="the list of capabilities", responseObject = CapabilityResponse.class) diff --git a/api/src/org/apache/cloudstack/api/response/StoragePoolResponse.java b/api/src/org/apache/cloudstack/api/response/StoragePoolResponse.java index 66dde3655f0..0b1622640d0 100644 --- a/api/src/org/apache/cloudstack/api/response/StoragePoolResponse.java +++ b/api/src/org/apache/cloudstack/api/response/StoragePoolResponse.java @@ -79,9 +79,26 @@ public class StoragePoolResponse extends BaseResponse { @SerializedName(ApiConstants.STATE) @Param(description="the state of the storage pool") private StoragePoolStatus state; + + @SerializedName(ApiConstants.SCOPE) @Param(description="the scope of the storage pool") + private String scope; + /** + * @return the scope + */ + public String getScope() { + return scope; + } + + /** + * @param scope the scope to set + */ + public void setScope(String scope) { + this.scope = scope; + } + @Override public String getObjectId() { return this.getId(); diff --git a/api/src/org/apache/cloudstack/network/ExternalNetworkDeviceManager.java b/api/src/org/apache/cloudstack/network/ExternalNetworkDeviceManager.java index bc22804ae06..aeed81d2011 100644 --- a/api/src/org/apache/cloudstack/network/ExternalNetworkDeviceManager.java +++ b/api/src/org/apache/cloudstack/network/ExternalNetworkDeviceManager.java @@ -43,7 +43,6 @@ public interface ExternalNetworkDeviceManager extends Manager { public static final NetworkDevice F5BigIpLoadBalancer = new NetworkDevice("F5BigIpLoadBalancer", Network.Provider.F5BigIp.getName()); public static final NetworkDevice JuniperSRXFirewall = new NetworkDevice("JuniperSRXFirewall", Network.Provider.JuniperSRX.getName()); public static final NetworkDevice NiciraNvp = new NetworkDevice("NiciraNvp", Network.Provider.NiciraNvp.getName()); - public static final NetworkDevice MidokuraMidonet = new NetworkDevice("MidokuraMidonet", Network.Provider.MidokuraMidonet.getName()); public NetworkDevice(String deviceName, String ntwkServiceprovider) { _name = deviceName; diff --git a/awsapi/conf/applicationContext.xml.in b/awsapi/conf/applicationContext.xml.in index 0a24df214af..8b3a0222262 100644 --- a/awsapi/conf/applicationContext.xml.in +++ b/awsapi/conf/applicationContext.xml.in @@ -37,17 +37,19 @@ - - - - - - - - + + - + + + + + + + + + diff --git a/client/WEB-INF/classes/resources/messages.properties b/client/WEB-INF/classes/resources/messages.properties index 66b32acfc6c..d62cbaeb99b 100644 --- a/client/WEB-INF/classes/resources/messages.properties +++ b/client/WEB-INF/classes/resources/messages.properties @@ -19,6 +19,14 @@ #new labels (begin) ********************************************************************************************** message.redirecting.region=Redirecting to region... label.use.vm.ip=Use VM IP: +label.cpu.limits=CPU limits +label.memory.limits=Memory limits (MiB) +label.primary.storage.limits=Primary Storage limits (GiB) +label.secondary.storage.limits=Secondary Storage limits (GiB) +label.max.cpus=Max. CPU cores +label.max.memory=Max. memory (MiB) +label.max.primary.storage=Max. primary (GiB) +label.max.secondary.storage=Max. secondary (GiB) label.menu.regions=Regions label.region=Region label.add.region=Add Region @@ -1574,6 +1582,10 @@ label.nicira.controller.address=Controller Address label.nicira.transportzoneuuid=Transport Zone Uuid label.nicira.l3gatewayserviceuuid=L3 Gateway Service Uuid +label.add.BigSwitchVns.device=Add BigSwitch Vns Controller +label.delete.BigSwitchVns=Remove BigSwitch Vns Controller +label.bigswitch.controller.address=BigSwitch Vns Controller Address + #resizeVolumes label.resize.new.size=New Size(GB) label.action.resize.volume=Resize Volume diff --git a/client/pom.xml b/client/pom.xml index 43cce4a42cb..4de80afa629 100644 --- a/client/pom.xml +++ b/client/pom.xml @@ -65,11 +65,6 @@ cloud-plugin-network-nvp ${project.version} - - org.apache.cloudstack - cloud-plugin-snmp-alerts - ${project.version} - org.apache.cloudstack cloud-plugin-network-ovs @@ -85,6 +80,11 @@ cloud-plugin-network-vns ${project.version} + + org.apache.cloudstack + cloud-plugin-network-midonet + ${project.version} + org.apache.cloudstack cloud-plugin-hypervisor-xen @@ -219,16 +219,21 @@ cloud-plugin-hypervisor-simulator ${project.version} - - org.apache.cloudstack - cloud-plugin-hypervisor-ucs - ${project.version} - org.apache.cloudstack cloud-plugin-storage-volume-default ${project.version} + + org.apache.cloudstack + cloud-plugin-syslog-alerts + ${project.version} + + + org.apache.cloudstack + cloud-plugin-snmp-alerts + ${project.version} + org.apache.cloudstack cloud-plugin-host-anti-affinity @@ -279,6 +284,26 @@ maven-antrun-plugin 1.7 + + + copy-systemvm + package + + run + + + + + + + + + + + + generate-resource generate-resources @@ -306,12 +331,6 @@ - - - - - - @@ -391,22 +410,38 @@ - - process-nonoss - process-resources - - run - - - - test - - - - + + process-nonoss + process-resources + + run + + + + test + + + + + + process-simulator-context + process-resources + + run + + + + test + + + + process-nonoss-spring-context process-resources @@ -495,6 +530,21 @@ + + developer + + + simulator + + + + + org.apache.cloudstack + cloud-plugin-hypervisor-simulator + ${project.version} + + + netapp diff --git a/client/tomcatconf/applicationContext.xml.in b/client/tomcatconf/applicationContext.xml.in index ebce0e3fbe4..ed881acb23c 100644 --- a/client/tomcatconf/applicationContext.xml.in +++ b/client/tomcatconf/applicationContext.xml.in @@ -32,32 +32,28 @@ - - + + + + + + - - - - - - - - - - - - - - + + + + + + + + + + @@ -91,9 +87,6 @@ - - - @@ -165,15 +158,688 @@ - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/client/tomcatconf/componentContext.xml.in b/client/tomcatconf/componentContext.xml.in index fac17f036e9..95737ce0cce 100644 --- a/client/tomcatconf/componentContext.xml.in +++ b/client/tomcatconf/componentContext.xml.in @@ -1,3 +1,4 @@ + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + - - - - - - + + + + + - - + + + + + + + + + + + + - - - + + + + + + + + + - - - - - - + + + + + + - - + + + + + + + + + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -166,6 +180,7 @@ under the License. + diff --git a/client/tomcatconf/nonossComponentContext.xml.in b/client/tomcatconf/nonossComponentContext.xml.in index 1cc1722cff5..5aec8887ffe 100644 --- a/client/tomcatconf/nonossComponentContext.xml.in +++ b/client/tomcatconf/nonossComponentContext.xml.in @@ -32,305 +32,20 @@ http://www.springframework.org/schema/context/spring-context-3.0.xsd"> - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -340,4 +55,282 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/client/tomcatconf/server-ssl.xml.in b/client/tomcatconf/server-ssl.xml.in index 5d68f1d3d8b..37bc53d25d4 100755 --- a/client/tomcatconf/server-ssl.xml.in +++ b/client/tomcatconf/server-ssl.xml.in @@ -94,7 +94,7 @@ maxThreads="150" scheme="https" secure="true" URIEncoding="UTF-8" clientAuth="false" sslProtocol="TLS" keystoreType="JKS" - keystoreFile="/etc/cloud/management/cloudmanagementserver.keystore" + keystoreFile="/etc/cloudstack/management/cloudmanagementserver.keystore" keystorePass="vmops.com"/> @@ -200,7 +200,7 @@ maxThreads="150" scheme="https" secure="true" clientAuth="false" sslProtocol="TLS" keystoreType="JKS" - keystoreFile="/etc/cloud/management/cloudmanagementserver.keystore" + keystoreFile="/etc/cloudstack/management/cloudmanagementserver.keystore" keystorePass="vmops.com"/> diff --git a/client/tomcatconf/simulatorComponentContext.xml.in b/client/tomcatconf/simulatorComponentContext.xml.in new file mode 100644 index 00000000000..1cb9f6f2b63 --- /dev/null +++ b/client/tomcatconf/simulatorComponentContext.xml.in @@ -0,0 +1,235 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/client/tomcatconf/tomcat6-ssl.conf.in b/client/tomcatconf/tomcat6-ssl.conf.in index 84b6d6275bb..0d2650871b6 100644 --- a/client/tomcatconf/tomcat6-ssl.conf.in +++ b/client/tomcatconf/tomcat6-ssl.conf.in @@ -40,7 +40,7 @@ CATALINA_TMPDIR="@MSENVIRON@/temp" # Use JAVA_OPTS to set java.library.path for libtcnative.so #JAVA_OPTS="-Djava.library.path=/usr/lib64" -JAVA_OPTS="-Djava.awt.headless=true -Djavax.net.ssl.trustStore=/etc/cloud/management/cloudmanagementserver.keystore -Djavax.net.ssl.trustStorePassword=vmops.com -Dcom.sun.management.jmxremote.port=45219 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Xmx2g -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=@MSLOGDIR@ -XX:MaxPermSize=800m -XX:PermSize=512M" +JAVA_OPTS="-Djava.awt.headless=true -Djavax.net.ssl.trustStore=/etc/cloudstack/management/cloudmanagementserver.keystore -Djavax.net.ssl.trustStorePassword=vmops.com -Dcom.sun.management.jmxremote.port=45219 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Xmx2g -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=@MSLOGDIR@ -XX:MaxPermSize=800m -XX:PermSize=512M" # What user should run tomcat TOMCAT_USER="@MSUSER@" diff --git a/debian/cloudstack-common.install b/debian/cloudstack-common.install index 9677f871cf0..021474e1b65 100644 --- a/debian/cloudstack-common.install +++ b/debian/cloudstack-common.install @@ -26,6 +26,7 @@ /usr/share/cloudstack-common/scripts/vm/hypervisor/kvm/* /usr/share/cloudstack-common/scripts/vm/hypervisor/versions.sh /usr/share/cloudstack-common/scripts/vm/hypervisor/xenserver/* +/usr/share/cloudstack-common/lib/* /usr/bin/cloud-set-guest-password /usr/bin/cloud-set-guest-sshkey /usr/lib/python2.?/*-packages/* diff --git a/debian/cloudstack-management.install b/debian/cloudstack-management.install index e80701d0a78..b42343ad5a4 100644 --- a/debian/cloudstack-management.install +++ b/debian/cloudstack-management.install @@ -31,5 +31,4 @@ /usr/bin/cloud-setup-databases /usr/bin/cloud-migrate-databases /usr/share/cloudstack-management/* -/usr/share/java/* /usr/share/tomcat6/lib/* diff --git a/debian/cloudstack-management.postinst b/debian/cloudstack-management.postinst index 4e9b046caff..08df3c7a465 100644 --- a/debian/cloudstack-management.postinst +++ b/debian/cloudstack-management.postinst @@ -20,7 +20,7 @@ if [ "$1" = configure ]; then if ! getent passwd cloud >/dev/null; then adduser --quiet --system --group --no-create-home --home /var/lib/cloudstack/management cloud else - usermod -m -d /var/lib/cloudstack/management cloud + usermod -m -d /var/lib/cloudstack/management cloud || true fi for i in /var/cache/cloudstack/management \ @@ -36,6 +36,20 @@ if [ "$1" = configure ]; then chgrp cloud $i done + OLDCONFDIR="/etc/cloud/management" + NEWCONFDIR="/etc/cloudstack/management" + CONFFILES="db.properties cloud.keystore key" + + # Copy old configuration so the admin doesn't have to do that + # Only do so when we are installing for the first time + if [ -z "$2" ]; then + for FILE in $CONFFILES; do + if [ -f "$OLDCONFDIR/${FILE}" ]; then + cp -a $OLDCONFDIR/$FILE $NEWCONFDIR/$FILE + fi + done + fi + chmod 0640 /etc/cloudstack/management/db.properties chgrp cloud /etc/cloudstack/management/db.properties fi diff --git a/debian/control b/debian/control index 8f82fc3ab2f..eec9ca25c7b 100644 --- a/debian/control +++ b/debian/control @@ -15,14 +15,14 @@ Description: A common package which contains files which are shared by several C Package: cloudstack-management Architecture: all -Depends: cloudstack-common (= ${source:Version}), tomcat6, sysvinit-utils, chkconfig, sudo, jsvc, python-mysqldb, python-paramiko, augeas-tools +Depends: cloudstack-common (= ${source:Version}), tomcat6, sysvinit-utils, sudo, jsvc, python-mysqldb, python-paramiko, augeas-tools Conflicts: cloud-server, cloud-client, cloud-client-ui Description: CloudStack server library The CloudStack management server Package: cloudstack-agent Architecture: all -Depends: openjdk-6-jre | openjdk-7-jre, cloudstack-common (= ${source:Version}), lsb-base (>= 3.2), libcommons-daemon-java, libjna-java, openssh-client, libvirt0, sysvinit-utils, chkconfig, qemu-kvm, libvirt-bin, uuid-runtime, rsync, grep, iproute, perl-base, perl-modules, ebtables, vlan, wget, jsvc +Depends: openjdk-6-jre | openjdk-7-jre, cloudstack-common (= ${source:Version}), lsb-base (>= 3.2), libcommons-daemon-java, libjna-java, openssh-client, libvirt0, sysvinit-utils, qemu-kvm, libvirt-bin, uuid-runtime, rsync, grep, iproute, perl-base, perl-modules, ebtables, vlan, wget, jsvc, ipset 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 diff --git a/debian/rules b/debian/rules index 3804d8d49e9..2cf037645fe 100755 --- a/debian/rules +++ b/debian/rules @@ -100,10 +100,8 @@ install: ln -s tomcat6-nonssl.conf $(DESTDIR)/$(SYSCONFDIR)/$(PACKAGE)/management/tomcat6.conf mkdir -p $(DESTDIR)/$(SYSCONFDIR)/$(PACKAGE)/management/Catalina/localhost/client mkdir -p ${DESTDIR}/usr/share/tomcat6/lib - mkdir -p ${DESTDIR}/usr/share/java install -D packaging/debian/init/cloud-management $(DESTDIR)/$(SYSCONFDIR)/init.d/$(PACKAGE)-management install -D client/bindir/cloud-update-xenserver-licenses.in $(DESTDIR)/usr/bin/cloud-update-xenserver-licenses - install -D server/target/cloud-server-$(VERSION)-SNAPSHOT.jar $(DESTDIR)/usr/share/java/$(PACKAGE)-server.jar ln -s /usr/share/tomcat6/bin $(DESTDIR)/usr/share/$(PACKAGE)-management/bin ln -s ../../..$(SYSCONFDIR)/$(PACKAGE)/management $(DESTDIR)/usr/share/$(PACKAGE)-management/conf ln -s ../../../usr/share/tomcat6/lib $(DESTDIR)/usr/share/$(PACKAGE)-management/lib @@ -116,6 +114,7 @@ install: mkdir -p $(DESTDIR)/usr/share/$(PACKAGE)-common mkdir $(DESTDIR)/usr/share/$(PACKAGE)-common/scripts mkdir $(DESTDIR)/usr/share/$(PACKAGE)-common/setup + mkdir $(DESTDIR)/usr/share/$(PACKAGE)-common/lib cp -r scripts/installer $(DESTDIR)/usr/share/$(PACKAGE)-common/scripts cp -r scripts/network $(DESTDIR)/usr/share/$(PACKAGE)-common/scripts cp -r scripts/storage $(DESTDIR)/usr/share/$(PACKAGE)-common/scripts @@ -126,7 +125,9 @@ install: install -D client/target/utilities/bin/cloud-set-guest-sshkey $(DESTDIR)/usr/bin install -D client/target/utilities/bin/cloud-setup-databases $(DESTDIR)/usr/bin install -D client/target/utilities/bin/cloud-setup-management $(DESTDIR)/usr/bin - install -D client/target/cloud-client-ui-$(VERSION)-SNAPSHOT/WEB-INF/classes/vms/systemvm.iso $(DESTDIR)/usr/share/$(PACKAGE)-common/vms/systemvm.iso + install -D services/console-proxy/server/dist/systemvm.iso $(DESTDIR)/usr/share/$(PACKAGE)-common/vms/systemvm.iso + # We need jasypt for cloud-install-sys-tmplt, so this is a nasty hack to get it into the right place + install -D agent/target/dependencies/jasypt-1.9.0.jar $(DESTDIR)/usr/share/$(PACKAGE)-common/lib # cloudstack-python mkdir -p $(DESTDIR)/usr/lib/python2.7/dist-packages diff --git a/developer/developer-prefill.sql b/developer/developer-prefill.sql index 6300d35df64..e4f90cad6e8 100644 --- a/developer/developer-prefill.sql +++ b/developer/developer-prefill.sql @@ -36,7 +36,7 @@ INSERT INTO `cloud`.`user` (id, uuid, username, password, account_id, firstname, -- Add system user with encrypted password=password INSERT INTO `cloud`.`user` (id, uuid, username, password, account_id, firstname, lastname, email, state, created) VALUES (2, UUID(), 'admin', '5f4dcc3b5aa765d61d8327deb882cf99', - '2', 'Admin', 'User', 'admin@mailprovider.com', 'enabled', NOW()); + '2', 'Admin', 'User', 'admin@mailprovider.com', 'disabled', NOW()); -- Add configurations INSERT INTO `cloud`.`configuration` (category, instance, component, name, value) diff --git a/docs/en-US/Installation_Guide.xml b/docs/en-US/Installation_Guide.xml index fed53fc4a1d..28df071d42f 100644 --- a/docs/en-US/Installation_Guide.xml +++ b/docs/en-US/Installation_Guide.xml @@ -50,6 +50,7 @@ + diff --git a/docs/en-US/choosing-a-hypervisor.xml b/docs/en-US/choosing-a-hypervisor.xml new file mode 100644 index 00000000000..bf83fe3d17f --- /dev/null +++ b/docs/en-US/choosing-a-hypervisor.xml @@ -0,0 +1,136 @@ + +%BOOK_ENTITIES; +]> + + + + Choosing a Hypervisor: Supported Features + &PRODUCT; supports many popular hypervisors. Your cloud can consist entirely of hosts running a single hypervisor, or you can use multiple hypervisors. Each cluster of hosts must run the same hypervisor. + You might already have an installed base of nodes running a particular hypervisor, in which case, your choice of hypervisor has already been made. If you are starting from scratch, you need to decide what hypervisor software best suits your needs. A discussion of the relative advantages of each hypervisor is outside the scope of our documentation. However, it will help you to know which features of each hypervisor are supported by &PRODUCT;. The following table provides this information. + + + + + + + + + + + + Feature + XenServer 6.0.2 + vSphere 4.1/5.0 + KVM - RHEL 6.2 + OVM 2.3 + Bare Metal + + + + + Network Throttling + Yes + Yes + No + No + N/A + + + Security groups in zones that use basic networking + Yes + No + Yes + No + No + + + iSCSI + Yes + Yes + Yes + Yes + N/A + + + FibreChannel + Yes + Yes + Yes + No + N/A + + + Local Disk + Yes + Yes + Yes + No + Yes + + + HA + Yes + Yes (Native) + Yes + Yes + N/A + + + Snapshots of local disk + Yes + Yes + Yes + No + N/A + + + Local disk as data disk + No + No + No + No + N/A + + + Work load balancing + No + DRS + No + No + N/A + + + Manual live migration of VMs from host to host + Yes + Yes + Yes + Yes + N/A + + + Conserve management traffic IP address by using link local network to communicate with virtual router + Yes + No + Yes + Yes + N/A + + + + + diff --git a/engine/api/src/org/apache/cloudstack/engine/datacenter/entity/api/HostEntity.java b/engine/api/src/org/apache/cloudstack/engine/datacenter/entity/api/HostEntity.java index 99f3120f93a..68a2ed2807b 100644 --- a/engine/api/src/org/apache/cloudstack/engine/datacenter/entity/api/HostEntity.java +++ b/engine/api/src/org/apache/cloudstack/engine/datacenter/entity/api/HostEntity.java @@ -14,48 +14,47 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package org.apache.cloudstack.engine.datacenter.entity.api; - -import com.cloud.hypervisor.Hypervisor.HypervisorType; - -public interface HostEntity extends DataCenterResourceEntity { - - /** - * @return total amount of memory. - */ - Long getTotalMemory(); - - /** - * @return # of cores in a machine. Note two cpus with two cores each returns 4. - */ - Integer getCpus(); - - /** - * @return speed of each cpu in mhz. - */ - Long getSpeed(); - - /** - * @return the pod. - */ - Long getPodId(); - - /** - * @return availability zone. - */ - long getDataCenterId(); - - /** - * @return type of hypervisor - */ - HypervisorType getHypervisorType(); - - /** - * @return the mac address of the host. - */ - String getGuid(); - - Long getClusterId(); - -} - +package org.apache.cloudstack.engine.datacenter.entity.api; + +import com.cloud.hypervisor.Hypervisor.HypervisorType; + +public interface HostEntity extends DataCenterResourceEntity { + + /** + * @return total amount of memory. + */ + Long getTotalMemory(); + + /** + * @return # of cores in a machine. Note two cpus with two cores each returns 4. + */ + Integer getCpus(); + + /** + * @return speed of each cpu in mhz. + */ + Long getSpeed(); + + /** + * @return the pod. + */ + Long getPodId(); + + /** + * @return availability zone. + */ + long getDataCenterId(); + + /** + * @return type of hypervisor + */ + HypervisorType getHypervisorType(); + + /** + * @return the mac address of the host. + */ + String getGuid(); + + Long getClusterId(); + +} diff --git a/engine/api/src/org/apache/cloudstack/engine/rest/service/api/ClusterRestService.java b/engine/api/src/org/apache/cloudstack/engine/rest/service/api/ClusterRestService.java index 216cfa81d0e..2718e2fdbc8 100755 --- a/engine/api/src/org/apache/cloudstack/engine/rest/service/api/ClusterRestService.java +++ b/engine/api/src/org/apache/cloudstack/engine/rest/service/api/ClusterRestService.java @@ -1,86 +1,86 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.rest.service.api; - -import java.util.List; - -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; - -import org.apache.cloudstack.engine.datacenter.entity.api.ClusterEntity; -import org.apache.cloudstack.engine.service.api.ProvisioningService; -import org.springframework.stereotype.Component; -import org.springframework.stereotype.Service; - -@Component -@Service("ClusterRestService") -@Produces("application/json") -public class ClusterRestService { -// @Inject - ProvisioningService _provisioningService; - - @GET @Path("/clusters") - public List listAll() { - return null; - } - - - @GET @Path("/cluster/{clusterid}") - public ClusterEntity get(@PathParam("clusterid") String clusterId) { - return null; - } - - @POST @Path("/cluster/{clusterid}/enable") - public String enable(@PathParam("clusterid") String clusterId) { - return null; - } - - @POST @Path("/cluster/{clusterid}/disable") - public String disable(@PathParam("clusterid") String clusterId) { - return null; - } - - @POST @Path("/cluster/{clusterid}/deactivate") - public String deactivate(@PathParam("clusterid") String clusterId) { - return null; - } - - @POST @Path("/cluster/{clusterid}/reactivate") - public String reactivate(@PathParam("clusterid") String clusterId) { - return null; - } - - @PUT @Path("/cluster/create") - public ClusterEntity create( - @QueryParam("xid") String xid, - @QueryParam("display-name") String displayName) { - return null; - } - - @PUT @Path("/cluster/{clusterid}/update") - public ClusterEntity update( - @QueryParam("display-name") String displayName) { - return null; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.rest.service.api; + +import java.util.List; + +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; + +import org.apache.cloudstack.engine.datacenter.entity.api.ClusterEntity; +import org.apache.cloudstack.engine.service.api.ProvisioningService; +import org.springframework.stereotype.Component; +import org.springframework.stereotype.Service; + +@Component +@Service("ClusterRestService") +@Produces("application/json") +public class ClusterRestService { +// @Inject + ProvisioningService _provisioningService; + + @GET @Path("/clusters") + public List listAll() { + return null; + } + + + @GET @Path("/cluster/{clusterid}") + public ClusterEntity get(@PathParam("clusterid") String clusterId) { + return null; + } + + @POST @Path("/cluster/{clusterid}/enable") + public String enable(@PathParam("clusterid") String clusterId) { + return null; + } + + @POST @Path("/cluster/{clusterid}/disable") + public String disable(@PathParam("clusterid") String clusterId) { + return null; + } + + @POST @Path("/cluster/{clusterid}/deactivate") + public String deactivate(@PathParam("clusterid") String clusterId) { + return null; + } + + @POST @Path("/cluster/{clusterid}/reactivate") + public String reactivate(@PathParam("clusterid") String clusterId) { + return null; + } + + @PUT @Path("/cluster/create") + public ClusterEntity create( + @QueryParam("xid") String xid, + @QueryParam("display-name") String displayName) { + return null; + } + + @PUT @Path("/cluster/{clusterid}/update") + public ClusterEntity update( + @QueryParam("display-name") String displayName) { + return null; + } +} diff --git a/engine/api/src/org/apache/cloudstack/engine/rest/service/api/NetworkRestService.java b/engine/api/src/org/apache/cloudstack/engine/rest/service/api/NetworkRestService.java index 3e81a443115..b75600e08fe 100755 --- a/engine/api/src/org/apache/cloudstack/engine/rest/service/api/NetworkRestService.java +++ b/engine/api/src/org/apache/cloudstack/engine/rest/service/api/NetworkRestService.java @@ -1,62 +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 org.apache.cloudstack.engine.rest.service.api; - -import java.util.List; - -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; - -import org.apache.cloudstack.engine.cloud.entity.api.NetworkEntity; -import org.springframework.stereotype.Component; -import org.springframework.stereotype.Service; - -@Service("NetworkRestService") -@Component -@Produces("application/json") -public class NetworkRestService { - @PUT @Path("/network/create") - public NetworkEntity create( - @QueryParam("xid") String xid, - @QueryParam("display-name") String displayName) { - return null; - } - - @GET @Path("/network/{network-id}") - public NetworkEntity get(@PathParam("network-id") String networkId) { - return null; - } - - @GET @Path("/networks") - public List listAll() { - return null; - } - - @POST @Path("/network/{network-id}/") - public String deploy(@PathParam("network-id") String networkId) { - return null; - } - - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.rest.service.api; + +import java.util.List; + +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; + +import org.apache.cloudstack.engine.cloud.entity.api.NetworkEntity; +import org.springframework.stereotype.Component; +import org.springframework.stereotype.Service; + +@Service("NetworkRestService") +@Component +@Produces("application/json") +public class NetworkRestService { + @PUT @Path("/network/create") + public NetworkEntity create( + @QueryParam("xid") String xid, + @QueryParam("display-name") String displayName) { + return null; + } + + @GET @Path("/network/{network-id}") + public NetworkEntity get(@PathParam("network-id") String networkId) { + return null; + } + + @GET @Path("/networks") + public List listAll() { + return null; + } + + @POST @Path("/network/{network-id}/") + public String deploy(@PathParam("network-id") String networkId) { + return null; + } + + +} diff --git a/engine/api/src/org/apache/cloudstack/engine/rest/service/api/PodRestService.java b/engine/api/src/org/apache/cloudstack/engine/rest/service/api/PodRestService.java index 0811f0b9cf9..9c009b9aea2 100755 --- a/engine/api/src/org/apache/cloudstack/engine/rest/service/api/PodRestService.java +++ b/engine/api/src/org/apache/cloudstack/engine/rest/service/api/PodRestService.java @@ -1,79 +1,79 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.rest.service.api; - -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; - -import org.apache.cloudstack.engine.datacenter.entity.api.PodEntity; -import org.apache.cloudstack.engine.service.api.ProvisioningService; -import org.springframework.stereotype.Component; -import org.springframework.stereotype.Service; - -@Component -@Service("PodService") -@Produces({"application/json"}) -public class PodRestService { -// @Inject - ProvisioningService _provisioningService; - - @GET @Path("/pod/{pod-id}") - public PodEntity getPod(@PathParam("pod-id") String podId) { - return null; - } - - @POST @Path("/pod/{pod-id}/enable") - public String enable(@PathParam("pod-id") String podId) { - return null; - } - - @POST @Path("/pod/{pod-id}/disable") - public String disable(@PathParam("pod-id") String podId) { - return null; - } - - @POST @Path("/pod/{pod-id}/deactivate") - public String deactivate(@PathParam("pod-id") String podId) { - return null; - } - - @POST @Path("/pod/{pod-id}/reactivate") - public String reactivate(@PathParam("pod-id") String podId) { - return null; - } - - @PUT @Path("/pod/create") - public PodEntity create( - @QueryParam("xid") String xid, - @QueryParam("display-name") String displayName) { - return null; - } - - @PUT @Path("/pod/{pod-id}") - public PodEntity update( - @PathParam("pod-id") String podId, - @QueryParam("display-name") String displayName) { - return null; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.rest.service.api; + +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; + +import org.apache.cloudstack.engine.datacenter.entity.api.PodEntity; +import org.apache.cloudstack.engine.service.api.ProvisioningService; +import org.springframework.stereotype.Component; +import org.springframework.stereotype.Service; + +@Component +@Service("PodService") +@Produces({"application/json"}) +public class PodRestService { +// @Inject + ProvisioningService _provisioningService; + + @GET @Path("/pod/{pod-id}") + public PodEntity getPod(@PathParam("pod-id") String podId) { + return null; + } + + @POST @Path("/pod/{pod-id}/enable") + public String enable(@PathParam("pod-id") String podId) { + return null; + } + + @POST @Path("/pod/{pod-id}/disable") + public String disable(@PathParam("pod-id") String podId) { + return null; + } + + @POST @Path("/pod/{pod-id}/deactivate") + public String deactivate(@PathParam("pod-id") String podId) { + return null; + } + + @POST @Path("/pod/{pod-id}/reactivate") + public String reactivate(@PathParam("pod-id") String podId) { + return null; + } + + @PUT @Path("/pod/create") + public PodEntity create( + @QueryParam("xid") String xid, + @QueryParam("display-name") String displayName) { + return null; + } + + @PUT @Path("/pod/{pod-id}") + public PodEntity update( + @PathParam("pod-id") String podId, + @QueryParam("display-name") String displayName) { + return null; + } +} diff --git a/engine/api/src/org/apache/cloudstack/engine/rest/service/api/VirtualMachineRestService.java b/engine/api/src/org/apache/cloudstack/engine/rest/service/api/VirtualMachineRestService.java index 2124a81261f..f3f7bad1936 100755 --- a/engine/api/src/org/apache/cloudstack/engine/rest/service/api/VirtualMachineRestService.java +++ b/engine/api/src/org/apache/cloudstack/engine/rest/service/api/VirtualMachineRestService.java @@ -1,56 +1,56 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.rest.service.api; - -import java.util.List; - -import javax.ws.rs.GET; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; - -import org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntity; -import org.springframework.stereotype.Component; -import org.springframework.stereotype.Service; - -@Component -@Service("VirtualMachineRestService") -@Produces("application/xml") -public class VirtualMachineRestService { - - @GET @Path("/vm/{vmid}") - public VirtualMachineEntity get(@PathParam("vmid") String vmId) { - return null; - } - - @PUT @Path("/vm/create") - public VirtualMachineEntity create( - @QueryParam("xid") String xid, - @QueryParam("hostname") String hostname, - @QueryParam("display-name") String displayName) { - return null; - } - - @GET @Path("/vms") - public List listAll() { - return null; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.rest.service.api; + +import java.util.List; + +import javax.ws.rs.GET; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; + +import org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntity; +import org.springframework.stereotype.Component; +import org.springframework.stereotype.Service; + +@Component +@Service("VirtualMachineRestService") +@Produces("application/xml") +public class VirtualMachineRestService { + + @GET @Path("/vm/{vmid}") + public VirtualMachineEntity get(@PathParam("vmid") String vmId) { + return null; + } + + @PUT @Path("/vm/create") + public VirtualMachineEntity create( + @QueryParam("xid") String xid, + @QueryParam("hostname") String hostname, + @QueryParam("display-name") String displayName) { + return null; + } + + @GET @Path("/vms") + public List listAll() { + return null; + } +} diff --git a/engine/api/src/org/apache/cloudstack/engine/rest/service/api/VolumeRestService.java b/engine/api/src/org/apache/cloudstack/engine/rest/service/api/VolumeRestService.java index 3e5174b9d90..cb1a0d3dc47 100755 --- a/engine/api/src/org/apache/cloudstack/engine/rest/service/api/VolumeRestService.java +++ b/engine/api/src/org/apache/cloudstack/engine/rest/service/api/VolumeRestService.java @@ -1,76 +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 org.apache.cloudstack.engine.rest.service.api; - -import java.util.List; - -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; - -import org.apache.cloudstack.engine.cloud.entity.api.VolumeEntity; -import org.springframework.stereotype.Component; -import org.springframework.stereotype.Service; - -@Component -@Service("VolumeRestService") -@Produces("application/json") -public class VolumeRestService { - - @PUT @Path("/vol/create") - public VolumeEntity create( - @QueryParam("xid") String xid, - @QueryParam("display-name") String displayName) { - return null; - } - - @POST @Path("/vol/{volid}/deploy") - public String deploy(@PathParam("volid") String volumeId) { - return null; - } - - @GET @Path("/vols") - public List listAll() { - return null; - } - - @POST @Path("/vol/{volid}/attach-to") - public String attachTo( - @PathParam("volid") String volumeId, - @QueryParam("vmid") String vmId, - @QueryParam("device-order") short device) { - return null; - } - - @DELETE @Path("/vol/{volid}") - public String delete(@PathParam("volid") String volumeId) { - return null; - } - - @POST @Path("/vol/{volid}/detach") - public String detach(@QueryParam("volid") String volumeId) { - return null; - } - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.rest.service.api; + +import java.util.List; + +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; + +import org.apache.cloudstack.engine.cloud.entity.api.VolumeEntity; +import org.springframework.stereotype.Component; +import org.springframework.stereotype.Service; + +@Component +@Service("VolumeRestService") +@Produces("application/json") +public class VolumeRestService { + + @PUT @Path("/vol/create") + public VolumeEntity create( + @QueryParam("xid") String xid, + @QueryParam("display-name") String displayName) { + return null; + } + + @POST @Path("/vol/{volid}/deploy") + public String deploy(@PathParam("volid") String volumeId) { + return null; + } + + @GET @Path("/vols") + public List listAll() { + return null; + } + + @POST @Path("/vol/{volid}/attach-to") + public String attachTo( + @PathParam("volid") String volumeId, + @QueryParam("vmid") String vmId, + @QueryParam("device-order") short device) { + return null; + } + + @DELETE @Path("/vol/{volid}") + public String delete(@PathParam("volid") String volumeId) { + return null; + } + + @POST @Path("/vol/{volid}/detach") + public String detach(@QueryParam("volid") String volumeId) { + return null; + } + +} diff --git a/engine/api/src/org/apache/cloudstack/engine/rest/service/api/ZoneRestService.java b/engine/api/src/org/apache/cloudstack/engine/rest/service/api/ZoneRestService.java index 7170f00747d..bd6980e064a 100755 --- a/engine/api/src/org/apache/cloudstack/engine/rest/service/api/ZoneRestService.java +++ b/engine/api/src/org/apache/cloudstack/engine/rest/service/api/ZoneRestService.java @@ -1,87 +1,87 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.rest.service.api; - -import java.util.List; - -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; - -import org.apache.cloudstack.engine.datacenter.entity.api.ZoneEntity; -import org.apache.cloudstack.engine.service.api.ProvisioningService; -import org.springframework.stereotype.Component; -import org.springframework.stereotype.Service; - -@Component -@Service("zoneService") -@Produces({"application/json"}) -public class ZoneRestService { -// @Inject - ProvisioningService _provisioningService; - - @GET @Path("/zones") - public List listAll() { - return _provisioningService.listZones(); - } - - @GET @Path("/zone/{zone-id}") - public ZoneEntity get(@PathParam("zone-id") String zoneId) { - return _provisioningService.getZone(zoneId); - } - - @POST @Path("/zone/{zone-id}/enable") - public String enable(String zoneId) { - return null; - } - - @POST @Path("/zone/{zone-id}/disable") - public String disable(@PathParam("zone-id") String zoneId) { - ZoneEntity zoneEntity = _provisioningService.getZone(zoneId); - zoneEntity.disable(); - return null; - } - - @POST @Path("/zone/{zone-id}/deactivate") - public String deactivate(@PathParam("zone-id") String zoneId) { - return null; - } - - @POST @Path("/zone/{zone-id}/activate") - public String reactivate(@PathParam("zone-id") String zoneId) { - return null; - } - - - @PUT @Path("/zone/create") - public ZoneEntity createZone(@QueryParam("xid") String xid, - @QueryParam("display-name") String displayName) { - return null; - } - - @DELETE @Path("/zone/{zone-id}") - public String deleteZone(@QueryParam("zone-id") String xid) { - return null; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.rest.service.api; + +import java.util.List; + +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; + +import org.apache.cloudstack.engine.datacenter.entity.api.ZoneEntity; +import org.apache.cloudstack.engine.service.api.ProvisioningService; +import org.springframework.stereotype.Component; +import org.springframework.stereotype.Service; + +@Component +@Service("zoneService") +@Produces({"application/json"}) +public class ZoneRestService { +// @Inject + ProvisioningService _provisioningService; + + @GET @Path("/zones") + public List listAll() { + return _provisioningService.listZones(); + } + + @GET @Path("/zone/{zone-id}") + public ZoneEntity get(@PathParam("zone-id") String zoneId) { + return _provisioningService.getZone(zoneId); + } + + @POST @Path("/zone/{zone-id}/enable") + public String enable(String zoneId) { + return null; + } + + @POST @Path("/zone/{zone-id}/disable") + public String disable(@PathParam("zone-id") String zoneId) { + ZoneEntity zoneEntity = _provisioningService.getZone(zoneId); + zoneEntity.disable(); + return null; + } + + @POST @Path("/zone/{zone-id}/deactivate") + public String deactivate(@PathParam("zone-id") String zoneId) { + return null; + } + + @POST @Path("/zone/{zone-id}/activate") + public String reactivate(@PathParam("zone-id") String zoneId) { + return null; + } + + + @PUT @Path("/zone/create") + public ZoneEntity createZone(@QueryParam("xid") String xid, + @QueryParam("display-name") String displayName) { + return null; + } + + @DELETE @Path("/zone/{zone-id}") + public String deleteZone(@QueryParam("zone-id") String xid) { + return null; + } +} diff --git a/engine/components-api/src/org/apache/cloudstack/compute/ComputeGuru.java b/engine/components-api/src/org/apache/cloudstack/compute/ComputeGuru.java index 5dbe0c6f931..73aa84c6152 100644 --- a/engine/components-api/src/org/apache/cloudstack/compute/ComputeGuru.java +++ b/engine/components-api/src/org/apache/cloudstack/compute/ComputeGuru.java @@ -1,34 +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.compute; - -import com.cloud.vm.VirtualMachineProfile; - -/** - * ComputeGuru understands everything about the hypervisor. - * - */ -public interface ComputeGuru { - String getVersion(); - String getHypervisor(); - void start(VirtualMachineProfile vm); - void stop(VirtualMachineProfile vm); - - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.compute; + +import com.cloud.vm.VirtualMachineProfile; + +/** + * ComputeGuru understands everything about the hypervisor. + * + */ +public interface ComputeGuru { + String getVersion(); + String getHypervisor(); + void start(VirtualMachineProfile vm); + void stop(VirtualMachineProfile vm); + + +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/VMEntityManager.java b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/VMEntityManager.java index a36ca3a3aba..82c580fd506 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/VMEntityManager.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/VMEntityManager.java @@ -14,32 +14,32 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package org.apache.cloudstack.engine.cloud.entity.api; - -import org.apache.cloudstack.engine.cloud.entity.api.db.VMEntityVO; - -import com.cloud.deploy.DeploymentPlan; -import com.cloud.deploy.DeploymentPlanner.ExcludeList; -import com.cloud.exception.AgentUnavailableException; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.OperationTimedoutException; -import com.cloud.exception.ResourceUnavailableException; +package org.apache.cloudstack.engine.cloud.entity.api; + +import org.apache.cloudstack.engine.cloud.entity.api.db.VMEntityVO; + +import com.cloud.deploy.DeploymentPlan; +import com.cloud.deploy.DeploymentPlanner.ExcludeList; +import com.cloud.exception.AgentUnavailableException; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.OperationTimedoutException; +import com.cloud.exception.ResourceUnavailableException; import com.cloud.vm.VirtualMachineProfile; import java.util.Map; - -public interface VMEntityManager { - - VMEntityVO loadVirtualMachine(String vmId); - - void saveVirtualMachine(VMEntityVO vmInstanceVO); - - String reserveVirtualMachine(VMEntityVO vmEntityVO, String plannerToUse, DeploymentPlan plan, ExcludeList exclude) throws InsufficientCapacityException, ResourceUnavailableException; - + +public interface VMEntityManager { + + VMEntityVO loadVirtualMachine(String vmId); + + void saveVirtualMachine(VMEntityVO vmInstanceVO); + + String reserveVirtualMachine(VMEntityVO vmEntityVO, String plannerToUse, DeploymentPlan plan, ExcludeList exclude) throws InsufficientCapacityException, ResourceUnavailableException; + void deployVirtualMachine(String reservationId, String caller, Map params) throws InsufficientCapacityException, ResourceUnavailableException; - - boolean stopvirtualmachine(VMEntityVO vmEntityVO, String caller) throws ResourceUnavailableException; - - boolean destroyVirtualMachine(VMEntityVO vmEntityVO, String caller) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException; -} + + boolean stopvirtualmachine(VMEntityVO vmEntityVO, String caller) throws ResourceUnavailableException; + + boolean destroyVirtualMachine(VMEntityVO vmEntityVO, String caller) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException; +} 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 508b0b9a746..c2ca729c909 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 @@ -14,33 +14,33 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package org.apache.cloudstack.engine.cloud.entity.api; - -import java.lang.reflect.Method; -import java.util.Date; -import java.util.List; -import java.util.Map; - -import javax.inject.Inject; - -import org.apache.cloudstack.engine.cloud.entity.api.db.VMEntityVO; +package org.apache.cloudstack.engine.cloud.entity.api; + +import java.lang.reflect.Method; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import javax.inject.Inject; + +import org.apache.cloudstack.engine.cloud.entity.api.db.VMEntityVO; import org.springframework.stereotype.Component; - -import com.cloud.deploy.DeploymentPlan; -import com.cloud.deploy.DeploymentPlanner.ExcludeList; -import com.cloud.exception.AgentUnavailableException; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.OperationTimedoutException; -import com.cloud.exception.ResourceUnavailableException; + +import com.cloud.deploy.DeploymentPlan; +import com.cloud.deploy.DeploymentPlanner.ExcludeList; +import com.cloud.exception.AgentUnavailableException; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.OperationTimedoutException; +import com.cloud.exception.ResourceUnavailableException; import com.cloud.vm.VirtualMachineProfile; @Component -public class VirtualMachineEntityImpl implements VirtualMachineEntity { - - @Inject private VMEntityManager manager; - - private VMEntityVO vmEntityVO; +public class VirtualMachineEntityImpl implements VirtualMachineEntity { + + @Inject private VMEntityManager manager; + + private VMEntityVO vmEntityVO; public VirtualMachineEntityImpl() { } @@ -61,204 +61,204 @@ public class VirtualMachineEntityImpl implements VirtualMachineEntity { manager.saveVirtualMachine(vmEntityVO); } - - public VirtualMachineEntityImpl(String vmId, VMEntityManager manager) { - this.manager = manager; - this.vmEntityVO = this.manager.loadVirtualMachine(vmId); - } - - public VirtualMachineEntityImpl(String vmId, String owner, String hostName, String displayName, int cpu, int speed, long memory, List computeTags, List rootDiskTags, List networks, VMEntityManager manager) { - this(vmId, manager); - 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); - - manager.saveVirtualMachine(vmEntityVO); - } - - @Override - public String getUuid() { - return vmEntityVO.getUuid(); - } - - @Override - public long getId() { - return vmEntityVO.getId(); - } - - @Override - public String getCurrentState() { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getDesiredState() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Date getCreatedTime() { - return vmEntityVO.getCreated(); - } - - @Override - public Date getLastUpdatedTime() { - return vmEntityVO.getUpdateTime(); - } - - @Override - public String getOwner() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Map getDetails() { - return vmEntityVO.getDetails(); - } - - @Override - public void addDetail(String name, String value) { - vmEntityVO.setDetail(name, value); - } - - @Override - public void delDetail(String name, String value) { - // TODO Auto-generated method stub - } - - @Override - public void updateDetail(String name, String value) { - // TODO Auto-generated method stub - } - - @Override - public List getApplicableActions() { - // TODO Auto-generated method stub - return null; - } - - @Override - public List listVolumeIds() { - // TODO Auto-generated method stub - return null; - } - - @Override - public List listVolumes() { - // TODO Auto-generated method stub - return null; - } - - @Override - public List listNicUuids() { - // TODO Auto-generated method stub - return null; - } - - @Override - public List listNics() { - // TODO Auto-generated method stub - return null; - } - - @Override - public TemplateEntity getTemplate() { - // TODO Auto-generated method stub - return null; - } - - @Override - public List listTags() { - // TODO Auto-generated method stub - return null; - } - - @Override - public void addTag() { - // TODO Auto-generated method stub - - } - - @Override - public void delTag() { - // TODO Auto-generated method stub - - } - - @Override - public String reserve(String plannerToUse, DeploymentPlan plan, - ExcludeList exclude, String caller) throws InsufficientCapacityException, ResourceUnavailableException { - return manager.reserveVirtualMachine(this.vmEntityVO, plannerToUse, plan, exclude); - } - - @Override - public void migrateTo(String reservationId, String caller) { - // TODO Auto-generated method stub - - } - - @Override + + public VirtualMachineEntityImpl(String vmId, VMEntityManager manager) { + this.manager = manager; + this.vmEntityVO = this.manager.loadVirtualMachine(vmId); + } + + public VirtualMachineEntityImpl(String vmId, String owner, String hostName, String displayName, int cpu, int speed, long memory, List computeTags, List rootDiskTags, List networks, VMEntityManager manager) { + this(vmId, manager); + 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); + + manager.saveVirtualMachine(vmEntityVO); + } + + @Override + public String getUuid() { + return vmEntityVO.getUuid(); + } + + @Override + public long getId() { + return vmEntityVO.getId(); + } + + @Override + public String getCurrentState() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getDesiredState() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Date getCreatedTime() { + return vmEntityVO.getCreated(); + } + + @Override + public Date getLastUpdatedTime() { + return vmEntityVO.getUpdateTime(); + } + + @Override + public String getOwner() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Map getDetails() { + return vmEntityVO.getDetails(); + } + + @Override + public void addDetail(String name, String value) { + vmEntityVO.setDetail(name, value); + } + + @Override + public void delDetail(String name, String value) { + // TODO Auto-generated method stub + } + + @Override + public void updateDetail(String name, String value) { + // TODO Auto-generated method stub + } + + @Override + public List getApplicableActions() { + // TODO Auto-generated method stub + return null; + } + + @Override + public List listVolumeIds() { + // TODO Auto-generated method stub + return null; + } + + @Override + public List listVolumes() { + // TODO Auto-generated method stub + return null; + } + + @Override + public List listNicUuids() { + // TODO Auto-generated method stub + return null; + } + + @Override + public List listNics() { + // TODO Auto-generated method stub + return null; + } + + @Override + public TemplateEntity getTemplate() { + // TODO Auto-generated method stub + return null; + } + + @Override + public List listTags() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void addTag() { + // TODO Auto-generated method stub + + } + + @Override + public void delTag() { + // TODO Auto-generated method stub + + } + + @Override + public String reserve(String plannerToUse, DeploymentPlan plan, + ExcludeList exclude, String caller) throws InsufficientCapacityException, ResourceUnavailableException { + return manager.reserveVirtualMachine(this.vmEntityVO, plannerToUse, plan, exclude); + } + + @Override + public void migrateTo(String reservationId, String caller) { + // TODO Auto-generated method stub + + } + + @Override public void deploy(String reservationId, String caller, Map params) throws InsufficientCapacityException, ResourceUnavailableException{ manager.deployVirtualMachine(reservationId, caller, params); - } - - @Override - public boolean stop(String caller) throws ResourceUnavailableException{ - return manager.stopvirtualmachine(this.vmEntityVO, caller); - } - - @Override - public void cleanup() { - // TODO Auto-generated method stub - - } - - @Override - public boolean destroy(String caller) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException { - return manager.destroyVirtualMachine(this.vmEntityVO, caller); - } - - @Override - public VirtualMachineEntity duplicate(String externalId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public SnapshotEntity takeSnapshotOf() { - // TODO Auto-generated method stub - return null; - } - - @Override - public void attach(VolumeEntity volume, short deviceId) { - // TODO Auto-generated method stub - - } - - @Override - public void detach(VolumeEntity volume) { - // TODO Auto-generated method stub - - } - - @Override - public void connectTo(NetworkEntity network, short nicId) { - // TODO Auto-generated method stub - - } - - @Override - public void disconnectFrom(NetworkEntity netowrk, short nicId) { - // TODO Auto-generated method stub - - } - -} + } + + @Override + public boolean stop(String caller) throws ResourceUnavailableException{ + return manager.stopvirtualmachine(this.vmEntityVO, caller); + } + + @Override + public void cleanup() { + // TODO Auto-generated method stub + + } + + @Override + public boolean destroy(String caller) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException { + return manager.destroyVirtualMachine(this.vmEntityVO, caller); + } + + @Override + public VirtualMachineEntity duplicate(String externalId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public SnapshotEntity takeSnapshotOf() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void attach(VolumeEntity volume, short deviceId) { + // TODO Auto-generated method stub + + } + + @Override + public void detach(VolumeEntity volume) { + // TODO Auto-generated method stub + + } + + @Override + public void connectTo(NetworkEntity network, short nicId) { + // TODO Auto-generated method stub + + } + + @Override + public void disconnectFrom(NetworkEntity netowrk, short nicId) { + // TODO Auto-generated method stub + + } + +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/VMComputeTagVO.java b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/VMComputeTagVO.java index c367ee95483..e4fc2283349 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/VMComputeTagVO.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/VMComputeTagVO.java @@ -14,54 +14,54 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package org.apache.cloudstack.engine.cloud.entity.api.db; - -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 = "vm_compute_tags") -public class VMComputeTagVO implements InternalIdentity{ - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - private long id; - - @Column(name = "vm_id") - private long vmId; - - @Column(name = "compute_tag") - private String computeTag; - - /** - * There should never be a public constructor for this class. Since it's - * only here to define the table for the DAO class. - */ - protected VMComputeTagVO() { - } - - public VMComputeTagVO(long vmId, String tag) { - this.vmId = vmId; - this.computeTag = tag; - } - - public long getId() { - return id; - } - - public long getVmId() { - return vmId; - } - - public String getComputeTag() { - return computeTag; - } - -} +package org.apache.cloudstack.engine.cloud.entity.api.db; + +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 = "vm_compute_tags") +public class VMComputeTagVO implements InternalIdentity{ + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "vm_id") + private long vmId; + + @Column(name = "compute_tag") + private String computeTag; + + /** + * There should never be a public constructor for this class. Since it's + * only here to define the table for the DAO class. + */ + protected VMComputeTagVO() { + } + + public VMComputeTagVO(long vmId, String tag) { + this.vmId = vmId; + this.computeTag = tag; + } + + public long getId() { + return id; + } + + public long getVmId() { + return vmId; + } + + public String getComputeTag() { + return computeTag; + } + +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/VMEntityVO.java b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/VMEntityVO.java index 4fe6718e33a..4748215e3c6 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/VMEntityVO.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/VMEntityVO.java @@ -574,4 +574,4 @@ public class VMEntityVO implements VirtualMachine, FiniteStateObject poolId - @Transient - Map volumeReservationMap; - - /** - * There should never be a public constructor for this class. Since it's - * only here to define the table for the DAO class. - */ - protected VMReservationVO() { - } - - public VMReservationVO(long vmId, long dataCenterId, long podId, long clusterId, long hostId) { - this.vmId = vmId; - this.dataCenterId = dataCenterId; - this.podId = podId; - this.clusterId = clusterId; - this.hostId = hostId; - this.uuid = UUID.randomUUID().toString(); - } - - - public long getId() { - return id; - } - - public long getVmId() { - return vmId; - } - - @Override - public String getUuid() { - return uuid; - } - - public long getDataCenterId() { - return dataCenterId; - } - - public Long getPodId() { - return podId; - } - - public Long getClusterId() { - return clusterId; - } - - public Long getHostId() { - return hostId; - } - - public Map getVolumeReservation(){ - return volumeReservationMap; - } - - public void setVolumeReservation(Map volumeReservationMap){ - this.volumeReservationMap = volumeReservationMap; - } - -} +package org.apache.cloudstack.engine.cloud.entity.api.db; + +import java.util.Date; +import java.util.Map; +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 javax.persistence.Transient; + +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +import com.cloud.utils.db.GenericDao; + +@Entity +@Table(name = "vm_reservation") +public class VMReservationVO implements Identity, InternalIdentity{ + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "vm_id") + private long vmId; + + @Column(name="uuid") + private String uuid; + + @Column(name="data_center_id") + private long dataCenterId; + + @Column(name="pod_id") + private long podId; + + @Column(name="cluster_id") + private long clusterId; + + @Column(name="host_id") + private long hostId; + + @Column(name=GenericDao.CREATED_COLUMN) + private Date created; + + @Column(name=GenericDao.REMOVED_COLUMN) + private Date removed; + + // VolumeId -> poolId + @Transient + Map volumeReservationMap; + + /** + * There should never be a public constructor for this class. Since it's + * only here to define the table for the DAO class. + */ + protected VMReservationVO() { + } + + public VMReservationVO(long vmId, long dataCenterId, long podId, long clusterId, long hostId) { + this.vmId = vmId; + this.dataCenterId = dataCenterId; + this.podId = podId; + this.clusterId = clusterId; + this.hostId = hostId; + this.uuid = UUID.randomUUID().toString(); + } + + + public long getId() { + return id; + } + + public long getVmId() { + return vmId; + } + + @Override + public String getUuid() { + return uuid; + } + + public long getDataCenterId() { + return dataCenterId; + } + + public Long getPodId() { + return podId; + } + + public Long getClusterId() { + return clusterId; + } + + public Long getHostId() { + return hostId; + } + + public Map getVolumeReservation(){ + return volumeReservationMap; + } + + public void setVolumeReservation(Map volumeReservationMap){ + this.volumeReservationMap = volumeReservationMap; + } + +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/VMRootDiskTagVO.java b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/VMRootDiskTagVO.java index a1cca3f9040..3c09e930693 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/VMRootDiskTagVO.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/VMRootDiskTagVO.java @@ -14,54 +14,54 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package org.apache.cloudstack.engine.cloud.entity.api.db; - -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 = "vm_root_disk_tags") -public class VMRootDiskTagVO implements InternalIdentity { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - private long id; - - @Column(name = "vm_id") - private long vmId; - - @Column(name = "root_disk_tag") - private String rootDiskTag; - - /** - * There should never be a public constructor for this class. Since it's - * only here to define the table for the DAO class. - */ - protected VMRootDiskTagVO() { - } - - public VMRootDiskTagVO(long vmId, String rootDiskTag) { - this.vmId = vmId; - this.rootDiskTag = rootDiskTag; - } - - public long getId() { - return id; - } - - public long getVmId() { - return vmId; - } - - public String getRootDiskTag() { - return rootDiskTag; - } - -} +package org.apache.cloudstack.engine.cloud.entity.api.db; + +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 = "vm_root_disk_tags") +public class VMRootDiskTagVO implements InternalIdentity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "vm_id") + private long vmId; + + @Column(name = "root_disk_tag") + private String rootDiskTag; + + /** + * There should never be a public constructor for this class. Since it's + * only here to define the table for the DAO class. + */ + protected VMRootDiskTagVO() { + } + + public VMRootDiskTagVO(long vmId, String rootDiskTag) { + this.vmId = vmId; + this.rootDiskTag = rootDiskTag; + } + + public long getId() { + return id; + } + + public long getVmId() { + return vmId; + } + + public String getRootDiskTag() { + return rootDiskTag; + } + +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/VolumeReservationVO.java b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/VolumeReservationVO.java index cbad9aba568..f064623f887 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/VolumeReservationVO.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/VolumeReservationVO.java @@ -14,87 +14,87 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package org.apache.cloudstack.engine.cloud.entity.api.db; - -import java.util.Date; -import java.util.Map; - -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 javax.persistence.Transient; - -import org.apache.cloudstack.api.Identity; -import org.apache.cloudstack.api.InternalIdentity; - -import com.cloud.utils.db.GenericDao; - -@Entity -@Table(name = "volume_reservation") -public class VolumeReservationVO implements InternalIdentity{ - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - private long id; - - @Column(name = "vm_reservation_id") - private Long vmReservationId; - - @Column(name = "vm_id") - private long vmId; - - @Column(name="volume_id") - private long volumeId; - - @Column(name="pool_id") - private long poolId; - - // VolumeId -> poolId - @Transient - Map volumeReservationMap; - - /** - * There should never be a public constructor for this class. Since it's - * only here to define the table for the DAO class. - */ - protected VolumeReservationVO() { - } - - public VolumeReservationVO(long vmId, long volumeId, long poolId, Long vmReservationId) { - this.vmId = vmId; - this.volumeId = volumeId; - this.poolId = poolId; - this.vmReservationId = vmReservationId; - } - - - public long getId() { - return id; - } - - public long getVmId() { - return vmId; - } - - public Long geVmReservationId() { - return vmReservationId; - } - - public long getVolumeId() { - return volumeId; - } - - public Long getPoolId() { - return poolId; - } - - - public Map getVolumeReservation(){ - return volumeReservationMap; - } - -} +package org.apache.cloudstack.engine.cloud.entity.api.db; + +import java.util.Date; +import java.util.Map; + +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 javax.persistence.Transient; + +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +import com.cloud.utils.db.GenericDao; + +@Entity +@Table(name = "volume_reservation") +public class VolumeReservationVO implements InternalIdentity{ + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "vm_reservation_id") + private Long vmReservationId; + + @Column(name = "vm_id") + private long vmId; + + @Column(name="volume_id") + private long volumeId; + + @Column(name="pool_id") + private long poolId; + + // VolumeId -> poolId + @Transient + Map volumeReservationMap; + + /** + * There should never be a public constructor for this class. Since it's + * only here to define the table for the DAO class. + */ + protected VolumeReservationVO() { + } + + public VolumeReservationVO(long vmId, long volumeId, long poolId, Long vmReservationId) { + this.vmId = vmId; + this.volumeId = volumeId; + this.poolId = poolId; + this.vmReservationId = vmReservationId; + } + + + public long getId() { + return id; + } + + public long getVmId() { + return vmId; + } + + public Long geVmReservationId() { + return vmReservationId; + } + + public long getVolumeId() { + return volumeId; + } + + public Long getPoolId() { + return poolId; + } + + + public Map getVolumeReservation(){ + return volumeReservationMap; + } + +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMComputeTagDao.java b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMComputeTagDao.java index d01bf2f12d3..d8178d4a8f4 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMComputeTagDao.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMComputeTagDao.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 org.apache.cloudstack.engine.cloud.entity.api.db.dao; - -import java.util.List; - -import org.apache.cloudstack.engine.cloud.entity.api.db.VMComputeTagVO; - -import com.cloud.utils.db.GenericDao; - -public interface VMComputeTagDao extends GenericDao{ - - void persist(long vmId, List computeTags); - - List getComputeTags(long vmId); - -} +package org.apache.cloudstack.engine.cloud.entity.api.db.dao; + +import java.util.List; + +import org.apache.cloudstack.engine.cloud.entity.api.db.VMComputeTagVO; + +import com.cloud.utils.db.GenericDao; + +public interface VMComputeTagDao extends GenericDao{ + + void persist(long vmId, List computeTags); + + List getComputeTags(long vmId); + +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMComputeTagDaoImpl.java b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMComputeTagDaoImpl.java index 6037ad4ec26..6f70b353176 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMComputeTagDaoImpl.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMComputeTagDaoImpl.java @@ -14,76 +14,76 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package org.apache.cloudstack.engine.cloud.entity.api.db.dao; - - -import java.util.ArrayList; -import java.util.List; - -import javax.annotation.PostConstruct; -import javax.ejb.Local; - - -import org.apache.cloudstack.engine.cloud.entity.api.db.VMComputeTagVO; - -import org.springframework.stereotype.Component; - -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.Transaction; - -@Component -@Local(value = { VMComputeTagDao.class }) -public class VMComputeTagDaoImpl extends GenericDaoBase implements VMComputeTagDao { - - protected SearchBuilder VmIdSearch; - - public VMComputeTagDaoImpl() { - } - - @PostConstruct - public void init() { - VmIdSearch = createSearchBuilder(); - VmIdSearch.and("vmId", VmIdSearch.entity().getVmId(), SearchCriteria.Op.EQ); - VmIdSearch.done(); - - } - - @Override - public void persist(long vmId, List computeTags) { - Transaction txn = Transaction.currentTxn(); - - txn.start(); - SearchCriteria sc = VmIdSearch.create(); - sc.setParameters("vmId", vmId); - expunge(sc); - - for (String tag : computeTags) { - if(tag != null){ - tag = tag.trim(); - if(tag.length() > 0) { - VMComputeTagVO vo = new VMComputeTagVO(vmId, tag); - persist(vo); - } - } - } - txn.commit(); - } - - @Override - public List getComputeTags(long vmId) { - - SearchCriteria sc = VmIdSearch.create(); - sc.setParameters("vmId", vmId); - - List results = search(sc, null); - List computeTags = new ArrayList(results.size()); - for (VMComputeTagVO result : results) { - computeTags.add(result.getComputeTag()); - } - - return computeTags; - } - -} +package org.apache.cloudstack.engine.cloud.entity.api.db.dao; + + +import java.util.ArrayList; +import java.util.List; + +import javax.annotation.PostConstruct; +import javax.ejb.Local; + + +import org.apache.cloudstack.engine.cloud.entity.api.db.VMComputeTagVO; + +import org.springframework.stereotype.Component; + +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.Transaction; + +@Component +@Local(value = { VMComputeTagDao.class }) +public class VMComputeTagDaoImpl extends GenericDaoBase implements VMComputeTagDao { + + protected SearchBuilder VmIdSearch; + + public VMComputeTagDaoImpl() { + } + + @PostConstruct + public void init() { + VmIdSearch = createSearchBuilder(); + VmIdSearch.and("vmId", VmIdSearch.entity().getVmId(), SearchCriteria.Op.EQ); + VmIdSearch.done(); + + } + + @Override + public void persist(long vmId, List computeTags) { + Transaction txn = Transaction.currentTxn(); + + txn.start(); + SearchCriteria sc = VmIdSearch.create(); + sc.setParameters("vmId", vmId); + expunge(sc); + + for (String tag : computeTags) { + if(tag != null){ + tag = tag.trim(); + if(tag.length() > 0) { + VMComputeTagVO vo = new VMComputeTagVO(vmId, tag); + persist(vo); + } + } + } + txn.commit(); + } + + @Override + public List getComputeTags(long vmId) { + + SearchCriteria sc = VmIdSearch.create(); + sc.setParameters("vmId", vmId); + + List results = search(sc, null); + List computeTags = new ArrayList(results.size()); + for (VMComputeTagVO result : results) { + computeTags.add(result.getComputeTag()); + } + + return computeTags; + } + +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMNetworkMapDao.java b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMNetworkMapDao.java index baa0920162b..59c41c298ac 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMNetworkMapDao.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMNetworkMapDao.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 org.apache.cloudstack.engine.cloud.entity.api.db.dao; - -import java.util.List; - -import org.apache.cloudstack.engine.cloud.entity.api.db.VMNetworkMapVO; - -import com.cloud.utils.db.GenericDao; - -public interface VMNetworkMapDao extends GenericDao{ - - void persist(long vmId, List networks); - - List getNetworks(long vmId); - -} +package org.apache.cloudstack.engine.cloud.entity.api.db.dao; + +import java.util.List; + +import org.apache.cloudstack.engine.cloud.entity.api.db.VMNetworkMapVO; + +import com.cloud.utils.db.GenericDao; + +public interface VMNetworkMapDao extends GenericDao{ + + void persist(long vmId, List networks); + + List getNetworks(long vmId); + +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMNetworkMapDaoImpl.java b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMNetworkMapDaoImpl.java index 378f16d519f..0f2c4ccb77e 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMNetworkMapDaoImpl.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMNetworkMapDaoImpl.java @@ -14,72 +14,72 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package org.apache.cloudstack.engine.cloud.entity.api.db.dao; - - -import java.util.ArrayList; -import java.util.List; -import javax.annotation.PostConstruct; -import javax.ejb.Local; -import javax.inject.Inject; -import org.apache.cloudstack.engine.cloud.entity.api.db.VMNetworkMapVO; -import org.springframework.stereotype.Component; -import com.cloud.network.dao.NetworkDao; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.Transaction; - -@Component -@Local(value = { VMNetworkMapDao.class }) -public class VMNetworkMapDaoImpl extends GenericDaoBase implements VMNetworkMapDao { - - protected SearchBuilder VmIdSearch; - - @Inject - protected NetworkDao _networkDao; - - public VMNetworkMapDaoImpl() { - } - - @PostConstruct - public void init() { - VmIdSearch = createSearchBuilder(); - VmIdSearch.and("vmId", VmIdSearch.entity().getVmId(), SearchCriteria.Op.EQ); - VmIdSearch.done(); - - } - - @Override - public void persist(long vmId, List networks) { - Transaction txn = Transaction.currentTxn(); - - txn.start(); - SearchCriteria sc = VmIdSearch.create(); - sc.setParameters("vmId", vmId); - expunge(sc); - - for (Long networkId : networks) { - VMNetworkMapVO vo = new VMNetworkMapVO(vmId, networkId); - persist(vo); - } - - txn.commit(); - } - - @Override - public List getNetworks(long vmId) { - - SearchCriteria sc = VmIdSearch.create(); - sc.setParameters("vmId", vmId); - - List results = search(sc, null); - List networks = new ArrayList(results.size()); - for (VMNetworkMapVO result : results) { - networks.add(result.getNetworkId()); - } - - return networks; - } - -} +package org.apache.cloudstack.engine.cloud.entity.api.db.dao; + + +import java.util.ArrayList; +import java.util.List; +import javax.annotation.PostConstruct; +import javax.ejb.Local; +import javax.inject.Inject; +import org.apache.cloudstack.engine.cloud.entity.api.db.VMNetworkMapVO; +import org.springframework.stereotype.Component; +import com.cloud.network.dao.NetworkDao; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.Transaction; + +@Component +@Local(value = { VMNetworkMapDao.class }) +public class VMNetworkMapDaoImpl extends GenericDaoBase implements VMNetworkMapDao { + + protected SearchBuilder VmIdSearch; + + @Inject + protected NetworkDao _networkDao; + + public VMNetworkMapDaoImpl() { + } + + @PostConstruct + public void init() { + VmIdSearch = createSearchBuilder(); + VmIdSearch.and("vmId", VmIdSearch.entity().getVmId(), SearchCriteria.Op.EQ); + VmIdSearch.done(); + + } + + @Override + public void persist(long vmId, List networks) { + Transaction txn = Transaction.currentTxn(); + + txn.start(); + SearchCriteria sc = VmIdSearch.create(); + sc.setParameters("vmId", vmId); + expunge(sc); + + for (Long networkId : networks) { + VMNetworkMapVO vo = new VMNetworkMapVO(vmId, networkId); + persist(vo); + } + + txn.commit(); + } + + @Override + public List getNetworks(long vmId) { + + SearchCriteria sc = VmIdSearch.create(); + sc.setParameters("vmId", vmId); + + List results = search(sc, null); + List networks = new ArrayList(results.size()); + for (VMNetworkMapVO result : results) { + networks.add(result.getNetworkId()); + } + + return networks; + } + +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMReservationDao.java b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMReservationDao.java index a312578a4ed..721a8c48326 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMReservationDao.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMReservationDao.java @@ -14,21 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package org.apache.cloudstack.engine.cloud.entity.api.db.dao; - - -import java.util.Map; - -import org.apache.cloudstack.engine.cloud.entity.api.db.VMReservationVO; - -import com.cloud.utils.db.GenericDao; - -public interface VMReservationDao extends GenericDao{ - - VMReservationVO findByVmId(long vmId); - - void loadVolumeReservation(VMReservationVO reservation); - - VMReservationVO findByReservationId(String reservationId); - -} +package org.apache.cloudstack.engine.cloud.entity.api.db.dao; + + +import java.util.Map; + +import org.apache.cloudstack.engine.cloud.entity.api.db.VMReservationVO; + +import com.cloud.utils.db.GenericDao; + +public interface VMReservationDao extends GenericDao{ + + VMReservationVO findByVmId(long vmId); + + void loadVolumeReservation(VMReservationVO reservation); + + VMReservationVO findByReservationId(String reservationId); + +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMReservationDaoImpl.java b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMReservationDaoImpl.java index dc346cc2423..73b4dd2194c 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMReservationDaoImpl.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMReservationDaoImpl.java @@ -14,98 +14,98 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package org.apache.cloudstack.engine.cloud.entity.api.db.dao; - - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.annotation.PostConstruct; -import javax.ejb.Local; -import javax.inject.Inject; - -import org.apache.cloudstack.engine.cloud.entity.api.db.VMEntityVO; -import org.apache.cloudstack.engine.cloud.entity.api.db.VMReservationVO; -import org.apache.cloudstack.engine.cloud.entity.api.db.VolumeReservationVO; -import org.springframework.stereotype.Component; - -import com.cloud.host.dao.HostTagsDaoImpl; -import com.cloud.utils.db.DB; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.Transaction; - -@Component -@Local(value = { VMReservationDao.class }) -public class VMReservationDaoImpl extends GenericDaoBase implements VMReservationDao { - - protected SearchBuilder VmIdSearch; - - @Inject protected VolumeReservationDao _volumeReservationDao; - - public VMReservationDaoImpl() { - } - - @PostConstruct - public void init() { - VmIdSearch = createSearchBuilder(); - VmIdSearch.and("vmId", VmIdSearch.entity().getVmId(), SearchCriteria.Op.EQ); - VmIdSearch.done(); - } - - @Override - public VMReservationVO findByVmId(long vmId) { - SearchCriteria sc = VmIdSearch.create("vmId", vmId); - VMReservationVO vmRes = findOneBy(sc); - loadVolumeReservation(vmRes); - return vmRes; - } - - - @Override - public void loadVolumeReservation(VMReservationVO reservation){ - if(reservation != null){ - List volumeResList = _volumeReservationDao.listVolumeReservation(reservation.getId()); - Map volumeReservationMap = new HashMap(); - - for(VolumeReservationVO res : volumeResList){ - volumeReservationMap.put(res.getVolumeId(), res.getPoolId()); - } - reservation.setVolumeReservation(volumeReservationMap); - } - } - - @Override - @DB - public VMReservationVO persist(VMReservationVO reservation) { - Transaction txn = Transaction.currentTxn(); - txn.start(); - - VMReservationVO dbVO = super.persist(reservation); - - saveVolumeReservation(reservation); - loadVolumeReservation(dbVO); - - txn.commit(); - - return dbVO; - } - - private void saveVolumeReservation(VMReservationVO reservation) { - if(reservation.getVolumeReservation() != null){ - for(Long volumeId : reservation.getVolumeReservation().keySet()){ - VolumeReservationVO volumeReservation = new VolumeReservationVO(reservation.getVmId(), volumeId, reservation.getVolumeReservation().get(volumeId), reservation.getId()); - _volumeReservationDao.persist(volumeReservation); - } - } - } - - @Override - public VMReservationVO findByReservationId(String reservationId) { - VMReservationVO vmRes = super.findByUuid(reservationId); - loadVolumeReservation(vmRes); - return vmRes; - } -} +package org.apache.cloudstack.engine.cloud.entity.api.db.dao; + + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.annotation.PostConstruct; +import javax.ejb.Local; +import javax.inject.Inject; + +import org.apache.cloudstack.engine.cloud.entity.api.db.VMEntityVO; +import org.apache.cloudstack.engine.cloud.entity.api.db.VMReservationVO; +import org.apache.cloudstack.engine.cloud.entity.api.db.VolumeReservationVO; +import org.springframework.stereotype.Component; + +import com.cloud.host.dao.HostTagsDaoImpl; +import com.cloud.utils.db.DB; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.Transaction; + +@Component +@Local(value = { VMReservationDao.class }) +public class VMReservationDaoImpl extends GenericDaoBase implements VMReservationDao { + + protected SearchBuilder VmIdSearch; + + @Inject protected VolumeReservationDao _volumeReservationDao; + + public VMReservationDaoImpl() { + } + + @PostConstruct + public void init() { + VmIdSearch = createSearchBuilder(); + VmIdSearch.and("vmId", VmIdSearch.entity().getVmId(), SearchCriteria.Op.EQ); + VmIdSearch.done(); + } + + @Override + public VMReservationVO findByVmId(long vmId) { + SearchCriteria sc = VmIdSearch.create("vmId", vmId); + VMReservationVO vmRes = findOneBy(sc); + loadVolumeReservation(vmRes); + return vmRes; + } + + + @Override + public void loadVolumeReservation(VMReservationVO reservation){ + if(reservation != null){ + List volumeResList = _volumeReservationDao.listVolumeReservation(reservation.getId()); + Map volumeReservationMap = new HashMap(); + + for(VolumeReservationVO res : volumeResList){ + volumeReservationMap.put(res.getVolumeId(), res.getPoolId()); + } + reservation.setVolumeReservation(volumeReservationMap); + } + } + + @Override + @DB + public VMReservationVO persist(VMReservationVO reservation) { + Transaction txn = Transaction.currentTxn(); + txn.start(); + + VMReservationVO dbVO = super.persist(reservation); + + saveVolumeReservation(reservation); + loadVolumeReservation(dbVO); + + txn.commit(); + + return dbVO; + } + + private void saveVolumeReservation(VMReservationVO reservation) { + if(reservation.getVolumeReservation() != null){ + for(Long volumeId : reservation.getVolumeReservation().keySet()){ + VolumeReservationVO volumeReservation = new VolumeReservationVO(reservation.getVmId(), volumeId, reservation.getVolumeReservation().get(volumeId), reservation.getId()); + _volumeReservationDao.persist(volumeReservation); + } + } + } + + @Override + public VMReservationVO findByReservationId(String reservationId) { + VMReservationVO vmRes = super.findByUuid(reservationId); + loadVolumeReservation(vmRes); + return vmRes; + } +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMRootDiskTagDao.java b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMRootDiskTagDao.java index 5a4c2be07d4..dc00880d79d 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMRootDiskTagDao.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMRootDiskTagDao.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 org.apache.cloudstack.engine.cloud.entity.api.db.dao; - -import java.util.List; - -import org.apache.cloudstack.engine.cloud.entity.api.db.VMRootDiskTagVO; - -import com.cloud.utils.db.GenericDao; - -public interface VMRootDiskTagDao extends GenericDao{ - - void persist(long vmId, List diskTags); - - List getRootDiskTags(long vmId); - -} +package org.apache.cloudstack.engine.cloud.entity.api.db.dao; + +import java.util.List; + +import org.apache.cloudstack.engine.cloud.entity.api.db.VMRootDiskTagVO; + +import com.cloud.utils.db.GenericDao; + +public interface VMRootDiskTagDao extends GenericDao{ + + void persist(long vmId, List diskTags); + + List getRootDiskTags(long vmId); + +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMRootDiskTagDaoImpl.java b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMRootDiskTagDaoImpl.java index 60ea5479398..be194bbfcaa 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMRootDiskTagDaoImpl.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VMRootDiskTagDaoImpl.java @@ -14,75 +14,75 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package org.apache.cloudstack.engine.cloud.entity.api.db.dao; - - -import java.util.ArrayList; -import java.util.List; - -import javax.annotation.PostConstruct; -import javax.ejb.Local; - - -import org.apache.cloudstack.engine.cloud.entity.api.db.VMRootDiskTagVO; - -import org.springframework.stereotype.Component; - -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.Transaction; - -@Component -@Local(value = { VMRootDiskTagDao.class }) -public class VMRootDiskTagDaoImpl extends GenericDaoBase implements VMRootDiskTagDao { - - protected SearchBuilder VmIdSearch; - - public VMRootDiskTagDaoImpl() { - } - - @PostConstruct - public void init() { - VmIdSearch = createSearchBuilder(); - VmIdSearch.and("vmId", VmIdSearch.entity().getVmId(), SearchCriteria.Op.EQ); - VmIdSearch.done(); - - } - - @Override - public void persist(long vmId, List rootDiskTags) { - Transaction txn = Transaction.currentTxn(); - - txn.start(); - SearchCriteria sc = VmIdSearch.create(); - sc.setParameters("vmId", vmId); - expunge(sc); - - for (String tag : rootDiskTags) { - if(tag != null){ - tag = tag.trim(); - if(tag.length() > 0) { - VMRootDiskTagVO vo = new VMRootDiskTagVO(vmId, tag); - persist(vo); - } - } - } - txn.commit(); - } - - - @Override - public List getRootDiskTags(long vmId) { - SearchCriteria sc = VmIdSearch.create(); - sc.setParameters("vmId", vmId); - - List results = search(sc, null); - List computeTags = new ArrayList(results.size()); - for (VMRootDiskTagVO result : results) { - computeTags.add(result.getRootDiskTag()); - } - return computeTags; - } - -} +package org.apache.cloudstack.engine.cloud.entity.api.db.dao; + + +import java.util.ArrayList; +import java.util.List; + +import javax.annotation.PostConstruct; +import javax.ejb.Local; + + +import org.apache.cloudstack.engine.cloud.entity.api.db.VMRootDiskTagVO; + +import org.springframework.stereotype.Component; + +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.Transaction; + +@Component +@Local(value = { VMRootDiskTagDao.class }) +public class VMRootDiskTagDaoImpl extends GenericDaoBase implements VMRootDiskTagDao { + + protected SearchBuilder VmIdSearch; + + public VMRootDiskTagDaoImpl() { + } + + @PostConstruct + public void init() { + VmIdSearch = createSearchBuilder(); + VmIdSearch.and("vmId", VmIdSearch.entity().getVmId(), SearchCriteria.Op.EQ); + VmIdSearch.done(); + + } + + @Override + public void persist(long vmId, List rootDiskTags) { + Transaction txn = Transaction.currentTxn(); + + txn.start(); + SearchCriteria sc = VmIdSearch.create(); + sc.setParameters("vmId", vmId); + expunge(sc); + + for (String tag : rootDiskTags) { + if(tag != null){ + tag = tag.trim(); + if(tag.length() > 0) { + VMRootDiskTagVO vo = new VMRootDiskTagVO(vmId, tag); + persist(vo); + } + } + } + txn.commit(); + } + + + @Override + public List getRootDiskTags(long vmId) { + SearchCriteria sc = VmIdSearch.create(); + sc.setParameters("vmId", vmId); + + List results = search(sc, null); + List computeTags = new ArrayList(results.size()); + for (VMRootDiskTagVO result : results) { + computeTags.add(result.getRootDiskTag()); + } + return computeTags; + } + +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VolumeReservationDao.java b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VolumeReservationDao.java index d6a9fe28146..fd709b0db0a 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VolumeReservationDao.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VolumeReservationDao.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 org.apache.cloudstack.engine.cloud.entity.api.db.dao; - -import java.util.List; - -import org.apache.cloudstack.engine.cloud.entity.api.db.VolumeReservationVO; - -import com.cloud.utils.db.GenericDao; - -public interface VolumeReservationDao extends GenericDao{ - - VolumeReservationVO findByVmId(long vmId); - - List listVolumeReservation(long vmReservationId); - -} +package org.apache.cloudstack.engine.cloud.entity.api.db.dao; + +import java.util.List; + +import org.apache.cloudstack.engine.cloud.entity.api.db.VolumeReservationVO; + +import com.cloud.utils.db.GenericDao; + +public interface VolumeReservationDao extends GenericDao{ + + VolumeReservationVO findByVmId(long vmId); + + List listVolumeReservation(long vmReservationId); + +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VolumeReservationDaoImpl.java b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VolumeReservationDaoImpl.java index 4b1b1e667d6..26bc65f35c1 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VolumeReservationDaoImpl.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/db/dao/VolumeReservationDaoImpl.java @@ -14,55 +14,55 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package org.apache.cloudstack.engine.cloud.entity.api.db.dao; - - -import java.util.List; - -import javax.annotation.PostConstruct; -import javax.ejb.Local; -import javax.inject.Inject; - -import org.apache.cloudstack.engine.cloud.entity.api.db.VMReservationVO; -import org.apache.cloudstack.engine.cloud.entity.api.db.VolumeReservationVO; -import org.springframework.stereotype.Component; - -import com.cloud.host.dao.HostTagsDaoImpl; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; - -@Component -@Local(value = { VolumeReservationDao.class }) -public class VolumeReservationDaoImpl extends GenericDaoBase implements VolumeReservationDao { - - protected SearchBuilder VmIdSearch; - protected SearchBuilder VmReservationIdSearch; - - public VolumeReservationDaoImpl() { - } - - @PostConstruct - public void init() { - VmIdSearch = createSearchBuilder(); - VmIdSearch.and("vmId", VmIdSearch.entity().getVmId(), SearchCriteria.Op.EQ); - VmIdSearch.done(); - - VmReservationIdSearch = createSearchBuilder(); - VmReservationIdSearch.and("vmReservationId", VmReservationIdSearch.entity().geVmReservationId(), SearchCriteria.Op.EQ); - VmReservationIdSearch.done(); - } - - @Override - public VolumeReservationVO findByVmId(long vmId) { - SearchCriteria sc = VmIdSearch.create("vmId", vmId); - return findOneBy(sc); - } - - @Override - public List listVolumeReservation(long vmReservationId) { - SearchCriteria sc = VmReservationIdSearch.create("vmReservationId", vmReservationId); - return listBy(sc); - } - -} +package org.apache.cloudstack.engine.cloud.entity.api.db.dao; + + +import java.util.List; + +import javax.annotation.PostConstruct; +import javax.ejb.Local; +import javax.inject.Inject; + +import org.apache.cloudstack.engine.cloud.entity.api.db.VMReservationVO; +import org.apache.cloudstack.engine.cloud.entity.api.db.VolumeReservationVO; +import org.springframework.stereotype.Component; + +import com.cloud.host.dao.HostTagsDaoImpl; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +@Component +@Local(value = { VolumeReservationDao.class }) +public class VolumeReservationDaoImpl extends GenericDaoBase implements VolumeReservationDao { + + protected SearchBuilder VmIdSearch; + protected SearchBuilder VmReservationIdSearch; + + public VolumeReservationDaoImpl() { + } + + @PostConstruct + public void init() { + VmIdSearch = createSearchBuilder(); + VmIdSearch.and("vmId", VmIdSearch.entity().getVmId(), SearchCriteria.Op.EQ); + VmIdSearch.done(); + + VmReservationIdSearch = createSearchBuilder(); + VmReservationIdSearch.and("vmReservationId", VmReservationIdSearch.entity().geVmReservationId(), SearchCriteria.Op.EQ); + VmReservationIdSearch.done(); + } + + @Override + public VolumeReservationVO findByVmId(long vmId) { + SearchCriteria sc = VmIdSearch.create("vmId", vmId); + return findOneBy(sc); + } + + @Override + public List listVolumeReservation(long vmReservationId) { + SearchCriteria sc = VmReservationIdSearch.create("vmReservationId", vmReservationId); + return listBy(sc); + } + +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/ClusterEntityImpl.java b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/ClusterEntityImpl.java index 3471b7ae376..46dd21d28eb 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/ClusterEntityImpl.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/ClusterEntityImpl.java @@ -14,196 +14,196 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. - -package org.apache.cloudstack.engine.datacenter.entity.api; - -import java.lang.reflect.Method; -import java.util.Date; -import java.util.List; -import java.util.Map; - -import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State.Event; -import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineClusterVO; -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.org.Cluster.ClusterType; -import com.cloud.org.Grouping.AllocationState; -import com.cloud.org.Managed.ManagedState; -import com.cloud.utils.fsm.NoTransitionException; - - -public class ClusterEntityImpl implements ClusterEntity { - - - private DataCenterResourceManager manager; - - private EngineClusterVO clusterVO; - - - public ClusterEntityImpl(String clusterId, DataCenterResourceManager manager) { - this.manager = manager; - this.clusterVO = this.manager.loadCluster(clusterId); - } - - @Override - public boolean enable() { - try { - manager.changeState(this, Event.EnableRequest); - } catch (NoTransitionException e) { - return false; - } - return true; - } - - @Override - public boolean disable() { - try { - manager.changeState(this, Event.DisableRequest); - } catch (NoTransitionException e) { - return false; - } - return true; - } - - @Override - public boolean deactivate() { - try { - manager.changeState(this, Event.DeactivateRequest); - } catch (NoTransitionException e) { - return false; - } - return true; - } - - - @Override - public boolean reactivate() { - try { - manager.changeState(this, Event.ActivatedRequest); - } catch (NoTransitionException e) { - return false; - } - return true; - } - - - @Override - public State getState() { - return clusterVO.getState(); - } - - @Override - public void persist() { - manager.saveCluster(clusterVO); - } - - @Override - public String getUuid() { - return clusterVO.getUuid(); - } - - @Override - public long getId() { - return clusterVO.getId(); - } - - @Override - public String getCurrentState() { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getDesiredState() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Date getCreatedTime() { - return clusterVO.getCreated(); - } - - @Override - public Date getLastUpdatedTime() { - return clusterVO.getLastUpdated(); - } - - @Override - public String getOwner() { - return clusterVO.getOwner(); - } - - @Override - public Map getDetails() { - // TODO Auto-generated method stub - return null; - } - - @Override - public void addDetail(String name, String value) { - // TODO Auto-generated method stub - - } - - @Override - public void delDetail(String name, String value) { - // TODO Auto-generated method stub - - } - - @Override - public void updateDetail(String name, String value) { - // TODO Auto-generated method stub - - } - - @Override - public List getApplicableActions() { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getName() { - return clusterVO.getName(); - } - - @Override - public long getDataCenterId() { - return clusterVO.getDataCenterId(); - } - - @Override - public long getPodId() { - return clusterVO.getPodId(); - } - - @Override - public HypervisorType getHypervisorType() { - return clusterVO.getHypervisorType(); - } - - @Override - public ClusterType getClusterType() { - return clusterVO.getClusterType(); - } - - @Override - public AllocationState getAllocationState() { - return clusterVO.getAllocationState(); - } - - @Override - public ManagedState getManagedState() { - return clusterVO.getManagedState(); - } - - public void setOwner(String owner) { - clusterVO.setOwner(owner); - } - - public void setName(String name) { - clusterVO.setName(name); - } - -} + +package org.apache.cloudstack.engine.datacenter.entity.api; + +import java.lang.reflect.Method; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State.Event; +import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineClusterVO; +import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.org.Cluster.ClusterType; +import com.cloud.org.Grouping.AllocationState; +import com.cloud.org.Managed.ManagedState; +import com.cloud.utils.fsm.NoTransitionException; + + +public class ClusterEntityImpl implements ClusterEntity { + + + private DataCenterResourceManager manager; + + private EngineClusterVO clusterVO; + + + public ClusterEntityImpl(String clusterId, DataCenterResourceManager manager) { + this.manager = manager; + this.clusterVO = this.manager.loadCluster(clusterId); + } + + @Override + public boolean enable() { + try { + manager.changeState(this, Event.EnableRequest); + } catch (NoTransitionException e) { + return false; + } + return true; + } + + @Override + public boolean disable() { + try { + manager.changeState(this, Event.DisableRequest); + } catch (NoTransitionException e) { + return false; + } + return true; + } + + @Override + public boolean deactivate() { + try { + manager.changeState(this, Event.DeactivateRequest); + } catch (NoTransitionException e) { + return false; + } + return true; + } + + + @Override + public boolean reactivate() { + try { + manager.changeState(this, Event.ActivatedRequest); + } catch (NoTransitionException e) { + return false; + } + return true; + } + + + @Override + public State getState() { + return clusterVO.getState(); + } + + @Override + public void persist() { + manager.saveCluster(clusterVO); + } + + @Override + public String getUuid() { + return clusterVO.getUuid(); + } + + @Override + public long getId() { + return clusterVO.getId(); + } + + @Override + public String getCurrentState() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getDesiredState() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Date getCreatedTime() { + return clusterVO.getCreated(); + } + + @Override + public Date getLastUpdatedTime() { + return clusterVO.getLastUpdated(); + } + + @Override + public String getOwner() { + return clusterVO.getOwner(); + } + + @Override + public Map getDetails() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void addDetail(String name, String value) { + // TODO Auto-generated method stub + + } + + @Override + public void delDetail(String name, String value) { + // TODO Auto-generated method stub + + } + + @Override + public void updateDetail(String name, String value) { + // TODO Auto-generated method stub + + } + + @Override + public List getApplicableActions() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getName() { + return clusterVO.getName(); + } + + @Override + public long getDataCenterId() { + return clusterVO.getDataCenterId(); + } + + @Override + public long getPodId() { + return clusterVO.getPodId(); + } + + @Override + public HypervisorType getHypervisorType() { + return clusterVO.getHypervisorType(); + } + + @Override + public ClusterType getClusterType() { + return clusterVO.getClusterType(); + } + + @Override + public AllocationState getAllocationState() { + return clusterVO.getAllocationState(); + } + + @Override + public ManagedState getManagedState() { + return clusterVO.getManagedState(); + } + + public void setOwner(String owner) { + clusterVO.setOwner(owner); + } + + public void setName(String name) { + clusterVO.setName(name); + } + +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/DataCenterResourceManager.java b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/DataCenterResourceManager.java index ab1cbe6b0b1..a5f6d5e8108 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/DataCenterResourceManager.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/DataCenterResourceManager.java @@ -14,37 +14,37 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package org.apache.cloudstack.engine.datacenter.entity.api; - - -import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State.Event; -import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineClusterVO; -import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineDataCenterVO; -import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineHostPodVO; -import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineHostVO; - -import com.cloud.utils.fsm.NoTransitionException; - - - -public interface DataCenterResourceManager { - - EngineDataCenterVO loadDataCenter(String dataCenterId); - - void saveDataCenter(EngineDataCenterVO dc); - - void savePod(EngineHostPodVO dc); - - void saveCluster(EngineClusterVO cluster); - - boolean changeState(DataCenterResourceEntity entity, Event event) throws NoTransitionException; - - EngineHostPodVO loadPod(String uuid); - - EngineClusterVO loadCluster(String uuid); - - EngineHostVO loadHost(String uuid); - - void saveHost(EngineHostVO hostVO); - -} +package org.apache.cloudstack.engine.datacenter.entity.api; + + +import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State.Event; +import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineClusterVO; +import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineDataCenterVO; +import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineHostPodVO; +import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineHostVO; + +import com.cloud.utils.fsm.NoTransitionException; + + + +public interface DataCenterResourceManager { + + EngineDataCenterVO loadDataCenter(String dataCenterId); + + void saveDataCenter(EngineDataCenterVO dc); + + void savePod(EngineHostPodVO dc); + + void saveCluster(EngineClusterVO cluster); + + boolean changeState(DataCenterResourceEntity entity, Event event) throws NoTransitionException; + + EngineHostPodVO loadPod(String uuid); + + EngineClusterVO loadCluster(String uuid); + + EngineHostVO loadHost(String uuid); + + void saveHost(EngineHostVO hostVO); + +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/DataCenterResourceManagerImpl.java b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/DataCenterResourceManagerImpl.java index 3cfca3b9369..c267e5515f1 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/DataCenterResourceManagerImpl.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/DataCenterResourceManagerImpl.java @@ -14,116 +14,116 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package org.apache.cloudstack.engine.datacenter.entity.api; - -import javax.inject.Inject; - -import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State; -import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State.Event; -import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineClusterVO; -import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineDataCenterVO; -import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineHostPodVO; -import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineHostVO; -import org.apache.cloudstack.engine.datacenter.entity.api.db.dao.EngineClusterDao; -import org.apache.cloudstack.engine.datacenter.entity.api.db.dao.EngineDataCenterDao; -import org.apache.cloudstack.engine.datacenter.entity.api.db.dao.EngineHostDao; -import org.apache.cloudstack.engine.datacenter.entity.api.db.dao.EngineHostPodDao; -import org.springframework.stereotype.Component; - - -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.utils.fsm.NoTransitionException; -import com.cloud.utils.fsm.StateMachine2; - -@Component -public class DataCenterResourceManagerImpl implements DataCenterResourceManager { - - @Inject - EngineDataCenterDao _dataCenterDao; - - @Inject - EngineHostPodDao _podDao; - - @Inject - EngineClusterDao _clusterDao; - - @Inject - EngineHostDao _hostDao; - - - protected StateMachine2 _stateMachine = DataCenterResourceEntity.State.s_fsm; - - @Override - public EngineDataCenterVO loadDataCenter(String dataCenterId) { - EngineDataCenterVO dataCenterVO = _dataCenterDao.findByUuid(dataCenterId); - if(dataCenterVO == null){ - throw new InvalidParameterValueException("Zone does not exist"); - } - return dataCenterVO; - } - - @Override - public void saveDataCenter(EngineDataCenterVO dc) { - _dataCenterDao.persist(dc); - - } - - @Override - public boolean changeState(DataCenterResourceEntity entity, Event event) throws NoTransitionException { - - if(entity instanceof ZoneEntity){ - return _stateMachine.transitTo(entity, event, null, _dataCenterDao); - }else if(entity instanceof PodEntity){ - return _stateMachine.transitTo(entity, event, null, _podDao); - }else if(entity instanceof ClusterEntity){ - return _stateMachine.transitTo(entity, event, null, _clusterDao); - }else if(entity instanceof HostEntity){ - return _stateMachine.transitTo(entity, event, null, _hostDao); - } - - return false; - } - - @Override - public EngineHostPodVO loadPod(String uuid) { - EngineHostPodVO pod = _podDao.findByUuid(uuid); - if(pod == null){ - throw new InvalidParameterValueException("Pod does not exist"); - } - return pod; - } - - @Override - public EngineClusterVO loadCluster(String uuid) { - EngineClusterVO cluster = _clusterDao.findByUuid(uuid); - if(cluster == null){ - throw new InvalidParameterValueException("Pod does not exist"); - } - return cluster; - } - - @Override - public void savePod(EngineHostPodVO pod) { - _podDao.persist(pod); - } - - @Override - public void saveCluster(EngineClusterVO cluster) { - _clusterDao.persist(cluster); - } - - @Override - public EngineHostVO loadHost(String uuid) { - EngineHostVO host = _hostDao.findByUuid(uuid); - if(host == null){ - throw new InvalidParameterValueException("Host does not exist"); - } - return host; - } - - @Override - public void saveHost(EngineHostVO hostVO) { - _hostDao.persist(hostVO); - } - -} +package org.apache.cloudstack.engine.datacenter.entity.api; + +import javax.inject.Inject; + +import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State; +import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State.Event; +import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineClusterVO; +import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineDataCenterVO; +import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineHostPodVO; +import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineHostVO; +import org.apache.cloudstack.engine.datacenter.entity.api.db.dao.EngineClusterDao; +import org.apache.cloudstack.engine.datacenter.entity.api.db.dao.EngineDataCenterDao; +import org.apache.cloudstack.engine.datacenter.entity.api.db.dao.EngineHostDao; +import org.apache.cloudstack.engine.datacenter.entity.api.db.dao.EngineHostPodDao; +import org.springframework.stereotype.Component; + + +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.utils.fsm.NoTransitionException; +import com.cloud.utils.fsm.StateMachine2; + +@Component +public class DataCenterResourceManagerImpl implements DataCenterResourceManager { + + @Inject + EngineDataCenterDao _dataCenterDao; + + @Inject + EngineHostPodDao _podDao; + + @Inject + EngineClusterDao _clusterDao; + + @Inject + EngineHostDao _hostDao; + + + protected StateMachine2 _stateMachine = DataCenterResourceEntity.State.s_fsm; + + @Override + public EngineDataCenterVO loadDataCenter(String dataCenterId) { + EngineDataCenterVO dataCenterVO = _dataCenterDao.findByUuid(dataCenterId); + if(dataCenterVO == null){ + throw new InvalidParameterValueException("Zone does not exist"); + } + return dataCenterVO; + } + + @Override + public void saveDataCenter(EngineDataCenterVO dc) { + _dataCenterDao.persist(dc); + + } + + @Override + public boolean changeState(DataCenterResourceEntity entity, Event event) throws NoTransitionException { + + if(entity instanceof ZoneEntity){ + return _stateMachine.transitTo(entity, event, null, _dataCenterDao); + }else if(entity instanceof PodEntity){ + return _stateMachine.transitTo(entity, event, null, _podDao); + }else if(entity instanceof ClusterEntity){ + return _stateMachine.transitTo(entity, event, null, _clusterDao); + }else if(entity instanceof HostEntity){ + return _stateMachine.transitTo(entity, event, null, _hostDao); + } + + return false; + } + + @Override + public EngineHostPodVO loadPod(String uuid) { + EngineHostPodVO pod = _podDao.findByUuid(uuid); + if(pod == null){ + throw new InvalidParameterValueException("Pod does not exist"); + } + return pod; + } + + @Override + public EngineClusterVO loadCluster(String uuid) { + EngineClusterVO cluster = _clusterDao.findByUuid(uuid); + if(cluster == null){ + throw new InvalidParameterValueException("Pod does not exist"); + } + return cluster; + } + + @Override + public void savePod(EngineHostPodVO pod) { + _podDao.persist(pod); + } + + @Override + public void saveCluster(EngineClusterVO cluster) { + _clusterDao.persist(cluster); + } + + @Override + public EngineHostVO loadHost(String uuid) { + EngineHostVO host = _hostDao.findByUuid(uuid); + if(host == null){ + throw new InvalidParameterValueException("Host does not exist"); + } + return host; + } + + @Override + public void saveHost(EngineHostVO hostVO) { + _hostDao.persist(hostVO); + } + +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/HostEntityImpl.java b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/HostEntityImpl.java index b4a20801a79..17114e7ce07 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/HostEntityImpl.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/HostEntityImpl.java @@ -14,202 +14,202 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package org.apache.cloudstack.engine.datacenter.entity.api; - -import java.lang.reflect.Method; -import java.util.Date; -import java.util.List; -import java.util.Map; - -import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State.Event; -import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineHostVO; - -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.utils.fsm.NoTransitionException; - -public class HostEntityImpl implements HostEntity { - - private DataCenterResourceManager manager; - - private EngineHostVO hostVO; - - public HostEntityImpl(String uuid, DataCenterResourceManager manager) { - this.manager = manager; - hostVO = manager.loadHost(uuid); - } - - @Override - public boolean enable() { - try { - manager.changeState(this, Event.EnableRequest); - } catch (NoTransitionException e) { - return false; - } - return true; - } - - @Override - public boolean disable() { - try { - manager.changeState(this, Event.DisableRequest); - } catch (NoTransitionException e) { - return false; - } - return true; - } - - @Override - public boolean deactivate() { - try { - manager.changeState(this, Event.DeactivateRequest); - } catch (NoTransitionException e) { - return false; - } - return true; - } - - @Override - public boolean reactivate() { - try { - manager.changeState(this, Event.ActivatedRequest); - } catch (NoTransitionException e) { - return false; - } - return true; - } - - @Override - public State getState() { - return hostVO.getOrchestrationState(); - } - - @Override - public void persist() { - manager.saveHost(hostVO); - } - - @Override - public String getName() { - return hostVO.getName(); - } - - @Override - public String getUuid() { - return hostVO.getUuid(); - } - - @Override - public long getId() { - return hostVO.getId(); - } - - @Override - public String getCurrentState() { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getDesiredState() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Date getCreatedTime() { - return hostVO.getCreated(); - } - - @Override - public Date getLastUpdatedTime() { - return hostVO.getLastUpdated(); - } - - @Override - public String getOwner() { - // TODO Auto-generated method stub - return hostVO.getOwner(); - } - - - public void setDetails(Map details) { - hostVO.setDetails(details); - } - - @Override - public Map getDetails() { - return hostVO.getDetails(); - } - - @Override - public void addDetail(String name, String value) { - hostVO.setDetail(name, value); - } - - @Override - public void delDetail(String name, String value) { - // TODO Auto-generated method stub - } - - @Override - public void updateDetail(String name, String value) { - // TODO Auto-generated method stub - - } - - @Override - public List getApplicableActions() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Long getTotalMemory() { - return hostVO.getTotalMemory(); - } - - @Override - public Integer getCpus() { - return hostVO.getCpus(); - } - - @Override - public Long getSpeed() { - return hostVO.getSpeed(); - } - - @Override - public Long getPodId() { - return hostVO.getPodId(); - } - - @Override - public long getDataCenterId() { - return hostVO.getDataCenterId(); - } - - @Override - public HypervisorType getHypervisorType() { - return hostVO.getHypervisorType(); - } - - @Override - public String getGuid() { - return hostVO.getGuid(); - } - - @Override - public Long getClusterId() { - return hostVO.getClusterId(); - } - - public void setOwner(String owner) { - hostVO.setOwner(owner); - } - - public void setName(String name) { - hostVO.setName(name); - } - - -} +package org.apache.cloudstack.engine.datacenter.entity.api; + +import java.lang.reflect.Method; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State.Event; +import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineHostVO; + +import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.utils.fsm.NoTransitionException; + +public class HostEntityImpl implements HostEntity { + + private DataCenterResourceManager manager; + + private EngineHostVO hostVO; + + public HostEntityImpl(String uuid, DataCenterResourceManager manager) { + this.manager = manager; + hostVO = manager.loadHost(uuid); + } + + @Override + public boolean enable() { + try { + manager.changeState(this, Event.EnableRequest); + } catch (NoTransitionException e) { + return false; + } + return true; + } + + @Override + public boolean disable() { + try { + manager.changeState(this, Event.DisableRequest); + } catch (NoTransitionException e) { + return false; + } + return true; + } + + @Override + public boolean deactivate() { + try { + manager.changeState(this, Event.DeactivateRequest); + } catch (NoTransitionException e) { + return false; + } + return true; + } + + @Override + public boolean reactivate() { + try { + manager.changeState(this, Event.ActivatedRequest); + } catch (NoTransitionException e) { + return false; + } + return true; + } + + @Override + public State getState() { + return hostVO.getOrchestrationState(); + } + + @Override + public void persist() { + manager.saveHost(hostVO); + } + + @Override + public String getName() { + return hostVO.getName(); + } + + @Override + public String getUuid() { + return hostVO.getUuid(); + } + + @Override + public long getId() { + return hostVO.getId(); + } + + @Override + public String getCurrentState() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getDesiredState() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Date getCreatedTime() { + return hostVO.getCreated(); + } + + @Override + public Date getLastUpdatedTime() { + return hostVO.getLastUpdated(); + } + + @Override + public String getOwner() { + // TODO Auto-generated method stub + return hostVO.getOwner(); + } + + + public void setDetails(Map details) { + hostVO.setDetails(details); + } + + @Override + public Map getDetails() { + return hostVO.getDetails(); + } + + @Override + public void addDetail(String name, String value) { + hostVO.setDetail(name, value); + } + + @Override + public void delDetail(String name, String value) { + // TODO Auto-generated method stub + } + + @Override + public void updateDetail(String name, String value) { + // TODO Auto-generated method stub + + } + + @Override + public List getApplicableActions() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long getTotalMemory() { + return hostVO.getTotalMemory(); + } + + @Override + public Integer getCpus() { + return hostVO.getCpus(); + } + + @Override + public Long getSpeed() { + return hostVO.getSpeed(); + } + + @Override + public Long getPodId() { + return hostVO.getPodId(); + } + + @Override + public long getDataCenterId() { + return hostVO.getDataCenterId(); + } + + @Override + public HypervisorType getHypervisorType() { + return hostVO.getHypervisorType(); + } + + @Override + public String getGuid() { + return hostVO.getGuid(); + } + + @Override + public Long getClusterId() { + return hostVO.getClusterId(); + } + + public void setOwner(String owner) { + hostVO.setOwner(owner); + } + + public void setName(String name) { + hostVO.setName(name); + } + + +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/PodEntityImpl.java b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/PodEntityImpl.java index 5c66a21a73e..758a99751ad 100755 --- a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/PodEntityImpl.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/PodEntityImpl.java @@ -1,211 +1,211 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.datacenter.entity.api; - -import java.lang.reflect.Method; -import java.util.Date; -import java.util.List; -import java.util.Map; - -import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State.Event; -import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineHostPodVO; - -import com.cloud.org.Cluster; -import com.cloud.org.Grouping.AllocationState; -import com.cloud.utils.fsm.NoTransitionException; - -public class PodEntityImpl implements PodEntity { - - - private DataCenterResourceManager manager; - - private EngineHostPodVO podVO; - - public PodEntityImpl(String uuid, DataCenterResourceManager manager) { - this.manager = manager; - podVO = manager.loadPod(uuid); - } - - @Override - public boolean enable() { - try { - manager.changeState(this, Event.EnableRequest); - } catch (NoTransitionException e) { - return false; - } - return true; - } - - @Override - public boolean disable() { - try { - manager.changeState(this, Event.DisableRequest); - } catch (NoTransitionException e) { - return false; - } - return true; - } - - @Override - public boolean deactivate() { - try { - manager.changeState(this, Event.DeactivateRequest); - } catch (NoTransitionException e) { - return false; - } - return true; - } - - @Override - public boolean reactivate() { - try { - manager.changeState(this, Event.ActivatedRequest); - } catch (NoTransitionException e) { - return false; - } - return true; - } - - @Override - public State getState() { - return podVO.getState(); - } - - @Override - public String getUuid() { - return podVO.getUuid(); - } - - @Override - public long getId() { - return podVO.getId(); - } - - @Override - public String getCurrentState() { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getDesiredState() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Date getCreatedTime() { - return podVO.getCreated(); - } - - @Override - public Date getLastUpdatedTime() { - return podVO.getLastUpdated(); - } - - @Override - public String getOwner() { - return podVO.getOwner(); - } - - - @Override - public List getApplicableActions() { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getCidrAddress() { - return podVO.getCidrAddress(); - } - - @Override - public int getCidrSize() { - return podVO.getCidrSize(); - } - - @Override - public String getGateway() { - return podVO.getGateway(); - } - - @Override - public long getDataCenterId() { - return podVO.getDataCenterId(); - } - - @Override - public String getName() { - return podVO.getName(); - } - - @Override - public AllocationState getAllocationState() { - return podVO.getAllocationState(); - } - - @Override - public boolean getExternalDhcp() { - return podVO.getExternalDhcp(); - } - - @Override - public List listClusters() { - // TODO Auto-generated method stub - return null; - } - - @Override - public void persist() { - manager.savePod(podVO); - - } - - @Override - public Map getDetails() { - return null; - } - - @Override - public void addDetail(String name, String value) { - // TODO Auto-generated method stub - - } - - @Override - public void delDetail(String name, String value) { - // TODO Auto-generated method stub - - } - - @Override - public void updateDetail(String name, String value) { - - } - - public void setOwner(String owner) { - podVO.setOwner(owner); - } - - public void setName(String name) { - podVO.setName(name); - } - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.datacenter.entity.api; + +import java.lang.reflect.Method; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State.Event; +import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineHostPodVO; + +import com.cloud.org.Cluster; +import com.cloud.org.Grouping.AllocationState; +import com.cloud.utils.fsm.NoTransitionException; + +public class PodEntityImpl implements PodEntity { + + + private DataCenterResourceManager manager; + + private EngineHostPodVO podVO; + + public PodEntityImpl(String uuid, DataCenterResourceManager manager) { + this.manager = manager; + podVO = manager.loadPod(uuid); + } + + @Override + public boolean enable() { + try { + manager.changeState(this, Event.EnableRequest); + } catch (NoTransitionException e) { + return false; + } + return true; + } + + @Override + public boolean disable() { + try { + manager.changeState(this, Event.DisableRequest); + } catch (NoTransitionException e) { + return false; + } + return true; + } + + @Override + public boolean deactivate() { + try { + manager.changeState(this, Event.DeactivateRequest); + } catch (NoTransitionException e) { + return false; + } + return true; + } + + @Override + public boolean reactivate() { + try { + manager.changeState(this, Event.ActivatedRequest); + } catch (NoTransitionException e) { + return false; + } + return true; + } + + @Override + public State getState() { + return podVO.getState(); + } + + @Override + public String getUuid() { + return podVO.getUuid(); + } + + @Override + public long getId() { + return podVO.getId(); + } + + @Override + public String getCurrentState() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getDesiredState() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Date getCreatedTime() { + return podVO.getCreated(); + } + + @Override + public Date getLastUpdatedTime() { + return podVO.getLastUpdated(); + } + + @Override + public String getOwner() { + return podVO.getOwner(); + } + + + @Override + public List getApplicableActions() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getCidrAddress() { + return podVO.getCidrAddress(); + } + + @Override + public int getCidrSize() { + return podVO.getCidrSize(); + } + + @Override + public String getGateway() { + return podVO.getGateway(); + } + + @Override + public long getDataCenterId() { + return podVO.getDataCenterId(); + } + + @Override + public String getName() { + return podVO.getName(); + } + + @Override + public AllocationState getAllocationState() { + return podVO.getAllocationState(); + } + + @Override + public boolean getExternalDhcp() { + return podVO.getExternalDhcp(); + } + + @Override + public List listClusters() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void persist() { + manager.savePod(podVO); + + } + + @Override + public Map getDetails() { + return null; + } + + @Override + public void addDetail(String name, String value) { + // TODO Auto-generated method stub + + } + + @Override + public void delDetail(String name, String value) { + // TODO Auto-generated method stub + + } + + @Override + public void updateDetail(String name, String value) { + + } + + public void setOwner(String owner) { + podVO.setOwner(owner); + } + + public void setName(String name) { + podVO.setName(name); + } + +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/ZoneEntityImpl.java b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/ZoneEntityImpl.java index 333a2207d66..e2548803d61 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/ZoneEntityImpl.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/ZoneEntityImpl.java @@ -1,201 +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 org.apache.cloudstack.engine.datacenter.entity.api; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State.Event; -import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineDataCenterVO; -import com.cloud.utils.fsm.FiniteStateObject; -import com.cloud.utils.fsm.NoTransitionException; - - -@Path("/zone/{id}") -public class ZoneEntityImpl implements ZoneEntity, FiniteStateObject { - - - private DataCenterResourceManager manager; - - private EngineDataCenterVO dataCenterVO; - - - public ZoneEntityImpl(String dataCenterId, DataCenterResourceManager manager) { - this.manager = manager; - this.dataCenterVO = this.manager.loadDataCenter(dataCenterId); - } - - @Override - @GET - public String getUuid() { - return dataCenterVO.getUuid(); - } - - @Override - public long getId() { - return dataCenterVO.getId(); - } - - @Override - public boolean enable() { - try { - manager.changeState(this, Event.EnableRequest); - } catch (NoTransitionException e) { - return false; - } - return true; - } - - @Override - public boolean disable() { - try { - manager.changeState(this, Event.DisableRequest); - } catch (NoTransitionException e) { - return false; - } - return true; - } - - @Override - public boolean deactivate() { - try { - manager.changeState(this, Event.DeactivateRequest); - } catch (NoTransitionException e) { - return false; - } - return true; - } - - @Override - public boolean reactivate() { - try { - manager.changeState(this, Event.ActivatedRequest); - } catch (NoTransitionException e) { - return false; - } - return true; - } - - @Override - public String getCurrentState() { - // TODO Auto-generated method stub - return "state"; - } - - @Override - public String getDesiredState() { - // TODO Auto-generated method stub - return "desired_state"; - } - - @Override - public Date getCreatedTime() { - return dataCenterVO.getCreated(); - } - - @Override - public Date getLastUpdatedTime() { - return dataCenterVO.getLastUpdated(); - } - - @Override - public String getOwner() { - return dataCenterVO.getOwner(); - } - - - public void setOwner(String owner) { - dataCenterVO.setOwner(owner); - } - - @Override - public Map getDetails() { - return dataCenterVO.getDetails(); - } - - public void setDetails(Map details) { - dataCenterVO.setDetails(details); - } - - - @Override - public void addDetail(String name, String value) { - dataCenterVO.setDetail(name, value); - } - - @Override - public void delDetail(String name, String value) { - // TODO Auto-generated method stub - } - - @Override - public void updateDetail(String name, String value) { - // TODO Auto-generated method stub - - } - - @Override - public List getApplicableActions() { - // TODO Auto-generated method stub - return null; - } - - @Override - public State getState() { - return dataCenterVO.getState(); - } - - - @Override - public List listPods() { - // TODO Auto-generated method stub - return null; - } - - @Override - public void setState(State state) { - //use FSM to set state. - } - - @Override - public void persist() { - manager.saveDataCenter(dataCenterVO); - } - - @Override - public String getName() { - return dataCenterVO.getName(); - } - - @Override - public List listPodIds() { - List podIds = new ArrayList(); - podIds.add("pod-uuid-1"); - podIds.add("pod-uuid-2"); - return podIds; - } - - public void setName(String name) { - dataCenterVO.setName(name); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.datacenter.entity.api; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State.Event; +import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineDataCenterVO; +import com.cloud.utils.fsm.FiniteStateObject; +import com.cloud.utils.fsm.NoTransitionException; + + +@Path("/zone/{id}") +public class ZoneEntityImpl implements ZoneEntity, FiniteStateObject { + + + private DataCenterResourceManager manager; + + private EngineDataCenterVO dataCenterVO; + + + public ZoneEntityImpl(String dataCenterId, DataCenterResourceManager manager) { + this.manager = manager; + this.dataCenterVO = this.manager.loadDataCenter(dataCenterId); + } + + @Override + @GET + public String getUuid() { + return dataCenterVO.getUuid(); + } + + @Override + public long getId() { + return dataCenterVO.getId(); + } + + @Override + public boolean enable() { + try { + manager.changeState(this, Event.EnableRequest); + } catch (NoTransitionException e) { + return false; + } + return true; + } + + @Override + public boolean disable() { + try { + manager.changeState(this, Event.DisableRequest); + } catch (NoTransitionException e) { + return false; + } + return true; + } + + @Override + public boolean deactivate() { + try { + manager.changeState(this, Event.DeactivateRequest); + } catch (NoTransitionException e) { + return false; + } + return true; + } + + @Override + public boolean reactivate() { + try { + manager.changeState(this, Event.ActivatedRequest); + } catch (NoTransitionException e) { + return false; + } + return true; + } + + @Override + public String getCurrentState() { + // TODO Auto-generated method stub + return "state"; + } + + @Override + public String getDesiredState() { + // TODO Auto-generated method stub + return "desired_state"; + } + + @Override + public Date getCreatedTime() { + return dataCenterVO.getCreated(); + } + + @Override + public Date getLastUpdatedTime() { + return dataCenterVO.getLastUpdated(); + } + + @Override + public String getOwner() { + return dataCenterVO.getOwner(); + } + + + public void setOwner(String owner) { + dataCenterVO.setOwner(owner); + } + + @Override + public Map getDetails() { + return dataCenterVO.getDetails(); + } + + public void setDetails(Map details) { + dataCenterVO.setDetails(details); + } + + + @Override + public void addDetail(String name, String value) { + dataCenterVO.setDetail(name, value); + } + + @Override + public void delDetail(String name, String value) { + // TODO Auto-generated method stub + } + + @Override + public void updateDetail(String name, String value) { + // TODO Auto-generated method stub + + } + + @Override + public List getApplicableActions() { + // TODO Auto-generated method stub + return null; + } + + @Override + public State getState() { + return dataCenterVO.getState(); + } + + + @Override + public List listPods() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setState(State state) { + //use FSM to set state. + } + + @Override + public void persist() { + manager.saveDataCenter(dataCenterVO); + } + + @Override + public String getName() { + return dataCenterVO.getName(); + } + + @Override + public List listPodIds() { + List podIds = new ArrayList(); + podIds.add("pod-uuid-1"); + podIds.add("pod-uuid-2"); + return podIds; + } + + public void setName(String name) { + dataCenterVO.setName(name); + } +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/EngineCluster.java b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/EngineCluster.java index c4f1940c119..98b7a991a3f 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/EngineCluster.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/EngineCluster.java @@ -1,23 +1,23 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES 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.datacenter.entity.api.db; - -import com.cloud.org.Cluster; - -public interface EngineCluster extends Cluster { - -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES 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.datacenter.entity.api.db; + +import com.cloud.org.Cluster; + +public interface EngineCluster extends Cluster { + +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/EngineDataCenter.java b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/EngineDataCenter.java index 24e01a0b0af..240dddf1529 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/EngineDataCenter.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/EngineDataCenter.java @@ -1,23 +1,23 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES 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.datacenter.entity.api.db; - -import com.cloud.dc.DataCenter; - -public interface EngineDataCenter extends DataCenter { - -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES 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.datacenter.entity.api.db; + +import com.cloud.dc.DataCenter; + +public interface EngineDataCenter extends DataCenter { + +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/EngineDataCenterVO.java b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/EngineDataCenterVO.java index 15bed6f8c1d..cdf08cc5b9c 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/EngineDataCenterVO.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/EngineDataCenterVO.java @@ -8,10 +8,10 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// +// // Automatically generated by addcopyright.py at 04/03/2012 -package org.apache.cloudstack.engine.datacenter.entity.api.db; - +package org.apache.cloudstack.engine.datacenter.entity.api.db; + import java.util.Date; import java.util.Map; import java.util.UUID; @@ -39,43 +39,43 @@ import com.cloud.org.Grouping; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.StateMachine; - -@Entity -@Table(name="data_center") -public class EngineDataCenterVO implements EngineDataCenter, Identity { - - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - private long id; - - @Column(name="name") - private String name = null; - - @Column(name="description") - private String description = null; - - @Column(name="dns1") - private String dns1 = null; - - @Column(name="dns2") - private String dns2 = null; - - @Column(name="ip6Dns1") - private String ip6Dns1 = null; - - @Column(name="ip6Dns2") - private String ip6Dns2 = null; - - @Column(name="internal_dns1") - private String internalDns1 = null; - - @Column(name="internal_dns2") - private String internalDns2 = null; - - @Column(name="router_mac_address", updatable = false, nullable=false) - private String routerMacAddress = "02:00:00:00:00:01"; - + +@Entity +@Table(name="data_center") +public class EngineDataCenterVO implements EngineDataCenter, Identity { + + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + private long id; + + @Column(name="name") + private String name = null; + + @Column(name="description") + private String description = null; + + @Column(name="dns1") + private String dns1 = null; + + @Column(name="dns2") + private String dns2 = null; + + @Column(name="ip6Dns1") + private String ip6Dns1 = null; + + @Column(name="ip6Dns2") + private String ip6Dns2 = null; + + @Column(name="internal_dns1") + private String internalDns1 = null; + + @Column(name="internal_dns2") + private String internalDns2 = null; + + @Column(name="router_mac_address", updatable = false, nullable=false) + private String routerMacAddress = "02:00:00:00:00:01"; + @Column(name="guest_network_cidr") private String guestNetworkCidr = null; @@ -207,13 +207,13 @@ public class EngineDataCenterVO implements EngineDataCenter, Identity { } public EngineDataCenterVO(long id, String name, String description, String dns1, String dns2, String dns3, String dns4, String guestCidr, String domain, Long domainId, NetworkType zoneType, String zoneToken, String domainSuffix) { - this(name, description, dns1, dns2, dns3, dns4, guestCidr, domain, domainId, zoneType, zoneToken, domainSuffix, false, false, null, null); + this(name, description, dns1, dns2, dns3, dns4, guestCidr, domain, domainId, zoneType, zoneToken, domainSuffix, false, false, null, null); this.id = id; this.allocationState = Grouping.AllocationState.Enabled; - this.uuid = UUID.randomUUID().toString(); - } - - public EngineDataCenterVO(String name, String description, String dns1, String dns2, String dns3, String dns4, String guestCidr, String domain, Long domainId, NetworkType zoneType, String zoneToken, String domainSuffix, boolean securityGroupEnabled, boolean localStorageEnabled, String ip6Dns1, String ip6Dns2) { + this.uuid = UUID.randomUUID().toString(); + } + + public EngineDataCenterVO(String name, String description, String dns1, String dns2, String dns3, String dns4, String guestCidr, String domain, Long domainId, NetworkType zoneType, String zoneToken, String domainSuffix, boolean securityGroupEnabled, boolean localStorageEnabled, String ip6Dns1, String ip6Dns2) { this.name = name; this.description = description; this.dns1 = dns1; @@ -285,72 +285,72 @@ public class EngineDataCenterVO implements EngineDataCenter, Identity { public void setDomainId(Long domainId) { this.domainId = domainId; - } - + } + @Override - public String getDescription() { - return description; - } - - public String getRouterMacAddress() { - return routerMacAddress; - } - + public String getDescription() { + return description; + } + + public String getRouterMacAddress() { + return routerMacAddress; + } + @Override - public String getDns1() { - return dns1; - } - + public String getDns1() { + return dns1; + } + @Override - public String getDns2() { - return dns2; - } - + public String getDns2() { + return dns2; + } + @Override - public String getInternalDns1() { - return internalDns1; - } - + public String getInternalDns1() { + return internalDns1; + } + @Override - public String getInternalDns2() { - return internalDns2; - } - - protected EngineDataCenterVO() { - } - + public String getInternalDns2() { + return internalDns2; + } + + protected EngineDataCenterVO() { + } + @Override - public long getId() { - return id; - } - + public long getId() { + return id; + } + @Override - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public void setDns1(String dns1) { - this.dns1 = dns1; - } - - public void setDns2(String dns2) { - this.dns2 = dns2; - } - - public void setInternalDns1(String dns3) { - this.internalDns1 = dns3; - } - - public void setInternalDns2(String dns4) { - this.internalDns2 = dns4; - } - - public void setRouterMacAddress(String routerMacAddress) { - this.routerMacAddress = routerMacAddress; + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public void setDns1(String dns1) { + this.dns1 = dns1; + } + + public void setDns2(String dns2) { + this.dns2 = dns2; + } + + public void setInternalDns1(String dns3) { + this.internalDns1 = dns3; + } + + public void setInternalDns2(String dns4) { + this.internalDns2 = dns4; + } + + public void setRouterMacAddress(String routerMacAddress) { + this.routerMacAddress = routerMacAddress; } @Override @@ -501,4 +501,4 @@ public class EngineDataCenterVO implements EngineDataCenter, Identity { public void setIp6Dns2(String ip6Dns2) { this.ip6Dns2 = ip6Dns2; } -} +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/EngineHost.java b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/EngineHost.java index fe1b832633e..127c4457071 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/EngineHost.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/EngineHost.java @@ -1,24 +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 org.apache.cloudstack.engine.datacenter.entity.api.db; - -import com.cloud.host.Host; - -public interface EngineHost extends Host { - -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES 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.datacenter.entity.api.db; + +import com.cloud.host.Host; + +public interface EngineHost extends Host { + +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/EngineHostPodVO.java b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/EngineHostPodVO.java index 99c95406f9e..65b9db53e93 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/EngineHostPodVO.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/EngineHostPodVO.java @@ -8,10 +8,10 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// +// // Automatically generated by addcopyright.py at 04/03/2012 -package org.apache.cloudstack.engine.datacenter.entity.api.db; - +package org.apache.cloudstack.engine.datacenter.entity.api.db; + import java.util.Date; import java.util.UUID; @@ -34,42 +34,42 @@ import com.cloud.org.Grouping; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.StateMachine; - -@Entity -@Table(name = "host_pod_ref") -public class EngineHostPodVO implements EnginePod, Identity { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - long id; - - @Column(name = "name") - private String name = null; - - @Column(name = "data_center_id") + +@Entity +@Table(name = "host_pod_ref") +public class EngineHostPodVO implements EnginePod, Identity { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + long id; + + @Column(name = "name") + private String name = null; + + @Column(name = "data_center_id") private long dataCenterId; @Column(name = "gateway") - private String gateway; - - @Column(name = "cidr_address") - private String cidrAddress; - - @Column(name = "cidr_size") - private int cidrSize; - - @Column(name = "description") + private String gateway; + + @Column(name = "cidr_address") + private String cidrAddress; + + @Column(name = "cidr_size") + private int cidrSize; + + @Column(name = "description") private String description; @Column(name="allocation_state") @Enumerated(value=EnumType.STRING) - AllocationState allocationState; + AllocationState allocationState; @Column(name = "external_dhcp") private Boolean externalDhcp; @Column(name=GenericDao.REMOVED_COLUMN) private Date removed; - + @Column(name = "uuid") private String uuid; @@ -93,66 +93,66 @@ public class EngineHostPodVO implements EnginePod, Identity { @StateMachine(state=State.class, event=Event.class) @Column(name="engine_state", updatable=true, nullable=false, length=32) protected State engineState = null; - - public EngineHostPodVO(String name, long dcId, String gateway, String cidrAddress, int cidrSize, String description) { - this.name = name; + + public EngineHostPodVO(String name, long dcId, String gateway, String cidrAddress, int cidrSize, String description) { + this.name = name; this.dataCenterId = dcId; - this.gateway = gateway; - this.cidrAddress = cidrAddress; - this.cidrSize = cidrSize; + this.gateway = gateway; + this.cidrAddress = cidrAddress; + this.cidrSize = cidrSize; this.description = description; this.allocationState = Grouping.AllocationState.Enabled; this.externalDhcp = false; this.uuid = UUID.randomUUID().toString(); - this.engineState = State.Disabled; - } - - /* - * public HostPodVO(String name, long dcId) { this(null, name, dcId); } - */ - protected EngineHostPodVO() { + this.engineState = State.Disabled; + } + + /* + * public HostPodVO(String name, long dcId) { this(null, name, dcId); } + */ + protected EngineHostPodVO() { this.uuid = UUID.randomUUID().toString(); - } - + } + @Override - public long getId() { - return id; - } - + public long getId() { + return id; + } + @Override - public long getDataCenterId() { - return dataCenterId; - } - - public void setDataCenterId(long dataCenterId) { - this.dataCenterId = dataCenterId; - } - + public long getDataCenterId() { + return dataCenterId; + } + + public void setDataCenterId(long dataCenterId) { + this.dataCenterId = dataCenterId; + } + @Override - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + @Override - public String getCidrAddress() { - return cidrAddress; - } - - public void setCidrAddress(String cidrAddress) { - this.cidrAddress = cidrAddress; - } - + public String getCidrAddress() { + return cidrAddress; + } + + public void setCidrAddress(String cidrAddress) { + this.cidrAddress = cidrAddress; + } + @Override - public int getCidrSize() { - return cidrSize; - } - - public void setCidrSize(int cidrSize) { - this.cidrSize = cidrSize; + public int getCidrSize() { + return cidrSize; + } + + public void setCidrSize(int cidrSize) { + this.cidrSize = cidrSize; } @Override @@ -162,15 +162,15 @@ public class EngineHostPodVO implements EnginePod, Identity { public void setGateway(String gateway) { this.gateway = gateway; - } - + } + @Override - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; } @Override @@ -241,5 +241,5 @@ public class EngineHostPodVO implements EnginePod, Identity { public State getState() { return engineState; - } -} + } +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/EnginePod.java b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/EnginePod.java index 3983dd90420..2adbca36af5 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/EnginePod.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/EnginePod.java @@ -1,23 +1,23 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES 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.datacenter.entity.api.db; - -import com.cloud.dc.Pod; - -public interface EnginePod extends Pod { - -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES 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.datacenter.entity.api.db; + +import com.cloud.dc.Pod; + +public interface EnginePod extends Pod { + +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/dao/EngineHostDao.java b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/dao/EngineHostDao.java index a27ed505289..3a71fe2cf9f 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/dao/EngineHostDao.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/dao/EngineHostDao.java @@ -82,4 +82,4 @@ public interface EngineHostDao extends GenericDao, StateDao< * @return */ List listAllUpAndEnabledNonHAHosts(Type type, Long clusterId, Long podId, long dcId, String haTag); -} +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/dao/EngineHostPodDao.java b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/dao/EngineHostPodDao.java index 48e77739085..451723e5370 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/dao/EngineHostPodDao.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/dao/EngineHostPodDao.java @@ -8,10 +8,10 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// +// // Automatically generated by addcopyright.py at 04/03/2012 -package org.apache.cloudstack.engine.datacenter.entity.api.db.dao; - +package org.apache.cloudstack.engine.datacenter.entity.api.db.dao; + import java.util.HashMap; import java.util.List; @@ -21,13 +21,13 @@ import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineHostPodVO; import com.cloud.utils.db.GenericDao; import com.cloud.utils.fsm.StateDao; - -public interface EngineHostPodDao extends GenericDao, StateDao { - public List listByDataCenterId(long id); - - public EngineHostPodVO findByName(String name, long dcId); - + +public interface EngineHostPodDao extends GenericDao, StateDao { + public List listByDataCenterId(long id); + + public EngineHostPodVO findByName(String name, long dcId); + public HashMap> getCurrentPodCidrSubnets(long zoneId, long podIdToSkip); public List listDisabledPods(long zoneId); -} +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/dao/EngineHostPodDaoImpl.java b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/dao/EngineHostPodDaoImpl.java index c5b4bd28de4..fee083a39a0 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/dao/EngineHostPodDaoImpl.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/datacenter/entity/api/db/dao/EngineHostPodDaoImpl.java @@ -8,10 +8,10 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// +// // Automatically generated by addcopyright.py at 04/03/2012 -package org.apache.cloudstack.engine.datacenter.entity.api.db.dao; - +package org.apache.cloudstack.engine.datacenter.entity.api.db.dao; + import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -39,27 +39,27 @@ import com.cloud.utils.db.UpdateBuilder; import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.Transaction; -@Component(value="EngineHostPodDao") -@Local(value={EngineHostPodDao.class}) -public class EngineHostPodDaoImpl extends GenericDaoBase implements EngineHostPodDao { - private static final Logger s_logger = Logger.getLogger(EngineHostPodDaoImpl.class); - - protected SearchBuilder DataCenterAndNameSearch; +@Component(value="EngineHostPodDao") +@Local(value={EngineHostPodDao.class}) +public class EngineHostPodDaoImpl extends GenericDaoBase implements EngineHostPodDao { + private static final Logger s_logger = Logger.getLogger(EngineHostPodDaoImpl.class); + + protected SearchBuilder DataCenterAndNameSearch; protected SearchBuilder DataCenterIdSearch; protected SearchBuilder UUIDSearch; - protected SearchBuilder StateChangeSearch; - - protected EngineHostPodDaoImpl() { - DataCenterAndNameSearch = createSearchBuilder(); - DataCenterAndNameSearch.and("dc", DataCenterAndNameSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); - DataCenterAndNameSearch.and("name", DataCenterAndNameSearch.entity().getName(), SearchCriteria.Op.EQ); - DataCenterAndNameSearch.done(); - - DataCenterIdSearch = createSearchBuilder(); - DataCenterIdSearch.and("dcId", DataCenterIdSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); + protected SearchBuilder StateChangeSearch; + + protected EngineHostPodDaoImpl() { + DataCenterAndNameSearch = createSearchBuilder(); + DataCenterAndNameSearch.and("dc", DataCenterAndNameSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); + DataCenterAndNameSearch.and("name", DataCenterAndNameSearch.entity().getName(), SearchCriteria.Op.EQ); + DataCenterAndNameSearch.done(); + + DataCenterIdSearch = createSearchBuilder(); + DataCenterIdSearch.and("dcId", DataCenterIdSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); DataCenterIdSearch.done(); - - + + UUIDSearch = createSearchBuilder(); UUIDSearch.and("uuid", UUIDSearch.entity().getUuid(), SearchCriteria.Op.EQ); UUIDSearch.done(); @@ -67,56 +67,56 @@ public class EngineHostPodDaoImpl extends GenericDaoBase StateChangeSearch = createSearchBuilder(); StateChangeSearch.and("id", StateChangeSearch.entity().getId(), SearchCriteria.Op.EQ); StateChangeSearch.and("state", StateChangeSearch.entity().getState(), SearchCriteria.Op.EQ); - StateChangeSearch.done(); - - } - + StateChangeSearch.done(); + + } + @Override - public List listByDataCenterId(long id) { - SearchCriteria sc = DataCenterIdSearch.create(); - sc.setParameters("dcId", id); - - return listBy(sc); - } - + public List listByDataCenterId(long id) { + SearchCriteria sc = DataCenterIdSearch.create(); + sc.setParameters("dcId", id); + + return listBy(sc); + } + @Override - public EngineHostPodVO findByName(String name, long dcId) { - SearchCriteria sc = DataCenterAndNameSearch.create(); - sc.setParameters("dc", dcId); - sc.setParameters("name", name); - - return findOneBy(sc); - } - - @Override - public HashMap> getCurrentPodCidrSubnets(long zoneId, long podIdToSkip) { - HashMap> currentPodCidrSubnets = new HashMap>(); - - String selectSql = "SELECT id, cidr_address, cidr_size FROM host_pod_ref WHERE data_center_id=" + zoneId +" and removed IS NULL"; - Transaction txn = Transaction.currentTxn(); - try { - PreparedStatement stmt = txn.prepareAutoCloseStatement(selectSql); - ResultSet rs = stmt.executeQuery(); - while (rs.next()) { - Long podId = rs.getLong("id"); - if (podId.longValue() == podIdToSkip) { + public EngineHostPodVO findByName(String name, long dcId) { + SearchCriteria sc = DataCenterAndNameSearch.create(); + sc.setParameters("dc", dcId); + sc.setParameters("name", name); + + return findOneBy(sc); + } + + @Override + public HashMap> getCurrentPodCidrSubnets(long zoneId, long podIdToSkip) { + HashMap> currentPodCidrSubnets = new HashMap>(); + + String selectSql = "SELECT id, cidr_address, cidr_size FROM host_pod_ref WHERE data_center_id=" + zoneId +" and removed IS NULL"; + Transaction txn = Transaction.currentTxn(); + try { + PreparedStatement stmt = txn.prepareAutoCloseStatement(selectSql); + ResultSet rs = stmt.executeQuery(); + while (rs.next()) { + Long podId = rs.getLong("id"); + if (podId.longValue() == podIdToSkip) { continue; - } - String cidrAddress = rs.getString("cidr_address"); - long cidrSize = rs.getLong("cidr_size"); - List cidrPair = new ArrayList(); - cidrPair.add(0, cidrAddress); - cidrPair.add(1, new Long(cidrSize)); - currentPodCidrSubnets.put(podId, cidrPair); - } - } catch (SQLException ex) { - s_logger.warn("DB exception " + ex.getMessage(), ex); - return null; - } - - return currentPodCidrSubnets; - } - + } + String cidrAddress = rs.getString("cidr_address"); + long cidrSize = rs.getLong("cidr_size"); + List cidrPair = new ArrayList(); + cidrPair.add(0, cidrAddress); + cidrPair.add(1, new Long(cidrSize)); + currentPodCidrSubnets.put(podId, cidrPair); + } + } catch (SQLException ex) { + s_logger.warn("DB exception " + ex.getMessage(), ex); + return null; + } + + return currentPodCidrSubnets; + } + @Override public boolean remove(Long id) { Transaction txn = Transaction.currentTxn(); @@ -179,6 +179,6 @@ public class EngineHostPodDaoImpl extends GenericDaoBase return rows > 0; } - - -} + + +} diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/service/api/ProvisioningServiceImpl.java b/engine/orchestration/src/org/apache/cloudstack/engine/service/api/ProvisioningServiceImpl.java index 83e78b45fd0..863c181a9a7 100644 --- a/engine/orchestration/src/org/apache/cloudstack/engine/service/api/ProvisioningServiceImpl.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/service/api/ProvisioningServiceImpl.java @@ -1,170 +1,170 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.service.api; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.inject.Inject; -import javax.ws.rs.Path; - -import org.apache.cloudstack.engine.datacenter.entity.api.ClusterEntity; -import org.apache.cloudstack.engine.datacenter.entity.api.ClusterEntityImpl; -import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceManager; -import org.apache.cloudstack.engine.datacenter.entity.api.HostEntity; -import org.apache.cloudstack.engine.datacenter.entity.api.HostEntityImpl; -import org.apache.cloudstack.engine.datacenter.entity.api.PodEntity; -import org.apache.cloudstack.engine.datacenter.entity.api.PodEntityImpl; -import org.apache.cloudstack.engine.datacenter.entity.api.StorageEntity; -import org.apache.cloudstack.engine.datacenter.entity.api.ZoneEntity; -import org.apache.cloudstack.engine.datacenter.entity.api.ZoneEntityImpl; -import org.springframework.stereotype.Component; -import org.springframework.stereotype.Service; - -import com.cloud.host.Host; -import com.cloud.host.Status; -import com.cloud.storage.StoragePool; - - -@Component -@Service("provisioningService") -@Path("/provisioning") -public class ProvisioningServiceImpl implements ProvisioningService { - - @Inject - DataCenterResourceManager manager; - - @Override - public StorageEntity registerStorage(String name, List tags, Map details) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ZoneEntity registerZone(String zoneUuid, String name, String owner, List tags, Map details) { - ZoneEntityImpl zoneEntity = new ZoneEntityImpl(zoneUuid, manager); - zoneEntity.setName(name); - zoneEntity.setOwner(owner); - zoneEntity.setDetails(details); - zoneEntity.persist(); - return zoneEntity; - } - - @Override - public PodEntity registerPod(String podUuid, String name, String owner, String zoneUuid, List tags, Map details) { - PodEntityImpl podEntity = new PodEntityImpl(podUuid, manager); - podEntity.setOwner(owner); - podEntity.setName(name); - podEntity.persist(); - return podEntity; - } - - @Override - public ClusterEntity registerCluster(String clusterUuid, String name, String owner, List tags, Map details) { - ClusterEntityImpl clusterEntity = new ClusterEntityImpl(clusterUuid, manager); - clusterEntity.setOwner(owner); - clusterEntity.setName(name); - clusterEntity.persist(); - return clusterEntity; - } - - @Override - public HostEntity registerHost(String hostUuid, String name, String owner, List tags, Map details) { - HostEntityImpl hostEntity = new HostEntityImpl(hostUuid, manager); - hostEntity.setOwner(owner); - hostEntity.setName(name); - hostEntity.setDetails(details); - - hostEntity.persist(); - return hostEntity; - } - - @Override - public void deregisterStorage(String uuid) { - // TODO Auto-generated method stub - - } - - @Override - public void deregisterZone(String uuid) { - ZoneEntityImpl zoneEntity = new ZoneEntityImpl(uuid, manager); - zoneEntity.disable(); - } - - @Override - public void deregisterPod(String uuid) { - PodEntityImpl podEntity = new PodEntityImpl(uuid, manager); - podEntity.disable(); - } - - @Override - public void deregisterCluster(String uuid) { - ClusterEntityImpl clusterEntity = new ClusterEntityImpl(uuid, manager); - clusterEntity.disable(); - - } - - @Override - public void deregisterHost(String uuid) { - HostEntityImpl hostEntity = new HostEntityImpl(uuid, manager); - hostEntity.disable(); - } - - @Override - public void changeState(String type, String entity, Status state) { - // TODO Auto-generated method stub - - } - - @Override - public List listHosts() { - // TODO Auto-generated method stub - return null; - } - - @Override - public List listPods() { - List pods = new ArrayList(); - //pods.add(new PodEntityImpl("pod-uuid-1", "pod1")); - //pods.add(new PodEntityImpl("pod-uuid-2", "pod2")); - return null; - } - - @Override - public List listZones() { - List zones = new ArrayList(); - //zones.add(new ZoneEntityImpl("zone-uuid-1")); - //zones.add(new ZoneEntityImpl("zone-uuid-2")); - return zones; - } - - @Override - public List listStorage() { - // TODO Auto-generated method stub - return null; - } - - @Override - public ZoneEntity getZone(String uuid) { - ZoneEntityImpl impl = new ZoneEntityImpl(uuid, manager); - return impl; - } - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.service.api; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.inject.Inject; +import javax.ws.rs.Path; + +import org.apache.cloudstack.engine.datacenter.entity.api.ClusterEntity; +import org.apache.cloudstack.engine.datacenter.entity.api.ClusterEntityImpl; +import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceManager; +import org.apache.cloudstack.engine.datacenter.entity.api.HostEntity; +import org.apache.cloudstack.engine.datacenter.entity.api.HostEntityImpl; +import org.apache.cloudstack.engine.datacenter.entity.api.PodEntity; +import org.apache.cloudstack.engine.datacenter.entity.api.PodEntityImpl; +import org.apache.cloudstack.engine.datacenter.entity.api.StorageEntity; +import org.apache.cloudstack.engine.datacenter.entity.api.ZoneEntity; +import org.apache.cloudstack.engine.datacenter.entity.api.ZoneEntityImpl; +import org.springframework.stereotype.Component; +import org.springframework.stereotype.Service; + +import com.cloud.host.Host; +import com.cloud.host.Status; +import com.cloud.storage.StoragePool; + + +@Component +@Service("provisioningService") +@Path("/provisioning") +public class ProvisioningServiceImpl implements ProvisioningService { + + @Inject + DataCenterResourceManager manager; + + @Override + public StorageEntity registerStorage(String name, List tags, Map details) { + // TODO Auto-generated method stub + return null; + } + + @Override + public ZoneEntity registerZone(String zoneUuid, String name, String owner, List tags, Map details) { + ZoneEntityImpl zoneEntity = new ZoneEntityImpl(zoneUuid, manager); + zoneEntity.setName(name); + zoneEntity.setOwner(owner); + zoneEntity.setDetails(details); + zoneEntity.persist(); + return zoneEntity; + } + + @Override + public PodEntity registerPod(String podUuid, String name, String owner, String zoneUuid, List tags, Map details) { + PodEntityImpl podEntity = new PodEntityImpl(podUuid, manager); + podEntity.setOwner(owner); + podEntity.setName(name); + podEntity.persist(); + return podEntity; + } + + @Override + public ClusterEntity registerCluster(String clusterUuid, String name, String owner, List tags, Map details) { + ClusterEntityImpl clusterEntity = new ClusterEntityImpl(clusterUuid, manager); + clusterEntity.setOwner(owner); + clusterEntity.setName(name); + clusterEntity.persist(); + return clusterEntity; + } + + @Override + public HostEntity registerHost(String hostUuid, String name, String owner, List tags, Map details) { + HostEntityImpl hostEntity = new HostEntityImpl(hostUuid, manager); + hostEntity.setOwner(owner); + hostEntity.setName(name); + hostEntity.setDetails(details); + + hostEntity.persist(); + return hostEntity; + } + + @Override + public void deregisterStorage(String uuid) { + // TODO Auto-generated method stub + + } + + @Override + public void deregisterZone(String uuid) { + ZoneEntityImpl zoneEntity = new ZoneEntityImpl(uuid, manager); + zoneEntity.disable(); + } + + @Override + public void deregisterPod(String uuid) { + PodEntityImpl podEntity = new PodEntityImpl(uuid, manager); + podEntity.disable(); + } + + @Override + public void deregisterCluster(String uuid) { + ClusterEntityImpl clusterEntity = new ClusterEntityImpl(uuid, manager); + clusterEntity.disable(); + + } + + @Override + public void deregisterHost(String uuid) { + HostEntityImpl hostEntity = new HostEntityImpl(uuid, manager); + hostEntity.disable(); + } + + @Override + public void changeState(String type, String entity, Status state) { + // TODO Auto-generated method stub + + } + + @Override + public List listHosts() { + // TODO Auto-generated method stub + return null; + } + + @Override + public List listPods() { + List pods = new ArrayList(); + //pods.add(new PodEntityImpl("pod-uuid-1", "pod1")); + //pods.add(new PodEntityImpl("pod-uuid-2", "pod2")); + return null; + } + + @Override + public List listZones() { + List zones = new ArrayList(); + //zones.add(new ZoneEntityImpl("zone-uuid-1")); + //zones.add(new ZoneEntityImpl("zone-uuid-2")); + return zones; + } + + @Override + public List listStorage() { + // TODO Auto-generated method stub + return null; + } + + @Override + public ZoneEntity getZone(String uuid) { + ZoneEntityImpl impl = new ZoneEntityImpl(uuid, manager); + return impl; + } + +} diff --git a/engine/orchestration/test/org/apache/cloudstack/engine/provisioning/test/ProvisioningTest.java b/engine/orchestration/test/org/apache/cloudstack/engine/provisioning/test/ProvisioningTest.java index a3ef2768287..0976f838b3b 100644 --- a/engine/orchestration/test/org/apache/cloudstack/engine/provisioning/test/ProvisioningTest.java +++ b/engine/orchestration/test/org/apache/cloudstack/engine/provisioning/test/ProvisioningTest.java @@ -14,124 +14,124 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -/** - * - */ -package org.apache.cloudstack.engine.provisioning.test; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import javax.inject.Inject; - -import org.apache.cloudstack.engine.datacenter.entity.api.ClusterEntity; -import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State; -import org.apache.cloudstack.engine.datacenter.entity.api.HostEntity; -import org.apache.cloudstack.engine.datacenter.entity.api.PodEntity; -import org.apache.cloudstack.engine.datacenter.entity.api.ZoneEntity; -import org.apache.cloudstack.engine.datacenter.entity.api.db.dao.EngineClusterDao; -import org.apache.cloudstack.engine.datacenter.entity.api.db.dao.EngineDataCenterDao; -import org.apache.cloudstack.engine.datacenter.entity.api.db.dao.EngineHostDao; -import org.apache.cloudstack.engine.datacenter.entity.api.db.dao.EngineHostPodDao; -import org.apache.cloudstack.engine.service.api.ProvisioningService; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineClusterVO; -import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineDataCenterVO; -import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineHostPodVO; -import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineHostVO; - -import com.cloud.dc.DataCenter.NetworkType; - -import junit.framework.TestCase; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations="classpath:/resource/provisioningContext.xml") -public class ProvisioningTest extends TestCase { - - @Inject - ProvisioningService service; - - @Inject - EngineDataCenterDao dcDao; - - @Inject - EngineHostPodDao _podDao; - - @Inject - EngineClusterDao _clusterDao; - - @Inject - EngineHostDao _hostDao; - - @Before - public void setUp() { - EngineDataCenterVO dc = new EngineDataCenterVO(UUID.randomUUID().toString(), "test", "8.8.8.8", null, "10.0.0.1", null, "10.0.0.1/24", - null, null, NetworkType.Basic, null, null, true, true, null, null); - Mockito.when(dcDao.findByUuid(Mockito.anyString())).thenReturn(dc); - Mockito.when(dcDao.persist((EngineDataCenterVO) Mockito.anyObject())).thenReturn(dc); - - EngineHostPodVO pod = new EngineHostPodVO("lab", 123, "10.0.0.1", "10.0.0.1", 24, "test"); - Mockito.when(_podDao.findByUuid(Mockito.anyString())).thenReturn(pod); - Mockito.when(_podDao.persist((EngineHostPodVO) Mockito.anyObject())).thenReturn(pod); - - EngineClusterVO cluster = new EngineClusterVO(); - Mockito.when(_clusterDao.findByUuid(Mockito.anyString())).thenReturn(cluster); - Mockito.when(_clusterDao.persist((EngineClusterVO) Mockito.anyObject())).thenReturn(cluster); - - EngineHostVO host = new EngineHostVO("68765876598"); - Mockito.when(_hostDao.findByUuid(Mockito.anyString())).thenReturn(host); - Mockito.when(_hostDao.persist((EngineHostVO) Mockito.anyObject())).thenReturn(host); - - } - - private void registerAndEnableZone() { - ZoneEntity zone = service.registerZone("47547648", "lab","owner", null, new HashMap()); - State state = zone.getState(); - System.out.println("state:"+state); - boolean result = zone.enable(); - System.out.println("result:"+result); - - } - - private void registerAndEnablePod() { - PodEntity pod = service.registerPod("47547648", "lab","owner", "8709874074", null, new HashMap()); - State state = pod.getState(); - System.out.println("state:"+state); - boolean result = pod.enable(); - System.out.println("result:"+result); - } - - private void registerAndEnableCluster() { - ClusterEntity cluster = service.registerCluster("1265476542", "lab","owner", null, new HashMap()); - State state = cluster.getState(); - System.out.println("state:"+state); - boolean result = cluster.enable(); - System.out.println("result:"+result); - } - - private void registerAndEnableHost() { - HostEntity host = service.registerHost("1265476542", "lab","owner", null, new HashMap()); - State state = host.getState(); - System.out.println("state:"+state); - boolean result = host.enable(); - System.out.println("result:"+result); - } - - @Test - public void testProvisioning() { - registerAndEnableZone(); - registerAndEnablePod(); - registerAndEnableCluster(); - registerAndEnableHost(); - } - - -} +/** + * + */ +package org.apache.cloudstack.engine.provisioning.test; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.inject.Inject; + +import org.apache.cloudstack.engine.datacenter.entity.api.ClusterEntity; +import org.apache.cloudstack.engine.datacenter.entity.api.DataCenterResourceEntity.State; +import org.apache.cloudstack.engine.datacenter.entity.api.HostEntity; +import org.apache.cloudstack.engine.datacenter.entity.api.PodEntity; +import org.apache.cloudstack.engine.datacenter.entity.api.ZoneEntity; +import org.apache.cloudstack.engine.datacenter.entity.api.db.dao.EngineClusterDao; +import org.apache.cloudstack.engine.datacenter.entity.api.db.dao.EngineDataCenterDao; +import org.apache.cloudstack.engine.datacenter.entity.api.db.dao.EngineHostDao; +import org.apache.cloudstack.engine.datacenter.entity.api.db.dao.EngineHostPodDao; +import org.apache.cloudstack.engine.service.api.ProvisioningService; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineClusterVO; +import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineDataCenterVO; +import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineHostPodVO; +import org.apache.cloudstack.engine.datacenter.entity.api.db.EngineHostVO; + +import com.cloud.dc.DataCenter.NetworkType; + +import junit.framework.TestCase; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations="classpath:/resource/provisioningContext.xml") +public class ProvisioningTest extends TestCase { + + @Inject + ProvisioningService service; + + @Inject + EngineDataCenterDao dcDao; + + @Inject + EngineHostPodDao _podDao; + + @Inject + EngineClusterDao _clusterDao; + + @Inject + EngineHostDao _hostDao; + + @Before + public void setUp() { + EngineDataCenterVO dc = new EngineDataCenterVO(UUID.randomUUID().toString(), "test", "8.8.8.8", null, "10.0.0.1", null, "10.0.0.1/24", + null, null, NetworkType.Basic, null, null, true, true, null, null); + Mockito.when(dcDao.findByUuid(Mockito.anyString())).thenReturn(dc); + Mockito.when(dcDao.persist((EngineDataCenterVO) Mockito.anyObject())).thenReturn(dc); + + EngineHostPodVO pod = new EngineHostPodVO("lab", 123, "10.0.0.1", "10.0.0.1", 24, "test"); + Mockito.when(_podDao.findByUuid(Mockito.anyString())).thenReturn(pod); + Mockito.when(_podDao.persist((EngineHostPodVO) Mockito.anyObject())).thenReturn(pod); + + EngineClusterVO cluster = new EngineClusterVO(); + Mockito.when(_clusterDao.findByUuid(Mockito.anyString())).thenReturn(cluster); + Mockito.when(_clusterDao.persist((EngineClusterVO) Mockito.anyObject())).thenReturn(cluster); + + EngineHostVO host = new EngineHostVO("68765876598"); + Mockito.when(_hostDao.findByUuid(Mockito.anyString())).thenReturn(host); + Mockito.when(_hostDao.persist((EngineHostVO) Mockito.anyObject())).thenReturn(host); + + } + + private void registerAndEnableZone() { + ZoneEntity zone = service.registerZone("47547648", "lab","owner", null, new HashMap()); + State state = zone.getState(); + System.out.println("state:"+state); + boolean result = zone.enable(); + System.out.println("result:"+result); + + } + + private void registerAndEnablePod() { + PodEntity pod = service.registerPod("47547648", "lab","owner", "8709874074", null, new HashMap()); + State state = pod.getState(); + System.out.println("state:"+state); + boolean result = pod.enable(); + System.out.println("result:"+result); + } + + private void registerAndEnableCluster() { + ClusterEntity cluster = service.registerCluster("1265476542", "lab","owner", null, new HashMap()); + State state = cluster.getState(); + System.out.println("state:"+state); + boolean result = cluster.enable(); + System.out.println("result:"+result); + } + + private void registerAndEnableHost() { + HostEntity host = service.registerHost("1265476542", "lab","owner", null, new HashMap()); + State state = host.getState(); + System.out.println("state:"+state); + boolean result = host.enable(); + System.out.println("result:"+result); + } + + @Test + public void testProvisioning() { + registerAndEnableZone(); + registerAndEnablePod(); + registerAndEnableCluster(); + registerAndEnableHost(); + } + + +} 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 747e2586fed..0dd55d1d325 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/allocator/ClusterScopeStoragePoolAllocator.java +++ b/engine/storage/src/org/apache/cloudstack/storage/allocator/ClusterScopeStoragePoolAllocator.java @@ -51,6 +51,7 @@ public class ClusterScopeStoragePoolAllocator extends AbstractStoragePoolAllocat @Override protected List select(DiskProfile dskCh, VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoid, int returnUpTo) { + s_logger.debug("ClusterScopeStoragePoolAllocator looking for storage pool"); List suitablePools = new ArrayList(); long dcId = plan.getDataCenterId(); diff --git a/engine/storage/src/org/apache/cloudstack/storage/allocator/GarbageCollectingStoragePoolAllocator.java b/engine/storage/src/org/apache/cloudstack/storage/allocator/GarbageCollectingStoragePoolAllocator.java index 91bc25c715d..02032ee4fbd 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/allocator/GarbageCollectingStoragePoolAllocator.java +++ b/engine/storage/src/org/apache/cloudstack/storage/allocator/GarbageCollectingStoragePoolAllocator.java @@ -48,7 +48,7 @@ public class GarbageCollectingStoragePoolAllocator extends AbstractStoragePoolAl @Override public List select(DiskProfile dskCh, VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoid, int returnUpTo) { - + s_logger.debug("GarbageCollectingStoragePoolAllocator looking for storage pool"); if (!_storagePoolCleanupEnabled) { s_logger.debug("Storage pool cleanup is not enabled, so GarbageCollectingStoragePoolAllocator is being skipped."); return null; diff --git a/engine/storage/src/org/apache/cloudstack/storage/allocator/LocalStoragePoolAllocator.java b/engine/storage/src/org/apache/cloudstack/storage/allocator/LocalStoragePoolAllocator.java index a8d5173cebe..7447d988a58 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/allocator/LocalStoragePoolAllocator.java +++ b/engine/storage/src/org/apache/cloudstack/storage/allocator/LocalStoragePoolAllocator.java @@ -69,11 +69,12 @@ public class LocalStoragePoolAllocator extends AbstractStoragePoolAllocator { List suitablePools = new ArrayList(); - - if (s_logger.isDebugEnabled()) { - s_logger.debug("LocalStoragePoolAllocator trying to find storage pool to fit the vm"); - } + s_logger.debug("LocalStoragePoolAllocator trying to find storage pool to fit the vm"); + if (!dskCh.useLocalStorage()) { + return suitablePools; + } + // data disk and host identified from deploying vm (attach volume case) if (dskCh.getType() == Volume.Type.DATADISK && plan.getHostId() != null) { List hostPools = _poolHostDao.listByHostId(plan.getHostId()); 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 c45f8a822a9..7c6c946765f 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/allocator/ZoneWideStoragePoolAllocator.java +++ b/engine/storage/src/org/apache/cloudstack/storage/allocator/ZoneWideStoragePoolAllocator.java @@ -55,8 +55,9 @@ public class ZoneWideStoragePoolAllocator extends AbstractStoragePoolAllocator { protected List select(DiskProfile dskCh, VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoid, int returnUpTo) { + s_logger.debug("ZoneWideStoragePoolAllocator to find storage pool"); List suitablePools = new ArrayList(); - HypervisorType hypervisor = vmProfile.getHypervisorType(); + HypervisorType hypervisor = dskCh.getHypersorType(); if (hypervisor != null) { if (hypervisor != HypervisorType.KVM) { s_logger.debug("Only kvm supports zone wide storage"); diff --git a/framework/rest/src/org/apache/cloudstack/framework/ws/jackson/CSJacksonAnnotationIntrospector.java b/framework/rest/src/org/apache/cloudstack/framework/ws/jackson/CSJacksonAnnotationIntrospector.java index 998bfa084b3..6a26a6c5947 100644 --- a/framework/rest/src/org/apache/cloudstack/framework/ws/jackson/CSJacksonAnnotationIntrospector.java +++ b/framework/rest/src/org/apache/cloudstack/framework/ws/jackson/CSJacksonAnnotationIntrospector.java @@ -1,60 +1,60 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.ws.jackson; - -import java.lang.reflect.AnnotatedElement; -import java.util.List; - -import com.fasterxml.jackson.core.Version; -import com.fasterxml.jackson.databind.introspect.Annotated; -import com.fasterxml.jackson.databind.introspect.NopAnnotationIntrospector; - - -/** - * Adds introspectors for the annotations added specifically for CloudStack - * Web Services. - * - */ -public class CSJacksonAnnotationIntrospector extends NopAnnotationIntrospector { - - private static final long serialVersionUID = 5532727887216652602L; - - @Override - public Version version() { - return new Version(1, 7, 0, "abc", "org.apache.cloudstack", "cloudstack-framework-rest"); - } - - @Override - public Object findSerializer(Annotated a) { - AnnotatedElement ae = a.getAnnotated(); - Url an = ae.getAnnotation(Url.class); - if (an == null) { - return null; - } - - if (an.type() == String.class) { - return new UriSerializer(an); - } else if (an.type() == List.class){ - return new UrisSerializer(an); - } - - throw new UnsupportedOperationException("Unsupported type " + an.type()); - - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.ws.jackson; + +import java.lang.reflect.AnnotatedElement; +import java.util.List; + +import com.fasterxml.jackson.core.Version; +import com.fasterxml.jackson.databind.introspect.Annotated; +import com.fasterxml.jackson.databind.introspect.NopAnnotationIntrospector; + + +/** + * Adds introspectors for the annotations added specifically for CloudStack + * Web Services. + * + */ +public class CSJacksonAnnotationIntrospector extends NopAnnotationIntrospector { + + private static final long serialVersionUID = 5532727887216652602L; + + @Override + public Version version() { + return new Version(1, 7, 0, "abc", "org.apache.cloudstack", "cloudstack-framework-rest"); + } + + @Override + public Object findSerializer(Annotated a) { + AnnotatedElement ae = a.getAnnotated(); + Url an = ae.getAnnotation(Url.class); + if (an == null) { + return null; + } + + if (an.type() == String.class) { + return new UriSerializer(an); + } else if (an.type() == List.class){ + return new UrisSerializer(an); + } + + throw new UnsupportedOperationException("Unsupported type " + an.type()); + + } +} diff --git a/framework/rest/src/org/apache/cloudstack/framework/ws/jackson/CSJacksonAnnotationModule.java b/framework/rest/src/org/apache/cloudstack/framework/ws/jackson/CSJacksonAnnotationModule.java index 55debd9b7b2..d274b858c5f 100644 --- a/framework/rest/src/org/apache/cloudstack/framework/ws/jackson/CSJacksonAnnotationModule.java +++ b/framework/rest/src/org/apache/cloudstack/framework/ws/jackson/CSJacksonAnnotationModule.java @@ -1,47 +1,47 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.ws.jackson; - - -import com.fasterxml.jackson.core.Version; -import com.fasterxml.jackson.databind.Module; - - -/** - * This module extends SimpleModle so that our annotations can be processed. - * - */ -public class CSJacksonAnnotationModule extends Module { - - @Override - public String getModuleName() { - return "CloudStackSupplementalModule"; - } - - @Override - public void setupModule(SetupContext ctx) { - ctx.appendAnnotationIntrospector(new CSJacksonAnnotationIntrospector()); - } - - @Override - public Version version() { - return new Version(1, 0, 0, "", "org.apache.cloudstack", "cloudstack-framework-rest"); - } - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.ws.jackson; + + +import com.fasterxml.jackson.core.Version; +import com.fasterxml.jackson.databind.Module; + + +/** + * This module extends SimpleModle so that our annotations can be processed. + * + */ +public class CSJacksonAnnotationModule extends Module { + + @Override + public String getModuleName() { + return "CloudStackSupplementalModule"; + } + + @Override + public void setupModule(SetupContext ctx) { + ctx.appendAnnotationIntrospector(new CSJacksonAnnotationIntrospector()); + } + + @Override + public Version version() { + return new Version(1, 0, 0, "", "org.apache.cloudstack", "cloudstack-framework-rest"); + } + +} diff --git a/framework/rest/src/org/apache/cloudstack/framework/ws/jackson/UriSerializer.java b/framework/rest/src/org/apache/cloudstack/framework/ws/jackson/UriSerializer.java index 074d60f8a98..07951496419 100644 --- a/framework/rest/src/org/apache/cloudstack/framework/ws/jackson/UriSerializer.java +++ b/framework/rest/src/org/apache/cloudstack/framework/ws/jackson/UriSerializer.java @@ -1,58 +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.framework.ws.jackson; - -import java.io.IOException; - -import javax.ws.rs.core.UriBuilder; - -import org.apache.cxf.jaxrs.impl.tl.ThreadLocalUriInfo; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; - -public class UriSerializer extends JsonSerializer { - - Url _annotation; - - public UriSerializer(Url annotation) { - _annotation = annotation; - } - - protected UriSerializer() { - } - - @Override - public void serialize(String id, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { - jgen.writeStartObject(); - jgen.writeStringField("id", id); - jgen.writeFieldName("uri"); - jgen.writeString(buildUri(_annotation.clazz(), _annotation.method(), id)); - jgen.writeEndObject(); - } - - protected String buildUri(Class clazz, String method, String id) { - ThreadLocalUriInfo uriInfo = new ThreadLocalUriInfo(); - UriBuilder ub = uriInfo.getAbsolutePathBuilder().path(clazz, method); - ub.build(id); - return ub.toString(); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.ws.jackson; + +import java.io.IOException; + +import javax.ws.rs.core.UriBuilder; + +import org.apache.cxf.jaxrs.impl.tl.ThreadLocalUriInfo; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; + +public class UriSerializer extends JsonSerializer { + + Url _annotation; + + public UriSerializer(Url annotation) { + _annotation = annotation; + } + + protected UriSerializer() { + } + + @Override + public void serialize(String id, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { + jgen.writeStartObject(); + jgen.writeStringField("id", id); + jgen.writeFieldName("uri"); + jgen.writeString(buildUri(_annotation.clazz(), _annotation.method(), id)); + jgen.writeEndObject(); + } + + protected String buildUri(Class clazz, String method, String id) { + ThreadLocalUriInfo uriInfo = new ThreadLocalUriInfo(); + UriBuilder ub = uriInfo.getAbsolutePathBuilder().path(clazz, method); + ub.build(id); + return ub.toString(); + } +} diff --git a/framework/rest/src/org/apache/cloudstack/framework/ws/jackson/UrisSerializer.java b/framework/rest/src/org/apache/cloudstack/framework/ws/jackson/UrisSerializer.java index 8b622123e3f..6ab3ced3cd4 100644 --- a/framework/rest/src/org/apache/cloudstack/framework/ws/jackson/UrisSerializer.java +++ b/framework/rest/src/org/apache/cloudstack/framework/ws/jackson/UrisSerializer.java @@ -1,71 +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. - */ -package org.apache.cloudstack.framework.ws.jackson; - -import java.io.IOException; -import java.util.Iterator; -import java.util.List; - -import javax.ws.rs.core.UriBuilder; - -import org.apache.cxf.jaxrs.impl.tl.ThreadLocalUriInfo; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; - - -/** - * Serializer for a list of ids. - * - */ -public class UrisSerializer extends JsonSerializer> { - Url _annotation; - - public UrisSerializer(Url annotation) { - _annotation = annotation; - } - - protected UrisSerializer() { - } - - @Override - public void serialize(List lst, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { - Iterator it = lst.iterator(); - jgen.writeStartObject(); - while (it.hasNext()) { - Object id = it.next(); - jgen.writeStartObject(); - jgen.writeFieldName("id"); - jgen.writeObject(id); - jgen.writeFieldName("uri"); - jgen.writeString(buildUri(_annotation.clazz(), _annotation.method(), id)); - jgen.writeEndObject(); - } - jgen.writeEndObject(); - } - - protected String buildUri(Class clazz, String method, Object id) { - ThreadLocalUriInfo uriInfo = new ThreadLocalUriInfo(); - UriBuilder ub = uriInfo.getAbsolutePathBuilder().path(clazz, method); - ub.build(id); - return ub.toString(); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.ws.jackson; + +import java.io.IOException; +import java.util.Iterator; +import java.util.List; + +import javax.ws.rs.core.UriBuilder; + +import org.apache.cxf.jaxrs.impl.tl.ThreadLocalUriInfo; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; + + +/** + * Serializer for a list of ids. + * + */ +public class UrisSerializer extends JsonSerializer> { + Url _annotation; + + public UrisSerializer(Url annotation) { + _annotation = annotation; + } + + protected UrisSerializer() { + } + + @Override + public void serialize(List lst, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { + Iterator it = lst.iterator(); + jgen.writeStartObject(); + while (it.hasNext()) { + Object id = it.next(); + jgen.writeStartObject(); + jgen.writeFieldName("id"); + jgen.writeObject(id); + jgen.writeFieldName("uri"); + jgen.writeString(buildUri(_annotation.clazz(), _annotation.method(), id)); + jgen.writeEndObject(); + } + jgen.writeEndObject(); + } + + protected String buildUri(Class clazz, String method, Object id) { + ThreadLocalUriInfo uriInfo = new ThreadLocalUriInfo(); + UriBuilder ub = uriInfo.getAbsolutePathBuilder().path(clazz, method); + ub.build(id); + return ub.toString(); + } +} diff --git a/framework/rest/src/org/apache/cloudstack/framework/ws/jackson/Url.java b/framework/rest/src/org/apache/cloudstack/framework/ws/jackson/Url.java index 7094fb07f84..9f9537c1cf3 100644 --- a/framework/rest/src/org/apache/cloudstack/framework/ws/jackson/Url.java +++ b/framework/rest/src/org/apache/cloudstack/framework/ws/jackson/Url.java @@ -1,53 +1,53 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES 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.ws.jackson; - -import static java.lang.annotation.ElementType.FIELD; -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -/** - * Url can be placed onto a method to construct an URL from the returned - * results. - * - * This annotation is supplemental to JAX-RS 2.0's annotations. JAX-RS 2.0 - * annotations do not include a way to construct an URL. Of - * course, this only works with how CloudStack works. - * - */ -@Target({FIELD, METHOD}) -@Retention(RUNTIME) -public @interface Url { - /** - * @return the class that the path should belong to. - */ - Class clazz() default Object.class; - - /** - * @return the name of the method that the path should call back to. - */ - String method(); - - String name() default ""; - - Class type() default String.class; -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES 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.ws.jackson; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + * Url can be placed onto a method to construct an URL from the returned + * results. + * + * This annotation is supplemental to JAX-RS 2.0's annotations. JAX-RS 2.0 + * annotations do not include a way to construct an URL. Of + * course, this only works with how CloudStack works. + * + */ +@Target({FIELD, METHOD}) +@Retention(RUNTIME) +public @interface Url { + /** + * @return the class that the path should belong to. + */ + Class clazz() default Object.class; + + /** + * @return the name of the method that the path should call back to. + */ + String method(); + + String name() default ""; + + Class type() default String.class; +} diff --git a/framework/rest/test/org/apache/cloudstack/framework/ws/jackson/CSJacksonAnnotationTest.java b/framework/rest/test/org/apache/cloudstack/framework/ws/jackson/CSJacksonAnnotationTest.java index 8869b218402..75e39046420 100644 --- a/framework/rest/test/org/apache/cloudstack/framework/ws/jackson/CSJacksonAnnotationTest.java +++ b/framework/rest/test/org/apache/cloudstack/framework/ws/jackson/CSJacksonAnnotationTest.java @@ -14,8 +14,8 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package org.apache.cloudstack.framework.ws.jackson; - +package org.apache.cloudstack.framework.ws.jackson; + import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; @@ -35,84 +35,84 @@ import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule; import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule.Priority; - -public class CSJacksonAnnotationTest { - - @Before - public void setUp() throws Exception { - } - - @Test @Ignore - public void test() { - ObjectMapper mapper = new ObjectMapper(); - JaxbAnnotationModule jaxbModule = new JaxbAnnotationModule(); - jaxbModule.setPriority(Priority.SECONDARY); - mapper.registerModule(jaxbModule); - mapper.registerModule(new CSJacksonAnnotationModule()); - - StringWriter writer = new StringWriter(); - - TestVO vo = new TestVO(1000, "name"); - vo.names = new ArrayList(); - vo.names.add("name1"); - vo.names.add("name2"); - vo.values = new HashMap(); - vo.values.put("key1", 1000l); - vo.values.put("key2", 2000l); - vo.vo2.name = "testvoname2"; - vo.pods="abcde"; - - try { - mapper.writeValue(writer, vo); - } catch (JsonGenerationException e) { - e.printStackTrace(); - } catch (JsonMappingException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - - System.out.print(writer.getBuffer().toString()); - - } - - @XmlRootElement(name="xml-test2") - public class Test2VO { - public String name; - } - - @XmlRootElement(name="abc") - public class TestVO { - public int id; - - public Map values; - - public String name; - - - public List names; - - public String pods; - - - @XmlElement(name="test2") - public Test2VO vo2 = new Test2VO(); - - public TestVO(int id, String name) { - this.id = id; - this.name = name; - } - - @Url(clazz=TestVO.class, method="getName") - public String getName() { - return name; - } - - @Url(clazz=TestVO.class, method="getNames", type=List.class) - public List getNames() { - return names; - } - - } - -} + +public class CSJacksonAnnotationTest { + + @Before + public void setUp() throws Exception { + } + + @Test @Ignore + public void test() { + ObjectMapper mapper = new ObjectMapper(); + JaxbAnnotationModule jaxbModule = new JaxbAnnotationModule(); + jaxbModule.setPriority(Priority.SECONDARY); + mapper.registerModule(jaxbModule); + mapper.registerModule(new CSJacksonAnnotationModule()); + + StringWriter writer = new StringWriter(); + + TestVO vo = new TestVO(1000, "name"); + vo.names = new ArrayList(); + vo.names.add("name1"); + vo.names.add("name2"); + vo.values = new HashMap(); + vo.values.put("key1", 1000l); + vo.values.put("key2", 2000l); + vo.vo2.name = "testvoname2"; + vo.pods="abcde"; + + try { + mapper.writeValue(writer, vo); + } catch (JsonGenerationException e) { + e.printStackTrace(); + } catch (JsonMappingException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + System.out.print(writer.getBuffer().toString()); + + } + + @XmlRootElement(name="xml-test2") + public class Test2VO { + public String name; + } + + @XmlRootElement(name="abc") + public class TestVO { + public int id; + + public Map values; + + public String name; + + + public List names; + + public String pods; + + + @XmlElement(name="test2") + public Test2VO vo2 = new Test2VO(); + + public TestVO(int id, String name) { + this.id = id; + this.name = name; + } + + @Url(clazz=TestVO.class, method="getName") + public String getName() { + return name; + } + + @Url(clazz=TestVO.class, method="getNames", type=List.class) + public List getNames() { + return names; + } + + } + +} diff --git a/packaging/centos63/cloud.spec b/packaging/centos63/cloud.spec index f8e31338005..aa4a15c3574 100644 --- a/packaging/centos63/cloud.spec +++ b/packaging/centos63/cloud.spec @@ -114,6 +114,7 @@ Requires: %{name}-common = %{_ver} Requires: libvirt Requires: bridge-utils Requires: ebtables +Requires: ipset Requires: jsvc Requires: jakarta-commons-daemon Requires: jakarta-commons-daemon-jsvc @@ -235,7 +236,7 @@ rm -rf ${RPM_BUILD_ROOT}%{_datadir}/%{name}-management/webapps/client/WEB-INF/cl rm -rf ${RPM_BUILD_ROOT}%{_datadir}/%{name}-management/webapps/client/WEB-INF/classes/vms for name in db.properties log4j-cloud.xml tomcat6-nonssl.conf tomcat6-ssl.conf server-ssl.xml server-nonssl.xml \ - catalina.policy catalina.properties db-enc.properties classpath.conf tomcat-users.xml web.xml environment.properties ; do + catalina.policy catalina.properties classpath.conf tomcat-users.xml web.xml environment.properties ; do mv ${RPM_BUILD_ROOT}%{_datadir}/%{name}-management/webapps/client/WEB-INF/classes/$name \ ${RPM_BUILD_ROOT}%{_sysconfdir}/%{name}/management/$name done @@ -362,9 +363,12 @@ if getent passwd cloud | grep -q /var/lib/cloud; then fi # if saved configs from upgrade exist, copy them over -if [ -d "%{_sysconfdir}/cloud.rpmsave/management" ]; then +if [ -f "%{_sysconfdir}/cloud.rpmsave/management/db.properties" ]; then + mv %{_sysconfdir}/%{name}/management/db.properties %{_sysconfdir}/%{name}/management/db.properties.rpmnew cp -p %{_sysconfdir}/cloud.rpmsave/management/db.properties %{_sysconfdir}/%{name}/management cp -p %{_sysconfdir}/cloud.rpmsave/management/key %{_sysconfdir}/%{name}/management + # make sure we only do this on the first install of this RPM, don't want to overwrite on a reinstall + mv %{_sysconfdir}/cloud.rpmsave/management/db.properties %{_sysconfdir}/cloud.rpmsave/management/db.properties.rpmsave fi # Choose server.xml and tomcat.conf links based on old config, if exists @@ -392,6 +396,13 @@ if [ -L $oldtomcatconf ] ; then fi fi +%preun agent +/sbin/service cloudstack-agent stop || true +if [ "$1" == "0" ] ; then + /sbin/chkconfig --del cloudstack-agent > /dev/null 2>&1 || true + /sbin/service cloudstack-agent stop > /dev/null 2>&1 || true +fi + %pre agent # save old configs if they exist (for upgrade). Otherwise we may lose them @@ -401,11 +412,17 @@ if [ -d "%{_sysconfdir}/cloud" ] ; then fi %post agent +if [ "$1" == "1" ] ; then + /sbin/chkconfig --add cloudstack-agent > /dev/null 2>&1 || true + /sbin/chkconfig --level 345 cloudstack-agent on > /dev/null 2>&1 || true +fi # if saved configs from upgrade exist, copy them over if [ -f "%{_sysconfdir}/cloud.rpmsave/agent/agent.properties" ]; then mv %{_sysconfdir}/%{name}/agent/agent.properties %{_sysconfdir}/%{name}/agent/agent.properties.rpmnew cp -p %{_sysconfdir}/cloud.rpmsave/agent/agent.properties %{_sysconfdir}/%{name}/agent + # make sure we only do this on the first install of this RPM, don't want to overwrite on a reinstall + mv %{_sysconfdir}/cloud.rpmsave/agent/agent.properties %{_sysconfdir}/cloud.rpmsave/agent/agent.properties.rpmsave fi #%post awsapi diff --git a/packaging/debian/init/cloud-management b/packaging/debian/init/cloud-management index 69a0428db21..1e008312e09 100755 --- a/packaging/debian/init/cloud-management +++ b/packaging/debian/init/cloud-management @@ -19,7 +19,7 @@ # specific language governing permissions and limitations # under the License. ### BEGIN INIT INFO -# Provides: tomcat-vmops +# Provides: cloudstack-management # Required-Start: $local_fs $remote_fs $network # Required-Stop: $local_fs $remote_fs $network # Should-Start: $named @@ -34,7 +34,7 @@ PATH=/bin:/usr/bin:/sbin:/usr/sbin NAME=cloudstack-management DESC="CloudStack-specific Tomcat servlet engine" DAEMON=/usr/bin/jsvc -CATALINA_HOME=/usr/share/cloudstack/management +CATALINA_HOME=/usr/share/cloudstack-management DEFAULT=/etc/cloudstack/management/tomcat6.conf JVM_TMP=/tmp/$NAME-temp @@ -65,7 +65,7 @@ TOMCAT6_USER=tomcat6 # The first existing directory is used for JAVA_HOME (if JAVA_HOME is not # defined in $DEFAULT) -JDK_DIRS="/usr/lib/jvm/java-1.6.0-openjdk-amd64/ /usr/lib/jvm/java-1.6.0-openjdk-i386/ /usr/lib/jvm/java-1.6.0-openjdk/ /usr/lib/jvm/java-6-openjdk /usr/lib/jvm/java-6-sun" +JDK_DIRS="/usr/lib/jvm/java-7-openjdk-amd64 /usr/lib/jvm/java-7-openjdk-i386 /usr/lib/jvm/java-6-openjdk /usr/lib/jvm/java-6-openjdk-i386 /usr/lib/jvm/java-6-openjdk-amd64 /usr/lib/jvm/java-6-sun" # Look for the right JVM to use for jdir in $JDK_DIRS; do @@ -76,7 +76,7 @@ done export JAVA_HOME # Directory for per-instance configuration files and webapps -CATALINA_BASE=/usr/share/cloudstack/management +CATALINA_BASE=/usr/share/cloudstack-management # Use the Java security manager? (yes/no) TOMCAT6_SECURITY=no @@ -125,8 +125,7 @@ fi # Define other required variables CATALINA_PID="/var/run/$NAME.pid" BOOTSTRAP_CLASS=org.apache.catalina.startup.Bootstrap -JSVC_CLASSPATH="/usr/share/java/commons-daemon.jar:$CATALINA_HOME/bin/bootstrap.jar" -JSVC_CLASSPATH=$CLASSPATH:$JSVC_CLASSPATH +JSVC_CLASSPATH="/usr/share/java/commons-daemon.jar:$CATALINA_HOME/bin/bootstrap.jar:/etc/cloudstack/management" # Look for Java Secure Sockets Extension (JSSE) JARs if [ -z "${JSSE_HOME}" -a -r "${JAVA_HOME}/jre/lib/jsse.jar" ]; then diff --git a/packaging/debian/replace.properties b/packaging/debian/replace.properties index 8705c78a8f7..8c852060c02 100644 --- a/packaging/debian/replace.properties +++ b/packaging/debian/replace.properties @@ -34,7 +34,7 @@ AWSAPILOG=/var/log/cloudstack/awsapi/awsapi.log BINDIR=/usr/bin COMMONLIBDIR=/usr/share/cloudstack-common CONFIGUREVARS= -DEPSCLASSPATH= +DEPSCLASSPATH=/usr/share/tomcat6/bin/bootstrap.jar:/usr/share/tomcat6/bin/tomcat-juli.jar DOCDIR= IPALOCATORLOG=/var/log/cloudstack/management/ipallocator.log JAVADIR=/usr/share/cloudstack-management/webapps/client/WEB-INF/lib diff --git a/plugins/alert-handlers/syslog-alerts/pom.xml b/plugins/alert-handlers/syslog-alerts/pom.xml new file mode 100644 index 00000000000..21aa54a7be2 --- /dev/null +++ b/plugins/alert-handlers/syslog-alerts/pom.xml @@ -0,0 +1,40 @@ + + + + cloudstack-plugins + org.apache.cloudstack + 4.2.0-SNAPSHOT + ../../pom.xml + + 4.0.0 + Apache CloudStack Plugin - Syslog Alerts + cloud-plugin-syslog-alerts + + + + log4j + log4j + ${cs.log4j.version} + + + + \ No newline at end of file diff --git a/plugins/alert-handlers/syslog-alerts/src/org/apache/cloudstack/syslog/AlertsSyslogAppender.java b/plugins/alert-handlers/syslog-alerts/src/org/apache/cloudstack/syslog/AlertsSyslogAppender.java new file mode 100644 index 00000000000..d2f25654c7a --- /dev/null +++ b/plugins/alert-handlers/syslog-alerts/src/org/apache/cloudstack/syslog/AlertsSyslogAppender.java @@ -0,0 +1,336 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES 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.syslog; + +import com.cloud.utils.net.NetUtils; +import org.apache.log4j.AppenderSkeleton; +import org.apache.log4j.net.SyslogAppender; +import org.apache.log4j.spi.LoggingEvent; + +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.StringTokenizer; + +public class AlertsSyslogAppender extends AppenderSkeleton { + String _syslogHosts = null; + String _delimiter = ","; + List _syslogHostsList = null; + List _syslogAppenders = null; + private String _facility; + private String _pairDelimiter = "//"; + private String _keyValueDelimiter = "::"; + private int alertType = -1; + private long dataCenterId = 0; + private long podId = 0; + private long clusterId = 0; + private String sysMessage = null; + public static final int LENGTH_OF_STRING_MESSAGE_AND_KEY_VALUE_DELIMITER = 9; + public static final int LENGTH_OF_STRING_MESSAGE = 8; + public static final String MESSAGE_DELIMITER_STRING = " "; + //add the alertType in this array it its level needs to be set to critical + private static final int[] criticalAlerts = {7, 8, 9, 10, 11, 12, 13, 15, 16, 19, 20}; + private static final Map alertsMap; + + static { + Map aMap = new HashMap(27); + aMap.put(0, "availableMemory"); + aMap.put(1, "availableCpu"); + aMap.put(2, "availableStorage"); + aMap.put(3, "remainingStorageAllocated"); + aMap.put(4, "unallocatedVirtualNetworkpublicIp"); + aMap.put(5, "unallocatedPrivateIp"); + aMap.put(6, "availableSecondaryStorage"); + aMap.put(7, "host"); + aMap.put(8, "userVmState"); + aMap.put(9, "domainRouterVmState "); + aMap.put(10, "consoleProxyVmState"); + aMap.put(11, "routingConnection"); + aMap.put(12, "storageIssueSystemVms"); + aMap.put(13, "usageServerStatus"); + aMap.put(14, "managementNode"); + aMap.put(15, "domainRouterMigrate"); + aMap.put(16, "consoleProxyMigrate"); + aMap.put(17, "userVmMigrate"); + aMap.put(18, "unallocatedVlan"); + aMap.put(19, "ssvmStopped"); + aMap.put(20, "usageServerResult"); + aMap.put(21, "storageDelete"); + aMap.put(22, "updateResourceCount"); + aMap.put(23, "usageSanityResult"); + aMap.put(24, "unallocatedDirectAttachedPublicIp"); + aMap.put(25, "unallocatedLocalStorage"); + aMap.put(26, "resourceLimitExceeded"); + + alertsMap = Collections.unmodifiableMap(aMap); + } + + @Override + protected void append(LoggingEvent event) { + if (!isAsSevereAsThreshold(event.getLevel())) { + return; + } + + if (_syslogAppenders != null && !_syslogAppenders.isEmpty()) { + try { + String logMessage = event.getRenderedMessage(); + if (logMessage.contains("alertType") && logMessage.contains("message")) { + parseMessage(logMessage); + String syslogMessage = createSyslogMessage(); + + LoggingEvent syslogEvent = new LoggingEvent(event.getFQNOfLoggerClass(), event.getLogger(), + event.getLevel(), syslogMessage, null); + + for (SyslogAppender syslogAppender : _syslogAppenders) { + syslogAppender.append(syslogEvent); + } + } + } catch (Exception e) { + errorHandler.error(e.getMessage()); + } + } + } + + @Override + synchronized public void close() { + for (SyslogAppender syslogAppender : _syslogAppenders) { + syslogAppender.close(); + } + } + + @Override + public boolean requiresLayout() { + return true; + } + + void setSyslogAppenders() { + if (_syslogAppenders == null) { + _syslogAppenders = new ArrayList(); + } + + if (_syslogHosts == null || _syslogHosts.trim().isEmpty()) { + reset(); + return; + } + + _syslogHostsList = parseSyslogHosts(_syslogHosts); + + if (!validateIpAddresses()) { + reset(); + errorHandler.error(" Invalid format for the IP Addresses parameter "); + return; + } + + for (String syslogHost : _syslogHostsList) { + _syslogAppenders.add(new SyslogAppender(getLayout(), syslogHost, SyslogAppender.getFacility(_facility))); + } + } + + private List parseSyslogHosts(String syslogHosts) { + List result = new ArrayList(); + + final StringTokenizer tokenizer = new StringTokenizer(syslogHosts, _delimiter); + while (tokenizer.hasMoreTokens()) { + result.add(tokenizer.nextToken().trim()); + } + return result; + } + + private boolean validateIpAddresses() { + for (String ipAddress : _syslogHostsList) { + if (ipAddress.trim().equalsIgnoreCase("localhost")) { + continue; + } + if (!NetUtils.isValidIp(ipAddress)) { + return false; + } + } + return true; + } + + void parseMessage(String logMessage) { + final StringTokenizer messageSplitter = new StringTokenizer(logMessage, _pairDelimiter); + while (messageSplitter.hasMoreTokens()) { + final String pairToken = messageSplitter.nextToken(); + final StringTokenizer pairSplitter = new StringTokenizer(pairToken, _keyValueDelimiter); + String keyToken; + String valueToken; + + if (pairSplitter.hasMoreTokens()) { + keyToken = pairSplitter.nextToken().trim(); + } else { + break; + } + + if (pairSplitter.hasMoreTokens()) { + valueToken = pairSplitter.nextToken().trim(); + } else { + break; + } + + if (keyToken.equalsIgnoreCase("alertType") && !valueToken.equalsIgnoreCase("null")) { + alertType = Short.parseShort(valueToken); + } else if (keyToken.equalsIgnoreCase("dataCenterId") && !valueToken.equalsIgnoreCase("null")) { + dataCenterId = Long.parseLong(valueToken); + } else if (keyToken.equalsIgnoreCase("podId") && !valueToken.equalsIgnoreCase("null")) { + podId = Long.parseLong(valueToken); + } else if (keyToken.equalsIgnoreCase("clusterId") && !valueToken.equalsIgnoreCase("null")) { + clusterId = Long.parseLong(valueToken); + } else if (keyToken.equalsIgnoreCase("message") && !valueToken.equalsIgnoreCase("null")) { + sysMessage = getSyslogMessage(logMessage); + } + } + } + + String createSyslogMessage() { + StringBuilder message = new StringBuilder(); + message.append(severityOfAlert(alertType)).append(MESSAGE_DELIMITER_STRING); + InetAddress ip; + try { + ip = InetAddress.getLocalHost(); + } catch (UnknownHostException e) { + ip = null; + } + + if (ip != null) { + message.append(ip.getHostName()).append(MESSAGE_DELIMITER_STRING); + } else { + message.append("unknown" + MESSAGE_DELIMITER_STRING); + } + + if (alertType > 0) { + message.append("alertType").append(_keyValueDelimiter).append(" ").append(alertsMap.get(alertType)) + .append(MESSAGE_DELIMITER_STRING); + if (dataCenterId != 0) { + message.append("dataCenterId").append(_keyValueDelimiter).append(" ").append(dataCenterId) + .append(MESSAGE_DELIMITER_STRING); + } + + if (podId != 0) { + message.append("podId").append(_keyValueDelimiter).append(" ").append(podId) + .append(MESSAGE_DELIMITER_STRING); + } + + if (clusterId != 0) { + message.append("clusterId").append(_keyValueDelimiter).append(" ").append(clusterId) + .append(MESSAGE_DELIMITER_STRING); + } + + if (sysMessage != null) { + message.append("message").append(_keyValueDelimiter).append(" ").append(sysMessage); + } else { + errorHandler.error(" What is the use of alert without message "); + } + } else { + errorHandler.error(" Invalid alert Type "); + } + + return message.toString(); + } + + private String getSyslogMessage(String message) { + int lastIndexOfKeyValueDelimiter = message.lastIndexOf(_keyValueDelimiter); + int lastIndexOfMessageInString = message.lastIndexOf("message"); + + if (lastIndexOfKeyValueDelimiter - lastIndexOfMessageInString <= + LENGTH_OF_STRING_MESSAGE_AND_KEY_VALUE_DELIMITER) { + return message.substring(lastIndexOfKeyValueDelimiter + _keyValueDelimiter.length()).trim(); + } else if (lastIndexOfMessageInString < lastIndexOfKeyValueDelimiter) { + return message.substring( + lastIndexOfMessageInString + _keyValueDelimiter.length() + LENGTH_OF_STRING_MESSAGE).trim(); + } + + return message.substring(message.lastIndexOf("message" + _keyValueDelimiter) + + LENGTH_OF_STRING_MESSAGE_AND_KEY_VALUE_DELIMITER).trim(); + } + + private void reset() { + _syslogAppenders.clear(); + } + + public void setFacility(String facility) { + if (facility == null) { + return; + } + + this._facility = facility; + if (_syslogAppenders != null && !_syslogAppenders.isEmpty()) { + for (SyslogAppender syslogAppender : _syslogAppenders) { + syslogAppender.setFacility(facility); + } + } + } + + private String severityOfAlert(int alertType) { + if (isCritical(alertType)) { + return "CRITICAL"; + } else { + return "WARN"; + } + } + + private boolean isCritical(int alertType) { + for (int type : criticalAlerts) { + if (type == alertType) { + return true; + } + } + return false; + } + + public String getFacility() { + return _facility; + } + + public String getSyslogHosts() { + return _syslogHosts; + } + + public void setSyslogHosts(String syslogHosts) { + this._syslogHosts = syslogHosts; + this.setSyslogAppenders(); + } + + public String getDelimiter() { + return _delimiter; + } + + public void setDelimiter(String delimiter) { + this._delimiter = delimiter; + } + + public String getPairDelimiter() { + return _pairDelimiter; + } + + public void setPairDelimiter(String pairDelimiter) { + this._pairDelimiter = pairDelimiter; + } + + public String getKeyValueDelimiter() { + return _keyValueDelimiter; + } + + public void setKeyValueDelimiter(String keyValueDelimiter) { + this._keyValueDelimiter = keyValueDelimiter; + } +} \ No newline at end of file diff --git a/plugins/alert-handlers/syslog-alerts/test/org/apache/cloudstack/syslog/AlertsSyslogAppenderTest.java b/plugins/alert-handlers/syslog-alerts/test/org/apache/cloudstack/syslog/AlertsSyslogAppenderTest.java new file mode 100644 index 00000000000..68585ee6055 --- /dev/null +++ b/plugins/alert-handlers/syslog-alerts/test/org/apache/cloudstack/syslog/AlertsSyslogAppenderTest.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 org.apache.cloudstack.syslog; + +import org.apache.log4j.PatternLayout; +import org.junit.Before; +import org.junit.Test; + +import javax.naming.ConfigurationException; + +import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.assertTrue; + +public class AlertsSyslogAppenderTest { + AlertsSyslogAppender _appender = new AlertsSyslogAppender(); + + @Before + public void setUp() throws ConfigurationException { + _appender.setLayout(new PatternLayout("%-5p [%c{3}] (%t:%x) %m%n")); + _appender.setFacility("LOCAL6"); + } + + @Test + public void setSyslogAppendersTest() { + _appender.setSyslogHosts("10.1.1.1,10.1.1.2"); + assertEquals(" error Syslog Appenders list size not as expected ", 2, _appender._syslogAppenders.size()); + } + + @Test + public void setSyslogAppendersNegativeTest() { + //setting invalid IP for Syslog Hosts + _appender.setSyslogHosts("10.1.1."); + assertTrue(" list was expected to be empty", _appender._syslogAppenders.isEmpty()); + } + + @Test + public void appendTest() { + String message = "alertType:: 14 // dataCenterId:: 0 // podId:: 0 // clusterId:: null // message:: Management" + + " server node 127.0.0.1 is up"; + _appender.parseMessage(message); + String createdMessage = _appender.createSyslogMessage(); + assertTrue(" message is not as expected ", createdMessage.contains("alertType:: managementNode" + + AlertsSyslogAppender.MESSAGE_DELIMITER_STRING + "message:: Management server node 127.0.0.1 is up")); + assertTrue("severity level not as expected ", createdMessage.contains("WARN")); + } +} \ No newline at end of file diff --git a/plugins/api/discovery/src/org/apache/cloudstack/api/response/ApiDiscoveryResponse.java b/plugins/api/discovery/src/org/apache/cloudstack/api/response/ApiDiscoveryResponse.java index 77484f0f7e7..ce7eb498be9 100644 --- a/plugins/api/discovery/src/org/apache/cloudstack/api/response/ApiDiscoveryResponse.java +++ b/plugins/api/discovery/src/org/apache/cloudstack/api/response/ApiDiscoveryResponse.java @@ -47,6 +47,9 @@ public class ApiDiscoveryResponse extends BaseResponse { @SerializedName(ApiConstants.RESPONSE) @Param(description="api response fields", responseObject = ApiResponseResponse.class) private Set apiResponse; + @SerializedName(ApiConstants.TYPE) @Param(description="response field type") + private String type; + public ApiDiscoveryResponse(){ params = new HashSet(); apiResponse = new HashSet(); @@ -81,6 +84,7 @@ public class ApiDiscoveryResponse extends BaseResponse { this.isAsync = isAsync; } + public boolean getAsync() { return isAsync; } diff --git a/plugins/api/discovery/src/org/apache/cloudstack/api/response/ApiResponseResponse.java b/plugins/api/discovery/src/org/apache/cloudstack/api/response/ApiResponseResponse.java index b96295e1290..1433879a6ce 100644 --- a/plugins/api/discovery/src/org/apache/cloudstack/api/response/ApiResponseResponse.java +++ b/plugins/api/discovery/src/org/apache/cloudstack/api/response/ApiResponseResponse.java @@ -16,11 +16,14 @@ // under the License. package org.apache.cloudstack.api.response; -import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseResponse; +import java.util.HashSet; +import java.util.Set; + public class ApiResponseResponse extends BaseResponse { @SerializedName(ApiConstants.NAME) @Param(description="the name of the api response field") private String name; @@ -31,6 +34,9 @@ public class ApiResponseResponse extends BaseResponse { @SerializedName(ApiConstants.TYPE) @Param(description="response field type") private String type; + @SerializedName(ApiConstants.RESPONSE) @Param(description="api response fields") + private Set apiResponse; + public void setName(String name) { this.name = name; } @@ -42,4 +48,11 @@ public class ApiResponseResponse extends BaseResponse { public void setType(String type) { this.type = type; } + + public void addApiResponse(ApiResponseResponse childApiResponse) { + if(this.apiResponse == null) { + this.apiResponse = new HashSet(); + } + this.apiResponse.add(childApiResponse); + } } 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 b3714883964..2d7dbd18671 100755 --- a/plugins/api/discovery/src/org/apache/cloudstack/discovery/ApiDiscoveryServiceImpl.java +++ b/plugins/api/discovery/src/org/apache/cloudstack/discovery/ApiDiscoveryServiceImpl.java @@ -16,25 +16,14 @@ // under the License. package org.apache.cloudstack.discovery; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.annotation.PostConstruct; -import javax.ejb.Local; -import javax.inject.Inject; - +import com.cloud.serializer.Param; +import com.cloud.user.User; +import com.cloud.utils.ReflectUtil; +import com.cloud.utils.StringUtils; +import com.cloud.utils.component.PluggableService; +import com.google.gson.annotations.SerializedName; import org.apache.cloudstack.acl.APIChecker; -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.BaseAsyncCmd; -import org.apache.cloudstack.api.BaseAsyncCreateCmd; -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.BaseResponse; -import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.*; import org.apache.cloudstack.api.command.user.discovery.ListApisCmd; import org.apache.cloudstack.api.response.ApiDiscoveryResponse; import org.apache.cloudstack.api.response.ApiParameterResponse; @@ -43,12 +32,11 @@ import org.apache.cloudstack.api.response.ListResponse; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.serializer.Param; -import com.cloud.user.User; -import com.cloud.utils.ReflectUtil; -import com.cloud.utils.StringUtils; -import com.cloud.utils.component.PluggableService; -import com.google.gson.annotations.SerializedName; +import javax.annotation.PostConstruct; +import javax.ejb.Local; +import javax.inject.Inject; +import java.lang.reflect.Field; +import java.util.*; @Component @Local(value = ApiDiscoveryService.class) @@ -69,9 +57,9 @@ public class ApiDiscoveryServiceImpl implements ApiDiscoveryService { long startTime = System.nanoTime(); s_apiNameDiscoveryResponseMap = new HashMap(); Set> cmdClasses = new HashSet>(); - for(PluggableService service: _services) { + for(PluggableService service: _services) { s_logger.debug(String.format("getting api commands of service: %s", service.getClass().getName())); - cmdClasses.addAll(service.getCommands()); + cmdClasses.addAll(service.getCommands()); } cmdClasses.addAll(this.getCommands()); cacheResponseMap(cmdClasses); @@ -80,72 +68,39 @@ public class ApiDiscoveryServiceImpl implements ApiDiscoveryService { } } - protected void cacheResponseMap(Set> cmdClasses) { + protected Map> cacheResponseMap(Set> cmdClasses) { Map> responseApiNameListMap = new HashMap>(); for(Class cmdClass: cmdClasses) { APICommand apiCmdAnnotation = cmdClass.getAnnotation(APICommand.class); - if (apiCmdAnnotation == null) + if (apiCmdAnnotation == null) { apiCmdAnnotation = cmdClass.getSuperclass().getAnnotation(APICommand.class); + } if (apiCmdAnnotation == null || !apiCmdAnnotation.includeInApiDoc() - || apiCmdAnnotation.name().isEmpty()) + || apiCmdAnnotation.name().isEmpty()) { continue; + } String apiName = apiCmdAnnotation.name(); + ApiDiscoveryResponse response = getCmdRequestMap(cmdClass, apiCmdAnnotation); + String responseName = apiCmdAnnotation.responseObject().getName(); if (!responseName.contains("SuccessResponse")) { - if (!responseApiNameListMap.containsKey(responseName)) + if (!responseApiNameListMap.containsKey(responseName)) { responseApiNameListMap.put(responseName, new ArrayList()); + } responseApiNameListMap.get(responseName).add(apiName); } - ApiDiscoveryResponse response = new ApiDiscoveryResponse(); - response.setName(apiName); - response.setDescription(apiCmdAnnotation.description()); - if (!apiCmdAnnotation.since().isEmpty()) - response.setSince(apiCmdAnnotation.since()); response.setRelated(responseName); + Field[] responseFields = apiCmdAnnotation.responseObject().getDeclaredFields(); for(Field responseField: responseFields) { - SerializedName serializedName = responseField.getAnnotation(SerializedName.class); - if(serializedName != null) { - ApiResponseResponse responseResponse = new ApiResponseResponse(); - responseResponse.setName(serializedName.value()); - Param param = responseField.getAnnotation(Param.class); - if (param != null) - responseResponse.setDescription(param.description()); - responseResponse.setType(responseField.getType().getSimpleName().toLowerCase()); - response.addApiResponse(responseResponse); - } + ApiResponseResponse responseResponse = getFieldResponseMap(responseField); + response.addApiResponse(responseResponse); } - Set fields = ReflectUtil.getAllFieldsForClass(cmdClass, - new Class[]{BaseCmd.class, BaseAsyncCmd.class, BaseAsyncCreateCmd.class}); - - boolean isAsync = ReflectUtil.isCmdClassAsync(cmdClass, - new Class[] {BaseAsyncCmd.class, BaseAsyncCreateCmd.class}); - - response.setAsync(isAsync); - - for(Field field: fields) { - Parameter parameterAnnotation = field.getAnnotation(Parameter.class); - if (parameterAnnotation != null - && parameterAnnotation.expose() - && parameterAnnotation.includeInApiDoc()) { - - ApiParameterResponse paramResponse = new ApiParameterResponse(); - paramResponse.setName(parameterAnnotation.name()); - paramResponse.setDescription(parameterAnnotation.description()); - paramResponse.setType(parameterAnnotation.type().toString().toLowerCase()); - paramResponse.setLength(parameterAnnotation.length()); - paramResponse.setRequired(parameterAnnotation.required()); - if (!parameterAnnotation.since().isEmpty()) - paramResponse.setSince(parameterAnnotation.since()); - paramResponse.setRelated(parameterAnnotation.entityType()[0].getName()); - response.addParam(paramResponse); - } - } response.setObjectName("api"); s_apiNameDiscoveryResponseMap.put(apiName, response); } @@ -173,6 +128,76 @@ public class ApiDiscoveryServiceImpl implements ApiDiscoveryService { } s_apiNameDiscoveryResponseMap.put(apiName, response); } + return responseApiNameListMap; + } + + private ApiResponseResponse getFieldResponseMap(Field responseField) { + ApiResponseResponse responseResponse = new ApiResponseResponse(); + SerializedName serializedName = responseField.getAnnotation(SerializedName.class); + Param param = responseField.getAnnotation(Param.class); + if (serializedName != null && param != null) { + responseResponse.setName(serializedName.value()); + responseResponse.setDescription(param.description()); + responseResponse.setType(responseField.getType().getSimpleName().toLowerCase()); + //If response is not of primitive type - we have a nested entity + Class fieldClass = param.responseObject(); + if (fieldClass != null) { + Class superClass = fieldClass.getSuperclass(); + if (superClass != null) { + String superName = superClass.getName(); + if (superName.equals(BaseResponse.class.getName())) { + Field[] fields = fieldClass.getDeclaredFields(); + for (Field field : fields) { + ApiResponseResponse innerResponse = getFieldResponseMap(field); + if (innerResponse != null) { + responseResponse.addApiResponse(innerResponse); + } + } + } + } + } + } + return responseResponse; + } + + private ApiDiscoveryResponse getCmdRequestMap(Class cmdClass, APICommand apiCmdAnnotation) { + String apiName = apiCmdAnnotation.name(); + ApiDiscoveryResponse response = new ApiDiscoveryResponse(); + response.setName(apiName); + response.setDescription(apiCmdAnnotation.description()); + if (!apiCmdAnnotation.since().isEmpty()) { + response.setSince(apiCmdAnnotation.since()); + } + + + Set fields = ReflectUtil.getAllFieldsForClass(cmdClass, + new Class[]{BaseCmd.class, BaseAsyncCmd.class, BaseAsyncCreateCmd.class}); + + boolean isAsync = ReflectUtil.isCmdClassAsync(cmdClass, + new Class[]{BaseAsyncCmd.class, BaseAsyncCreateCmd.class}); + + response.setAsync(isAsync); + + for(Field field: fields) { + Parameter parameterAnnotation = field.getAnnotation(Parameter.class); + if (parameterAnnotation != null + && parameterAnnotation.expose() + && parameterAnnotation.includeInApiDoc()) { + + ApiParameterResponse paramResponse = new ApiParameterResponse(); + paramResponse.setName(parameterAnnotation.name()); + paramResponse.setDescription(parameterAnnotation.description()); + paramResponse.setType(parameterAnnotation.type().toString().toLowerCase()); + paramResponse.setLength(parameterAnnotation.length()); + paramResponse.setRequired(parameterAnnotation.required()); + if (!parameterAnnotation.since().isEmpty()) { + paramResponse.setSince(parameterAnnotation.since()); + } + paramResponse.setRelated(parameterAnnotation.entityType()[0].getName()); + response.addParam(paramResponse); + } + } + return response; } @Override diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/manager/AddBaremetalHostCmd.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/manager/AddBaremetalHostCmd.java index f07b212173f..8d459028a17 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/manager/AddBaremetalHostCmd.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/manager/AddBaremetalHostCmd.java @@ -14,35 +14,35 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -// +// // Automatically generated by addcopyright.py at 01/29/2013 -package com.cloud.baremetal.manager; - +package com.cloud.baremetal.manager; + import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.command.admin.host.AddHostCmd; import org.apache.cloudstack.api.response.HostResponse; -@APICommand(name="addBaremetalHost", description="add a baremetal host", responseObject = HostResponse.class) +@APICommand(name="addBaremetalHost", description="add a baremetal host", responseObject = HostResponse.class) public class AddBaremetalHostCmd extends AddHostCmd { - - @Parameter(name=ApiConstants.IP_ADDRESS, type=CommandType.STRING, description="ip address intentionally allocated to this host after provisioning") - private String vmIpAddress; - - public AddBaremetalHostCmd() { - } - + + @Parameter(name=ApiConstants.IP_ADDRESS, type=CommandType.STRING, description="ip address intentionally allocated to this host after provisioning") + private String vmIpAddress; + + public AddBaremetalHostCmd() { + } + @Override - public void execute(){ - this.getFullUrlParams().put(ApiConstants.BAREMETAL_DISCOVER_NAME, BareMetalDiscoverer.class.getName()); - super.execute(); - } - - public String getVmIpAddress() { - return vmIpAddress; - } - - public void setVmIpAddress(String vmIpAddress) { - this.vmIpAddress = vmIpAddress; - } -} + public void execute(){ + this.getFullUrlParams().put(ApiConstants.BAREMETAL_DISCOVER_NAME, BareMetalDiscoverer.class.getName()); + super.execute(); + } + + public String getVmIpAddress() { + return vmIpAddress; + } + + public void setVmIpAddress(String vmIpAddress) { + this.vmIpAddress = vmIpAddress; + } +} diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/manager/BareMetalDiscoverer.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/manager/BareMetalDiscoverer.java index 28c83753c09..edb5dea8ca5 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/manager/BareMetalDiscoverer.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/manager/BareMetalDiscoverer.java @@ -202,7 +202,7 @@ public class BareMetalDiscoverer extends DiscovererBase implements Discoverer, R if (vmIp != null) { details.put(ApiConstants.IP_ADDRESS, vmIp); } - String isEchoScAgent = _configDao.getValue(Config.EnableBaremetalSecurityGroupAgentEcho.key()); + String isEchoScAgent = _configDao.getValue(Config.EnableBaremetalSecurityGroupAgentEcho.key()); details.put(BaremetalManager.EchoSecurityGroupAgent, isEchoScAgent); resources.put(resource, details); diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/manager/BaremetalManager.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/manager/BaremetalManager.java index 6467c945795..60edde3c70d 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/manager/BaremetalManager.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/manager/BaremetalManager.java @@ -22,7 +22,7 @@ import com.cloud.network.Network.Provider; import com.cloud.utils.component.Manager; import com.cloud.utils.component.PluggableService; -public interface BaremetalManager extends Manager, PluggableService { +public interface BaremetalManager extends Manager, PluggableService { public static final String EchoSecurityGroupAgent = "EchoSecurityGroupAgent"; public static final String ExternalBaremetalSystemUrl = "ExternalBaremetalSystemUrl"; public static final String DO_PXE = "doPxe"; diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/manager/BaremetalPlannerSelector.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/manager/BaremetalPlannerSelector.java index 9daee3f3fe7..45fbeb782ab 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/manager/BaremetalPlannerSelector.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/manager/BaremetalPlannerSelector.java @@ -1,39 +1,39 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.baremetal.manager; - -import java.util.Map; - -import javax.ejb.Local; -import javax.naming.ConfigurationException; - -import com.cloud.deploy.AbstractDeployPlannerSelector; -import com.cloud.deploy.DeployPlannerSelector; -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.vm.UserVmVO; -@Local(value = {DeployPlannerSelector.class}) -public class BaremetalPlannerSelector extends AbstractDeployPlannerSelector{ - - @Override - public String selectPlanner(UserVmVO vm) { - if (vm.getHypervisorType() == HypervisorType.BareMetal) { - return "BareMetalPlanner"; - } - return null; - } - -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.baremetal.manager; + +import java.util.Map; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; + +import com.cloud.deploy.AbstractDeployPlannerSelector; +import com.cloud.deploy.DeployPlannerSelector; +import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.vm.UserVmVO; +@Local(value = {DeployPlannerSelector.class}) +public class BaremetalPlannerSelector extends AbstractDeployPlannerSelector{ + + @Override + public String selectPlanner(UserVmVO vm) { + if (vm.getHypervisorType() == HypervisorType.BareMetal) { + return "BareMetalPlanner"; + } + return null; + } + +} diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/AddBaremetalKickStartPxeCmd.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/AddBaremetalKickStartPxeCmd.java index 596a86dac8f..8bcc7c13f62 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/AddBaremetalKickStartPxeCmd.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/AddBaremetalKickStartPxeCmd.java @@ -14,24 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -// +// // Automatically generated by addcopyright.py at 01/29/2013 -package com.cloud.baremetal.networkservice; - +package com.cloud.baremetal.networkservice; + import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseCmd.CommandType; import org.apache.cloudstack.api.Parameter; @APICommand(name="addBaremetalPxeKickStartServer", description="add a baremetal pxe server", responseObject = BaremetalPxeKickStartResponse.class) -public class AddBaremetalKickStartPxeCmd extends AddBaremetalPxeCmd { - @Parameter(name=ApiConstants.TFTP_DIR, type=CommandType.STRING, required = true, description="Tftp root directory of PXE server") - private String tftpDir; - - public String getTftpDir() { - return tftpDir; - } - - public void setTftpDir(String tftpDir) { - this.tftpDir = tftpDir; +public class AddBaremetalKickStartPxeCmd extends AddBaremetalPxeCmd { + @Parameter(name=ApiConstants.TFTP_DIR, type=CommandType.STRING, required = true, description="Tftp root directory of PXE server") + private String tftpDir; + + public String getTftpDir() { + return tftpDir; } -} + + public void setTftpDir(String tftpDir) { + this.tftpDir = tftpDir; + } +} diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BareMetalResourceBase.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BareMetalResourceBase.java index 4c99f6bf544..86e41fea070 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BareMetalResourceBase.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BareMetalResourceBase.java @@ -97,7 +97,7 @@ public class BareMetalResourceBase extends ManagerBase implements ServerResource protected String _mac; protected String _username; protected String _password; - protected String _ip; + protected String _ip; protected boolean _isEchoScAgent; protected IAgentControl _agentControl; protected Script2 _pingCommand; @@ -146,7 +146,7 @@ public class BareMetalResourceBase extends ManagerBase implements ServerResource _mac = (String) params.get(ApiConstants.HOST_MAC); _username = (String) params.get(ApiConstants.USERNAME); _password = (String) params.get(ApiConstants.PASSWORD); - _vmName = (String) params.get("vmName"); + _vmName = (String) params.get("vmName"); String echoScAgent = (String) params.get(BaremetalManager.EchoSecurityGroupAgent); if (_pod == null) { @@ -172,9 +172,9 @@ public class BareMetalResourceBase extends ManagerBase implements ServerResource if (_uuid == null) { throw new ConfigurationException("Unable to get the uuid"); - } - - if (echoScAgent != null) { + } + + if (echoScAgent != null) { _isEchoScAgent = Boolean.valueOf(echoScAgent); } @@ -416,9 +416,9 @@ public class BareMetalResourceBase extends ManagerBase implements ServerResource protected CheckNetworkAnswer execute(CheckNetworkCommand cmd) { return new CheckNetworkAnswer(cmd, true, "Success"); } - - protected Answer execute(SecurityGroupRulesCmd cmd) { - SecurityGroupHttpClient hc = new SecurityGroupHttpClient(); + + protected Answer execute(SecurityGroupRulesCmd cmd) { + SecurityGroupHttpClient hc = new SecurityGroupHttpClient(); return hc.call(cmd.getGuestIp(), cmd); } @@ -531,13 +531,13 @@ public class BareMetalResourceBase extends ManagerBase implements ServerResource if (!doScript(_powerOnCommand)) { return new StartAnswer(cmd, "IPMI power on failed"); } - } - - if (_isEchoScAgent) { - SecurityGroupHttpClient hc = new SecurityGroupHttpClient(); - boolean echoRet = hc.echo(vm.getNics()[0].getIp(), TimeUnit.MINUTES.toMillis(30), TimeUnit.MINUTES.toMillis(1)); + } + + if (_isEchoScAgent) { + SecurityGroupHttpClient hc = new SecurityGroupHttpClient(); + boolean echoRet = hc.echo(vm.getNics()[0].getIp(), TimeUnit.MINUTES.toMillis(30), TimeUnit.MINUTES.toMillis(1)); if (!echoRet) { - return new StartAnswer(cmd, String.format("Call security group agent on vm[%s] timeout", vm.getNics()[0].getIp())); + return new StartAnswer(cmd, String.format("Call security group agent on vm[%s] timeout", vm.getNics()[0].getIp())); } } diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetaNetworkGuru.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetaNetworkGuru.java index bec6e38b7c8..6d14e3f1a0c 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetaNetworkGuru.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetaNetworkGuru.java @@ -14,10 +14,10 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -// +// // Automatically generated by addcopyright.py at 01/29/2013 -package com.cloud.baremetal.networkservice; - +package com.cloud.baremetal.networkservice; + import java.net.URI; import javax.ejb.Local; @@ -56,11 +56,11 @@ import com.cloud.vm.NicProfile; import com.cloud.vm.ReservationContext; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; - -@Local(value = { NetworkGuru.class }) -public class BaremetaNetworkGuru extends DirectPodBasedNetworkGuru { - private static final Logger s_logger = Logger.getLogger(BaremetaNetworkGuru.class); - @Inject + +@Local(value = { NetworkGuru.class }) +public class BaremetaNetworkGuru extends DirectPodBasedNetworkGuru { + private static final Logger s_logger = Logger.getLogger(BaremetaNetworkGuru.class); + @Inject private HostDao _hostDao; @Inject DataCenterDao _dcDao; @@ -73,101 +73,101 @@ public class BaremetaNetworkGuru extends DirectPodBasedNetworkGuru { @Inject NetworkOfferingDao _networkOfferingDao; @Inject - PodVlanMapDao _podVlanDao; - - @Override - public void reserve(NicProfile nic, Network network, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) - throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException, ConcurrentOperationException { - if (dest.getHost().getHypervisorType() != HypervisorType.BareMetal) { - super.reserve(nic, network, vm, dest, context); - return; - } - - HostVO host = _hostDao.findById(dest.getHost().getId()); - _hostDao.loadDetails(host); - String intentIp = host.getDetail(ApiConstants.IP_ADDRESS); - if (intentIp == null) { - super.reserve(nic, network, vm, dest, context); - return; - } - - String oldIp = nic.getIp4Address(); - boolean getNewIp = false; - if (oldIp == null) { - getNewIp = true; - } else { - // we need to get a new ip address if we try to deploy a vm in a - // different pod - IPAddressVO ipVO = _ipAddressDao.findByIpAndSourceNetworkId(network.getId(), oldIp); - if (ipVO != null) { - PodVlanMapVO mapVO = _podVlanDao.listPodVlanMapsByVlan(ipVO.getVlanId()); - if (mapVO.getPodId() != dest.getPod().getId()) { - Transaction txn = Transaction.currentTxn(); - txn.start(); - - // release the old ip here - _networkMgr.markIpAsUnavailable(ipVO.getId()); - _ipAddressDao.unassignIpAddress(ipVO.getId()); - - txn.commit(); - - nic.setIp4Address(null); - getNewIp = true; - } - } - } - - if (getNewIp) { - // we don't set reservationStrategy to Create because we need this - // method to be called again for the case when vm fails to deploy in - // Pod1, and we try to redeploy it in Pod2 - getBaremetalIp(nic, dest.getPod(), vm, network, intentIp); - } - - DataCenter dc = _dcDao.findById(network.getDataCenterId()); - nic.setDns1(dc.getDns1()); - nic.setDns2(dc.getDns2()); - - /* - * Pod pod = dest.getPod(); Pair ip = - * _dcDao.allocatePrivateIpAddress(dest.getDataCenter().getId(), - * dest.getPod().getId(), nic.getId(), context.getReservationId(), - * intentIp); if (ip == null) { throw new - * InsufficientAddressCapacityException - * ("Unable to get a management ip address", Pod.class, pod.getId()); } - * - * nic.setIp4Address(ip.first()); - * nic.setMacAddress(NetUtils.long2Mac(NetUtils - * .createSequenceBasedMacAddress(ip.second()))); - * nic.setGateway(pod.getGateway()); nic.setFormat(AddressFormat.Ip4); - * String netmask = NetUtils.getCidrNetmask(pod.getCidrSize()); - * nic.setNetmask(netmask); - * nic.setBroadcastType(BroadcastDomainType.Native); - * nic.setBroadcastUri(null); nic.setIsolationUri(null); - */ - - s_logger.debug("Allocated a nic " + nic + " for " + vm); - } + PodVlanMapDao _podVlanDao; - private void getBaremetalIp(NicProfile nic, Pod pod, VirtualMachineProfile vm, Network network, String requiredIp) - throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException, ConcurrentOperationException { - DataCenter dc = _dcDao.findById(pod.getDataCenterId()); - if (nic.getIp4Address() == null) { - s_logger.debug(String.format("Requiring ip address: %s", nic.getIp4Address())); - PublicIp ip = _networkMgr.assignPublicIpAddress(dc.getId(), pod.getId(), vm.getOwner(), VlanType.DirectAttached, network.getId(), requiredIp, false); - nic.setIp4Address(ip.getAddress().toString()); - nic.setFormat(AddressFormat.Ip4); - nic.setGateway(ip.getGateway()); - nic.setNetmask(ip.getNetmask()); - if (ip.getVlanTag() != null && ip.getVlanTag().equalsIgnoreCase(Vlan.UNTAGGED)) { - nic.setIsolationUri(URI.create("ec2://" + Vlan.UNTAGGED)); - nic.setBroadcastUri(URI.create("vlan://" + Vlan.UNTAGGED)); - nic.setBroadcastType(BroadcastDomainType.Native); - } - nic.setReservationId(String.valueOf(ip.getVlanTag())); - nic.setMacAddress(ip.getMacAddress()); - } - nic.setDns1(dc.getDns1()); - nic.setDns2(dc.getDns2()); - } -} + @Override + public void reserve(NicProfile nic, Network network, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) + throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException, ConcurrentOperationException { + if (dest.getHost().getHypervisorType() != HypervisorType.BareMetal) { + super.reserve(nic, network, vm, dest, context); + return; + } + + HostVO host = _hostDao.findById(dest.getHost().getId()); + _hostDao.loadDetails(host); + String intentIp = host.getDetail(ApiConstants.IP_ADDRESS); + if (intentIp == null) { + super.reserve(nic, network, vm, dest, context); + return; + } + + String oldIp = nic.getIp4Address(); + boolean getNewIp = false; + if (oldIp == null) { + getNewIp = true; + } else { + // we need to get a new ip address if we try to deploy a vm in a + // different pod + IPAddressVO ipVO = _ipAddressDao.findByIpAndSourceNetworkId(network.getId(), oldIp); + if (ipVO != null) { + PodVlanMapVO mapVO = _podVlanDao.listPodVlanMapsByVlan(ipVO.getVlanId()); + if (mapVO.getPodId() != dest.getPod().getId()) { + Transaction txn = Transaction.currentTxn(); + txn.start(); + + // release the old ip here + _networkMgr.markIpAsUnavailable(ipVO.getId()); + _ipAddressDao.unassignIpAddress(ipVO.getId()); + + txn.commit(); + + nic.setIp4Address(null); + getNewIp = true; + } + } + } + + if (getNewIp) { + // we don't set reservationStrategy to Create because we need this + // method to be called again for the case when vm fails to deploy in + // Pod1, and we try to redeploy it in Pod2 + getBaremetalIp(nic, dest.getPod(), vm, network, intentIp); + } + + DataCenter dc = _dcDao.findById(network.getDataCenterId()); + nic.setDns1(dc.getDns1()); + nic.setDns2(dc.getDns2()); + + /* + * Pod pod = dest.getPod(); Pair ip = + * _dcDao.allocatePrivateIpAddress(dest.getDataCenter().getId(), + * dest.getPod().getId(), nic.getId(), context.getReservationId(), + * intentIp); if (ip == null) { throw new + * InsufficientAddressCapacityException + * ("Unable to get a management ip address", Pod.class, pod.getId()); } + * + * nic.setIp4Address(ip.first()); + * nic.setMacAddress(NetUtils.long2Mac(NetUtils + * .createSequenceBasedMacAddress(ip.second()))); + * nic.setGateway(pod.getGateway()); nic.setFormat(AddressFormat.Ip4); + * String netmask = NetUtils.getCidrNetmask(pod.getCidrSize()); + * nic.setNetmask(netmask); + * nic.setBroadcastType(BroadcastDomainType.Native); + * nic.setBroadcastUri(null); nic.setIsolationUri(null); + */ + + s_logger.debug("Allocated a nic " + nic + " for " + vm); + } + + private void getBaremetalIp(NicProfile nic, Pod pod, VirtualMachineProfile vm, Network network, String requiredIp) + throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException, ConcurrentOperationException { + DataCenter dc = _dcDao.findById(pod.getDataCenterId()); + if (nic.getIp4Address() == null) { + s_logger.debug(String.format("Requiring ip address: %s", nic.getIp4Address())); + PublicIp ip = _networkMgr.assignPublicIpAddress(dc.getId(), pod.getId(), vm.getOwner(), VlanType.DirectAttached, network.getId(), requiredIp, false); + nic.setIp4Address(ip.getAddress().toString()); + nic.setFormat(AddressFormat.Ip4); + nic.setGateway(ip.getGateway()); + nic.setNetmask(ip.getNetmask()); + if (ip.getVlanTag() != null && ip.getVlanTag().equalsIgnoreCase(Vlan.UNTAGGED)) { + nic.setIsolationUri(URI.create("ec2://" + Vlan.UNTAGGED)); + nic.setBroadcastUri(URI.create("vlan://" + Vlan.UNTAGGED)); + nic.setBroadcastType(BroadcastDomainType.Native); + } + nic.setReservationId(String.valueOf(ip.getVlanTag())); + nic.setMacAddress(ip.getMacAddress()); + } + nic.setDns1(dc.getDns1()); + nic.setDns2(dc.getDns2()); + } +} 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 58c6e862d9f..7a7a5153e5c 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartPxeResource.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartPxeResource.java @@ -14,10 +14,10 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -// +// // Automatically generated by addcopyright.py at 01/29/2013 -package com.cloud.baremetal.networkservice; - +package com.cloud.baremetal.networkservice; + import java.util.HashMap; import java.util.List; import java.util.Map; @@ -37,166 +37,166 @@ import com.cloud.utils.script.Script; import com.cloud.utils.ssh.SSHCmdHelper; import com.cloud.vm.VirtualMachine.State; import com.trilead.ssh2.SCPClient; - -public class BaremetalKickStartPxeResource extends BaremetalPxeResourceBase { - private static final Logger s_logger = Logger.getLogger(BaremetalKickStartPxeResource.class); - private static final String _name = "BaremetalKickStartPxeResource"; - String _tftpDir; - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - super.configure(name, params); - _tftpDir = (String) params.get(BaremetalPxeService.PXE_PARAM_TFTP_DIR); - if (_tftpDir == null) { - throw new ConfigurationException("No tftp directory specified"); - } - - com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(_ip, 22); - - s_logger.debug(String.format("Trying to connect to kickstart PXE server(IP=%1$s, username=%2$s, password=%3$s", _ip, _username, "******")); - try { - sshConnection.connect(null, 60000, 60000); - if (!sshConnection.authenticateWithPassword(_username, _password)) { - s_logger.debug("SSH Failed to authenticate"); - throw new ConfigurationException(String.format("Cannot connect to kickstart PXE server(IP=%1$s, username=%2$s, password=%3$s", _ip, _username, - "******")); - } - - String cmd = String.format("[ -f /%1$s/pxelinux.0 ]", _tftpDir); - if (!SSHCmdHelper.sshExecuteCmd(sshConnection, cmd)) { - throw new ConfigurationException("Miss files in TFTP directory at " + _tftpDir + " check if pxelinux.0 are here"); - } - - SCPClient scp = new SCPClient(sshConnection); - String prepareScript = "scripts/network/ping/prepare_kickstart_bootfile.py"; - String prepareScriptPath = Script.findScript("", prepareScript); - if (prepareScriptPath == null) { - throw new ConfigurationException("Can not find prepare_kickstart_bootfile.py at " + prepareScript); - } - scp.put(prepareScriptPath, "/usr/bin/", "0755"); - String cpScript = "scripts/network/ping/prepare_kickstart_kernel_initrd.py"; - String cpScriptPath = Script.findScript("", cpScript); - if (cpScriptPath == null) { - throw new ConfigurationException("Can not find prepare_kickstart_kernel_initrd.py at " + cpScript); - } - scp.put(cpScriptPath, "/usr/bin/", "0755"); - - String userDataScript = "scripts/network/ping/baremetal_user_data.py"; - String userDataScriptPath = Script.findScript("", userDataScript); - if (userDataScriptPath == null) { - throw new ConfigurationException("Can not find baremetal_user_data.py at " + userDataScript); - } - scp.put(userDataScriptPath, "/usr/bin/", "0755"); - - return true; - } catch (Exception e) { - throw new CloudRuntimeException(e); - } finally { - if (sshConnection != null) { - sshConnection.close(); - } - } - } - - @Override - public PingCommand getCurrentStatus(long id) { - com.trilead.ssh2.Connection sshConnection = SSHCmdHelper.acquireAuthorizedConnection(_ip, _username, _password); - if (sshConnection == null) { - return null; - } else { - SSHCmdHelper.releaseSshConnection(sshConnection); - return new PingRoutingCommand(getType(), id, new HashMap()); - } - } - - private Answer execute(VmDataCommand cmd) { - com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(_ip, 22); - try { - List vmData = cmd.getVmData(); - StringBuilder sb = new StringBuilder(); - for (String[] data : vmData) { - String folder = data[0]; - String file = data[1]; - String contents = (data[2] == null) ? "none" : data[2]; - sb.append(cmd.getVmIpAddress()); - sb.append(","); - sb.append(folder); - sb.append(","); - sb.append(file); - sb.append(","); - sb.append(contents); - sb.append(";"); - } - String arg = StringUtils.stripEnd(sb.toString(), ";"); - - sshConnection.connect(null, 60000, 60000); - if (!sshConnection.authenticateWithPassword(_username, _password)) { - s_logger.debug("SSH Failed to authenticate"); - throw new ConfigurationException(String.format("Cannot connect to PING PXE server(IP=%1$s, username=%2$s, password=%3$s", _ip, _username, - _password)); - } - - String script = String.format("python /usr/bin/baremetal_user_data.py '%s'", arg); - if (!SSHCmdHelper.sshExecuteCmd(sshConnection, script)) { - return new Answer(cmd, false, "Failed to add user data, command:" + script); - } - - return new Answer(cmd, true, "Success"); - } catch (Exception e){ - s_logger.debug("Prepare for creating baremetal template failed", e); - return new Answer(cmd, false, e.getMessage()); - } finally { - if (sshConnection != null) { - sshConnection.close(); - } - } - } - - @Override - public Answer executeRequest(Command cmd) { - if (cmd instanceof PrepareKickstartPxeServerCommand) { - return execute((PrepareKickstartPxeServerCommand) cmd); - } else if (cmd instanceof VmDataCommand) { - return execute((VmDataCommand)cmd); - } else { - return super.executeRequest(cmd); - } - } - - private Answer execute(PrepareKickstartPxeServerCommand cmd) { - com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(_ip, 22); - try { - sshConnection.connect(null, 60000, 60000); - if (!sshConnection.authenticateWithPassword(_username, _password)) { - s_logger.debug("SSH Failed to authenticate"); - throw new ConfigurationException(String.format("Cannot connect to PING PXE server(IP=%1$s, username=%2$s, password=%3$s", _ip, _username, - _password)); +public class BaremetalKickStartPxeResource extends BaremetalPxeResourceBase { + private static final Logger s_logger = Logger.getLogger(BaremetalKickStartPxeResource.class); + private static final String _name = "BaremetalKickStartPxeResource"; + String _tftpDir; + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + super.configure(name, params); + _tftpDir = (String) params.get(BaremetalPxeService.PXE_PARAM_TFTP_DIR); + if (_tftpDir == null) { + throw new ConfigurationException("No tftp directory specified"); + } + + com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(_ip, 22); + + s_logger.debug(String.format("Trying to connect to kickstart PXE server(IP=%1$s, username=%2$s, password=%3$s", _ip, _username, "******")); + try { + sshConnection.connect(null, 60000, 60000); + if (!sshConnection.authenticateWithPassword(_username, _password)) { + s_logger.debug("SSH Failed to authenticate"); + throw new ConfigurationException(String.format("Cannot connect to kickstart PXE server(IP=%1$s, username=%2$s, password=%3$s", _ip, _username, + "******")); } - + + String cmd = String.format("[ -f /%1$s/pxelinux.0 ]", _tftpDir); + if (!SSHCmdHelper.sshExecuteCmd(sshConnection, cmd)) { + throw new ConfigurationException("Miss files in TFTP directory at " + _tftpDir + " check if pxelinux.0 are here"); + } + + SCPClient scp = new SCPClient(sshConnection); + String prepareScript = "scripts/network/ping/prepare_kickstart_bootfile.py"; + String prepareScriptPath = Script.findScript("", prepareScript); + if (prepareScriptPath == null) { + throw new ConfigurationException("Can not find prepare_kickstart_bootfile.py at " + prepareScript); + } + scp.put(prepareScriptPath, "/usr/bin/", "0755"); + + String cpScript = "scripts/network/ping/prepare_kickstart_kernel_initrd.py"; + String cpScriptPath = Script.findScript("", cpScript); + if (cpScriptPath == null) { + throw new ConfigurationException("Can not find prepare_kickstart_kernel_initrd.py at " + cpScript); + } + scp.put(cpScriptPath, "/usr/bin/", "0755"); + + String userDataScript = "scripts/network/ping/baremetal_user_data.py"; + String userDataScriptPath = Script.findScript("", userDataScript); + if (userDataScriptPath == null) { + throw new ConfigurationException("Can not find baremetal_user_data.py at " + userDataScript); + } + scp.put(userDataScriptPath, "/usr/bin/", "0755"); + + return true; + } catch (Exception e) { + throw new CloudRuntimeException(e); + } finally { + if (sshConnection != null) { + sshConnection.close(); + } + } + } + + @Override + public PingCommand getCurrentStatus(long id) { + com.trilead.ssh2.Connection sshConnection = SSHCmdHelper.acquireAuthorizedConnection(_ip, _username, _password); + if (sshConnection == null) { + return null; + } else { + SSHCmdHelper.releaseSshConnection(sshConnection); + return new PingRoutingCommand(getType(), id, new HashMap()); + } + } + + private Answer execute(VmDataCommand cmd) { + com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(_ip, 22); + try { + List vmData = cmd.getVmData(); + StringBuilder sb = new StringBuilder(); + for (String[] data : vmData) { + String folder = data[0]; + String file = data[1]; + String contents = (data[2] == null) ? "none" : data[2]; + sb.append(cmd.getVmIpAddress()); + sb.append(","); + sb.append(folder); + sb.append(","); + sb.append(file); + sb.append(","); + sb.append(contents); + sb.append(";"); + } + String arg = StringUtils.stripEnd(sb.toString(), ";"); + + sshConnection.connect(null, 60000, 60000); + if (!sshConnection.authenticateWithPassword(_username, _password)) { + s_logger.debug("SSH Failed to authenticate"); + throw new ConfigurationException(String.format("Cannot connect to PING PXE server(IP=%1$s, username=%2$s, password=%3$s", _ip, _username, + _password)); + } + + String script = String.format("python /usr/bin/baremetal_user_data.py '%s'", arg); + if (!SSHCmdHelper.sshExecuteCmd(sshConnection, script)) { + return new Answer(cmd, false, "Failed to add user data, command:" + script); + } + + return new Answer(cmd, true, "Success"); + } catch (Exception e){ + s_logger.debug("Prepare for creating baremetal template failed", e); + return new Answer(cmd, false, e.getMessage()); + } finally { + if (sshConnection != null) { + sshConnection.close(); + } + } + } + + @Override + public Answer executeRequest(Command cmd) { + if (cmd instanceof PrepareKickstartPxeServerCommand) { + return execute((PrepareKickstartPxeServerCommand) cmd); + } else if (cmd instanceof VmDataCommand) { + return execute((VmDataCommand)cmd); + } else { + return super.executeRequest(cmd); + } + } + + private Answer execute(PrepareKickstartPxeServerCommand cmd) { + com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(_ip, 22); + try { + sshConnection.connect(null, 60000, 60000); + if (!sshConnection.authenticateWithPassword(_username, _password)) { + s_logger.debug("SSH Failed to authenticate"); + throw new ConfigurationException(String.format("Cannot connect to PING PXE server(IP=%1$s, username=%2$s, password=%3$s", _ip, _username, + _password)); + } + String copyTo = String.format("%s/%s", _tftpDir, cmd.getTemplateUuid()); - String script = String.format("python /usr/bin/prepare_kickstart_kernel_initrd.py %s %s %s", cmd.getKernel(), cmd.getInitrd(), copyTo); - - if (!SSHCmdHelper.sshExecuteCmd(sshConnection, script)) { - return new Answer(cmd, false, "prepare kickstart at pxe server " + _ip + " failed, command:" + script); - } - - String kernelPath = String.format("%s/vmlinuz", cmd.getTemplateUuid()); - String initrdPath = String.format("%s/initrd.img", cmd.getTemplateUuid()); - script = String.format("python /usr/bin/prepare_kickstart_bootfile.py %s %s %s %s %s %s", _tftpDir, cmd.getMac(), kernelPath, initrdPath, cmd.getKsFile(), cmd.getMac()); - if (!SSHCmdHelper.sshExecuteCmd(sshConnection, script)) { - return new Answer(cmd, false, "prepare kickstart at pxe server " + _ip + " failed, command:" + script); - } - - s_logger.debug("Prepare kickstart PXE server successfully"); - return new Answer(cmd, true, "Success"); - } catch (Exception e){ - s_logger.debug("Prepare for kickstart server failed", e); - return new Answer(cmd, false, e.getMessage()); - } finally { - if (sshConnection != null) { - sshConnection.close(); - } - } - } -} + String script = String.format("python /usr/bin/prepare_kickstart_kernel_initrd.py %s %s %s", cmd.getKernel(), cmd.getInitrd(), copyTo); + + if (!SSHCmdHelper.sshExecuteCmd(sshConnection, script)) { + return new Answer(cmd, false, "prepare kickstart at pxe server " + _ip + " failed, command:" + script); + } + + String kernelPath = String.format("%s/vmlinuz", cmd.getTemplateUuid()); + String initrdPath = String.format("%s/initrd.img", cmd.getTemplateUuid()); + script = String.format("python /usr/bin/prepare_kickstart_bootfile.py %s %s %s %s %s %s", _tftpDir, cmd.getMac(), kernelPath, initrdPath, cmd.getKsFile(), cmd.getMac()); + if (!SSHCmdHelper.sshExecuteCmd(sshConnection, script)) { + return new Answer(cmd, false, "prepare kickstart at pxe server " + _ip + " failed, command:" + script); + } + + s_logger.debug("Prepare kickstart PXE server successfully"); + return new Answer(cmd, true, "Success"); + } catch (Exception e){ + s_logger.debug("Prepare for kickstart server failed", e); + return new Answer(cmd, false, e.getMessage()); + } finally { + if (sshConnection != null) { + sshConnection.close(); + } + } + } +} diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartServiceImpl.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartServiceImpl.java index 8a5ac78729e..49582b07862 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartServiceImpl.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartServiceImpl.java @@ -14,87 +14,87 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -// +// // Automatically generated by addcopyright.py at 01/29/2013 -package com.cloud.baremetal.networkservice; - -import java.net.URI; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.ejb.Local; +package com.cloud.baremetal.networkservice; + +import java.net.URI; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ejb.Local; import javax.inject.Inject; - -import org.apache.log4j.Logger; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.baremetal.IpmISetBootDevCommand; -import com.cloud.agent.api.baremetal.IpmISetBootDevCommand.BootDev; -import com.cloud.baremetal.database.BaremetalPxeDao; -import com.cloud.baremetal.database.BaremetalPxeVO; -import com.cloud.baremetal.networkservice.BaremetalPxeManager.BaremetalPxeType; -import com.cloud.deploy.DeployDestination; -import com.cloud.host.Host; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDetailsDao; -import com.cloud.network.PhysicalNetworkServiceProvider; -import com.cloud.network.dao.NetworkDao; + +import org.apache.log4j.Logger; + +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.baremetal.IpmISetBootDevCommand; +import com.cloud.agent.api.baremetal.IpmISetBootDevCommand.BootDev; +import com.cloud.baremetal.database.BaremetalPxeDao; +import com.cloud.baremetal.database.BaremetalPxeVO; +import com.cloud.baremetal.networkservice.BaremetalPxeManager.BaremetalPxeType; +import com.cloud.deploy.DeployDestination; +import com.cloud.host.Host; +import com.cloud.host.HostVO; +import com.cloud.host.dao.HostDetailsDao; +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.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.ServerResource; -import com.cloud.storage.VMTemplateVO; -import com.cloud.storage.dao.VMTemplateDao; -import com.cloud.uservm.UserVm; -import com.cloud.utils.db.DB; -import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteriaService; -import com.cloud.utils.db.Transaction; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.vm.NicProfile; -import com.cloud.vm.ReservationContext; -import com.cloud.vm.UserVmVO; -import com.cloud.vm.VirtualMachineProfile; - -@Local(value = BaremetalPxeService.class) -public class BaremetalKickStartServiceImpl extends BareMetalPxeServiceBase implements BaremetalPxeService { - private static final Logger s_logger = Logger.getLogger(BaremetalKickStartServiceImpl.class); - @Inject - ResourceManager _resourceMgr; - @Inject - PhysicalNetworkDao _physicalNetworkDao; - @Inject - PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; - @Inject - HostDetailsDao _hostDetailsDao; - @Inject - BaremetalPxeDao _pxeDao; +import com.cloud.resource.ResourceManager; +import com.cloud.resource.ServerResource; +import com.cloud.storage.VMTemplateVO; +import com.cloud.storage.dao.VMTemplateDao; +import com.cloud.uservm.UserVm; +import com.cloud.utils.db.DB; +import com.cloud.utils.db.SearchCriteria.Op; +import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.SearchCriteriaService; +import com.cloud.utils.db.Transaction; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.vm.NicProfile; +import com.cloud.vm.ReservationContext; +import com.cloud.vm.UserVmVO; +import com.cloud.vm.VirtualMachineProfile; + +@Local(value = BaremetalPxeService.class) +public class BaremetalKickStartServiceImpl extends BareMetalPxeServiceBase implements BaremetalPxeService { + private static final Logger s_logger = Logger.getLogger(BaremetalKickStartServiceImpl.class); @Inject - NetworkDao _nwDao; + ResourceManager _resourceMgr; + @Inject + PhysicalNetworkDao _physicalNetworkDao; + @Inject + PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; + @Inject + HostDetailsDao _hostDetailsDao; + @Inject + BaremetalPxeDao _pxeDao; + @Inject + NetworkDao _nwDao; @Inject VMTemplateDao _tmpDao; - - @Override + + @Override public boolean prepare(VirtualMachineProfile profile, NicProfile nic, DeployDestination dest, ReservationContext context) { NetworkVO nwVO = _nwDao.findById(nic.getNetworkId()); - SearchCriteriaService sc = SearchCriteria2.create(BaremetalPxeVO.class); + SearchCriteriaService sc = SearchCriteria2.create(BaremetalPxeVO.class); sc.addAnd(sc.getEntity().getDeviceType(), Op.EQ, BaremetalPxeType.KICK_START.toString()); - sc.addAnd(sc.getEntity().getPhysicalNetworkId(), Op.EQ, nwVO.getPhysicalNetworkId()); - BaremetalPxeVO pxeVo = sc.find(); - if (pxeVo == null) { - throw new CloudRuntimeException("No kickstart PXE server found in pod: " + dest.getPod().getId() + ", you need to add it before starting VM"); + sc.addAnd(sc.getEntity().getPhysicalNetworkId(), Op.EQ, nwVO.getPhysicalNetworkId()); + BaremetalPxeVO pxeVo = sc.find(); + if (pxeVo == null) { + throw new CloudRuntimeException("No kickstart PXE server found in pod: " + dest.getPod().getId() + ", you need to add it before starting VM"); } - VMTemplateVO template = _tmpDao.findById(profile.getTemplateId()); - - try { - String tpl = profile.getTemplate().getUrl(); - assert tpl != null : "How can a null template get here!!!"; + VMTemplateVO template = _tmpDao.findById(profile.getTemplateId()); + + try { + String tpl = profile.getTemplate().getUrl(); + assert tpl != null : "How can a null template get here!!!"; String[] tpls = tpl.split(";"); CloudRuntimeException err = new CloudRuntimeException(String.format("template url[%s] is not correctly encoded. it must be in format of ks=http_link_to_kickstartfile;kernel=nfs_path_to_pxe_kernel;initrd=nfs_path_to_pxe_initrd", tpl)); if (tpls.length != 3) { @@ -120,149 +120,149 @@ public class BaremetalKickStartServiceImpl extends BareMetalPxeServiceBase imple throw err; } } - - PrepareKickstartPxeServerCommand cmd = new PrepareKickstartPxeServerCommand(); + + PrepareKickstartPxeServerCommand cmd = new PrepareKickstartPxeServerCommand(); cmd.setKsFile(ks); cmd.setInitrd(initrd); - cmd.setKernel(kernel); + cmd.setKernel(kernel); cmd.setMac(nic.getMacAddress()); - cmd.setTemplateUuid(template.getUuid()); - Answer aws = _agentMgr.send(pxeVo.getHostId(), cmd); - if (!aws.getResult()) { - s_logger.warn("Unable to set host: " + dest.getHost().getId() + " to PXE boot because " + aws.getDetails()); - return aws.getResult(); + cmd.setTemplateUuid(template.getUuid()); + Answer aws = _agentMgr.send(pxeVo.getHostId(), cmd); + if (!aws.getResult()) { + s_logger.warn("Unable to set host: " + dest.getHost().getId() + " to PXE boot because " + aws.getDetails()); + return aws.getResult(); } - - IpmISetBootDevCommand bootCmd = new IpmISetBootDevCommand(BootDev.pxe); - aws = _agentMgr.send(dest.getHost().getId(), bootCmd); - if (!aws.getResult()) { - s_logger.warn("Unable to set host: " + dest.getHost().getId() + " to PXE boot because " + aws.getDetails()); + + IpmISetBootDevCommand bootCmd = new IpmISetBootDevCommand(BootDev.pxe); + aws = _agentMgr.send(dest.getHost().getId(), bootCmd); + if (!aws.getResult()) { + s_logger.warn("Unable to set host: " + dest.getHost().getId() + " to PXE boot because " + aws.getDetails()); } - - return aws.getResult(); - } catch (Exception e) { - s_logger.warn("Cannot prepare PXE server", e); - return false; - } - } - - @Override - public boolean prepareCreateTemplate(Long pxeServerId, UserVm vm, String templateUrl) { - // TODO Auto-generated method stub - return false; - } - + + return aws.getResult(); + } catch (Exception e) { + s_logger.warn("Cannot prepare PXE server", e); + return false; + } + } + @Override - @DB - public BaremetalPxeVO addPxeServer(AddBaremetalPxeCmd cmd) { - AddBaremetalKickStartPxeCmd kcmd = (AddBaremetalKickStartPxeCmd)cmd; - PhysicalNetworkVO pNetwork = null; - long zoneId; - - if (cmd.getPhysicalNetworkId() == null || cmd.getUrl() == null || cmd.getUsername() == null || cmd.getPassword() == null) { - throw new IllegalArgumentException("At least one of the required parameters(physical network id, url, username, password) is null"); - } - - pNetwork = _physicalNetworkDao.findById(cmd.getPhysicalNetworkId()); - if (pNetwork == null) { - throw new IllegalArgumentException("Could not find phyical network with ID: " + cmd.getPhysicalNetworkId()); - } - zoneId = pNetwork.getDataCenterId(); - - PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), BaremetalPxeManager.BAREMETAL_PXE_SERVICE_PROVIDER.getName()); - if (ntwkSvcProvider == null) { - throw new CloudRuntimeException("Network Service Provider: " + BaremetalPxeManager.BAREMETAL_PXE_SERVICE_PROVIDER.getName() + - " is not enabled in the physical network: " + cmd.getPhysicalNetworkId() + "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: " + cmd.getPhysicalNetworkId() + "to add this device"); - } - - List pxes = _resourceMgr.listAllHostsInOneZoneByType(Host.Type.BaremetalPxe, zoneId); - if (!pxes.isEmpty()) { + public boolean prepareCreateTemplate(Long pxeServerId, UserVm vm, String templateUrl) { + // TODO Auto-generated method stub + return false; + } + + @Override + @DB + public BaremetalPxeVO addPxeServer(AddBaremetalPxeCmd cmd) { + AddBaremetalKickStartPxeCmd kcmd = (AddBaremetalKickStartPxeCmd)cmd; + PhysicalNetworkVO pNetwork = null; + long zoneId; + + if (cmd.getPhysicalNetworkId() == null || cmd.getUrl() == null || cmd.getUsername() == null || cmd.getPassword() == null) { + throw new IllegalArgumentException("At least one of the required parameters(physical network id, url, username, password) is null"); + } + + pNetwork = _physicalNetworkDao.findById(cmd.getPhysicalNetworkId()); + if (pNetwork == null) { + throw new IllegalArgumentException("Could not find phyical network with ID: " + cmd.getPhysicalNetworkId()); + } + zoneId = pNetwork.getDataCenterId(); + + PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), BaremetalPxeManager.BAREMETAL_PXE_SERVICE_PROVIDER.getName()); + if (ntwkSvcProvider == null) { + throw new CloudRuntimeException("Network Service Provider: " + BaremetalPxeManager.BAREMETAL_PXE_SERVICE_PROVIDER.getName() + + " is not enabled in the physical network: " + cmd.getPhysicalNetworkId() + "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: " + cmd.getPhysicalNetworkId() + "to add this device"); + } + + List pxes = _resourceMgr.listAllHostsInOneZoneByType(Host.Type.BaremetalPxe, zoneId); + if (!pxes.isEmpty()) { throw new IllegalArgumentException("Already had a PXE server zone: " + zoneId); - } - - String tftpDir = kcmd.getTftpDir(); - if (tftpDir == null) { - throw new IllegalArgumentException("No TFTP directory specified"); - } - - URI uri; - try { - uri = new URI(cmd.getUrl()); - } catch (Exception e) { - s_logger.debug(e); - throw new IllegalArgumentException(e.getMessage()); - } - String ipAddress = uri.getHost(); - - String guid = getPxeServerGuid(Long.toString(zoneId), BaremetalPxeType.KICK_START.toString(), ipAddress); - - ServerResource resource = null; - Map params = new HashMap(); - params.put(BaremetalPxeService.PXE_PARAM_ZONE, Long.toString(zoneId)); - params.put(BaremetalPxeService.PXE_PARAM_IP, ipAddress); - params.put(BaremetalPxeService.PXE_PARAM_USERNAME, cmd.getUsername()); - params.put(BaremetalPxeService.PXE_PARAM_PASSWORD, cmd.getPassword()); - params.put(BaremetalPxeService.PXE_PARAM_TFTP_DIR, tftpDir); + } + + String tftpDir = kcmd.getTftpDir(); + if (tftpDir == null) { + throw new IllegalArgumentException("No TFTP directory specified"); + } + + URI uri; + try { + uri = new URI(cmd.getUrl()); + } catch (Exception e) { + s_logger.debug(e); + throw new IllegalArgumentException(e.getMessage()); + } + String ipAddress = uri.getHost(); + + String guid = getPxeServerGuid(Long.toString(zoneId), BaremetalPxeType.KICK_START.toString(), ipAddress); + + ServerResource resource = null; + Map params = new HashMap(); + params.put(BaremetalPxeService.PXE_PARAM_ZONE, Long.toString(zoneId)); + params.put(BaremetalPxeService.PXE_PARAM_IP, ipAddress); + params.put(BaremetalPxeService.PXE_PARAM_USERNAME, cmd.getUsername()); + params.put(BaremetalPxeService.PXE_PARAM_PASSWORD, cmd.getPassword()); + params.put(BaremetalPxeService.PXE_PARAM_TFTP_DIR, tftpDir); params.put(BaremetalPxeService.PXE_PARAM_GUID, guid); resource = new BaremetalKickStartPxeResource(); try { - resource.configure("KickStart PXE resource", params); - } catch (Exception e) { - throw new CloudRuntimeException(e.getMessage(), e); + resource.configure("KickStart PXE resource", params); + } catch (Exception e) { + throw new CloudRuntimeException(e.getMessage(), e); } - - Host pxeServer = _resourceMgr.addHost(zoneId, resource, Host.Type.BaremetalPxe, params); - if (pxeServer == null) { - throw new CloudRuntimeException("Cannot add PXE server as a host"); + + Host pxeServer = _resourceMgr.addHost(zoneId, resource, Host.Type.BaremetalPxe, params); + if (pxeServer == null) { + throw new CloudRuntimeException("Cannot add PXE server as a host"); } - - BaremetalPxeVO vo = new BaremetalPxeVO(); - Transaction txn = Transaction.currentTxn(); - vo.setHostId(pxeServer.getId()); - vo.setNetworkServiceProviderId(ntwkSvcProvider.getId()); - vo.setPhysicalNetworkId(kcmd.getPhysicalNetworkId()); - vo.setDeviceType(BaremetalPxeType.KICK_START.toString()); - txn.start(); - _pxeDao.persist(vo); - txn.commit(); - return vo; - } - - @Override - public BaremetalPxeResponse getApiResponse(BaremetalPxeVO vo) { - BaremetalPxeKickStartResponse response = new BaremetalPxeKickStartResponse(); - response.setId(String.valueOf(vo.getId())); - response.setPhysicalNetworkId(String.valueOf(vo.getPhysicalNetworkId())); - response.setPodId(String.valueOf(vo.getPodId())); - Map details = _hostDetailsDao.findDetails(vo.getHostId()); - response.setTftpDir(details.get(BaremetalPxeService.PXE_PARAM_TFTP_DIR)); - return response; - } - - @Override - public List listPxeServers(ListBaremetalPxePingServersCmd cmd) { - SearchCriteriaService sc = SearchCriteria2.create(BaremetalPxeVO.class); - sc.addAnd(sc.getEntity().getDeviceType(), Op.EQ, BaremetalPxeType.KICK_START.toString()); - if (cmd.getPodId() != null) { - sc.addAnd(sc.getEntity().getPodId(), Op.EQ, cmd.getPodId()); - if (cmd.getId() != null) { - sc.addAnd(sc.getEntity().getId(), Op.EQ, cmd.getId()); - } - } - List vos = sc.list(); - List responses = new ArrayList(vos.size()); - for (BaremetalPxeVO vo : vos) { - responses.add(getApiResponse(vo)); - } - return responses; + + BaremetalPxeVO vo = new BaremetalPxeVO(); + Transaction txn = Transaction.currentTxn(); + vo.setHostId(pxeServer.getId()); + vo.setNetworkServiceProviderId(ntwkSvcProvider.getId()); + vo.setPhysicalNetworkId(kcmd.getPhysicalNetworkId()); + vo.setDeviceType(BaremetalPxeType.KICK_START.toString()); + txn.start(); + _pxeDao.persist(vo); + txn.commit(); + return vo; + } + + @Override + public BaremetalPxeResponse getApiResponse(BaremetalPxeVO vo) { + BaremetalPxeKickStartResponse response = new BaremetalPxeKickStartResponse(); + response.setId(String.valueOf(vo.getId())); + response.setPhysicalNetworkId(String.valueOf(vo.getPhysicalNetworkId())); + response.setPodId(String.valueOf(vo.getPodId())); + Map details = _hostDetailsDao.findDetails(vo.getHostId()); + response.setTftpDir(details.get(BaremetalPxeService.PXE_PARAM_TFTP_DIR)); + return response; + } + + @Override + public List listPxeServers(ListBaremetalPxePingServersCmd cmd) { + SearchCriteriaService sc = SearchCriteria2.create(BaremetalPxeVO.class); + sc.addAnd(sc.getEntity().getDeviceType(), Op.EQ, BaremetalPxeType.KICK_START.toString()); + if (cmd.getPodId() != null) { + sc.addAnd(sc.getEntity().getPodId(), Op.EQ, cmd.getPodId()); + if (cmd.getId() != null) { + sc.addAnd(sc.getEntity().getId(), Op.EQ, cmd.getId()); + } + } + List vos = sc.list(); + List responses = new ArrayList(vos.size()); + for (BaremetalPxeVO vo : vos) { + responses.add(getApiResponse(vo)); + } + return responses; } @Override public String getPxeServiceType() { return BaremetalPxeManager.BaremetalPxeType.KICK_START.toString(); - } - -} + } + +} diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeKickStartResponse.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeKickStartResponse.java index 64f22e0947e..116de440770 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeKickStartResponse.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeKickStartResponse.java @@ -14,10 +14,10 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -// +// // Automatically generated by addcopyright.py at 01/29/2013 -package com.cloud.baremetal.networkservice; - +package com.cloud.baremetal.networkservice; + import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.EntityReference; @@ -25,16 +25,16 @@ import com.cloud.baremetal.database.BaremetalPxeVO; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; -@EntityReference(value=BaremetalPxeVO.class) -public class BaremetalPxeKickStartResponse extends BaremetalPxeResponse { - @SerializedName(ApiConstants.TFTP_DIR) @Param(description="Tftp root directory of PXE server") - private String tftpDir; - - public String getTftpDir() { - return tftpDir; - } - - public void setTftpDir(String tftpDir) { - this.tftpDir = tftpDir; - } -} +@EntityReference(value=BaremetalPxeVO.class) +public class BaremetalPxeKickStartResponse extends BaremetalPxeResponse { + @SerializedName(ApiConstants.TFTP_DIR) @Param(description="Tftp root directory of PXE server") + private String tftpDir; + + public String getTftpDir() { + return tftpDir; + } + + public void setTftpDir(String tftpDir) { + this.tftpDir = tftpDir; + } +} diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeManagerImpl.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeManagerImpl.java index 6288f918567..59a28117cb5 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeManagerImpl.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeManagerImpl.java @@ -110,11 +110,11 @@ public class BaremetalPxeManagerImpl extends ManagerBase implements BaremetalPxe if (service.getPxeServiceType().equals(type)) { return service; } - } - + } + throw new CloudRuntimeException("Cannot find PXE service for " + type); } - + @Override public boolean prepare(VirtualMachineProfile profile, NicProfile nic, DeployDestination dest, ReservationContext context) { //TODO: select type from template 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 3d9f5819582..49c6fd9b957 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalUserdataElement.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalUserdataElement.java @@ -14,144 +14,144 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -// +// // Automatically generated by addcopyright.py at 01/29/2013 -package com.cloud.baremetal.networkservice; - +package com.cloud.baremetal.networkservice; + import java.util.HashMap; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.ejb.Local; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.ejb.Local; import javax.inject.Inject; - -import com.cloud.baremetal.manager.BaremetalManager; -import com.cloud.dc.DataCenter.NetworkType; -import com.cloud.deploy.DeployDestination; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.network.Network; -import com.cloud.network.Network.Capability; -import com.cloud.network.Network.GuestType; -import com.cloud.network.Network.Provider; -import com.cloud.network.Network.Service; -import com.cloud.network.Networks.TrafficType; -import com.cloud.network.PhysicalNetworkServiceProvider; -import com.cloud.network.element.IpDeployer; -import com.cloud.network.element.NetworkElement; -import com.cloud.network.element.UserDataServiceProvider; -import com.cloud.offering.NetworkOffering; -import com.cloud.uservm.UserVm; -import com.cloud.utils.component.AdapterBase; -import com.cloud.vm.NicProfile; -import com.cloud.vm.ReservationContext; -import com.cloud.vm.VirtualMachine; + +import com.cloud.baremetal.manager.BaremetalManager; +import com.cloud.dc.DataCenter.NetworkType; +import com.cloud.deploy.DeployDestination; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.network.Network; +import com.cloud.network.Network.Capability; +import com.cloud.network.Network.GuestType; +import com.cloud.network.Network.Provider; +import com.cloud.network.Network.Service; +import com.cloud.network.Networks.TrafficType; +import com.cloud.network.PhysicalNetworkServiceProvider; +import com.cloud.network.element.IpDeployer; +import com.cloud.network.element.NetworkElement; +import com.cloud.network.element.UserDataServiceProvider; +import com.cloud.offering.NetworkOffering; +import com.cloud.uservm.UserVm; +import com.cloud.utils.component.AdapterBase; +import com.cloud.vm.NicProfile; +import com.cloud.vm.ReservationContext; +import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; - -@Local(value = NetworkElement.class) -public class BaremetalUserdataElement extends AdapterBase implements NetworkElement, UserDataServiceProvider { + +@Local(value = NetworkElement.class) +public class BaremetalUserdataElement extends AdapterBase implements NetworkElement, UserDataServiceProvider { private static Map> capabilities; - - @Inject + + @Inject private BaremetalPxeManager pxeMgr; - - static { + + static { capabilities = new HashMap>(); - capabilities.put(Service.UserData, null); + capabilities.put(Service.UserData, null); } - - private boolean canHandle(DeployDestination dest) { - if (dest.getDataCenter().getNetworkType() == NetworkType.Basic && dest.getHost().getHypervisorType() == HypervisorType.BareMetal) { - return true; + + private boolean canHandle(DeployDestination dest) { + if (dest.getDataCenter().getNetworkType() == NetworkType.Basic && dest.getHost().getHypervisorType() == HypervisorType.BareMetal) { + return true; } - return false; + return false; } - - @Override - public boolean addPasswordAndUserdata(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, + + @Override + public boolean addPasswordAndUserdata(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { - if (!canHandle(dest)) { - return false; + if (!canHandle(dest)) { + return false; } - - if (vm.getType() != VirtualMachine.Type.User) { - return false; + + if (vm.getType() != VirtualMachine.Type.User) { + return false; } - - return pxeMgr.addUserData(nic, (VirtualMachineProfile) vm); - } - - @Override - public boolean savePassword(Network network, NicProfile nic, VirtualMachineProfile vm) throws ResourceUnavailableException { - // TODO Auto-generated method stub - return false; - } - - @Override + + return pxeMgr.addUserData(nic, (VirtualMachineProfile) vm); + } + + @Override + public boolean savePassword(Network network, NicProfile nic, VirtualMachineProfile vm) throws ResourceUnavailableException { + // TODO Auto-generated method stub + return false; + } + + @Override public boolean saveSSHKey(Network network, NicProfile nic, VirtualMachineProfile vm, String SSHPublicKey) throws ResourceUnavailableException { // TODO Auto-generated method stub return false; } @Override - public Map> getCapabilities() { - return capabilities; - } - - @Override - public Provider getProvider() { - return BaremetalPxeManager.BAREMETAL_USERDATA_PROVIDER; - } - - @Override - public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) - throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, - ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean release(Network network, NicProfile nic, VirtualMachineProfile vm, ReservationContext context) - throws ConcurrentOperationException, ResourceUnavailableException { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean isReady(PhysicalNetworkServiceProvider provider) { - return true; - } - - @Override - public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean canEnableIndividualServices() { - // TODO Auto-generated method stub - return true; - } - + public Map> getCapabilities() { + return capabilities; + } + + @Override + public Provider getProvider() { + return BaremetalPxeManager.BAREMETAL_USERDATA_PROVIDER; + } + + @Override + public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) + throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, + ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean release(Network network, NicProfile nic, VirtualMachineProfile vm, ReservationContext context) + throws ConcurrentOperationException, ResourceUnavailableException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean isReady(PhysicalNetworkServiceProvider provider) { + return true; + } + + @Override + public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException, + ResourceUnavailableException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean canEnableIndividualServices() { + // TODO Auto-generated method stub + return true; + } + @Override public boolean saveUserData(Network network, NicProfile nic, VirtualMachineProfile vm) @@ -162,12 +162,12 @@ public class BaremetalUserdataElement extends AdapterBase implements NetworkElem @Override public boolean destroy(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { - return true; - } - - @Override - public boolean verifyServicesCombination(Set services) { - return true; - } - -} + return true; + } + + @Override + public boolean verifyServicesCombination(Set services) { + return true; + } + +} diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/PrepareKickstartPxeServerCommand.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/PrepareKickstartPxeServerCommand.java index 25dfeb70d30..a9899793885 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/PrepareKickstartPxeServerCommand.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/PrepareKickstartPxeServerCommand.java @@ -14,32 +14,32 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -// +// // Automatically generated by addcopyright.py at 01/29/2013 -package com.cloud.baremetal.networkservice; - -import com.cloud.agent.api.Command; - -public class PrepareKickstartPxeServerCommand extends Command { +package com.cloud.baremetal.networkservice; + +import com.cloud.agent.api.Command; + +public class PrepareKickstartPxeServerCommand extends Command { private String ksFile; - private String templateUuid; - private String mac; + private String templateUuid; + private String mac; private String ksDevice; private String kernel; - private String initrd; - - @Override - public boolean executeInSequence() { - return true; - } - - public String getKsFile() { - return ksFile; - } - - public void setKsFile(String ksFile) { - this.ksFile = ksFile; - } + private String initrd; + + @Override + public boolean executeInSequence() { + return true; + } + + public String getKsFile() { + return ksFile; + } + + public void setKsFile(String ksFile) { + this.ksFile = ksFile; + } public String getKernel() { return kernel; @@ -57,27 +57,27 @@ public class PrepareKickstartPxeServerCommand extends Command { this.initrd = initrd; } - public String getTemplateUuid() { - return templateUuid; - } - - public void setTemplateUuid(String templateUuid) { - this.templateUuid = templateUuid; - } - - public String getMac() { - return mac; - } - - public void setMac(String mac) { - this.mac = mac; - } - - public String getKsDevice() { - return ksDevice; - } - - public void setKsDevice(String ksDevice) { - this.ksDevice = ksDevice; - } -} + public String getTemplateUuid() { + return templateUuid; + } + + public void setTemplateUuid(String templateUuid) { + this.templateUuid = templateUuid; + } + + public String getMac() { + return mac; + } + + public void setMac(String mac) { + this.mac = mac; + } + + public String getKsDevice() { + return ksDevice; + } + + public void setKsDevice(String ksDevice) { + this.ksDevice = ksDevice; + } +} diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/SecurityGroupHttpClient.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/SecurityGroupHttpClient.java index 7ad351c2e33..b9c2e8484aa 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/SecurityGroupHttpClient.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/SecurityGroupHttpClient.java @@ -1,38 +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. -// -// Automatically generated by addcopyright.py at 01/29/2013 -// Apache License, Version 2.0 (the "License"); you may not use this -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -package com.cloud.baremetal.networkservice; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.SecurityGroupRulesCmd; - -public class SecurityGroupHttpClient { - - public Answer call(String guestIp, SecurityGroupRulesCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - public boolean echo(String ip, long millis, long millis2) { - // TODO Auto-generated method stub - return false; - } - -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// +// Automatically generated by addcopyright.py at 01/29/2013 +// Apache License, Version 2.0 (the "License"); you may not use this +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +package com.cloud.baremetal.networkservice; + +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.SecurityGroupRulesCmd; + +public class SecurityGroupHttpClient { + + public Answer call(String guestIp, SecurityGroupRulesCmd cmd) { + // TODO Auto-generated method stub + return null; + } + + public boolean echo(String ip, long millis, long millis2) { + // TODO Auto-generated method stub + return false; + } + +} diff --git a/plugins/hypervisors/kvm/pom.xml b/plugins/hypervisors/kvm/pom.xml index 013a58d8b7c..613c817668e 100644 --- a/plugins/hypervisors/kvm/pom.xml +++ b/plugins/hypervisors/kvm/pom.xml @@ -1,22 +1,15 @@ - - + + 4.0.0 cloud-plugin-hypervisor-kvm Apache CloudStack Plugin - Hypervisor KVM @@ -45,28 +38,84 @@ - install - src - test - - - org.apache.maven.plugins - maven-dependency-plugin - 2.5.1 - - - copy-dependencies - package - - copy-dependencies - - - ${project.build.directory}/dependencies - runtime - - - - + install + src + test + + + org.apache.maven.plugins + maven-dependency-plugin + 2.5.1 + + + copy-dependencies + package + + copy-dependencies + + + ${project.build.directory}/dependencies + runtime + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.14 + + + **/Qemu*.java + + + + + maven-assembly-plugin + 2.3 + + kvm-agent + false + + agent-descriptor.xml + + + + + make-agent + package + + single + + + + + + maven-resources-plugin + 2.6 + + + copy-resources + + package + + copy-resources + + + dist + + + target + + kvm-agent.zip + + + + + + + + diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/DirectVifDriver.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/DirectVifDriver.java new file mode 100644 index 00000000000..1946d74a495 --- /dev/null +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/DirectVifDriver.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 com.cloud.hypervisor.kvm.resource; + +import com.cloud.agent.api.to.NicTO; +import com.cloud.exception.InternalErrorException; +import com.cloud.network.Networks; +import org.apache.log4j.Logger; +import org.libvirt.LibvirtException; + +import javax.naming.ConfigurationException; +import java.util.Map; + +public class DirectVifDriver extends VifDriverBase { + + private static final Logger s_logger = Logger.getLogger(DirectVifDriver.class); + + /** + * Experimental driver to configure direct networking in libvirt. This should only + * be used on an LXC cluster that does not run any system VMs. + * + * @param nic + * @param guestOsType + * @return + * @throws InternalErrorException + * @throws LibvirtException + */ + public LibvirtVMDef.InterfaceDef plug(NicTO nic, String guestOsType) throws InternalErrorException, + LibvirtException { + LibvirtVMDef.InterfaceDef intf = new LibvirtVMDef.InterfaceDef(); + + if (nic.getType() == Networks.TrafficType.Guest) { + intf.defDirectNet(_libvirtComputingResource.getNetworkDirectDevice(), null, nic.getMac(), getGuestNicModel(guestOsType), + _libvirtComputingResource.getNetworkDirectSourceMode()); + + } else if (nic.getType() == Networks.TrafficType.Public) { + intf.defDirectNet(_libvirtComputingResource.getNetworkDirectDevice(), null, nic.getMac(), getGuestNicModel(guestOsType), + _libvirtComputingResource.getNetworkDirectSourceMode()); + } + + return intf; + } + + public void unplug(LibvirtVMDef.InterfaceDef iface) { + // not needed, libvirt will cleanup + } + +} \ No newline at end of file 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 f786f886bf1..362e0a53e53 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 @@ -57,6 +57,10 @@ import javax.ejb.Local; import javax.naming.ConfigurationException; import org.apache.log4j.Logger; +import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat; +import org.apache.cloudstack.utils.qemu.QemuImg; +import org.apache.cloudstack.utils.qemu.QemuImgFile; +import org.apache.cloudstack.utils.qemu.QemuImgException; import org.libvirt.Connect; import org.libvirt.Domain; import org.libvirt.DomainInfo; @@ -182,6 +186,7 @@ import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DevicesDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef.diskProtocol; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.FeaturesDef; +import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.FilesystemDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.GraphicDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.GuestDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.GuestResourceDef; @@ -192,7 +197,6 @@ import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.SerialDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.VirtioSerialDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.TermPolicy; import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk; -import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk.PhysicalDiskFormat; import com.cloud.hypervisor.kvm.storage.KVMStoragePool; import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager; import com.cloud.network.Networks.BroadcastDomainType; @@ -323,9 +327,11 @@ ServerResource { + " {1}" + " " + " "); - protected String _hypervisorType; + protected HypervisorType _hypervisorType; protected String _hypervisorURI; protected String _hypervisorPath; + protected String _networkDirectSourceMode; + protected String _networkDirectDevice; protected String _sysvmISOPath; protected String _privNwName; protected String _privBridgeName; @@ -392,6 +398,7 @@ ServerResource { private Map getDeveloperProperties() throws ConfigurationException { + final File file = PropertiesUtil.findConfigFile("developer.properties"); if (file == null) { throw new ConfigurationException( @@ -447,6 +454,14 @@ ServerResource { return "scripts/network/domr/kvm"; } + protected String getNetworkDirectSourceMode() { + return _networkDirectSourceMode; + } + + protected String getNetworkDirectDevice() { + return _networkDirectDevice; + } + @Override public boolean configure(String name, Map params) throws ConfigurationException { @@ -586,15 +601,19 @@ ServerResource { String instance = (String) params.get("instance"); - _hypervisorType = (String) params.get("hypervisor.type"); - if (_hypervisorType == null) { - _hypervisorType = "kvm"; + _hypervisorType = HypervisorType.getType((String) params.get("hypervisor.type")); + if (_hypervisorType == HypervisorType.None) { + _hypervisorType = HypervisorType.KVM; } _hypervisorURI = (String) params.get("hypervisor.uri"); if (_hypervisorURI == null) { - _hypervisorURI = "qemu:///system"; + _hypervisorURI = LibvirtConnection.getHypervisorURI(_hypervisorType.toString()); } + + _networkDirectSourceMode = (String) params.get("network.direct.source.mode"); + _networkDirectDevice = (String) params.get("network.direct.device"); + String startMac = (String) params.get("private.macaddr.start"); if (startMac == null) { startMac = "00:16:3e:77:e2:a0"; @@ -647,6 +666,9 @@ ServerResource { if (_localStoragePath == null) { _localStoragePath = "/var/lib/libvirt/images/"; } + + File storagePath = new File(_localStoragePath); + _localStoragePath = storagePath.getAbsolutePath(); _localStorageUUID = (String) params.get("local.storage.uuid"); if (_localStorageUUID == null) { @@ -680,12 +702,14 @@ ServerResource { throw new CloudRuntimeException(e.getMessage()); } - /* 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)"); + if (HypervisorType.KVM == _hypervisorType) { + /* 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)"); + } } _hypervisorPath = getHypervisorPath(conn); @@ -1218,10 +1242,23 @@ ServerResource { StorageFilerTO pool = cmd.getPool(); String secondaryStorageUrl = cmd.getSecondaryStorageURL(); KVMStoragePool secondaryStoragePool = null; + KVMStoragePool primaryPool = null; try { - KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool( - pool.getType(), - pool.getUuid()); + try { + primaryPool = _storagePoolMgr.getStoragePool( + pool.getType(), + pool.getUuid()); + } 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()); + } else { + return new CopyVolumeAnswer(cmd, false, e.getMessage(), null, null); + } + } + String volumeName = UUID.randomUUID().toString(); if (copyToSecondary) { @@ -1387,12 +1424,12 @@ ServerResource { StoragePoolType poolType = pool.getType(); PhysicalDiskFormat volFormat = vol.getFormat(); - if(pool.getType() == StoragePoolType.CLVM && volFormat == KVMPhysicalDisk.PhysicalDiskFormat.RAW) { + if(pool.getType() == StoragePoolType.CLVM && volFormat == PhysicalDiskFormat.RAW) { return "CLVM"; } else if ((poolType == StoragePoolType.NetworkFilesystem || poolType == StoragePoolType.SharedMountPoint || poolType == StoragePoolType.Filesystem) - && volFormat == KVMPhysicalDisk.PhysicalDiskFormat.QCOW2 ) { + && volFormat == PhysicalDiskFormat.QCOW2 ) { return "QCOW2"; } return null; @@ -1501,7 +1538,7 @@ ServerResource { NicTO nic = cmd.getNic(); String vmName = cmd.getVmName(); try { - Connect conn = LibvirtConnection.getConnection(); + Connect conn = LibvirtConnection.getConnectionByVmName(vmName); Domain vm = getDomain(conn, vmName); List pluggedNics = getInterfaces(conn, vmName); Integer nicnum = 0; @@ -1530,7 +1567,7 @@ ServerResource { NicTO nic = cmd.getNic(); String vmName = cmd.getInstanceName(); try { - conn = LibvirtConnection.getConnection(); + conn = LibvirtConnection.getConnectionByVmName(vmName); Domain vm = getDomain(conn, vmName); List pluggedNics = getInterfaces(conn, vmName); for (InterfaceDef pluggedNic : pluggedNics) { @@ -1568,7 +1605,7 @@ ServerResource { } try { - conn = LibvirtConnection.getConnection(); + conn = LibvirtConnection.getConnectionByVmName(routerName); Domain vm = getDomain(conn, routerName); List pluggedNics = getInterfaces(conn, routerName); InterfaceDef routerNic = null; @@ -1609,7 +1646,7 @@ ServerResource { String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); try { - conn = LibvirtConnection.getConnection(); + conn = LibvirtConnection.getConnectionByVmName(routerName); Domain vm = getDomain(conn, routerName); String [][] rules = cmd.generateFwRules(); String[] aclRules = rules[0]; @@ -1648,7 +1685,7 @@ ServerResource { IpAddressTO pubIP = cmd.getIpAddress(); try { - conn = LibvirtConnection.getConnection(); + conn = LibvirtConnection.getConnectionByVmName(routerName); Domain vm = getDomain(conn, routerName); Integer devNum = 0; String pubVlan = pubIP.getVlanId(); @@ -1694,7 +1731,7 @@ ServerResource { String routerIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); try { - conn = LibvirtConnection.getConnection(); + conn = LibvirtConnection.getConnectionByVmName(routerName); IpAddressTO[] ips = cmd.getIpAddresses(); Domain vm = getDomain(conn, routerName); Integer devNum = 0; @@ -1742,7 +1779,7 @@ ServerResource { String[] results = new String[cmd.getIpAddresses().length]; Connect conn; try { - conn = LibvirtConnection.getConnection(); + conn = LibvirtConnection.getConnectionByVmName(routerName); List nics = getInterfaces(conn, routerName); Map vlanAllocatedToVM = new HashMap(); Integer nicPos = 0; @@ -1799,7 +1836,7 @@ ServerResource { String snapshotPath = cmd.getSnapshotPath(); String vmName = cmd.getVmName(); try { - Connect conn = LibvirtConnection.getConnection(); + Connect conn = LibvirtConnection.getConnectionByVmName(vmName); DomainInfo.DomainState state = null; Domain vm = null; if (vmName != null) { @@ -1888,7 +1925,7 @@ ServerResource { String vmName = cmd.getVmName(); KVMStoragePool secondaryStoragePool = null; try { - Connect conn = LibvirtConnection.getConnection(); + Connect conn = LibvirtConnection.getConnectionByVmName(vmName); secondaryStoragePool = _storagePoolMgr.getStoragePoolByURI( secondaryStoragePoolUrl); @@ -2155,8 +2192,9 @@ ServerResource { String secondaryStorageURL = cmd.getSecondaryStorageUrl(); KVMStoragePool secondaryStorage = null; + KVMStoragePool primary = null; try { - Connect conn = LibvirtConnection.getConnection(); + Connect conn = LibvirtConnection.getConnectionByVmName(cmd.getVmName()); String templateFolder = cmd.getAccountId() + File.separator + cmd.getTemplateId() + File.separator; String templateInstallFolder = "/template/tmpl/" + templateFolder; @@ -2164,9 +2202,21 @@ ServerResource { secondaryStorage = _storagePoolMgr.getStoragePoolByURI( secondaryStorageURL); - KVMStoragePool primary = _storagePoolMgr.getStoragePool( + try { + primary = _storagePoolMgr.getStoragePool( cmd.getPool().getType(), cmd.getPrimaryStoragePoolNameLabel()); + } 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()); + } else { + return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage()); + } + } + KVMPhysicalDisk disk = primary.getPhysicalDisk(cmd.getVolumePath()); String tmpltPath = secondaryStorage.getLocalPath() + File.separator + templateInstallFolder; @@ -2186,14 +2236,25 @@ ServerResource { } } else { s_logger.debug("Converting RBD disk " + disk.getPath() + " into template " + cmd.getUniqueName()); - Script.runSimpleBashScript("qemu-img convert" - + " -f raw -O qcow2 " - + KVMPhysicalDisk.RBDStringBuilder(primary.getSourceHost(), + + QemuImgFile srcFile = new QemuImgFile(KVMPhysicalDisk.RBDStringBuilder(primary.getSourceHost(), primary.getSourcePort(), primary.getAuthUserName(), primary.getAuthSecret(), - disk.getPath()) - + " " + tmpltPath + "/" + cmd.getUniqueName() + ".qcow2"); + disk.getPath())); + srcFile.setFormat(PhysicalDiskFormat.RAW); + + QemuImgFile destFile = new QemuImgFile(tmpltPath + "/" + cmd.getUniqueName() + ".qcow2"); + destFile.setFormat(PhysicalDiskFormat.QCOW2); + + QemuImg q = new QemuImg(); + try { + 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()); + } + File templateProp = new File(tmpltPath + "/template.properties"); if (!templateProp.exists()) { templateProp.createNewFile(); @@ -2331,7 +2392,7 @@ ServerResource { String vif = null; String brname = null; try { - Connect conn = LibvirtConnection.getConnection(); + Connect conn = LibvirtConnection.getConnectionByVmName(cmd.getVmName()); List nics = getInterfaces(conn, cmd.getVmName()); vif = nics.get(0).getDevName(); brname = nics.get(0).getBrName(); @@ -2365,7 +2426,7 @@ ServerResource { protected GetVncPortAnswer execute(GetVncPortCommand cmd) { try { - Connect conn = LibvirtConnection.getConnection(); + Connect conn = LibvirtConnection.getConnectionByVmName(cmd.getName()); Integer vncPort = getVncPort(conn, cmd.getName()); return new GetVncPortAnswer(cmd, _privateIp, 5900 + vncPort); } catch (LibvirtException e) { @@ -2436,7 +2497,7 @@ ServerResource { private Answer execute(AttachIsoCommand cmd) { try { - Connect conn = LibvirtConnection.getConnection(); + Connect conn = LibvirtConnection.getConnectionByVmName(cmd.getVmName()); attachOrDetachISO(conn, cmd.getVmName(), cmd.getIsoPath(), cmd.isAttach()); } catch (LibvirtException e) { @@ -2452,7 +2513,7 @@ ServerResource { private AttachVolumeAnswer execute(AttachVolumeCommand cmd) { try { - Connect conn = LibvirtConnection.getConnection(); + Connect conn = LibvirtConnection.getConnectionByVmName(cmd.getVmName()); KVMStoragePool primary = _storagePoolMgr.getStoragePool( cmd.getPooltype(), cmd.getPoolUuid()); @@ -2504,7 +2565,7 @@ ServerResource { private Answer execute(CheckVirtualMachineCommand cmd) { try { - Connect conn = LibvirtConnection.getConnection(); + Connect conn = LibvirtConnection.getConnectionByVmName(cmd.getVmName()); final State state = getVmState(conn, cmd.getVmName()); Integer vncPort = null; if (state == State.Running) { @@ -2573,7 +2634,7 @@ ServerResource { Domain destDomain = null; Connect conn = null; try { - conn = LibvirtConnection.getConnection(); + conn = LibvirtConnection.getConnectionByVmName(cmd.getVmName()); ifaces = getInterfaces(conn, vmName); dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName .getBytes())); @@ -2633,7 +2694,7 @@ ServerResource { NicTO[] nics = vm.getNics(); try { - Connect conn = LibvirtConnection.getConnection(); + Connect conn = LibvirtConnection.getConnectionByVmName(vm.getName()); for (NicTO nic : nics) { getVifDriver(nic.getType()).plug(nic, null); } @@ -2828,7 +2889,7 @@ ServerResource { } try { - Connect conn = LibvirtConnection.getConnection(); + Connect conn = LibvirtConnection.getConnectionByVmName(cmd.getVmName()); final String result = rebootVM(conn, cmd.getVmName()); if (result == null) { Integer vncPort = null; @@ -2866,8 +2927,8 @@ ServerResource { List vmNames = cmd.getVmNames(); try { HashMap vmStatsNameMap = new HashMap(); - Connect conn = LibvirtConnection.getConnection(); for (String vmName : vmNames) { + Connect conn = LibvirtConnection.getConnectionByVmName(vmName); VmStatsEntry statEntry = getVmStat(conn, vmName); if (statEntry == null) { continue; @@ -2891,7 +2952,7 @@ ServerResource { _vms.put(vmName, State.Stopping); } try { - Connect conn = LibvirtConnection.getConnection(); + Connect conn = LibvirtConnection.getConnectionByVmName(vmName); List disks = getDisks(conn, vmName); List ifaces = getInterfaces(conn, vmName); @@ -3021,14 +3082,22 @@ ServerResource { protected LibvirtVMDef createVMFromSpec(VirtualMachineTO vmTO) { LibvirtVMDef vm = new LibvirtVMDef(); - vm.setHvsType(_hypervisorType); vm.setDomainName(vmTO.getName()); vm.setDomUUID(UUID.nameUUIDFromBytes(vmTO.getName().getBytes()) .toString()); vm.setDomDescription(vmTO.getOs()); GuestDef guest = new GuestDef(); - guest.setGuestType(GuestDef.guestType.KVM); + + if (HypervisorType.LXC == _hypervisorType && + VirtualMachine.Type.User == vmTO.getType()) { + // LXC domain is only valid for user VMs. Use KVM for system VMs. + guest.setGuestType(GuestDef.guestType.LXC); + vm.setHvsType(HypervisorType.LXC.toString().toLowerCase()); + } else { + guest.setGuestType(GuestDef.guestType.KVM); + vm.setHvsType(HypervisorType.KVM.toString().toLowerCase()); + } guest.setGuestArch(vmTO.getArch()); guest.setMachineType("pc"); guest.setBootOrder(GuestDef.bootOrder.CDROM); @@ -3040,8 +3109,8 @@ ServerResource { if (vmTO.getMinRam() != vmTO.getMaxRam()){ grd.setMemBalloning(true); - grd.setCurrentMem((int)vmTO.getMinRam()/1024); - grd.setMemorySize((int)vmTO.getMaxRam()/1024); + grd.setCurrentMem((long)vmTO.getMinRam()/1024); + grd.setMemorySize((long)vmTO.getMaxRam()/1024); } else{ grd.setMemorySize(vmTO.getMaxRam() / 1024); @@ -3089,6 +3158,7 @@ ServerResource { DevicesDef devices = new DevicesDef(); devices.setEmulatorPath(_hypervisorPath); + devices.setGuestType(guest.getGuestType()); SerialDef serial = new SerialDef("pty", null, (short) 0); devices.addDevice(serial); @@ -3134,13 +3204,14 @@ ServerResource { State state = State.Stopped; Connect conn = null; try { - conn = LibvirtConnection.getConnection(); synchronized (_vms) { _vms.put(vmName, State.Starting); } vm = createVMFromSpec(vmSpec); + conn = LibvirtConnection.getConnectionByType(vm.getHvsType()); + createVbd(conn, vmSpec, vmName, vm); createVifs(vmSpec, vm); @@ -3305,6 +3376,22 @@ ServerResource { vm.getDevices().addDevice(iso); } } + + // For LXC, find and add the root filesystem + if (HypervisorType.LXC.toString().toLowerCase().equals(vm.getHvsType())) { + for (VolumeTO volume : disks) { + if (volume.getType() == Volume.Type.ROOT) { + KVMStoragePool pool = _storagePoolMgr.getStoragePool( + volume.getPoolType(), + volume.getPoolUuid()); + KVMPhysicalDisk physicalDisk = pool.getPhysicalDisk(volume.getPath()); + FilesystemDef rootFs = new FilesystemDef(physicalDisk.getPath(), "/"); + vm.getDevices().addDevice(rootFs); + break; + } + } + } + } private VolumeTO getVolume(VirtualMachineTO vmSpec, Volume.Type type) { @@ -3539,7 +3626,7 @@ ServerResource { 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.KVM, + (Long) info.get(4), (String) info.get(3), _hypervisorType, RouterPrivateIpStrategy.HostLocal); cmd.setStateChanges(changes); fillNetworkInformation(cmd); @@ -3695,7 +3782,7 @@ ServerResource { Domain dm = null; for (; i < 5; i++) { try { - Connect conn = LibvirtConnection.getConnection(); + Connect conn = LibvirtConnection.getConnectionByVmName(vm); dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vm .getBytes())); DomainInfo.DomainState vps = dm.getInfo().state; @@ -3767,16 +3854,30 @@ ServerResource { private HashMap getAllVms() { final HashMap vmStates = new HashMap(); + Connect conn = null; + + try { + conn = LibvirtConnection.getConnectionByType(HypervisorType.LXC.toString()); + vmStates.putAll(getAllVms(conn)); + } catch (LibvirtException e) { + s_logger.debug("Failed to get connection: " + e.getMessage()); + } + + try { + conn = LibvirtConnection.getConnectionByType(HypervisorType.KVM.toString()); + vmStates.putAll(getAllVms(conn)); + } catch (LibvirtException e) { + s_logger.debug("Failed to get connection: " + e.getMessage()); + } + + return vmStates; + } + + private HashMap getAllVms(Connect conn) { + final HashMap vmStates = new HashMap(); String[] vms = null; int[] ids = null; - Connect conn = null; - try { - conn = LibvirtConnection.getConnection(); - } catch (LibvirtException e) { - s_logger.debug("Failed to get connection: " + e.getMessage()); - return vmStates; - } try { ids = conn.listDomains(); @@ -4227,9 +4328,11 @@ ServerResource { } private void cleanupVMNetworks(Connect conn, List nics) { - for (InterfaceDef nic : nics) { - if (nic.getHostNetType() == hostNicType.VNET) { - cleanupVnet(conn, getVnetIdFromBrName(nic.getBrName())); + if (nics != null) { + for (InterfaceDef nic : nics) { + if (nic.getHostNetType() == hostNicType.VNET) { + cleanupVnet(conn, getVnetIdFromBrName(nic.getBrName())); + } } } } @@ -4441,7 +4544,7 @@ ServerResource { } List intfs = getInterfaces(conn, vmName); - if (intfs.size() < nic.getDeviceId()) { + if (intfs.size() == 0 || intfs.size() < nic.getDeviceId()) { return false; } @@ -4539,7 +4642,7 @@ ServerResource { cmd.add("--vif", vif); cmd.add("--brname", brname); cmd.add("--nicsecips", secIps); - if (rules != null) { + if (newRules != null && !newRules.isEmpty()) { cmd.add("--rules", newRules); } String result = cmd.execute(); @@ -4647,7 +4750,7 @@ ServerResource { boolean success = false; Connect conn; try { - conn = LibvirtConnection.getConnection(); + conn = LibvirtConnection.getConnectionByVmName(cmd.getVmName()); success = default_network_rules_for_systemvm(conn, cmd.getVmName()); } catch (LibvirtException e) { s_logger.trace("Ignoring libvirt error.", e); @@ -4660,7 +4763,7 @@ ServerResource { boolean success = false; Connect conn; try { - conn = LibvirtConnection.getConnection(); + conn = LibvirtConnection.getConnectionByVmName(cmd.getVmName()); success = network_rules_vmSecondaryIp(conn, cmd.getVmName(), cmd.getVmSecIp(), cmd.getAction()); } catch (LibvirtException e) { // TODO Auto-generated catch block 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 981d343004d..2ad16166c42 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 @@ -16,33 +16,75 @@ // under the License. package com.cloud.hypervisor.kvm.resource; +import com.cloud.hypervisor.Hypervisor; +import com.cloud.hypervisor.Hypervisor.HypervisorType; import org.apache.log4j.Logger; import org.libvirt.Connect; import org.libvirt.LibvirtException; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + public class LibvirtConnection { private static final Logger s_logger = Logger .getLogger(LibvirtConnection.class); + static private Map _connections = new HashMap(); + static private Connect _connection; static private String _hypervisorURI; static public Connect getConnection() throws LibvirtException { - if (_connection == null) { - _connection = new Connect(_hypervisorURI, false); + return getConnection(_hypervisorURI); + } + + static public Connect getConnection(String hypervisorURI) throws LibvirtException { + Connect conn = _connections.get(hypervisorURI); + + if (conn == null) { + conn = new Connect(hypervisorURI, false); + _connections.put(hypervisorURI, conn); } else { try { - _connection.getVersion(); + conn.getVersion(); } catch (LibvirtException e) { s_logger.debug("Connection with libvirtd is broken, due to " + e.getMessage()); - _connection = new Connect(_hypervisorURI, false); + conn = new Connect(hypervisorURI, false); + _connections.put(hypervisorURI, conn); } } - return _connection; + return conn; + } + + static public Connect getConnectionByVmName(String vmName) throws LibvirtException { + HypervisorType[] hypervisors = new HypervisorType[] {HypervisorType.KVM, Hypervisor.HypervisorType.LXC}; + + for (HypervisorType hypervisor : hypervisors) { + Connect conn = LibvirtConnection.getConnectionByType(hypervisor.toString()); + if (conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName.getBytes())) != null) { + return conn; + } + } + + // return the default connection + return getConnection(); + } + + static public Connect getConnectionByType(String hypervisorType) throws LibvirtException { + return getConnection(getHypervisorURI(hypervisorType)); } static void initialize(String hypervisorURI) { _hypervisorURI = hypervisorURI; } + + static String getHypervisorURI(String hypervisorType) { + if ("LXC".equalsIgnoreCase(hypervisorType)) { + return "lxc:///"; + } else { + return "qemu:///system"; + } + } } diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtDomainXMLParser.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtDomainXMLParser.java index b622b6d33cf..ac4baf122a9 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtDomainXMLParser.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtDomainXMLParser.java @@ -25,6 +25,7 @@ import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; +import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat; import org.apache.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -110,23 +111,29 @@ public class LibvirtDomainXMLParser { String bridge = getAttrValue("source", "bridge", nic); def.defBridgeNet(bridge, dev, mac, nicModel.valueOf(model.toUpperCase())); + } else if (type.equalsIgnoreCase("ethernet")) { + String scriptPath = getAttrValue("script", "path", nic); + def.defEthernet(dev, mac, nicModel.valueOf(model.toUpperCase()), scriptPath); } interfaces.add(def); } Element graphic = (Element) devices .getElementsByTagName("graphics").item(0); - String port = graphic.getAttribute("port"); - if (port != null) { - try { - vncPort = Integer.parseInt(port); - if (vncPort != -1) { - vncPort = vncPort - 5900; - } else { + + if (graphic != null) { + String port = graphic.getAttribute("port"); + if (port != null) { + try { + vncPort = Integer.parseInt(port); + if (vncPort != -1) { + vncPort = vncPort - 5900; + } else { + vncPort = null; + } + } catch (NumberFormatException nfe) { vncPort = null; } - } catch (NumberFormatException nfe) { - vncPort = null; } } diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtStorageVolumeDef.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtStorageVolumeDef.java index d5cd91a954c..7f9ceebe742 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtStorageVolumeDef.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtStorageVolumeDef.java @@ -18,7 +18,7 @@ package com.cloud.hypervisor.kvm.resource; public class LibvirtStorageVolumeDef { public enum volFormat { - RAW("raw"), QCOW2("qcow2"), DIR("dir"); + RAW("raw"), QCOW2("qcow2"), DIR("dir"), TAR("tar"); private String _format; volFormat(String format) { @@ -38,6 +38,10 @@ public class LibvirtStorageVolumeDef { return RAW; } else if (format.equalsIgnoreCase("qcow2")) { return QCOW2; + } else if (format.equalsIgnoreCase("dir")) { + return DIR; + } else if (format.equalsIgnoreCase("tar")) { + return TAR; } return null; } 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 c93aeeb2dd6..9cddb2e4323 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 @@ -31,7 +31,7 @@ public class LibvirtVMDef { public static class GuestDef { enum guestType { - KVM, XEN, EXE + KVM, XEN, EXE, LXC } enum bootOrder { @@ -62,6 +62,10 @@ public class LibvirtVMDef { _type = type; } + public guestType getGuestType() { + return _type; + } + public void setGuestArch(String arch) { _arch = arch; } @@ -106,14 +110,22 @@ public class LibvirtVMDef { } guestDef.append("\n"); return guestDef.toString(); - } else + } else if (_type == guestType.LXC) { + StringBuilder guestDef = new StringBuilder(); + guestDef.append("\n"); + guestDef.append("exe\n"); + guestDef.append("/sbin/init\n"); + guestDef.append("\n"); + return guestDef.toString(); + } else { return null; + } } } public static class GuestResourceDef { private long _mem; - private int _currentMem = -1; + private long _currentMem = -1; private String _memBacking; private int _vcpu = -1; private boolean _memBalloning= false; @@ -122,7 +134,7 @@ public class LibvirtVMDef { _mem = mem; } - public void setCurrentMem(int currMem) { + public void setCurrentMem(long currMem) { _currentMem = currMem; } @@ -279,6 +291,7 @@ public class LibvirtVMDef { public static class DevicesDef { private String _emulator; + private GuestDef.guestType _guestType; private final Map> devices = new HashMap>(); public boolean addDevice(Object device) { @@ -298,6 +311,10 @@ public class LibvirtVMDef { _emulator = emulator; } + public void setGuestType(GuestDef.guestType guestType) { + _guestType = guestType; + } + @Override public String toString() { StringBuilder devicesBuilder = new StringBuilder(); @@ -309,6 +326,13 @@ public class LibvirtVMDef { for (List devs : devices.values()) { for (Object dev : devs) { + if (_guestType == GuestDef.guestType.LXC) { + if (dev instanceof GraphicDef || + dev instanceof InputDef || + dev instanceof DiskDef) { + continue; + } + } devicesBuilder.append(dev.toString()); } } @@ -610,7 +634,7 @@ public class LibvirtVMDef { public static class InterfaceDef { enum guestNetType { - BRIDGE("bridge"), NETWORK("network"), USER("user"), ETHERNET( + BRIDGE("bridge"), DIRECT("direct"), NETWORK("network"), USER("user"), ETHERNET( "ethernet"), INTERNAL("internal"); String _type; @@ -648,6 +672,7 @@ public class LibvirtVMDef { * internal */ private hostNicType _hostNetType; /* Only used by agent java code */ + private String _netSourceMode; private String _sourceName; private String _networkName; private String _macAddr; @@ -667,6 +692,16 @@ public class LibvirtVMDef { _model = model; } + public void defDirectNet(String sourceName, String targetName, + String macAddr, nicModel model, String sourceMode) { + _netType = guestNetType.DIRECT; + _netSourceMode = sourceMode; + _sourceName = sourceName; + _networkName = targetName; + _macAddr = macAddr; + _model = model; + } + public void defPrivateNet(String networkName, String targetName, String macAddr, nicModel model) { _netType = guestNetType.NETWORK; @@ -676,13 +711,19 @@ public class LibvirtVMDef { _model = model; } - public void defEthernet(String targetName, String macAddr, nicModel model) { + public void defEthernet(String targetName, String macAddr, nicModel model, String scriptPath) { _netType = guestNetType.ETHERNET; _networkName = targetName; + _sourceName = targetName; _macAddr = macAddr; _model = model; + _scriptPath = scriptPath; } + public void defEthernet(String targetName, String macAddr, nicModel model) { + defEthernet(targetName, macAddr, model, null); + } + public void setHostNetType(hostNicType hostNetType) { _hostNetType = hostNetType; } @@ -699,6 +740,10 @@ public class LibvirtVMDef { return _netType; } + public String getNetSourceMode() { + return _netSourceMode; + } + public String getDevName() { return _networkName; } @@ -739,6 +784,8 @@ public class LibvirtVMDef { netBuilder.append("\n"); } else if (_netType == guestNetType.NETWORK) { netBuilder.append("\n"); + } else if (_netType == guestNetType.DIRECT) { + netBuilder.append("\n"); } if (_networkName != null) { netBuilder.append("\n"); @@ -749,6 +796,9 @@ public class LibvirtVMDef { if (_model != null) { netBuilder.append("\n"); } + if (_scriptPath != null) { + netBuilder.append(" diff --git a/ui/scripts/accounts.js b/ui/scripts/accounts.js index 3403337a834..8353d70536e 100644 --- a/ui/scripts/accounts.js +++ b/ui/scripts/accounts.js @@ -409,6 +409,77 @@ }); } + if(args.data.cpuLimit != null) { + var data = { + resourceType: 8, + max: args.data.cpuLimit, + domainid: accountObj.domainid, + account: accountObj.name + }; + + $.ajax({ + url: createURL('updateResourceLimit'), + data: data, + async: false, + success: function(json) { + accountObj["cpuLimit"] = args.data.cpuLimit; + } + }); + } + + if(args.data.memoryLimit != null) { + var data = { + resourceType: 9, + max: args.data.memoryLimit, + domainid: accountObj.domainid, + account: accountObj.name + }; + + $.ajax({ + url: createURL('updateResourceLimit'), + data: data, + async: false, + success: function(json) { + accountObj["memoryLimit"] = args.data.memoryLimit; + } + }); + } + + if(args.data.primaryStorageLimit != null) { + var data = { + resourceType: 10, + max: args.data.primaryStorageLimit, + domainid: accountObj.domainid, + account: accountObj.name + }; + + $.ajax({ + url: createURL('updateResourceLimit'), + data: data, + async: false, + success: function(json) { + accountObj["primaryStorageLimit"] = args.data.primaryStorageLimit; + } + }); + } + + if(args.data.secondaryStorageLimit != null) { + var data = { + resourceType: 11, + max: args.data.secondaryStorageLimit, + domainid: accountObj.domainid, + account: accountObj.name + }; + + $.ajax({ + url: createURL('updateResourceLimit'), + data: data, + async: false, + success: function(json) { + accountObj["secondaryStorageLimit"] = args.data.secondaryStorageLimit; + } + }); + } args.response.success({data: accountObj}); } }, @@ -698,6 +769,42 @@ return false; } }, + cpuLimit: { + label: 'label.cpu.limits', + isEditable: function(context) { + if (context.accounts[0].accounttype == roleTypeUser || context.accounts[0].accounttype == roleTypeDomainAdmin) //updateResourceLimits is only allowed on account whose type is user or domain-admin + return true; + else + return false; + } + }, + memoryLimit: { + label: 'label.memory.limits', + isEditable: function(context) { + if (context.accounts[0].accounttype == roleTypeUser || context.accounts[0].accounttype == roleTypeDomainAdmin) //updateResourceLimits is only allowed on account whose type is user or domain-admin + return true; + else + return false; + } + }, + primaryStorageLimit: { + label: 'label.primary.storage.limits', + isEditable: function(context) { + if (context.accounts[0].accounttype == roleTypeUser || context.accounts[0].accounttype == roleTypeDomainAdmin) //updateResourceLimits is only allowed on account whose type is user or domain-admin + return true; + else + return false; + } + }, + secondaryStorageLimit: { + label: 'label.secondary.storage.limits', + isEditable: function(context) { + if (context.accounts[0].accounttype == roleTypeUser || context.accounts[0].accounttype == roleTypeDomainAdmin) //updateResourceLimits is only allowed on account whose type is user or domain-admin + return true; + else + return false; + } + }, vmtotal: { label: 'label.total.of.vm' }, iptotal: { label: 'label.total.of.ip' }, @@ -725,11 +832,11 @@ dataProvider: function(args) { var data = { id: args.context.accounts[0].id - }; + }; $.ajax({ url: createURL('listAccounts'), - data: data, - success: function(json) { + data: data, + success: function(json) { var accountObj = json.listaccountsresponse.account[0]; var data = { domainid: accountObj.domainid, @@ -737,7 +844,7 @@ }; $.ajax({ url: createURL('listResourceLimits'), - data: data, + data: data, success: function(json) { var limits = json.listresourcelimitsresponse.resourcelimit; if (limits != null) { @@ -759,22 +866,34 @@ case "4": accountObj["templateLimit"] = limit.max; break; - case "7": + case "7": accountObj["vpcLimit"] = limit.max; break; + case "8": + accountObj["cpuLimit"] = limit.max; + break; + case "9": + accountObj["memoryLimit"] = limit.max; + break; + case "10": + accountObj["primaryStorageLimit"] = limit.max; + break; + case "11": + accountObj["secondaryStorageLimit"] = limit.max; + break; } } - } + } args.response.success( { actionFilter: accountActionfilter, data: accountObj } - ); + ); } - }); + }); } - }); + }); } } } diff --git a/ui/scripts/domains.js b/ui/scripts/domains.js index 991e37d7324..8ee0ee6816a 100644 --- a/ui/scripts/domains.js +++ b/ui/scripts/domains.js @@ -184,6 +184,50 @@ }); } + if(args.data.cpuLimit != null) { + $.ajax({ + url: createURL("updateResourceLimit&domainid=" + args.context.domains[0].id + "&resourceType=8&max=" + args.data.cpuLimit), + dataType: "json", + async: false, + success: function(json) { + domainObj["cpuLimit"] = args.data.cpuLimit; + } + }); + } + + if(args.data.memoryLimit != null) { + $.ajax({ + url: createURL("updateResourceLimit&domainid=" + args.context.domains[0].id + "&resourceType=9&max=" + args.data.memoryLimit), + dataType: "json", + async: false, + success: function(json) { + domainObj["memoryLimit"] = args.data.memoryLimit; + } + }); + } + + if(args.data.primaryStorageLimit != null) { + $.ajax({ + url: createURL("updateResourceLimit&domainid=" + args.context.domains[0].id + "&resourceType=10&max=" + args.data.primaryStorageLimit), + dataType: "json", + async: false, + success: function(json) { + domainObj["primaryStorageLimit"] = args.data.primaryStorageLimit; + } + }); + } + + if(args.data.secondaryStorageLimit != null) { + $.ajax({ + url: createURL("updateResourceLimit&domainid=" + args.context.domains[0].id + "&resourceType=11&max=" + args.data.secondaryStorageLimit), + dataType: "json", + async: false, + success: function(json) { + domainObj["secondaryStorageLimit"] = args.data.secondaryStorageLimit; + } + }); + } + args.response.success({data: domainObj}); } }, @@ -348,6 +392,42 @@ return false; } }, + cpuLimit: { + label: 'label.cpu.limits', + isEditable: function(context) { + if(context.domains[0].level != 0) //ROOT domain (whose level is 0) is not allowed to updateResourceLimits + return true; + else + return false; + } + }, + memoryLimit: { + label: 'label.memory.limits', + isEditable: function(context) { + if(context.domains[0].level != 0) //ROOT domain (whose level is 0) is not allowed to updateResourceLimits + return true; + else + return false; + } + }, + primaryStorageLimit: { + label: 'label.primary.storage.limits', + isEditable: function(context) { + if(context.domains[0].level != 0) //ROOT domain (whose level is 0) is not allowed to updateResourceLimits + return true; + else + return false; + } + }, + secondaryStorageLimit: { + label: 'label.secondary.storage.limits', + isEditable: function(context) { + if(context.domains[0].level != 0) //ROOT domain (whose level is 0) is not allowed to updateResourceLimits + return true; + else + return false; + } + }, accountTotal: { label: 'label.accounts' }, vmTotal: { label: 'label.instances' }, volumeTotal: { label: 'label.volumes' } @@ -441,6 +521,18 @@ case "7": domainObj["vpcLimit"] = limit.max; break; + case "8": + domainObj["cpuLimit"] = limit.max; + break; + case "9": + domainObj["memoryLimit"] = limit.max; + break; + case "10": + domainObj["primaryStorageLimit"] = limit.max; + break; + case "7": + domainObj["secondaryStorageLimit"] = limit.max; + break; } } } diff --git a/ui/scripts/events.js b/ui/scripts/events.js index 1c89b58346c..3b6874c6274 100644 --- a/ui/scripts/events.js +++ b/ui/scripts/events.js @@ -257,8 +257,6 @@ } }); - $(window).trigger('cloudStack.fullRefresh'); - } }, diff --git a/ui/scripts/projects.js b/ui/scripts/projects.js index b62dcb4c6a2..4004709a75d 100644 --- a/ui/scripts/projects.js +++ b/ui/scripts/projects.js @@ -71,7 +71,7 @@ var resourceLimits = $.grep( json.listresourcelimitsresponse.resourcelimit, function(resourceLimit) { - return resourceLimit.resourcetype != 5 && resourceLimit.resourcetype != 8; + return resourceLimit.resourcetype != 5 && resourceLimit.resourcetype != 12; } ); @@ -111,7 +111,23 @@ 7: { id: 'vpc', label: 'label.max.vpcs' - } + }, + 8: { + id: 'cpu', + label: 'label.max.cpus' + }, + 9: { + id: 'memory', + label: 'label.max.memory' + }, + 10: { + id: 'primary_storage', + label: 'label.max.primary.storage' + }, + 11: { + id: 'secondary_storage', + label: 'label.max.secondary.storage' + } }; return { diff --git a/ui/scripts/regions.js b/ui/scripts/regions.js index 8839dec77c3..0aaece009f7 100644 --- a/ui/scripts/regions.js +++ b/ui/scripts/regions.js @@ -18,6 +18,10 @@ cloudStack.sections.regions = { title: 'label.menu.regions', id: 'regions', + sectionSelect: { + label: 'label.select-view', + preFilter: function() { return ['regions']; } + }, regionSelector: { dataProvider: function(args) { $.ajax({ @@ -31,163 +35,208 @@ ] }); } - }); + }); } }, - listView: { - section: 'regions', - fields: { - name: { label: 'label.name' }, - id: { label: 'ID' }, - endpoint: { label: 'label.endpoint' } - }, - actions: { - add: { - label: 'label.add.region', - messages: { - notification: function() { return 'label.add.region'; } + sections: { + regions: { + id: 'regions', + type: 'select', + title: 'label.menu.regions', + listView: { + section: 'regions', + id: 'regions', + label: 'label.menu.regions', + fields: { + name: { label: 'label.name' }, + id: { label: 'ID' }, + endpoint: { label: 'label.endpoint' } }, - createForm: { - title: 'label.add.region', - desc: 'message.add.region', - fields: { - id: { label: 'label.id', validation: { required: true } }, - name: { label: 'label.name', validation: { required: true } }, - endpoint: { label: 'label.endpoint', validation: { required: true } } + actions: { + add: { + label: 'label.add.region', + messages: { + notification: function() { return 'label.add.region'; } + }, + createForm: { + title: 'label.add.region', + desc: 'message.add.region', + fields: { + id: { label: 'label.id', validation: { required: true } }, + name: { label: 'label.name', validation: { required: true } }, + endpoint: { label: 'label.endpoint', validation: { required: true } } + } + }, + action: function(args) { + var data = { + id: args.data.id, + name: args.data.name, + endpoint: args.data.endpoint + }; + + $.ajax({ + url: createURL('addRegion'), + data: data, + success: function(json) { + var item = json.addregionresponse.region; + args.response.success({data: item}); + $(window).trigger('cloudStack.refreshRegions'); + }, + error: function(json) { + args.response.error(parseXMLHttpResponse(json)); + } + }); + }, + notification: { + poll: function(args) { + args.complete(); + } + } } }, - action: function(args) { - var data = { - id: args.data.id, - name: args.data.name, - endpoint: args.data.endpoint - }; - + dataProvider: function(args) { $.ajax({ - url: createURL('addRegion'), - data: data, - success: function(json) { - var item = json.addregionresponse.region; - args.response.success({data: item}); - $(window).trigger('cloudStack.refreshRegions'); + url: createURL('listRegions&listAll=true'), + success: function(json) { + var regions = json.listregionsresponse.region + + args.response.success({ + data: regions ? regions : [] + }); }, error: function(json) { args.response.error(parseXMLHttpResponse(json)); - } - }); - }, - notification: { - poll: function(args) { - args.complete(); - } - } - } - }, - dataProvider: function(args) { - $.ajax({ - url: createURL('listRegions&listAll=true'), - success: function(json) { - var regions = json.listregionsresponse.region - - args.response.success({ - data: regions ? regions : [] + } }); }, - error: function(json) { - args.response.error(parseXMLHttpResponse(json)); - } - }); - }, - detailView: { - name: 'Region details', - actions: { - edit: { - label: 'label.edit.region', - action: function(args) { - var data = { - id: args.context.regions[0].id, - name: args.data.name, - endpoint: args.data.endpoint - }; - - $.ajax({ - url: createURL('updateRegion'), - data: data, - success: function(json) { - args.response.success(); - $(window).trigger('cloudStack.refreshRegions'); - }, - error: function(json) { - args.response.error(parseXMLHttpResponse(json)); - } - }); - } - }, - remove: { - label: 'label.remove.region', - messages: { - notification: function() { return 'label.remove.region'; }, - confirm: function() { return 'message.remove.region'; } - }, - preAction: function(args) { - var region = args.context.regions[0]; - - /* e.g. - region.endpoint == "http://localhost:8080/client/" - document.location.href == "http://localhost:8080/client/#" - */ - /* - if(document.location.href.indexOf(region.endpoint) != -1) { - cloudStack.dialog.notice({ message: _l('You can not remove the region that you are currently in.') }); - return false; - } - */ - return true; - }, - action: function(args) { - var region = args.context.regions[0]; + detailView: { + name: 'Region details', + viewAll: { path: 'regions.GSLB', label: 'GSLB' }, + actions: { + edit: { + label: 'label.edit.region', + action: function(args) { + var data = { + id: args.context.regions[0].id, + name: args.data.name, + endpoint: args.data.endpoint + }; - $.ajax({ - url: createURL('removeRegion'), - data: { id: region.id }, - success: function(json) { - args.response.success(); - $(window).trigger('cloudStack.refreshRegions'); + $.ajax({ + url: createURL('updateRegion'), + data: data, + success: function(json) { + args.response.success(); + $(window).trigger('cloudStack.refreshRegions'); + }, + error: function(json) { + args.response.error(parseXMLHttpResponse(json)); + } + }); + } + }, + remove: { + label: 'label.remove.region', + messages: { + notification: function() { return 'label.remove.region'; }, + confirm: function() { return 'message.remove.region'; } }, - error: function(json) { - args.response.error(parseXMLHttpResponse(json)); - } - }); + preAction: function(args) { + var region = args.context.regions[0]; + + /* e.g. + region.endpoint == "http://localhost:8080/client/" + document.location.href == "http://localhost:8080/client/#" + */ + /* + if(document.location.href.indexOf(region.endpoint) != -1) { + cloudStack.dialog.notice({ message: _l('You can not remove the region that you are currently in.') }); + return false; + } + */ + return true; + }, + action: function(args) { + var region = args.context.regions[0]; + + $.ajax({ + url: createURL('removeRegion'), + data: { id: region.id }, + success: function(json) { + args.response.success(); + $(window).trigger('cloudStack.refreshRegions'); + }, + error: function(json) { + args.response.error(parseXMLHttpResponse(json)); + } + }); + } + } + }, + tabs: { + details: { + title: 'label.details', + fields: [ + { + id: { label: 'label.id' } + }, + { + name: { label: 'label.name', isEditable: true }, + endpoint: { label: 'label.endpoint', isEditable: true } + } + ], + dataProvider: function(args) { + $.ajax({ + url: createURL('listRegions&listAll=true'), + data: { id: args.context.regions[0].id }, + success: function(json) { + var region = json.listregionsresponse.region + + args.response.success({ + data: region ? region[0] : {} + }); + }, + error: function(json) { + args.response.error(parseXMLHttpResponse(json)); + } + }); + } + } } } - }, - tabs: { - details: { - title: 'label.details', - fields: [ - { - id: { label: 'label.id' } - }, - { - name: { label: 'label.name', isEditable: true }, - endpoint: { label: 'label.endpoint', isEditable: true } - } - ], - dataProvider: function(args) { + } + }, + GSLB: { + id: 'GSLB', + type: 'select', + title: 'GSLB', + listView: { + id: 'GSLB', + label: 'GSLB', + fields: { + name: { label: 'label.name' } + }, + dataProvider: function(args) { + if('regions' in args.context) { + var data = { + regionid: args.context.regions[0].id + }; $.ajax({ - url: createURL('listRegions&listAll=true'), - data: { id: args.context.regions[0].id }, + url: createURL('listGlobalLoadBalancerRules'), + data: data, success: function(json) { - var region = json.listregionsresponse.region - + debugger; + var items = json.listgloballoadbalancerrulesresponse.globalloadbalancerrule; args.response.success({ - data: region ? region[0] : {} + data: items }); - }, - error: function(json) { - args.response.error(parseXMLHttpResponse(json)); - } - }); + } + }); + } + else { + args.response.success({ + data: null + }); } } } diff --git a/ui/scripts/system.js b/ui/scripts/system.js index 8c5a6bb9a1d..8d08584dc60 100644 --- a/ui/scripts/system.js +++ b/ui/scripts/system.js @@ -114,28 +114,34 @@ } }); - if(trafficType.xennetworklabel == null || trafficType.xennetworklabel == 0) - trafficType.xennetworklabel = dictionary['label.network.label.display.for.blank.value']; - if(trafficType.kvmnetworklabel == null || trafficType.kvmnetworklabel == 0) - trafficType.kvmnetworklabel = dictionary['label.network.label.display.for.blank.value']; - if(trafficType.vmwarenetworklabel == null || trafficType.vmwarenetworklabel == 0) - trafficType.vmwarenetworklabel = dictionary['label.network.label.display.for.blank.value']; - if(trafficType.ovmnetworklabel == null || trafficType.ovmnetworklabel == 0) - trafficType.ovmnetworklabel = dictionary['label.network.label.display.for.blank.value']; + if(trafficType.xennetworklabel == null || trafficType.xennetworklabel == 0) + trafficType.xennetworklabel = dictionary['label.network.label.display.for.blank.value']; + if(trafficType.kvmnetworklabel == null || trafficType.kvmnetworklabel == 0) + trafficType.kvmnetworklabel = dictionary['label.network.label.display.for.blank.value']; + if(trafficType.vmwarenetworklabel == null || trafficType.vmwarenetworklabel == 0) + trafficType.vmwarenetworklabel = dictionary['label.network.label.display.for.blank.value']; + if(trafficType.ovmnetworklabel == null || trafficType.ovmnetworklabel == 0) + trafficType.ovmnetworklabel = dictionary['label.network.label.display.for.blank.value']; + if(trafficType.lxcnetworklabel == null || trafficType.lxcnetworklabel == 0) + trafficType.lxcnetworklabel = dictionary['label.network.label.display.for.blank.value']; + return trafficType; }; var updateTrafficLabels = function(trafficType, labels, complete) { var array1 = []; - if(labels.xennetworklabel != dictionary['label.network.label.display.for.blank.value']) - array1.push("&xennetworklabel=" + labels.xennetworklabel); - if(labels.kvmnetworklabel != dictionary['label.network.label.display.for.blank.value']) - array1.push("&kvmnetworklabel=" + labels.kvmnetworklabel); - if(labels.vmwarenetworklabel != dictionary['label.network.label.display.for.blank.value']) - array1.push("&vmwarenetworklabel=" + labels.vmwarenetworklabel); - if(labels.ovmnetworklabel != dictionary['label.network.label.display.for.blank.value']) - array1.push("&ovmnetworklabel=" + labels.ovmnetworklabel); - $.ajax({ + if(labels.xennetworklabel != dictionary['label.network.label.display.for.blank.value']) + array1.push("&xennetworklabel=" + labels.xennetworklabel); + if(labels.kvmnetworklabel != dictionary['label.network.label.display.for.blank.value']) + array1.push("&kvmnetworklabel=" + labels.kvmnetworklabel); + if(labels.vmwarenetworklabel != dictionary['label.network.label.display.for.blank.value']) + array1.push("&vmwarenetworklabel=" + labels.vmwarenetworklabel); + if(labels.ovmnetworklabel != dictionary['label.network.label.display.for.blank.value']) + array1.push("&ovmnetworklabel=" + labels.ovmnetworklabel); + if(labels.lxcnetworklabel != dictionary['label.network.label.display.for.blank.value']) + array1.push("&lxcnetworklabel=" + labels.lxcnetworklabel); + + $.ajax({ url: createURL('updateTrafficType' + array1.join("")), data: { id: trafficType.id @@ -463,7 +469,8 @@ xennetworklabel: { label: 'label.xen.traffic.label', isEditable: true }, kvmnetworklabel: { label: 'label.kvm.traffic.label', isEditable: true }, vmwarenetworklabel: { label: 'label.vmware.traffic.label', isEditable: true }, - ovmnetworklabel: { label: 'OVM traffic label',isEditable: true } + ovmnetworklabel: { label: 'OVM traffic label',isEditable: true }, + lxcnetworklabel: { label: 'label.lxc.traffic.label',isEditable: true } } ], @@ -483,6 +490,7 @@ selectedPublicNetworkObj.kvmnetworklabel = trafficType.kvmnetworklabel; selectedPublicNetworkObj.vmwarenetworklabel = trafficType.vmwarenetworklabel; selectedPublicNetworkObj.ovmnetworklabel = trafficType.ovmnetworklabel; + selectedPublicNetworkObj.lxcnetworklabel = trafficType.lxcnetworklabel; args.response.success({data: selectedPublicNetworkObj}); } @@ -636,7 +644,8 @@ xennetworklabel: { label: 'label.xen.traffic.label', isEditable: true }, kvmnetworklabel: { label: 'label.kvm.traffic.label', isEditable: true }, vmwarenetworklabel: { label: 'label.vmware.traffic.label', isEditable: true }, - ovmnetworklabel: { label: 'OVM traffic label', isEditable: true } + ovmnetworklabel: { label: 'OVM traffic label', isEditable: true }, + lxcnetworklabel: { label: 'label.lxc.traffic.label', isEditable: true } } ], @@ -795,7 +804,8 @@ xennetworklabel: { label: 'label.xen.traffic.label', isEditable: true }, kvmnetworklabel: { label: 'label.kvm.traffic.label', isEditable: true }, vmwarenetworklabel: { label: 'label.vmware.traffic.label', isEditable: true }, - ovmnetworklabel: { label: 'OVM traffic label', isEditable: true } + ovmnetworklabel: { label: 'OVM traffic label', isEditable: true }, + lxcnetworklabel: { label: 'label.lxc.traffic.label', isEditable: true } } ], dataProvider: function(args) { @@ -811,6 +821,7 @@ selectedManagementNetworkObj.kvmnetworklabel = trafficType.kvmnetworklabel; selectedManagementNetworkObj.vmwarenetworklabel = trafficType.vmwarenetworklabel; selectedManagementNetworkObj.ovmnetworklabel = trafficType.ovmnetworklabel; + selectedManagementNetworkObj.lxcnetworklabel = trafficType.lxcnetworklabel; args.response.success({ data: selectedManagementNetworkObj }); } }); @@ -887,7 +898,59 @@ }); }, notification: { poll: pollAsyncJobResult } - } + }, + + addVlanRange:{ + label:'Add VLAN Range', + title:'Add VLAN Range', + + messages: { + confirm: function(args) { + return 'Are you sure you want to add another VLAN Range to this guest network?'; + }, + notification: function(args) { + return 'VLAN Range added'; + } + }, + + createForm:{ + title:'Add VLAN Range', + fields:{ + startvlan: {label:'Vlan Start', validation:{required:true}}, + endvlan:{label:'Vlan End', validation:{required:true}} + } + + }, + + action:function(args){ + + var array1=[]; + if(args.data.startvlan != "" && args.data.endvlan != ""){ + array1.push("&vlan=" + todb(args.data.startvlan) + "-" + todb(args.data.endvlan)); + + } + $.ajax({ + url: createURL("updatePhysicalNetwork&id=" + selectedPhysicalNetworkObj.id + array1.join("")), + dataType: "json", + success: function(json) { + var jobId = json.updatephysicalnetworkresponse.jobid; + + var trafficType = getTrafficType(selectedPhysicalNetworkObj, 'Guest'); + + updateTrafficLabels(trafficType, args.data, function() { + args.response.success({ _custom: { jobId: jobId }}); + }); + } + }); + + + }, + notification:{poll:pollAsyncJobResult} + + + } + + }, tabFilter: function(args) { @@ -928,7 +991,8 @@ xennetworklabel: { label: 'label.xen.traffic.label', isEditable: true }, kvmnetworklabel: { label: 'label.kvm.traffic.label', isEditable: true }, vmwarenetworklabel: { label: 'label.vmware.traffic.label', isEditable: true }, - ovmnetworklabel: { label: 'OVM traffic label', isEditable: true } + ovmnetworklabel: { label: 'OVM traffic label', isEditable: true }, + lxcnetworklabel: { label: 'label.lxc.traffic.label', isEditable: true } } ], dataProvider: function(args) { //physical network + Guest traffic type @@ -964,10 +1028,11 @@ selectedPhysicalNetworkObj["kvmnetworklabel"] = trafficType.kvmnetworklabel; selectedPhysicalNetworkObj["vmwarenetworklabel"] = trafficType.vmwarenetworklabel; selectedPhysicalNetworkObj["ovmnetworklabel"] = trafficType.ovmnetworklabel; + selectedPhysicalNetworkObj["lxcnetworklabel"] = trafficType.lxcnetworklabel; args.response.success({ actionFilter: function() { - var allowedActions = ['edit']; + var allowedActions = ['edit' , 'addVlanRange']; return allowedActions; }, data: selectedPhysicalNetworkObj @@ -4109,6 +4174,303 @@ notification: { poll: pollAsyncJobResult } } } + }, + // BigSwitch Vns provider detail view + bigswitchVns: { + type: 'detailView', + id: 'bigswitchVnsProvider', + label: 'label.bigswitchVns', + viewAll: { label: 'label.devices', path: '_zone.bigswitchVnsDevices' }, + tabs: { + details: { + title: 'label.details', + fields: [ + { + name: { label: 'label.name' } + }, + { + state: { label: 'label.state' } + } + ], + dataProvider: function(args) { + refreshNspData("BigSwitchVns"); + var providerObj; + $(nspHardcodingArray).each(function(){ + if(this.id == "bigswitchVns") { + providerObj = this; + return false; + } + }); + args.response.success({ + data: providerObj, + actionFilter: networkProviderActionFilter('bigswitchVns') + }); + } + } + }, + actions: { + add: { + label: 'label.add.BigSwitchVns.device', + createForm: { + title: 'label.add.BigSwitchVns.device', + preFilter: function(args) { }, + fields: { + host: { + label: 'label.ip.address' + }, + numretries: { + label: 'label.numretries', + defaultValue: '2' + }, + } + }, + action: function(args) { + if(nspMap["bigswitchVns"] == null) { + $.ajax({ + url: createURL("addNetworkServiceProvider&name=BigSwitchVns&physicalnetworkid=" + selectedPhysicalNetworkObj.id), + dataType: "json", + async: true, + success: function(json) { + var jobId = json.addnetworkserviceproviderresponse.jobid; + var addBigSwitchVnsProviderIntervalID = setInterval(function() { + $.ajax({ + url: createURL("queryAsyncJobResult&jobId="+jobId), + dataType: "json", + success: function(json) { + var result = json.queryasyncjobresultresponse; + if (result.jobstatus == 0) { + return; //Job has not completed + } + else { + clearInterval(addBigSwitchVnsProviderIntervalID); + if (result.jobstatus == 1) { + nspMap["bigswitchVns"] = json.queryasyncjobresultresponse.jobresult.networkserviceprovider; + addBigSwitchVnsDevice(args, selectedPhysicalNetworkObj, "addBigSwitchVnsDevice", "addbigswitchvnsdeviceresponse", "bigswitchvnsdevice") + } + else if (result.jobstatus == 2) { + alert("addNetworkServiceProvider&name=BigSwitchVns failed. Error: " + _s(result.jobresult.errortext)); + } + } + }, + error: function(XMLHttpResponse) { + var errorMsg = parseXMLHttpResponse(XMLHttpResponse); + alert("addNetworkServiceProvider&name=BigSwitchVns failed. Error: " + errorMsg); + } + }); + }, 3000); + } + }); + } + else { + addBigSwitchVnsDevice(args, selectedPhysicalNetworkObj, "addBigSwitchVnsDevice", "addbigswitchvnsdeviceresponse", "bigswitchvnsdevice") + } + }, + messages: { + notification: function(args) { + return 'label.add.BigSwitchVns.device'; + } + }, + notification: { + poll: pollAsyncJobResult + } + }, + enable: { + label: 'label.enable.provider', + action: function(args) { + $.ajax({ + url: createURL("updateNetworkServiceProvider&id=" + nspMap["bigswitchVns"].id + "&state=Enabled"), + dataType: "json", + success: function(json) { + var jid = json.updatenetworkserviceproviderresponse.jobid; + args.response.success( + {_custom: + { + jobId: jid, + getUpdatedItem: function(json) { + $(window).trigger('cloudStack.fullRefresh'); + } + } + } + ); + } + }); + }, + messages: { + confirm: function(args) { + return 'message.confirm.enable.provider'; + }, + notification: function() { + return 'label.enable.provider'; + } + }, + notification: { poll: pollAsyncJobResult } + }, + disable: { + label: 'label.disable.provider', + action: function(args) { + $.ajax({ + url: createURL("updateNetworkServiceProvider&id=" + nspMap["bigswitchVns"].id + "&state=Disabled"), + dataType: "json", + success: function(json) { + var jid = json.updatenetworkserviceproviderresponse.jobid; + args.response.success( + {_custom: + { + jobId: jid, + getUpdatedItem: function(json) { + $(window).trigger('cloudStack.fullRefresh'); + } + } + } + ); + } + }); + }, + messages: { + confirm: function(args) { + return 'message.confirm.disable.provider'; + }, + notification: function() { + return 'label.disable.provider'; + } + }, + notification: { poll: pollAsyncJobResult } + }, + destroy: { + label: 'label.shutdown.provider', + action: function(args) { + $.ajax({ + url: createURL("deleteNetworkServiceProvider&id=" + nspMap["bigswitchVns"].id), + dataType: "json", + success: function(json) { + var jid = json.deletenetworkserviceproviderresponse.jobid; + args.response.success( + {_custom: + { + jobId: jid + } + } + ); + + $(window).trigger('cloudStack.fullRefresh'); + } + }); + }, + messages: { + confirm: function(args) { + return 'message.confirm.shutdown.provider'; + }, + notification: function(args) { + return 'label.shutdown.provider'; + } + }, + notification: { poll: pollAsyncJobResult } + } + } + }, + + + // MidoNet provider detailView + midoNet: { + id: 'midoNet', + label: 'label.midoNet', + isMaximized: true, + type: 'detailView', + fields: { + name: { label: 'label.name' }, + //ipaddress: { label: 'label.ip.address' }, + state: { label: 'label.status', indicator: { 'Enabled': 'on' } } + }, + tabs: { + details: { + title: 'label.network', + fields: [ + { + name: { label: 'label.name' } + }, + { + id: { label: 'label.id' }, + state: { label: 'label.state' }, + physicalnetworkid: { label: 'label.physical.network.ID' }, + destinationphysicalnetworkid: { label: 'label.destination.physical.network.id' }, + supportedServices: { label: 'label.supported.services' } + } + ], + dataProvider: function(args) { + refreshNspData("MidoNet"); + args.response.success({ + actionFilter: virtualRouterProviderActionFilter, + data: $.extend(nspMap["midoNet"], { + supportedServices: nspMap["midoNet"].servicelist.join(', ') + }) + }); + } + }, + }, + actions: { + enable: { + label: 'label.enable.provider', + action: function(args) { + $.ajax({ + url: createURL("updateNetworkServiceProvider&id=" + nspMap["midoNet"].id + "&state=Enabled"), + dataType: "json", + success: function(json) { + var jid = json.updatenetworkserviceproviderresponse.jobid; + args.response.success( + {_custom: + { + jobId: jid, + getUpdatedItem: function(json) { + $(window).trigger('cloudStack.fullRefresh'); + } + } + } + ); + } + }); + }, + messages: { + confirm: function(args) { + return 'message.confirm.enable.provider'; + }, + notification: function() { + return 'label.enable.provider'; + } + }, + notification: { poll: pollAsyncJobResult } + }, + disable: { + label: 'label.disable.provider', + action: function(args) { + $.ajax({ + url: createURL("updateNetworkServiceProvider&id=" + nspMap["midoNet"].id + "&state=Disabled"), + dataType: "json", + success: function(json) { + var jid = json.updatenetworkserviceproviderresponse.jobid; + args.response.success( + {_custom: + { + jobId: jid, + getUpdatedItem: function(json) { + $(window).trigger('cloudStack.fullRefresh'); + } + } + } + ); + } + }); + }, + messages: { + confirm: function(args) { + return 'message.confirm.disable.provider'; + }, + notification: function() { + return 'label.disable.provider'; + } + }, + notification: { poll: pollAsyncJobResult } + } + } } } } @@ -6914,6 +7276,152 @@ } } }, + bigswitchVnsDevices: { + id: 'bigswitchVnsDevices', + title: 'label.devices', + listView: { + id: 'bigswitchVnsDevices', + fields: { + hostname: { label: 'label.bigswitch.controller.address' }, + }, + actions: { + add: { + label: 'label.add.BigSwitchVns.device', + createForm: { + title: 'label.add.BigSwitchVns.device', + preFilter: function(args) { }, + fields: { + host: { + label: 'label.ip.address' + }, + numretries: { + label: 'label.numretries', + defaultValue: '2' + }, + } + }, + action: function(args) { + if(nspMap["bigswitchVns"] == null) { + $.ajax({ + url: createURL("addNetworkServiceProvider&name=BigSwitchVns&physicalnetworkid=" + selectedPhysicalNetworkObj.id), + dataType: "json", + async: true, + success: function(json) { + var jobId = json.addnetworkserviceproviderresponse.jobid; + var addBigSwitchVnsProviderIntervalID = setInterval(function() { + $.ajax({ + url: createURL("queryAsyncJobResult&jobId="+jobId), + dataType: "json", + success: function(json) { + var result = json.queryasyncjobresultresponse; + if (result.jobstatus == 0) { + return; + } + else { + clearInterval(addBigSwitchVnsProviderIntervalID); + if (result.jobstatus == 1) { + nspMap["bigswitchVns"] = json.queryasyncjobresultresponse.jobresult.networkserviceprovider; + addBigSwitchVnsDevice(args, selectedPhysicalNetworkObj, "addBigSwitchVnsDevice", "addbigswitchvnsdeviceresponse", "bigswitchvnsdevice") + } + else if (result.jobstatus == 2) { + alert("addNetworkServiceProvider&name=BigSwitchVns failed. Error: " + _s(result.jobresult.errortext)); + } + } + }, + error: function(XMLHttpResponse) { + var errorMsg = parseXMLHttpResponse(XMLHttpResponse); + alert("addNetworkServiceProvider&name=BigSwitchVns failed. Error: " + errorMsg); + } + }); + }, 3000); + } + }); + } + else { + addBigSwitchVnsDevice(args, selectedPhysicalNetworkObj, "addBigSwitchVnsDevice", "addbigswitchvnsdeviceresponse", "bigswitchvnsdevice") + } + }, + + messages: { + notification: function(args) { + return 'Added new BigSwitch Vns Controller'; + } + }, + notification: { + poll: pollAsyncJobResult + } + } + }, + dataProvider: function(args) { + $.ajax({ + url: createURL("listBigSwitchVnsDevices&physicalnetworkid=" + selectedPhysicalNetworkObj.id), + data: { page: args.page, pageSize: pageSize }, + dataType: "json", + async: false, + success: function(json) { + var items = json.listbigswitchvnsdeviceresponse.bigswitchvnsdevice; + args.response.success({data: items}); + } + }); + }, + detailView: { + name: 'BigSwitch Vns details', + actions: { + 'remove': { + label: 'label.delete.BigSwitchVns', + messages: { + confirm: function(args) { + return 'message.confirm.delete.BigSwitchVns'; + }, + notification: function(args) { + return 'label.delete.BigSwitchVns'; + } + }, + action: function(args) { + $.ajax({ + url: createURL("deleteBigSwitchVnsDevice&vnsdeviceid=" + args.context.bigswitchvnsDevices[0].vnsdeviceid), + dataType: "json", + async: true, + success: function(json) { + var jid = json.deletebigswitchvnsdeviceresponse.jobid; + args.response.success( + {_custom: + {jobId: jid} + } + ); + } + }); + }, + notification: { + poll: pollAsyncJobResult + } + } + }, + tabs: { + details: { + title: 'label.details', + fields: [ + { + vnsdeviceid: { label: 'label.id' }, + hostname: { label: 'label.ip.address' }, + } + ], + dataProvider: function(args) { + $.ajax({ + url: createURL("listBigSwitchVnsDevices&vnsdeviceid=" + args.context.bigswitchVnsDevices[0].vnsdeviceid), + dataType: "json", + async: true, + success: function(json) { + var item = json.listbigswitchvnsdeviceresponse.bigswitchvnsdevice[0]; + args.response.success({data: item}); + } + }); + } + } + } + } + } + }, pods: { title: 'label.pods', listView: { @@ -8964,8 +9472,8 @@ select: function(args) { var scope = [ { id: 'zone', description: _l('label.zone.wide') }, - { id: 'cluster', description: _l('label.cluster') }, - { id: 'host', description: _l('label.host') } + { id: 'cluster', description: _l('label.cluster') } + // { id: 'host', description: _l('label.host') } ]; args.response.success({ @@ -9152,6 +9660,13 @@ items.push({id: "ocfs2", description: "ocfs2"}); args.response.success({data: items}); } + else if(selectedClusterObj.hypervisortype == "LXC") { + var items = []; + items.push({id: "nfs", description: "nfs"}); + items.push({id: "SharedMountPoint", description: "SharedMountPoint"}); + items.push({id: "rbd", description: "RBD"}); + args.response.success({data: items}); + } else { args.response.success({data:[]}); } @@ -10397,6 +10912,30 @@ }); } + function addBigSwitchVnsDevice(args, physicalNetworkObj, apiCmd, apiCmdRes, apiCmdObj) { + var array1 = []; + array1.push("&physicalnetworkid=" + physicalNetworkObj.id); + array1.push("&hostname=" + todb(args.data.host)); + + $.ajax({ + url: createURL(apiCmd + array1.join("")), + dataType: "json", + success: function(json) { + var jid = json[apiCmdRes].jobid; + args.response.success( + {_custom: + {jobId: jid, + getUpdatedItem: function(json) { + var item = json.queryasyncjobresultresponse.jobresult[apiCmdObj]; + + return item; + } + } + } + ); + } + }); + } var afterCreateZonePhysicalNetworkTrafficTypes = function(args, newZoneObj, newPhysicalnetwork) { $.ajax({ @@ -10970,6 +11509,9 @@ case "Netscaler": nspMap["netscaler"] = items[i]; break; + case "MidoNet": + nspMap["midoNet"] = items[i]; + break; case "F5BigIp": nspMap["f5"] = items[i]; break; @@ -10982,6 +11524,9 @@ case "NiciraNvp": nspMap["niciraNvp"] = items[i]; break; + case "BigSwitchVns": + nspMap["bigswitchVns"] = items[i]; + break; } } } @@ -11003,7 +11548,12 @@ id: 'niciraNvp', name: 'Nicira Nvp', state: nspMap.niciraNvp ? nspMap.niciraNvp.state : 'Disabled' - } + }, + { + id: 'bigswitchVns', + name: 'BigSwitch Vns', + state: nspMap.bigswitchVns ? nspMap.bigswitchVns.state : 'Disabled' + } ]; if(selectedZoneObj.networktype == "Basic") { @@ -11018,6 +11568,13 @@ else if(selectedZoneObj.networktype == "Advanced"){ nspHardcodingArray.push( { + id: 'midoNet', + name: 'MidoNet', + state: nspMap.midoNet? nspMap.midoNet.state : 'Disabled' + } + ); + nspHardcodingArray.push( + { id: 'vpcVirtualRouter', name: 'VPC Virtual Router', state: nspMap.vpcVirtualRouter ? nspMap.vpcVirtualRouter.state : 'Disabled' diff --git a/ui/scripts/templates.js b/ui/scripts/templates.js index 040ce4a92c1..6268f6b29b5 100644 --- a/ui/scripts/templates.js +++ b/ui/scripts/templates.js @@ -237,6 +237,10 @@ //formatSelect.append(""); items.push({id:'RAW', description: 'RAW'}); } + else if(args.hypervisor == "LXC") { + //formatSelect.append(""); + items.push({id:'TAR', description: 'TAR'}); + } args.response.success({data: items}); } }, diff --git a/ui/scripts/ui/widgets/detailView.js b/ui/scripts/ui/widgets/detailView.js index 0731dda8928..4b520f934ba 100644 --- a/ui/scripts/ui/widgets/detailView.js +++ b/ui/scripts/ui/widgets/detailView.js @@ -304,7 +304,16 @@ } if($detailView.data("list-view-row") != null) { - $detailView.data("list-view-row").remove(); + var $row = $detailView.data('list-view-row'); + var $tbody = $row.closest('tbody'); + + $row.remove(); + if(!$tbody.find('tr').size()) { + $("").addClass('empty').append( + $("").html(_l('label.no.data')) + ).appendTo($tbody); + } + $tbody.closest('table').dataTable('refresh'); } } }); diff --git a/ui/scripts/vpc.js b/ui/scripts/vpc.js index 4281ca283fa..a4834f26c72 100644 --- a/ui/scripts/vpc.js +++ b/ui/scripts/vpc.js @@ -616,6 +616,7 @@ } }, gateways: { + add: { preCheck: function(args) { if(isAdmin()) { //root-admin @@ -732,6 +733,92 @@ netmask: { label: 'label.netmask', validation: { required: true }}, vlan: { label: 'label.vlan', validation: { required: true }} }, + + actions:{ + add:{ + label:'Add Private Gateway', + createForm:{ + title: 'label.add.new.gateway', + desc: 'message.add.new.gateway.to.vpc', + fields: { + physicalnetworkid: { + docID: 'helpVPCGatewayPhysicalNetwork', + label: 'label.physical.network', + select: function(args) { + $.ajax({ + url: createURL("listPhysicalNetworks"), + data: { + zoneid: args.context.vpc[0].zoneid + }, + success: function(json) { + var objs = json.listphysicalnetworksresponse.physicalnetwork; + var items = []; + $(objs).each(function() { + items.push({id: this.id, description: this.name}); + }); + args.response.success({data: items}); + } + }); + } + }, + vlan: { + label: 'label.vlan', validation: { required: true }, + docID: 'helpVPCGatewayVLAN' + }, + ipaddress: { + label: 'label.ip.address', validation: { required: true }, + docID: 'helpVPCGatewayIP' + }, + gateway: { + label: 'label.gateway', validation: { required: true }, + docID: 'helpVPCGatewayGateway' + }, + netmask: { + label: 'label.netmask', validation: { required: true }, + docID: 'helpVPCGatewayNetmask' + } + } + + + + }, + action:function(args){ + $.ajax({ + url: createURL('createPrivateGateway'), + data: { + physicalnetworkid: args.data.physicalnetworkid, + vpcid: args.context.vpc[0].id, + ipaddress: args.data.ipaddress, + gateway: args.data.gateway, + netmask: args.data.netmask, + vlan: args.data.vlan + }, + success: function(json) { + var jid = json.createprivategatewayresponse.jobid; + args.response.success( + {_custom: + {jobId: jid, + getUpdatedItem: function(json) { + return json.queryasyncjobresultresponse.jobresult.privategateway; + } + } + } + ); + }, + error: function(json) { + args.response.error(parseXMLHttpResponse(json)); + } + }); + }, + + notification: { + poll: pollAsyncJobResult + } + + + } + }, + dataProvider: function(args) { $.ajax({ url: createURL('listPrivateGateways'), diff --git a/ui/scripts/zoneWizard.js b/ui/scripts/zoneWizard.js index c09da8a33a2..8add9bb085e 100755 --- a/ui/scripts/zoneWizard.js +++ b/ui/scripts/zoneWizard.js @@ -53,6 +53,9 @@ case 'Ovm': hypervisorAttr = 'ovmnetworklabel'; break; + case 'LXC': + hypervisorAttr = 'lxcnetworklabel'; + break; } trafficLabelStr = trafficLabel ? '&' + hypervisorAttr + '=' + trafficLabel : ''; @@ -395,6 +398,7 @@ nonSupportedHypervisors["VMware"] = 1; nonSupportedHypervisors["BareMetal"] = 1; nonSupportedHypervisors["Ovm"] = 1; + nonSupportedHypervisors["LXC"] = 1; } if(items != null) { @@ -1185,16 +1189,32 @@ scope: { label: 'label.scope', select: function(args) { + + var selectedHypervisorObj = { + hypervisortype: $.isArray(args.context.zones[0].hypervisor) ? + // We want the cluster's hypervisor type + args.context.zones[0].hypervisor[1] : args.context.zones[0].hypervisor + }; - var scope = [ - { id: 'zone', description: _l('label.zone.wide') }, - { id: 'cluster', description: _l('label.cluster') }, - { id: 'host', description: _l('label.host') } - ]; + if(selectedHypervisorObj == null) { + return; + } - args.response.success({ - data: scope - }); + // ZWPS is supported only for KVM as the hypervisor + if(selectedHypervisorObj.hypervisortype != "KVM"){ + var scope=[]; + scope.push({ id: 'cluster', description: _l('label.cluster') }); + //scope.push({ id: 'host', description: _l('label.host') }); + args.response.success({data: scope}); + } + + else { + var scope=[]; + scope.push({ id: 'zone', description: _l('label.zone.wide') }); + scope.push({ id: 'cluster', description: _l('label.cluster') }); + // scope.push({ id: 'host', description: _l('label.host') }); + args.response.success({data: scope}); + } } @@ -1240,6 +1260,12 @@ items.push({id: "ocfs2", description: "ocfs2"}); args.response.success({data: items}); } + else if(selectedClusterObj.hypervisortype == "LXC") { + var items = []; + items.push({id: "nfs", description: "nfs"}); + items.push({id: "SharedMountPoint", description: "SharedMountPoint"}); + args.response.success({data: items}); + } else { args.response.success({data:[]}); } diff --git a/usage/resources/usageApplicationContext.xml b/usage/resources/usageApplicationContext.xml index 0340038a06a..fc67e0ad32a 100644 --- a/usage/resources/usageApplicationContext.xml +++ b/usage/resources/usageApplicationContext.xml @@ -38,17 +38,16 @@ - - - - - - - - + + + + + + + + + diff --git a/usage/src/com/cloud/usage/UsageServer.java b/usage/src/com/cloud/usage/UsageServer.java index 881962f5c79..3f2b43e2bc9 100644 --- a/usage/src/com/cloud/usage/UsageServer.java +++ b/usage/src/com/cloud/usage/UsageServer.java @@ -17,12 +17,14 @@ package com.cloud.usage; import java.io.File; +import java.io.FileNotFoundException; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.xml.DOMConfigurator; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.util.Log4jConfigurer; import com.cloud.utils.PropertiesUtil; import com.cloud.utils.component.ComponentContext; @@ -75,12 +77,21 @@ public class UsageServer { static private void initLog4j() { File file = PropertiesUtil.findConfigFile("log4j-cloud.xml"); if (file != null) { - s_logger.info("log4j configuration found at " + file.getAbsolutePath()); - DOMConfigurator.configureAndWatch(file.getAbsolutePath()); + System.out.println("log4j configuration found at " + file.getAbsolutePath()); + try { + Log4jConfigurer.initLogging(file.getAbsolutePath()); + } catch (FileNotFoundException e) { + } + DOMConfigurator.configureAndWatch(file.getAbsolutePath()); + } else { file = PropertiesUtil.findConfigFile("log4j-cloud.properties"); if (file != null) { - s_logger.info("log4j configuration found at " + file.getAbsolutePath()); + System.out.println("log4j configuration found at " + file.getAbsolutePath()); + try { + Log4jConfigurer.initLogging(file.getAbsolutePath()); + } catch (FileNotFoundException e) { + } PropertyConfigurator.configureAndWatch(file.getAbsolutePath()); } } diff --git a/utils/src/com/cloud/utils/component/AdapterBase.java b/utils/src/com/cloud/utils/component/AdapterBase.java index ea5e9611ab6..8353cee967a 100644 --- a/utils/src/com/cloud/utils/component/AdapterBase.java +++ b/utils/src/com/cloud/utils/component/AdapterBase.java @@ -19,7 +19,7 @@ package com.cloud.utils.component; import java.util.List; // Typical Adapter implementation. -public class AdapterBase extends ComponentLifecycleBase implements Adapter { +public class AdapterBase extends ComponentLifecycleBase implements Adapter, ComponentMethodInterceptable { public AdapterBase() { // set default run level for adapter components @@ -29,7 +29,7 @@ public class AdapterBase extends ComponentLifecycleBase implements Adapter { public static T getAdapterByName(List adapters, String name) { for(T adapter : adapters) { if(adapter.getName() != null && adapter.getName().equalsIgnoreCase(name)) - return ComponentContext.getTargetObject(adapter); + return adapter; } return null; } diff --git a/utils/src/com/cloud/utils/component/MatchAnyMethodPointcut.java b/utils/src/com/cloud/utils/component/AdapterList.java similarity index 76% rename from utils/src/com/cloud/utils/component/MatchAnyMethodPointcut.java rename to utils/src/com/cloud/utils/component/AdapterList.java index dd597344fa3..ae8671772f2 100644 --- a/utils/src/com/cloud/utils/component/MatchAnyMethodPointcut.java +++ b/utils/src/com/cloud/utils/component/AdapterList.java @@ -16,12 +16,19 @@ // under the License. package com.cloud.utils.component; -import java.lang.reflect.Method; +import java.util.List; -import org.springframework.aop.support.StaticMethodMatcherPointcut; +public class AdapterList { + protected List adapters; -public class MatchAnyMethodPointcut extends StaticMethodMatcherPointcut { - public boolean matches(Method method, Class cls) { - return true; - } + public AdapterList() { + } + + public List getAdapters() { + return adapters; + } + + public void setAdapters(List adapters) { + this.adapters = adapters; + } } diff --git a/utils/src/com/cloud/utils/component/ComponentContext.java b/utils/src/com/cloud/utils/component/ComponentContext.java index ca7ad5c7b4b..796d4ec0282 100644 --- a/utils/src/com/cloud/utils/component/ComponentContext.java +++ b/utils/src/com/cloud/utils/component/ComponentContext.java @@ -59,16 +59,18 @@ public class ComponentContext implements ApplicationContextAware { public static ApplicationContext getApplicationContext() { return s_appContext; - } - + } + public static void initComponentsLifeCycle() { - // Run the SystemIntegrityCheckers first - Map integrityCheckers = getApplicationContext().getBeansOfType(SystemIntegrityChecker.class); - for (Entry entry : integrityCheckers.entrySet() ){ - s_logger.info ("Running SystemIntegrityChecker " + entry.getKey()); - entry.getValue().check(); - } - + AutowireCapableBeanFactory beanFactory = s_appContext.getAutowireCapableBeanFactory(); + + Map interceptableComponents = getApplicationContext().getBeansOfType( + ComponentMethodInterceptable.class); + for(Map.Entry entry : interceptableComponents.entrySet()) { + Object bean = getTargetObject(entry.getValue()); + beanFactory.configureBean(bean, entry.getKey()); + } + Map lifecyleComponents = getApplicationContext().getBeansOfType(ComponentLifecycle.class); Map[] classifiedComponents = new Map[ComponentLifecycle.MAX_RUN_LEVELS]; @@ -79,6 +81,18 @@ public class ComponentContext implements ApplicationContextAware { for(Map.Entry entry : lifecyleComponents.entrySet()) { classifiedComponents[entry.getValue().getRunLevel()].put(entry.getKey(), entry.getValue()); } + + // Run the SystemIntegrityCheckers first + Map integrityCheckers = getApplicationContext().getBeansOfType(SystemIntegrityChecker.class); + for (Entry entry : integrityCheckers.entrySet() ){ + s_logger.info ("Running SystemIntegrityChecker " + entry.getKey()); + try { + entry.getValue().check(); + } catch(Throwable e) { + s_logger.error("System integrity check failed. Refuse to startup"); + System.exit(1); + } + } // configuration phase Map avoidMap = new HashMap(); diff --git a/utils/src/com/cloud/utils/component/ComponentInstantiationPostProcessor.java b/utils/src/com/cloud/utils/component/ComponentInstantiationPostProcessor.java new file mode 100644 index 00000000000..cb64975d585 --- /dev/null +++ b/utils/src/com/cloud/utils/component/ComponentInstantiationPostProcessor.java @@ -0,0 +1,152 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The 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.utils.component; + +import java.beans.PropertyDescriptor; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; + +import net.sf.cglib.proxy.Callback; +import net.sf.cglib.proxy.CallbackFilter; +import net.sf.cglib.proxy.Enhancer; +import net.sf.cglib.proxy.MethodInterceptor; +import net.sf.cglib.proxy.MethodProxy; +import net.sf.cglib.proxy.NoOp; + +import org.apache.log4j.Logger; +import org.springframework.beans.BeansException; +import org.springframework.beans.PropertyValues; +import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor; + +import com.cloud.utils.Pair; + +public class ComponentInstantiationPostProcessor implements InstantiationAwareBeanPostProcessor { + private static final Logger s_logger = Logger.getLogger(ComponentInstantiationPostProcessor.class); + + private List _interceptors = new ArrayList(); + private Callback[] _callbacks; + private CallbackFilter _callbackFilter; + + public ComponentInstantiationPostProcessor() { + _callbacks = new Callback[2]; + _callbacks[0] = NoOp.INSTANCE; + _callbacks[1] = new InterceptorDispatcher(); + + _callbackFilter = new InterceptorFilter(); + } + + public List getInterceptors() { + return _interceptors; + } + + public void setInterceptors(List interceptors) { + _interceptors = interceptors; + } + + private Callback[] getCallbacks() { + return _callbacks; + } + + private CallbackFilter getCallbackFilter() { + return _callbackFilter; + } + + @Override + public Object postProcessBeforeInitialization(Object bean, String beanName) + throws BeansException { + return bean; + } + + @Override + public Object postProcessAfterInitialization(Object bean, String beanName) + throws BeansException { + return bean; + } + + @Override + public Object postProcessBeforeInstantiation(Class beanClass, + String beanName) throws BeansException { + if(_interceptors != null && _interceptors.size() > 0) { + if(ComponentMethodInterceptable.class.isAssignableFrom(beanClass)) { + Enhancer enhancer = new Enhancer(); + enhancer.setSuperclass(beanClass); + enhancer.setCallbacks(getCallbacks()); + enhancer.setCallbackFilter(getCallbackFilter()); + enhancer.setNamingPolicy(ComponentNamingPolicy.INSTANCE); + + Object bean = enhancer.create(); + return bean; + } + } + return null; + } + + @Override + public boolean postProcessAfterInstantiation(Object bean, String beanName) + throws BeansException { + return true; + } + + @Override + public PropertyValues postProcessPropertyValues(PropertyValues pvs, + PropertyDescriptor[] pds, Object bean, String beanName) + throws BeansException { + return pvs; + } + + protected class InterceptorDispatcher implements MethodInterceptor { + @Override + public Object intercept(Object target, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { + ArrayList> interceptors = new ArrayList>(); + + for (ComponentMethodInterceptor interceptor : getInterceptors()) { + if (interceptor.needToIntercept(method)) { + Object objReturnedInInterceptStart = interceptor.interceptStart(method, target); + interceptors.add(new Pair(interceptor, objReturnedInInterceptStart)); + } + } + boolean success = false; + try { + Object obj = methodProxy.invokeSuper(target, args); + success = true; + return obj; + } finally { + for (Pair interceptor : interceptors) { + if (success) { + interceptor.first().interceptComplete(method, target, interceptor.second()); + } else { + interceptor.first().interceptException(method, target, interceptor.second()); + } + } + } + } + } + + protected class InterceptorFilter implements CallbackFilter { + @Override + public int accept(Method method) { + for(ComponentMethodInterceptor interceptor : getInterceptors()) { + + if (interceptor.needToIntercept(method)) { + return 1; + } + } + return 0; + } + } +} diff --git a/utils/src/com/cloud/utils/component/InterceptorLibrary.java b/utils/src/com/cloud/utils/component/ComponentMethodInterceptable.java similarity index 85% rename from utils/src/com/cloud/utils/component/InterceptorLibrary.java rename to utils/src/com/cloud/utils/component/ComponentMethodInterceptable.java index 96be50b07ef..5a95c43ea93 100644 --- a/utils/src/com/cloud/utils/component/InterceptorLibrary.java +++ b/utils/src/com/cloud/utils/component/ComponentMethodInterceptable.java @@ -16,10 +16,9 @@ // under the License. package com.cloud.utils.component; -import java.util.List; - -public interface InterceptorLibrary { - - void addInterceptors(List> interceptors); - +/** + * Marker interface to work with CGLIB based CloudStack legacy AOP + * + */ +public interface ComponentMethodInterceptable { } diff --git a/utils/src/com/cloud/utils/component/AnnotationInterceptor.java b/utils/src/com/cloud/utils/component/ComponentMethodInterceptor.java similarity index 63% rename from utils/src/com/cloud/utils/component/AnnotationInterceptor.java rename to utils/src/com/cloud/utils/component/ComponentMethodInterceptor.java index e69862c9022..39a81d0349c 100644 --- a/utils/src/com/cloud/utils/component/AnnotationInterceptor.java +++ b/utils/src/com/cloud/utils/component/ComponentMethodInterceptor.java @@ -16,21 +16,12 @@ // under the License. package com.cloud.utils.component; -import java.lang.reflect.AnnotatedElement; +import java.lang.reflect.Method; -import net.sf.cglib.proxy.Callback; - -/** - * AnnotationIntercepter says it can intercept an annotation. - */ -public interface AnnotationInterceptor { - boolean needToIntercept(AnnotatedElement element); - - T interceptStart(AnnotatedElement element); - - void interceptComplete(AnnotatedElement element, T attach); - - void interceptException(AnnotatedElement element, T attach); - - Callback getCallback(); +public interface ComponentMethodInterceptor { + boolean needToIntercept(Method method); + + Object interceptStart(Method method, Object target); + void interceptComplete(Method method, Object target, Object objReturnedInInterceptStart); + void interceptException(Method method, Object target, Object objReturnedInInterceptStart); } diff --git a/utils/src/com/cloud/utils/component/ComponentMethodProxyCache.java b/utils/src/com/cloud/utils/component/ComponentMethodProxyCache.java deleted file mode 100644 index ea3b68573cf..00000000000 --- a/utils/src/com/cloud/utils/component/ComponentMethodProxyCache.java +++ /dev/null @@ -1,90 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.component; - -import java.lang.ref.WeakReference; -import java.lang.reflect.Method; -import java.util.WeakHashMap; - -public class ComponentMethodProxyCache { - - private static WeakHashMap> s_cache = new WeakHashMap>(); - - public ComponentMethodProxyCache() { - } - - public static Method getTargetMethod(Method method, Object target) { - synchronized(s_cache) { - WeakReference targetMethod = s_cache.get(new TargetKey(method, target)); - if(targetMethod != null && targetMethod.get() != null) - return targetMethod.get(); - - Class clazz = target.getClass(); - for(Method m : clazz.getMethods()) { - if(isMethodMatched(method, m)) { - s_cache.put(new TargetKey(method, target), new WeakReference(m)); - return m; - } - } - - return method; - } - } - - private static boolean isMethodMatched(Method m1, Method m2) { - if(!m1.getName().equals(m2.getName())) - return false; - - Class[] params1 = m1.getParameterTypes(); - Class[] params2 = m2.getParameterTypes(); - - if(params1.length != params2.length) - return false; - - for(int i = 0; i < params1.length; i++) { - if(!params1[i].isAssignableFrom(params2[i])) - return false; - } - - return true; - } - - public static class TargetKey { - Method _method; - Object _target; - - public TargetKey(Method method, Object target) { - _method = method; - _target = target; - } - - @Override - public boolean equals(Object obj) { - if(!(obj instanceof TargetKey)) - return false; - - // for target object, we just check the reference - return _method.equals(((TargetKey)obj)._method) && - _target == ((TargetKey)obj)._target; - } - - public int hashCode() { - return _target.hashCode() ^ _target.hashCode(); - } - } -} diff --git a/utils/src/com/cloud/utils/component/ComponentNamingPolicy.java b/utils/src/com/cloud/utils/component/ComponentNamingPolicy.java new file mode 100644 index 00000000000..5659a487395 --- /dev/null +++ b/utils/src/com/cloud/utils/component/ComponentNamingPolicy.java @@ -0,0 +1,63 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The 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.utils.component; + +import net.sf.cglib.core.NamingPolicy; +import net.sf.cglib.core.Predicate; + +/** + * Copied/Modified from Spring source + * + */ +public class ComponentNamingPolicy implements NamingPolicy { + + public static final ComponentNamingPolicy INSTANCE = new ComponentNamingPolicy(); + + public String getClassName(String prefix, String source, Object key, Predicate names) { + if (prefix == null) { + prefix = "net.sf.cglib.empty.Object"; + } else if (prefix.startsWith("java")) { + prefix = "_" + prefix; + } + String base = + prefix + "_" + + source.substring(source.lastIndexOf('.') + 1) + + getTag() + "_" + + Integer.toHexString(key.hashCode()); + String attempt = base; + int index = 2; + while (names.evaluate(attempt)) + attempt = base + "_" + index++; + return attempt; + } + + /** + * Returns a string which is incorporated into every generated class name. + * By default returns "ByCloudStack" + */ + protected String getTag() { + return "ByCloudStack"; + } + + public int hashCode() { + return getTag().hashCode(); + } + + public boolean equals(Object o) { + return (o instanceof ComponentNamingPolicy) && ((ComponentNamingPolicy) o).getTag().equals(getTag()); + } +} diff --git a/utils/src/com/cloud/utils/component/ManagerBase.java b/utils/src/com/cloud/utils/component/ManagerBase.java index 529ef629201..1908f4e1051 100644 --- a/utils/src/com/cloud/utils/component/ManagerBase.java +++ b/utils/src/com/cloud/utils/component/ManagerBase.java @@ -16,7 +16,7 @@ // under the License. package com.cloud.utils.component; -public class ManagerBase extends ComponentLifecycleBase { +public class ManagerBase extends ComponentLifecycleBase implements ComponentMethodInterceptable { public ManagerBase() { // set default run level for manager components setRunLevel(ComponentLifecycle.RUN_LEVEL_COMPONENT_BOOTSTRAP); diff --git a/utils/src/com/cloud/utils/component/SpringComponentScanUtils.java b/utils/src/com/cloud/utils/component/SpringComponentScanUtils.java index 9a85c79fa80..28b84e68ce9 100644 --- a/utils/src/com/cloud/utils/component/SpringComponentScanUtils.java +++ b/utils/src/com/cloud/utils/component/SpringComponentScanUtils.java @@ -1,41 +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 -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.component; - -import org.springframework.context.annotation.ComponentScan; - -import com.cloud.utils.exception.CloudRuntimeException; - -public class SpringComponentScanUtils { - - public static boolean includedInBasePackageClasses(String clazzName, ComponentScan cs) { - Class clazzToCheck; - try { - clazzToCheck = Class.forName(clazzName); - } catch (ClassNotFoundException e) { - throw new CloudRuntimeException("Unable to find " + clazzName); - } - Class[] clazzes = cs.basePackageClasses(); - for (Class clazz : clazzes) { - if (clazzToCheck.isAssignableFrom(clazz)) { - return true; - } - } - return false; - } -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The 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.utils.component; + +import org.springframework.context.annotation.ComponentScan; + +import com.cloud.utils.exception.CloudRuntimeException; + +public class SpringComponentScanUtils { + + public static boolean includedInBasePackageClasses(String clazzName, ComponentScan cs) { + Class clazzToCheck; + try { + clazzToCheck = Class.forName(clazzName); + } catch (ClassNotFoundException e) { + throw new CloudRuntimeException("Unable to find " + clazzName); + } + Class[] clazzes = cs.basePackageClasses(); + for (Class clazz : clazzes) { + if (clazzToCheck.isAssignableFrom(clazz)) { + return true; + } + } + return false; + } +} diff --git a/utils/src/com/cloud/utils/db/DatabaseCallback.java b/utils/src/com/cloud/utils/db/DatabaseCallback.java deleted file mode 100644 index 718acf545c9..00000000000 --- a/utils/src/com/cloud/utils/db/DatabaseCallback.java +++ /dev/null @@ -1,84 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.lang.reflect.AnnotatedElement; -import java.lang.reflect.Method; - -import net.sf.cglib.proxy.Callback; -import net.sf.cglib.proxy.MethodInterceptor; -import net.sf.cglib.proxy.MethodProxy; - -import com.cloud.utils.component.AnnotationInterceptor; - -public class DatabaseCallback implements MethodInterceptor, AnnotationInterceptor { - - @Override - public Object intercept(Object object, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { - Transaction txn = interceptStart(method); - try { - return methodProxy.invokeSuper(object, args); - } finally { - interceptComplete(method, txn); - } - } - - @Override - public boolean needToIntercept(AnnotatedElement element) { - if (!(element instanceof Method)) { - return false; - - } - Method method = (Method)element; - DB db = method.getAnnotation(DB.class); - if (db != null) { - return db.txn(); - } - - Class clazz = method.getDeclaringClass(); - do { - db = clazz.getAnnotation(DB.class); - if (db != null) { - return db.txn(); - } - clazz = clazz.getSuperclass(); - } while (clazz != Object.class && clazz != null); - - return false; - } - - @Override - public Transaction interceptStart(AnnotatedElement element) { - return Transaction.open(((Method)element).getName()); - } - - @Override - public void interceptComplete(AnnotatedElement element, Transaction txn) { - txn.close(); - } - - @Override - public void interceptException(AnnotatedElement element, Transaction txn) { - txn.close(); - } - - @Override - public Callback getCallback() { - return this; - } - -} diff --git a/utils/src/com/cloud/utils/db/DatabaseCallbackFilter.java b/utils/src/com/cloud/utils/db/DatabaseCallbackFilter.java deleted file mode 100755 index 7bace706e29..00000000000 --- a/utils/src/com/cloud/utils/db/DatabaseCallbackFilter.java +++ /dev/null @@ -1,58 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.lang.reflect.Method; - -import net.sf.cglib.proxy.CallbackFilter; - -public class DatabaseCallbackFilter implements CallbackFilter { - @Override - public int accept(Method method) { - return checkAnnotation(method) ? 1 : 0; - } - - public static boolean checkAnnotation(Method method) { - /*Check self*/ - DB db = method.getAnnotation(DB.class); - if (db != null) { - return db.txn(); - } - Class clazz = method.getDeclaringClass(); - - /*Check parent method*/ - try { - Method pMethod = clazz.getMethod(method.getName(), method.getParameterTypes()); - db = pMethod.getAnnotation(DB.class); - if (db != null) { - return db.txn(); - } - } catch (SecurityException e) { - } catch (NoSuchMethodException e) { - } - - /*Check class's annotation and ancestor's annotation*/ - do { - db = clazz.getAnnotation(DB.class); - if (db != null) { - return db.txn(); - } - clazz = clazz.getSuperclass(); - } while (clazz != Object.class && clazz != null); - return false; - } -} diff --git a/utils/src/com/cloud/utils/db/GenericDaoBase.java b/utils/src/com/cloud/utils/db/GenericDaoBase.java index afb12471da7..f0fc7006003 100755 --- a/utils/src/com/cloud/utils/db/GenericDaoBase.java +++ b/utils/src/com/cloud/utils/db/GenericDaoBase.java @@ -71,6 +71,7 @@ import com.cloud.utils.Ternary; import com.cloud.utils.component.ComponentContext; import com.cloud.utils.component.ComponentLifecycle; import com.cloud.utils.component.ComponentLifecycleBase; +import com.cloud.utils.component.ComponentMethodInterceptable; import com.cloud.utils.crypt.DBEncryptionUtil; import com.cloud.utils.db.SearchCriteria.SelectType; import com.cloud.utils.exception.CloudRuntimeException; @@ -114,7 +115,7 @@ import edu.emory.mathcs.backport.java.util.Collections; * **/ @DB -public abstract class GenericDaoBase extends ComponentLifecycleBase implements GenericDao { +public abstract class GenericDaoBase extends ComponentLifecycleBase implements GenericDao, ComponentMethodInterceptable { private final static Logger s_logger = Logger.getLogger(GenericDaoBase.class); protected final static TimeZone s_gmtTimeZone = TimeZone.getTimeZone("GMT"); @@ -193,15 +194,14 @@ public abstract class GenericDaoBase extends Compone ( (Class)((Class)t).getGenericSuperclass()).getGenericSuperclass()).getActualTypeArguments()[0]; } -/* - s_daoMaps.put(_entityBeanType, ComponentContext.getComponent(this.getClass())); + s_daoMaps.put(_entityBeanType, this); Class[] interphaces = _entityBeanType.getInterfaces(); if (interphaces != null) { for (Class interphace : interphaces) { - s_daoMaps.put(interphace, ComponentContext.getComponent(this.getClass())); + s_daoMaps.put(interphace, this); } } -*/ + _table = DbUtil.getTableName(_entityBeanType); final SqlGenerator generator = new SqlGenerator(_entityBeanType); @@ -1750,25 +1750,6 @@ public abstract class GenericDaoBase extends Compone public boolean configure(final String name, final Map params) throws ConfigurationException { _name = name; - Class daoInterface = null; - for(Class intf : this.getClass().getInterfaces()) { - if(GenericDao.class.isAssignableFrom(intf)) { - daoInterface = intf; - break; - } - } - - if(daoInterface != null) { - s_logger.info("Register dao interface in GenericDaoBase entity-DAO map. " + daoInterface.getName()); - s_daoMaps.put(_entityBeanType, (GenericDao) ComponentContext.getComponent(daoInterface)); - Class[] interphaces = _entityBeanType.getInterfaces(); - if (interphaces != null) { - for (Class interphace : interphaces) { - s_daoMaps.put(interphace, (GenericDao) ComponentContext.getComponent(daoInterface)); - } - } - } - final String value = (String)params.get("lock.timeout"); _timeoutSeconds = NumbersUtil.parseInt(value, 300); diff --git a/utils/src/com/cloud/utils/db/TransactionContextBuilder.java b/utils/src/com/cloud/utils/db/TransactionContextBuilder.java index 7ca33ab5f5d..40fcbbf5593 100644 --- a/utils/src/com/cloud/utils/db/TransactionContextBuilder.java +++ b/utils/src/com/cloud/utils/db/TransactionContextBuilder.java @@ -18,65 +18,20 @@ package com.cloud.utils.db; import java.lang.reflect.Method; -import org.aopalliance.intercept.MethodInterceptor; -import org.aopalliance.intercept.MethodInvocation; -import org.apache.log4j.Logger; -import org.aspectj.lang.ProceedingJoinPoint; -import org.aspectj.lang.reflect.MethodSignature; +import com.cloud.utils.component.ComponentMethodInterceptor; -import com.cloud.utils.component.ComponentMethodProxyCache; - -public class TransactionContextBuilder implements MethodInterceptor { - private static final Logger s_logger = Logger.getLogger(TransactionContextBuilder.class); +public class TransactionContextBuilder implements ComponentMethodInterceptor { public TransactionContextBuilder() { } - public Object AroundAnyMethod(ProceedingJoinPoint call) throws Throwable { - MethodSignature methodSignature = (MethodSignature)call.getSignature(); - Method targetMethod = methodSignature.getMethod(); - if(needToIntercept(targetMethod, call.getTarget())) { - Transaction txn = Transaction.open(call.getSignature().getName()); - Object ret = null; - try { - ret = call.proceed(); - } finally { - txn.close(); - } - return ret; - } - return call.proceed(); - } - @Override - public Object invoke(MethodInvocation method) throws Throwable { - Method targetMethod = method.getMethod(); - - if(needToIntercept(targetMethod, method.getThis())) { - Transaction txn = Transaction.open(targetMethod.getName()); - Object ret = null; - try { - ret = method.proceed(); - } finally { - txn.close(); - } - return ret; - } - return method.proceed(); - } - - private boolean needToIntercept(Method method, Object target) { + public boolean needToIntercept(Method method) { DB db = method.getAnnotation(DB.class); if (db != null) { return true; } Class clazz = method.getDeclaringClass(); - if(clazz.isInterface()) { - clazz = target.getClass(); - Method targetMethod = ComponentMethodProxyCache.getTargetMethod(method, target); - if(targetMethod != null && targetMethod.getAnnotation(DB.class) != null) - return true; - } do { db = clazz.getAnnotation(DB.class); @@ -88,4 +43,23 @@ public class TransactionContextBuilder implements MethodInterceptor { return false; } + + @Override + public Object interceptStart(Method method, Object target) { + return Transaction.open(method.getName()); + } + + @Override + public void interceptComplete(Method method, Object target, Object objReturnedInInterceptStart) { + Transaction txn = (Transaction)objReturnedInInterceptStart; + if(txn != null) + txn.close(); + } + + @Override + public void interceptException(Method method, Object target, Object objReturnedInInterceptStart) { + Transaction txn = (Transaction)objReturnedInInterceptStart; + if(txn != null) + txn.close(); + } } diff --git a/utils/src/com/cloud/utils/script/Script.java b/utils/src/com/cloud/utils/script/Script.java index cb258449e43..3632bf5ad1b 100755 --- a/utils/src/com/cloud/utils/script/Script.java +++ b/utils/src/com/cloud/utils/script/Script.java @@ -460,20 +460,7 @@ public class Script implements Callable { } public static String runSimpleBashScript(String command) { - - Script s = new Script("/bin/bash"); - s.add("-c"); - s.add(command); - - OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser(); - if (s.execute(parser) != null) - return null; - - String result = parser.getLine(); - if (result == null || result.trim().isEmpty()) - return null; - else - return result.trim(); + return Script.runSimpleBashScript(command, 0); } public static String runSimpleBashScript(String command, int timeout) { @@ -493,10 +480,4 @@ public class Script implements Callable { return result.trim(); } - public static void main(String[] args) { - String path = findScript(".", "try.sh"); - Script script = new Script(path, 5000, s_logger); - script.execute(); - System.exit(1); - } } diff --git a/utils/src/com/cloud/utils/xmlobject/XmlObject.java b/utils/src/com/cloud/utils/xmlobject/XmlObject.java index 80ac13df794..67bb8ed7cac 100644 --- a/utils/src/com/cloud/utils/xmlobject/XmlObject.java +++ b/utils/src/com/cloud/utils/xmlobject/XmlObject.java @@ -14,183 +14,183 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.utils.xmlobject; - -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import com.cloud.utils.exception.CloudRuntimeException; - -import edu.emory.mathcs.backport.java.util.Collections; - -public class XmlObject { - private Map elements = new HashMap(); - private String text; - private String tag; - - XmlObject() { - } - - public XmlObject(String tag) { - this.tag = tag; - } - +package com.cloud.utils.xmlobject; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import com.cloud.utils.exception.CloudRuntimeException; + +import edu.emory.mathcs.backport.java.util.Collections; + +public class XmlObject { + private Map elements = new HashMap(); + private String text; + private String tag; + + XmlObject() { + } + + public XmlObject(String tag) { + this.tag = tag; + } + public XmlObject putElement(String key, Object e) { if (e == null) { throw new IllegalArgumentException(String.format("element[%s] can not be null", key)); - } - Object old = elements.get(key); - if (old == null) { - System.out.println(String.format("no %s, add new", key)); - elements.put(key, e); - } else { - if (old instanceof List) { - System.out.println(String.format("already list %s, add", key)); - ((List)old).add(e); - } else { - System.out.println(String.format("not list list %s, add list", key)); - List lst = new ArrayList(); - lst.add(old); - lst.add(e); - elements.put(key, lst); - } - } - - return this; - } - - private Object recurGet(XmlObject obj, Iterator it) { - String key = it.next(); - Object e = obj.elements.get(key); - if (e == null) { - return null; - } - - if (!it.hasNext()) { - return e; - } else { - if (!(e instanceof XmlObject)) { - throw new CloudRuntimeException(String.format("%s doesn't reference to a XmlObject", it.next())); - } - return recurGet((XmlObject) e, it); - } - } - - public T get(String elementStr) { - String[] strs = elementStr.split("\\."); - List lst = new ArrayList(strs.length); - Collections.addAll(lst, strs); - return (T)recurGet(this, lst.iterator()); - } - - public List getAsList(String elementStr) { - Object e = get(elementStr); - if (e instanceof List) { - return (List)e; - } - List lst = new ArrayList(1); - lst.add(e); - return lst; - } - - public String getText() { - return text; - } - - public XmlObject setText(String text) { - this.text = text; - return this; - } - - public String getTag() { - return tag; - } - - public XmlObject setTag(String tag) { - this.tag = tag; - return this; - } - - public String dump() { - StringBuilder sb = new StringBuilder(); - sb.append("<").append(tag); - List children = new ArrayList(); - for (Map.Entry e : elements.entrySet()) { - String key = e.getKey(); - Object val = e.getValue(); - if (val instanceof String) { - sb.append(String.format(" %s=\"%s\"", key, val.toString())); - } else if (val instanceof XmlObject) { - children.add((XmlObject) val); - } else if (val instanceof List) { - children.addAll((Collection) val); - } else { - throw new CloudRuntimeException(String.format("unsupported element type[tag:%s, class: %s], only allowed type of [String, List, Object]", key, val.getClass().getName())); - } - } - - if (!children.isEmpty() && text != null) { - throw new CloudRuntimeException(String.format("element %s cannot have both text[%s] and child elements", tag, text)); - } - - if (!children.isEmpty()) { - sb.append(">"); - for (XmlObject x : children) { - sb.append(x.dump()); - } - sb.append(String.format("", tag)); - } else { - if (text != null) { - sb.append(">"); - sb.append(text); - sb.append(String.format("", tag)); - } else { - sb.append(" />"); - } - } - return sb.toString(); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("<" + tag); - for (Map.Entry e : elements.entrySet()) { - String key = e.getKey(); - Object value = e.getValue(); - if (!(value instanceof String)) { - continue; - } - sb.append(String.format(" %s=\"%s\"", key, value.toString())); - } - - if (text == null || "".equals(text.trim())) { - sb.append(" />"); - } else { - sb.append(">").append(text).append(String.format("", tag)); - } - return sb.toString(); - } - - public T evaluateObject(T obj) { - Class clazz = obj.getClass(); - try { - do { - Field[] fs = clazz.getDeclaredFields(); - for (Field f : fs) { - f.setAccessible(true); - Object value = get(f.getName()); - f.set(obj, value); - } - clazz = clazz.getSuperclass(); - } while (clazz != null && clazz != Object.class); - return obj; - } catch (Exception e) { - throw new CloudRuntimeException(e); - } - } -} + } + Object old = elements.get(key); + if (old == null) { + System.out.println(String.format("no %s, add new", key)); + elements.put(key, e); + } else { + if (old instanceof List) { + System.out.println(String.format("already list %s, add", key)); + ((List)old).add(e); + } else { + System.out.println(String.format("not list list %s, add list", key)); + List lst = new ArrayList(); + lst.add(old); + lst.add(e); + elements.put(key, lst); + } + } + + return this; + } + + private Object recurGet(XmlObject obj, Iterator it) { + String key = it.next(); + Object e = obj.elements.get(key); + if (e == null) { + return null; + } + + if (!it.hasNext()) { + return e; + } else { + if (!(e instanceof XmlObject)) { + throw new CloudRuntimeException(String.format("%s doesn't reference to a XmlObject", it.next())); + } + return recurGet((XmlObject) e, it); + } + } + + public T get(String elementStr) { + String[] strs = elementStr.split("\\."); + List lst = new ArrayList(strs.length); + Collections.addAll(lst, strs); + return (T)recurGet(this, lst.iterator()); + } + + public List getAsList(String elementStr) { + Object e = get(elementStr); + if (e instanceof List) { + return (List)e; + } + List lst = new ArrayList(1); + lst.add(e); + return lst; + } + + public String getText() { + return text; + } + + public XmlObject setText(String text) { + this.text = text; + return this; + } + + public String getTag() { + return tag; + } + + public XmlObject setTag(String tag) { + this.tag = tag; + return this; + } + + public String dump() { + StringBuilder sb = new StringBuilder(); + sb.append("<").append(tag); + List children = new ArrayList(); + for (Map.Entry e : elements.entrySet()) { + String key = e.getKey(); + Object val = e.getValue(); + if (val instanceof String) { + sb.append(String.format(" %s=\"%s\"", key, val.toString())); + } else if (val instanceof XmlObject) { + children.add((XmlObject) val); + } else if (val instanceof List) { + children.addAll((Collection) val); + } else { + throw new CloudRuntimeException(String.format("unsupported element type[tag:%s, class: %s], only allowed type of [String, List, Object]", key, val.getClass().getName())); + } + } + + if (!children.isEmpty() && text != null) { + throw new CloudRuntimeException(String.format("element %s cannot have both text[%s] and child elements", tag, text)); + } + + if (!children.isEmpty()) { + sb.append(">"); + for (XmlObject x : children) { + sb.append(x.dump()); + } + sb.append(String.format("", tag)); + } else { + if (text != null) { + sb.append(">"); + sb.append(text); + sb.append(String.format("", tag)); + } else { + sb.append(" />"); + } + } + return sb.toString(); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("<" + tag); + for (Map.Entry e : elements.entrySet()) { + String key = e.getKey(); + Object value = e.getValue(); + if (!(value instanceof String)) { + continue; + } + sb.append(String.format(" %s=\"%s\"", key, value.toString())); + } + + if (text == null || "".equals(text.trim())) { + sb.append(" />"); + } else { + sb.append(">").append(text).append(String.format("", tag)); + } + return sb.toString(); + } + + public T evaluateObject(T obj) { + Class clazz = obj.getClass(); + try { + do { + Field[] fs = clazz.getDeclaredFields(); + for (Field f : fs) { + f.setAccessible(true); + Object value = get(f.getName()); + f.set(obj, value); + } + clazz = clazz.getSuperclass(); + } while (clazz != null && clazz != Object.class); + return obj; + } catch (Exception e) { + throw new CloudRuntimeException(e); + } + } +} diff --git a/utils/src/com/cloud/utils/xmlobject/XmlObjectParser.java b/utils/src/com/cloud/utils/xmlobject/XmlObjectParser.java index af62bed999e..3a44c5152ee 100644 --- a/utils/src/com/cloud/utils/xmlobject/XmlObjectParser.java +++ b/utils/src/com/cloud/utils/xmlobject/XmlObjectParser.java @@ -14,110 +14,110 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.utils.xmlobject; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.util.Stack; - -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; - -import org.xml.sax.Attributes; -import org.xml.sax.SAXException; -import org.xml.sax.helpers.DefaultHandler; - -import com.cloud.utils.exception.CloudRuntimeException; - -public class XmlObjectParser { - final private InputStream is; - - private class XmlHandler extends DefaultHandler { - private Stack stack; - private String currentValue; - private XmlObject root; - - XmlHandler() { - stack = new Stack(); - } - - @Override - public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { - //System.out.println(String.format("startElement: namespaceURI:%s, localName:%s, qName:%s", namespaceURI, localName, qName)); - currentValue = null; - XmlObject obj = new XmlObject(); - for (int i=0; i stack; + private String currentValue; + private XmlObject root; + + XmlHandler() { + stack = new Stack(); + } + + @Override + public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { + //System.out.println(String.format("startElement: namespaceURI:%s, localName:%s, qName:%s", namespaceURI, localName, qName)); + currentValue = null; + XmlObject obj = new XmlObject(); + for (int i=0; i lst = xo.get("management-server.adapters"); - for (XmlObject x : lst) { - List lst1 = x.getAsList("adapter"); - for (XmlObject y : lst1) { - p(y.toString()); - } - } - */ - } - -} +package com.cloud.utils.xmlobject; + +import static org.junit.Assert.*; + +import java.util.List; + +import org.junit.Test; + +public class TestXmlObject { + + void p(String str) { + System.out.println(str); + } + + @Test + public void test() { + + // deprecated, since we no longer use component.xml.in any more + /* + XmlObject xo = XmlObjectParser.parseFromFile("z:/components.xml.in"); + p(xo.getTag()); + p((String) xo.get("system-integrity-checker.checker").toString()); + List lst = xo.get("management-server.adapters"); + for (XmlObject x : lst) { + List lst1 = x.getAsList("adapter"); + for (XmlObject y : lst1) { + p(y.toString()); + } + } + */ + } + +} diff --git a/utils/test/com/cloud/utils/xmlobject/TestXmlObject2.java b/utils/test/com/cloud/utils/xmlobject/TestXmlObject2.java index 9bde687d2f2..e7e0d10659b 100644 --- a/utils/test/com/cloud/utils/xmlobject/TestXmlObject2.java +++ b/utils/test/com/cloud/utils/xmlobject/TestXmlObject2.java @@ -14,40 +14,40 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.utils.xmlobject; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class TestXmlObject2 { - void p(String str) { - System.out.println(str); - } - - XmlObject xo(String name) { - return new XmlObject(name); - } - - @Test - public void test() { - XmlObject root = new XmlObject("test"); - root.putElement("key1", "value1").putElement("key2", "value2"); - p(root.dump()); - - XmlObject c1 = new XmlObject("child1"); - XmlObject c2 = new XmlObject("child2"); - c2.putElement("ckey1", "value1"); - c1.putElement(c2.getTag(), c2); - root.putElement(c1.getTag(), c1); - p(root.dump()); - - root = xo("test2").putElement("key1", "value1").putElement("child1", xo("child1").setText("yyy")) - .putElement("child1", xo("child1") - .putElement("child2", xo("child2") - .putElement("child3", xo("child3").putElement("key3", "value3").setText("xxxxx")))); - - p(root.dump()); - } - -} +package com.cloud.utils.xmlobject; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class TestXmlObject2 { + void p(String str) { + System.out.println(str); + } + + XmlObject xo(String name) { + return new XmlObject(name); + } + + @Test + public void test() { + XmlObject root = new XmlObject("test"); + root.putElement("key1", "value1").putElement("key2", "value2"); + p(root.dump()); + + XmlObject c1 = new XmlObject("child1"); + XmlObject c2 = new XmlObject("child2"); + c2.putElement("ckey1", "value1"); + c1.putElement(c2.getTag(), c2); + root.putElement(c1.getTag(), c1); + p(root.dump()); + + root = xo("test2").putElement("key1", "value1").putElement("child1", xo("child1").setText("yyy")) + .putElement("child1", xo("child1") + .putElement("child2", xo("child2") + .putElement("child3", xo("child3").putElement("key3", "value3").setText("xxxxx")))); + + p(root.dump()); + } + +} diff --git a/utils/test/resources/testContext.xml b/utils/test/resources/testContext.xml index 26cdaaed32f..5cccfcdd745 100644 --- a/utils/test/resources/testContext.xml +++ b/utils/test/resources/testContext.xml @@ -33,22 +33,18 @@ - + - - - - - - - - - + + + + + + +