CLOUDSTACK-297: Reset SSH key to access VM

This feature provides resetting a SSH key for an existing VM which means,
setting the old ssh key that is assigned to the VM previously with the new ssh
key.

Signed-off-by: Harikrishna Patnala <harikrishna.patnala@citrix.com>
Signed-off-by: Rohit Yadav <bhaisaab@apache.org>
This commit is contained in:
Harikrishna Patnala 2013-01-30 17:09:04 -08:00 committed by Rohit Yadav
parent 15906c03ca
commit b21595c10d
15 changed files with 354 additions and 11 deletions

View File

@ -26,6 +26,7 @@ public class EventTypes {
public static final String EVENT_VM_UPDATE = "VM.UPDATE";
public static final String EVENT_VM_UPGRADE = "VM.UPGRADE";
public static final String EVENT_VM_RESETPASSWORD = "VM.RESETPASSWORD";
public static final String EVENT_VM_RESETSSHKEY = "VM.RESETSSHKEY";
public static final String EVENT_VM_MIGRATE = "VM.MIGRATE";
public static final String EVENT_VM_MOVE = "VM.MOVE";
public static final String EVENT_VM_RESTORE = "VM.RESTORE";

View File

@ -30,4 +30,5 @@ public interface UserDataServiceProvider extends NetworkElement {
public boolean addPasswordAndUserdata(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException;
boolean savePassword(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm) throws ResourceUnavailableException;
boolean saveUserData(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm) throws ResourceUnavailableException;
boolean saveSSHKey(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, String SSHPublicKey) throws ResourceUnavailableException;
}

View File

@ -33,6 +33,7 @@ import org.apache.cloudstack.api.command.user.volume.DetachVolumeCmd;
import org.apache.cloudstack.api.command.user.vm.RebootVMCmd;
import org.apache.cloudstack.api.command.admin.vm.RecoverVMCmd;
import org.apache.cloudstack.api.command.user.vm.ResetVMPasswordCmd;
import org.apache.cloudstack.api.command.user.vm.ResetVMSSHKeyCmd;
import org.apache.cloudstack.api.command.user.vm.RestoreVMCmd;
import org.apache.cloudstack.api.command.user.vm.UpgradeVMCmd;
@ -88,6 +89,15 @@ public interface UserVmService {
*/
UserVm resetVMPassword(ResetVMPasswordCmd cmd, String password) throws ResourceUnavailableException, InsufficientCapacityException;
/**
* Resets the SSH Key of a virtual machine.
*
* @param cmd
* - the command specifying vmId, Keypair name
* @return the VM if reset worked successfully, null otherwise
*/
UserVm resetVMSSHKey(ResetVMSSHKeyCmd cmd) throws ResourceUnavailableException, InsufficientCapacityException;
/**
* Attaches the specified volume to the specified VM
*

View File

@ -0,0 +1,151 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES 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.user.vm;
import org.apache.log4j.Logger;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.BaseAsyncCmd;
import org.apache.cloudstack.api.BaseCmd;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.UserVmResponse;
import org.apache.cloudstack.api.response.DomainResponse;
import org.apache.cloudstack.api.response.ProjectResponse;
import com.cloud.async.AsyncJob;
import com.cloud.user.Account;
import com.cloud.user.UserContext;
import com.cloud.uservm.UserVm;
import com.cloud.event.EventTypes;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.ResourceUnavailableException;
@APICommand(name = "resetSSHKeyForVirtualMachine", responseObject = UserVmResponse.class, description = "Resets the SSH Key for virtual machine. " +
"The virtual machine must be in a \"Stopped\" state. [async]")
public class ResetVMSSHKeyCmd extends BaseAsyncCmd {
public static final Logger s_logger = Logger.getLogger(ResetVMSSHKeyCmd.class.getName());
private static final String s_name = "resetSSHKeyforvirtualmachineresponse";
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
@Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = UserVmResponse.class, required = true, description = "The ID of the virtual machine")
private Long id;
@Parameter(name = ApiConstants.SSH_KEYPAIR, type = CommandType.STRING, required = true, description = "name of the ssh key pair used to login to the virtual machine")
private String name;
//Owner information
@Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "an optional account for the ssh key. Must be used with domainId.")
private String accountName;
@Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, entityType = DomainResponse.class, description = "an optional domainId for the virtual machine. If the account parameter is used, domainId must also be used.")
private Long domainId;
@Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, entityType = ProjectResponse.class, description = "an optional project for the ssh key")
private Long projectId;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
public String getName() {
return name;
}
public Long getId() {
return id;
}
public String getAccountName() {
return accountName;
}
public Long getDomainId() {
return domainId;
}
public Long getProjectId() {
return projectId;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@Override
public String getEventType() {
return EventTypes.EVENT_VM_RESETSSHKEY;
}
@Override
public String getEventDescription() {
return "resetting SSHKey for vm: " + getId();
}
public AsyncJob.Type getInstanceType() {
return AsyncJob.Type.VirtualMachine;
}
@Override
public String getCommandName() {
return s_name;
}
@Override
public long getEntityOwnerId() {
UserVm vm = _responseGenerator.findUserVmById(getId());
if (vm != null) {
return vm.getAccountId();
}
return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked
}
public Long getInstanceId() {
return getId();
}
@Override
public void execute() throws ResourceUnavailableException,
InsufficientCapacityException {
UserContext.current().setEventDetails("Vm Id: " + getId());
UserVm result = _userVmService.resetVMSSHKey(this);
if (result != null) {
UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", result).get(0);
response.setResponseName(getCommandName());
this.setResponseObject(response);
} else {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to reset vm SSHKey");
}
}
}

View File

@ -60,6 +60,7 @@ rebootVirtualMachine=15
startVirtualMachine=15
stopVirtualMachine=15
resetPasswordForVirtualMachine=15
resetSSHKeyForVirtualMachine=15
updateVirtualMachine=15
listVirtualMachines=15
getVMPassword=15

View File

@ -144,6 +144,8 @@ public interface NetworkManager {
UserDataServiceProvider getPasswordResetProvider(Network network);
UserDataServiceProvider getSSHKeyResetProvider(Network network);
boolean applyIpAssociations(Network network, boolean continueOnError) throws ResourceUnavailableException;
boolean applyIpAssociations(Network network, boolean rulesRevoked, boolean continueOnError, List<? extends PublicIpAddress> publicIps) throws ResourceUnavailableException;

View File

@ -2626,6 +2626,18 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener {
return (UserDataServiceProvider)_networkModel.getElementImplementingProvider(passwordProvider);
}
@Override
public UserDataServiceProvider getSSHKeyResetProvider(Network network) {
String SSHKeyProvider = _ntwkSrvcDao.getProviderForServiceInNetwork(network.getId(), Service.UserData);
if (SSHKeyProvider == null) {
s_logger.debug("Network " + network + " doesn't support service " + Service.UserData.getName());
return null;
}
return (UserDataServiceProvider)getElementImplementingProvider(SSHKeyProvider);
}
protected boolean isSharedNetworkOfferingWithServices(long networkOfferingId) {
NetworkOfferingVO networkOffering = _networkOfferingDao.findById(networkOfferingId);
if ( (networkOffering.getGuestType() == Network.GuestType.Shared) && (

View File

@ -251,6 +251,12 @@ public class CloudZonesNetworkElement extends AdapterBase implements NetworkElem
return false;
}
@Override
public boolean saveSSHKey(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, String SSHPublicKey) throws ResourceUnavailableException {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean saveUserData(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm) throws ResourceUnavailableException {
// TODO Auto-generated method stub

View File

@ -664,6 +664,24 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
return _routerMgr.savePasswordToRouter(network, nic, uservm, routers);
}
@Override
public boolean saveSSHKey(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, String SSHPublicKey)
throws ResourceUnavailableException {
if (!canHandle(network, null)) {
return false;
}
List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER);
if (routers == null || routers.isEmpty()) {
s_logger.debug("Can't find virtual router element in network " + network.getId());
return true;
}
@SuppressWarnings("unchecked")
VirtualMachineProfile<UserVm> uservm = (VirtualMachineProfile<UserVm>) vm;
return _routerMgr.saveSSHPublicKeyToRouter(network, nic, uservm, routers, SSHPublicKey);
}
@Override
public boolean saveUserData(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm)
throws ResourceUnavailableException {

View File

@ -63,6 +63,9 @@ public interface VirtualNetworkApplianceManager extends Manager, VirtualNetworkA
boolean savePasswordToRouter(Network network, NicProfile nic, VirtualMachineProfile<UserVm> profile,
List<? extends VirtualRouter> routers) throws ResourceUnavailableException;
boolean saveSSHPublicKeyToRouter(Network network, NicProfile nic, VirtualMachineProfile<UserVm> profile,
List<? extends VirtualRouter> routers, String SSHPublicKey) throws ResourceUnavailableException;
boolean saveUserDataToRouter(Network network, NicProfile nic, VirtualMachineProfile<UserVm> profile,
List<? extends VirtualRouter> routers) throws ResourceUnavailableException;

View File

@ -474,6 +474,28 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
});
}
@Override
public boolean saveSSHPublicKeyToRouter(Network network, final NicProfile nic, VirtualMachineProfile<UserVm> profile, List<? extends VirtualRouter> routers, final String SSHPublicKey) throws ResourceUnavailableException {
_userVmDao.loadDetails((UserVmVO) profile.getVirtualMachine());
final VirtualMachineProfile<UserVm> updatedProfile = profile;
return applyRules(network, routers, "save SSHkey entry", false, null, false, new RuleApplier() {
@Override
public boolean execute(Network network, VirtualRouter router) throws ResourceUnavailableException {
// for basic zone, send vm data/password information only to the router in the same pod
Commands cmds = new Commands(OnError.Stop);
NicVO nicVo = _nicDao.findById(nic.getId());
VMTemplateVO template = _templateDao.findByIdIncludingRemoved(updatedProfile.getTemplateId());
if(template != null && template.getEnablePassword()) {
createPasswordCommand(router, updatedProfile, nicVo, cmds);
}
createVmDataCommand(router, updatedProfile.getVirtualMachine(), nicVo, SSHPublicKey, cmds);
return sendCommandsToRouter(router, cmds);
}
});
}
@Override
public boolean saveUserDataToRouter(Network network, final NicProfile nic, VirtualMachineProfile<UserVm> profile, List<? extends VirtualRouter> routers) throws ResourceUnavailableException {
_userVmDao.loadDetails((UserVmVO) profile.getVirtualMachine());

View File

@ -406,6 +406,116 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager
}
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_RESETSSHKEY, eventDescription = "resetting Vm SSHKey", async = true)
public UserVm resetVMSSHKey(ResetVMSSHKeyCmd cmd)
throws ResourceUnavailableException, InsufficientCapacityException {
Account caller = UserContext.current().getCaller();
Account owner = _accountMgr.finalizeOwner(caller, cmd.getAccountName(), cmd.getDomainId(), cmd.getProjectId());
Long vmId = cmd.getId();
UserVmVO userVm = _vmDao.findById(cmd.getId());
_vmDao.loadDetails(userVm);
VMTemplateVO template = _templateDao.findByIdIncludingRemoved(userVm.getTemplateId());
// Do parameters input validation
if (userVm == null) {
throw new InvalidParameterValueException("unable to find a virtual machine by id" + cmd.getId());
}
if (userVm.getState() == State.Error || userVm.getState() == State.Expunging) {
s_logger.error("vm is not in the right state: " + vmId);
throw new InvalidParameterValueException("Vm with specified id is not in the right state");
}
if (userVm.getState() != State.Stopped) {
s_logger.error("vm is not in the right state: " + vmId);
throw new InvalidParameterValueException("Vm " + userVm + " should be stopped to do SSH Key reset");
}
SSHKeyPairVO s = _sshKeyPairDao.findByName(owner.getAccountId(), owner.getDomainId(), cmd.getName());
if (s == null) {
throw new InvalidParameterValueException("A key pair with name '" + cmd.getName() + "' does not exist for account " + owner.getAccountName() + " in specified domain id");
}
_accountMgr.checkAccess(caller, null, true, userVm);
String password = null;
String sshPublicKey = s.getPublicKey();
if (template != null && template.getEnablePassword()) {
password = generateRandomPassword();
}
boolean result = resetVMSSHKeyInternal(vmId, sshPublicKey, password);
if (result) {
userVm.setDetail("SSH.PublicKey", sshPublicKey);
if (template != null && template.getEnablePassword()) {
userVm.setPassword(password);
//update the encrypted password in vm_details table too
if (sshPublicKey != null && !sshPublicKey.equals("") && password != null && !password.equals("saved_password")) {
String encryptedPasswd = RSAHelper.encryptWithSSHPublicKey(sshPublicKey, password);
if (encryptedPasswd == null) {
throw new CloudRuntimeException("Error encrypting password");
}
userVm.setDetail("Encrypted.Password", encryptedPasswd);
}
}
_vmDao.saveDetails(userVm);
} else {
throw new CloudRuntimeException("Failed to reset SSH Key for the virtual machine ");
}
return userVm;
}
private boolean resetVMSSHKeyInternal(Long vmId, String SSHPublicKey, String password) throws ResourceUnavailableException, InsufficientCapacityException {
Long userId = UserContext.current().getCallerUserId();
VMInstanceVO vmInstance = _vmDao.findById(vmId);
VMTemplateVO template = _templateDao.findByIdIncludingRemoved(vmInstance.getTemplateId());
Nic defaultNic = _networkMgr.getDefaultNic(vmId);
if (defaultNic == null) {
s_logger.error("Unable to reset SSH Key for vm " + vmInstance + " as the instance doesn't have default nic");
return false;
}
Network defaultNetwork = _networkDao.findById(defaultNic.getNetworkId());
NicProfile defaultNicProfile = new NicProfile(defaultNic, defaultNetwork, null, null, null,
_networkMgr.isSecurityGroupSupportedInNetwork(defaultNetwork),
_networkMgr.getNetworkTag(template.getHypervisorType(), defaultNetwork));
VirtualMachineProfile<VMInstanceVO> vmProfile = new VirtualMachineProfileImpl<VMInstanceVO>(vmInstance);
if (template != null && template.getEnablePassword()) {
vmProfile.setParameter(VirtualMachineProfile.Param.VmPassword, password);
}
UserDataServiceProvider element = _networkMgr.getSSHKeyResetProvider(defaultNetwork);
if (element == null) {
throw new CloudRuntimeException("Can't find network element for " + Service.UserData.getName() + " provider needed for SSH Key reset");
}
boolean result = element.saveSSHKey(defaultNetwork, defaultNicProfile, vmProfile, SSHPublicKey);
// Need to reboot the virtual machine so that the password gets redownloaded from the DomR, and reset on the VM
if (!result) {
s_logger.debug("Failed to reset SSH Key for the virutal machine; no need to reboot the vm");
return false;
} else {
if (vmInstance.getState() == State.Stopped) {
s_logger.debug("Vm " + vmInstance + " is stopped, not rebooting it as a part of SSH Key reset");
return true;
}
if (rebootVirtualMachine(userId, vmId) == null) {
s_logger.warn("Failed to reboot the vm " + vmInstance);
return false;
} else {
s_logger.debug("Vm " + vmInstance + " is rebooted successfully as a part of SSH Key reset");
return true;
}
}
}
@Override
public boolean stopVirtualMachine(long userId, long vmId) {
boolean status = false;

View File

@ -417,17 +417,18 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkS
return null;
}
@Override
public UserDataServiceProvider getPasswordResetProvider(Network network) {
// TODO Auto-generated method stub
return null;
}
@Override
public UserDataServiceProvider getSSHKeyResetProvider(Network network) {
// TODO Auto-generated method stub
return null;
}
@Override
public PhysicalNetworkServiceProvider updateNetworkServiceProvider(Long id, String state, List<String> enabledServices) {
// TODO Auto-generated method stub

View File

@ -248,6 +248,12 @@ public class MockUserVmManagerImpl implements UserVmManager, UserVmService, Mana
return null;
}
@Override
public UserVm resetVMSSHKey(ResetVMSSHKeyCmd cmd) throws ResourceUnavailableException, InsufficientCapacityException {
// TODO Auto-generated method stub
return null;
}
@Override
public Volume attachVolumeToVM(AttachVolumeCmd cmd) {
// TODO Auto-generated method stub

View File

@ -867,10 +867,6 @@ public class MockNetworkManagerImpl implements NetworkManager, NetworkService, M
return false;
}
/* (non-Javadoc)
* @see com.cloud.network.NetworkManager#getPasswordResetProvider(com.cloud.network.Network)
*/
@ -880,8 +876,11 @@ public class MockNetworkManagerImpl implements NetworkManager, NetworkService, M
return null;
}
@Override
public UserDataServiceProvider getSSHKeyResetProvider(Network network) {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)