Repository navigation
Expand file tree
/
Copy pathAffinityGroupServiceImpl.java
More file actions
488 lines (406 loc) · 20.2 KB
/
Copy pathAffinityGroupServiceImpl.java
File metadata and controls
488 lines (406 loc) · 20.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.affinity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.ejb.Local;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import com.cloud.utils.fsm.StateMachine2;
import org.apache.log4j.Logger;
import org.apache.cloudstack.acl.ControlledEntity;
import org.apache.cloudstack.acl.ControlledEntity.ACLType;
import org.apache.cloudstack.acl.SecurityChecker.AccessType;
import org.apache.cloudstack.affinity.dao.AffinityGroupDao;
import org.apache.cloudstack.affinity.dao.AffinityGroupDomainMapDao;
import org.apache.cloudstack.affinity.dao.AffinityGroupVMMapDao;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.framework.messagebus.MessageBus;
import org.apache.cloudstack.framework.messagebus.PublishScope;
import com.cloud.domain.DomainVO;
import com.cloud.domain.dao.DomainDao;
import com.cloud.event.ActionEvent;
import com.cloud.event.EventTypes;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.DomainManager;
import com.cloud.uservm.UserVm;
import com.cloud.utils.Pair;
import com.cloud.utils.component.Manager;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.EntityManager;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.db.TransactionCallback;
import com.cloud.utils.db.TransactionCallbackNoReturn;
import com.cloud.utils.db.TransactionStatus;
import com.cloud.utils.fsm.StateListener;
import com.cloud.vm.UserVmVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachine.Event;
import com.cloud.vm.VirtualMachine.State;
import com.cloud.vm.dao.UserVmDao;
@Local(value = {AffinityGroupService.class})
public class AffinityGroupServiceImpl extends ManagerBase implements AffinityGroupService, Manager, StateListener<State, VirtualMachine.Event, VirtualMachine> {
public static final Logger s_logger = Logger.getLogger(AffinityGroupServiceImpl.class);
private String _name;
@Inject
AccountManager _accountMgr;
@Inject
AffinityGroupDao _affinityGroupDao;
@Inject
AffinityGroupVMMapDao _affinityGroupVMMapDao;
@Inject
AffinityGroupDomainMapDao _affinityGroupDomainMapDao;
@Inject
private UserVmDao _userVmDao;
@Inject
DomainDao _domainDao;
@Inject
DomainManager _domainMgr;
@Inject
MessageBus _messageBus;
protected List<AffinityGroupProcessor> _affinityProcessors;
public List<AffinityGroupProcessor> getAffinityGroupProcessors() {
return _affinityProcessors;
}
public void setAffinityGroupProcessors(List<AffinityGroupProcessor> affinityProcessors) {
_affinityProcessors = affinityProcessors;
}
@DB
@Override
@ActionEvent(eventType = EventTypes.EVENT_AFFINITY_GROUP_CREATE, eventDescription = "Creating Affinity Group", create = true)
public AffinityGroup createAffinityGroup(String account, Long projectId, Long domainId, String affinityGroupName, String affinityGroupType, String description) {
//validate the affinityGroupType
Map<String, AffinityGroupProcessor> typeProcessorMap = getAffinityTypeToProcessorMap();
if (typeProcessorMap != null && !typeProcessorMap.isEmpty()) {
if (!typeProcessorMap.containsKey(affinityGroupType)) {
throw new InvalidParameterValueException("Unable to create affinity group, invalid affinity group type" + affinityGroupType);
}
} else {
throw new InvalidParameterValueException("Unable to create affinity group, no Affinity Group Types configured");
}
AffinityGroupProcessor processor = typeProcessorMap.get(affinityGroupType);
if (processor.isAdminControlledGroup()) {
throw new PermissionDeniedException("Cannot create the affinity group");
}
return createAffinityGroupInternal(account, projectId, domainId, affinityGroupName, affinityGroupType, description);
}
@DB
@Override
public AffinityGroup createAffinityGroupInternal(String account, final Long projectId, final Long domainId, final String affinityGroupName, final String affinityGroupType,
final String description) {
Account caller = CallContext.current().getCallingAccount();
// validate the affinityGroupType
Map<String, AffinityGroupProcessor> typeProcessorMap = getAffinityTypeToProcessorMap();
if (typeProcessorMap != null && !typeProcessorMap.isEmpty()) {
if (!typeProcessorMap.containsKey(affinityGroupType)) {
throw new InvalidParameterValueException("Unable to create affinity group, invalid affinity group type" + affinityGroupType);
}
} else {
throw new InvalidParameterValueException("Unable to create affinity group, no Affinity Group Types configured");
}
final AffinityGroupProcessor processor = typeProcessorMap.get(affinityGroupType);
if (processor.isAdminControlledGroup() && !_accountMgr.isRootAdmin(caller.getId())) {
throw new PermissionDeniedException("Cannot create the affinity group");
}
ControlledEntity.ACLType aclType = null;
Account owner = null;
boolean domainLevel = false;
if (account != null && domainId != null) {
owner = _accountMgr.finalizeOwner(caller, account, domainId, null);
aclType = ControlledEntity.ACLType.Account;
} else if (domainId != null && account == null) {
if (!_accountMgr.isRootAdmin(caller.getId())) {
// non root admin need to pass both account and domain
throw new InvalidParameterValueException("Unable to create affinity group, account name must be passed with the domainId");
} else if (!processor.canBeSharedDomainWide()) {
// cannot be domain level
throw new InvalidParameterValueException("Unable to create affinity group, account name is needed");
}
DomainVO domain = _domainDao.findById(domainId);
if (domain == null) {
throw new InvalidParameterValueException("Unable to find domain by specified id");
}
_accountMgr.checkAccess(caller, domain);
// domain level group, owner is SYSTEM.
owner = _accountMgr.getAccount(Account.ACCOUNT_ID_SYSTEM);
aclType = ControlledEntity.ACLType.Domain;
domainLevel = true;
} else {
owner = caller;
aclType = ControlledEntity.ACLType.Account;
}
if (_affinityGroupDao.isNameInUse(owner.getAccountId(), owner.getDomainId(), affinityGroupName)) {
throw new InvalidParameterValueException("Unable to create affinity group, a group with name " + affinityGroupName + " already exists.");
}
if (domainLevel && _affinityGroupDao.findDomainLevelGroupByName(domainId, affinityGroupName) != null) {
throw new InvalidParameterValueException("Unable to create affinity group, a group with name " + affinityGroupName + " already exists under the domain.");
}
final Account ownerFinal = owner;
final ControlledEntity.ACLType aclTypeFinal = aclType;
AffinityGroupVO group = Transaction.execute(new TransactionCallback<AffinityGroupVO>() {
@Override
public AffinityGroupVO doInTransaction(TransactionStatus status) {
AffinityGroupVO group =
new AffinityGroupVO(affinityGroupName, affinityGroupType, description, ownerFinal.getDomainId(), ownerFinal.getId(), aclTypeFinal);
_affinityGroupDao.persist(group);
if (domainId != null && aclTypeFinal == ACLType.Domain) {
boolean subDomainAccess = false;
subDomainAccess = processor.subDomainAccess();
AffinityGroupDomainMapVO domainMap = new AffinityGroupDomainMapVO(group.getId(), domainId,
subDomainAccess);
_affinityGroupDomainMapDao.persist(domainMap);
//send event for storing the domain wide resource access
Map<String, Object> params = new HashMap<String, Object>();
params.put(ApiConstants.ENTITY_TYPE, AffinityGroup.class);
params.put(ApiConstants.ENTITY_ID, group.getId());
params.put(ApiConstants.DOMAIN_ID, domainId);
params.put(ApiConstants.SUBDOMAIN_ACCESS, subDomainAccess);
_messageBus.publish(_name, EntityManager.MESSAGE_ADD_DOMAIN_WIDE_ENTITY_EVENT, PublishScope.LOCAL,
params);
}
return group;
}
});
if (s_logger.isDebugEnabled()) {
s_logger.debug("Created affinity group =" + affinityGroupName);
}
return group;
}
@DB
@ActionEvent(eventType = EventTypes.EVENT_AFFINITY_GROUP_DELETE, eventDescription = "Deleting affinity group")
public boolean deleteAffinityGroup(Long affinityGroupId, String account, Long projectId, Long domainId, String affinityGroupName) {
Account caller = CallContext.current().getCallingAccount();
Long accountId = _accountMgr.finalyzeAccountId(account, domainId, projectId, true);
AffinityGroupVO group = null;
if (affinityGroupId != null) {
group = _affinityGroupDao.findById(affinityGroupId);
if (group == null) {
throw new InvalidParameterValueException("Unable to find affinity group: " + affinityGroupId + "; failed to delete group.");
}
} else if (affinityGroupName != null) {
group = _affinityGroupDao.findByAccountAndName(accountId, affinityGroupName);
if (group == null) {
throw new InvalidParameterValueException("Unable to find affinity group: " + affinityGroupName + "; failed to delete group.");
}
} else {
throw new InvalidParameterValueException("Either the affinity group Id or group name must be specified to delete the group");
}
if (affinityGroupId == null) {
affinityGroupId = group.getId();
}
// check permissions
_accountMgr.checkAccess(caller, AccessType.OperateEntry, true, group);
final Long affinityGroupIdFinal = affinityGroupId;
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
AffinityGroupVO group = _affinityGroupDao.lockRow(affinityGroupIdFinal, true);
if (group == null) {
throw new InvalidParameterValueException("Unable to find affinity group by id " + affinityGroupIdFinal);
}
List<AffinityGroupVMMapVO> affinityGroupVmMap = _affinityGroupVMMapDao.listByAffinityGroup(affinityGroupIdFinal);
if (!affinityGroupVmMap.isEmpty()) {
SearchBuilder<AffinityGroupVMMapVO> listByAffinityGroup = _affinityGroupVMMapDao.createSearchBuilder();
listByAffinityGroup.and("affinityGroupId", listByAffinityGroup.entity().getAffinityGroupId(), SearchCriteria.Op.EQ);
listByAffinityGroup.done();
SearchCriteria<AffinityGroupVMMapVO> sc = listByAffinityGroup.create();
sc.setParameters("affinityGroupId", affinityGroupIdFinal);
_affinityGroupVMMapDao.lockRows(sc, null, true);
_affinityGroupVMMapDao.remove(sc);
}
// call processor to handle the group delete
AffinityGroupProcessor processor = getAffinityGroupProcessorForType(group.getType());
if (processor != null) {
processor.handleDeleteGroup(group);
}
if(_affinityGroupDao.expunge(affinityGroupIdFinal)){
AffinityGroupDomainMapVO groupDomain = _affinityGroupDomainMapDao
.findByAffinityGroup(affinityGroupIdFinal);
if (groupDomain != null) {
_affinityGroupDomainMapDao.remove(groupDomain.getId());
}
}
}
});
// remove its related ACL permission
Pair<Class<?>, Long> params = new Pair<Class<?>, Long>(AffinityGroup.class, affinityGroupIdFinal);
_messageBus.publish(_name, EntityManager.MESSAGE_REMOVE_ENTITY_EVENT, PublishScope.LOCAL, params);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Deleted affinity group id=" + affinityGroupId);
}
return true;
}
@Override
public List<String> listAffinityGroupTypes() {
List<String> types = new ArrayList<String>();
for (AffinityGroupProcessor processor : _affinityProcessors) {
if (processor.isAdminControlledGroup()) {
continue; // we dont list the type if this group can be
// created only as an admin/system operation.
}
types.add(processor.getType());
}
return types;
}
protected Map<String, AffinityGroupProcessor> getAffinityTypeToProcessorMap() {
Map<String, AffinityGroupProcessor> typeProcessorMap = new HashMap<String, AffinityGroupProcessor>();
for (AffinityGroupProcessor processor : _affinityProcessors) {
typeProcessorMap.put(processor.getType(), processor);
}
return typeProcessorMap;
}
@Override
public boolean isAdminControlledGroup(AffinityGroup group) {
if (group != null) {
String affinityGroupType = group.getType();
Map<String, AffinityGroupProcessor> typeProcessorMap = getAffinityTypeToProcessorMap();
if (typeProcessorMap != null && !typeProcessorMap.isEmpty()) {
AffinityGroupProcessor processor = typeProcessorMap.get(affinityGroupType);
if (processor != null) {
return processor.isAdminControlledGroup();
}
}
}
return false;
}
@Override
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
_name = name;
VirtualMachine.State.getStateMachine().registerListener(this);
return true;
}
@Override
public boolean start() {
return true;
}
@Override
public boolean stop() {
return true;
}
@Override
public String getName() {
return _name;
}
@Override
public AffinityGroup getAffinityGroup(Long groupId) {
return _affinityGroupDao.findById(groupId);
}
@Override
public boolean preStateTransitionEvent(State oldState, Event event, State newState, VirtualMachine vo, boolean status, Object opaque) {
return true;
}
@Override
public boolean postStateTransitionEvent(StateMachine2.Transition<State, Event> transition, VirtualMachine vo, boolean status, Object opaque) {
if (!status) {
return false;
}
State newState = transition.getToState();
if ((newState == State.Expunging) || (newState == State.Error)) {
// cleanup all affinity groups associations of the Expunged VM
SearchCriteria<AffinityGroupVMMapVO> sc = _affinityGroupVMMapDao.createSearchCriteria();
sc.addAnd("instanceId", SearchCriteria.Op.EQ, vo.getId());
_affinityGroupVMMapDao.expunge(sc);
}
return true;
}
@Override
public UserVm updateVMAffinityGroups(Long vmId, List<Long> affinityGroupIds) {
// Verify input parameters
UserVmVO vmInstance = _userVmDao.findById(vmId);
if (vmInstance == null) {
throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId);
}
// Check that the VM is stopped
if (!vmInstance.getState().equals(State.Stopped)) {
s_logger.warn("Unable to update affinity groups of the virtual machine " + vmInstance.toString() + " in state " + vmInstance.getState());
throw new InvalidParameterValueException("Unable update affinity groups of the virtual machine " + vmInstance.toString() + " " + "in state " +
vmInstance.getState() + "; make sure the virtual machine is stopped and not in an error state before updating.");
}
Account caller = CallContext.current().getCallingAccount();
Account owner = _accountMgr.getAccount(vmInstance.getAccountId());
// check that the affinity groups exist
for (Long affinityGroupId : affinityGroupIds) {
AffinityGroupVO ag = _affinityGroupDao.findById(affinityGroupId);
if (ag == null) {
throw new InvalidParameterValueException("Unable to find affinity group by id " + affinityGroupId);
} else {
// verify permissions
_accountMgr.checkAccess(caller, null, true, owner, ag);
// Root admin has access to both VM and AG by default, but make sure the
// owner of these entities is same
if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getId())) {
if (ag.getAccountId() != owner.getAccountId()) {
throw new PermissionDeniedException("Affinity Group " + ag + " does not belong to the VM's account");
}
}
}
}
_affinityGroupVMMapDao.updateMap(vmId, affinityGroupIds);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Updated VM :" + vmId + " affinity groups to =" + affinityGroupIds);
}
// APIResponseHelper will pull out the updated affinitygroups.
return vmInstance;
}
@Override
public boolean isAffinityGroupProcessorAvailable(String affinityGroupType) {
for (AffinityGroupProcessor processor : _affinityProcessors) {
if (affinityGroupType != null && affinityGroupType.equals(processor.getType())) {
return true;
}
}
return false;
}
private AffinityGroupProcessor getAffinityGroupProcessorForType(String affinityGroupType) {
for (AffinityGroupProcessor processor : _affinityProcessors) {
if (affinityGroupType != null && affinityGroupType.equals(processor.getType())) {
return processor;
}
}
return null;
}
@Override
public boolean isAffinityGroupAvailableInDomain(long affinityGroupId, long domainId) {
Long groupDomainId = null;
AffinityGroupDomainMapVO domainMap = _affinityGroupDomainMapDao.findByAffinityGroup(affinityGroupId);
if (domainMap == null) {
return false;
} else {
groupDomainId = domainMap.getDomainId();
}
if (domainId == groupDomainId.longValue()) {
return true;
}
if (domainMap.subdomainAccess) {
Set<Long> parentDomains = _domainMgr.getDomainParentIds(domainId);
if (parentDomains.contains(groupDomainId)) {
return true;
}
}
return false;
}
}