Skip to content

Commit b16520b

Browse files
committed
volume upload: added max size check for temaplte/volume post upload
used the existing configuration variables max.template.iso.size and storage.max.volume.upload.size for templates and volumes respectively.
1 parent dd1a8da commit b16520b

6 files changed

Lines changed: 63 additions & 10 deletions

File tree

‎core/src/org/apache/cloudstack/storage/command/TemplateOrVolumePostUploadCommand.java‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,8 @@ public class TemplateOrVolumePostUploadCommand {
4545

4646
String remoteEndPoint;
4747

48+
String maxUploadSize;
49+
4850
public TemplateOrVolumePostUploadCommand(long entityId, String entityUUID, String absolutePath, String checksum, String type, String name, String imageFormat, String dataTo,
4951
String dataToRole) {
5052
this.entityId = entityId;
@@ -156,4 +158,12 @@ public String getName() {
156158
public void setName(String name) {
157159
this.name = name;
158160
}
161+
162+
public String getMaxUploadSize() {
163+
return maxUploadSize;
164+
}
165+
166+
public void setMaxUploadSize(String maxUploadSize) {
167+
this.maxUploadSize = maxUploadSize;
168+
}
159169
}

‎server/src/com/cloud/storage/VolumeApiServiceImpl.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,8 @@ public GetUploadParamsResponse doInTransaction(TransactionStatus status) throws
337337
vol.getName(), vol.getFormat().toString(), dataObject.getDataStore().getUri(),
338338
dataObject.getDataStore().getRole().toString());
339339
command.setLocalPath(volumeStore.getLocalDownloadPath());
340+
//using the existing max upload size configuration
341+
command.setMaxUploadSize(_configDao.getValue(Config.MaxUploadVolumeSize.key()));
340342
Gson gson = new GsonBuilder().create();
341343
String metadata = EncryptionUtil.encodeData(gson.toJson(command), key);
342344
response.setMetadata(metadata);

‎server/src/com/cloud/template/HypervisorTemplateAdapter.java‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
import javax.ejb.Local;
2727
import javax.inject.Inject;
2828

29+
import com.cloud.configuration.Config;
2930
import org.apache.cloudstack.api.command.user.template.GetUploadParamsForTemplateCmd;
3031
import org.apache.cloudstack.engine.subsystem.api.storage.DataObject;
3132
import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint;
@@ -259,6 +260,8 @@ public List<TemplateOrVolumePostUploadCommand> createTemplateForPostUpload(Templ
259260
TemplateOrVolumePostUploadCommand payload = new TemplateOrVolumePostUploadCommand(template.getId(), template.getUuid(), tmpl.getInstallPath(), tmpl.getChecksum(), tmpl
260261
.getType().toString(), template.getName(), template.getFormat().toString(), templateOnStore.getDataStore().getUri(), templateOnStore.getDataStore().getRole()
261262
.toString());
263+
//using the existing max template size configuration
264+
payload.setMaxUploadSize(_configDao.getValue(Config.MaxTemplateAndIsoSize.key()));
262265
payload.setRemoteEndPoint(ep.getPublicAddr());
263266
payload.setRequiresHvm(template.requiresHvm());
264267
payloads.add(payload);

‎services/secondary-storage/server/src/org/apache/cloudstack/storage/resource/HttpUploadServerHandler.java‎

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,8 @@ public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Excep
108108
String expires = null;
109109
String metadata = null;
110110
String hostname = null;
111+
long contentLength = 0;
112+
111113
for (Entry<String, String> entry : request.headers()) {
112114
switch (entry.getKey()) {
113115
case HEADER_SIGNATURE:
@@ -122,12 +124,16 @@ public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Excep
122124
case HEADER_HOST:
123125
hostname = entry.getValue();
124126
break;
127+
case HttpHeaders.Names.CONTENT_LENGTH:
128+
contentLength = Long.valueOf(entry.getValue());
129+
break;
125130
}
126131
}
127132
logger.info("HEADER: signature=" + signature);
128133
logger.info("HEADER: metadata=" + metadata);
129134
logger.info("HEADER: expires=" + expires);
130135
logger.info("HEADER: hostname=" + hostname);
136+
logger.info("HEADER: Content-Length=" + contentLength);
131137
QueryStringDecoder decoderQuery = new QueryStringDecoder(uri);
132138
Map<String, List<String>> uriAttributes = decoderQuery.parameters();
133139
uuid = uriAttributes.get("uuid").get(0);
@@ -136,9 +142,9 @@ public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Excep
136142
UploadEntity uploadEntity = null;
137143
try {
138144
// Validate the request here
139-
storageResource.validatePostUploadRequest(signature, metadata, expires, hostname, uuid);
145+
storageResource.validatePostUploadRequest(signature, metadata, expires, hostname, contentLength, uuid);
140146
//create an upload entity. This will fail if entity already exists.
141-
uploadEntity = storageResource.createUploadEntity(uuid, metadata);
147+
uploadEntity = storageResource.createUploadEntity(uuid, metadata, contentLength);
142148
} catch (InvalidParameterValueException ex) {
143149
logger.error("post request validation failed", ex);
144150
responseContent.append(ex.getMessage());
@@ -185,9 +191,15 @@ public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Excep
185191
return;
186192
}
187193
if (chunk instanceof LastHttpContent) {
188-
readFileUploadData();
189-
writeResponse(ctx.channel(), HttpResponseStatus.OK);
190-
reset();
194+
try {
195+
readFileUploadData();
196+
writeResponse(ctx.channel(), HttpResponseStatus.OK);
197+
reset();
198+
} catch (InvalidParameterValueException e) {
199+
logger.error("error during the file install.", e);
200+
responseContent.append("\n").append(e.getMessage());
201+
writeResponse(ctx.channel(), HttpResponseStatus.INTERNAL_SERVER_ERROR);
202+
}
191203
}
192204
}
193205
}

