forked from apache/cloudstack
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathResourceCountDaoImpl.java
More file actions
399 lines (349 loc) · 17.5 KB
/
ResourceCountDaoImpl.java
File metadata and controls
399 lines (349 loc) · 17.5 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
// 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.configuration.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import com.cloud.configuration.Resource;
import com.cloud.configuration.Resource.ResourceOwnerType;
import com.cloud.configuration.Resource.ResourceType;
import com.cloud.configuration.ResourceCountVO;
import com.cloud.configuration.ResourceLimit;
import com.cloud.domain.DomainVO;
import com.cloud.domain.dao.DomainDao;
import com.cloud.user.AccountVO;
import com.cloud.user.ResourceLimitService;
import com.cloud.user.dao.AccountDao;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.JoinBuilder;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.TransactionLegacy;
import com.cloud.utils.exception.CloudRuntimeException;
@Component
public class ResourceCountDaoImpl extends GenericDaoBase<ResourceCountVO, Long> implements ResourceCountDao {
private final SearchBuilder<ResourceCountVO> TypeSearch;
private final SearchBuilder<ResourceCountVO> TypeNullTagSearch;
private final SearchBuilder<ResourceCountVO> NonMatchingTagsSearch;
private final SearchBuilder<ResourceCountVO> AccountSearch;
private final SearchBuilder<ResourceCountVO> DomainSearch;
private final SearchBuilder<ResourceCountVO> IdsSearch;
@Inject
private DomainDao _domainDao;
@Inject
private AccountDao _accountDao;
protected static final String INCREMENT_COUNT_BY_IDS_SQL = "UPDATE `cloud`.`resource_count` SET `count` = `count` + ? WHERE `id` IN (?)";
protected static final String DECREMENT_COUNT_BY_IDS_SQL = "UPDATE `cloud`.`resource_count` SET `count` = `count` - ? WHERE `id` IN (?)";
public ResourceCountDaoImpl() {
TypeSearch = createSearchBuilder();
TypeSearch.and("type", TypeSearch.entity().getType(), SearchCriteria.Op.EQ);
TypeSearch.and("accountId", TypeSearch.entity().getAccountId(), SearchCriteria.Op.IN);
TypeSearch.and("domainId", TypeSearch.entity().getDomainId(), SearchCriteria.Op.IN);
TypeSearch.and("tag", TypeSearch.entity().getTag(), SearchCriteria.Op.EQ);
TypeSearch.done();
TypeNullTagSearch = createSearchBuilder();
TypeNullTagSearch.and("type", TypeNullTagSearch.entity().getType(), SearchCriteria.Op.EQ);
TypeNullTagSearch.and("accountId", TypeNullTagSearch.entity().getAccountId(), SearchCriteria.Op.IN);
TypeNullTagSearch.and("domainId", TypeNullTagSearch.entity().getDomainId(), SearchCriteria.Op.IN);
TypeNullTagSearch.and("tag", TypeNullTagSearch.entity().getTag(), SearchCriteria.Op.NULL);
TypeNullTagSearch.done();
NonMatchingTagsSearch = createSearchBuilder();
NonMatchingTagsSearch.and("accountId", NonMatchingTagsSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
NonMatchingTagsSearch.and("domainId", NonMatchingTagsSearch.entity().getDomainId(), SearchCriteria.Op.EQ);
NonMatchingTagsSearch.and("types", NonMatchingTagsSearch.entity().getType(), SearchCriteria.Op.IN);
NonMatchingTagsSearch.and("tagNotNull", NonMatchingTagsSearch.entity().getTag(), SearchCriteria.Op.NNULL);
NonMatchingTagsSearch.and("tags", NonMatchingTagsSearch.entity().getTag(), SearchCriteria.Op.NIN);
NonMatchingTagsSearch.done();
AccountSearch = createSearchBuilder();
DomainSearch = createSearchBuilder();
IdsSearch = createSearchBuilder();
IdsSearch.and("id", IdsSearch.entity().getId(), SearchCriteria.Op.IN);
IdsSearch.done();
}
@PostConstruct
protected void configure() {
AccountSearch.and("accountId", AccountSearch.entity().getAccountId(), SearchCriteria.Op.NNULL);
SearchBuilder<AccountVO> joinAccount = _accountDao.createSearchBuilder();
joinAccount.and("notremoved", joinAccount.entity().getRemoved(), SearchCriteria.Op.NULL);
AccountSearch.join("account", joinAccount, AccountSearch.entity().getAccountId(), joinAccount.entity().getId(), JoinBuilder.JoinType.INNER);
AccountSearch.done();
DomainSearch.and("domainId", DomainSearch.entity().getDomainId(), SearchCriteria.Op.NNULL);
SearchBuilder<DomainVO> joinDomain = _domainDao.createSearchBuilder();
joinDomain.and("notremoved", joinDomain.entity().getRemoved(), SearchCriteria.Op.NULL);
DomainSearch.join("domain", joinDomain, DomainSearch.entity().getDomainId(), joinDomain.entity().getId(), JoinBuilder.JoinType.INNER);
DomainSearch.done();
}
@Override
public ResourceCountVO findByOwnerAndTypeAndTag(long ownerId, ResourceOwnerType ownerType, ResourceType type, String tag) {
List<ResourceCountVO> resourceCounts = findByOwnersAndTypeAndTag(List.of(ownerId), ownerType, type, tag);
if (CollectionUtils.isNotEmpty(resourceCounts)) {
return resourceCounts.get(0);
} else {
return null;
}
}
@Override
public List<ResourceCountVO> findByOwnersAndTypeAndTag(List<Long> ownerIdList, ResourceOwnerType ownerType, ResourceType type, String tag) {
if (CollectionUtils.isEmpty(ownerIdList)) {
return new ArrayList<>();
}
SearchCriteria<ResourceCountVO> sc = tag != null ? TypeSearch.create() : TypeNullTagSearch.create();
sc.setParameters("type", type);
if (tag != null) {
sc.setParameters("tag", tag);
}
if (ownerType == ResourceOwnerType.Account) {
sc.setParameters("accountId", ownerIdList.toArray());
return listIncludingRemovedBy(sc);
} else if (ownerType == ResourceOwnerType.Domain) {
sc.setParameters("domainId", ownerIdList.toArray());
return listIncludingRemovedBy(sc);
} else {
return new ArrayList<>();
}
}
@Override
public long getResourceCount(long ownerId, ResourceOwnerType ownerType, ResourceType type, String tag) {
ResourceCountVO vo = findByOwnerAndTypeAndTag(ownerId, ownerType, type, tag);
if (vo != null) {
return vo.getCount();
} else {
return 0;
}
}
@Override
public void setResourceCount(long ownerId, ResourceOwnerType ownerType, ResourceType type, String tag, long count) {
ResourceCountVO resourceCountVO = findByOwnerAndTypeAndTag(ownerId, ownerType, type, tag);
if (resourceCountVO != null && count != resourceCountVO.getCount()) {
resourceCountVO.setCount(count);
update(resourceCountVO.getId(), resourceCountVO);
}
}
@Override
public boolean updateById(long id, boolean increment, long delta) {
delta = increment ? delta : delta * -1;
ResourceCountVO resourceCountVO = findById(id);
resourceCountVO.setCount(resourceCountVO.getCount() + delta);
return update(resourceCountVO.getId(), resourceCountVO);
}
@Override
public boolean updateCountByDeltaForIds(List<Long> ids, boolean increment, long delta) {
if (CollectionUtils.isEmpty(ids)) {
return false;
}
String updateSql = increment ? INCREMENT_COUNT_BY_IDS_SQL : DECREMENT_COUNT_BY_IDS_SQL;
String poolIdsInStr = ids.stream().map(String::valueOf).collect(Collectors.joining(",", "(", ")"));
String sql = updateSql.replace("(?)", poolIdsInStr);
final TransactionLegacy txn = TransactionLegacy.currentTxn();
try(PreparedStatement pstmt = txn.prepareStatement(sql);) {
pstmt.setLong(1, delta);
pstmt.executeUpdate();
return true;
} catch (SQLException e) {
throw new CloudRuntimeException(e);
}
}
@Override
public Set<Long> listRowsToUpdateForDomain(long domainId, ResourceType type, String tag) {
Set<Long> rowIds = new HashSet<Long>();
Set<Long> domainIdsToUpdate = _domainDao.getDomainParentIds(domainId);
for (Long domainIdToUpdate : domainIdsToUpdate) {
ResourceCountVO domainCountRecord = findByOwnerAndTypeAndTag(domainIdToUpdate, ResourceOwnerType.Domain, type, tag);
if (domainCountRecord != null) {
rowIds.add(domainCountRecord.getId());
} else {
if (StringUtils.isNotEmpty(tag)) {
ResourceCountVO resourceCountVO = createTaggedResourceCount(domainIdToUpdate, ResourceOwnerType.Domain, type, tag);
rowIds.add(resourceCountVO.getId());
}
}
}
return rowIds;
}
@Override
public Set<Long> listAllRowsToUpdate(long ownerId, ResourceOwnerType ownerType, ResourceType type, String tag) {
Set<Long> rowIds = new HashSet<Long>();
if (ownerType == ResourceOwnerType.Account) {
//get records for account
ResourceCountVO accountCountRecord = findByOwnerAndTypeAndTag(ownerId, ResourceOwnerType.Account, type, tag);
if (accountCountRecord != null) {
rowIds.add(accountCountRecord.getId());
} else {
if (StringUtils.isNotEmpty(tag)) {
ResourceCountVO resourceCountVO = createTaggedResourceCount(ownerId, ownerType, type, tag);
rowIds.add(resourceCountVO.getId());
}
}
//get records for account's domain and all its parent domains
rowIds.addAll(listRowsToUpdateForDomain(_accountDao.findByIdIncludingRemoved(ownerId).getDomainId(), type, tag));
} else if (ownerType == ResourceOwnerType.Domain) {
rowIds = listRowsToUpdateForDomain(ownerId, type, tag);
}
return rowIds;
}
protected ResourceCountVO createTaggedResourceCount(long ownerId, ResourceLimit.ResourceOwnerType ownerType, ResourceType resourceType, String tag) {
ResourceCountVO taggedResourceCountVO = new ResourceCountVO(resourceType, 0, ownerId, ownerType, tag);
return persist(taggedResourceCountVO);
}
protected void createTaggedResourceCounts(long ownerId, ResourceLimit.ResourceOwnerType ownerType, ResourceType resourceType, List<String> tags) {
for (String tag : tags) {
createTaggedResourceCount(ownerId, ownerType, resourceType, tag);
}
}
@Override
@DB
public void createResourceCounts(long ownerId, ResourceLimit.ResourceOwnerType ownerType) {
TransactionLegacy txn = TransactionLegacy.currentTxn();
txn.start();
ResourceType[] resourceTypes = Resource.ResourceType.values();
List<String> hostTags = new ArrayList<>();
if (StringUtils.isNotEmpty(ResourceLimitService.ResourceLimitHostTags.value())) {
hostTags = Arrays.asList(ResourceLimitService.ResourceLimitHostTags.value().split(","));
}
List<String> storageTags = new ArrayList<>();
if (StringUtils.isNotEmpty(ResourceLimitService.ResourceLimitStorageTags.value())) {
storageTags = Arrays.asList(ResourceLimitService.ResourceLimitStorageTags.value().split(","));
}
for (ResourceType resourceType : resourceTypes) {
ResourceCountVO resourceCountVO = new ResourceCountVO(resourceType, 0, ownerId, ownerType);
persist(resourceCountVO);
if (ResourceLimitService.HostTagsSupportingTypes.contains(resourceType)) {
createTaggedResourceCounts(ownerId, ownerType, resourceType, hostTags);
}
if (ResourceLimitService.StorageTagsSupportingTypes.contains(resourceType)) {
createTaggedResourceCounts(ownerId, ownerType, resourceType, storageTags);
}
}
txn.commit();
}
private List<ResourceCountVO> listByDomainId(long domainId) {
SearchCriteria<ResourceCountVO> sc = TypeSearch.create();
sc.setParameters("domainId", domainId);
return listBy(sc);
}
private List<ResourceCountVO> listByAccountId(long accountId) {
SearchCriteria<ResourceCountVO> sc = TypeSearch.create();
sc.setParameters("accountId", accountId);
return listBy(sc);
}
@Override
public List<ResourceCountVO> listByOwnerId(long ownerId, ResourceOwnerType ownerType) {
if (ownerType == ResourceOwnerType.Account) {
return listByAccountId(ownerId);
} else if (ownerType == ResourceOwnerType.Domain) {
return listByDomainId(ownerId);
} else {
return new ArrayList<ResourceCountVO>();
}
}
@Override
public List<ResourceCountVO> listResourceCountByOwnerType(ResourceOwnerType ownerType) {
if (ownerType == ResourceOwnerType.Account) {
return listBy(AccountSearch.create());
} else if (ownerType == ResourceOwnerType.Domain) {
return listBy(DomainSearch.create());
} else {
return new ArrayList<ResourceCountVO>();
}
}
@Override
public long removeEntriesByOwner(long ownerId, ResourceOwnerType ownerType) {
SearchCriteria<ResourceCountVO> sc = TypeSearch.create();
if (ownerType == ResourceOwnerType.Account) {
sc.setParameters("accountId", ownerId);
return remove(sc);
} else if (ownerType == ResourceOwnerType.Domain) {
sc.setParameters("domainId", ownerId);
return remove(sc);
}
return 0;
}
private String baseSqlCountComputingResourceAllocatedToAccount = "Select "
+ " SUM((CASE "
+ " WHEN so.%s is not null THEN so.%s "
+ " ELSE CONVERT(vmd.value, UNSIGNED INTEGER) "
+ " END)) as total "
+ " from vm_instance vm "
+ " join service_offering so on so.id = vm.service_offering_id "
+ " left join vm_instance_details vmd on vmd.vm_id = vm.id and vmd.name = '%s' "
+ " where vm.type = 'User' and state not in ('Destroyed', 'Error', 'Expunging') and display_vm = true and account_id = ? ";
@Override
public long countCpuNumberAllocatedToAccount(long accountId) {
String sqlCountCpuNumberAllocatedToAccount = String.format(baseSqlCountComputingResourceAllocatedToAccount, ResourceType.cpu, ResourceType.cpu, "cpuNumber");
return executeSqlCountComputingResourcesForAccount(accountId, sqlCountCpuNumberAllocatedToAccount);
}
@Override
public long countMemoryAllocatedToAccount(long accountId) {
String serviceOfferingRamSizeField = "ram_size";
String sqlCountCpuNumberAllocatedToAccount = String.format(baseSqlCountComputingResourceAllocatedToAccount, serviceOfferingRamSizeField, serviceOfferingRamSizeField, "memory");
return executeSqlCountComputingResourcesForAccount(accountId, sqlCountCpuNumberAllocatedToAccount);
}
private long executeSqlCountComputingResourcesForAccount(long accountId, String sqlCountComputingResourcesAllocatedToAccount) {
TransactionLegacy tx = TransactionLegacy.currentTxn();
try {
PreparedStatement pstmt = tx.prepareAutoCloseStatement(sqlCountComputingResourcesAllocatedToAccount);
pstmt.setLong(1, accountId);
ResultSet rs = pstmt.executeQuery();
if (!rs.next()) {
return 0L;
}
return rs.getLong("total");
} catch (SQLException e) {
throw new CloudRuntimeException(e);
}
}
@Override
public void removeResourceCountsForNonMatchingTags(Long ownerId, ResourceOwnerType ownerType, List<ResourceType> types, List<String> tags) {
SearchCriteria<ResourceCountVO> sc = NonMatchingTagsSearch.create();
if (ObjectUtils.allNotNull(ownerId, ownerType)) {
if (ResourceOwnerType.Account.equals(ownerType)) {
sc.setParameters("accountId", ownerId);
} else {
sc.setParameters("domainId", ownerId);
}
}
if (CollectionUtils.isNotEmpty(types)) {
sc.setParameters("types", types.stream().map(ResourceType::getName).toArray());
}
if (CollectionUtils.isNotEmpty(tags)) {
sc.setParameters("tags", tags.toArray());
}
remove(sc);
}
@Override
public List<ResourceCountVO> lockRows(Set<Long> ids) {
if (CollectionUtils.isEmpty(ids)) {
return new ArrayList<>();
}
SearchCriteria<ResourceCountVO> sc = IdsSearch.create();
sc.setParameters("id", ids.toArray());
return lockRows(sc, null, true);
}
}