Merge remote-tracking branch 'origin/master' into marvin

This commit is contained in:
Girish Shilamkar 2014-01-29 14:20:04 +05:30
commit df58f51e33
450 changed files with 12670 additions and 9836 deletions

View File

@ -1,16 +1,16 @@
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.

View File

@ -114,3 +114,7 @@ domr.scripts.dir=scripts/network/domr/kvm
# for examples:"Conroe" "Penryn", "Nehalem", "Westmere", "pentiumpro" and so
# on,run virsh capabilities for more details.
# guest.cpu.model=
#
# vm.memballoon.disable=true
# Disable memory ballooning on vm guests for overcommit, by default overcommit
# feature enables balloon and sets currentMemory to a minimum value.

View File

@ -1,4 +1,3 @@
#!/bin/bash
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
@ -15,15 +14,5 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# @VERSION@
cert="/root/.ssh/id_rsa.cloud"
domr=$1
shift
ssh -p 3922 -o StrictHostKeyChecking=no -i $cert root@$domr "/opt/cloud/bin/ipsectunnel.sh $*" >/dev/null
exit $?
name=api-config
parent=core

View File

@ -0,0 +1,32 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"
>
<bean id="apiServiceConfiguration" class="org.apache.cloudstack.config.ApiServiceConfiguration" />
</beans>

View File