‎services/secondary-storage/server/src/org/apache/cloudstack/storage/resource/NfsSecondaryStorageResource.java‎

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2602,18 +2602,24 @@ private String getScriptLocation(UploadEntity.ResourceType resourceType) {
26022602
return Script.findScript(scriptsDir, scriptname);
26032603
}
26042604

2605-
public UploadEntity createUploadEntity(String uuid, String metadata) {
2605+
public UploadEntity createUploadEntity(String uuid, String metadata, long contentLength) {
26062606
TemplateOrVolumePostUploadCommand cmd = getTemplateOrVolumePostUploadCmd(metadata);
26072607
UploadEntity uploadEntity = null;
26082608
if(cmd == null ){
26092609
updateStateMapWithError(uuid,"unable decode and deserialize metadata.");
26102610
throw new InvalidParameterValueException("unable to decode and deserialize metadata");
26112611
} else {
26122612
uuid = cmd.getEntityUUID();
2613-
if(uploadEntityStateMap.containsKey(uuid)) {
2613+
if (uploadEntityStateMap.containsKey(uuid)) {
26142614
uploadEntity = uploadEntityStateMap.get(uuid);
26152615
throw new InvalidParameterValueException("The one time post url is already used and the upload is in " + uploadEntity.getUploadState() + " state.");
26162616
}
2617+
int maxSizeInGB = Integer.valueOf(cmd.getMaxUploadSize());
2618+
int contentLengthInGB = getSizeInGB(contentLength);
2619+
if (contentLengthInGB > maxSizeInGB) {
2620+
throw new InvalidParameterValueException("Maximum file upload size exceeded. Content Length received: " + contentLengthInGB + "GB. Maximum allowed size: " +
2621+
maxSizeInGB + "GB.");
2622+
}
26172623
try {
26182624
String absolutePath = cmd.getAbsolutePath();
26192625
uploadEntity = new UploadEntity(uuid, cmd.getEntityId(), UploadEntity.Status.IN_PROGRESS, cmd.getName(), absolutePath);
@@ -2627,20 +2633,24 @@ public UploadEntity createUploadEntity(String uuid, String metadata) {
26272633
uploadEntity.setInstallPathPrefix(installPathPrefix);
26282634
uploadEntity.setHvm(cmd.getRequiresHvm());
26292635
uploadEntity.setChksum(cmd.getChecksum());
2636+
uploadEntity.setMaxSizeInGB(maxSizeInGB);
26302637
// create a install dir
26312638
if (!_storage.exists(installPathPrefix)) {
26322639
_storage.mkdir(installPathPrefix);
26332640
}
26342641
uploadEntityStateMap.put(uuid, uploadEntity);
26352642
} catch (Exception e) {
26362643
//upload entity will be null incase an exception occurs and the handler will not proceed.
2637-
s_logger.debug("exception occured while creating upload entity " + e);
2644+
s_logger.error("exception occurred while creating upload entity ", e);
26382645
updateStateMapWithError(uuid, e.getMessage());
26392646
}
26402647
}
26412648
return uploadEntity;
26422649
}
26432650

2651+
private int getSizeInGB(long sizeInBytes) {
2652+
return (int)Math.ceil(sizeInBytes * 1.0d / (1024 * 1024 * 1024));
2653+
}
26442654

26452655
public String postUpload(String uuid, String filename) {
26462656
UploadEntity uploadEntity = uploadEntityStateMap.get(uuid);
@@ -2657,7 +2667,11 @@ public String postUpload(String uuid, String filename) {
26572667
//}
26582668
//dnld.setCheckSum(checkSum);
26592669

2660-
int imgSizeGigs = (int)Math.ceil(_storage.getSize(fileSavedTempLocation) * 1.0d / (1024 * 1024 * 1024));
2670+
int imgSizeGigs = getSizeInGB(_storage.getSize(fileSavedTempLocation));
2671+
int maxSize = uploadEntity.getMaxSizeInGB();
2672+
if(imgSizeGigs > maxSize) {
2673+
throw new InvalidParameterValueException("Maximum file upload size exceeded. Physical file size: "+imgSizeGigs+"GB. Maximum allowed size: "+maxSize+"GB.");
2674+
}
26612675
imgSizeGigs++; // add one just in case
26622676
long timeout = (long)imgSizeGigs * installTimeoutPerGig;
26632677
Script scr = new Script(getScriptLocation(resourceType), timeout, s_logger);
@@ -2771,13 +2785,18 @@ private void updateStateMapWithError(String uuid,String errorMessage) {
27712785
uploadEntityStateMap.put(uuid, uploadEntity);
27722786
}
27732787

2774-
public void validatePostUploadRequest(String signature, String metadata, String timeout, String hostname, String uuid) throws InvalidParameterValueException{
2788+
public void validatePostUploadRequest(String signature, String metadata, String timeout, String hostname,long contentLength, String uuid) throws InvalidParameterValueException{
27752789
// check none of the params are empty
27762790
if(StringUtils.isEmpty(signature) || StringUtils.isEmpty(metadata) || StringUtils.isEmpty(timeout)) {
27772791
updateStateMapWithError(uuid,"signature, metadata and expires are compulsory fields.");
27782792
throw new InvalidParameterValueException("signature, metadata and expires are compulsory fields.");
27792793
}
27802794

2795+
//check that contentLength exists and is greater than zero
2796+
if (contentLength <= 0) {
2797+
throw new InvalidParameterValueException("content length is not set in the request or has invalid value.");
2798+
}
2799+
27812800
//validate signature
27822801
String fullUrl = "https://" + hostname + "/upload/" + uuid;
27832802
String computedSignature = EncryptionUtil.generateSignature(metadata + fullUrl + timeout, getPostUploadPSK());

‎services/secondary-storage/server/src/org/apache/cloudstack/storage/template/UploadEntity.java‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ public class UploadEntity {
3131
private long entityId;
3232
private String chksum;
3333
private long physicalSize;
34+
private int maxSizeInGB;
3435

3536
public static enum ResourceType {
3637
VOLUME, TEMPLATE
@@ -172,5 +173,11 @@ public long getPhysicalSize() {
172173
return physicalSize;
173174
}
174175

176+
public int getMaxSizeInGB() {
177+
return maxSizeInGB;
178+
}
175179

180+
public void setMaxSizeInGB(int maxSizeInGB) {
181+
this.maxSizeInGB = maxSizeInGB;
182+
}
176183
}

0 commit comments

Comments
 (0)