Skip to content

Commit b21595c

Browse files
Harikrishna Patnalayadvr
authored andcommitted
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>
1 parent 15906c0 commit b21595c

15 files changed

Lines changed: 354 additions & 11 deletions

api/src/com/cloud/event/EventTypes.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ public class EventTypes {
2626
public static final String EVENT_VM_UPDATE = "VM.UPDATE";
2727
public static final String EVENT_VM_UPGRADE = "VM.UPGRADE";
2828
public static final String EVENT_VM_RESETPASSWORD = "VM.RESETPASSWORD";
29+
public static final String EVENT_VM_RESETSSHKEY = "VM.RESETSSHKEY";
2930
public static final String EVENT_VM_MIGRATE = "VM.MIGRATE";
3031
public static final String EVENT_VM_MOVE = "VM.MOVE";
3132
public static final String EVENT_VM_RESTORE = "VM.RESTORE";

api/src/com/cloud/network/element/UserDataServiceProvider.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,4 +30,5 @@ public interface UserDataServiceProvider extends NetworkElement {
3030
public boolean addPasswordAndUserdata(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException;
3131
boolean savePassword(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm) throws ResourceUnavailableException;
3232
boolean saveUserData(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm) throws ResourceUnavailableException;
33+
boolean saveSSHKey(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, String SSHPublicKey) throws ResourceUnavailableException;
3334
}

api/src/com/cloud/vm/UserVmService.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
import org.apache.cloudstack.api.command.user.vm.RebootVMCmd;
3434
import org.apache.cloudstack.api.command.admin.vm.RecoverVMCmd;
3535
import org.apache.cloudstack.api.command.user.vm.ResetVMPasswordCmd;
36+
import org.apache.cloudstack.api.command.user.vm.ResetVMSSHKeyCmd;
3637
import org.apache.cloudstack.api.command.user.vm.RestoreVMCmd;
3738
import org.apache.cloudstack.api.command.user.vm.UpgradeVMCmd;
3839

@@ -88,6 +89,15 @@ public interface UserVmService {
8889
*/
8990
UserVm resetVMPassword(ResetVMPasswordCmd cmd, String password) throws ResourceUnavailableException, InsufficientCapacityException;
9091

92+
/**
93+
* Resets the SSH Key of a virtual machine.
94+
*
95+
* @param cmd
96+
* - the command specifying vmId, Keypair name
97+
* @return the VM if reset worked successfully, null otherwise
98+
*/
99+
UserVm resetVMSSHKey(ResetVMSSHKeyCmd cmd) throws ResourceUnavailableException, InsufficientCapacityException;
100+
91101
/**
92102
* Attaches the specified volume to the specified VM
93103
*
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
// Licensed to the Apache Software Foundation (ASF) under one
2+
// or more contributor license agreements. See the NOTICE file
3+
// distributed with this work for additional information
4+
// regarding copyright ownership. The ASF licenses this file
5+
// to you under the Apache License, Version 2.0 (the
6+
// "License"); you may not use this file except in compliance
7+
// with the License. You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing,
12+
// software distributed under the License is distributed on an
13+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
// KIND, either express or implied. See the License for the
15+
// specific language governing permissions and limitations
16+
// under the License.
17+
18+
package org.apache.cloudstack.api.command.user.vm;
19+
20+
import org.apache.log4j.Logger;
21+
22+
import org.apache.cloudstack.api.ApiConstants;
23+
import org.apache.cloudstack.api.ApiErrorCode;
24+
import org.apache.cloudstack.api.BaseAsyncCmd;
25+
import org.apache.cloudstack.api.BaseCmd;
26+
import org.apache.cloudstack.api.APICommand;
27+
import org.apache.cloudstack.api.Parameter;
28+
import org.apache.cloudstack.api.ServerApiException;
29+
import org.apache.cloudstack.api.response.UserVmResponse;
30+
import org.apache.cloudstack.api.response.DomainResponse;
31+
import org.apache.cloudstack.api.response.ProjectResponse;
32+
import com.cloud.async.AsyncJob;
33+
import com.cloud.user.Account;
34+
import com.cloud.user.UserContext;
35+
import com.cloud.uservm.UserVm;
36+
import com.cloud.event.EventTypes;
37+
import com.cloud.exception.InsufficientCapacityException;
38+
import com.cloud.exception.ResourceUnavailableException;
39+
40+
@APICommand(name = "resetSSHKeyForVirtualMachine", responseObject = UserVmResponse.class, description = "Resets the SSH Key for virtual machine. " +
41+
"The virtual machine must be in a \"Stopped\" state. [async]")
42+
public class ResetVMSSHKeyCmd extends BaseAsyncCmd {
43+
44+
public static final Logger s_logger = Logger.getLogger(ResetVMSSHKeyCmd.class.getName());
45+
46+
private static final String s_name = "resetSSHKeyforvirtualmachineresponse";
47+
48+
/////////////////////////////////////////////////////
49+
//////////////// API parameters /////////////////////
50+
/////////////////////////////////////////////////////
51+
52+
@Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = UserVmResponse.class, required = true, description = "The ID of the virtual machine")
53+
private Long id;
54+
55+
@Parameter(name = ApiConstants.SSH_KEYPAIR, type = CommandType.STRING, required = true, description = "name of the ssh key pair used to login to the virtual machine")
56+
private String name;
57+
58+
59+
//Owner information
60+
@Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "an optional account for the ssh key. Must be used with domainId.")
61+
private String accountName;
62+
63+
@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.")
64+
private Long domainId;
65+
66+
@Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, entityType = ProjectResponse.class, description = "an optional project for the ssh key")
67+
private Long projectId;
68+
69+
70+
/////////////////////////////////////////////////////
71+
/////////////////// Accessors ///////////////////////
72+
/////////////////////////////////////////////////////
73+
74+
public String getName() {
75+
return name;
76+
}
77+
78+
79+
public Long getId() {
80+
return id;
81+
}
82+
83+
public String getAccountName() {
84+
return accountName;
85+
}
86+
87+
public Long getDomainId() {
88+
return domainId;
89+
}
90+
91+
public Long getProjectId() {
92+
return projectId;
93+
}
94+
95+
/////////////////////////////////////////////////////
96+
/////////////// API Implementation///////////////////
97+
/////////////////////////////////////////////////////
98+
99+
100+
@Override
101+
public String getEventType() {
102+
return EventTypes.EVENT_VM_RESETSSHKEY;
103+
}
104+
105+
@Override
106+
public String getEventDescription() {
107+
return "resetting SSHKey for vm: " + getId();
108+
}
109+
110+
public AsyncJob.Type getInstanceType() {
111+
return AsyncJob.Type.VirtualMachine;
112+
}
113+
114+
115+
@Override
116+
public String getCommandName() {
117+
return s_name;
118+
}
119+
120+
@Override
121+
public long getEntityOwnerId() {
122+
UserVm vm = _responseGenerator.findUserVmById(getId());
123+
if (vm != null) {
124+
return vm.getAccountId();
125+
}
126+
127+
return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked
128+
}
129+
130+
public Long getInstanceId() {
131+
return getId();
132+
}
133+
134+
135+
@Override
136+
public void execute() throws ResourceUnavailableException,
137+
InsufficientCapacityException {
138+
139+
UserContext.current().setEventDetails("Vm Id: " + getId());
140+
UserVm result = _userVmService.resetVMSSHKey(this);
141+
142+
if (result != null) {
143+
UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", result).get(0);
144+
response.setResponseName(getCommandName());
145+
this.setResponseObject(response);
146+
} else {
147+
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to reset vm SSHKey");
148+
}
149+
}
150+
151+
}

client/tomcatconf/commands.properties.in

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ rebootVirtualMachine=15
6060
startVirtualMachine=15
6161
stopVirtualMachine=15
6262
resetPasswordForVirtualMachine=15
63+
resetSSHKeyForVirtualMachine=15
6364
updateVirtualMachine=15
6465
listVirtualMachines=15
6566
getVMPassword=15

server/src/com/cloud/network/NetworkManager.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,8 @@ boolean associateIpAddressListToAccount(long userId, long accountId, long zoneId
144144

145145
UserDataServiceProvider getPasswordResetProvider(Network network);
146146

147+
UserDataServiceProvider getSSHKeyResetProvider(Network network);
148+
147149
boolean applyIpAssociations(Network network, boolean continueOnError) throws ResourceUnavailableException;
148150

149151
boolean applyIpAssociations(Network network, boolean rulesRevoked, boolean continueOnError, List<? extends PublicIpAddress> publicIps) throws ResourceUnavailableException;

server/src/com/cloud/network/NetworkManagerImpl.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2626,6 +2626,18 @@ public UserDataServiceProvider getPasswordResetProvider(Network network) {
26262626
return (UserDataServiceProvider)_networkModel.getElementImplementingProvider(passwordProvider);
26272627
}
26282628

2629+
@Override
2630+
public UserDataServiceProvider getSSHKeyResetProvider(Network network) {
2631+
String SSHKeyProvider = _ntwkSrvcDao.getProviderForServiceInNetwork(network.getId(), Service.UserData);
2632+
2633+
if (SSHKeyProvider == null) {
2634+
s_logger.debug("Network " + network + " doesn't support service " + Service.UserData.getName());
2635+
return null;
2636+
}
2637+
2638+
return (UserDataServiceProvider)getElementImplementingProvider(SSHKeyProvider);
2639+
}
2640+
26292641
protected boolean isSharedNetworkOfferingWithServices(long networkOfferingId) {
26302642
NetworkOfferingVO networkOffering = _networkOfferingDao.findById(networkOfferingId);
26312643
if ( (networkOffering.getGuestType() == Network.GuestType.Shared) && (

server/src/com/cloud/network/element/CloudZonesNetworkElement.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,12 @@ public boolean savePassword(Network network, NicProfile nic, VirtualMachineProfi
251251
return false;
252252
}
253253

254+
@Override
255+
public boolean saveSSHKey(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, String SSHPublicKey) throws ResourceUnavailableException {
256+
// TODO Auto-generated method stub
257+
return false;
258+
}
259+
254260
@Override
255261
public boolean saveUserData(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm) throws ResourceUnavailableException {
256262
// TODO Auto-generated method stub

server/src/com/cloud/network/element/VirtualRouterElement.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -664,6 +664,24 @@ public boolean savePassword(Network network, NicProfile nic, VirtualMachineProfi
664664
return _routerMgr.savePasswordToRouter(network, nic, uservm, routers);
665665
}
666666

667+
@Override
668+
public boolean saveSSHKey(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, String SSHPublicKey)
669+
throws ResourceUnavailableException {
670+
if (!canHandle(network, null)) {
671+
return false;
672+
}
673+
List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER);
674+
if (routers == null || routers.isEmpty()) {
675+
s_logger.debug("Can't find virtual router element in network " + network.getId());
676+
return true;
677+
}
678+
679+
@SuppressWarnings("unchecked")
680+
VirtualMachineProfile<UserVm> uservm = (VirtualMachineProfile<UserVm>) vm;
681+
682+
return _routerMgr.saveSSHPublicKeyToRouter(network, nic, uservm, routers, SSHPublicKey);
683+
}
684+
667685
@Override
668686
public boolean saveUserData(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm)
669687
throws ResourceUnavailableException {

server/src/com/cloud/network/router/VirtualNetworkApplianceManager.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,9 @@ public interface VirtualNetworkApplianceManager extends Manager, VirtualNetworkA
6363
boolean savePasswordToRouter(Network network, NicProfile nic, VirtualMachineProfile<UserVm> profile,
6464
List<? extends VirtualRouter> routers) throws ResourceUnavailableException;
6565

66+
boolean saveSSHPublicKeyToRouter(Network network, NicProfile nic, VirtualMachineProfile<UserVm> profile,
67+
List<? extends VirtualRouter> routers, String SSHPublicKey) throws ResourceUnavailableException;
68+
6669
boolean saveUserDataToRouter(Network network, NicProfile nic, VirtualMachineProfile<UserVm> profile,
6770
List<? extends VirtualRouter> routers) throws ResourceUnavailableException;
6871

0 commit comments

Comments
 (0)