@ -33,6 +33,8 @@ public class IpAddressTO {
private Integer networkRate;
private TrafficType trafficType;
private String networkName;
private Integer nicDevId;
private boolean newNic;
public IpAddressTO(long accountId, String ipAddress, boolean add, boolean firstIP, boolean sourceNat, String broadcastUri, String vlanGateway, String vlanNetmask,
String vifMacAddress, Integer networkRate, boolean isOneToOneNat) {
@ -116,4 +118,19 @@ public class IpAddressTO {
return networkRate;
}
public Integer getNicDevId() {
return nicDevId;
}
public void setNicDevId(Integer nicDevId) {
this.nicDevId = nicDevId;
}
public boolean isNewNic() {
return newNic;
}
public void setNewNic(boolean newNic) {
this.newNic = newNic;
}
}

View File

@ -112,7 +112,7 @@ public interface Network extends ControlledEntity, StateObject<Network.State>, I
private static List<Provider> supportedProviders = new ArrayList<Provider>();
public static final Provider VirtualRouter = new Provider("VirtualRouter", false);
public static final Provider JuniperContrail = new Provider("JuniperContrail", false);
public static final Provider JuniperContrailRouter = new Provider("JuniperContrailRouter", false);
public static final Provider JuniperSRX = new Provider("JuniperSRX", true);
public static final Provider PaloAlto = new Provider("PaloAlto", true);
public static final Provider F5BigIp = new Provider("F5BigIp", true);

View File

@ -110,7 +110,7 @@ public interface NetworkService {
long findPhysicalNetworkId(long zoneId, String tag, TrafficType trafficType);
PhysicalNetworkTrafficType addTrafficTypeToPhysicalNetwork(Long physicalNetworkId, String trafficType, String xenLabel, String kvmLabel, String vmwareLabel,
PhysicalNetworkTrafficType addTrafficTypeToPhysicalNetwork(Long physicalNetworkId, String trafficType, String isolationMethod, String xenLabel, String kvmLabel, String vmwareLabel,
String simulatorLabel, String vlan, String hypervLabel);
PhysicalNetworkTrafficType getPhysicalNetworkTrafficType(Long id);

View File

@ -94,7 +94,22 @@ public class Networks {
return uri.getSchemeSpecificPart();
}
},
Mido("mido", String.class), Pvlan("pvlan", String.class), Vxlan("vxlan", Long.class), UnDecided(null, null), OpenDaylight("opendaylight", String.class);
Mido("mido", String.class), Pvlan("pvlan", String.class),
Vxlan("vxlan", Long.class) {
@Override
public <T> URI toUri(T value) {
try {
if (value.toString().contains("://"))
return new URI(value.toString());
else
return new URI("vxlan://" + value.toString());
} catch (URISyntaxException e) {
throw new CloudRuntimeException(
"Unable to convert to broadcast URI: " + value);
}
}
},
UnDecided(null, null), OpenDaylight("opendaylight", String.class);
private final String scheme;
private final Class<?> type;

View File

@ -33,7 +33,7 @@ public interface PhysicalNetwork extends Identity, InternalIdentity {
}
public enum IsolationMethod {
VLAN, L3, GRE, STT, VNS, MIDO, SSP, VXLAN, ODL;
VLAN, L3, GRE, STT, VNS, MIDO, SSP, VXLAN, ODL, L3VPN;
}
public enum BroadcastDomainRange {

View File

@ -69,5 +69,5 @@ public interface VirtualNetworkApplianceService {
List<Long> upgradeRouterTemplate(UpgradeRouterTemplateCmd cmd);
public static final String MinVRVersion = "4.2.0";
public static final String MinVRVersion = "4.3.0";
}

View File

@ -36,7 +36,8 @@ public interface FirewallRule extends ControlledEntity, Identity, InternalIdenti
Staged, // Rule been created but has never got through network rule conflict detection. Rules in this state can not be sent to network elements.
Add, // Add means the rule has been created and has gone through network rule conflict detection.
Active, // Rule has been sent to the network elements and reported to be active.
Revoke // Revoke means this rule has been revoked. If this rule has been sent to the network elements, the rule will be deleted from database.
Revoke, // Revoke means this rule has been revoked. If this rule has been sent to the network elements, the rule will be deleted from database.
Deleting // rule has been revoked and is scheduled for deletion
}
enum TrafficType {

View File

@ -25,7 +25,8 @@ public interface StaticRoute extends ControlledEntity, Identity, InternalIdentit
Staged, // route been created but has never got through network rule conflict detection. Routes in this state can not be sent to VPC virtual router.
Add, // Add means the route has been created and has gone through network rule conflict detection.
Active, // Route has been sent to the VPC router and reported to be active.
Revoke // Revoke means this route has been revoked. If this route has been sent to the VPC router, the route will be deleted from database.
Revoke, // Revoke means this route has been revoked. If this route has been sent to the VPC router, the route will be deleted from database.
Deleting // rule has been revoked and is scheduled for deletion
}
/**

View File

@ -24,25 +24,49 @@ public interface ResourceTag extends ControlledEntity, Identity, InternalIdentit
// FIXME - extract enum to another interface as its used both by resourceTags and resourceMetaData code
public enum ResourceObjectType {
UserVm(true, true), Template(true, true), ISO(true, false), Volume(true, true), Snapshot(true, false), Network(true, true), Nic(false, true), LoadBalancer(true, true), PortForwardingRule(
true, true), FirewallRule(true, true), SecurityGroup(true, false), PublicIpAddress(true, true), Project(true, false), Vpc(true, true), NetworkACL(true, true), StaticRoute(
true, false), VMSnapshot(true, false), RemoteAccessVpn(true, true), Zone(false, true), ServiceOffering(false, true), Storage(false, true), PrivateGateway(false,
true), NetworkACLList(false, true), VpnGateway(false, true), CustomerGateway(false, true), VpnConnection(false, true), User(true, true), DiskOffering(false, true);
UserVm(true, true),
Template(true, true),
ISO(true, false),
Volume(true, true),
Snapshot(true, false),
Network(true, true),
Nic(false, true),
LoadBalancer(true, true),
PortForwardingRule(true, true),
FirewallRule(true, true),
SecurityGroup(true, false),
PublicIpAddress(true, true),
Project(true, false),
Vpc(true, true),
NetworkACL(true, true),
StaticRoute(true, false),
VMSnapshot(true, false),
RemoteAccessVpn(true, true),
Zone(false, true),
ServiceOffering(false, true),
Storage(false, true),
PrivateGateway(false, true),
NetworkACLList(false, true),
VpnGateway(false, true),
CustomerGateway(false, true),
VpnConnection(false, true),
User(true, true),
DiskOffering(false, true);
ResourceObjectType(boolean resourceTagsSupport, boolean resourceMetadataSupport) {
this.resourceTagsSupport = resourceTagsSupport;
this.metadataSupport = resourceMetadataSupport;
metadataSupport = resourceMetadataSupport;
}
private final boolean resourceTagsSupport;
private final boolean metadataSupport;
public boolean resourceTagsSupport() {
return this.resourceTagsSupport;
return resourceTagsSupport;
}
public boolean resourceMetadataSupport() {
return this.metadataSupport;
return metadataSupport;
}
}

View File

@ -461,4 +461,12 @@ public interface UserVmService {
UserVm expungeVm(long vmId) throws ResourceUnavailableException, ConcurrentOperationException;
/**
* Finds and returns an encrypted password for a VM.
*
* @param userVmId
* @return Base64 encoded userdata
*/
String getVmUserData(long vmId);
}

View File

@ -124,6 +124,7 @@ public interface VirtualMachine extends RunningOn, ControlledEntity, Identity, I
s_fsm.addTransition(State.Stopping, VirtualMachine.Event.FollowAgentPowerOffReport, State.Stopped);
s_fsm.addTransition(State.Running, VirtualMachine.Event.FollowAgentPowerOffReport, State.Stopped);
s_fsm.addTransition(State.Migrating, VirtualMachine.Event.FollowAgentPowerOffReport, State.Stopped);
s_fsm.addTransition(State.Stopped, VirtualMachine.Event.FollowAgentPowerOffReport, State.Stopped);
}
public static boolean isVmStarted(State oldState, Event e, State newState) {

View File

@ -344,6 +344,7 @@ public class ApiConstants {
public static final String CAPACITY_IOPS = "capacityiops";
public static final String NETWORK_SPEED = "networkspeed";
public static final String BROADCAST_DOMAIN_RANGE = "broadcastdomainrange";
public static final String ISOLATION_METHOD = "isolationmethod";
public static final String ISOLATION_METHODS = "isolationmethods";
public static final String PHYSICAL_NETWORK_ID = "physicalnetworkid";
public static final String DEST_PHYSICAL_NETWORK_ID = "destinationphysicalnetworkid";

View File

@ -26,6 +26,8 @@ import java.util.regex.Pattern;
import javax.inject.Inject;
import org.apache.log4j.Logger;
import org.apache.cloudstack.affinity.AffinityGroupService;
import org.apache.cloudstack.alert.AlertService;
import org.apache.cloudstack.network.element.InternalLoadBalancerElementService;
@ -33,7 +35,6 @@ import org.apache.cloudstack.network.lb.ApplicationLoadBalancerService;
import org.apache.cloudstack.network.lb.InternalLoadBalancerVMService;
import org.apache.cloudstack.query.QueryService;
import org.apache.cloudstack.usage.UsageService;
import org.apache.log4j.Logger;
import com.cloud.configuration.ConfigurationService;
import com.cloud.domain.Domain;
@ -153,8 +154,6 @@ public abstract class BaseCmd {
@Inject
public ResourceLimitService _resourceLimitService;
@Inject
public IdentityService _identityService;
@Inject
public StorageNetworkService _storageNetworkService;
@Inject
public TaggedResourceService _taggedResourceService;
@ -358,11 +357,11 @@ public abstract class BaseCmd {
}
public void setFullUrlParams(Map<String, String> map) {
this.fullUrlParams = map;
fullUrlParams = map;
}
public Map<String, String> getFullUrlParams() {
return this.fullUrlParams;
return fullUrlParams;
}
public Long finalyzeAccountId(String accountName, Long domainId, Long projectId, boolean enabledOnly) {

View File

@ -77,6 +77,10 @@ public class AddTrafficTypeCmd extends BaseAsyncCreateCmd {
@Parameter(name = ApiConstants.VLAN, type = CommandType.STRING, description = "The VLAN id to be used for Management traffic by VMware host")
private String vlan;
@Parameter(name=ApiConstants.ISOLATION_METHOD, type=CommandType.STRING, description="Used if physical network has multiple isolation types and traffic type is public."
+ " Choose which isolation method. Valid options currently 'vlan' or 'vxlan', defaults to 'vlan'.")
private String isolationMethod;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
@ -118,6 +122,14 @@ public class AddTrafficTypeCmd extends BaseAsyncCreateCmd {
return vlan;
}
public String getIsolationMethod() {
if (isolationMethod != null && !isolationMethod.isEmpty()) {
return isolationMethod;
} else {
return "vlan";
}
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@ -148,7 +160,7 @@ public class AddTrafficTypeCmd extends BaseAsyncCreateCmd {
@Override
public void create() throws ResourceAllocationException {
PhysicalNetworkTrafficType result =
_networkService.addTrafficTypeToPhysicalNetwork(getPhysicalNetworkId(), getTrafficType(), getXenLabel(), getKvmLabel(), getVmwareLabel(),
_networkService.addTrafficTypeToPhysicalNetwork(getPhysicalNetworkId(), getTrafficType(), getIsolationMethod(), getXenLabel(), getKvmLabel(), getVmwareLabel(),
getSimulatorLabel(), getVlan(), getHypervLabel());
if (result != null) {
setEntityId(result.getId());

View File

@ -0,0 +1,81 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.cloudstack.api.command.admin.vm;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.BaseCmd;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.response.UserVmResponse;
import org.apache.cloudstack.api.response.VMUserDataResponse;
import org.apache.log4j.Logger;
import com.cloud.user.Account;
import com.cloud.uservm.UserVm;
@APICommand(name = "getVirtualMachineUserData", description = "Returns user data associated with the VM", responseObject = VMUserDataResponse.class, since = "4.4")
public class GetVMUserDataCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(GetVMUserDataCmd.class);
private static final String s_name = "getvirtualmachineuserdataresponse";
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
@Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID, type = CommandType.UUID, entityType = UserVmResponse.class, required = true, description = "The ID of the virtual machine")
private Long vmId;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
public long getId() {
return vmId;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@Override
public void execute() {
String userData = _userVmService.getVmUserData(getId());
VMUserDataResponse resp = new VMUserDataResponse();
resp.setVmId(_entityMgr.findById(UserVm.class, getId()).getUuid());
resp.setUserData(userData);
resp.setObjectName("virtualmachineuserdata");
resp.setResponseName(getCommandName());
this.setResponseObject(resp);
}
@Override
public long getEntityOwnerId() {
UserVm userVm = _entityMgr.findById(UserVm.class, getId());
if (userVm != null) {
return userVm.getAccountId();
}
return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked
}
@Override
public String getCommandName() {
return s_name;
}
}

View File

@ -130,7 +130,7 @@ public class AddIpToVmNicCmd extends BaseAsyncCmd {
try {
result = _networkService.allocateSecondaryGuestIP(getNicId(), getIpaddress());
} catch (InsufficientAddressCapacityException e) {
throw new InvalidParameterValueException("Allocating guest ip for nic failed");
throw new InvalidParameterValueException("Allocating guest ip for nic failed : " + e.getMessage());
}
if (result != null) {

View File

@ -0,0 +1,44 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.cloudstack.api.response;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.BaseResponse;
import com.cloud.serializer.Param;
import com.google.gson.annotations.SerializedName;
public class VMUserDataResponse extends BaseResponse {
@SerializedName(ApiConstants.VIRTUAL_MACHINE_ID)
@Param(description = "the ID of the virtual machine")
private String vmId;
@SerializedName(ApiConstants.USER_DATA)
@Param(description = "Base 64 encoded VM user data")
private String userData;
public void setUserData(String userData) {
this.userData = userData;
}
public void setVmId(String vmId) {
this.vmId = vmId;
}
}

View File

@ -0,0 +1,40 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.config;
import javax.ejb.Local;
import org.apache.cloudstack.framework.config.ConfigKey;
import org.apache.cloudstack.framework.config.Configurable;
@Local(value = {ApiServiceConfiguration.class})
public class ApiServiceConfiguration implements Configurable {
public static final ConfigKey<String> ManagementHostIPAdr = new ConfigKey<String>("Advanced", String.class, "host", "localhost", "The ip address of management server", true);
public static final ConfigKey<String> ApiServletPath = new ConfigKey<String>("Advanced", String.class, "api.servlet.endpoint", "http://localhost:8080/client/api?",
"API end point. Can be used by CS components/services deployed remotely, for sending CS API requests", true);
@Override
public String getConfigComponentName() {
return ApiServiceConfiguration.class.getSimpleName();
}
@Override
public ConfigKey<?>[] getConfigKeys() {
return new ConfigKey<?>[] {ManagementHostIPAdr, ApiServletPath};
}
}

View File

@ -142,7 +142,7 @@
</exclusion>
<exclusion>
<groupId>org.opensaml</groupId>
<artifactId>opensaml</artifactId>
<artifactId>opensaml1</artifactId>
</exclusion>
</exclusions>
</dependency>
@ -162,7 +162,7 @@
</exclusion>
<exclusion>
<groupId>org.opensaml</groupId>
<artifactId>opensaml</artifactId>
<artifactId>opensaml1</artifactId>
</exclusion>
</exclusions>
</dependency>
@ -178,7 +178,7 @@
</exclusion>
<exclusion>
<groupId>org.opensaml</groupId>
<artifactId>opensaml</artifactId>
<artifactId>opensaml1</artifactId>
</exclusion>
</exclusions>
</dependency>
@ -194,7 +194,7 @@
</exclusion>
<exclusion>
<groupId>org.opensaml</groupId>
<artifactId>opensaml</artifactId>
<artifactId>opensaml1</artifactId>
</exclusion>
</exclusions>
</dependency>
@ -210,7 +210,7 @@
</exclusion>
<exclusion>
<groupId>org.opensaml</groupId>
<artifactId>opensaml</artifactId>
<artifactId>opensaml1</artifactId>
</exclusion>
</exclusions>
</dependency>
@ -223,7 +223,6 @@
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.1</version>
<scope>runtime</scope>
</dependency>
<dependency>
@ -271,8 +270,6 @@
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk16</artifactId>
<!-- TODO: do we need this explicit version override? -->
<version>1.45</version>
<scope>runtime</scope>
</dependency>
<dependency>
@ -320,9 +317,9 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>${cs.checkstyle.version}</version>
<executions>
<execution>
<id>cloudstack-checkstyle</id>
<phase>none</phase>
</execution>
</executions>

View File

@ -66,6 +66,7 @@ import com.cloud.stack.models.CloudStackPasswordData;
import com.cloud.stack.models.CloudStackResourceLimit;
import com.cloud.stack.models.CloudStackResourceTag;
import com.cloud.stack.models.CloudStackSecurityGroup;
import com.cloud.stack.models.CloudStackServiceOffering;
import com.cloud.stack.models.CloudStackSnapshot;
import com.cloud.stack.models.CloudStackTemplate;
import com.cloud.stack.models.CloudStackTemplatePermission;
@ -1414,7 +1415,7 @@ public class EC2Engine extends ManagerBase {
if (request.getInstanceType() != null) {
instanceType = request.getInstanceType();
}
CloudStackServiceOfferingVO svcOffering = getCSServiceOfferingId(instanceType);
CloudStackServiceOffering svcOffering = getCSServiceOfferingId(instanceType);
if (svcOffering == null) {
logger.info("No ServiceOffering found to be defined by name, please contact the administrator " + instanceType);
throw new Exception("instanceType not found");
@ -1609,7 +1610,7 @@ public class EC2Engine extends ManagerBase {
if (request.getInstanceType() != null) {
String instanceType = request.getInstanceType();
CloudStackServiceOfferingVO svcOffering = getCSServiceOfferingId(instanceType);
CloudStackServiceOffering svcOffering = getCSServiceOfferingId(instanceType);
if (svcOffering == null)
throw new Exception("instanceType not found");
CloudStackUserVm userVm = getApi().changeServiceForVirtualMachine(instanceId, svcOffering.getId());
@ -1783,11 +1784,12 @@ public class EC2Engine extends ManagerBase {
*
*/
private CloudStackServiceOfferingVO getCSServiceOfferingId(String instanceType) throws Exception {
private CloudStackServiceOffering getCSServiceOfferingId(String instanceType) throws Exception {
try {
if (instanceType == null)
instanceType = "m1.small"; // default value
return scvoDao.getSvcOfferingByName(instanceType);
List<CloudStackServiceOffering> serviceOfferings = getApi().listServiceOfferings(null, null, false, null, instanceType, null, null);
return serviceOfferings.get(0);
} catch (Exception e) {
logger.error("Error while retrieving ServiceOffering information by name - ", e);
throw new Exception("No ServiceOffering found to be defined by name");

View File

@ -31,7 +31,7 @@ label.smb.password=SMB Password
label.smb.domain=SMB Domain
label.hypervisors=Hypervisors
label.home=Home
label.sockets=Sockets
label.sockets=CPU Sockets
label.root.disk.size=Root disk size
label.s3.nfs.server=S3 NFS Server
label.s3.nfs.path=S3 NFS Path
@ -706,6 +706,7 @@ label.lang.arabic=Arabic
label.lang.brportugese=Brazilian Portugese
label.lang.catalan=Catalan
label.lang.chinese=Chinese (Simplified)
label.lang.dutch=Dutch (Netherlands)
label.lang.english=English
label.lang.french=French
label.lang.german=German
@ -713,6 +714,7 @@ label.lang.italian=Italian
label.lang.japanese=Japanese
label.lang.korean=Korean
label.lang.norwegian=Norwegian
label.lang.polish=Polish
label.lang.russian=Russian
label.lang.spanish=Spanish
label.last.disconnected=Last Disconnected

View File

@ -22,6 +22,7 @@ error.session.expired=Su sesi\u00c3\u00b3n ha caducado.
error.unresolved.internet.name=El nombre de Internet no se puede resolver.
extractable=extra\u00c3\u00adble
force.delete.domain.warning=Advertencia\: Si elige esta opci\u00c3\u00b3n, la supresi\u00c3\u00b3n de todos los dominios secundarios y todas las cuentas asociadas y sus recursos.
<<<<<<< HEAD
force.delete=Fuerza Borrar
force.remove=Fuerza Retire
force.remove.host.warning=Advertencia\: Si elige esta opci\u00c3\u00b3n, CloudStack para detener la fuerza todas las m\u00c3\u00a1quinas virtuales en ejecuci\u00c3\u00b3n antes de retirar este host del cl\u00c3\u00baster.
@ -31,25 +32,38 @@ ICMP.code=ICMP C\u00c3\u00b3digo
ICMP.type=Tipo ICMP
image.directory=Directorio de la imagen
inline=en l\u00c3\u00adnea
=======
force.delete=Forzar el borrado
force.remove=Forzar el retiro
force.remove.host.warning=Advertencia\: Si elige esta opci\u00f3n, CloudStack para detener la fuerza todas las m\u00e1quinas virtuales en ejecuci\u00f3n antes de retirar este host del cl\u00faster.
force.stop=Forzar la detenci\u00f3n
force.stop.instance.warning=Advertencia\: Forzar la dertenci\u00f3n de esta instancia deber\u00ed\u00ada ser su \u00faltima opci\u00f3n. Puede conducir a la p\u00e9rdida de datos, as\u00ed\u00ad como un comportamiento incoherente del Estado de la m\u00e1quina virtual.
ICMP.code=C\u00f3digo ICMP
ICMP.type=Tipo ICMP
image.directory=Directorio de im\u00e1genes
inline=alineado
label.about=Acerca de
label.about.app=Acerca de CloudStack
>>>>>>> 4e449ff... Add Dutch (Netherlands, Polish languages in Web UI Change Japanese code (ja -> ja_JP) Update transifex sync config
label.account=Cuenta
label.account.id=ID de la cuenta
label.account.name=Nombre de la cuenta
label.account.name=Nombre de cuenta
label.accounts=Cuentas
label.account.specific=espec\u00c3\u00adficas de la cuenta
label.acquire.new.ip=adquirir nuevas IP
label.acquire.new.ip=Adquirir nueva IP
label.action.attach.disk=Conecte el disco
label.action.attach.disk.processing=disco Fijaci\u00c3\u00b3n ....
label.action.attach.iso=Adjuntar ISO
label.action.attach.iso.processing=Colocaci\u00c3\u00b3n de la norma ISO ....
label.action.cancel.maintenance.mode=Cancelar modo de mantenimiento
label.action.cancel.maintenance.mode.processing=Cancelaci\u00c3\u00b3n del modo de mantenimiento ....
label.action.change.password=Cambiar contrase\u00c3\u00b1a
label.action.change.service=Cambio de Servicio
label.action.change.service.processing=Cambio de servicio ....
label.action.copy.ISO=Copia de la ISO
label.action.copy.ISO.processing=hacer frente ISO ....
label.action.copy.template=Copia de plantilla
label.action.copy.template.processing=hacer frente plantilla ....
label.action.attach.disk.processing=Conectando el disco....
label.action.attach.iso=Conectar ISO
label.action.attach.iso.processing=Conectando el ISO....
label.action.cancel.maintenance.mode=Cancelar el modo de mantenimiento
label.action.cancel.maintenance.mode.processing=Cancelando el modo de mantenimiento....
label.action.change.password=Cambiar la contrase\u00f1a
label.action.change.service=Cambiar el Servicio
label.action.change.service.processing=Cambiando el servicio....
label.action.copy.ISO=Copiar ISO
label.action.copy.ISO.processing=Copiando ISO ....
label.action.copy.template=Copiear la plantilla
label.action.copy.template.processing=Copiando la plantilla ....
label.action.create.template=Crear plantilla
label.action.create.template.from.vm=Crear plantilla de VM
label.action.create.template.from.volume=Crear plantilla de volumen
@ -250,6 +264,9 @@ label.alert=Alerta
label.algorithm=Algoritmo
label.allocated=Asignados
label.api.key=clave de API
label.app.name=CloudStack
label.archive.alerts=Archivar alertas
label.archive.events=Archivar sucesos
label.assign=Asignar
label.assign.to.load.balancer=instancia de Asignaci\u00c3\u00b3n de equilibrador de carga
label.associated.network.id=ID de red asociados
@ -263,9 +280,13 @@ label.basic.mode=Modo b\u00c3\u00a1sico
label.bootable=arranque
label.broadcast.domain.type=Tipo de dominio de difusi\u00c3\u00b3n
label.by.account=Por Cuenta
label.by.alert.type=Por tipo de alerta
label.by.availability=Por Disponibilidad
label.by.date.end=Por fecha (finalizaci\u00f3n)
label.by.date.start=Por fecha (inicio)
label.by.domain=Por dominio
label.by.end.date=Por Fecha de finalizaci\u00c3\u00b3n
label.by.event.type=Por tipo de suceso
label.by.level=por Nivel
label.by.pod=Por Pod
label.by.role=por funci\u00c3\u00b3n
@ -300,6 +321,7 @@ label.cpu=CPU
label.cpu.utilized=CPU Utilizado
label.created=creaci\u00c3\u00b3n
label.cross.zones=Cruz Zonas
label.custom.disk.iops=IOPS personalizadas
label.custom.disk.size=Personal Disk Size
label.daily=diario
label.data.disk.offering=Datos Disco Offering
@ -307,7 +329,9 @@ label.date=Fecha
label.day.of.month=D\u00c3\u00ada del mes
label.day.of.week=d\u00c3\u00ada de la semana
label.default.use=Usar por defecto
label.delete.alerts=Eliminar alertas
label.delete=Eliminar
label.delete.events=Eliminar sucesos
label.deleting.failed=No se pudo eliminar
label.deleting.processing=Eliminar ....
label.description=Descripci\u00c3\u00b3n
@ -319,6 +343,9 @@ label.DHCP.server.type=Tipo de servidor DHCP
label.disabled=personas de movilidad reducida
label.disabling.vpn.access=Desactivaci\u00c3\u00b3n de VPN de acceso
label.disk.allocated=disco asignado
label.disk.iops.max=IOPS m\u00e1ximas
label.disk.iops.min=IOPS m\u00ednimas
label.disk.iops.total=Total de IOPS
label.disk.offering=disco Ofrenda
label.disk.size.gb=tama\u00c3\u00b1o de disco (en GB)
label.disk.size=tama\u00c3\u00b1o de disco
@ -335,6 +362,7 @@ label.domain.suffix=DNS sufijo de dominio (es decir, xyz.com)
label.double.quotes.are.not.allowed=comillas dobles no se permite
label.download.progress=Progreso de la descarga
label.edit=Editar
label.egress.default.policy=Directiva de salida predeterminada
label.email=correo electr\u00c3\u00b3nico
label.enabling.vpn.access=Habilitaci\u00c3\u00b3n de Acceso VPN
label.enabling.vpn=Habilitaci\u00c3\u00b3n VPN
@ -374,6 +402,8 @@ label.host.name=nombre de host
label.hosts=Ej\u00c3\u00a9rcitos
label.hourly=por hora
label.hypervisor=Hypervisor
label.hypervisors=Hipervisores
label.hypervisor.snapshot.reserve=Reserva de instant\u00e1neas de hipervisores
label.hypervisor.type=Tipo Hypervisor
label.id=ID
label.info=Informaci\u00c3\u00b3n
@ -576,7 +606,10 @@ label.resource=Recursos
label.resources=Recursos
label.role=Papel
label.root.disk.offering=Root Disco Offering
label.routing=Enrutamiento
label.running.vms=Ejecuci\u00c3\u00b3n de m\u00c3\u00a1quinas virtuales
label.s3.nfs.path=Ruta NFS S3
label.s3.nfs.server=Servidor NFS S3
label.s3.secret_key=clave secreta
label.saturday=s\u00c3\u00a1bado
label.save=Guardar
@ -594,6 +627,7 @@ label.select.a.zone=Seleccione una zona.
label.sent=Enviados
label.server=Servidor
label.service.offering=Oferta de Servicio
label.service.state=Estado del servicio
label.session.expired=Session Caducado
label.shared=compartidas
label.SharedMountPoint=SharedMountPoint
@ -605,6 +639,7 @@ label.snapshot.name=Nombre de instant\u00c3\u00a1neas
label.snapshot.schedule=Lista de instant\u00c3\u00a1neas
label.snapshot.s=Instant\u00c3\u00a1nea (s)
label.snapshots=instant\u00c3\u00a1neas
label.sockets=Sockets
label.source.nat=NAT Fuente
label.specify.vlan=Especifique VLAN
label.specify.vxlan=Especifique VXLAN
@ -636,6 +671,7 @@ label.submit=Enviar
label.submitted.by=[Enviado por\: <span id\="submitted_by"> </span>]
label.succeeded=Sucesor
label.sunday=domingo
label.switch.type=Cambiar el tipo
label.system.capacity=Capacidad de todo el sistema
label.system.vm=Sistema de VM
label.system.vms=Sistema de m\u00c3\u00a1quinas virtuales
@ -680,6 +716,7 @@ label.vcenter.host=vCenter anfitri\u00c3\u00b3n
label.vcenter.password=vCenter Contrase\u00c3\u00b1a
label.vcenter.username=vCenter Nombre de usuario
label.version=Versi\u00c3\u00b3n
label.view.secondary.ips=Ver las IP secundarias
label.virtual.appliances=Virtual Appliances
label.virtual.appliance=Virtual Appliance
label.virtual.machines=Maquinas virtuales
@ -854,6 +891,7 @@ message.step.4.continue=Por favor seleccione al menos una red social para contin
message.step.4.desc=Por favor, seleccione la red primaria que la instancia virtual estar\u00c3\u00a1 conectado.
message.update.os.preference=Por favor seleccione un sistema operativo de preferencia para este equipo. Todas las instancias virtuales con preferencias similares ser\u00c3\u00a1n los primeros asignados a este equipo antes de elegir otro.
message.update.ssl=Por favor, env\u00c3\u00ade una nueva X.509 compatible con certificado SSL que se actualizar\u00c3\u00a1 a cada instancia virtual de la consola del servidor proxy\:
message.validate.invalid.characters=Se han hallado caracteres no v\u00e1lidos. Por favor, corr\u00edjalos.
message.virtual.network.desc=Una red dedicada virtualizados para su cuenta. El dominio de difusi\u00c3\u00b3n est\u00c3\u00a1 contenida dentro de una VLAN y todos los acceso a la red p\u00c3\u00bablica se encamina a cabo por un router virtual.
message.vm.create.template.confirm=Crear plantilla de la m\u00c3\u00a1quina virtual se reiniciar\u00c3\u00a1 autom\u00c3\u00a1ticamente.
message.volume.create.template.confirm=Por favor, confirme que desea crear una plantilla para este volumen de disco. Creaci\u00c3\u00b3n de la plantilla puede oscilar entre varios minutos m\u00c3\u00a1s, dependiendo del tama\u00c3\u00b1o del volumen.

View File

@ -641,6 +641,7 @@ label.lang.arabic=Arabe
label.lang.brportugese=Portuguais Br\u00e9sil
label.lang.catalan=Catalan
label.lang.chinese=Chinois (simplifi\u00e9)
label.lang.dutch=N\u00e9erlandais
label.lang.english=Anglais
label.lang.french=Fran\u00e7ais
label.lang.german=Allemand
@ -648,6 +649,7 @@ label.lang.italian=Italien
label.lang.japanese=Japonais
label.lang.korean=Cor\u00e9en
label.lang.norwegian=Norv\u00e9gien
label.lang.polish=Polonais
label.lang.russian=Russe
label.lang.spanish=Espagnol
label.last.disconnected=Derni\u00e8re D\u00e9connexion

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,469 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
error.invalid.username.password=B\u0142\u0119dna nazwa u\u017cytkownika lub has\u0142o
label.account.id=ID konta
label.account=Konto
label.account.name=Nazwa konta
label.accounts=Konta
label.action.attach.disk=Dodaj dysk
label.action.attach.disk.processing=Dodawanie dysku
label.action.attach.iso=Dodaj obraz ISO
label.action.attach.iso.processing=Dodawanie obrazu ISO
label.action.change.password=Zmie\u0144 has\u0142o
label.action.copy.ISO=Kopiuj ISO
label.action.copy.ISO.processing=Kopiuj ISO....
label.action.copy.template=Kopij szablon
label.action.copy.template.processing=Kopije szablon....
label.action.create.template.from.vm=Utw\u00f3rz szablon z VM
label.action.create.template.from.volume=Utw\u00f3rz Szablon z wolumenu
label.action.create.template.processing=Tworz\u0119 szablon
label.action.create.template=Utw\u00f3rz szablon
label.action.create.vm.processing=Tworz\u0119 VM....
label.action.create.vm=Utw\u00f3rz VM
label.action.create.volume.processing=Tworz\u0119 wolumen....
label.action.create.volume=Utw\u00f3rz wolumen
label.action.delete.account.processing=Usuwanie dost\u0119pu....
label.action.delete.account=Usu\u0144 dost\u0119p
label.action.delete.cluster.processing=Usuwam klaster....
label.action.delete.cluster=Usu\u0144 klaster
label.action.delete.domain.processing=Usuwam domen\u0119....
label.action.delete.domain=Usu\u0144 domen\u0119
label.action.delete.firewall.processing=Usuwam Firewall
label.action.delete.firewall=Usu\u0144 regu\u0142\u0119 Firewall
label.action.delete.ISO.processing=Usuwam ISO....
label.action.delete.ISO=Usu\u0144 ISO
label.action.delete.network.processing=Usuwam sie\u0107....
label.action.delete.network=Usu\u0144 sie\u0107
label.action.delete.nexusVswitch=Usu\u0144 Nexus 1000v
label.action.delete.physical.network=Usu\u0144 fizyczn\u0105 sie\u0107
label.action.delete.user.processing=Usuwam u\u017cytkownika....
label.action.delete.user=Usu\u0144 u\u017cytkownika
label.action.delete.volume.processing=Usuwam wolumen....
label.action.delete.volume=Usu\u0144 wolumen
label.action.delete.zone.processing=Usuwam stref\u0119....
label.action.delete.zone=Usu\u0144 stref\u0119
label.action.destroy.instance.processing=Usuwam instancj\u0119
label.action.destroy.instance=Usu\u0144 instancj\u0119
label.action.detach.disk=Od\u0142\u0105cz dysk
label.action.detach.disk.processing=Od\u0142\u0105czanie dysku....
label.action.detach.iso=Od\u0142\u0105cz obraz ISO
label.action.detach.iso.processing=Od\u0142\u0105czanie obrazu ISO
label.action.disable.account.processing=Wy\u0142\u0105czam dost\u0119p....
label.action.disable.account=Wy\u0142\u0105cz dost\u0119p
label.action.disable.cluster.processing=Wy\u0142\u0105czam klaster....
label.action.disable.cluster=Wy\u0142\u0105cz klaster
label.action.disable.nexusVswitch=Wy\u0142\u0105cz Nexus 1000v
label.action.disable.physical.network=Wy\u0142\u0105cz fizyczn\u0105 sie\u0107
label.action.disable.user.processing=Wy\u0142\u0105czam u\u017cytkownika
label.action.disable.user=Wy\u0142\u0105cz u\u017cytkownika
label.action.disable.zone.processing=Wy\u0142\u0105czam stref\u0119....
label.action.disable.zone=Wy\u0142\u0105cz stref\u0119
label.action.download.ISO=Pobierz ISO
label.action.download.template=Pobierz szablon
label.action.download.volume=Pobierz wolumen
label.action.download.volume.processing=Pobieram wolumen....
label.action.edit.account=Edytuj dost\u0119p
label.action.edit.domain=Edytuj domen\u0119
label.action.edit.global.setting=Edytuj Globalne ustawienia
label.action.edit.host=Edytuj host
label.action.edit.instance=Edytuj instancj\u0119
label.action.edit.ISO=Edytuj ISO
label.action.edit.network=Edytuj sie\u0107
label.action.edit.network.processing=Zmieniam sie\u0107....
label.action.edit.template=Edytuj szablon
label.action.edit.user=Edytuj u\u017cytkownika
label.action.edit.zone=Edytuj stref\u0119
label.action.enable.account.processing=W\u0142\u0105czam dost\u0119p....
label.action.enable.account=W\u0142\u0105cz dost\u0119p
label.action.enable.cluster.processing=W\u0142\u0105czam klaster....
label.action.enable.cluster=W\u0142\u0105cz klaster
label.action.enable.nexusVswitch=W\u0142\u0105cz Nexus 1000v
label.action.enable.physical.network=W\u0142\u0105cz fizyczn\u0105 sie\u0107
label.action.enable.user.processing=W\u0142\u0105czam u\u017cytkownika....
label.action.enable.user=W\u0142\u0105cz u\u017cytkownika
label.action.enable.zone.processing=W\u0142\u0105czam stref\u0119....
label.action.enable.zone=W\u0142\u0105cz stref\u0119
label.action.generate.keys=Generuj klucze
label.action.generate.keys.processing=Generuj\u0119 klucze....
label.action.list.nexusVswitch=Kista Nexus 1000v
label.action.lock.account.processing=Blokuj\u0119 dost\u0119p....
label.action.lock.account=Zablokuj dost\u0119p
label.action.manage.cluster.processing=Zarz\u0105dzam klastrem....
label.action.manage.cluster=Zarz\u0105dzaj klastrem
label.action.migrate.instance=Migruj instancj\u0119
label.action.migrate.instance.processing=Migruj\u0119 instancj\u0119....
label.action.migrate.router=Migruj router
label.action.migrate.router.processing=Migruje router....
label.action.migrate.systemvm=Migruj system VM
label.action.migrate.systemvm.processing=Migruj\u0119 system VM....
label.action.reboot.instance.processing=Restartuje instancj\u0119
label.action.reboot.instance=Restartuj instancj\u0119
label.action.reboot.router.processing=Restartuje router.....
label.action.reboot.router=Restartuj router
label.action.reboot.systemvm.processing=Restartuje system VM....
label.action.reboot.systemvm=Restartuj system VM
label.action.register.iso=Rejestruj ISO
label.action.register.template=Rejestruj szablon
label.action.remove.host.processing=Usuwam host....
label.action.remove.host=Usu\u0144 host
label.action.reset.password.processing=Resetuj\u0119 has\u0142o....
label.action.reset.password=Resetuj has\u0142o
label.action.resize.volume.processing=Zmieniam wielko\u015b\u0107 wolumenu....
label.action.resize.volume=Zmie\u0144 wielko\u015b\u0107 wolumenu
label.action.restore.instance=Przywr\u00f3\u0107 instancj\u0119
label.actions=Akcje
label.action.start.instance.processing=Uruchamiam instancj\u0119....
label.action.start.instance=Uruchom instancj\u0119
label.action.start.router.processing=Uruchamiam router....
label.action.start.router=Uruchom router
label.action.start.systemvm.processing=Uruchamiam system VM...
label.action.start.systemvm=Uruchom system VM
label.action.stop.instance.processing=Zatrzymuj\u0119 instancj\u0119....
label.action.stop.instance=Zatrzymaj instancj\u0119
label.action.stop.router.processing=Zatrzymuj\u0119 router...
label.action.stop.router=Zatrzymaj router
label.action.stop.systemvm.processing=Zatrzymuj\u0119 system VM....
label.action.stop.systemvm=Zatrzymaj system VM
label.action.take.snapshot.processing=Tworz\u0119 snapshot....
label.action.take.snapshot=Zr\u00f3b snapshot
label.activate.project=Aktywuj projekt
label.add.account=Dodaj konto
label.add.accounts=Dodaj konta
label.add.accounts.to=Dodaj konto do
label.add.account.to.project=Dodaj konto do projektu
label.add.ACL=Dodaj ACL
label.add.by.cidr=Dodaj przez CIDR
label.add.by=Dodaj przez
label.add.by.group=Dodaj przez grup\u0119
label.add.cluster=Dodaj klaster
label.add=Dodaj
label.add.domain=Dodaj domen\u0119
label.add.firewall=Dodaj regu\u0142\u0119 firewall
label.add.host=Dodaj host
label.adding=Dodawanie
label.adding.failed=Dodanie nieudane
label.adding.processing=Dodawanie
label.adding.succeeded=Dodanie udane
label.add.more=Dodaj wi\u0119cej
label.add.network.device=Dodaj urz\u0105dzenie sieciowe
label.add.network=Dodaj sie\u0107
label.add.new.F5=Dodaj nowy F5
label.add.new.SRX=Dodaj nowy SRX
label.add.region=Dodaj region
label.add.rule=Dodaj regu\u0142\u0119
label.add.to.group=Dodaj do grupy
label.add.user=Dodaj u\u017cytkownika
label.add.vlan=Dodaj VLAN
label.add.vm=Dodaj VM
label.add.vms=Dodaj VM-ny
label.add.volume=Dodaj wolumen
label.add.vpc=Dodaj VPC
label.add.zone=Dodaj stref\u0119
label.admin=Admin
label.api.key=Klucz API
label.apply=Zastosuj
label.author.name=Imi\u0119 autora
label.available=Dost\u0119pne
label.available.public.ips=Dost\u0119pne publiczne adresy IP
label.back=Wstecz
label.bandwidth=Przepustowo\u015b\u0107
label.cancel=Zako\u0144cz
label.certificate=Certyfikat
label.cidr=CIDR
label.CIDR.list=Lista CIDR
label.clean.up=Wyczy\u015b\u0107
label.clear.list=Wyczy\u015b\u0107 list\u0119
label.close=Zamknij
label.clvm=CLVM
label.code=Kod
label.community=Spo\u0142eczno\u015b\u0107
label.configuration=Konfiguracja
label.configure=Konfiguruj
label.configure.vpc=Konfiguruj VPC
label.confirmation=Potwierdzenie
label.confirm.password=Potwierd\u017a has\u0142o
label.congratulations=Gratulacje\!
label.continue=Kontynuuj
label.corrections.saved=Poprawka zapisana
label.cpu=CPU
label.cpu.limits=Limit CPU
label.cpu.mhz=CPU (w MHz)
label.created.by.system=Utworzono przez system
label.created=Utworzono
label.create.project=Stw\u00f3rz projekt
label.daily=Dziennie
label.date=Data
label.day.of.month=Dzie\u0144 miesi\u0105ca
label.day.of.week=Dzie\u0144 tygodnia
label.dedicated=Dedykowany
label.default=Domy\u015blnie
label.default.view=Widok domy\u015blny
label.delete.F5=Usu\u0144 F5
label.delete.project=Usu\u0144 projekt
label.delete.SRX=Usu\u0144 SRX
label.delete=Usu\u0144
label.deleting.failed=Usuwanie nieudane
label.deleting.processing=Usuwanie....
label.destroy.router=Zniszcz router
label.destroy=Zniszcz
label.detaching.disk=Od\u0142\u0105czanie dysku
label.details=Szczeg\u00f3\u0142y
label.disabled=Wy\u0142\u0105czony
label.disable.vpn=Wy\u0142\u0105cz VPN
label.disk.size.gb=Wielko\u015b\u0107 dysku (w GB)
label.disk.size=Wielko\u015b\u0107 dysku
label.display.name=Wy\u015bwietlana nazwa
label.domain.admin=Administrator domeny
label.domain=Domena
label.domain.id=ID domeny
label.domain.name=Nazwa domeny
label.done=Sko\u0144czono
label.download.progress=Post\u0119p w pobieraniu
label.drag.new.position=Przenie\u015b w nowe miejsce
label.edit=Edytuj
label.edit.network.details=Edytuj szczeg\u00f3\u0142y sieci
label.edit.project.details=Zmie\u0144 szczeg\u00f3\u0142y projektu
label.edit.vpc=Edytuj VPC
label.elastic=Elastyczny
label.elastic.IP=Zmienne IP
label.email=Poczta
label.enable.vpn=W\u0142\u0105cz VPN
label.error=B\u0142\u0105d
label.f5=F5
label.featured=Polecane
label.filterBy=Filtrowanie wg
label.firewall=Zapora
label.first.name=Pierwsza nazwa
label.format=Format
label.friday=Pi\u0105tek
label.full.path=Pe\u0142na \u015bcie\u017cka
label.go.step.2=Id\u017a do punktu 2
label.go.step.3=Id\u017a do punktu 3
label.go.step.4=Id\u017a do punktu 4
label.go.step.5=Id\u017a do punktu 5
label.group=Grupa
label.group.optional=Grupa (opcjonalnie)
label.guest=Go\u015b\u0107
label.guest.type=Rodzaj go\u015bci
label.help=Pomoc
label.hints=Podpowiedzi
label.id=ID
label.info=Informacje
label.instances=Instancje
label.invitations=Zaproszenia
label.invited.accounts=Zaproszone konta
label.invite.to=Zapro\u015b do
label.invite=Zapro\u015b
label.ip=IP
label.iso=ISO
label.keep=Zostaw
label.key=Klucz
label.lang.english=Angielski
label.lang.french=Francuski
label.lang.japanese=Japo\u0144ski
label.lang.korean=Korea\u0144ski
label.lang.russian=Rosyjski
label.lang.spanish=Hiszpia\u0144ski
label.last.name=Nazwisko
label.least.connections=Ostatnie po\u0142\u0105czenie
label.level=Poziom
label.loading=Wczytywanie
label.local=Lokalne
label.local.storage.enabled=Pami\u0119\u0107 lokalna w\u0142\u0105czona
label.local.storage=Pami\u0119\u0107 lokalna
label.login=Zaloguj
label.logout=Wyloguj
label.lun=LUN
label.LUN.number=LUN \#
label.max.guest.limit=Maksymalna liczba go\u015bci
label.maximum=Maksimum
label.max.public.ips=Maksymalna liczba publicznych adres\u00f3w IP
label.memory.limits=Limit pami\u0119ci (MiB)
label.memory.mb=Pami\u0119\u0107 (w MB)
label.memory=Pami\u0119\u0107
label.menu.accounts=Konta
label.menu.alerts=Alarmy
label.menu.all.accounts=Wszystkie konta
label.menu.all.instances=Wszystkie instancje
label.menu.configuration=Konfiguracja
label.menu.domains=Domeny
label.menu.infrastructure=Infrastruktura
label.menu.instances=Instancje
label.menu.ipaddresses=Adresy IP
label.menu.isos=ISO
label.menu.my.accounts=Moje konta
label.menu.my.instances=Moje instancje
label.menu.my.isos=Moje ISO
label.menu.network=Sie\u0107
label.menu.regions=Regiony
label.menu.system=System
label.minimum=Minimum
label.monday=Poniedzia\u0142ek
label.monthly=Miesi\u0119cznie
label.move.down.row=Jeden rz\u0105d na d\u00f3\u0142
label.move.to.top=Przenie\u015b na sam\u0105 g\u00f3r\u0119
label.move.up.row=Jeden rz\u0105d do g\u00f3ry
label.my.account=Moje konto
label.my.network=Moja sie\u0107
label.name=Nazwa
label.name.optional=Nazwa (opcjonalnie)
label.network.id=ID sieci
label.network.name=Nazwa sieci
label.network=Sie\u0107
label.networks=Sieci
label.new=Nowy
label.new.project=Nowy projekt
label.next=Nast\u0119pny
label.nfs=NFS
label.nfs.server=Serwer NFS
label.no.data=Brak danych
label.none=Brak
label.no=Nie
label.no.thanks=Nie dzi\u0119kuj\u0119
label.notifications=Przypomnienia
label.number.of.hosts=Liczba host\u00f3w
label.ok=OK
label.order=Zadanie
label.password=Has\u0142o
label.path=\u015acie\u017cka
label.please.wait=Prosz\u0119 czeka\u0107
label.plugin.details=Szczeg\u00f3\u0142y wtyczki
label.plugins=Wtyczki
label.previous=Wstecz
label.private.network=Sie\u0107 prywatna
label.project.id=Nazwa ID projektu
label.project.invite=Zapro\u015b do projektu
label.project.name=Nazwa projektu
label.project=Projekt
label.projects=Projekty
label.protocol=Protok\u00f3\u0142
label.providers=Dostawcy
label.public.ip=Publiczny adres IP
label.public.ips=Publiczne adresy IP
label.public.network=Sie\u0107 publiczna
label.public=Pobliczny
label.public.port=Publiczny port
label.reboot=Uruchom ponownie
label.refresh=Od\u015bwie\u017c
label.region=Region
label.remind.later=Przypomnij p\u00f3\u017aniej
label.remove.rule=Usu\u0144 regu\u0142\u0119
label.remove.vpc=Usu\u0144 VPC
label.removing.user=Usu\u0144 u\u017cytkownika
label.removing=Usuwanie
label.required=Wymagane
label.resource.limits=Limit zasob\u00f3w
label.resources=Zasoby
label.resource=Zas\u00f3b
label.restart.required=Wymagany restart
label.rules=Zasady
label.saturday=Sobota
label.save.and.continue=Zapisz i kontynuuj
label.save=Zapisz
label.saving.processing=Zapisywanie....
label.search=Szukaj
label.select.instance=Wybierz instancj\u0119
label.select.project=Wybierz projekt
label.select=Wybierz
label.sent=Wys\u0142ano
label.server=Serwer
label.size=Wielko\u015bc
label.specify.IP.ranges=Wyszczeg\u00f3lnij zasi\u0119g adres\u00f3w IP
label.srx=SRX
label.statistics=Statystyki
label.status=Status
label.step.1=Krok 1
label.step.2=Krok 2
label.step.3=Krok 3
label.step.4=Krok 4
label.step.5=Krok 5
label.sticky.domain=Domena
label.sticky.expire=Wygasa
label.sticky.length=D\u0142ugo\u015b\u0107
label.sticky.mode=Tryb
label.sticky.prefix=Prefiks
label.stop=Stop
label.sunday=Niedziela
label.suspend.project=Zawie\u015b projekt
label.tagged=Otagowany
label.tags=Tagi
label.task.completed=Zadania uko\u0144czone
label.time=Czas
label.time.zone=Strefa czasowa
label.timezone=Strefa czasowa
label.type.id=Wpisz ID
label.type=Wpisz
label.unavailable=Niedost\u0119pny
label.unlimited=Nieograniczony
label.untagged=Nieotagowany
label.updating=Aktualizowanie
label.url=URL
label.used=U\u017cyte
label.username=Nazwa u\u017cytkownika
label.users=U\u017cytkownicy
label.user=U\u017cytkowni
label.version=Wersja
label.view.all=Zobacz wszystko
label.view=Zobacz
label.vm.add=Dodaj instancj\u0119
label.vm.destroy=Zniszcz
label.vmfs=VMFS
label.vm.name=Nazwa VM
label.vm.reboot=Uruchom ponownie
label.vmsnapshot.type=Wpisz
label.vm.start=Rozpocznij
label.vm.stop=Stop
label.vms=VMs
label.vpc=VPC
label.vpn=VPN
label.waiting=Czekanie
label.warn=Ostrze\u017cenie
label.wednesday=\u015aroda
label.weekly=Tygodniowo
label.welcome=Witaj
label.what.is.cloudstack=Czym jest CloudStack&\#8482?
label.yes=Tak
message.action.delete.nexusVswitch=Potwierd\u017a, \u017ce chcesz usun\u0105\u0107\: nexus 1000v
message.action.download.iso=Potwierd\u017a, \u017ce chcesz pobra\u0107 ten obraz ISO.
message.activate.project=Czy na pewno chcesz aktywowa\u0107 ten projekt?
message.confirm.delete.F5=Czy na pewno chcesz usun\u0105\u0107 F5?
message.confirm.delete.SRX=Czy na pewno chcesz usun\u0105\u0107 SRX?
message.delete.project=Czy na pewno chcesz usun\u0105\u0107 ten projekt?
message.disable.vpn=Czy na pewno chcesz wy\u0142\u0105czy\u0107 VPN?
message.no.projects=Nie posiadasz \u017cadnych projekt\u00f3w.<br/> Utw\u00f3rz nowy projekt w zak\u0142adce projekty
message.please.proceed=Przejd\u017a do nast\u0119pnego punktu
message.step.2.desc=
message.step.3.desc=
message.suspend.project=Czy na pewno chcesz zawiesi\u0107 ten projekt
mode=Tryb
state.Accepted=Akceptowano
state.Active=Aktywny
state.Completed=Uko\u0144czono
state.Creating=Tworzenie
state.Declined=Odrzucono
state.Destroyed=Zniszczono
state.Disabled=Wy\u0142\u0105czony
state.enabled=W\u0142\u0105czone
state.Enabled=W\u0142\u0105czone
state.Error=B\u0142\u0105d
state.ready=Gotowe
state.Ready=Gotowe
state.Starting=Rozpoczynanie
state.Stopped=Zatrzymano
state.Suspended=Zawieszono
ui.listView.filters.all=Wszystko

View File

@ -373,6 +373,7 @@ label.compute.and.storage=Processamento e Armazenamento
label.compute.offering=Oferta de Computa\u00e7\u00e3o
label.configuration=Configura\u00e7\u00e3o
label.configure=Configurar
label.configure.ldap=Configurar LDAP
label.configure.network.ACLs=Configure ACLs de rede
label.configure.vpc=Configurar VPC
label.confirmation=Confirma\u00e7\u00e3o
@ -390,6 +391,7 @@ label.cpu.mhz=CPU (em MHz)
label.cpu.utilized=CPU Utilizada
label.created.by.system=Criado pelo sistema
label.created=Criado
label.create.nfs.secondary.staging.store=Criar storage staging secund\u00e1rio NFS
label.create.project=Criar um projeto
label.create.template=Criar template
label.create.VPN.connection=Criar uma conex\u00e3o VPN
@ -418,6 +420,7 @@ label.delete.VPN.gateway=deletar um gateway de VPN
label.delete.vpn.user=Deletar usu\u00e1rio VPN
label.deleting.failed=Falha ao remover
label.deleting.processing=Removendo....
label.deployment.planner=Deployment planejado
label.description=Descri\u00e7\u00e3o
label.destination.physical.network.id=ID de destino da rede f\u00edsica
label.destination.zone=Zona de Destino
@ -617,6 +620,9 @@ label.launch=Executar
label.launch.vm=Executar VM
label.launch.zone=Executar zona.
label.LB.isolation=Isolamento de LB
label.ldap.configuration=Configura\u00e7\u00e3o do LDAP
label.ldap.group.name=Grupo LDAP
label.ldap.port=Porta do LDAP
label.least.connections=Least connections
label.level=N\u00edvel
label.load.balancer=Load Balancer
@ -784,6 +790,7 @@ label.PING.CIFS.password=PING CIFS password
label.PING.CIFS.username=PING CIFS username
label.PING.dir=PING Directory
label.PING.storage.IP=Disparar PING para IP do Storage
label.planner.mode=Modo planejado
label.please.specify.netscaler.info=Por favor especifique as informa\u00e7\u00f5es do Netscaler
label.please.wait=Por Favor Aguarde
label.pod.name=Nome do Pod
@ -791,6 +798,7 @@ label.pod=POD
label.pods=Pods
label.port.forwarding=Encaminhamento de Porta
label.port.forwarding.policies=Pol\u00edticas de redirecionamento de portas
label.port=Porta
label.port.range=Range de Porta
label.PreSetup=PreSetup
label.previous=Anterior
@ -829,6 +837,15 @@ label.public.zone=Zona P\u00fablica
label.purpose=Prop\u00f3sito
label.Pxe.server.type=Tipo de Servidor PXE
label.quickview=Visualiza\u00e7\u00e3o r\u00e1pida
<<<<<<< HEAD
=======
label.quiesce.vm=Quiesce VM
label.rbd.id=Usu\u00e1rio Ceph
label.rbd.monitor=Monitor Ceph
label.rbd.pool=Pool Ceph
label.rbd=RDB
label.rbd.secret=Cephx secret
>>>>>>> 4e449ff... Add Dutch (Netherlands, Polish languages in Web UI Change Japanese code (ja -> ja_JP) Update transifex sync config
label.reboot=Reiniciar
label.recent.errors=Erros Recentes
label.redundant.router.capability=Recurso de roteador redundante
@ -841,6 +858,7 @@ label.remove.egress.rule=Remover regra egress
label.remove.from.load.balancer=Removendo Cloud Server do Load Balancer
label.remove.ingress.rule=Remover regra ingress
label.remove.ip.range=Remover range de IP
label.remove.ldap=Remover LDAP
label.remove.pf=Remover regra de redirecionamento de porta
label.remove.project.account=Remover conta de projeto
label.remove.rule=Remover regra
@ -924,6 +942,9 @@ label.show.ingress.rule=Mostrar Regra de Entrada
label.site.to.site.VPN=Site-to-site VPN
label.size=Tamanho
label.skip.guide=Eu utilizei o CloudStack antes, pular este guia
label.smb.domain=Dom\u00ednio SMB
label.smb.password=Senha SMB
label.smb.username=Usu\u00e1rio SMB
label.snapshot.limits=Limites de Snapshot
label.snapshot.name=Nome do Snapshot
label.snapshot=Snapshot
@ -1080,6 +1101,12 @@ label.vm.state=Estado da VM
label.vm.stop=Parar
label.vms=VMs
label.vmware.traffic.label=Etiqueta de tr\u00e1fego VMware
<<<<<<< HEAD
=======
label.vnet.id=VLAN ID
label.vnet=VLAN
label.volatile=Vol\u00e1til
>>>>>>> 4e449ff... Add Dutch (Netherlands, Polish languages in Web UI Change Japanese code (ja -> ja_JP) Update transifex sync config
label.volgroup=Grupo de Volume
label.volume=Disco
label.volume.limits=Limites de Disco
@ -1230,6 +1257,7 @@ message.basic.mode.desc=Escolha este modelo de rede se voc\u00ea <b>*<u>n\u00e3o
message.change.offering.confirm=Confirme que voc\u00ea deseja mudar o plano deste Cloud Server.
message.change.password=Por favor, troque sua senha.
message.configure.all.traffic.types=Voc\u00ea tem m\u00faltiplas redes f\u00edsicas; favor configurar etiquetas para cada tipo de tr\u00e1fego clicando no bot\u00e3o Edit.
message.configure.ldap=Por favor, confirme que voc\u00ea deseja configurar o LDAP.
message.configuring.guest.traffic=Configurando tr\u00e1fego do guest
message.configuring.physical.networks=Configurando redes f\u00edsicas
message.configuring.public.traffic=Configurando tr\u00e1fego p\u00fablico
@ -1355,6 +1383,14 @@ message.please.select.a.different.public.and.management.network.before.removing=
message.please.select.networks=Por favor selecione as redes para sua m\u00e1quina virtual.
message.please.wait.while.zone.is.being.created=Por favor, espere enquanto sua zona est\u00e1 sendo criada; isto pode demorar um pouco...
message.project.invite.sent=Convite enviado para o usu\u00e1rio; Eles ser\u00e3o adicionados ao projeto ap\u00f3s aceitarem o convite
<<<<<<< HEAD
=======
message.public.traffic.in.advanced.zone=O tr\u00e1fego p\u00fablico \u00e9 gerado quando as VMs na nuvem acessam a internet. Os IPs acess\u00edveis ao p\u00fablico devem ser alocados para essa finalidade. Os usu\u00e1rios finais podem usar a interface do usu\u00e1rio CloudStack para adquirir esses IPs afim de implementar NAT entre a sua rede de guests e sua rede p\u00fablica. <br/><br/> Forne\u00e7a pelo menos um intervalo de endere\u00e7os IP para o tr\u00e1fego de internet.
message.public.traffic.in.basic.zone=O tr\u00e1fego p\u00fablico \u00e9 gerado quando as VMs na nuvem acessam a Internet ou prestam servi\u00e7os aos clientes atrav\u00e9s da Internet. Os IPs acess\u00edveis ao p\u00fablico devem ser alocados para essa finalidade. Quando uma inst\u00e2ncia \u00e9 criada, um IP a partir deste conjunto de IPs p\u00fablicos ser\u00e3o destinados \u00e0 inst\u00e2ncia, al\u00e9m do endere\u00e7o IP guest. Um NAT est\u00e1tico 1-1 ser\u00e1 criada automaticamente entre o IP p\u00fablico e IP guest. Os usu\u00e1rios finais tamb\u00e9m podem usar a interface de usu\u00e1rio CloudStack para adquirir IPs adicionais afim de se implementar NAT est\u00e1tico entre suas inst\u00e2ncias e o IP p\u00fablico.
message.redirecting.region=Redirecionando para regi\u00e3o...
message.remove.ldap=Voc\u00ea tem certeza que deseja deletar a configura\u00e7\u00e3o LDAP?
message.remove.region=Voc\u00ea tem certeza que deseja remover esta regi\u00e3o deste servidor de gerenciamento?
>>>>>>> 4e449ff... Add Dutch (Netherlands, Polish languages in Web UI Change Japanese code (ja -> ja_JP) Update transifex sync config
message.remove.vpc=Favor confirmar que voc\u00ea deseja remover a VPC
message.remove.vpn.access=Confirme se voc\u00ea deseja remover acesso VPN do seguinte Usu\u00e1rio.
message.reset.password.warning.notPasswordEnabled=O template desta inst\u00e2ncia foi criado sem senha habilitada

View File

@ -72,6 +72,7 @@ migrateVirtualMachine=1
migrateVirtualMachineWithVolume=1
recoverVirtualMachine=7
expungeVirtualMachine=7
getVirtualMachineUserData=15
#### snapshot commands
createSnapshot=15

View File

@ -0,0 +1,68 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.agent.api;
import java.util.List;
public class GetVmConfigAnswer extends Answer {
String vmName;
List<NicDetails> nics;
protected GetVmConfigAnswer() {
}
public GetVmConfigAnswer(String vmName, List<NicDetails> nics) {
this.vmName = vmName;
this.nics = nics;
}
public String getVmName() {
return vmName;
}
public List<NicDetails> getNics() {
return nics;
}
public class NicDetails {
String macAddress;
int vlanid;
public NicDetails() {
}
public NicDetails(String macAddress, int vlanid) {
this.macAddress = macAddress;
this.vlanid = vlanid;
}
public String getMacAddress() {
return macAddress;
}
public int getVlanid() {
return vlanid;
}
}
@Override
public boolean executeInSequence() {
return false;
}
}

View File

@ -14,25 +14,33 @@
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.agent.api;
package com.cloud.uuididentity.dao;
import com.cloud.server.ResourceTag.ResourceObjectType;
import com.cloud.utils.Pair;
import com.cloud.utils.db.GenericDao;
import java.util.List;
public interface IdentityDao extends GenericDao<IdentityVO, Long> {
Long getIdentityId(String tableName, String identityString);
import com.cloud.agent.api.to.NicTO;
String getIdentityUuid(String tableName, String identityString);
public class GetVmConfigCommand extends Command {
String vmName;
List<NicTO> nics;
protected GetVmConfigCommand() {
}
void initializeDefaultUuid(String tableName);
public GetVmConfigCommand(String vmName) {
this.vmName = vmName;
}
/**
* @param tableName
* @param identityId
* @param resourceType TODO
* @return
*/
Pair<Long, Long> getAccountDomainInfo(String tableName, Long identityId, ResourceObjectType resourceType);
public String getVmName() {
return vmName;
}
public void setNics(List<NicTO> nics){
this.nics = nics;
}
@Override
public boolean executeInSequence() {
return false;
}
}

View File

@ -14,10 +14,23 @@
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.api;
package com.cloud.agent.api;
public interface IdentityService {
Long getIdentityId(String tableName, String identityString);
public class ModifyVmNicConfigAnswer extends Answer {
String vmName;
protected ModifyVmNicConfigAnswer() {
}
String getIdentityUuid(String tableName, String identityString);
public ModifyVmNicConfigAnswer(String vmName) {
this.vmName = vmName;
}
public String getVmName() {
return vmName;
}
@Override
public boolean executeInSequence() {
return false;
}
}

View File

@ -14,31 +14,29 @@
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.uuididentity;
package com.cloud.agent.api;
import javax.ejb.Local;
import javax.inject.Inject;
import org.springframework.stereotype.Component;
import org.apache.cloudstack.api.IdentityService;
import com.cloud.utils.component.ManagerBase;
import com.cloud.uuididentity.dao.IdentityDao;
@Component
@Local(value = {IdentityService.class})
public class IdentityServiceImpl extends ManagerBase implements IdentityService {
@Inject
private IdentityDao _identityDao;
@Override
public Long getIdentityId(String tableName, String identityString) {
return _identityDao.getIdentityId(tableName, identityString);
public class ModifyVmNicConfigCommand extends Command {
String vmName;
int vlan;
String macAddress;
protected ModifyVmNicConfigCommand() {
}
public ModifyVmNicConfigCommand(String vmName, int vlan, String macAddress) {
this.vmName = vmName;
this.vlan = vlan;
this.macAddress = macAddress;
}
public String getVmName() {
return vmName;
}
@Override
public String getIdentityUuid(String tableName, String identityString) {
return _identityDao.getIdentityUuid(tableName, identityString);
public boolean executeInSequence() {
return false;
}
}

View File

@ -16,10 +16,10 @@
// under the License.
package com.cloud.agent.api.routing;
import java.util.HashMap;
import com.cloud.agent.api.Command;
import java.util.HashMap;
public abstract class NetworkElementCommand extends Command {
HashMap<String, String> accessDetails = new HashMap<String, String>(0);
@ -35,6 +35,8 @@ public abstract class NetworkElementCommand extends Command {
public static final String VPC_PRIVATE_GATEWAY = "vpc.gateway.private";
public static final String FIREWALL_EGRESS_DEFAULT = "firewall.egress.default";
private String routerAccessIp;
protected NetworkElementCommand() {
super();
}
@ -52,4 +54,11 @@ public abstract class NetworkElementCommand extends Command {
return false;
}
public String getRouterAccessIp() {
return routerAccessIp;
}
public void setRouterAccessIp(String routerAccessIp) {
this.routerAccessIp = routerAccessIp;
}
}

View File

@ -14,12 +14,14 @@
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.uuididentity.dao;
package com.cloud.agent.resource.virtualnetwork;
import javax.persistence.Entity;
import com.cloud.agent.api.routing.NetworkElementCommand;
import com.cloud.utils.ExecutionResult;
/**
*/
@Entity
public class IdentityVO {
public interface VirtualRouterDeployer {
ExecutionResult executeInVR(String routerIp, String script, String args);
ExecutionResult createFileInVR(String routerIp, String path, String filename, String content);
ExecutionResult prepareCommand(NetworkElementCommand cmd);
ExecutionResult cleanupCommand(NetworkElementCommand cmd);
}

View File

@ -23,6 +23,7 @@ import java.io.StringReader;
import java.lang.reflect.Type;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.zip.GZIPInputStream;
@ -49,6 +50,7 @@ import com.cloud.exception.UnsupportedVersionException;
import com.cloud.serializer.GsonHelper;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.StringUtils;
import com.cloud.utils.exception.CloudRuntimeException;
/**
@ -436,11 +438,35 @@ public class Request {
}
buf.append(", Ver: ").append(_ver.toString());
buf.append(", Flags: ").append(Integer.toBinaryString(getFlags())).append(", ");
buf.append(content);
String cleanContent = content.toString();
if(cleanContent.contains("password")) {
buf.append(cleanPassword(cleanContent));
} else {
buf.append(content);
}
buf.append(" }");
return buf.toString();
}
public static String cleanPassword(String logString) {
String cleanLogString = null;
if (logString != null) {
cleanLogString = logString;
String[] temp = logString.split(",");
int i = 0;
if (temp != null) {
while (i < temp.length) {
temp[i] = StringUtils.cleanString(temp[i]);
i++;
}
List<String> stringList = new ArrayList<String>();
Collections.addAll(stringList, temp);
cleanLogString = StringUtils.join(stringList, ",");
}
}
return cleanLogString;
}
/**
* Factory method for Request and Response. It expects the bytes to be
* correctly formed so it's possible that it throws underflow exceptions

6
debian/control vendored
View File

@ -2,7 +2,7 @@ Source: cloudstack
Section: libs
Priority: extra
Maintainer: Wido den Hollander <wido@widodh.nl>
Build-Depends: debhelper (>= 7), openjdk-6-jdk | openjdk-7-jdk, tomcat6, genisoimage,
Build-Depends: debhelper (>= 7), openjdk-7-jdk, tomcat6, genisoimage,
python-mysqldb, maven3 | maven (>= 3), python (>= 2.6.6-3~)
Standards-Version: 3.8.1
Homepage: http://www.cloudstack.org/
@ -22,7 +22,7 @@ Description: CloudStack server library
Package: cloudstack-agent
Architecture: all
Depends: openjdk-6-jre | openjdk-7-jre, cloudstack-common (= ${source:Version}), lsb-base (>= 3.2), libcommons-daemon-java, openssh-client, libvirt0, sysvinit-utils, qemu-kvm, libvirt-bin, uuid-runtime, rsync, grep, iproute, perl-base, perl-modules, ebtables, vlan, wget, jsvc, ipset, python-libvirt, ethtool, iptables
Depends: openjdk-7-jre, cloudstack-common (= ${source:Version}), lsb-base (>= 3.2), libcommons-daemon-java, openssh-client, libvirt0, sysvinit-utils, qemu-kvm, libvirt-bin, uuid-runtime, rsync, grep, iproute, perl-base, perl-modules, ebtables, vlan, wget, jsvc, ipset, python-libvirt, ethtool, iptables
Conflicts: cloud-agent, cloud-agent-libs, cloud-agent-deps, cloud-agent-scripts
Description: CloudStack agent
The CloudStack agent is in charge of managing shared computing resources in
@ -31,7 +31,7 @@ Description: CloudStack agent
Package: cloudstack-usage
Architecture: all
Depends: openjdk-6-jre | openjdk-7-jre, cloudstack-common (= ${source:Version}), jsvc
Depends: openjdk-7-jre, cloudstack-common (= ${source:Version}), jsvc
Description: CloudStack usage monitor
The CloudStack usage monitor provides usage accounting across the entire cloud for
cloud operators to charge based on usage parameters.

View File

@ -40,9 +40,9 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>${cs.checkstyle.version}</version>
<executions>
<execution>
<id>cloudstack-checkstyle</id>
<phase>none</phase>
</execution>
</executions>

View File

@ -20,4 +20,5 @@ public interface VmWorkConstants {
public static final String VM_WORK_QUEUE = "VmWorkJobQueue";
public static final String VM_WORK_JOB_DISPATCHER = "VmWorkJobDispatcher";
public static final String VM_WORK_JOB_WAKEUP_DISPATCHER = "VmWorkJobWakeupDispatcher";
public static final String VM_WORK_JOB_PLACEHOLDER = "VmWorkJobPlaceHolder";
}

View File

@ -61,6 +61,7 @@ import org.apache.cloudstack.framework.jobs.impl.AsyncJobVO;
import org.apache.cloudstack.framework.jobs.impl.OutcomeImpl;
import org.apache.cloudstack.framework.jobs.impl.VmWorkJobVO;
import org.apache.cloudstack.framework.messagebus.MessageBus;
import org.apache.cloudstack.framework.messagebus.MessageDispatcher;
import org.apache.cloudstack.framework.messagebus.MessageHandler;
import org.apache.cloudstack.jobs.JobInfo;
import org.apache.cloudstack.managed.context.ManagedContextRunnable;
@ -491,7 +492,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
Long hostId = vm.getHostId() != null ? vm.getHostId() : vm.getLastHostId();
if (volumeExpungeCommands != null && hostId != null) {
if (volumeExpungeCommands != null && volumeExpungeCommands.size() > 0 && hostId != null) {
Commands cmds = new Commands(Command.OnError.Stop);
for (Command volumeExpungeCommand : volumeExpungeCommands) {
@ -560,6 +561,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
_executor.scheduleAtFixedRate(new TransitionTask(), 5000, VmJobStateReportInterval.value(), TimeUnit.SECONDS);
_executor.scheduleAtFixedRate(new CleanupTask(), VmOpCleanupInterval.value(), VmOpCleanupInterval.value(), TimeUnit.SECONDS);
cancelWorkItems(_nodeId);
// cleanup left over place holder works
_workJobDao.expungeLeftoverWorkJobs(ManagementServerNode.getManagementServerId());
return true;
}
@ -578,6 +582,10 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
_agentMgr.registerForHostEvents(this, true, true, true);
if (VmJobEnabled.value()) {
_messageBus.subscribe(VirtualMachineManager.Topics.VM_POWER_STATE, MessageDispatcher.getDispatcher(this));
}
return true;
}
@ -746,7 +754,17 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
orchestrateStart(vmUuid, params, planToDeploy, planner);
VmWorkJobVO placeHolder = null;
if (VmJobEnabled.value()) {
VirtualMachine vm = _vmDao.findByUuid(vmUuid);
placeHolder = createPlaceHolderWork(vm.getId());
}
try {
orchestrateStart(vmUuid, params, planToDeploy, planner);
} finally {
if (VmJobEnabled.value())
_workJobDao.expunge(placeHolder.getId());
}
} else {
Outcome<VirtualMachine> outcome = startVmThroughJobQueue(vmUuid, params, planToDeploy);
@ -1107,6 +1125,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
VolumeVO volume = _volsDao.findById(volumeId);
disk.setPath(volume.get_iScsiName());
if (disk.getData() instanceof VolumeObjectTO) {
VolumeObjectTO volTo = (VolumeObjectTO)disk.getData();
volTo.setPath(volume.get_iScsiName());
}
volume.setPath(volume.get_iScsiName());
_volsDao.update(volumeId, volume);
@ -1117,20 +1142,22 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
// for managed storage on XenServer and VMware, need to update the DB with a path if the VDI/VMDK file was newly created
private void handlePath(DiskTO[] disks, Map<String, String> iqnToPath) {
if (disks != null) {
if (disks != null && iqnToPath != null) {
for (DiskTO disk : disks) {
Map<String, String> details = disk.getDetails();
boolean isManaged = details != null && Boolean.parseBoolean(details.get(DiskTO.MANAGED));
if (isManaged && disk.getPath() == null) {
if (isManaged) {
Long volumeId = disk.getData().getId();
VolumeVO volume = _volsDao.findById(volumeId);
String iScsiName = volume.get_iScsiName();
String path = iqnToPath.get(iScsiName);
volume.setPath(path);
if (path != null) {
volume.setPath(path);
_volsDao.update(volumeId, volume);
_volsDao.update(volumeId, volume);
}
}
}
}
@ -1268,7 +1295,19 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
orchestrateStop(vmUuid, cleanUpEvenIfUnableToStop);
VmWorkJobVO placeHolder = null;
if (VmJobEnabled.value()) {
VirtualMachine vm = _vmDao.findByUuid(vmUuid);
placeHolder = createPlaceHolderWork(vm.getId());
}
try {
orchestrateStop(vmUuid, cleanUpEvenIfUnableToStop);
} finally {
if (VmJobEnabled.value())
_workJobDao.expunge(placeHolder.getId());
}
} else {
Outcome<VirtualMachine> outcome = stopVmThroughJobQueue(vmUuid, cleanUpEvenIfUnableToStop);
@ -1560,7 +1599,17 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
orchestrateStorageMigration(vmUuid, destPool);
VmWorkJobVO placeHolder = null;
if (VmJobEnabled.value()) {
VirtualMachine vm = _vmDao.findByUuid(vmUuid);
placeHolder = createPlaceHolderWork(vm.getId());
}
try {
orchestrateStorageMigration(vmUuid, destPool);
} finally {
if (VmJobEnabled.value())
_workJobDao.expunge(placeHolder.getId());
}
} else {
Outcome<VirtualMachine> outcome = migrateVmStorageThroughJobQueue(vmUuid, destPool);
@ -1642,7 +1691,17 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
orchestrateMigrate(vmUuid, srcHostId, dest);
VmWorkJobVO placeHolder = null;
if (VmJobEnabled.value()) {
VirtualMachine vm = _vmDao.findByUuid(vmUuid);
placeHolder = createPlaceHolderWork(vm.getId());
}
try {
orchestrateMigrate(vmUuid, srcHostId, dest);
} finally {
if (VmJobEnabled.value())
_workJobDao.expunge(placeHolder.getId());
}
} else {
Outcome<VirtualMachine> outcome = migrateVmThroughJobQueue(vmUuid, srcHostId, dest);
@ -1913,7 +1972,19 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
orchestrateMigrateWithStorage(vmUuid, srcHostId, destHostId, volumeToPool);
VmWorkJobVO placeHolder = null;
if (VmJobEnabled.value()) {
VirtualMachine vm = _vmDao.findByUuid(vmUuid);
placeHolder = createPlaceHolderWork(vm.getId());
}
try {
orchestrateMigrateWithStorage(vmUuid, srcHostId, destHostId, volumeToPool);
} finally {
if (VmJobEnabled.value())
_workJobDao.expunge(placeHolder.getId());
}
} else {
Outcome<VirtualMachine> outcome = migrateVmWithStorageThroughJobQueue(vmUuid, srcHostId, destHostId, volumeToPool);
@ -2156,6 +2227,10 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
s_logger.trace("VM Operation Thread Running");
try {
_workDao.cleanup(VmOpCleanupWait.value());
// TODO. hard-coded to one hour after job has been completed
Date cutDate = new Date(new Date().getTime() - 3600000);
_workJobDao.expungeCompletedWorkJobs(cutDate);
} catch (Exception e) {
s_logger.error("VM Operations failed due to ", e);
}
@ -2192,7 +2267,17 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
orchestrateReboot(vmUuid, params);
VmWorkJobVO placeHolder = null;
if (VmJobEnabled.value()) {
VirtualMachine vm = _vmDao.findByUuid(vmUuid);
placeHolder = createPlaceHolderWork(vm.getId());
}
try {
orchestrateReboot(vmUuid, params);
} finally {
if (VmJobEnabled.value())
_workJobDao.expunge(placeHolder.getId());
}
} else {
Outcome<VirtualMachine> outcome = rebootVmThroughJobQueue(vmUuid, params);
@ -2743,7 +2828,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
s_logger.warn(e.getMessage());
}
}
} else if (serverState == State.Stopping) {
} else if (serverState == State.Stopped) {
s_logger.debug("Scheduling a stop command for " + vm);
_haMgr.scheduleStop(vm, hostId, WorkType.Stop);
} else {
@ -3113,7 +3198,16 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
return orchestrateAddVmToNetwork(vm, network, requested);
VmWorkJobVO placeHolder = null;
if (VmJobEnabled.value()) {
placeHolder = createPlaceHolderWork(vm.getId());
}
try {
return orchestrateAddVmToNetwork(vm, network, requested);
} finally {
if (VmJobEnabled.value())
_workJobDao.expunge(placeHolder.getId());
}
} else {
Outcome<VirtualMachine> outcome = addVmToNetworkThroughJobQueue(vm, network, requested);
@ -3216,7 +3310,17 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
return orchestrateRemoveNicFromVm(vm, nic);
VmWorkJobVO placeHolder = null;
if (VmJobEnabled.value()) {
placeHolder = createPlaceHolderWork(vm.getId());
}
try {
return orchestrateRemoveNicFromVm(vm, nic);
} finally {
if (VmJobEnabled.value())
_workJobDao.expunge(placeHolder.getId());
}
} else {
Outcome<VirtualMachine> outcome = removeNicFromVmThroughJobQueue(vm, nic);
@ -3455,7 +3559,17 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
orchestrateMigrateForScale(vmUuid, srcHostId, dest, oldSvcOfferingId);
VmWorkJobVO placeHolder = null;
if (VmJobEnabled.value()) {
VirtualMachine vm = _vmDao.findByUuid(vmUuid);
placeHolder = createPlaceHolderWork(vm.getId());
}
try {
orchestrateMigrateForScale(vmUuid, srcHostId, dest, oldSvcOfferingId);
} finally {
if (VmJobEnabled.value())
_workJobDao.expunge(placeHolder.getId());
}
} else {
Outcome<VirtualMachine> outcome = migrateVmForScaleThroughJobQueue(vmUuid, srcHostId, dest, oldSvcOfferingId);
@ -3704,7 +3818,17 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
return orchestrateReConfigureVm(vmUuid, oldServiceOffering, reconfiguringOnExistingHost);
VmWorkJobVO placeHolder = null;
if (VmJobEnabled.value()) {
VirtualMachine vm = _vmDao.findByUuid(vmUuid);
placeHolder = createPlaceHolderWork(vm.getId());
}
try {
return orchestrateReConfigureVm(vmUuid, oldServiceOffering, reconfiguringOnExistingHost);
} finally {
if (VmJobEnabled.value())
_workJobDao.expunge(placeHolder.getId());
}
} else {
Outcome<VirtualMachine> outcome = reconfigureVmThroughJobQueue(vmUuid, oldServiceOffering, reconfiguringOnExistingHost);
@ -3816,7 +3940,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
//
@MessageHandler(topic = Topics.VM_POWER_STATE)
private void HandlePownerStateReport(Object target, String subject, String senderAddress, Object args) {
private void HandlePowerStateReport(String subject, String senderAddress, Object args) {
assert (args != null);
Long vmId = (Long)args;
@ -3836,7 +3960,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
break;
// PowerUnknown shouldn't be reported, it is a derived
// VM power state from host state (host un-reachable
// VM power state from host state (host un-reachable)
case PowerUnknown:
default:
assert (false);
@ -3846,8 +3970,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
s_logger.warn("VM " + vmId + " no longer exists when processing VM state report");
}
} else {
// TODO, do job wake-up signalling, since currently async job wake-up is not in use
// we will skip it for nows
// reset VM power state tracking so that we won't lost signal when VM has
// been translated to
_vmDao.resetVmPowerStateTracking(vmId);
}
}
@ -3924,6 +4049,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
switch (vm.getState()) {
case Starting:
case Stopping:
case Running:
case Stopped:
case Migrating:
try {
@ -3937,7 +4063,6 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
// TODO: we need to forcely release all resource allocation
break;
case Running:
case Destroyed:
case Expunging:
break;
@ -4179,7 +4304,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
workJob.setAccountId(callingAccount.getId());
workJob.setUserId(callingUser.getId());
workJob.setStep(VmWorkJobVO.Step.Starting);
workJob.setVmType(vm.getType());
workJob.setVmType(VirtualMachine.Type.Instance);
workJob.setVmInstanceId(vm.getId());
workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId());
@ -4192,7 +4317,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
return new Object[] {workJob, new Long(workJob.getId())};
return new Object[] {workJob, workJob.getId()};
}
});
@ -4232,7 +4357,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
workJob.setAccountId(account.getId());
workJob.setUserId(user.getId());
workJob.setStep(VmWorkJobVO.Step.Prepare);
workJob.setVmType(vm.getType());
workJob.setVmType(VirtualMachine.Type.Instance);
workJob.setVmInstanceId(vm.getId());
workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId());
@ -4243,7 +4368,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
return new Object[] {workJob, new Long(workJob.getId())};
return new Object[] {workJob, workJob.getId()};
}
});
@ -4285,7 +4410,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
workJob.setAccountId(account.getId());
workJob.setUserId(user.getId());
workJob.setStep(VmWorkJobVO.Step.Prepare);
workJob.setVmType(vm.getType());
workJob.setVmType(VirtualMachine.Type.Instance);
workJob.setVmInstanceId(vm.getId());
workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId());
@ -4296,7 +4421,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
return new Object[] {workJob, new Long(workJob.getId())};
return new Object[] {workJob, workJob.getId()};
}
});
@ -4335,7 +4460,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
workJob.setAccountId(account.getId());
workJob.setUserId(user.getId());
workJob.setVmType(vm.getType());
workJob.setVmType(VirtualMachine.Type.Instance);
workJob.setVmInstanceId(vm.getId());
workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId());
@ -4345,7 +4470,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
return new Object[] {workJob, new Long(workJob.getId())};
return new Object[] {workJob, workJob.getId()};
}
});
@ -4389,7 +4514,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
workJob.setAccountId(account.getId());
workJob.setUserId(user.getId());
workJob.setVmType(vm.getType());
workJob.setVmType(VirtualMachine.Type.Instance);
workJob.setVmInstanceId(vm.getId());
workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId());
@ -4400,7 +4525,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
return new Object[] {workJob, new Long(workJob.getId())};
return new Object[] {workJob, workJob.getId()};
}
});
@ -4441,7 +4566,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
workJob.setAccountId(account.getId());
workJob.setUserId(user.getId());
workJob.setVmType(vm.getType());
workJob.setVmType(VirtualMachine.Type.Instance);
workJob.setVmInstanceId(vm.getId());
workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId());
@ -4453,7 +4578,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
return new Object[] {workJob, new Long(workJob.getId())};
return new Object[] {workJob, workJob.getId()};
}
});
@ -4493,7 +4618,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
workJob.setAccountId(account.getId());
workJob.setUserId(user.getId());
workJob.setVmType(vm.getType());
workJob.setVmType(VirtualMachine.Type.Instance);
workJob.setVmInstanceId(vm.getId());
workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId());
@ -4505,7 +4630,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
return new Object[] {workJob, new Long(workJob.getId())};
return new Object[] {workJob, workJob.getId()};
}
});
@ -4543,7 +4668,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
workJob.setAccountId(account.getId());
workJob.setUserId(user.getId());
workJob.setVmType(vm.getType());
workJob.setVmType(VirtualMachine.Type.Instance);
workJob.setVmInstanceId(vm.getId());
workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId());
@ -4554,7 +4679,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
return new Object[] {workJob, new Long(workJob.getId())};
return new Object[] {workJob, workJob.getId()};
}
});
@ -4592,7 +4717,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
workJob.setAccountId(account.getId());
workJob.setUserId(user.getId());
workJob.setVmType(vm.getType());
workJob.setVmType(VirtualMachine.Type.Instance);
workJob.setVmInstanceId(vm.getId());
workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId());
@ -4603,7 +4728,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
return new Object[] {workJob, new Long(workJob.getId())};
return new Object[] {workJob, workJob.getId()};
}
});
@ -4641,7 +4766,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
workJob.setAccountId(account.getId());
workJob.setUserId(user.getId());
workJob.setVmType(vm.getType());
workJob.setVmType(VirtualMachine.Type.Instance);
workJob.setVmInstanceId(vm.getId());
workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId());
@ -4652,7 +4777,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
return new Object[] {workJob, new Long(workJob.getId())};
return new Object[] {workJob, workJob.getId()};
}
});
@ -4692,7 +4817,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
workJob.setAccountId(account.getId());
workJob.setUserId(user.getId());
workJob.setVmType(vm.getType());
workJob.setVmType(VirtualMachine.Type.Instance);
workJob.setVmInstanceId(vm.getId());
workJob.setRelated(AsyncJobExecutionContext.getOriginJobContextId());
@ -4703,7 +4828,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
return new Object[] {workJob, new Long(workJob.getId())};
return new Object[] {workJob, workJob.getId()};
}
});
@ -4793,7 +4918,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
NicProfile nic = orchestrateAddVmToNetwork(vm, network,
work.getRequestedNicProfile());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED, _jobMgr.marshallResultObject(new Long(nic.getId())));
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED, _jobMgr.marshallResultObject(nic.getId()));
}
private Pair<JobInfo.Status, String> orchestrateRemoveNicFromVm(VmWorkRemoveNicFromVm work) throws Exception {
@ -4848,4 +4973,23 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
public Pair<JobInfo.Status, String> handleVmWorkJob(VmWork work) throws Exception {
return _jobHandlerProxy.handleVmWorkJob(work);
}
private VmWorkJobVO createPlaceHolderWork(long instanceId) {
VmWorkJobVO workJob = new VmWorkJobVO("");
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_PLACEHOLDER);
workJob.setCmd("");
workJob.setCmdInfo("");
workJob.setAccountId(0);
workJob.setUserId(0);
workJob.setStep(VmWorkJobVO.Step.Starting);
workJob.setVmType(VirtualMachine.Type.Instance);
workJob.setVmInstanceId(instanceId);
workJob.setInitMsid(ManagementServerNode.getManagementServerId());
_workJobDao.persist(workJob);
return workJob;
}
}

View File

@ -28,4 +28,6 @@ public interface VirtualMachinePowerStateSync {
// to adapt legacy ping report
void processHostVmStatePingReport(long hostId, Map<String, HostVmStateReportEntry> report);
Map<Long, VirtualMachine.PowerState> convertVmStateReport(Map<String, HostVmStateReportEntry> states);
}

View File

@ -32,12 +32,9 @@ import com.cloud.vm.dao.VMInstanceDao;
public class VirtualMachinePowerStateSyncImpl implements VirtualMachinePowerStateSync {
private static final Logger s_logger = Logger.getLogger(VirtualMachinePowerStateSyncImpl.class);
@Inject
MessageBus _messageBus;
@Inject
VMInstanceDao _instanceDao;
@Inject
VirtualMachineManager _vmMgr;
@Inject MessageBus _messageBus;
@Inject VMInstanceDao _instanceDao;
@Inject VirtualMachineManager _vmMgr;
public VirtualMachinePowerStateSyncImpl() {
}
@ -53,7 +50,7 @@ public class VirtualMachinePowerStateSyncImpl implements VirtualMachinePowerStat
if (s_logger.isDebugEnabled())
s_logger.debug("Process host VM state report from ping process. host: " + hostId);
Map<Long, VirtualMachine.PowerState> translatedInfo = convertToInfos(report);
Map<Long, VirtualMachine.PowerState> translatedInfo = convertVmStateReport(report);
processReport(hostId, translatedInfo);
}
@ -62,7 +59,7 @@ public class VirtualMachinePowerStateSyncImpl implements VirtualMachinePowerStat
if (s_logger.isDebugEnabled())
s_logger.debug("Process host VM state report from ping process. host: " + hostId);
Map<Long, VirtualMachine.PowerState> translatedInfo = convertToInfos(report);
Map<Long, VirtualMachine.PowerState> translatedInfo = convertVmStateReport(report);
processReport(hostId, translatedInfo);
}
@ -74,16 +71,19 @@ public class VirtualMachinePowerStateSyncImpl implements VirtualMachinePowerStat
s_logger.debug("VM state report. host: " + hostId + ", vm id: " + entry.getKey() + ", power state: " + entry.getValue());
if (_instanceDao.updatePowerState(entry.getKey(), hostId, entry.getValue())) {
if (s_logger.isDebugEnabled())
s_logger.debug("VM state report is updated. host: " + hostId + ", vm id: " + entry.getKey() + ", power state: " + entry.getValue());
_messageBus.publish(null, VirtualMachineManager.Topics.VM_POWER_STATE, PublishScope.GLOBAL, entry.getKey());
} else {
if (s_logger.isDebugEnabled())
s_logger.debug("VM power state does not change, skip DB writing. vm id: " + entry.getKey());
}
}
}
private Map<Long, VirtualMachine.PowerState> convertToInfos(Map<String, HostVmStateReportEntry> states) {
@Override
public Map<Long, VirtualMachine.PowerState> convertVmStateReport(Map<String, HostVmStateReportEntry> states) {
final HashMap<Long, VirtualMachine.PowerState> map = new HashMap<Long, VirtualMachine.PowerState>();
if (states == null) {
return map;
@ -93,7 +93,6 @@ public class VirtualMachinePowerStateSyncImpl implements VirtualMachinePowerStat
VMInstanceVO vm = findVM(entry.getKey());
if (vm != null) {
map.put(vm.getId(), entry.getValue().getState());
break;
} else {
s_logger.info("Unable to find matched VM in CloudStack DB. name: " + entry.getKey());
}

View File

@ -60,9 +60,6 @@ public class VmWorkJobDispatcher extends AdapterBase implements AsyncJobDispatch
String cmd = job.getCmd();
assert (cmd != null);
if (s_logger.isDebugEnabled())
s_logger.debug("Run VM work job: " + cmd + ", job origin: " + job.getRelated());
Class<?> workClz = null;
try {
workClz = Class.forName(job.getCmd());
@ -80,27 +77,33 @@ public class VmWorkJobDispatcher extends AdapterBase implements AsyncJobDispatch
return;
}
if (_handlers == null || _handlers.isEmpty()) {
s_logger.error("Invalid startup configuration, no work job handler is found. cmd: " + job.getCmd() + ", job info: " + job.getCmdInfo()
+ ", job origin: " + job.getRelated());
_asyncJobMgr.completeAsyncJob(job.getId(), JobInfo.Status.FAILED, 0, "Invalid startup configuration. no job handler is found");
return;
if (s_logger.isDebugEnabled())
s_logger.debug("Run VM work job: " + cmd + " for VM " + work.getVmId() + ", job origin: " + job.getRelated());
try {
if (_handlers == null || _handlers.isEmpty()) {
s_logger.error("Invalid startup configuration, no work job handler is found. cmd: " + job.getCmd() + ", job info: " + job.getCmdInfo()
+ ", job origin: " + job.getRelated());
_asyncJobMgr.completeAsyncJob(job.getId(), JobInfo.Status.FAILED, 0, "Invalid startup configuration. no job handler is found");
return;
}
VmWorkJobHandler handler = _handlers.get(work.getHandlerName());
if (handler == null) {
s_logger.error("Unable to find work job handler. handler name: " + work.getHandlerName() + ", job cmd: " + job.getCmd()
+ ", job info: " + job.getCmdInfo() + ", job origin: " + job.getRelated());
_asyncJobMgr.completeAsyncJob(job.getId(), JobInfo.Status.FAILED, 0, "Unable to find work job handler");
return;
}
CallContext.register(work.getUserId(), work.getAccountId(), job.getRelated());
Pair<JobInfo.Status, String> result = handler.handleVmWorkJob(work);
_asyncJobMgr.completeAsyncJob(job.getId(), result.first(), 0, result.second());
} finally {
if (s_logger.isDebugEnabled())
s_logger.debug("Done with run of VM work job: " + cmd + " for VM " + work.getVmId() + ", job origin: " + job.getRelated());
}
VmWorkJobHandler handler = _handlers.get(work.getHandlerName());
if (handler == null) {
s_logger.error("Unable to find work job handler. handler name: " + work.getHandlerName() + ", job cmd: " + job.getCmd()
+ ", job info: " + job.getCmdInfo() + ", job origin: " + job.getRelated());
_asyncJobMgr.completeAsyncJob(job.getId(), JobInfo.Status.FAILED, 0, "Unable to find work job handler");
return;
}
CallContext.register(work.getUserId(), work.getAccountId(), job.getRelated());
Pair<JobInfo.Status, String> result = handler.handleVmWorkJob(work);
_asyncJobMgr.completeAsyncJob(job.getId(), result.first(), 0, result.second());
} catch(Throwable e) {
s_logger.error("Unable to complete " + job + ", job origin:" + job.getRelated(), e);

View File

@ -323,6 +323,13 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati
while ((pool = findStoragePool(dskCh, dc, pod.first(), null, null, null, poolsToAvoid)) != null) {
break;
}
if (pool != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Found a suitable pool for create volume: " + pool.getId());
}
break;
}
}
}
@ -408,6 +415,7 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati
@DB
public VolumeInfo createVolume(VolumeInfo volume, VirtualMachine vm, VirtualMachineTemplate template, DataCenter dc, Pod pod, Long clusterId, ServiceOffering offering,
DiskOffering diskOffering, List<StoragePool> avoids, long size, HypervisorType hyperType) {
// update the volume's hypervisor_ss_reserve from its disk offering (used for managed storage)
volume = updateHypervisorSnapshotReserveForVolume(diskOffering, volume, hyperType);
StoragePool pool = null;
@ -1089,6 +1097,14 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati
// retry one more time in case of template reload is required for Vmware case
AsyncCallFuture<VolumeApiResult> future = null;
if (templateId == null) {
DiskOffering diskOffering = _entityMgr.findById(DiskOffering.class, volume.getDiskOfferingId());
HypervisorType hyperType = vm.getVirtualMachine().getHypervisorType();
// update the volume's hypervisor_ss_reserve from its disk offering (used for managed storage)
updateHypervisorSnapshotReserveForVolume(diskOffering, volume, hyperType);
volume = volFactory.getVolume(newVol.getId(), destPool);
future = volService.createVolumeAsync(volume, destPool);
} else {
TemplateInfo templ = tmplFactory.getTemplate(templateId, DataStoreRole.Image);
@ -1106,6 +1122,16 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati
throw new StorageUnavailableException("Unable to create " + newVol + ":" + result.getResult(), destPool.getId());
}
}
StoragePoolVO storagePool = _storagePoolDao.findById(destPool.getId());
if (newVol.getVolumeType() == Type.DATADISK && storagePool.isManaged()) {
long hostId = vm.getVirtualMachine().getHostId();
Host host = _hostDao.findById(hostId);
volService.connectVolumeToHost(volFactory.getVolume(newVol.getId()), host, destPool);
}
newVol = _volsDao.findById(newVol.getId());
break; //break out of template-redeploy retry loop
} catch (InterruptedException e) {

View File

@ -171,7 +171,6 @@
<bean id="hostTagsDaoImpl" class="com.cloud.host.dao.HostTagsDaoImpl" />
<bean id="hostTransferMapDaoImpl" class="com.cloud.cluster.agentlb.dao.HostTransferMapDaoImpl" />
<bean id="iPAddressDaoImpl" class="com.cloud.network.dao.IPAddressDaoImpl" />
<bean id="identityDaoImpl" class="com.cloud.uuididentity.dao.IdentityDaoImpl" />
<bean id="imageStoreDaoImpl" class="org.apache.cloudstack.storage.image.db.ImageStoreDaoImpl" />
<bean id="imageStoreDetailsDaoImpl" class="org.apache.cloudstack.storage.image.db.ImageStoreDetailsDaoImpl" />
<bean id="imageStoreJoinDaoImpl" class="com.cloud.api.query.dao.ImageStoreJoinDaoImpl" />

View File

@ -27,11 +27,9 @@ import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.apache.log4j.Logger;
@ -83,7 +81,6 @@ public class Upgrade410to420 implements DbUpgrade {
persistVswitchConfiguration(conn);
createPlaceHolderNics(conn);
updateRemoteAccessVpn(conn);
updateSystemVmTemplates(conn);
updateOverCommitRatioClusterDetails(conn);
updatePrimaryStore(conn);
addEgressFwRulesForSRXGuestNw(conn);
@ -634,173 +631,6 @@ public class Upgrade410to420 implements DbUpgrade {
}
private void updateSystemVmTemplates(Connection conn) {
// TODO: system vm template migration after storage refactoring
PreparedStatement pstmt = null;
ResultSet rs = null;
s_logger.debug("Updating System Vm template IDs");
try {
//Get all hypervisors in use
Set<HypervisorType> hypervisorsListInUse = new HashSet<HypervisorType>();
try {
pstmt = conn.prepareStatement("select distinct(hypervisor_type) from `cloud`.`cluster` where removed is null");
rs = pstmt.executeQuery();
while (rs.next()) {
switch (HypervisorType.getType(rs.getString(1))) {
case XenServer:
hypervisorsListInUse.add(HypervisorType.XenServer);
break;
case KVM:
hypervisorsListInUse.add(HypervisorType.KVM);
break;
case VMware:
hypervisorsListInUse.add(HypervisorType.VMware);
break;
case Hyperv:
hypervisorsListInUse.add(HypervisorType.Hyperv);
break;
case LXC:
hypervisorsListInUse.add(HypervisorType.LXC);
break;
}
}
} catch (SQLException e) {
throw new CloudRuntimeException("Error while listing hypervisors in use", e);
}
Map<HypervisorType, String> NewTemplateNameList = new HashMap<HypervisorType, String>() {
{
put(HypervisorType.XenServer, "systemvm-xenserver-4.2");
put(HypervisorType.VMware, "systemvm-vmware-4.2");
put(HypervisorType.KVM, "systemvm-kvm-4.2");
put(HypervisorType.LXC, "systemvm-lxc-4.2");
put(HypervisorType.Hyperv, "systemvm-hyperv-4.2");
}
};
Map<HypervisorType, String> routerTemplateConfigurationNames = new HashMap<HypervisorType, String>() {
{
put(HypervisorType.XenServer, "router.template.xen");
put(HypervisorType.VMware, "router.template.vmware");
put(HypervisorType.KVM, "router.template.kvm");
put(HypervisorType.LXC, "router.template.lxc");
put(HypervisorType.Hyperv, "router.template.hyperv");
}
};
Map<HypervisorType, String> newTemplateUrl = new HashMap<HypervisorType, String>() {
{
put(HypervisorType.XenServer, "http://download.cloud.com/templates/4.2/systemvmtemplate-2013-07-12-master-xen.vhd.bz2");
put(HypervisorType.VMware, "http://download.cloud.com/templates/4.2/systemvmtemplate-4.2-vh7.ova");
put(HypervisorType.KVM, "http://download.cloud.com/templates/4.2/systemvmtemplate-2013-06-12-master-kvm.qcow2.bz2");
put(HypervisorType.LXC, "http://download.cloud.com/templates/acton/acton-systemvm-02062012.qcow2.bz2");
put(HypervisorType.Hyperv, "http://download.cloud.com/templates/4.2/systemvmtemplate-2013-06-12-master-xen.vhd.bz2");
}
};
Map<HypervisorType, String> newTemplateChecksum = new HashMap<HypervisorType, String>() {
{
put(HypervisorType.XenServer, "fb1b6e032a160d86f2c28feb5add6d83");
put(HypervisorType.VMware, "8fde62b1089e5844a9cd3b9b953f9596");
put(HypervisorType.KVM, "6cea42b2633841648040becb588bd8f0");
put(HypervisorType.LXC, "2755de1f9ef2ce4d6f2bee2efbb4da92");
put(HypervisorType.Hyperv, "fb1b6e032a160d86f2c28feb5add6d83");
}
};
for (Map.Entry<HypervisorType, String> hypervisorAndTemplateName : NewTemplateNameList.entrySet()) {
s_logger.debug("Updating " + hypervisorAndTemplateName.getKey() + " System Vms");
try {
//Get 4.2.0 system Vm template Id for corresponding hypervisor
pstmt = conn.prepareStatement("select id from `cloud`.`vm_template` where name = ? and removed is null order by id desc limit 1");
pstmt.setString(1, hypervisorAndTemplateName.getValue());
rs = pstmt.executeQuery();
if (rs.next()) {
long templateId = rs.getLong(1);
rs.close();
pstmt.close();
// Mark the old system templates as removed
pstmt =
conn.prepareStatement("UPDATE `cloud`.`vm_template` SET removed = now() WHERE hypervisor_type = ? AND type = 'SYSTEM' AND removed is null");
pstmt.setString(1, hypervisorAndTemplateName.getKey().toString());
pstmt.executeUpdate();
pstmt.close();
// change template type to SYSTEM
pstmt = conn.prepareStatement("update `cloud`.`vm_template` set type='SYSTEM' where id = ?");
pstmt.setLong(1, templateId);
pstmt.executeUpdate();
pstmt.close();
// update templete ID of system Vms
pstmt = conn.prepareStatement("update `cloud`.`vm_instance` set vm_template_id = ? where type <> 'User' and hypervisor_type = ?");
pstmt.setLong(1, templateId);
pstmt.setString(2, hypervisorAndTemplateName.getKey().toString());
pstmt.executeUpdate();
pstmt.close();
// Change value of global configuration parameter router.template.* for the corresponding hypervisor
pstmt = conn.prepareStatement("UPDATE `cloud`.`configuration` SET value = ? WHERE name = ?");
pstmt.setString(1, hypervisorAndTemplateName.getValue());
pstmt.setString(2, routerTemplateConfigurationNames.get(hypervisorAndTemplateName.getKey()));
pstmt.executeUpdate();
pstmt.close();
} else {
if (hypervisorsListInUse.contains(hypervisorAndTemplateName.getKey())) {
throw new CloudRuntimeException("4.2.0 " + hypervisorAndTemplateName.getKey() + " SystemVm template not found. Cannot upgrade system Vms");
} else {
s_logger.warn("4.2.0 " + hypervisorAndTemplateName.getKey() + " SystemVm template not found. " + hypervisorAndTemplateName.getKey() +
" hypervisor is not used, so not failing upgrade");
// Update the latest template URLs for corresponding hypervisor
pstmt =
conn.prepareStatement("UPDATE `cloud`.`vm_template` SET url = ? , checksum = ? WHERE hypervisor_type = ? AND type = 'SYSTEM' AND removed is null order by id desc limit 1");
pstmt.setString(1, newTemplateUrl.get(hypervisorAndTemplateName.getKey()));
pstmt.setString(2, newTemplateChecksum.get(hypervisorAndTemplateName.getKey()));
pstmt.setString(3, hypervisorAndTemplateName.getKey().toString());
pstmt.executeUpdate();
pstmt.close();
}
}
} catch (SQLException e) {
throw new CloudRuntimeException("Error while updating " + hypervisorAndTemplateName.getKey() + " systemVm template", e);
}
}
try {
pstmt = conn.prepareStatement("UPDATE `cloud`.`vm_template` set dynamically_scalable = 1 where name = ? and type = 'SYSTEM'");
pstmt.setString(1, NewTemplateNameList.get(HypervisorType.VMware));
pstmt.executeUpdate();
pstmt.close();
} catch (SQLException e) {
throw new CloudRuntimeException("Error while updating dynamically_scalable flag to 1 for SYSTEM template systemvm-vmware-4.2");
}
s_logger.debug("Updating System Vm Template IDs Complete");
} finally {
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException e) {
}
}
/*
pstmt = null;
try {
pstmt = conn.prepareStatement("update vm_template set image_data_store_id = 1 where type = 'SYSTEM' or type = 'BUILTIN'");
pstmt.executeUpdate();
} catch (SQLException e) {
throw new CloudRuntimeException("Failed to upgrade vm template data store uuid: " + e.toString());
} finally {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
}
}
}
*/
}
//KVM snapshot flag: only turn on if Customers is using snapshot;
private void setKVMSnapshotFlag(Connection conn) {
s_logger.debug("Verify and set the KVM snapshot flag if snapshot was used. ");

View File

@ -24,10 +24,15 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.cloud.hypervisor.Hypervisor;
import com.cloud.utils.crypt.DBEncryptionUtil;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.script.Script;
@ -63,6 +68,51 @@ public class Upgrade421to430 implements DbUpgrade {
@Override
public void performDataMigration(Connection conn) {
encryptLdapConfigParams(conn);
encryptImageStoreDetails(conn);
upgradeMemoryOfSsvmOffering(conn);
updateSystemVmTemplates(conn);
}
private void upgradeMemoryOfSsvmOffering(Connection conn) {
PreparedStatement updatePstmt = null;
PreparedStatement selectPstmt = null;
ResultSet selectResultSet = null;
int newRamSize = 512; //512MB
long serviceOfferingId = 0;
/**
* Pick first row in service_offering table which has system vm type as secondary storage vm. User added offerings would start from 2nd row onwards.
* We should not update/modify any user-defined offering.
*/
try {
selectPstmt = conn.prepareStatement("SELECT id FROM `cloud`.`service_offering` WHERE vm_type='secondarystoragevm'");
updatePstmt = conn.prepareStatement("UPDATE `cloud`.`service_offering` SET ram_size=? WHERE id=?");
selectResultSet = selectPstmt.executeQuery();
if(selectResultSet.next()) {
serviceOfferingId = selectResultSet.getLong("id");
}
updatePstmt.setInt(1, newRamSize);
updatePstmt.setLong(2, serviceOfferingId);
updatePstmt.executeUpdate();
} catch (SQLException e) {
throw new CloudRuntimeException("Unable to upgrade ram_size of service offering for secondary storage vm. ", e);
} finally {
try {
if (selectPstmt != null) {
selectPstmt.close();
}
if (selectResultSet != null) {
selectResultSet.close();
}
if (updatePstmt != null) {
updatePstmt.close();
}
} catch (SQLException e) {
}
}
s_logger.debug("Done upgrading RAM for service offering of Secondary Storage VM to " + newRamSize);
}
private void encryptLdapConfigParams(Connection conn) {
@ -140,6 +190,174 @@ public class Upgrade421to430 implements DbUpgrade {
}
private void updateSystemVmTemplates(Connection conn) {
PreparedStatement pstmt = null;
ResultSet rs = null;
s_logger.debug("Updating System Vm template IDs");
try{
//Get all hypervisors in use
Set<Hypervisor.HypervisorType> hypervisorsListInUse = new HashSet<Hypervisor.HypervisorType>();
try {
pstmt = conn.prepareStatement("select distinct(hypervisor_type) from `cloud`.`cluster` where removed is null");
rs = pstmt.executeQuery();
while(rs.next()){
switch (Hypervisor.HypervisorType.getType(rs.getString(1))) {
case XenServer: hypervisorsListInUse.add(Hypervisor.HypervisorType.XenServer);
break;
case KVM: hypervisorsListInUse.add(Hypervisor.HypervisorType.KVM);
break;
case VMware: hypervisorsListInUse.add(Hypervisor.HypervisorType.VMware);
break;
case Hyperv: hypervisorsListInUse.add(Hypervisor.HypervisorType.Hyperv);
break;
case LXC: hypervisorsListInUse.add(Hypervisor.HypervisorType.LXC);
break;
}
}
} catch (SQLException e) {
throw new CloudRuntimeException("Error while listing hypervisors in use", e);
}
Map<Hypervisor.HypervisorType, String> NewTemplateNameList = new HashMap<Hypervisor.HypervisorType, String>(){
{ put(Hypervisor.HypervisorType.XenServer, "systemvm-xenserver-4.3");
put(Hypervisor.HypervisorType.VMware, "systemvm-vmware-4.3");
put(Hypervisor.HypervisorType.KVM, "systemvm-kvm-4.3");
put(Hypervisor.HypervisorType.LXC, "systemvm-lxc-4.3");
put(Hypervisor.HypervisorType.Hyperv, "systemvm-hyperv-4.3");
}
};
Map<Hypervisor.HypervisorType, String> routerTemplateConfigurationNames = new HashMap<Hypervisor.HypervisorType, String>(){
{ put(Hypervisor.HypervisorType.XenServer, "router.template.xen");
put(Hypervisor.HypervisorType.VMware, "router.template.vmware");
put(Hypervisor.HypervisorType.KVM, "router.template.kvm");
put(Hypervisor.HypervisorType.LXC, "router.template.lxc");
put(Hypervisor.HypervisorType.Hyperv, "router.template.hyperv");
}
};
Map<Hypervisor.HypervisorType, String> newTemplateUrl = new HashMap<Hypervisor.HypervisorType, String>(){
{ put(Hypervisor.HypervisorType.XenServer, "http://download.cloud.com/templates/4.3/systemvm64template-2014-01-14-master-xen.vhd.bz2");
put(Hypervisor.HypervisorType.VMware, "http://download.cloud.com/templates/4.3/systemvm64template-2014-01-14-master-vmware.ova");
put(Hypervisor.HypervisorType.KVM, "http://download.cloud.com/templates/4.3/systemvm64template-2014-01-14-master-kvm.qcow2.bz2");
put(Hypervisor.HypervisorType.LXC, "http://download.cloud.com/templates/4.3/systemvm64template-2014-01-14-master-kvm.qcow2.bz2");
put(Hypervisor.HypervisorType.Hyperv, "http://download.cloud.com/templates/4.3/systemvm64template-2013-12-23-hyperv.vhd.bz2");
}
};
Map<Hypervisor.HypervisorType, String> newTemplateChecksum = new HashMap<Hypervisor.HypervisorType, String>(){
{ put(Hypervisor.HypervisorType.XenServer, "74b92f031cc5c2089ee89efb81344dcf");
put(Hypervisor.HypervisorType.VMware, "ef593a061f3b7594ab0bfd9b0ed0a0d4");
put(Hypervisor.HypervisorType.KVM, "85a1bed07bf43cbf022451cb2ecae4ff");
put(Hypervisor.HypervisorType.LXC, "85a1bed07bf43cbf022451cb2ecae4ff");
put(Hypervisor.HypervisorType.Hyperv, "5df45ee6ebe1b703a8805f4e1f4d0818");
}
};
for (Map.Entry<Hypervisor.HypervisorType, String> hypervisorAndTemplateName : NewTemplateNameList.entrySet()){
s_logger.debug("Updating " + hypervisorAndTemplateName.getKey() + " System Vms");
try {
//Get 4.3.0 system Vm template Id for corresponding hypervisor
pstmt = conn.prepareStatement("select id from `cloud`.`vm_template` where name = ? and removed is null order by id desc limit 1");
pstmt.setString(1, hypervisorAndTemplateName.getValue());
rs = pstmt.executeQuery();
if(rs.next()){
long templateId = rs.getLong(1);
rs.close();
pstmt.close();
// // Mark the old system templates as removed
// pstmt = conn.prepareStatement("UPDATE `cloud`.`vm_template` SET removed = now() WHERE hypervisor_type = ? AND type = 'SYSTEM' AND removed is null");
// pstmt.setString(1, hypervisorAndTemplateName.getKey().toString());
// pstmt.executeUpdate();
// pstmt.close();
// change template type to SYSTEM
pstmt = conn.prepareStatement("update `cloud`.`vm_template` set type='SYSTEM' where id = ?");
pstmt.setLong(1, templateId);
pstmt.executeUpdate();
pstmt.close();
// update templete ID of system Vms
pstmt = conn.prepareStatement("update `cloud`.`vm_instance` set vm_template_id = ? where type <> 'User' and hypervisor_type = ?");
pstmt.setLong(1, templateId);
pstmt.setString(2, hypervisorAndTemplateName.getKey().toString());
pstmt.executeUpdate();
pstmt.close();
// Change value of global configuration parameter router.template.* for the corresponding hypervisor
pstmt = conn.prepareStatement("UPDATE `cloud`.`configuration` SET value = ? WHERE name = ?");
pstmt.setString(1, hypervisorAndTemplateName.getValue());
pstmt.setString(2, routerTemplateConfigurationNames.get(hypervisorAndTemplateName.getKey()));
pstmt.executeUpdate();
pstmt.close();
} else {
if (hypervisorsListInUse.contains(hypervisorAndTemplateName.getKey())){
throw new CloudRuntimeException("4.3.0 " + hypervisorAndTemplateName.getKey() + " SystemVm template not found. Cannot upgrade system Vms");
} else {
s_logger.warn("4.3.0 " + hypervisorAndTemplateName.getKey() + " SystemVm template not found. " + hypervisorAndTemplateName.getKey() + " hypervisor is not used, so not failing upgrade");
// Update the latest template URLs for corresponding hypervisor
pstmt = conn.prepareStatement("UPDATE `cloud`.`vm_template` SET url = ? , checksum = ? WHERE hypervisor_type = ? AND type = 'SYSTEM' AND removed is null order by id desc limit 1");
pstmt.setString(1, newTemplateUrl.get(hypervisorAndTemplateName.getKey()));
pstmt.setString(2, newTemplateChecksum.get(hypervisorAndTemplateName.getKey()));
pstmt.setString(3, hypervisorAndTemplateName.getKey().toString());
pstmt.executeUpdate();
pstmt.close();
}
}
} catch (SQLException e) {
throw new CloudRuntimeException("Error while updating "+ hypervisorAndTemplateName.getKey() +" systemVm template", e);
}
}
s_logger.debug("Updating System Vm Template IDs Complete");
} finally {
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException e) {
}
}
}
private void encryptImageStoreDetails(Connection conn) {
s_logger.debug("Encrypting image store details");
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = conn.prepareStatement("select id, value from `cloud`.`image_store_details` where name = 'key' or name = 'secretkey'");
rs = pstmt.executeQuery();
while (rs.next()) {
long id = rs.getLong(1);
String value = rs.getString(2);
if (value == null) {
continue;
}
String encryptedValue = DBEncryptionUtil.encrypt(value);
pstmt = conn.prepareStatement("update `cloud`.`image_store_details` set value=? where id=?");
pstmt.setBytes(1, encryptedValue.getBytes("UTF-8"));
pstmt.setLong(2, id);
pstmt.executeUpdate();
}
} catch (SQLException e) {
throw new CloudRuntimeException("Unable encrypt image_store_details values ", e);
} catch (UnsupportedEncodingException e) {
throw new CloudRuntimeException("Unable encrypt image_store_details values ", e);
} finally {
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException e) {
}
}
s_logger.debug("Done encrypting image_store_details");
}
@Override
public File[] getCleanupScripts() {
String script = Script.findScript("", "db/schema-421to430-cleanup.sql");

View File

@ -19,7 +19,11 @@ package com.cloud.upgrade.dao;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.cloud.network.Network;
import org.apache.log4j.Logger;
import com.cloud.utils.exception.CloudRuntimeException;
@ -55,8 +59,148 @@ public class Upgrade430to440 implements DbUpgrade {
@Override
public void performDataMigration(Connection conn) {
secondaryIpsAccountAndDomainIdsUpdate(conn);
}
private void secondaryIpsAccountAndDomainIdsUpdate(Connection conn) {
PreparedStatement pstmt = null;
PreparedStatement pstmtVm = null;
PreparedStatement pstmtNw = null;
PreparedStatement pstmtUpdate = null;
ResultSet rs1 = null;
ResultSet vmRs = null;
ResultSet networkRs = null;
String secondIpsSql = "SELECT id, vmId, network_id, account_id, domain_id, ip4_address FROM `cloud`.`nic_secondary_ips`";
try {
pstmt = conn.prepareStatement(secondIpsSql);
rs1 = pstmt.executeQuery();
while(rs1.next()) {
long ipId = rs1.getLong(1);
long vmId = rs1.getLong(2);
long networkId = rs1.getLong(3);
long accountId = rs1.getLong(4);
long domainId = rs1.getLong(5);
String ipAddr = rs1.getString(6);
pstmtVm = conn.prepareStatement("SELECT account_id, domain_id FROM `cloud`.`vm_instance` where id = ?");
pstmtVm.setLong(1,vmId);
vmRs = pstmtVm.executeQuery();
if (vmRs.next()) {
long vmAccountId = vmRs.getLong(1);
long vmDomainId = vmRs.getLong(2);
if (vmAccountId != accountId && vmAccountId != domainId) {
// update the secondary ip accountid and domainid to vm accountid domainid
// check the network type. If network is shared accountid doaminid needs to be updated in
// in both nic_secondary_ips table and user_ip_address table
pstmtUpdate = conn.prepareStatement("UPDATE `cloud`.`nic_secondary_ips` SET account_id = ?, domain_id= ? WHERE id = ?");
pstmtUpdate.setLong(1, vmAccountId);
pstmtUpdate.setLong(2,vmDomainId);
pstmtUpdate.setLong(3,ipId);
pstmtUpdate.executeUpdate();
pstmtUpdate.close();
pstmtNw = conn.prepareStatement("SELECT guest_type FROM `cloud`.`networks` where id = ?");
pstmtNw.setLong(1,networkId);
networkRs = pstmtNw.executeQuery();
if (networkRs.next()) {
String guesttype = networkRs.getString(1);
if (guesttype == Network.GuestType.Shared.toString()) {
pstmtUpdate = conn.prepareStatement("UPDATE `cloud`.`user_ip_address` SET account_id = ?, domain_id= ? WHERE public_ip_address = ?");
pstmtUpdate.setLong(1,vmAccountId);
pstmtUpdate.setLong(2,vmDomainId);
pstmtUpdate.setString(3,ipAddr);
pstmtUpdate.executeUpdate();
pstmtUpdate.close();
}
}
networkRs.close();
networkRs = null;
pstmtNw.close();
pstmtNw = null;
}
} //if
pstmtVm.close();
pstmtVm = null;
vmRs.close();
vmRs = null;
} // while
} catch (SQLException e) {
throw new CloudRuntimeException("Exception while Moving private zone information to dedicated resources", e);
} finally {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
}
}
if (rs1 != null) {
try {
rs1.close();
} catch (SQLException e) {
}
}
if (pstmtVm != null) {
try {
pstmtVm.close();
} catch (SQLException e) {
}
}
if (vmRs != null) {
try {
vmRs.close();
} catch (SQLException e) {
}
}
if (pstmtNw != null) {
try {
pstmtNw.close();
} catch (SQLException e) {
}
}
if (networkRs != null) {
try {
networkRs.close();
} catch (SQLException e) {
}
}
}
s_logger.debug("Done updating vm nic secondary ip account and domain ids");
}
@Override
public File[] getCleanupScripts() {
String script = Script.findScript("", "db/schema-430to440-cleanup.sql");

View File

@ -51,4 +51,6 @@ public interface NicSecondaryIpDao extends GenericDao<NicSecondaryIpVO, Long> {
NicSecondaryIpVO findByIp4AddressAndNetworkIdAndInstanceId(long networkId, Long vmId, String vmIp);
List<String> getSecondaryIpAddressesForNic(long nicId);
Long countByNicId(long nicId);
}

View File

@ -35,6 +35,7 @@ import com.cloud.utils.db.SearchCriteria.Op;
public class NicSecondaryIpDaoImpl extends GenericDaoBase<NicSecondaryIpVO, Long> implements NicSecondaryIpDao {
private final SearchBuilder<NicSecondaryIpVO> AllFieldsSearch;
private final GenericSearchBuilder<NicSecondaryIpVO, String> IpSearch;
protected GenericSearchBuilder<NicSecondaryIpVO, Long> CountByNicId;
protected NicSecondaryIpDaoImpl() {
super();
@ -50,6 +51,11 @@ public class NicSecondaryIpDaoImpl extends GenericDaoBase<NicSecondaryIpVO, Long
IpSearch.and("network", IpSearch.entity().getNetworkId(), Op.EQ);
IpSearch.and("address", IpSearch.entity().getIp4Address(), Op.NNULL);
IpSearch.done();
CountByNicId = createSearchBuilder(Long.class);
CountByNicId.select(null, Func.COUNT, null);
CountByNicId.and("nic", CountByNicId.entity().getNicId(), SearchCriteria.Op.EQ);
CountByNicId.done();
}
@Override
@ -135,4 +141,11 @@ public class NicSecondaryIpDaoImpl extends GenericDaoBase<NicSecondaryIpVO, Long
sc.setParameters("address", vmIp);
return findOneBy(sc);
}
@Override
public Long countByNicId(long nicId) {
SearchCriteria<Long> sc = CountByNicId.create();
sc.setParameters("nic", nicId);
return customSearch(sc, null).get(0);
}
}

View File

@ -69,6 +69,8 @@ public interface VMInstanceDao extends GenericDao<VMInstanceVO, Long>, StateDao<
List<VMInstanceVO> findVMInTransition(Date time, State... states);
List<VMInstanceVO> listByHostAndState(long hostId, State... states);
List<VMInstanceVO> listByTypes(VirtualMachine.Type... types);
VMInstanceVO findByIdTypes(long id, VirtualMachine.Type... types);

View File

@ -48,7 +48,11 @@ import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SearchCriteria.Func;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.db.TransactionCallback;
import com.cloud.utils.db.TransactionCallbackNoReturn;
import com.cloud.utils.db.TransactionLegacy;
import com.cloud.utils.db.TransactionStatus;
import com.cloud.utils.db.UpdateBuilder;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.vm.NicVO;
@ -76,6 +80,7 @@ public class VMInstanceDaoImpl extends GenericDaoBase<VMInstanceVO, Long> implem
protected SearchBuilder<VMInstanceVO> TypesSearch;
protected SearchBuilder<VMInstanceVO> IdTypesSearch;
protected SearchBuilder<VMInstanceVO> HostIdTypesSearch;
protected SearchBuilder<VMInstanceVO> HostIdStatesSearch;
protected SearchBuilder<VMInstanceVO> HostIdUpTypesSearch;
protected SearchBuilder<VMInstanceVO> HostUpSearch;
protected SearchBuilder<VMInstanceVO> InstanceNameSearch;
@ -182,6 +187,11 @@ public class VMInstanceDaoImpl extends GenericDaoBase<VMInstanceVO, Long> implem
HostIdTypesSearch.and("types", HostIdTypesSearch.entity().getType(), Op.IN);
HostIdTypesSearch.done();
HostIdStatesSearch = createSearchBuilder();
HostIdStatesSearch.and("hostId", HostIdStatesSearch.entity().getHostId(), Op.EQ);
HostIdStatesSearch.and("states", HostIdStatesSearch.entity().getState(), Op.IN);
HostIdStatesSearch.done();
HostIdUpTypesSearch = createSearchBuilder();
HostIdUpTypesSearch.and("hostid", HostIdUpTypesSearch.entity().getHostId(), Op.EQ);
HostIdUpTypesSearch.and("types", HostIdUpTypesSearch.entity().getType(), Op.IN);
@ -334,6 +344,15 @@ public class VMInstanceDaoImpl extends GenericDaoBase<VMInstanceVO, Long> implem
return listBy(sc);
}
@Override
public List<VMInstanceVO> listByHostAndState(long hostId, State... states) {
SearchCriteria<VMInstanceVO> sc = HostIdStatesSearch.create();
sc.setParameters("hostId", hostId);
sc.setParameters("states", (Object[])states);
return listBy(sc);
}
@Override
public List<VMInstanceVO> listUpByHostIdTypes(long hostid, Type... types) {
SearchCriteria<VMInstanceVO> sc = HostIdUpTypesSearch.create();
@ -702,60 +721,66 @@ public class VMInstanceDaoImpl extends GenericDaoBase<VMInstanceVO, Long> implem
}
@Override
public boolean updatePowerState(long instanceId, long powerHostId, VirtualMachine.PowerState powerState) {
boolean needToUpdate = false;
TransactionLegacy txn = TransactionLegacy.currentTxn();
txn.start();
public boolean updatePowerState(final long instanceId, final long powerHostId, final VirtualMachine.PowerState powerState) {
return Transaction.execute(new TransactionCallback<Boolean>() {
@Override
public Boolean doInTransaction(TransactionStatus status) {
boolean needToUpdate = false;
VMInstanceVO instance = findById(instanceId);
if (instance != null) {
Long savedPowerHostId = instance.getPowerHostId();
if (instance.getPowerState() != powerState || savedPowerHostId == null
|| savedPowerHostId.longValue() != powerHostId) {
instance.setPowerState(powerState);
instance.setPowerHostId(powerHostId);
instance.setPowerStateUpdateCount(1);
instance.setPowerStateUpdateTime(DateUtil.currentGMTTime());
needToUpdate = true;
update(instanceId, instance);
} else {
// to reduce DB updates, consecutive same state update for more than 3 times
if (instance.getPowerStateUpdateCount() < MAX_CONSECUTIVE_SAME_STATE_UPDATE_COUNT) {
instance.setPowerStateUpdateCount(instance.getPowerStateUpdateCount() + 1);
instance.setPowerStateUpdateTime(DateUtil.currentGMTTime());
needToUpdate = true;
update(instanceId, instance);
}
}
}
return needToUpdate;
}
});
}
VMInstanceVO instance = findById(instanceId);
if (instance != null) {
Long savedPowerHostId = instance.getPowerHostId();
if (instance.getPowerState() != powerState || savedPowerHostId == null || savedPowerHostId.longValue() != powerHostId) {
instance.setPowerState(powerState);
instance.setPowerHostId(powerHostId);
instance.setPowerStateUpdateCount(1);
instance.setPowerStateUpdateTime(DateUtil.currentGMTTime());
needToUpdate = true;
update(instanceId, instance);
} else {
// to reduce DB updates, consecutive same state update for more than 3 times
if (instance.getPowerStateUpdateCount() < MAX_CONSECUTIVE_SAME_STATE_UPDATE_COUNT) {
instance.setPowerStateUpdateCount(instance.getPowerStateUpdateCount() + 1);
@Override
public void resetVmPowerStateTracking(final long instanceId) {
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
VMInstanceVO instance = findById(instanceId);
if (instance != null) {
instance.setPowerStateUpdateCount(0);
instance.setPowerStateUpdateTime(DateUtil.currentGMTTime());
needToUpdate = true;
update(instanceId, instance);
}
}
}
txn.commit();
return needToUpdate;
});
}
@Override
public void resetVmPowerStateTracking(long instanceId) {
TransactionLegacy txn = TransactionLegacy.currentTxn();
txn.start();
VMInstanceVO instance = findById(instanceId);
if (instance != null) {
instance.setPowerStateUpdateCount(0);
instance.setPowerStateUpdateTime(DateUtil.currentGMTTime());
update(instanceId, instance);
}
@Override @DB
public void resetHostPowerStateTracking(final long hostId) {
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
SearchCriteria<VMInstanceVO> sc = createSearchCriteria();
sc.addAnd("powerHostId", SearchCriteria.Op.EQ, hostId);
txn.commit();
}
VMInstanceVO instance = createForUpdate();
instance.setPowerStateUpdateCount(0);
instance.setPowerStateUpdateTime(DateUtil.currentGMTTime());
@Override
@DB
public void resetHostPowerStateTracking(long hostId) {
SearchCriteria<VMInstanceVO> sc = createSearchCriteria();
sc.addAnd("powerHostId", SearchCriteria.Op.EQ, hostId);
VMInstanceVO instance = this.createForUpdate();
instance.setPowerStateUpdateCount(0);
instance.setPowerStateUpdateTime(DateUtil.currentGMTTime());
this.update(instance, sc);
update(instance, sc);
}
});
}
}

View File

@ -75,6 +75,7 @@ import com.cloud.dc.dao.DataCenterDao;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.storage.DataStoreRole;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.Storage.TemplateType;
import com.cloud.storage.StoragePool;
import com.cloud.storage.VMTemplateStorageResourceAssoc;
@ -721,6 +722,13 @@ public class TemplateServiceImpl implements TemplateService {
@Override
public AsyncCallFuture<TemplateApiResult> copyTemplate(TemplateInfo srcTemplate, DataStore destStore) {
// for vmware template, we need to check if ova packing is needed, since template created from snapshot does not have .ova file
// we invoke createEntityExtractURL to trigger ova packing. Ideally, we can directly use extractURL to pass to following createTemplate.
// Need to understand what is the background to use two different urls for copy and extract.
if (srcTemplate.getFormat() == ImageFormat.OVA){
ImageStoreEntity tmpltStore = (ImageStoreEntity)srcTemplate.getDataStore();
tmpltStore.createEntityExtractUrl(srcTemplate.getInstallPath(), srcTemplate.getFormat(), srcTemplate);
}
// generate a URL from source template ssvm to download to destination data store
String url = generateCopyUrl(srcTemplate);
if (url == null) {

View File

@ -119,8 +119,6 @@
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<!-- TODO: Is this version override required -->
<version>4.2.2</version>
<scope>compile</scope>
</dependency>
<dependency>

View File

@ -26,6 +26,7 @@ import javax.inject.Inject;
import org.springframework.stereotype.Component;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
import org.apache.cloudstack.storage.datastore.db.ImageStoreDao;
import org.apache.cloudstack.storage.datastore.db.ImageStoreDetailVO;
@ -35,6 +36,7 @@ import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao;
import com.cloud.storage.DataStoreRole;
import com.cloud.storage.ScopeType;
import com.cloud.utils.crypt.DBEncryptionUtil;
import com.cloud.utils.exception.CloudRuntimeException;
@Component
@ -104,7 +106,12 @@ public class ImageStoreHelper {
ImageStoreDetailVO detail = new ImageStoreDetailVO();
detail.setStoreId(store.getId());
detail.setName(key);
detail.setValue(details.get(key));
String value = details.get(key);
// encrypt swift key or s3 secret key
if (key.equals(ApiConstants.KEY) || key.equals(ApiConstants.S3_SECRET_KEY)) {
value = DBEncryptionUtil.encrypt(value);
}
detail.setValue(value);
imageStoreDetailsDao.persist(detail);
}
}

View File

@ -24,9 +24,11 @@ import javax.ejb.Local;
import org.springframework.stereotype.Component;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.storage.datastore.db.ImageStoreDetailVO;
import org.apache.cloudstack.storage.datastore.db.ImageStoreDetailsDao;
import com.cloud.utils.crypt.DBEncryptionUtil;
import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
@ -68,7 +70,12 @@ public class ImageStoreDetailsDaoImpl extends GenericDaoBase<ImageStoreDetailVO,
List<ImageStoreDetailVO> details = listBy(sc);
Map<String, String> detailsMap = new HashMap<String, String>();
for (ImageStoreDetailVO detail : details) {
detailsMap.put(detail.getName(), detail.getValue());
String name = detail.getName();
String value = detail.getValue();
if (name.equals(ApiConstants.KEY) || name.equals(ApiConstants.S3_SECRET_KEY)) {
value = DBEncryptionUtil.decrypt(value);
}
detailsMap.put(name, value);
}
return detailsMap;

View File

@ -158,8 +158,9 @@ public class VolumeServiceImpl implements VolumeService {
return null;
}
@Override
public boolean connectVolumeToHost(VolumeInfo volumeInfo, Host host, DataStore dataStore) {
DataStoreDriver dataStoreDriver = dataStore.getDriver();
DataStoreDriver dataStoreDriver = dataStore != null ? dataStore.getDriver() : null;
if (dataStoreDriver instanceof PrimaryDataStoreDriver) {
return ((PrimaryDataStoreDriver)dataStoreDriver).connectVolumeToHost(volumeInfo, host, dataStore);
@ -168,8 +169,9 @@ public class VolumeServiceImpl implements VolumeService {
return false;
}
@Override
public void disconnectVolumeFromHost(VolumeInfo volumeInfo, Host host, DataStore dataStore) {
DataStoreDriver dataStoreDriver = dataStore.getDriver();
DataStoreDriver dataStoreDriver = dataStore != null ? dataStore.getDriver() : null;
if (dataStoreDriver instanceof PrimaryDataStoreDriver) {
((PrimaryDataStoreDriver)dataStoreDriver).disconnectVolumeFromHost(volumeInfo, host, dataStore);

View File

@ -26,7 +26,6 @@ public interface ClusterManager extends Manager {
"Interval to check for the heart beat between management server nodes", false);
final ConfigKey<Integer> HeartbeatThreshold = new ConfigKey<Integer>(Integer.class, "cluster.heartbeat.threshold", "management-server", "150000",
"Threshold before self-fence the management server", true);
final ConfigKey<String> ManagementHostIPAdr = new ConfigKey<String>("Advanced", String.class, "host", "localhost", "The ip address of management server", true);
void OnReceiveClusterServicePdu(ClusterServicePdu pdu);

View File

@ -1099,7 +1099,7 @@ public class ClusterManagerImpl extends ManagerBase implements ClusterManager, C
@Override
public ConfigKey<?>[] getConfigKeys() {
return new ConfigKey<?>[] {HeartbeatInterval, HeartbeatThreshold, ManagementHostIPAdr};
return new ConfigKey<?>[] {HeartbeatInterval, HeartbeatThreshold};
}
private boolean pingManagementNode(ManagementServerHostVO mshost) {

View File

@ -27,4 +27,8 @@ public interface ConfigDepot {
ConfigKey<?> get(String paramName);
Set<ConfigKey<?>> getConfigListByScope(String scope);
<T> void set(ConfigKey<T> key, T value);
<T> void createOrUpdateConfigObject(String componentName, ConfigKey<T> key, String value);
}

View File

@ -27,15 +27,14 @@ import java.util.Set;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import org.apache.commons.lang.ObjectUtils;
import org.apache.log4j.Logger;
import org.apache.cloudstack.framework.config.ConfigDepot;
import org.apache.cloudstack.framework.config.ConfigDepotAdmin;
import org.apache.cloudstack.framework.config.ConfigKey;
import org.apache.cloudstack.framework.config.Configurable;
import org.apache.cloudstack.framework.config.ScopedConfigStorage;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.commons.lang.ObjectUtils;
import org.apache.log4j.Logger;
import com.cloud.utils.Pair;
import com.cloud.utils.exception.CloudRuntimeException;
@ -116,23 +115,8 @@ public class ConfigDepotImpl implements ConfigDepot, ConfigDepotAdmin {
}
_allKeys.put(key.key(), new Pair<String, ConfigKey<?>>(configurable.getConfigComponentName(), key));
ConfigurationVO vo = _configDao.findById(key.key());
if (vo == null) {
vo = new ConfigurationVO(configurable.getConfigComponentName(), key);
vo.setUpdated(date);
_configDao.persist(vo);
} else {
if (vo.isDynamic() != key.isDynamic() || !ObjectUtils.equals(vo.getDescription(), key.description()) ||
!ObjectUtils.equals(vo.getDefaultValue(), key.defaultValue()) ||
!ObjectUtils.equals(vo.getScope(), key.scope().toString())) {
vo.setDynamic(key.isDynamic());
vo.setDescription(key.description());
vo.setDefaultValue(key.defaultValue());
vo.setScope(key.scope().toString());
vo.setUpdated(date);
_configDao.persist(vo);
}
}
createOrupdateConfigObject(date, configurable.getConfigComponentName(), key, null);
if ((key.scope() != null) && (key.scope() != ConfigKey.Scope.Global)) {
Set<ConfigKey<?>> currentConfigs = _scopeLevelConfigsMap.get(key.scope());
currentConfigs.add(key);
@ -142,6 +126,28 @@ public class ConfigDepotImpl implements ConfigDepot, ConfigDepotAdmin {
_configured.add(configurable);
}
private void createOrupdateConfigObject(Date date, String componentName, ConfigKey<?> key, String value) {
ConfigurationVO vo = _configDao.findById(key.key());
if (vo == null) {
vo = new ConfigurationVO(componentName, key);
vo.setUpdated(date);
if (value != null) {
vo.setValue(value);
}
_configDao.persist(vo);
} else {
if (vo.isDynamic() != key.isDynamic() || !ObjectUtils.equals(vo.getDescription(), key.description()) || !ObjectUtils.equals(vo.getDefaultValue(), key.defaultValue())
|| !ObjectUtils.equals(vo.getScope(), key.scope().toString())) {
vo.setDynamic(key.isDynamic());
vo.setDescription(key.description());
vo.setDefaultValue(key.defaultValue());
vo.setScope(key.scope().toString());
vo.setUpdated(date);
_configDao.persist(vo);
}
}
}
@Override
public void populateConfiguration(Configurable configurable) {
populateConfiguration(new Date(), configurable);
@ -172,7 +178,7 @@ public class ConfigDepotImpl implements ConfigDepot, ConfigDepotAdmin {
@Inject
public void setScopedStorages(List<ScopedConfigStorage> scopedStorages) {
this._scopedStorages = scopedStorages;
_scopedStorages = scopedStorages;
}
public List<Configurable> getConfigurables() {
@ -181,7 +187,7 @@ public class ConfigDepotImpl implements ConfigDepot, ConfigDepotAdmin {
@Inject
public void setConfigurables(List<Configurable> configurables) {
this._configurables = configurables;
_configurables = configurables;
}
@Override
@ -189,4 +195,14 @@ public class ConfigDepotImpl implements ConfigDepot, ConfigDepotAdmin {
return _scopeLevelConfigsMap.get(ConfigKey.Scope.valueOf(scope));
}
@Override
public <T> void set(ConfigKey<T> key, T value) {
_configDao.update(key.key(), value.toString());
}
@Override
public <T> void createOrUpdateConfigObject(String componentName, ConfigKey<T> key, String value) {
createOrupdateConfigObject(new Date(), componentName, key, value);
}
}

View File

@ -658,9 +658,21 @@ public abstract class GenericDaoBase<T, ID extends Serializable> extends Compone
}
}
/**
* Get a value from a result set.
*
* @param type
* the expected type of the result
* @param rs
* the result set
* @param index
* the index of the column
* @return the result in the requested type
* @throws SQLException
*/
@DB()
@SuppressWarnings("unchecked")
protected <M> M getObject(Class<M> type, ResultSet rs, int index) throws SQLException {
protected static <M> M getObject(Class<M> type, ResultSet rs, int index) throws SQLException {
if (type == String.class) {
byte[] bytes = rs.getBytes(index);
if (bytes != null) {
@ -681,12 +693,12 @@ public abstract class GenericDaoBase<T, ID extends Serializable> extends Compone
return (M)new Integer(rs.getInt(index));
}
} else if (type == long.class) {
return (M)new Long(rs.getLong(index));
return (M) (Long) rs.getLong(index);
} else if (type == Long.class) {
if (rs.getObject(index) == null) {
return null;
} else {
return (M)new Long(rs.getLong(index));
return (M) (Long) rs.getLong(index);
}
} else if (type == Date.class) {
final Object data = rs.getDate(index);
@ -696,44 +708,44 @@ public abstract class GenericDaoBase<T, ID extends Serializable> extends Compone
return (M)DateUtil.parseDateString(s_gmtTimeZone, rs.getString(index));
}
} else if (type == short.class) {
return (M)new Short(rs.getShort(index));
return (M) (Short) rs.getShort(index);
} else if (type == Short.class) {
if (rs.getObject(index) == null) {
return null;
} else {
return (M)new Short(rs.getShort(index));
return (M) (Short) rs.getShort(index);
}
} else if (type == boolean.class) {
return (M)new Boolean(rs.getBoolean(index));
return (M) (Boolean) rs.getBoolean(index);
} else if (type == Boolean.class) {
if (rs.getObject(index) == null) {
return null;
} else {
return (M)new Boolean(rs.getBoolean(index));
return (M) (Boolean) rs.getBoolean(index);
}
} else if (type == float.class) {
return (M)new Float(rs.getFloat(index));
return (M) (Float) rs.getFloat(index);
} else if (type == Float.class) {
if (rs.getObject(index) == null) {
return null;
} else {
return (M)new Float(rs.getFloat(index));
return (M) (Float) rs.getFloat(index);
}
} else if (type == double.class) {
return (M)new Double(rs.getDouble(index));
return (M) (Double) rs.getDouble(index);
} else if (type == Double.class) {
if (rs.getObject(index) == null) {
return null;
} else {
return (M)new Double(rs.getDouble(index));
return (M) (Double) rs.getDouble(index);
}
} else if (type == byte.class) {
return (M)new Byte(rs.getByte(index));
return (M) (Byte) rs.getByte(index);
} else if (type == Byte.class) {
if (rs.getObject(index) == null) {
return null;
} else {
return (M)new Byte(rs.getByte(index));
return (M) (Byte) rs.getByte(index);
}
} else if (type == Calendar.class) {
final Object data = rs.getDate(index);

View File

@ -0,0 +1,134 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.utils.db;
import java.sql.ResultSet;
import java.sql.SQLException;
import junit.framework.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class GenericDaoBaseTest {
@Mock
ResultSet resultSet;
@Test
public void getObjectBoolean() throws SQLException {
Mockito.when(resultSet.getObject(1)).thenReturn(false);
Mockito.when(resultSet.getBoolean(1)).thenReturn(false);
Assert.assertFalse(GenericDaoBase
.getObject(Boolean.class, resultSet, 1));
Mockito.verify(resultSet).getBoolean(1);
}
@Test
public void getObjectPrimitiveBoolean() throws SQLException {
Mockito.when(resultSet.getObject(1)).thenReturn(false);
Mockito.when(resultSet.getBoolean(1)).thenReturn(false);
Assert.assertFalse(GenericDaoBase
.getObject(boolean.class, resultSet, 1));
Mockito.verify(resultSet).getBoolean(1);
}
@Test
public void getObjectPrimitiveShort() throws SQLException {
Mockito.when(resultSet.getObject(1)).thenReturn((short) 1);
Mockito.when(resultSet.getShort(1)).thenReturn((short) 1);
Assert.assertEquals(Short.valueOf((short) 1),
GenericDaoBase.getObject(short.class, resultSet, 1));
Mockito.verify(resultSet).getShort(1);
}
@Test
public void getObjectShort() throws SQLException {
Mockito.when(resultSet.getObject(1)).thenReturn((short) 1);
Mockito.when(resultSet.getShort(1)).thenReturn((short) 1);
Assert.assertEquals(Short.valueOf((short) 1),
GenericDaoBase.getObject(Short.class, resultSet, 1));
Mockito.verify(resultSet).getShort(1);
}
@Test
public void getObjectFloat() throws SQLException {
Mockito.when(resultSet.getObject(1)).thenReturn(0.1f);
Mockito.when(resultSet.getFloat(1)).thenReturn(0.1f);
Assert.assertEquals(0.1f,
GenericDaoBase.getObject(Float.class, resultSet, 1));
Mockito.verify(resultSet).getFloat(1);
}
@Test
public void getObjectPrimitiveFloat() throws SQLException {
Mockito.when(resultSet.getObject(1)).thenReturn(0.1f);
Mockito.when(resultSet.getFloat(1)).thenReturn(0.1f);
Assert.assertEquals(0.1f,
GenericDaoBase.getObject(float.class, resultSet, 1));
Mockito.verify(resultSet).getFloat(1);
}
@Test
public void getObjectPrimitiveDouble() throws SQLException {
Mockito.when(resultSet.getObject(1)).thenReturn(0.1d);
Mockito.when(resultSet.getDouble(1)).thenReturn(0.1d);
Assert.assertEquals(0.1d,
GenericDaoBase.getObject(double.class, resultSet, 1));
Mockito.verify(resultSet).getDouble(1);
}
@Test
public void getObjectDouble() throws SQLException {
Mockito.when(resultSet.getObject(1)).thenReturn(0.1d);
Mockito.when(resultSet.getDouble(1)).thenReturn(0.1d);
Assert.assertEquals(0.1d,
GenericDaoBase.getObject(Double.class, resultSet, 1));
Mockito.verify(resultSet).getDouble(1);
}
@Test
public void getObjectLong() throws SQLException {
Mockito.when(resultSet.getObject(1)).thenReturn(1l);
Mockito.when(resultSet.getLong(1)).thenReturn(1l);
Assert.assertEquals((Long) 1l,
GenericDaoBase.getObject(Long.class, resultSet, 1));
Mockito.verify(resultSet).getLong(1);
}
@Test
public void getObjectPrimitiveLong() throws SQLException {
Mockito.when(resultSet.getObject(1)).thenReturn(1l);
Mockito.when(resultSet.getLong(1)).thenReturn(1l);
Assert.assertEquals((Long) 1l,
GenericDaoBase.getObject(long.class, resultSet, 1));
Mockito.verify(resultSet).getLong(1);
}
@Test
public void getObjectPrimitiveByte() throws SQLException {
Mockito.when(resultSet.getObject(1)).thenReturn((byte) 1);
Mockito.when(resultSet.getByte(1)).thenReturn((byte) 1);
Assert.assertTrue((byte) 1 == GenericDaoBase.getObject(byte.class,
resultSet, 1));
Mockito.verify(resultSet).getByte(1);
}
}

View File

@ -20,17 +20,24 @@ package org.apache.cloudstack.framework.messagebus;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
public class MessageDispatcher implements MessageSubscriber {
private static Map<Class<?>, Method> s_handlerCache = new HashMap<Class<?>, Method>();
private static final Logger s_logger = Logger.getLogger(MessageDispatcher.class);
private static Map<Class<?>, List<Method>> s_handlerCache = new HashMap<Class<?>, List<Method>>();
private static Map<Object, MessageDispatcher> s_targetMap = new HashMap<Object, MessageDispatcher>();
private Object _targetObject;
public MessageDispatcher(Object targetObject) {
_targetObject = targetObject;
buildHandlerMethodCache(targetObject.getClass());
}
@Override
@ -67,10 +74,13 @@ public class MessageDispatcher implements MessageSubscriber {
try {
handler.invoke(target, subject, senderAddress, args);
} catch (IllegalArgumentException e) {
s_logger.error("Unexpected exception when calling " + target.getClass().getName() + "." + handler.getName(), e);
throw new RuntimeException("IllegalArgumentException when invoking event handler for subject: " + subject);
} catch (IllegalAccessException e) {
s_logger.error("Unexpected exception when calling " + target.getClass().getName() + "." + handler.getName(), e);
throw new RuntimeException("IllegalAccessException when invoking event handler for subject: " + subject);
} catch (InvocationTargetException e) {
s_logger.error("Unexpected exception when calling " + target.getClass().getName() + "." + handler.getName(), e);
throw new RuntimeException("InvocationTargetException when invoking event handler for subject: " + subject);
}
@ -79,18 +89,18 @@ public class MessageDispatcher implements MessageSubscriber {
public static Method resolveHandler(Class<?> handlerClz, String subject) {
synchronized (s_handlerCache) {
Method handler = s_handlerCache.get(handlerClz);
if (handler != null)
return handler;
List<Method> handlerList = s_handlerCache.get(handlerClz);
if (handlerList != null) {
for (Method method : handlerList) {
MessageHandler annotation = method.getAnnotation(MessageHandler.class);
assert (annotation != null);
for (Method method : handlerClz.getMethods()) {
MessageHandler annotation = method.getAnnotation(MessageHandler.class);
if (annotation != null) {
if (match(annotation.topic(), subject)) {
s_handlerCache.put(handlerClz, method);
return method;
}
}
} else {
s_logger.error("Handler class " + handlerClz.getName() + " is not registered");
}
}
@ -100,4 +110,40 @@ public class MessageDispatcher implements MessageSubscriber {
private static boolean match(String expression, String param) {
return param.matches(expression);
}
private void buildHandlerMethodCache(Class<?> handlerClz) {
if (s_logger.isInfoEnabled())
s_logger.info("Build message handler cache for " + handlerClz.getName());
synchronized (s_handlerCache) {
List<Method> handlerList = s_handlerCache.get(handlerClz);
if (handlerList == null) {
handlerList = new ArrayList<Method>();
s_handlerCache.put(handlerClz, handlerList);
Class<?> clz = handlerClz;
while (clz != null && clz != Object.class) {
for (Method method : clz.getDeclaredMethods()) {
MessageHandler annotation = method.getAnnotation(MessageHandler.class);
if (annotation != null) {
// allow private member access via reflection
method.setAccessible(true);
handlerList.add(method);
if (s_logger.isInfoEnabled())
s_logger.info("Add message handler " + handlerClz.getName() + "." + method.getName() + " to cache");
}
}
clz = clz.getSuperclass();
}
} else {
if (s_logger.isInfoEnabled())
s_logger.info("Message handler for class " + handlerClz.getName() + " is already in cache");
}
}
if (s_logger.isInfoEnabled())
s_logger.info("Done building message handler cache for " + handlerClz.getName());
}
}

View File

@ -30,7 +30,9 @@ import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.ResourceUnavailableException;
public class AsyncJobExecutionContext {
public class AsyncJobExecutionContext {
private static final Logger s_logger = Logger.getLogger(AsyncJobExecutionContext.class);
private AsyncJob _job;
static private AsyncJobManager s_jobMgr;
@ -112,7 +114,8 @@ public class AsyncJobExecutionContext {
}
//
// check failure exception before we disjoin the worker job
// check failure exception before we disjoin the worker job, work job usually fails with exception
// this will help propogate exception between jobs
// TODO : it is ugly and this will become unnecessary after we switch to full-async mode
//
public void disjoinJob(long joinedJobId) throws InsufficientCapacityException,
@ -120,21 +123,34 @@ public class AsyncJobExecutionContext {
assert (_job != null);
AsyncJobJoinMapVO record = s_joinMapDao.getJoinRecord(_job.getId(), joinedJobId);
if (record.getJoinStatus() == JobInfo.Status.FAILED && record.getJoinResult() != null) {
Object exception = JobSerializerHelper.fromObjectSerializedString(record.getJoinResult());
if (exception != null && exception instanceof Exception) {
if (exception instanceof InsufficientCapacityException)
throw (InsufficientCapacityException)exception;
else if (exception instanceof ConcurrentOperationException)
throw (ConcurrentOperationException)exception;
else if (exception instanceof ResourceUnavailableException)
throw (ResourceUnavailableException)exception;
else
throw new RuntimeException((Exception)exception);
s_jobMgr.disjoinJob(_job.getId(), joinedJobId);
if (record.getJoinStatus() == JobInfo.Status.FAILED) {
if (record.getJoinResult() != null) {
Object exception = JobSerializerHelper.fromObjectSerializedString(record.getJoinResult());
if (exception != null && exception instanceof Exception) {
if (exception instanceof InsufficientCapacityException) {
s_logger.error("Job " + joinedJobId + " failed with InsufficientCapacityException");
throw (InsufficientCapacityException)exception;
}
else if (exception instanceof ConcurrentOperationException) {
s_logger.error("Job " + joinedJobId + " failed with ConcurrentOperationException");
throw (ConcurrentOperationException)exception;
}
else if (exception instanceof ResourceUnavailableException) {
s_logger.error("Job " + joinedJobId + " failed with ResourceUnavailableException");
throw (ResourceUnavailableException)exception;
}
else {
s_logger.error("Job " + joinedJobId + " failed with exception");
throw new RuntimeException((Exception)exception);
}
}
} else {
s_logger.error("Job " + joinedJobId + " failed without providing an error object");
throw new RuntimeException("Job " + joinedJobId + " failed without providing an error object");
}
}
s_jobMgr.disjoinJob(_job.getId(), joinedJobId);
}
public void completeJoin(JobInfo.Status joinStatus, String joinResult) {
@ -151,6 +167,8 @@ public class AsyncJobExecutionContext {
public static AsyncJobExecutionContext getCurrentExecutionContext() {
AsyncJobExecutionContext context = s_currentExectionContext.get();
if (context == null) {
// TODO, this has security implicitions
s_logger.warn("Job is executed without a context, setup psudo job for the executing thread");
context = registerPseudoExecutionContext(CallContext.current().getCallingAccountId(),
CallContext.current().getCallingUserId());
}

View File

@ -35,4 +35,6 @@ public interface VmWorkJobDao extends GenericDao<VmWorkJobVO, Long> {
void updateStep(long workJobId, Step step);
void expungeCompletedWorkJobs(Date cutDate);
void expungeLeftoverWorkJobs(long msid);
}

View File

@ -16,8 +16,11 @@
// under the License.
package org.apache.cloudstack.framework.jobs.dao;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import javax.annotation.PostConstruct;
@ -31,13 +34,16 @@ import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.db.TransactionCallbackNoReturn;
import com.cloud.utils.db.TransactionLegacy;
import com.cloud.utils.db.TransactionStatus;
import com.cloud.vm.VirtualMachine;
public class VmWorkJobDaoImpl extends GenericDaoBase<VmWorkJobVO, Long> implements VmWorkJobDao {
protected SearchBuilder<VmWorkJobVO> PendingWorkJobSearch;
protected SearchBuilder<VmWorkJobVO> PendingWorkJobByCommandSearch;
protected SearchBuilder<VmWorkJobVO> ExpungeWorkJobSearch;
public VmWorkJobDaoImpl() {
}
@ -48,7 +54,6 @@ public class VmWorkJobDaoImpl extends GenericDaoBase<VmWorkJobVO, Long> implemen
PendingWorkJobSearch.and("jobStatus", PendingWorkJobSearch.entity().getStatus(), Op.EQ);
PendingWorkJobSearch.and("vmType", PendingWorkJobSearch.entity().getVmType(), Op.EQ);
PendingWorkJobSearch.and("vmInstanceId", PendingWorkJobSearch.entity().getVmInstanceId(), Op.EQ);
PendingWorkJobSearch.and("step", PendingWorkJobSearch.entity().getStep(), Op.NEQ);
PendingWorkJobSearch.done();
PendingWorkJobByCommandSearch = createSearchBuilder();
@ -58,11 +63,6 @@ public class VmWorkJobDaoImpl extends GenericDaoBase<VmWorkJobVO, Long> implemen
PendingWorkJobByCommandSearch.and("step", PendingWorkJobByCommandSearch.entity().getStep(), Op.NEQ);
PendingWorkJobByCommandSearch.and("cmd", PendingWorkJobByCommandSearch.entity().getCmd(), Op.EQ);
PendingWorkJobByCommandSearch.done();
ExpungeWorkJobSearch = createSearchBuilder();
ExpungeWorkJobSearch.and("lastUpdated", ExpungeWorkJobSearch.entity().getLastUpdated(), Op.LT);
ExpungeWorkJobSearch.and("jobStatus", ExpungeWorkJobSearch.entity().getStatus(), Op.NEQ);
ExpungeWorkJobSearch.done();
}
@Override
@ -115,11 +115,80 @@ public class VmWorkJobDaoImpl extends GenericDaoBase<VmWorkJobVO, Long> implemen
}
@Override
public void expungeCompletedWorkJobs(Date cutDate) {
SearchCriteria<VmWorkJobVO> sc = ExpungeWorkJobSearch.create();
sc.setParameters("lastUpdated", cutDate);
sc.setParameters("jobStatus", JobInfo.Status.IN_PROGRESS);
public void expungeCompletedWorkJobs(final Date cutDate) {
// current DAO machenism does not support following usage
/*
SearchCriteria<VmWorkJobVO> sc = ExpungeWorkJobSearch.create();
sc.setParameters("lastUpdated",cutDate);
sc.setParameters("jobStatus", JobInfo.Status.IN_PROGRESS);
expunge(sc);
expunge(sc);
*/
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
TransactionLegacy txn = TransactionLegacy.currentTxn();
PreparedStatement pstmt = null;
try {
pstmt = txn.prepareAutoCloseStatement(
"DELETE FROM vm_work_job WHERE id IN (SELECT id FROM async_job WHERE job_dispatcher='VmWorkJobDispatcher' AND job_status != 0 AND last_updated < ?)");
pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
pstmt.execute();
} catch (SQLException e) {
} catch (Throwable e) {
}
try {
pstmt = txn.prepareAutoCloseStatement(
"DELETE FROM async_job WHERE job_dispatcher='VmWorkJobDispatcher' AND job_status != 0 AND last_updated < ?");
pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
pstmt.execute();
} catch (SQLException e) {
} catch (Throwable e) {
}
}
});
}
@Override
public void expungeLeftoverWorkJobs(final long msid) {
// current DAO machenism does not support following usage
/*
SearchCriteria<VmWorkJobVO> sc = ExpungePlaceHolderWorkJobSearch.create();
sc.setParameters("dispatcher", "VmWorkJobPlaceHolder");
sc.setParameters("msid", msid);
expunge(sc);
*/
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
TransactionLegacy txn = TransactionLegacy.currentTxn();
PreparedStatement pstmt = null;
try {
pstmt = txn.prepareAutoCloseStatement(
"DELETE FROM vm_work_job WHERE id IN (SELECT id FROM async_job WHERE (job_dispatcher='VmWorkJobPlaceHolder' OR job_dispatcher='VmWorkJobDispatcher') AND job_init_msid=?)");
pstmt.setLong(1, msid);
pstmt.execute();
} catch (SQLException e) {
} catch (Throwable e) {
}
try {
pstmt = txn.prepareAutoCloseStatement(
"DELETE FROM async_job WHERE (job_dispatcher='VmWorkJobPlaceHolder' OR job_dispatcher='VmWorkJobDispatcher') AND job_init_msid=?");
pstmt.setLong(1, msid);
pstmt.execute();
} catch (SQLException e) {
} catch (Throwable e) {
}
}
});
}
}

View File

@ -475,7 +475,9 @@ public class AsyncJobManagerImpl extends ManagerBase implements AsyncJobManager,
if (jobDispatcher != null) {
jobDispatcher.runJob(job);
} else {
s_logger.error("Unable to find a wakeup dispatcher from the joined job: " + job);
// TODO, job wakeup is not in use yet
if (s_logger.isTraceEnabled())
s_logger.trace("Unable to find a wakeup dispatcher from the joined job: " + job);
}
} else {
AsyncJobDispatcher jobDispatcher = getDispatcher(job.getDispatcher());

View File

@ -25,7 +25,7 @@
<artifactId>cloudstack-framework</artifactId>
<version>4.4.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.cloudstack</groupId>
@ -42,6 +42,10 @@
<artifactId>cloud-framework-ipc</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>org.apache.cloudstack</groupId>
<artifactId>cloud-framework-db</artifactId>
@ -51,6 +55,6 @@
<groupId>org.apache.cloudstack</groupId>
<artifactId>cloud-framework-config</artifactId>
<version>${project.version}</version>
</dependency>
</dependency>
</dependencies>
</project>

View File

@ -28,4 +28,5 @@
>
<bean id="keystoreManagerImpl" class="org.apache.cloudstack.framework.security.keystore.KeystoreManagerImpl" />
<bean id="keystoreDaoImpl" class="org.apache.cloudstack.framework.security.keystore.KeystoreDaoImpl" />
<bean id="keysManagerImpl" class="org.apache.cloudstack.framework.security.keys.KeysManagerImpl"/>
</beans>

View File

@ -0,0 +1,38 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.framework.security.keys;
import org.apache.cloudstack.framework.config.ConfigKey;
/**
*
* Started this file to manage keys. Will be needed by other services.
*
*/
public interface KeysManager {
final ConfigKey<String> EncryptionKey = new ConfigKey<String>("Hidden", String.class, "security.encryption.key", null, "base64 encoded key data", false);
final ConfigKey<String> EncryptionIV = new ConfigKey<String>("Hidden", String.class, "security.encryption.iv", null, "base64 encoded IV data", false);
final ConfigKey<String> HashKey = new ConfigKey<String>("Hidden", String.class, "security.hash.key", null, "for generic key-ed hash", false);
String getEncryptionKey();
String getEncryptionIV();
void resetEncryptionKeyIV();
String getHashKey();
}

View File

@ -0,0 +1,127 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.framework.security.keys;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.inject.Inject;
import javax.net.ssl.KeyManager;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.apache.cloudstack.framework.config.ConfigDepot;
import org.apache.cloudstack.framework.config.ConfigKey;
import org.apache.cloudstack.framework.config.Configurable;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.cloudstack.framework.config.impl.ConfigurationVO;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
/**
* To be perfectly honest, I'm not sure why we need this class. This used
* to be in ManagementServerImpl. I moved the functionality because it seems
* many features will need this. However, the right thing will be for setup
* and upgrade to take care of key generation. Here, the methods appear to
* mainly be used for dynamic generation. I added this class because after
* talking to Kelven, we think there will be other functionalities we need
* to centralize to this class. We'll see how that works out.
*
* There's multiple problems here that we need to fix.
* - Multiple servers can be generating keys. This is not atomic.
* - The functionality of generating the keys should be moved over to setup/upgrade.
*
*/
public class KeysManagerImpl implements KeysManager, Configurable {
private static final Logger s_logger = Logger.getLogger(KeysManagerImpl.class);
@Inject
ConfigurationDao _configDao;
@Inject
ConfigDepot _configDepot;
@Override
public String getHashKey() {
String value = HashKey.value();
if (value == null) {
_configDepot.set(HashKey, getBase64EncodedRandomKey(128));
}
return HashKey.value();
}
@Override
public String getEncryptionKey() {
String value = EncryptionKey.value();
if (value == null) {
_configDepot.set(EncryptionKey, getBase64EncodedRandomKey(128));
}
return EncryptionKey.value();
}
@Override
public String getEncryptionIV() {
String value = EncryptionIV.value();
if (value == null) {
_configDepot.set(EncryptionIV, getBase64EncodedRandomKey(128));
}
return EncryptionIV.value();
}
private static String getBase64EncodedRandomKey(int nBits) {
SecureRandom random;
try {
random = SecureRandom.getInstance("SHA1PRNG");
byte[] keyBytes = new byte[nBits / 8];
random.nextBytes(keyBytes);
return Base64.encodeBase64URLSafeString(keyBytes);
} catch (NoSuchAlgorithmException e) {
s_logger.error("Unhandled exception: ", e);
}
return null;
}
@Override
@DB
public void resetEncryptionKeyIV() {
SearchBuilder<ConfigurationVO> sb = _configDao.createSearchBuilder();
sb.and("name1", sb.entity().getName(), SearchCriteria.Op.EQ);
sb.or("name2", sb.entity().getName(), SearchCriteria.Op.EQ);
sb.done();
SearchCriteria<ConfigurationVO> sc = sb.create();
sc.setParameters("name1", EncryptionKey.key());
sc.setParameters("name2", EncryptionIV.key());
_configDao.expunge(sc);
}
@Override
public String getConfigComponentName() {
return KeyManager.class.getSimpleName();
}
@Override
public ConfigKey<?>[] getConfigKeys() {
return new ConfigKey<?>[] {EncryptionKey, EncryptionIV, HashKey};
}
}

View File

@ -20,6 +20,7 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>cloud-framework-spring-module</artifactId>
<name>Apache CloudStack Framework - Spring Module</name>
<parent>
<groupId>org.apache.cloudstack</groupId>
<artifactId>cloud-maven-standard</artifactId>

View File

@ -43,7 +43,7 @@ Group: System Environment/Libraries
Source0: %{name}-%{_maventag}.tgz
BuildRoot: %{_tmppath}/%{name}-%{_maventag}-%{release}-build
BuildRequires: java-1.6.0-openjdk-devel
BuildRequires: java-1.7.0-openjdk-devel
BuildRequires: tomcat6
BuildRequires: ws-commons-util
BuildRequires: jpackage-utils
@ -60,7 +60,7 @@ intelligent IaaS cloud implementation.
%package management
Summary: CloudStack management server UI
Requires: tomcat6
Requires: java >= 1.6.0
Requires: java >= 1.7.0
Requires: python
Requires: bash
Requires: bzip2
@ -111,7 +111,8 @@ The Apache CloudStack files shared between agent and management server
%package agent
Summary: CloudStack Agent for KVM hypervisors
Requires: java >= 1.6.0
Requires: openssh-clients
Requires: java >= 1.7.0
Requires: %{name}-common = %{_ver}
Requires: libvirt
Requires: bridge-utils
@ -137,7 +138,7 @@ The CloudStack agent for KVM hypervisors
%package usage
Summary: CloudStack Usage calculation server
Requires: java >= 1.6.0
Requires: java >= 1.7.0
Requires: jsvc
Requires: jakarta-commons-daemon
Requires: jakarta-commons-daemon-jsvc

View File

@ -45,7 +45,7 @@ namespace CloudStack.Plugin.AgentShell
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.ServiceName = "CloudStack ServerResource";
this.ServiceName = Program.serviceName;
}
#endregion

View File

@ -47,7 +47,7 @@ namespace CloudStack.Plugin.AgentShell
logger.Info("Starting CloudStack agent");
InitializeComponent();
UriBuilder baseUri = new UriBuilder("http", AgentSettings.Default.private_ip_address, AgentSettings.Default.port);
UriBuilder baseUri = new UriBuilder("https", AgentSettings.Default.private_ip_address, AgentSettings.Default.port);
var config = new HttpSelfHostConfiguration(baseUri.Uri);

View File

@ -10,9 +10,9 @@
</sectionGroup>
</configSections>
<startup>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</startup>
<log4net>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
@ -25,13 +25,14 @@
</appender>
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
<appendToFile value="true" />
<param name="ApplicationName" value="CloudStack Hyper-V Agent" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/>
</layout>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="FileAppender"/>
<appender-ref ref="EventLogAppender"/>
</root>
</log4net>
@ -95,7 +96,7 @@
<value>2048</value>
</setting>
<setting name="private_ip_address" serializeAs="String">
<value>10.102.192.150</value>
<value>0.0.0.0</value>
</setting>
</CloudStack.Plugin.AgentShell.AgentSettings>
</applicationSettings>

View File

@ -61,7 +61,7 @@ namespace HypervResource
get
{
string uncPath = null;
if (uri.Scheme.Equals("cifs") || uri.Scheme.Equals("networkfilesystem"))
if (uri != null && (uri.Scheme.Equals("cifs") || uri.Scheme.Equals("networkfilesystem")))
{
uncPath = @"\\" + uri.Host + uri.LocalPath;
}
@ -73,8 +73,13 @@ namespace HypervResource
{
get
{
var queryDictionary = System.Web.HttpUtility.ParseQueryString(uri.Query);
return System.Web.HttpUtility.UrlDecode(queryDictionary["user"]);
string user = null;
if (uri != null)
{
var queryDictionary = System.Web.HttpUtility.ParseQueryString(uri.Query);
user = System.Web.HttpUtility.UrlDecode(queryDictionary["user"]);
}
return user;
}
}
@ -82,8 +87,13 @@ namespace HypervResource
{
get
{
var queryDictionary = System.Web.HttpUtility.ParseQueryString(uri.Query);
return System.Web.HttpUtility.UrlDecode(queryDictionary["password"]);
string password = null;
if (uri != null)
{
var queryDictionary = System.Web.HttpUtility.ParseQueryString(uri.Query);
password = System.Web.HttpUtility.UrlDecode(queryDictionary["password"]);
}
return password;
}
}
@ -91,12 +101,17 @@ namespace HypervResource
{
get
{
var queryDictionary = System.Web.HttpUtility.ParseQueryString(uri.Query);
if (queryDictionary["domain"] != null)
string domain = null;
if (uri != null)
{
return System.Web.HttpUtility.UrlDecode(queryDictionary["domain"]);
var queryDictionary = System.Web.HttpUtility.ParseQueryString(uri.Query);
if (queryDictionary["domain"] != null)
{
domain = System.Web.HttpUtility.UrlDecode(queryDictionary["domain"]);
}
else domain = uri.Host;
}
else return uri.Host;
return domain;
}
}
@ -239,7 +254,7 @@ namespace HypervResource
// Assert
if (result.dataStore == null || (result.primaryDataStore == null && result.nfsDataStore == null))
{
String errMsg = "VolumeObjectTO missing dataStore in spec " + volumeObjectTOJson.ToString();
String errMsg = "VolumeObjectTO missing dataStore in spec " + Utils.CleanString(volumeObjectTOJson.ToString());
logger.Error(errMsg);
throw new ArgumentNullException(errMsg);
}
@ -277,7 +292,7 @@ namespace HypervResource
}
else
{
String errMsg = "VolumeObjectTO missing dataStore in spec " + volInfo.ToString();
String errMsg = "VolumeObjectTO missing dataStore in spec " + Utils.CleanString(volInfo.ToString());
logger.Error(errMsg);
throw new ArgumentNullException(errMsg);
}
@ -675,6 +690,20 @@ namespace HypervResource
public String entityType;
}
public class NicDetails
{
[JsonProperty("macAddress")]
public string macaddress;
[JsonProperty("vlanid")]
public int vlanid;
public NicDetails() { }
public NicDetails(String macaddress, int vlanid)
{
this.macaddress = macaddress;
this.vlanid = vlanid;
}
}
/// <summary>
/// Fully qualified named for a number of types used in CloudStack. Used to specify the intended type for JSON serialised objects.
/// </summary>
@ -723,6 +752,10 @@ namespace HypervResource
public const string GetVmDiskStatsCommand = "com.cloud.agent.api.GetVmDiskStatsCommand";
public const string GetVmStatsAnswer = "com.cloud.agent.api.GetVmStatsAnswer";
public const string GetVmStatsCommand = "com.cloud.agent.api.GetVmStatsCommand";
public const string GetVmConfigCommand = "com.cloud.agent.api.GetVmConfigCommand";
public const string GetVmConfigAnswer = "com.cloud.agent.api.GetVmConfigAnswer";
public const string ModifyVmNicConfigCommand = "com.cloud.agent.api.ModifyVmNicConfigCommand";
public const string ModifyVmNicConfigAnswer = "com.cloud.agent.api.ModifyVmNicConfigAnswer";
public const string GetVncPortAnswer = "com.cloud.agent.api.GetVncPortAnswer";
public const string GetVncPortCommand = "com.cloud.agent.api.GetVncPortCommand";
public const string HostStatsEntry = "com.cloud.agent.api.HostStatsEntry";

View File

@ -207,7 +207,7 @@ namespace HypervResource
{
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
{
logger.Info(CloudStackTypes.AttachCommand + cmd.ToString());
logger.Info(CloudStackTypes.AttachCommand + Utils.CleanString(cmd.ToString()));
string details = null;
bool result = false;
@ -268,7 +268,7 @@ namespace HypervResource
{
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
{
logger.Info(CloudStackTypes.DettachCommand + cmd.ToString());
logger.Info(CloudStackTypes.DettachCommand + Utils.CleanString(cmd.ToString()));
string details = null;
bool result = false;
@ -485,7 +485,7 @@ namespace HypervResource
{
JObject ansObj = Utils.CreateCloudStackObject(ansType, ansContent);
JArray answer = new JArray(ansObj);
logger.Info(ansObj.ToString());
logger.Info(Utils.CleanString(ansObj.ToString()));
return answer;
}
@ -496,7 +496,7 @@ namespace HypervResource
{
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
{
logger.Info(CloudStackTypes.CreateCommand + cmd.ToString());
logger.Info(CloudStackTypes.CreateCommand + Utils.CleanString(cmd.ToString()));
string details = null;
bool result = false;
@ -603,7 +603,7 @@ namespace HypervResource
{
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
{
logger.Info(CloudStackTypes.PrimaryStorageDownloadCommand + cmd.ToString());
logger.Info(CloudStackTypes.PrimaryStorageDownloadCommand + Utils.CleanString(cmd.ToString()));
string details = null;
bool result = false;
long size = 0;
@ -871,7 +871,7 @@ namespace HypervResource
{
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
{
logger.Info(CloudStackTypes.CreateStoragePoolCommand + cmd.ToString());
logger.Info(CloudStackTypes.CreateStoragePoolCommand + Utils.CleanString(cmd.ToString()));
object ansContent = new
{
result = true,
@ -889,7 +889,7 @@ namespace HypervResource
{
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
{
logger.Info(CloudStackTypes.ModifyStoragePoolCommand + cmd.ToString());
logger.Info(CloudStackTypes.ModifyStoragePoolCommand + Utils.CleanString(cmd.ToString()));
string details = null;
string localPath;
StoragePoolType poolType;
@ -982,6 +982,24 @@ namespace HypervResource
return true;
}
// POST api/HypervResource/PlugNicCommand
[HttpPost]
[ActionName(CloudStackTypes.PlugNicCommand)]
public JContainer PlugNicCommand([FromBody]dynamic cmd)
{
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
{
logger.Info(CloudStackTypes.PlugNicCommand + cmd.ToString());
object ansContent = new
{
result = true,
details = "instead of plug, change he network settings",
contextMap = contextMap
};
return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.PlugNicAnswer);
}
}
// POST api/HypervResource/CleanupNetworkRulesCmd
[HttpPost]
@ -1045,7 +1063,7 @@ namespace HypervResource
{
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
{
logger.Info(CloudStackTypes.StartCommand + cmd.ToString()); // TODO: Security hole? VM data printed to log
logger.Info(CloudStackTypes.StartCommand + Utils.CleanString(cmd.ToString()));
string details = null;
bool result = false;
@ -1144,7 +1162,7 @@ namespace HypervResource
{
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
{
logger.Info(CloudStackTypes.CreateObjectCommand + cmd.ToString());
logger.Info(CloudStackTypes.CreateObjectCommand + Utils.CleanString(cmd.ToString()));
bool result = false;
string details = null;
@ -1264,6 +1282,88 @@ namespace HypervResource
}
}
// POST api/HypervResource/ModifyVmVnicVlanCommand
[HttpPost]
[ActionName(CloudStackTypes.ModifyVmNicConfigCommand)]
public JContainer ModifyVmNicConfigCommand([FromBody]dynamic cmd)
{
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
{
logger.Info(CloudStackTypes.ModifyVmNicConfigCommand + cmd.ToString());
bool result = false;
String vmName = cmd.vmName;
uint vlan = (uint)cmd.vlan;
string macAddress = cmd.macAddress;
wmiCallsV2.ModifyVmVLan(vmName, vlan, macAddress);
result = true;
object ansContent = new
{
vmName = vmName,
result = result,
contextMap = contextMap
};
return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.ModifyVmNicConfigAnswer);
}
}
// POST api/HypervResource/GetVmConfigCommand
[HttpPost]
[ActionName(CloudStackTypes.GetVmConfigCommand)]
public JContainer GetVmConfigCommand([FromBody]dynamic cmd)
{
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
{
logger.Info(CloudStackTypes.GetVmConfigCommand + cmd.ToString());
bool result = false;
String vmName = cmd.vmName;
ComputerSystem vm = wmiCallsV2.GetComputerSystem(vmName);
List<NicDetails> nicDetails = new List<NicDetails>();
var nicSettingsViaVm = wmiCallsV2.GetEthernetPortSettings(vm);
NicDetails nic = null;
String[] macAddress = new String[nicSettingsViaVm.Length];
int index = 0;
foreach (SyntheticEthernetPortSettingData item in nicSettingsViaVm)
{
macAddress[index++] = item.Address;
}
index = 0;
var ethernetConnections = wmiCallsV2.GetEthernetConnections(vm);
int vlanid = 1;
foreach (EthernetPortAllocationSettingData item in ethernetConnections)
{
EthernetSwitchPortVlanSettingData vlanSettings = wmiCallsV2.GetVlanSettings(item);
if (vlanSettings == null)
{
vlanid = -1;
}
else
{
vlanid = vlanSettings.AccessVlanId;
}
nic = new NicDetails(macAddress[index++], vlanid);
nicDetails.Add(nic);
}
result = true;
object ansContent = new
{
vmName = vmName,
nics = nicDetails,
result = result,
contextMap = contextMap
};
return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.GetVmConfigAnswer);
}
}
// POST api/HypervResource/GetVmStatsCommand
[HttpPost]
[ActionName(CloudStackTypes.GetVmStatsCommand)]
@ -1315,7 +1415,7 @@ namespace HypervResource
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
{
// Log command *after* we've removed security details from the command.
logger.Info(CloudStackTypes.CopyCommand + cmd.ToString());
logger.Info(CloudStackTypes.CopyCommand + Utils.CleanString(cmd.ToString()));
bool result = false;
string details = null;
@ -1474,15 +1574,8 @@ namespace HypervResource
{
// TODO: thin provision instead of copying the full file.
File.Copy(srcFile, destFile);
VolumeObjectTO volume = new VolumeObjectTO();
volume.path = destFile;
volume.dataStore = destVolumeObjectTO.dataStore;
volume.name = destVolumeObjectTO.name;
volume.size = ulong.Parse(destVolumeObjectTO.size.ToString());
volume.format = destVolumeObjectTO.format;
volume.nfsDataStore = destVolumeObjectTO.nfsDataStore;
volume.primaryDataStore = destVolumeObjectTO.primaryDataStore;
JObject ansObj = Utils.CreateCloudStackObject(CloudStackTypes.VolumeObjectTO, volume);
destVolumeObjectTO.path = destFile;
JObject ansObj = Utils.CreateCloudStackObject(CloudStackTypes.VolumeObjectTO, destVolumeObjectTO);
newData = ansObj;
result = true;
}
@ -1597,6 +1690,11 @@ namespace HypervResource
string templatePropFile = Path.Combine(path, "template.properties");
using (StreamWriter sw = new StreamWriter(File.Open(templatePropFile, FileMode.Create), Encoding.GetEncoding("iso-8859-1")))
{
if (format != null)
{
format = format.ToLower();
}
sw.NewLine = "\n";
sw.WriteLine("id=" + templateId);
sw.WriteLine("filename=" + templateUuid + "." + format);
@ -1606,7 +1704,7 @@ namespace HypervResource
sw.WriteLine("virtualsize=" + virtualSize);
sw.WriteLine(format + ".virtualsize=" + virtualSize);
sw.WriteLine("size=" + physicalSize);
sw.WriteLine("vhd.size=" + physicalSize);
sw.WriteLine(format + ".size=" + physicalSize);
sw.WriteLine("public=false");
}
}
@ -1693,7 +1791,7 @@ namespace HypervResource
{
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
{
logger.Info(CloudStackTypes.GetStorageStatsCommand + cmd.ToString());
logger.Info(CloudStackTypes.GetStorageStatsCommand + Utils.CleanString(cmd.ToString()));
bool result = false;
string details = null;
long capacity = 0;
@ -1923,6 +2021,7 @@ namespace HypervResource
string productVersion = System.Environment.OSVersion.Version.Major.ToString() + "." +
System.Environment.OSVersion.Version.Minor.ToString();
details.Add("product_version", productVersion);
details.Add("rdp.server.port", 2179);
}
// Detect CPUs, speed, memory
@ -2002,6 +2101,45 @@ namespace HypervResource
}
}
// POST api/HypervResource/GetVncPortCommand
[HttpPost]
[ActionName(CloudStackTypes.GetVncPortCommand)]
public JContainer GetVncPortCommand([FromBody]dynamic cmd)
{
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
{
logger.Info(CloudStackTypes.GetVncPortCommand + cmd.ToString());
string details = null;
bool result = false;
string address = null;
int port = -9;
try
{
string vmName = (string)cmd.name;
var sys = wmiCallsV2.GetComputerSystem(vmName);
address = "instanceId=" + sys.Name ;
result = true;
}
catch (Exception sysEx)
{
details = CloudStackTypes.GetVncPortAnswer + " failed due to " + sysEx.Message;
logger.Error(details, sysEx);
}
object ansContent = new
{
result = result,
details = details,
address = address,
port = port
};
return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.GetVncPortAnswer);
}
}
public static System.Net.NetworkInformation.NetworkInterface GetNicInfoFromIpAddress(string ipAddress, out string subnet)
{
System.Net.NetworkInformation.NetworkInterface[] nics = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();

View File

@ -66,5 +66,6 @@ namespace HypervResource
void patchSystemVmIso(string vmName, string systemVmIso);
void SetState(ComputerSystem vm, ushort requiredState);
Dictionary<String, VmState> GetVmSync(String privateIpAddress);
void ModifyVmVLan(string vmName, uint vlanid, string mac);
}
}

View File

@ -164,6 +164,16 @@ namespace HypervResource
capacity = totalNumberOfBytes > 0 ? (long)totalNumberOfBytes : 0;
}
public static string CleanString(string stringToClean)
{
string cleanString = null;
string regexQueryString = "(&|%26)?(password|accesskey|secretkey)(=|%3D).*?(?=(%26|[&'\"]))";
string regexJson = "\"(password|accesskey|secretkey)\":\".*?\",?";
cleanString = System.Text.RegularExpressions.Regex.Replace(stringToClean, regexQueryString, "");
cleanString = System.Text.RegularExpressions.Regex.Replace(cleanString, regexJson, "");
return cleanString;
}
// from http://stackoverflow.com/a/2541569/939250
#region imports
[DllImport("advapi32.dll", SetLastError = true)]

View File

@ -443,6 +443,7 @@ namespace HypervResource
nicCount++;
}
// pass the boot args for the VM using KVP component.
// We need to pass the boot args to system vm's to get them configured with cloudstack configuration.
// Add new user data
@ -909,6 +910,37 @@ namespace HypervResource
return new ResourceAllocationSettingData((ManagementBaseObject)defaultDiskDriveSettings.LateBoundObject.Clone());
}
// Modify the systemvm nic's VLAN id
public void ModifyVmVLan(string vmName, uint vlanid, String mac)
{
ComputerSystem vm = GetComputerSystem(vmName);
SyntheticEthernetPortSettingData[] nicSettingsViaVm = GetEthernetPortSettings(vm);
// Obtain controller for Hyper-V virtualisation subsystem
VirtualSystemManagementService vmMgmtSvc = GetVirtualisationSystemManagementService();
string normalisedMAC = string.Join("", (mac.Split(new char[] { ':' })));
int index = 0;
foreach (SyntheticEthernetPortSettingData item in nicSettingsViaVm)
{
if (normalisedMAC.ToLower().Equals(item.Address.ToLower()))
{
break;
}
index++;
}
//TODO: make sure the index wont be out of range.
EthernetPortAllocationSettingData[] ethernetConnections = GetEthernetConnections(vm);
EthernetSwitchPortVlanSettingData vlanSettings = GetVlanSettings(ethernetConnections[index]);
//Assign configuration to new NIC
vlanSettings.LateBoundObject["AccessVlanId"] = vlanid;
vlanSettings.LateBoundObject["OperationMode"] = 1;
ModifyFeatureVmResources(vmMgmtSvc, vm, new String[] {
vlanSettings.LateBoundObject.GetText(TextFormat.CimDtd20)});
}
public void AttachIso(string displayName, string iso)
{
logger.DebugFormat("Got request to attach iso {0} to vm {1}", iso, displayName);
@ -1420,6 +1452,36 @@ namespace HypervResource
return vSwitch;
}
private static void ModifyFeatureVmResources(VirtualSystemManagementService vmMgmtSvc, ComputerSystem vm, string[] resourceSettings)
{
// Resource settings are changed through the management service
System.Management.ManagementPath jobPath;
System.Management.ManagementPath[] results;
var ret_val = vmMgmtSvc.ModifyFeatureSettings(
resourceSettings,
out jobPath,
out results);
// If the Job is done asynchronously
if (ret_val == ReturnCode.Started)
{
JobCompleted(jobPath);
}
else if (ret_val != ReturnCode.Completed)
{
var errMsg = string.Format(
"Failed to update VM {0} (GUID {1}) due to {2} (ModifyVirtualSystem call), existing VM not deleted",
vm.ElementName,
vm.Name,
ReturnCode.ToString(ret_val));
var ex = new WmiException(errMsg);
logger.Error(errMsg, ex);
throw ex;
}
}
private static void ModifyVmResources(VirtualSystemManagementService vmMgmtSvc, ComputerSystem vm, string[] resourceSettings)
{
// Resource settings are changed through the management service

View File

@ -90,7 +90,6 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12</version>
<configuration>
<!-- Exclude tests that require an agent, they appear under a different profile -->
<excludes>

View File

@ -16,15 +16,30 @@
// under the License.
package com.cloud.hypervisor.hyperv.guru;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.ejb.Local;
import javax.inject.Inject;
import com.cloud.agent.api.to.NicTO;
import com.cloud.agent.api.to.VirtualMachineTO;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.hypervisor.HypervisorGuru;
import com.cloud.hypervisor.HypervisorGuruBase;
import com.cloud.storage.GuestOSVO;
import com.cloud.storage.dao.GuestOSDao;
import com.cloud.exception.InsufficientAddressCapacityException;
import com.cloud.hypervisor.hyperv.manager.HypervManager;
import com.cloud.network.NetworkModel;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.dao.NetworkDao;
import com.cloud.network.dao.NetworkVO;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.vm.NicProfile;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineProfile;
/**
@ -35,6 +50,9 @@ public class HypervGuru extends HypervisorGuruBase implements HypervisorGuru {
@Inject
private GuestOSDao _guestOsDao;
@Inject HypervManager _hypervMgr;
@Inject NetworkDao _networkDao;
@Inject NetworkModel _networkMgr;
@Override
public final HypervisorType getHypervisorType() {
@ -51,6 +69,78 @@ public class HypervGuru extends HypervisorGuruBase implements HypervisorGuru {
@Override
public final VirtualMachineTO implement(VirtualMachineProfile vm) {
VirtualMachineTO to = toVirtualMachineTO(vm);
List<NicProfile> nicProfiles = vm.getNics();
if(vm.getVirtualMachine().getType() == VirtualMachine.Type.DomainRouter) {
NicProfile publicNicProfile = null;
for(NicProfile nicProfile : nicProfiles) {
if(nicProfile.getTrafficType() == TrafficType.Public) {
publicNicProfile = nicProfile;
break;
}
}
if(publicNicProfile != null) {
NicTO[] nics = to.getNics();
// reserve extra NICs
NicTO[] expandedNics = new NicTO[nics.length + _hypervMgr.getRouterExtraPublicNics()];
int i = 0;
int deviceId = -1;
for(i = 0; i < nics.length; i++) {
expandedNics[i] = nics[i];
if(nics[i].getDeviceId() > deviceId)
deviceId = nics[i].getDeviceId();
}
deviceId++;
long networkId = publicNicProfile.getNetworkId();
NetworkVO network = _networkDao.findById(networkId);
for(; i < nics.length + _hypervMgr.getRouterExtraPublicNics(); i++) {
NicTO nicTo = new NicTO();
nicTo.setDeviceId(deviceId++);
nicTo.setBroadcastType(publicNicProfile.getBroadcastType());
nicTo.setType(publicNicProfile.getTrafficType());
nicTo.setIp("0.0.0.0");
nicTo.setNetmask("255.255.255.255");
nicTo.setName(publicNicProfile.getName());
try {
String mac = _networkMgr.getNextAvailableMacAddressInNetwork(networkId);
nicTo.setMac(mac);
} catch (InsufficientAddressCapacityException e) {
throw new CloudRuntimeException("unable to allocate mac address on network: " + networkId);
}
nicTo.setDns1(publicNicProfile.getDns1());
nicTo.setDns2(publicNicProfile.getDns2());
if (publicNicProfile.getGateway() != null) {
nicTo.setGateway(publicNicProfile.getGateway());
} else {
nicTo.setGateway(network.getGateway());
}
nicTo.setDefaultNic(false);
nicTo.setBroadcastUri(publicNicProfile.getBroadCastUri());
nicTo.setIsolationuri(publicNicProfile.getIsolationUri());
Integer networkRate = _networkMgr.getNetworkRate(network.getId(), null);
nicTo.setNetworkRateMbps(networkRate);
expandedNics[i] = nicTo;
}
to.setNics(expandedNics);
}
StringBuffer sbMacSequence = new StringBuffer();
for(NicTO nicTo : sortNicsByDeviceId(to.getNics())) {
sbMacSequence.append(nicTo.getMac()).append("|");
}
sbMacSequence.deleteCharAt(sbMacSequence.length() - 1);
String bootArgs = to.getBootArgs();
to.setBootArgs(bootArgs + " nic_macs=" + sbMacSequence.toString());
}
// Determine the VM's OS description
GuestOSVO guestOS = _guestOsDao.findById(vm.getVirtualMachine().getGuestOSId());
@ -59,6 +149,29 @@ public class HypervGuru extends HypervisorGuruBase implements HypervisorGuru {
return to;
}
private NicTO[] sortNicsByDeviceId(NicTO[] nics) {
List<NicTO> listForSort = new ArrayList<NicTO>();
for (NicTO nic : nics) {
listForSort.add(nic);
}
Collections.sort(listForSort, new Comparator<NicTO>() {
@Override
public int compare(NicTO arg0, NicTO arg1) {
if (arg0.getDeviceId() < arg1.getDeviceId()) {
return -1;
} else if (arg0.getDeviceId() == arg1.getDeviceId()) {
return 0;
}
return 1;
}
});
return listForSort.toArray(new NicTO[0]);
}
@Override
public final boolean trackVmHostChange() {
return false;

View File

@ -21,4 +21,5 @@ import com.cloud.utils.component.Manager;
public interface HypervManager extends Manager {
public String prepareSecondaryStorageStore(long zoneId);
int getRouterExtraPublicNics();
}

View File

@ -45,6 +45,8 @@ import com.cloud.utils.NumbersUtil;
import com.cloud.utils.db.GlobalLock;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.script.Script;
import com.cloud.vm.dao.NicDao;
import com.cloud.vm.dao.VMInstanceDao;
@Local(value = {HypervManager.class})
public class HypervManagerImpl implements HypervManager {
@ -60,10 +62,11 @@ public class HypervManagerImpl implements HypervManager {
Map<String, String> _storageMounts = new HashMap<String, String>();
StorageLayer _storage;
@Inject
ConfigurationDao _configDao;
@Inject
DataStoreManager _dataStoreMgr;
@Inject ConfigurationDao _configDao;
@Inject DataStoreManager _dataStoreMgr;
@Inject VMInstanceDao _vminstanceDao;
@Inject NicDao _nicDao;
int _routerExtraPublicNics = 2;
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
@ -77,7 +80,7 @@ public class HypervManagerImpl implements HypervManager {
_storage = new JavaStorageLayer();
_storage.configure("StorageLayer", params);
}
_routerExtraPublicNics = NumbersUtil.parseInt(_configDao.getValue(Config.RouterExtraPublicNics.key()), 2);
return true;
}
@ -373,4 +376,9 @@ public class HypervManagerImpl implements HypervManager {
}
}
}
}
@Override
public int getRouterExtraPublicNics() {
return _routerExtraPublicNics;
}
}

View File

@ -25,23 +25,39 @@ import java.net.URISyntaxException;
import java.net.URL;
import java.nio.channels.SocketChannel;
import java.rmi.RemoteException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.annotation.PostConstruct;
import javax.ejb.Local;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.BasicClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
@ -55,7 +71,12 @@ import com.cloud.agent.api.CheckS2SVpnConnectionsCommand;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.GetDomRVersionAnswer;
import com.cloud.agent.api.GetDomRVersionCmd;
import com.cloud.agent.api.GetVmConfigAnswer;
import com.cloud.agent.api.GetVmConfigAnswer.NicDetails;
import com.cloud.agent.api.GetVmConfigCommand;
import com.cloud.agent.api.HostVmStateReportEntry;
import com.cloud.agent.api.ModifyVmNicConfigAnswer;
import com.cloud.agent.api.ModifyVmNicConfigCommand;
import com.cloud.agent.api.NetworkUsageAnswer;
import com.cloud.agent.api.NetworkUsageCommand;
import com.cloud.agent.api.PingCommand;
@ -101,11 +122,13 @@ import com.cloud.agent.api.to.PortForwardingRuleTO;
import com.cloud.agent.api.to.StaticNatRuleTO;
import com.cloud.agent.api.to.VirtualMachineTO;
import com.cloud.dc.DataCenter.NetworkType;
import com.cloud.exception.InternalErrorException;
import com.cloud.host.Host.Type;
import com.cloud.hypervisor.Hypervisor;
import com.cloud.hypervisor.hyperv.manager.HypervManager;
import com.cloud.network.HAProxyConfigurator;
import com.cloud.network.LoadBalancerConfigurator;
import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.network.Networks.RouterPrivateIpStrategy;
import com.cloud.network.rules.FirewallRule;
import com.cloud.resource.ServerResource;
@ -118,6 +141,7 @@ import com.cloud.utils.ssh.SshHelper;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineName;
/**
* Implementation of dummy resource to be returned from discoverer.
**/
@ -302,7 +326,9 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
URI agentUri = null;
try {
String cmdName = StartupCommand.class.getName();
agentUri = new URI("http", null, _agentIp, _port, "/api/HypervResource/" + cmdName, null, null);
agentUri =
new URI("https", null, _agentIp, _port,
"/api/HypervResource/" + cmdName, null, null);
} catch (URISyntaxException e) {
// TODO add proper logging
String errMsg = "Could not generate URI for Hyper-V agent";
@ -339,7 +365,9 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
Answer answer = null;
try {
String cmdName = cmd.getClass().getName();
agentUri = new URI("http", null, _agentIp, _port, "/api/HypervResource/" + cmdName, null, null);
agentUri =
new URI("https", null, _agentIp, _port,
"/api/HypervResource/" + cmdName, null, null);
} catch (URISyntaxException e) {
// TODO add proper logging
String errMsg = "Could not generate URI for Hyper-V agent";
@ -416,7 +444,8 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
// Only Answer instances are returned by remote agents.
// E.g. see Response.getAnswers()
Answer[] result = s_gson.fromJson(ansStr, Answer[].class);
s_logger.debug("executeRequest received response " + s_gson.toJson(result));
String logResult = cleanPassword(StringEscapeUtils.unescapeJava(result.toString()));
s_logger.debug("executeRequest received response " + logResult);
if (result.length > 0) {
return result[0];
}
@ -686,65 +715,6 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
}
}
//
// find mac address of a specified ethx device
// ip address show ethx | grep link/ether | sed -e 's/^[ \t]*//' | cut -d' ' -f2
// returns
// eth0:xx.xx.xx.xx
//
// list IP with eth devices
// ifconfig ethx |grep -B1 "inet addr" | awk '{ if ( $1 == "inet" ) { print $2 } else if ( $2 == "Link" ) { printf "%s:" ,$1 } }'
// | awk -F: '{ print $1 ": " $3 }'
//
// returns
// eth0:xx.xx.xx.xx
//
//
private int findRouterEthDeviceIndex(String domrName, String routerIp, String mac) throws Exception {
s_logger.info("findRouterEthDeviceIndex. mac: " + mac);
// TODO : this is a temporary very inefficient solution, will refactor it later
Pair<Boolean, String> result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "ls /proc/sys/net/ipv4/conf");
// when we dynamically plug in a new NIC into virtual router, it may take time to show up in guest OS
// we use a waiting loop here as a workaround to synchronize activities in systems
long startTick = System.currentTimeMillis();
while (System.currentTimeMillis() - startTick < 15000) {
if (result.first()) {
String[] tokens = result.second().split("\\s+");
for (String token : tokens) {
if (!("all".equalsIgnoreCase(token) || "default".equalsIgnoreCase(token) || "lo".equalsIgnoreCase(token))) {
String cmd = String.format("ip address show %s | grep link/ether | sed -e 's/^[ \t]*//' | cut -d' ' -f2", token);
if (s_logger.isDebugEnabled())
s_logger.debug("Run domr script " + cmd);
Pair<Boolean, String> result2 = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null,
// TODO need to find the dev index inside router based on IP address
cmd);
if (s_logger.isDebugEnabled())
s_logger.debug("result: " + result2.first() + ", output: " + result2.second());
if (result2.first() && result2.second().trim().equalsIgnoreCase(mac.trim()))
return Integer.parseInt(token.substring(3));
}
}
}
s_logger.warn("can not find intereface associated with mac: " + mac + ", guest OS may still at loading state, retry...");
try {
Thread.currentThread();
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
return -1;
}
protected Answer execute(SetPortForwardingRulesCommand cmd) {
if (s_logger.isInfoEnabled()) {
s_logger.info("Executing resource SetPortForwardingRulesCommand: " + s_gson.toJson(cmd));
@ -1150,74 +1120,35 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
if (s_logger.isInfoEnabled()) {
s_logger.info("Executing resource VmDataCommand: " + s_gson.toJson(cmd));
}
String routerPrivateIpAddress = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
String controlIp = getRouterSshControlIp(cmd);
Map<String, List<String[]>> data = new HashMap<String, List<String[]>>();
data.put(cmd.getVmIpAddress(), cmd.getVmData());
String vmIpAddress = cmd.getVmIpAddress();
List<String[]> vmData = cmd.getVmData();
String[] vmDataArgs = new String[vmData.size() * 2 + 4];
vmDataArgs[0] = "routerIP";
vmDataArgs[1] = routerPrivateIpAddress;
vmDataArgs[2] = "vmIP";
vmDataArgs[3] = vmIpAddress;
int i = 4;
for (String[] vmDataEntry : vmData) {
String folder = vmDataEntry[0];
String file = vmDataEntry[1];
String contents = (vmDataEntry[2] != null) ? vmDataEntry[2] : "none";
String json = new Gson().toJson(data);
s_logger.debug("VM data JSON IS:" + json);
vmDataArgs[i] = folder + "," + file;
vmDataArgs[i + 1] = contents;
i += 2;
}
json = Base64.encodeBase64String(json.getBytes());
String content = encodeDataArgs(vmDataArgs);
String tmpFileName = UUID.randomUUID().toString();
if (s_logger.isDebugEnabled()) {
s_logger.debug("Run vm_data command on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", data: " + content);
}
String args = "-d " + json;
try {
SshHelper.scpTo(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/tmp", content.getBytes(), tmpFileName, null);
try {
Pair<Boolean, String> result =
SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/root/userdata.py " + tmpFileName);
if (!result.first()) {
s_logger.error("vm_data command on domain router " + controlIp + " failed. messge: " + result.second());
return new Answer(cmd, false, "VmDataCommand failed due to " + result.second());
}
} finally {
SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "rm /tmp/" + tmpFileName);
Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/opt/cloud/bin/vmdata.py " + args);
if (!result.first()) {
s_logger.error("vm_data command on domain router " + controlIp + " failed. messge: " + result.second());
return new Answer(cmd, false, "VmDataCommand failed due to " + result.second());
}
if (s_logger.isInfoEnabled()) {
s_logger.info("vm_data command on domain router " + controlIp + " completed");
}
} catch (Throwable e) {
String msg = "VmDataCommand failed due to " + e;
String msg = "VmDataCommand failed due to " + e.getMessage();
s_logger.error(msg, e);
return new Answer(cmd, false, msg);
}
return new Answer(cmd);
}
private String encodeDataArgs(String[] dataArgs) {
StringBuilder sb = new StringBuilder();
for (String arg : dataArgs) {
sb.append(arg);
sb.append("\n");
}
return sb.toString();
}
protected Answer execute(DhcpEntryCommand cmd) {
if (s_logger.isInfoEnabled()) {
s_logger.info("Executing resource DhcpEntryCommand: " + s_gson.toJson(cmd));
@ -1366,6 +1297,102 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
return new Answer(cmd);
}
//
// find mac address of a specified ethx device
// ip address show ethx | grep link/ether | sed -e 's/^[ \t]*//' | cut -d' ' -f2
// returns
// eth0:xx.xx.xx.xx
//
// list IP with eth devices
// ifconfig ethx |grep -B1 "inet addr" | awk '{ if ( $1 == "inet" ) { print $2 } else if ( $2 == "Link" ) { printf "%s:" ,$1 } }'
// | awk -F: '{ print $1 ": " $3 }'
//
// returns
// eth0:xx.xx.xx.xx
//
//
private int findRouterEthDeviceIndex(String domrName, String routerIp, String mac) throws Exception {
s_logger.info("findRouterEthDeviceIndex. mac: " + mac);
// TODO : this is a temporary very inefficient solution, will refactor it later
Pair<Boolean, String> result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null,
"ls /proc/sys/net/ipv4/conf");
// when we dynamically plug in a new NIC into virtual router, it may take time to show up in guest OS
// we use a waiting loop here as a workaround to synchronize activities in systems
long startTick = System.currentTimeMillis();
while (System.currentTimeMillis() - startTick < 15000) {
if (result.first()) {
String[] tokens = result.second().split("\\s+");
for (String token : tokens) {
if (!("all".equalsIgnoreCase(token) || "default".equalsIgnoreCase(token) || "lo".equalsIgnoreCase(token))) {
String cmd = String.format("ip address show %s | grep link/ether | sed -e 's/^[ \t]*//' | cut -d' ' -f2", token);
if (s_logger.isDebugEnabled())
s_logger.debug("Run domr script " + cmd);
Pair<Boolean, String> result2 = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null,
// TODO need to find the dev index inside router based on IP address
cmd);
if (s_logger.isDebugEnabled())
s_logger.debug("result: " + result2.first() + ", output: " + result2.second());
if (result2.first() && result2.second().trim().equalsIgnoreCase(mac.trim()))
return Integer.parseInt(token.substring(3));
}
}
}
s_logger.warn("can not find intereface associated with mac: " + mac + ", guest OS may still at loading state, retry...");
}
return -1;
}
private Pair<Integer, String> findRouterFreeEthDeviceIndex(String routerIp) throws Exception {
s_logger.info("findRouterFreeEthDeviceIndex. mac: ");
// TODO : this is a temporary very inefficient solution, will refactor it later
Pair<Boolean, String> result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null,
"ip address | grep DOWN| cut -f2 -d :");
// when we dynamically plug in a new NIC into virtual router, it may take time to show up in guest OS
// we use a waiting loop here as a workaround to synchronize activities in systems
long startTick = System.currentTimeMillis();
while (System.currentTimeMillis() - startTick < 15000) {
if (result.first() && !result.second().isEmpty()) {
String[] tokens = result.second().split("\\n");
for (String token : tokens) {
if (!("all".equalsIgnoreCase(token) || "default".equalsIgnoreCase(token) || "lo".equalsIgnoreCase(token))) {
//String cmd = String.format("ip address show %s | grep link/ether | sed -e 's/^[ \t]*//' | cut -d' ' -f2", token);
//TODO: don't check for eth0,1,2, as they will be empty by default.
//String cmd = String.format("ip address show %s ", token);
String cmd = String.format("ip address show %s | grep link/ether | sed -e 's/^[ \t]*//' | cut -d' ' -f2", token);
if (s_logger.isDebugEnabled())
s_logger.debug("Run domr script " + cmd);
Pair<Boolean, String> result2 = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null,
// TODO need to find the dev index inside router based on IP address
cmd);
if (s_logger.isDebugEnabled())
s_logger.debug("result: " + result2.first() + ", output: " + result2.second());
if (result2.first() && result2.second().trim().length() > 0)
return new Pair<Integer, String>(Integer.parseInt(token.trim().substring(3)), result2.second().trim()) ;
}
}
}
//s_logger.warn("can not find intereface associated with mac: , guest OS may still at loading state, retry...");
}
return new Pair<Integer, String>(-1, "");
}
protected Answer execute(IpAssocCommand cmd) {
if (s_logger.isInfoEnabled()) {
s_logger.info("Executing resource IPAssocCommand: " + s_gson.toJson(cmd));
@ -1381,7 +1408,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
String controlIp = getRouterSshControlIp(cmd);
for (IpAddressTO ip : ips) {
assignPublicIpAddress(routerName, controlIp, ip.getPublicIp(), ip.isAdd(), ip.isFirstIP(), ip.isSourceNat(), ip.getBroadcastUri(), ip.getVlanGateway(),
ip.getVlanNetmask(), ip.getVifMacAddress());
ip.getVlanNetmask(), ip.getVifMacAddress());
results[i++] = ip.getPublicIp() + " - success";
}
@ -1399,16 +1426,97 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
return new IpAssocAnswer(cmd, results);
}
protected int getVmNics(String vmName, int vlanid) {
GetVmConfigCommand vmConfig = new GetVmConfigCommand(vmName);
URI agentUri = null;
int nicposition = -1;
try {
String cmdName = GetVmConfigCommand.class.getName();
agentUri =
new URI("https", null, _agentIp, _port,
"/api/HypervResource/" + cmdName, null, null);
} catch (URISyntaxException e) {
String errMsg = "Could not generate URI for Hyper-V agent";
s_logger.error(errMsg, e);
}
String ansStr = postHttpRequest(s_gson.toJson(vmConfig), agentUri);
Answer[] result = s_gson.fromJson(ansStr, Answer[].class);
s_logger.debug("executeRequest received response "
+ s_gson.toJson(result));
if (result.length > 0) {
GetVmConfigAnswer ans = ((GetVmConfigAnswer)result[0]);
List<NicDetails> nics = ans.getNics();
for (NicDetails nic : nics) {
if (nic.getVlanid() == vlanid) {
nicposition = nics.indexOf(nic);
break;
}
}
}
return nicposition;
}
protected void modifyNicVlan(String vmName, int vlanId, String macAddress) {
ModifyVmNicConfigCommand modifynic = new ModifyVmNicConfigCommand(vmName, vlanId, macAddress);
URI agentUri = null;
try {
String cmdName = ModifyVmNicConfigCommand.class.getName();
agentUri =
new URI("https", null, _agentIp, _port,
"/api/HypervResource/" + cmdName, null, null);
} catch (URISyntaxException e) {
String errMsg = "Could not generate URI for Hyper-V agent";
s_logger.error(errMsg, e);
}
String ansStr = postHttpRequest(s_gson.toJson(modifynic), agentUri);
Answer[] result = s_gson.fromJson(ansStr, Answer[].class);
s_logger.debug("executeRequest received response "
+ s_gson.toJson(result));
if (result.length > 0) {
ModifyVmNicConfigAnswer ans = ((ModifyVmNicConfigAnswer)result[0]);
}
}
protected void assignPublicIpAddress(final String vmName, final String privateIpAddress, final String publicIpAddress, final boolean add, final boolean firstIP,
final boolean sourceNat, final String vlanId, final String vlanGateway, final String vlanNetmask, final String vifMacAddress) throws Exception {
final boolean sourceNat, final String broadcastId, final String vlanGateway, final String vlanNetmask, final String vifMacAddress) throws Exception {
URI broadcastUri = BroadcastDomainType.fromString(broadcastId);
if (BroadcastDomainType.getSchemeValue(broadcastUri) != BroadcastDomainType.Vlan) {
throw new InternalErrorException("Unable to assign a public IP to a VIF on network " + broadcastId);
}
int vlanId = Integer.parseInt(BroadcastDomainType.getValue(broadcastUri));
int publicNicInfo = -1;
publicNicInfo = getVmNics(vmName, vlanId);
boolean addVif = false;
if (add) {
if (add && publicNicInfo == -1) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Plug new NIC to associate" + privateIpAddress + " to " + publicIpAddress);
}
addVif = true;
} else if (!add && firstIP) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unplug NIC " + publicNicInfo);
}
}
if (addVif) {
Pair<Integer, String> nicdevice = findRouterFreeEthDeviceIndex(privateIpAddress);
publicNicInfo = nicdevice.first();
if (publicNicInfo > 0) {
modifyNicVlan(vmName, vlanId, nicdevice.second());
// After modifying the vnic on VR, check the VR VNics config in the host and get the device position
publicNicInfo = getVmNics(vmName, vlanId);
// As a new nic got activated in the VR. add the entry in the NIC's table.
networkUsage(privateIpAddress, "addVif", "eth" + publicNicInfo);
}
else {
// we didn't find any eth device available in VR to configure the ip range with new VLAN
String msg = "No Nic is available on DomR VIF to associate/disassociate IP with.";
s_logger.error(msg);
throw new InternalErrorException(msg);
}
}
String args = null;
@ -1430,8 +1538,8 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
args += publicIpAddress + "/" + cidrSize;
args += " -c ";
args += "eth" + "2"; // currently hardcoding to eth 2 (which is default public ipd)//publicNicInfo.first();
args += "eth" + publicNicInfo;
args += " -g ";
args += vlanGateway;
@ -1444,7 +1552,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
}
Pair<Boolean, String> result =
SshHelper.sshExecute(privateIpAddress, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/opt/cloud/bin/ipassoc.sh " + args);
SshHelper.sshExecute(privateIpAddress, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "/opt/cloud/bin/ipassoc.sh " + args);
if (!result.first()) {
s_logger.error("ipassoc command on domain router " + privateIpAddress + " failed. message: " + result.second());
@ -1662,10 +1770,37 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
// comment to use Apache HttpClient
// http://stackoverflow.com/a/2793153/939250, but final comment is to
// use Apache.
s_logger.debug("POST request to" + agentUri.toString() + " with contents" + jsonCmd);
String logMessage = StringEscapeUtils.unescapeJava(jsonCmd);
logMessage = cleanPassword(logMessage);
s_logger.debug("POST request to " + agentUri.toString()
+ " with contents " + logMessage);
// Create request
HttpClient httpClient = new DefaultHttpClient();
HttpClient httpClient = null;
TrustStrategy easyStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
return true;
}
};
try {
SSLSocketFactory sf = new SSLSocketFactory(easyStrategy, new AllowAllHostnameVerifier());
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("https", DEFAULT_AGENT_PORT, sf));
ClientConnectionManager ccm = new BasicClientConnectionManager(registry);
httpClient = new DefaultHttpClient(ccm);
} catch (KeyManagementException e) {
s_logger.error("failed to initialize http client " + e.getMessage());
} catch (UnrecoverableKeyException e) {
s_logger.error("failed to initialize http client " + e.getMessage());
} catch (NoSuchAlgorithmException e) {
s_logger.error("failed to initialize http client " + e.getMessage());
} catch (KeyStoreException e) {
s_logger.error("failed to initialize http client " + e.getMessage());
}
String result = null;
// TODO: are there timeout settings and worker thread settings to tweak?
@ -1678,7 +1813,8 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
StringEntity cmdJson = new StringEntity(jsonCmd);
request.addHeader("content-type", "application/json");
request.setEntity(cmdJson);
s_logger.debug("Sending cmd to " + agentUri.toString() + " cmd data:" + jsonCmd);
s_logger.debug("Sending cmd to " + agentUri.toString()
+ " cmd data:" + logMessage);
HttpResponse response = httpClient.execute(request);
// Unsupported commands will not route.
@ -1695,7 +1831,8 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
return null;
} else {
result = EntityUtils.toString(response.getEntity());
s_logger.debug("POST response is" + result);
String logResult = cleanPassword(StringEscapeUtils.unescapeJava(result));
s_logger.debug("POST response is " + logResult);
}
} catch (ClientProtocolException protocolEx) {
// Problem with HTTP message exchange
@ -1791,7 +1928,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
sch.connect(addr);
return null;
} catch (IOException e) {
s_logger.info("Could not connect to " + ipAddress + " due to " + e.toString());
s_logger.info("Could] not connect to " + ipAddress + " due to " + e.toString());
if (e instanceof ConnectException) {
// if connection is refused because of VM is being started,
// we give it more sleep time
@ -1821,4 +1958,22 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
return "Unable to connect";
}
public static String cleanPassword(String logString) {
String cleanLogString = null;
if (logString != null) {
cleanLogString = logString;
String[] temp = logString.split(",");
int i = 0;
if (temp != null) {
while (i < temp.length) {
temp[i] = StringUtils.cleanString(temp[i]);
i++;
}
List<String> stringList = new ArrayList<String>();
Collections.addAll(stringList, temp);
cleanLogString = StringUtils.join(stringList, ",");
}
}
return cleanLogString;
}
}

View File

@ -67,7 +67,6 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.5.1</version>
<executions>
<execution>
<id>copy-dependencies</id>
@ -85,7 +84,6 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.14</version>
<configuration>
<excludes>
<exclude>**/Qemu*.java</exclude>

View File

@ -16,73 +16,12 @@
// under the License.
package com.cloud.hypervisor.kvm.resource;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.libvirt.Connect;
import org.libvirt.Domain;
import org.libvirt.DomainBlockStats;
import org.libvirt.DomainInfo;
import org.libvirt.DomainInterfaceStats;
import org.libvirt.DomainSnapshot;
import org.libvirt.LibvirtException;
import org.libvirt.NodeInfo;
import com.ceph.rados.IoCTX;
import com.ceph.rados.Rados;
import com.ceph.rados.RadosException;
import com.ceph.rbd.Rbd;
import com.ceph.rbd.RbdException;
import com.ceph.rbd.RbdImage;
import org.apache.cloudstack.storage.command.StorageSubSystemCommand;
import org.apache.cloudstack.storage.to.PrimaryDataStoreTO;
import org.apache.cloudstack.storage.to.VolumeObjectTO;
import org.apache.cloudstack.utils.qemu.QemuImg;
import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat;
import org.apache.cloudstack.utils.qemu.QemuImgException;
import org.apache.cloudstack.utils.qemu.QemuImgFile;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.AttachIsoCommand;
import com.cloud.agent.api.AttachVolumeAnswer;
@ -155,7 +94,6 @@ import com.cloud.agent.api.RebootCommand;
import com.cloud.agent.api.RebootRouterCommand;
import com.cloud.agent.api.SecurityGroupRuleAnswer;
import com.cloud.agent.api.SecurityGroupRulesCmd;
import com.cloud.agent.api.SetupGuestNetworkAnswer;
import com.cloud.agent.api.SetupGuestNetworkCommand;
import com.cloud.agent.api.StartAnswer;
import com.cloud.agent.api.StartCommand;
@ -174,14 +112,9 @@ import com.cloud.agent.api.check.CheckSshCommand;
import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
import com.cloud.agent.api.proxy.ConsoleProxyLoadAnswer;
import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand;
import com.cloud.agent.api.routing.IpAssocAnswer;
import com.cloud.agent.api.routing.IpAssocCommand;
import com.cloud.agent.api.routing.IpAssocVpcCommand;
import com.cloud.agent.api.routing.NetworkElementCommand;
import com.cloud.agent.api.routing.SetMonitorServiceCommand;
import com.cloud.agent.api.routing.SetNetworkACLAnswer;
import com.cloud.agent.api.routing.SetNetworkACLCommand;
import com.cloud.agent.api.routing.SetSourceNatAnswer;
import com.cloud.agent.api.routing.SetSourceNatCommand;
import com.cloud.agent.api.storage.CopyVolumeAnswer;
import com.cloud.agent.api.storage.CopyVolumeCommand;
@ -202,6 +135,7 @@ import com.cloud.agent.api.to.NicTO;
import com.cloud.agent.api.to.StorageFilerTO;
import com.cloud.agent.api.to.VirtualMachineTO;
import com.cloud.agent.api.to.VolumeTO;
import com.cloud.agent.resource.virtualnetwork.VirtualRouterDeployer;
import com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource;
import com.cloud.dc.Vlan;
import com.cloud.exception.InternalErrorException;
@ -251,17 +185,77 @@ import com.cloud.storage.template.Processor.FormatInfo;
import com.cloud.storage.template.QCOW2Processor;
import com.cloud.storage.template.TemplateLocation;
import com.cloud.storage.template.TemplateProp;
import com.cloud.utils.ExecutionResult;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils;
import com.cloud.utils.script.OutputInterpreter;
import com.cloud.utils.script.OutputInterpreter.AllLinesParser;
import com.cloud.utils.script.Script;
import com.cloud.utils.ssh.SshHelper;
import com.cloud.vm.DiskProfile;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachine.PowerState;
import com.cloud.vm.VirtualMachine.State;
import org.apache.cloudstack.storage.command.StorageSubSystemCommand;
import org.apache.cloudstack.storage.to.PrimaryDataStoreTO;
import org.apache.cloudstack.storage.to.VolumeObjectTO;
import org.apache.cloudstack.utils.qemu.QemuImg;
import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat;
import org.apache.cloudstack.utils.qemu.QemuImgException;
import org.apache.cloudstack.utils.qemu.QemuImgFile;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.libvirt.Connect;
import org.libvirt.Domain;
import org.libvirt.DomainBlockStats;
import org.libvirt.DomainInfo;
import org.libvirt.DomainInterfaceStats;
import org.libvirt.DomainSnapshot;
import org.libvirt.LibvirtException;
import org.libvirt.NodeInfo;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* LibvirtComputingResource execute requests on the computing/routing host using
@ -286,7 +280,7 @@ import com.cloud.vm.VirtualMachine.State;
* pool | the parent of the storage pool hierarchy * }
**/
@Local(value = {ServerResource.class})
public class LibvirtComputingResource extends ServerResourceBase implements ServerResource {
public class LibvirtComputingResource extends ServerResourceBase implements ServerResource, VirtualRouterDeployer {
private static final Logger s_logger = Logger.getLogger(LibvirtComputingResource.class);
private String _modifyVlanPath;
@ -323,6 +317,59 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
protected static final String DEFAULT_OVS_VIF_DRIVER_CLASS_NAME = "com.cloud.hypervisor.kvm.resource.OvsVifDriver";
protected static final String DEFAULT_BRIDGE_VIF_DRIVER_CLASS_NAME = "com.cloud.hypervisor.kvm.resource.BridgeVifDriver";
@Override
public ExecutionResult executeInVR(String routerIp, String script, String args) {
final Script command = new Script(_routerProxyPath, _timeout, s_logger);
final AllLinesParser parser = new AllLinesParser();
command.add(script);
command.add(routerIp);
if (args != null) {
command.add(args);
}
String details = command.execute(parser);
if (details == null) {
details = parser.getLines();
}
return new ExecutionResult(command.getExitValue() == 0, details);
}
@Override
public ExecutionResult createFileInVR(String routerIp, String path, String filename, String content) {
File permKey = new File("/root/.ssh/id_rsa.cloud");
String error = null;
try {
SshHelper.scpTo(routerIp, 3922, "root", permKey, null, path, content.getBytes(), filename, null);
} catch (Exception e) {
s_logger.warn("Fail to create file " + path + filename + " in VR " + routerIp, e);
error = e.getMessage();
}
return new ExecutionResult(error == null, error);
}
@Override
public ExecutionResult prepareCommand(NetworkElementCommand cmd) {
//Update IP used to access router
cmd.setRouterAccessIp(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP));
assert cmd.getRouterAccessIp() != null;
if (cmd instanceof IpAssocVpcCommand) {
return prepareNetworkElementCommand((IpAssocVpcCommand)cmd);
} else if (cmd instanceof IpAssocCommand) {
return prepareNetworkElementCommand((IpAssocCommand)cmd);
} else if (cmd instanceof SetupGuestNetworkCommand) {
return prepareNetworkElementCommand((SetupGuestNetworkCommand)cmd);
} else if (cmd instanceof SetSourceNatCommand) {
return prepareNetworkElementCommand((SetSourceNatCommand)cmd);
}
return new ExecutionResult(true, null);
}
@Override
public ExecutionResult cleanupCommand(NetworkElementCommand cmd) {
return new ExecutionResult(true, null);
}
private static final class KeyValueInterpreter extends OutputInterpreter {
private final Map<String, String> map = new HashMap<String, String>();
@ -377,6 +424,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
private boolean _canBridgeFirewall;
protected String _localStoragePath;
protected String _localStorageUUID;
protected boolean _noMemBalloon = false;
protected String _guestCpuMode;
protected String _guestCpuModel;
private final Map<String, String> _pifs = new HashMap<String, String>();
@ -538,7 +586,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
params.put("domr.scripts.dir", domrScriptsDir);
_virtRouterResource = new VirtualRoutingResource();
_virtRouterResource = new VirtualRoutingResource(this);
success = _virtRouterResource.configure(name, params);
if (!success) {
@ -724,6 +772,11 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
value = (String)params.get("cmds.timeout");
_cmdsTimeout = NumbersUtil.parseInt(value, 7200) * 1000;
value = (String) params.get("vm.memballoon.disable");
if (Boolean.parseBoolean(value)) {
_noMemBalloon = true;
}
value = (String)params.get("host.reserved.mem.mb");
_dom0MinMem = NumbersUtil.parseInt(value, 0) * 1024 * 1024;
@ -1259,16 +1312,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
return execute((PlugNicCommand)cmd);
} else if (cmd instanceof UnPlugNicCommand) {
return execute((UnPlugNicCommand)cmd);
} else if (cmd instanceof SetupGuestNetworkCommand) {
return execute((SetupGuestNetworkCommand)cmd);
} else if (cmd instanceof SetNetworkACLCommand) {
return execute((SetNetworkACLCommand)cmd);
} else if (cmd instanceof SetSourceNatCommand) {
return execute((SetSourceNatCommand)cmd);
} else if (cmd instanceof IpAssocVpcCommand) {
return execute((IpAssocVpcCommand)cmd);
} else if (cmd instanceof IpAssocCommand) {
return execute((IpAssocCommand)cmd);
} else if (cmd instanceof NetworkElementCommand) {
return _virtRouterResource.executeRequest(cmd);
} else if (cmd instanceof CheckSshCommand) {
@ -1291,8 +1334,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
return storageHandler.handleStorageCommands((StorageSubSystemCommand)cmd);
} else if (cmd instanceof PvlanSetupCommand) {
return execute((PvlanSetupCommand)cmd);
} else if (cmd instanceof SetMonitorServiceCommand) {
return execute((SetMonitorServiceCommand)cmd);
} else if (cmd instanceof CheckOnHostCommand) {
return execute((CheckOnHostCommand)cmd);
} else if (cmd instanceof OvsFetchInterfaceCommand) {
@ -1980,25 +2021,10 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
}
}
private SetupGuestNetworkAnswer execute(SetupGuestNetworkCommand cmd) {
private ExecutionResult prepareNetworkElementCommand(SetupGuestNetworkCommand cmd) {
Connect conn;
NicTO nic = cmd.getNic();
String routerIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
String routerGIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP);
String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
String gateway = cmd.getAccessDetail(NetworkElementCommand.GUEST_NETWORK_GATEWAY);
String cidr = Long.toString(NetUtils.getCidrSize(nic.getNetmask()));
String domainName = cmd.getNetworkDomain();
String dns = cmd.getDefaultDns1();
if (dns == null || dns.isEmpty()) {
dns = cmd.getDefaultDns2();
} else {
String dns2 = cmd.getDefaultDns2();
if (dns2 != null && !dns2.isEmpty()) {
dns += "," + dns2;
}
}
try {
conn = LibvirtConnection.getConnectionByVmName(routerName);
@ -2013,75 +2039,18 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
}
if (routerNic == null) {
return new SetupGuestNetworkAnswer(cmd, false, "Can not find nic with mac " + nic.getMac() + " for VM " + routerName);
return new ExecutionResult(false, "Can not find nic with mac " + nic.getMac() + " for VM " + routerName);
}
String dev = "eth" + nic.getDeviceId();
String netmask = NetUtils.getSubNet(routerGIP, nic.getNetmask());
String result = _virtRouterResource.assignGuestNetwork(dev, routerIP, routerGIP, gateway, cidr, netmask, dns, domainName);
if (result != null) {
return new SetupGuestNetworkAnswer(cmd, false, "Creating guest network failed due to " + result);
}
return new SetupGuestNetworkAnswer(cmd, true, "success");
return new ExecutionResult(true, null);
} catch (LibvirtException e) {
String msg = "Creating guest network failed due to " + e.toString();
s_logger.warn(msg, e);
return new SetupGuestNetworkAnswer(cmd, false, msg);
return new ExecutionResult(false, msg);
}
}
private Answer execute(SetMonitorServiceCommand cmd) {
String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
String config = cmd.getConfiguration();
String result = _virtRouterResource.configureMonitor(routerIp, config);
if (result != null) {
return new Answer(cmd, false, "SetMonitorServiceCommand failed");
}
return new Answer(cmd);
}
private SetNetworkACLAnswer execute(SetNetworkACLCommand cmd) {
String[] results = new String[cmd.getRules().length];
String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
String privateGw = cmd.getAccessDetail(NetworkElementCommand.VPC_PRIVATE_GATEWAY);
try {
String[][] rules = cmd.generateFwRules();
String[] aclRules = rules[0];
NicTO nic = cmd.getNic();
String dev = "eth" + nic.getDeviceId();
String netmask = Long.toString(NetUtils.getCidrSize(nic.getNetmask()));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < aclRules.length; i++) {
sb.append(aclRules[i]).append(',');
}
String rule = sb.toString();
String result = _virtRouterResource.assignNetworkACL(routerIp, dev, nic.getIp(), netmask, rule, privateGw);
if (result != null) {
for (int i = 0; i < results.length; i++) {
results[i] = "Failed";
}
return new SetNetworkACLAnswer(cmd, false, results);
}
return new SetNetworkACLAnswer(cmd, true, results);
} catch (Exception e) {
String msg = "SetNetworkACL failed due to " + e.toString();
s_logger.error(msg, e);
return new SetNetworkACLAnswer(cmd, false, results);
}
}
protected SetSourceNatAnswer execute(SetSourceNatCommand cmd) {
protected ExecutionResult prepareNetworkElementCommand(SetSourceNatCommand cmd) {
Connect conn;
String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
String routerIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
@ -2102,7 +2071,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
/*skip over, no physical bridge device exists*/
} else if (pluggedVlanId == null) {
/*this should only be true in the case of link local bridge*/
return new SetSourceNatAnswer(cmd, false, "unable to find the vlan id for bridge " + pluggedVlanBr + " when attempting to set up" + pubVlan +
return new ExecutionResult(false, "unable to find the vlan id for bridge " + pluggedVlanBr + " when attempting to set up" + pubVlan +
" on router " + routerName);
} else if (pluggedVlanId.equals(pubVlan)) {
break;
@ -2110,26 +2079,20 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
devNum++;
}
String dev = "eth" + devNum;
String result = _virtRouterResource.assignSourceNat(routerIP, pubIP.getPublicIp(), dev);
pubIP.setNicDevId(devNum);
if (result != null) {
return new SetSourceNatAnswer(cmd, false, "KVM plugin \"vpc_snat\" failed:" + result);
}
return new SetSourceNatAnswer(cmd, true, "success");
return new ExecutionResult(true, "success");
} catch (LibvirtException e) {
String msg = "Ip SNAT failure due to " + e.toString();
s_logger.error(msg, e);
return new SetSourceNatAnswer(cmd, false, msg);
return new ExecutionResult(false, msg);
}
}
protected IpAssocAnswer execute(IpAssocVpcCommand cmd) {
protected ExecutionResult prepareNetworkElementCommand(IpAssocVpcCommand cmd) {
Connect conn;
String[] results = new String[cmd.getIpAddresses().length];
int i = 0;
String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
String routerIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
try {
conn = LibvirtConnection.getConnectionByVmName(routerName);
@ -2152,31 +2115,19 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
}
for (IpAddressTO ip : ips) {
String nicName = "eth" + broadcastUriToNicNum.get(ip.getBroadcastUri());
String netmask = Long.toString(NetUtils.getCidrSize(ip.getVlanNetmask()));
String subnet = NetUtils.getSubNet(ip.getPublicIp(), ip.getVlanNetmask());
_virtRouterResource.assignVpcIpToRouter(routerIP, ip.isAdd(), ip.getPublicIp(), nicName, ip.getVlanGateway(), netmask, subnet, ip.isSourceNat());
results[i++] = ip.getPublicIp() + " - success";
ip.setNicDevId(broadcastUriToNicNum.get(ip.getBroadcastUri()));
}
return new ExecutionResult(true, null);
} catch (LibvirtException e) {
s_logger.error("Ip Assoc failure on applying one ip due to exception: ", e);
results[i++] = IpAssocAnswer.errorResult;
} catch (InternalErrorException e) {
s_logger.error("Ip Assoc failure on applying one ip due to exception: ", e);
results[i++] = IpAssocAnswer.errorResult;
return new ExecutionResult(false, e.getMessage());
}
return new IpAssocAnswer(cmd, results);
}
public Answer execute(IpAssocCommand cmd) {
public ExecutionResult prepareNetworkElementCommand(IpAssocCommand cmd) {
String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
String[] results = new String[cmd.getIpAddresses().length];
for (int i = 0; i < results.length; i++) {
results[i] = IpAssocAnswer.errorResult;
}
Connect conn;
try {
conn = LibvirtConnection.getConnectionByVmName(routerName);
@ -2198,11 +2149,9 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
nicPos++;
}
IpAddressTO[] ips = cmd.getIpAddresses();
int i = 0;
String result = null;
int nicNum = 0;
boolean newNic = false;
for (IpAddressTO ip : ips) {
boolean newNic = false;
if (!broadcastUriAllocatedToVM.containsKey(ip.getBroadcastUri())) {
/* plug a vif into router */
VifHotPlug(conn, routerName, ip.getBroadcastUri(), ip.getVifMacAddress());
@ -2211,21 +2160,17 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
}
nicNum = broadcastUriAllocatedToVM.get(ip.getBroadcastUri());
networkUsage(routerIp, "addVif", "eth" + nicNum);
result =
_virtRouterResource.assignPublicIpAddress(routerName, routerIp, ip.getPublicIp(), ip.isAdd(), ip.isFirstIP(), ip.isSourceNat(), ip.getBroadcastUri(),
ip.getVlanGateway(), ip.getVlanNetmask(), ip.getVifMacAddress(), nicNum, newNic);
if (result == null) {
results[i++] = ip.getPublicIp() + " - success";
}
ip.setNicDevId(nicNum);
ip.setNewNic(newNic);
}
return new IpAssocAnswer(cmd, results);
return new ExecutionResult(true, null);
} catch (LibvirtException e) {
s_logger.error("ipassoccmd failed", e);
return new IpAssocAnswer(cmd, results);
return new ExecutionResult(false, e.getMessage());
} catch (InternalErrorException e) {
s_logger.error("ipassoccmd failed", e);
return new IpAssocAnswer(cmd, results);
return new ExecutionResult(false, e.getMessage());
}
}
@ -2988,10 +2933,9 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
dconn = new Connect("qemu+tcp://" + cmd.getDestinationIp() + "/system");
/*
* Hard code lm flags: VIR_MIGRATE_LIVE(1<<0) and
* VIR_MIGRATE_PERSIST_DEST(1<<3)
* Hard code lm flag: VIR_MIGRATE_LIVE(1<<0)
*/
destDomain = dm.migrate(dconn, (1 << 0) | (1 << 3), xmlDesc, vmName, "tcp:" + cmd.getDestinationIp(), _migrateSpeed);
destDomain = dm.migrate(dconn, (1 << 0), xmlDesc, vmName, "tcp:" + cmd.getDestinationIp(), _migrateSpeed);
_storagePoolMgr.disconnectPhysicalDisksViaVmSpec(cmd.getVirtualMachine());
} catch (LibvirtException e) {
@ -3159,8 +3103,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
String[] splitResult = result.split(":");
int i = 0;
while (i < splitResult.length - 1) {
stats[0] += (new Long(splitResult[i++])).longValue();
stats[1] += (new Long(splitResult[i++])).longValue();
stats[0] += Long.parseLong(splitResult[i++]);
stats[1] += Long.parseLong(splitResult[i++]);
}
}
return stats;
@ -3201,8 +3145,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
String[] splitResult = result.split(":");
int i = 0;
while (i < splitResult.length - 1) {
stats[0] += (new Long(splitResult[i++])).longValue();
stats[1] += (new Long(splitResult[i++])).longValue();
stats[0] += Long.parseLong(splitResult[i++]);
stats[1] += Long.parseLong(splitResult[i++]);
}
}
return stats;
@ -3488,7 +3432,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
GuestResourceDef grd = new GuestResourceDef();
if (vmTO.getMinRam() != vmTO.getMaxRam()) {
if (vmTO.getMinRam() != vmTO.getMaxRam() && !_noMemBalloon) {
grd.setMemBalloning(true);
grd.setCurrentMem(vmTO.getMinRam() / 1024);
grd.setMemorySize(vmTO.getMaxRam() / 1024);

View File

@ -162,6 +162,8 @@ public class LibvirtVMDef {
}
if (_memBalloning) {
resBuidler.append("<devices>\n" + "<memballoon model='virtio'/>\n" + "</devices>\n");
} else {
resBuidler.append("<devices>\n" + "<memballoon model='none'/>\n" + "</devices>\n");
}
if (_vcpu != -1) {
resBuidler.append("<vcpu>" + _vcpu + "</vcpu>\n");

View File

@ -386,7 +386,7 @@ public class LibvirtStorageAdaptor implements StorageAdaptor {
LibvirtStoragePool libvirtPool = (LibvirtStoragePool)pool;
try {
StorageVol vol = this.getVolume(libvirtPool.getPool(), volumeUuid);
StorageVol vol = getVolume(libvirtPool.getPool(), volumeUuid);
KVMPhysicalDisk disk;
LibvirtStorageVolumeDef voldef = getStorageVolumeDef(libvirtPool.getPool().getConnect(), vol);
disk = new KVMPhysicalDisk(vol.getPath(), vol.getName(), pool);
@ -471,7 +471,7 @@ public class LibvirtStorageAdaptor implements StorageAdaptor {
String targetPath = pdef.getTargetPath();
if (targetPath != null && targetPath.equals(path)) {
s_logger.debug("Storage pool utilizing path '" + path + "' already exists as pool " + poolname +
", undefining so we can re-define with correct name " + name);
", undefining so we can re-define with correct name " + name);
if (p.isPersistent() == 1) {
p.destroy();
p.undefine();
@ -527,8 +527,8 @@ public class LibvirtStorageAdaptor implements StorageAdaptor {
String error = e.toString();
if (error.contains("Storage source conflict")) {
throw new CloudRuntimeException("A pool matching this location already exists in libvirt, " +
" but has a different UUID/Name. Cannot create new pool without first " + " removing it. Check for inactive pools via 'virsh pool-list --all'. " +
error);
" but has a different UUID/Name. Cannot create new pool without first " + " removing it. Check for inactive pools via 'virsh pool-list --all'. " +
error);
} else {
throw new CloudRuntimeException(error);
}
@ -556,7 +556,7 @@ public class LibvirtStorageAdaptor implements StorageAdaptor {
/*
* Some storage pools, like RBD also have 'secret' information stored in libvirt
* Destroy them if they exist
*/
*/
try {
s = conn.secretLookupByUUIDString(uuid);
} catch (LibvirtException e) {
@ -580,7 +580,7 @@ public class LibvirtStorageAdaptor implements StorageAdaptor {
if (e.toString().contains("exit status 16")) {
String targetPath = _mountPoint + File.separator + uuid;
s_logger.error("deleteStoragePool removed pool from libvirt, but libvirt had trouble" + "unmounting the pool. Trying umount location " + targetPath +
"again in a few seconds");
"again in a few seconds");
String result = Script.runSimpleBashScript("sleep 5 && umount " + targetPath);
if (result == null) {
s_logger.error("Succeeded in unmounting " + targetPath);
@ -624,7 +624,7 @@ public class LibvirtStorageAdaptor implements StorageAdaptor {
IoCTX io = r.ioCtxCreate(pool.getSourceDir());
Rbd rbd = new Rbd(io);
rbd.create(name, size, this.rbdFeatures, this.rbdOrder);
rbd.create(name, size, rbdFeatures, rbdOrder);
r.ioCtxDestroy(io);
} catch (RadosException e) {
@ -702,7 +702,7 @@ public class LibvirtStorageAdaptor implements StorageAdaptor {
try {
Connect conn = LibvirtConnection.getConnection();
StoragePool pool = conn.storagePoolLookupByUUIDString(poolUuid);
conn.storagePoolLookupByUUIDString(poolUuid);
deleteStoragePool(poolUuid);
@ -753,7 +753,7 @@ public class LibvirtStorageAdaptor implements StorageAdaptor {
LibvirtStoragePool libvirtPool = (LibvirtStoragePool)pool;
try {
StorageVol vol = this.getVolume(libvirtPool.getPool(), uuid);
StorageVol vol = getVolume(libvirtPool.getPool(), uuid);
deleteVol(libvirtPool, vol);
vol.free();
return true;
@ -784,7 +784,7 @@ public class LibvirtStorageAdaptor implements StorageAdaptor {
So for RBD we don't create the image, but let qemu-img do that for us.
We then create a KVMPhysicalDisk object that we can return
*/
*/
try {
if (destPool.getType() != StoragePoolType.RBD) {
disk = destPool.createPhysicalDisk(newUuid, format, template.getVirtualSize());
@ -815,8 +815,8 @@ public class LibvirtStorageAdaptor implements StorageAdaptor {
QemuImg qemu = new QemuImg(timeout);
QemuImgFile srcFile;
QemuImgFile destFile =
new QemuImgFile(KVMPhysicalDisk.RBDStringBuilder(destPool.getSourceHost(), destPool.getSourcePort(), destPool.getAuthUserName(),
destPool.getAuthSecret(), disk.getPath()));
new QemuImgFile(KVMPhysicalDisk.RBDStringBuilder(destPool.getSourceHost(), destPool.getSourcePort(), destPool.getAuthUserName(),
destPool.getAuthSecret(), disk.getPath()));
destFile.setFormat(format);
if (srcPool.getType() != StoragePoolType.RBD) {
@ -850,9 +850,9 @@ public class LibvirtStorageAdaptor implements StorageAdaptor {
if (srcImage.isOldFormat()) {
/* The source image is RBD format 1, we have to do a regular copy */
s_logger.debug("The source image " + srcPool.getSourceDir() + "/" + template.getName() +
" is RBD format 1. We have to perform a regular copy (" + template.getVirtualSize() + " bytes)");
" is RBD format 1. We have to perform a regular copy (" + template.getVirtualSize() + " bytes)");
rbd.create(disk.getName(), template.getVirtualSize(), this.rbdFeatures, this.rbdOrder);
rbd.create(disk.getName(), template.getVirtualSize(), rbdFeatures, rbdOrder);
RbdImage destImage = rbd.open(disk.getName());
s_logger.debug("Starting to copy " + srcImage.getName() + " to " + destImage.getName() + " in Ceph pool " + srcPool.getSourceDir());
@ -862,10 +862,10 @@ public class LibvirtStorageAdaptor implements StorageAdaptor {
rbd.close(destImage);
} else {
s_logger.debug("The source image " + srcPool.getSourceDir() + "/" + template.getName() +
" is RBD format 2. We will perform a RBD clone using snapshot " + this.rbdTemplateSnapName);
" is RBD format 2. We will perform a RBD clone using snapshot " + rbdTemplateSnapName);
/* The source image is format 2, we can do a RBD snapshot+clone (layering) */
rbd.clone(template.getName(), this.rbdTemplateSnapName, io, disk.getName(), this.rbdFeatures, this.rbdOrder);
s_logger.debug("Succesfully cloned " + template.getName() + "@" + this.rbdTemplateSnapName + " to " + disk.getName());
rbd.clone(template.getName(), rbdTemplateSnapName, io, disk.getName(), rbdFeatures, rbdOrder);
s_logger.debug("Succesfully cloned " + template.getName() + "@" + rbdTemplateSnapName + " to " + disk.getName());
}
rbd.close(srcImage);
@ -893,14 +893,14 @@ public class LibvirtStorageAdaptor implements StorageAdaptor {
Rbd dRbd = new Rbd(dIO);
s_logger.debug("Creating " + disk.getName() + " on the destination cluster " + rDest.confGet("mon_host") + " in pool " +
destPool.getSourceDir());
dRbd.create(disk.getName(), template.getVirtualSize(), this.rbdFeatures, this.rbdOrder);
destPool.getSourceDir());
dRbd.create(disk.getName(), template.getVirtualSize(), rbdFeatures, rbdOrder);
RbdImage srcImage = sRbd.open(template.getName());
RbdImage destImage = dRbd.open(disk.getName());
s_logger.debug("Copying " + template.getName() + " from Ceph cluster " + rSrc.confGet("mon_host") + " to " + disk.getName() + " on cluster " +
rDest.confGet("mon_host"));
rDest.confGet("mon_host"));
sRbd.copy(srcImage, destImage);
sRbd.close(srcImage);
@ -923,7 +923,7 @@ public class LibvirtStorageAdaptor implements StorageAdaptor {
}
if (disk == null) {
throw new CloudRuntimeException("Failed to create " + disk.getPath() + " from template " + template.getName());
throw new CloudRuntimeException("Failed to create disk from template " + template.getName());
}
return disk;
@ -942,7 +942,7 @@ public class LibvirtStorageAdaptor implements StorageAdaptor {
try {
String[] vols = virtPool.listVolumes();
for (String volName : vols) {
KVMPhysicalDisk disk = this.getPhysicalDisk(volName, pool);
KVMPhysicalDisk disk = getPhysicalDisk(volName, pool);
disks.add(disk);
}
return disks;
@ -1036,11 +1036,11 @@ public class LibvirtStorageAdaptor implements StorageAdaptor {
}
} else if ((srcPool.getType() != StoragePoolType.RBD) && (destPool.getType() == StoragePoolType.RBD)) {
/**
* Qemu doesn't support writing to RBD format 2 directly, so we have to write to a temporary RAW file first
* which we then convert to RBD format 2.
*
* A HUGE performance gain can be achieved here if QCOW2 -> RBD format 2 can be done in one step
*/
* Qemu doesn't support writing to RBD format 2 directly, so we have to write to a temporary RAW file first
* which we then convert to RBD format 2.
*
* A HUGE performance gain can be achieved here if QCOW2 -> RBD format 2 can be done in one step
*/
s_logger.debug("The source image is not RBD, but the destination is. We will convert into RBD format 2");
String sourceFile;
boolean useTmpFile = false;
@ -1069,7 +1069,7 @@ public class LibvirtStorageAdaptor implements StorageAdaptor {
Rbd rbd = new Rbd(io);
s_logger.debug("Creating RBD image " + name + " in Ceph pool " + destPool.getSourceDir() + " with RBD format 2");
rbd.create(name, disk.getVirtualSize(), this.rbdFeatures, this.rbdOrder);
rbd.create(name, disk.getVirtualSize(), rbdFeatures, rbdOrder);
RbdImage image = rbd.open(name);
@ -1098,10 +1098,10 @@ public class LibvirtStorageAdaptor implements StorageAdaptor {
}
/* Snapshot the image and protect that snapshot so we can clone (layer) from it */
s_logger.debug("Creating RBD snapshot " + this.rbdTemplateSnapName + " on image " + name);
image.snapCreate(this.rbdTemplateSnapName);
s_logger.debug("Protecting RBD snapshot " + this.rbdTemplateSnapName + " on image " + name);
image.snapProtect(this.rbdTemplateSnapName);
s_logger.debug("Creating RBD snapshot " + rbdTemplateSnapName + " on image " + name);
image.snapCreate(rbdTemplateSnapName);
s_logger.debug("Protecting RBD snapshot " + rbdTemplateSnapName + " on image " + name);
image.snapProtect(rbdTemplateSnapName);
rbd.close(image);
r.ioCtxDestroy(io);
@ -1125,8 +1125,8 @@ public class LibvirtStorageAdaptor implements StorageAdaptor {
it doesn't benefit us. It's better to keep the current code in place which works
*/
srcFile =
new QemuImgFile(KVMPhysicalDisk.RBDStringBuilder(srcPool.getSourceHost(), srcPool.getSourcePort(), srcPool.getAuthUserName(), srcPool.getAuthSecret(),
sourcePath));
new QemuImgFile(KVMPhysicalDisk.RBDStringBuilder(srcPool.getSourceHost(), srcPool.getSourcePort(), srcPool.getAuthUserName(), srcPool.getAuthSecret(),
sourcePath));
srcFile.setFormat(sourceFormat);
destFile = new QemuImgFile(destPath);
destFile.setFormat(destFormat);

View File

@ -0,0 +1,55 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.cloud.hypervisor.kvm.resource;
import junit.framework.TestCase;
import com.cloud.hypervisor.kvm.resource.LibvirtSecretDef.usage;
public class LibvirtSecretDefTest extends TestCase {
public void testVolumeSecretDef() {
String uuid = "db66f42b-a79e-4666-9910-9dfc8a024427";
String name = "myEncryptedQCOW2";
usage use = usage.VOLUME;
LibvirtSecretDef def = new LibvirtSecretDef(use, uuid);
def.setVolumeVolume(name);
String expectedXml = "<secret ephemeral='no' private='no'>\n<uuid>" + uuid + "</uuid>\n" +
"<usage type='" + use.toString() + "'>\n<volume>" + name + "</volume>\n</usage>\n</secret>\n";
assertEquals(expectedXml, def.toString());
}
public void testCephSecretDef() {
String uuid = "a9febe83-ac5c-467a-bf19-eb75325ec23c";
String name = "admin";
usage use = usage.CEPH;
LibvirtSecretDef def = new LibvirtSecretDef(use, uuid);
def.setCephName(name);
String expectedXml = "<secret ephemeral='no' private='no'>\n<uuid>" + uuid + "</uuid>\n" +
"<usage type='" + use.toString() + "'>\n<name>" + name + "</name>\n</usage>\n</secret>\n";
assertEquals(expectedXml, def.toString());
}
}

View File

@ -0,0 +1,84 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.cloud.hypervisor.kvm.resource;
import junit.framework.TestCase;
import com.cloud.hypervisor.kvm.resource.LibvirtStoragePoolDef.poolType;
import com.cloud.hypervisor.kvm.resource.LibvirtStoragePoolDef.authType;
public class LibvirtStoragePoolDefTest extends TestCase {
public void testSetGetStoragePool() {
poolType type = poolType.NETFS;
String name = "myNFSPool";
String uuid = "d7846cb0-f610-4a5b-8d38-ee6e8d63f37b";
String host = "127.0.0.1";
String dir = "/export/primary";
String targetPath = "/mnt/" + uuid;
int port = 1234;
LibvirtStoragePoolDef pool = new LibvirtStoragePoolDef(type, name, uuid, host, port, dir, targetPath);
assertEquals(type, pool.getPoolType());
assertEquals(name, pool.getPoolName());
assertEquals(host, pool.getSourceHost());
assertEquals(port, pool.getSourcePort());
assertEquals(dir, pool.getSourceDir());
assertEquals(targetPath, pool.getTargetPath());
}
public void testNfsStoragePool() {
poolType type = poolType.NETFS;
String name = "myNFSPool";
String uuid = "89a605bc-d470-4637-b3df-27388be452f5";
String host = "127.0.0.1";
String dir = "/export/primary";
String targetPath = "/mnt/" + uuid;
LibvirtStoragePoolDef pool = new LibvirtStoragePoolDef(type, name, uuid, host, dir, targetPath);
String expectedXml = "<pool type='" + type.toString() + "'>\n<name>" + name + "</name>\n<uuid>" + uuid + "</uuid>\n" +
"<source>\n<host name='" + host + "'/>\n<dir path='" + dir + "'/>\n</source>\n<target>\n" +
"<path>" + targetPath + "</path>\n</target>\n</pool>\n";
assertEquals(expectedXml, pool.toString());
}
public void testRbdStoragePool() {
poolType type = poolType.RBD;
String name = "myRBDPool";
String uuid = "921ef8b2-955a-4c18-a697-66bb9adf6131";
String host = "127.0.0.1";
String dir = "cloudstackrbdpool";
String authUsername = "admin";
String secretUuid = "08c2fa02-50d0-4a78-8903-b742d3f34934";
authType auth = authType.CEPH;
int port = 6789;
LibvirtStoragePoolDef pool = new LibvirtStoragePoolDef(type, name, uuid, host, port, dir, authUsername, auth, secretUuid);
String expectedXml = "<pool type='" + type.toString() + "'>\n<name>" + name + "</name>\n<uuid>" + uuid + "</uuid>\n" +
"<source>\n<host name='" + host + "' port='" + port + "'/>\n<name>" + dir + "</name>\n" +
"<auth username='" + authUsername + "' type='" + auth.toString() + "'>\n<secret uuid='" + secretUuid + "'/>\n" +
"</auth>\n</source>\n</pool>\n";
assertEquals(expectedXml, pool.toString());
}
}

View File

@ -20,6 +20,7 @@
package com.cloud.hypervisor.kvm.resource;
import junit.framework.TestCase;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef;
public class LibvirtVMDefTest extends TestCase {
@ -65,4 +66,28 @@ public class LibvirtVMDefTest extends TestCase {
}
public void testDiskDef() {
String filePath = "/var/lib/libvirt/images/disk.qcow2";
String diskLabel = "vda";
DiskDef disk = new DiskDef();
DiskDef.diskBus bus = DiskDef.diskBus.VIRTIO;
DiskDef.diskFmtType type = DiskDef.diskFmtType.QCOW2;
DiskDef.diskCacheMode cacheMode = DiskDef.diskCacheMode.WRITEBACK;
disk.defFileBasedDisk(filePath, diskLabel, bus, type);
disk.setCacheMode(cacheMode);
assertEquals(filePath, disk.getDiskPath());
assertEquals(diskLabel, disk.getDiskLabel());
assertEquals(bus, disk.getBusType());
assertEquals(DiskDef.deviceType.DISK, disk.getDeviceType());
String xmlDef = disk.toString();
String expectedXml = "<disk device='disk' type='file'>\n<driver name='qemu' type='" + type.toString() + "' cache='" + cacheMode.toString() + "' />\n" +
"<source file='" + filePath + "'/>\n<target dev='" + diskLabel + "' bus='" + bus.toString() + "'/>\n</disk>\n";
assertEquals(xmlDef, expectedXml);
}
}

View File

@ -32,6 +32,8 @@ import javax.ejb.Local;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import com.cloud.user.AccountManager;
import org.apache.cloudstack.context.CallContext;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
@ -87,6 +89,7 @@ public class MockAgentManagerImpl extends ManagerBase implements MockAgentManage
MockStorageManager _storageMgr = null;
@Inject
ResourceManager _resourceMgr;
@Inject private AccountManager _accountMgr;
SimulatorSecondaryDiscoverer discoverer;
@Inject
@ -303,8 +306,10 @@ public class MockAgentManagerImpl extends ManagerBase implements MockAgentManage
@Override
@DB
public void run() {
CallContext.register(_accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
if (this.mode.equalsIgnoreCase("Stop")) {
handleSystemVMStop();
CallContext.unregister();
return;
}
@ -359,10 +364,12 @@ public class MockAgentManagerImpl extends ManagerBase implements MockAgentManage
_resourceMgr.discoverHosts(cmd);
} catch (DiscoveryException e) {
s_logger.debug("Failed to discover host: " + e.toString());
CallContext.unregister();
return;
}
} catch (ConfigurationException e) {
s_logger.debug("Failed to load secondary storage resource: " + e.toString());
CallContext.unregister();
return;
}
}

View File

@ -27,13 +27,15 @@ import javax.persistence.Table;
import com.cloud.utils.NumbersUtil;
/**
* LegacyZoneVO contains id of CloudStack zone containing clusters from multiple VMware vCetners and/or VMware Datacenters.
*/
* LegacyZoneVO contains id of CloudStack zone containing clusters from multiple VMware vCetners and/or VMware Datacenters.
*/
@Entity
@Table(name = "legacy_zones")
public class LegacyZoneVO implements LegacyZone {
private static final long serialVersionUID = -3979866054555152793L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
@ -60,7 +62,7 @@ public class LegacyZoneVO implements LegacyZone {
@Override
public boolean equals(Object obj) {
if (obj instanceof LegacyZoneVO) {
return ((LegacyZoneVO)obj).getId() == this.getId();
return ((LegacyZoneVO)obj).getId() == getId();
} else {
return false;
}
@ -70,7 +72,7 @@ public class LegacyZoneVO implements LegacyZone {
}
public LegacyZoneVO(long zoneId) {
this.id = zoneId;
id = zoneId;
}
public LegacyZoneVO(long id, long zoneId) {

Some files were not shown because too many files have changed in this diff Show More