forked from AnythingLinux/cloudstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTemplateAdapterBase.java
More file actions
executable file
·392 lines (332 loc) · 16.8 KB
/
TemplateAdapterBase.java
File metadata and controls
executable file
·392 lines (332 loc) · 16.8 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
// 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.template;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import org.apache.log4j.Logger;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.command.user.iso.DeleteIsoCmd;
import org.apache.cloudstack.api.command.user.iso.RegisterIsoCmd;
import org.apache.cloudstack.api.command.user.template.DeleteTemplateCmd;
import org.apache.cloudstack.api.command.user.template.ExtractTemplateCmd;
import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreDao;
import com.cloud.api.ApiDBUtils;
import com.cloud.configuration.Config;
import com.cloud.configuration.Resource.ResourceType;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.domain.dao.DomainDao;
import com.cloud.event.dao.UsageEventDao;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.org.Grouping;
import com.cloud.projects.ProjectManager;
import com.cloud.server.ConfigurationServer;
import com.cloud.storage.GuestOS;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.Storage.TemplateType;
import com.cloud.storage.TemplateProfile;
import com.cloud.storage.VMTemplateVO;
import com.cloud.storage.dao.GuestOSHypervisorDao;
import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.storage.dao.VMTemplateZoneDao;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.ResourceLimitService;
import com.cloud.user.UserVO;
import com.cloud.user.dao.AccountDao;
import com.cloud.user.dao.UserDao;
import com.cloud.utils.EnumUtils;
import com.cloud.utils.component.AdapterBase;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.vm.UserVmVO;
import com.cloud.vm.dao.UserVmDao;
public abstract class TemplateAdapterBase extends AdapterBase implements TemplateAdapter {
private final static Logger s_logger = Logger.getLogger(TemplateAdapterBase.class);
protected @Inject DomainDao _domainDao;
protected @Inject AccountDao _accountDao;
protected @Inject ConfigurationDao _configDao;
protected @Inject UserDao _userDao;
protected @Inject AccountManager _accountMgr;
protected @Inject DataCenterDao _dcDao;
protected @Inject VMTemplateDao _tmpltDao;
protected @Inject TemplateDataStoreDao _tmpltStoreDao;
protected @Inject VMTemplateZoneDao _tmpltZoneDao;
protected @Inject UsageEventDao _usageEventDao;
protected @Inject HostDao _hostDao;
protected @Inject UserVmDao _userVmDao;
protected @Inject GuestOSHypervisorDao _osHyperDao;
protected @Inject ResourceLimitService _resourceLimitMgr;
protected @Inject DataStoreManager storeMgr;
@Inject TemplateManager templateMgr;
@Inject ConfigurationServer _configServer;
@Inject ProjectManager _projectMgr;
@Override
public boolean stop() {
return true;
}
private static boolean isAdmin(short accountType) {
return ((accountType == Account.ACCOUNT_TYPE_ADMIN) ||
(accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) ||
(accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) ||
(accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN));
}
@Override
public TemplateProfile prepare(boolean isIso, Long userId, String name, String displayText, Integer bits,
Boolean passwordEnabled, Boolean requiresHVM, String url, Boolean isPublic, Boolean featured,
Boolean isExtractable, String format, Long guestOSId, Long zoneId, HypervisorType hypervisorType,
String accountName, Long domainId, String chksum, Boolean bootable, Map details) throws ResourceAllocationException {
return prepare(isIso, userId, name, displayText, bits, passwordEnabled, requiresHVM, url, isPublic, featured, isExtractable, format, guestOSId, zoneId, hypervisorType,
chksum, bootable, null, null, details, false, null, false, TemplateType.USER);
}
@Override
public TemplateProfile prepare(boolean isIso, long userId, String name, String displayText, Integer bits,
Boolean passwordEnabled, Boolean requiresHVM, String url, Boolean isPublic, Boolean featured,
Boolean isExtractable, String format, Long guestOSId, Long zoneId, HypervisorType hypervisorType,
String chksum, Boolean bootable, String templateTag, Account templateOwner, Map details, Boolean sshkeyEnabled,
String imageStoreUuid, Boolean isDynamicallyScalable, TemplateType templateType) throws ResourceAllocationException {
//Long accountId = null;
// parameters verification
if (isPublic == null) {
isPublic = Boolean.FALSE;
}
if (zoneId.longValue() == -1) {
zoneId = null;
}
if (isIso) {
if (bootable == null) {
bootable = Boolean.TRUE;
}
GuestOS noneGuestOs = ApiDBUtils.findGuestOSByDisplayName(ApiConstants.ISO_GUEST_OS_NONE);
if ((guestOSId == null || guestOSId == noneGuestOs.getId()) && bootable == true){
throw new InvalidParameterValueException("Please pass a valid GuestOS Id");
}
if (bootable == false){
guestOSId = noneGuestOs.getId(); //Guest os id of None.
}
} else {
if (bits == null) {
bits = Integer.valueOf(64);
}
if (passwordEnabled == null) {
passwordEnabled = false;
}
if (requiresHVM == null) {
requiresHVM = true;
}
}
if (isExtractable == null) {
isExtractable = Boolean.FALSE;
}
if (sshkeyEnabled == null) {
sshkeyEnabled = Boolean.FALSE;
}
boolean isAdmin = _accountDao.findById(templateOwner.getId()).getType() == Account.ACCOUNT_TYPE_ADMIN;
if (!isAdmin && zoneId == null) {
throw new InvalidParameterValueException("Please specify a valid zone Id.");
}
if (url.toLowerCase().contains("file://")) {
throw new InvalidParameterValueException("File:// type urls are currently unsupported");
}
// check whether owner can create public templates
boolean allowPublicUserTemplates = Boolean.parseBoolean(_configServer.getConfigValue(Config.AllowPublicUserTemplates.key(), Config.ConfigurationParameterScope.account.toString(), templateOwner.getId()));
if (!isAdmin && !allowPublicUserTemplates && isPublic) {
throw new InvalidParameterValueException("Only private templates/ISO can be created.");
}
if (!isAdmin || featured == null) {
featured = Boolean.FALSE;
}
ImageFormat imgfmt = ImageFormat.valueOf(format.toUpperCase());
if (imgfmt == null) {
throw new IllegalArgumentException("Image format is incorrect " + format + ". Supported formats are " + EnumUtils.listValues(ImageFormat.values()));
}
// Check that the resource limit for templates/ISOs won't be exceeded
UserVO user = _userDao.findById(userId);
if (user == null) {
throw new IllegalArgumentException("Unable to find user with id " + userId);
}
_resourceLimitMgr.checkResourceLimit(templateOwner, ResourceType.template);
if (templateOwner.getType() != Account.ACCOUNT_TYPE_ADMIN && zoneId == null) {
throw new IllegalArgumentException("Only admins can create templates in all zones");
}
// If a zoneId is specified, make sure it is valid
if (zoneId != null) {
DataCenterVO zone = _dcDao.findById(zoneId);
if (zone == null) {
throw new IllegalArgumentException("Please specify a valid zone.");
}
Account caller = CallContext.current().getCallingAccount();
if(Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getType())){
throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: "+ zoneId );
}
}
List<VMTemplateVO> systemvmTmplts = _tmpltDao.listAllSystemVMTemplates();
for (VMTemplateVO template : systemvmTmplts) {
if (template.getName().equalsIgnoreCase(name) || template.getDisplayText().equalsIgnoreCase(displayText)) {
throw new IllegalArgumentException("Cannot use reserved names for templates");
}
}
Long id = _tmpltDao.getNextInSequence(Long.class, "id");
CallContext.current().setEventDetails("Id: " +id+ " name: " + name);
return new TemplateProfile(id, userId, name, displayText, bits, passwordEnabled, requiresHVM, url, isPublic,
featured, isExtractable, imgfmt, guestOSId, zoneId, hypervisorType, templateOwner.getAccountName(), templateOwner.getDomainId(),
templateOwner.getAccountId(), chksum, bootable, templateTag, details, sshkeyEnabled, null, isDynamicallyScalable, templateType);
}
@Override
public TemplateProfile prepare(RegisterTemplateCmd cmd) throws ResourceAllocationException {
//check if the caller can operate with the template owner
Account caller = CallContext.current().getCallingAccount();
Account owner = _accountMgr.getAccount(cmd.getEntityOwnerId());
_accountMgr.checkAccess(caller, null, true, owner);
boolean isRouting = (cmd.isRoutingType() == null) ? false : cmd.isRoutingType();
return prepare(false, CallContext.current().getCallingUserId(), cmd.getTemplateName(), cmd.getDisplayText(),
cmd.getBits(), cmd.isPasswordEnabled(), cmd.getRequiresHvm(), cmd.getUrl(), cmd.isPublic(), cmd.isFeatured(),
cmd.isExtractable(), cmd.getFormat(), cmd.getOsTypeId(), cmd.getZoneId(), HypervisorType.getType(cmd.getHypervisor()),
cmd.getChecksum(), true, cmd.getTemplateTag(), owner, cmd.getDetails(), cmd.isSshKeyEnabled(), null, cmd.isDynamicallyScalable(),
isRouting ? TemplateType.ROUTING : TemplateType.USER);
}
@Override
public TemplateProfile prepare(RegisterIsoCmd cmd) throws ResourceAllocationException {
//check if the caller can operate with the template owner
Account caller = CallContext.current().getCallingAccount();
Account owner = _accountMgr.getAccount(cmd.getEntityOwnerId());
_accountMgr.checkAccess(caller, null, true, owner);
return prepare(true, CallContext.current().getCallingUserId(), cmd.getIsoName(), cmd.getDisplayText(), 64, false,
true, cmd.getUrl(), cmd.isPublic(), cmd.isFeatured(), cmd.isExtractable(), ImageFormat.ISO.toString(), cmd.getOsTypeId(),
cmd.getZoneId(), HypervisorType.None, cmd.getChecksum(), cmd.isBootable(), null, owner, null, false, cmd.getImageStoreUuid(), cmd.isDynamicallyScalable(),
TemplateType.USER);
}
protected VMTemplateVO persistTemplate(TemplateProfile profile) {
Long zoneId = profile.getZoneId();
VMTemplateVO template = new VMTemplateVO(profile.getTemplateId(), profile.getName(), profile.getFormat(), profile.getIsPublic(),
profile.getFeatured(), profile.getIsExtractable(), profile.getTemplateType(), profile.getUrl(), profile.getRequiresHVM(),
profile.getBits(), profile.getAccountId(), profile.getCheckSum(), profile.getDisplayText(),
profile.getPasswordEnabled(), profile.getGuestOsId(), profile.getBootable(), profile.getHypervisorType(), profile.getTemplateTag(),
profile.getDetails(), profile.getSshKeyEnabled());
if (zoneId == null || zoneId.longValue() == -1) {
List<DataCenterVO> dcs = _dcDao.listAll();
if (dcs.isEmpty()) {
throw new CloudRuntimeException("No zones are present in the system, can't add template");
}
template.setCrossZones(true);
for (DataCenterVO dc: dcs) {
_tmpltDao.addTemplateToZone(template, dc.getId());
}
} else {
_tmpltDao.addTemplateToZone(template, zoneId);
}
return _tmpltDao.findById(template.getId());
}
private Long accountAndUserValidation(Account account, long userId, UserVmVO vmInstanceCheck, VMTemplateVO template, String msg)
throws PermissionDeniedException {
if (account != null) {
if (!isAdmin(account.getType())) {
if ((vmInstanceCheck != null) && (account.getId() != vmInstanceCheck.getAccountId())) {
throw new PermissionDeniedException(msg + ". Permission denied.");
}
if ((template != null)
&& (!template.isPublicTemplate() && (account.getId() != template.getAccountId()) && (template.getTemplateType() != TemplateType.PERHOST))) {
//special handling for the project case
Account owner = _accountMgr.getAccount(template.getAccountId());
if (owner.getType() == Account.ACCOUNT_TYPE_PROJECT) {
if (!_projectMgr.canAccessProjectAccount(account, owner.getId())) {
throw new PermissionDeniedException(msg + ". Permission denied. The caller can't access project's template");
}
} else {
throw new PermissionDeniedException(msg + ". Permission denied.");
}
}
} else {
if ((vmInstanceCheck != null) && !_domainDao.isChildDomain(account.getDomainId(), vmInstanceCheck.getDomainId())) {
throw new PermissionDeniedException(msg + ". Permission denied.");
}
// FIXME: if template/ISO owner is null we probably need to
// throw some kind of exception
if (template != null) {
Account templateOwner = _accountDao.findById(template.getAccountId());
if ((templateOwner != null) && !_domainDao.isChildDomain(account.getDomainId(), templateOwner.getDomainId())) {
throw new PermissionDeniedException(msg + ". Permission denied.");
}
}
}
}
return userId;
}
@Override
public TemplateProfile prepareDelete(DeleteTemplateCmd cmd) {
Long templateId = cmd.getId();
Long userId = CallContext.current().getCallingUserId();
Account account = CallContext.current().getCallingAccount();
Long zoneId = cmd.getZoneId();
VMTemplateVO template = _tmpltDao.findById(templateId.longValue());
if (template == null) {
throw new InvalidParameterValueException("unable to find template with id " + templateId);
}
userId = accountAndUserValidation(account, userId, null, template, "Unable to delete template ");
UserVO user = _userDao.findById(userId);
if (user == null) {
throw new InvalidParameterValueException("Please specify a valid user.");
}
if (template.getFormat() == ImageFormat.ISO) {
throw new InvalidParameterValueException("Please specify a valid template.");
}
return new TemplateProfile(userId, template, zoneId);
}
@Override
public TemplateProfile prepareExtractTemplate(ExtractTemplateCmd cmd) {
Long templateId = cmd.getId();
Long userId = CallContext.current().getCallingUserId();
Long zoneId = cmd.getZoneId();
VMTemplateVO template = _tmpltDao.findById(templateId.longValue());
if (template == null) {
throw new InvalidParameterValueException("unable to find template with id " + templateId);
}
return new TemplateProfile(userId, template, zoneId);
}
@Override
public TemplateProfile prepareDelete(DeleteIsoCmd cmd) {
Long templateId = cmd.getId();
Long userId = CallContext.current().getCallingUserId();
Account account = CallContext.current().getCallingAccount();
Long zoneId = cmd.getZoneId();
VMTemplateVO template = _tmpltDao.findById(templateId.longValue());
if (template == null) {
throw new InvalidParameterValueException("unable to find iso with id " + templateId);
}
userId = accountAndUserValidation(account, userId, null, template, "Unable to delete iso " );
UserVO user = _userDao.findById(userId);
if (user == null) {
throw new InvalidParameterValueException("Please specify a valid user.");
}
if (template.getFormat() != ImageFormat.ISO) {
throw new InvalidParameterValueException("Please specify a valid iso.");
}
return new TemplateProfile(userId, template, zoneId);
}
@Override
abstract public VMTemplateVO create(TemplateProfile profile);
@Override
abstract public boolean delete(TemplateProfile profile);
}