-
Notifications
You must be signed in to change notification settings - Fork 131
/
FileResources.java
660 lines (618 loc) · 29.4 KB
/
FileResources.java
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
package org.dcache.restful.resources.namespace;
import static org.dcache.restful.providers.SuccessfulResponse.successfulResponse;
import com.google.common.base.Strings;
import com.google.common.collect.Range;
import diskCacheV111.util.AttributeExistsCacheException;
import diskCacheV111.util.CacheException;
import diskCacheV111.util.FileNotFoundCacheException;
import diskCacheV111.util.FsPath;
import diskCacheV111.util.NoAttributeCacheException;
import diskCacheV111.util.PermissionDeniedCacheException;
import diskCacheV111.util.PnfsHandler;
import diskCacheV111.util.PnfsId;
import diskCacheV111.vehicles.HttpProtocolInfo;
import diskCacheV111.vehicles.PnfsWriteExtendedAttributesMessage.Mode;
import diskCacheV111.vehicles.ProtocolInfo;
import dmg.cells.nucleus.NoRouteToCellException;
import dmg.util.Exceptions;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.Authorization;
import io.swagger.annotations.Example;
import io.swagger.annotations.ExampleProperty;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import javax.inject.Named;
import javax.security.auth.Subject;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.ForbiddenException;
import javax.ws.rs.GET;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.dcache.auth.Subjects;
import org.dcache.cells.CellStub;
import org.dcache.http.PathMapper;
import org.dcache.namespace.FileAttribute;
import org.dcache.namespace.FileType;
import org.dcache.pinmanager.PinManagerPinMessage;
import org.dcache.pinmanager.PinManagerUnpinMessage;
import org.dcache.poolmanager.PoolMonitor;
import org.dcache.qos.QoSTransitionEngine;
import org.dcache.qos.data.FileQoSRequirements;
import org.dcache.qos.remote.clients.RemoteQoSRequirementsClient;
import org.dcache.restful.providers.JsonFileAttributes;
import org.dcache.restful.util.HandlerBuilders;
import org.dcache.restful.util.HttpServletRequests;
import org.dcache.restful.util.RequestUser;
import org.dcache.restful.util.namespace.NamespaceUtils;
import org.dcache.util.list.DirectoryEntry;
import org.dcache.util.list.DirectoryStream;
import org.dcache.util.list.ListDirectoryHandler;
import org.dcache.vehicles.FileAttributes;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Component;
/**
* RestFul API to provide files/folders manipulation operations.
*/
@Api(value = "namespace", authorizations = {@Authorization("basicAuth")})
@Component
@Path("/namespace")
public class FileResources {
private static final Logger LOG = LoggerFactory.getLogger(FileResources.class);
/*
* Used to get fully qualified name of the client
* or the last proxy that sent the request.
* Later used for querying locality of the file.
*/
@Context
private HttpServletRequest request;
@Inject
private PoolMonitor poolMonitor;
@Inject
private PathMapper pathMapper;
@Inject
private ListDirectoryHandler listDirectoryHandler;
@Inject
@Named("pool-manager-stub")
private CellStub poolmanager;
@Inject
@Named("pinManagerStub")
private CellStub pinmanager;
@Inject
@Named("pnfs-stub")
private CellStub pnfsmanager;
@Inject
@Named("qos-engine")
private CellStub qosEngine;
private boolean useQosService;
@GET
@ApiOperation(value = "Find metadata and optionally directory contents.",
notes = "The method offers the possibility to list the content of a "
+ "directory in addition to providing metadata of a "
+ "specified file or directory.")
@ApiResponses({
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 403, message = "Forbidden"),
@ApiResponse(code = 404, message = "Not Found"),
@ApiResponse(code = 500, message = "Internal Server Error"),
})
@Path("{path : .*}")
@Produces(MediaType.APPLICATION_JSON)
public JsonFileAttributes getFileAttributes(@ApiParam("Path of file or directory.")
@PathParam("path") String requestPath,
@ApiParam("Whether to include directory listing.")
@DefaultValue("false")
@QueryParam("children") boolean isList,
@ApiParam("Whether to include file locality information.")
@DefaultValue("false")
@QueryParam("locality") boolean isLocality,
@ApiParam(value = "Whether to include replica locations.")
@QueryParam("locations") boolean isLocations,
@ApiParam(value = "Whether to include quality of service.")
@DefaultValue("false")
@QueryParam("qos") boolean isQos,
@ApiParam("Whether to include extended attributes.")
@QueryParam("xattr") boolean isXattr,
@ApiParam("Whether to include labels.")
@QueryParam("labels") boolean isLabels,
@ApiParam("Whether or not to list checksum values.")
@QueryParam("checksum") boolean isChecksum,
@ApiParam("Whether or not to print optional attributes")
@DefaultValue("false")
@QueryParam("optional") boolean isOptional,
@ApiParam("Limit number of replies in directory listing.")
@QueryParam("limit") String limit,
@ApiParam("Number of entries to skip in directory listing.")
@QueryParam("offset") String offset) throws CacheException {
JsonFileAttributes fileAttributes = new JsonFileAttributes();
Set<FileAttribute> attributes =
NamespaceUtils.getRequestedAttributes(isLocality,
isLocations,
isQos,
isChecksum,
isOptional);
PnfsHandler handler = HandlerBuilders.roleAwarePnfsHandler(pnfsmanager);
FsPath path = pathMapper.asDcachePath(request, requestPath, ForbiddenException::new, handler);
try {
FileAttributes namespaceAttributes = handler.getFileAttributes(path, attributes);
NamespaceUtils.chimeraToJsonAttributes(path.name(), fileAttributes,
namespaceAttributes,
isLocality, isLocations, isLabels,
isOptional, isXattr, isChecksum,
request, poolMonitor);
if (isQos) {
NamespaceUtils.addQoSAttributes(fileAttributes,
namespaceAttributes,
request, poolMonitor, pinmanager);
}
// fill children list id it's a directory and listing is requested
if (namespaceAttributes.getFileType() == FileType.DIR && isList) {
Range<Integer> range;
try {
int lower = (offset == null) ? 0 : Integer.parseInt(offset);
int ceiling = (limit == null) ? Integer.MAX_VALUE : Integer.parseInt(limit);
if (ceiling < 0 || lower < 0) {
throw new BadRequestException(
"limit and offset can not be less than zero.");
}
range = (Integer.MAX_VALUE - lower < ceiling) ? Range.atLeast(lower)
: Range.closedOpen(lower, lower + ceiling);
} catch (NumberFormatException e) {
throw new BadRequestException("limit and offset must be an integer value.");
}
List<JsonFileAttributes> children = new ArrayList<>();
DirectoryStream stream = listDirectoryHandler.list(
HttpServletRequests.roleAwareSubject(request),
HttpServletRequests.roleAwareRestriction(request),
path,
null,
range,
attributes);
for (DirectoryEntry entry : stream) {
String fName = entry.getName();
JsonFileAttributes childrenAttributes = new JsonFileAttributes();
NamespaceUtils.chimeraToJsonAttributes(fName,
childrenAttributes,
entry.getFileAttributes(),
isLocality, isLocations, isLabels,
isOptional, isXattr, isChecksum,
request, poolMonitor);
childrenAttributes.setFileName(fName);
if (isQos) {
NamespaceUtils.addQoSAttributes(childrenAttributes,
entry.getFileAttributes(),
request, poolMonitor, pinmanager);
}
children.add(childrenAttributes);
}
fileAttributes.setChildren(children);
}
} catch (FileNotFoundCacheException e) {
throw new NotFoundException(e);
} catch (PermissionDeniedCacheException e) {
if (RequestUser.isAnonymous()) {
throw new NotAuthorizedException(e);
} else {
throw new ForbiddenException(e);
}
} catch (CacheException | InterruptedException | NoRouteToCellException ex) {
LOG.warn(Exceptions.meaningfulMessage(ex));
throw new InternalServerErrorException(ex);
}
return fileAttributes;
}
@POST
@ApiOperation(value = "Modify a file or directory.")
@Path("{path : .*}")
@ApiResponses({
@ApiResponse(code = 400, message = "Transition for directories not supported"),
@ApiResponse(code = 400, message = "Unsupported QoS transition"),
@ApiResponse(code = 400, message = "Unknown target QoS"),
@ApiResponse(code = 400, message = "Unknown action"),
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 403, message = "Forbidden"),
@ApiResponse(code = 404, message = "Not Found"),
@ApiResponse(code = 409, message = "Attribute already exists"),
@ApiResponse(code = 409, message = "No such attribute"),
@ApiResponse(code = 500, message = "Internal Server Error"),
})
@Consumes({MediaType.APPLICATION_JSON})
@Produces(MediaType.APPLICATION_JSON)
public Response cmrResources(
@ApiParam(value = "Path of file or directory to be modified.", required = true)
@PathParam("path") String requestPath,
@ApiParam(value = "A JSON object that has an 'action' "
+ "item with a String value.\n"
+ "\n"
+ "If the 'action' value is 'mkdir' "
+ "then a new directory is created "
+ "with the name taken from the "
+ "value of the JSON object 'name' "
+ "item. This directory is created "
+ "within the supplied path parameter, "
+ "which must be an existing directory.\n"
+ "\n"
+ "If action is 'mv' then the file "
+ "or directory specified by the path "
+ "parameter is moved and/or "
+ "renamed with the value of the JSON "
+ "object 'destination' item describing "
+ "the final location. If the "
+ "'destination' value is a relative "
+ "path then it is resolved against "
+ "the path parameter value.\n"
+ "\n"
+ "If action is 'qos' then the value "
+ "of the JSON object 'target' item "
+ "describes the desired QoS."
+ "\n"
+ "If action is 'pin' then the default "
+ "value of lifetime is 0 and liftime-unit "
+ "SECONDS."
+ "\n"
+ "If action is 'rm-xattr' then "
+ "extended attributes of a file "
+ "or directory are removed as "
+ "given by the 'names' item. The "
+ "'names' value is either a "
+ "string or an array of strings."
+ "\n"
+ "If action is 'set-xattr' then "
+ "extended attributes are created "
+ "or modified. The optional "
+ "'mode' item controls whether to "
+ "create a new attribute (CREATE), "
+ "to modify an existing attribute "
+ "(MODIFY), or to assign the value "
+ "by either creating a new "
+ "attribute or modifying an "
+ "existing attribute (EITHER). "
+ "EITHER is the default mode. The "
+ "'attributes' item value is a JSON "
+ "Object with the new attributes,"
+ "where the JSON Object's key is "
+ "the attribute name and the "
+ "corresponding JSON Object's "
+ "value is this attribute's value."
+ "\n"
+ "If action is 'set-label' then "
+ "a label is added to the"
+ "given file object."
+ "'label' item value is a String."
+ "\n"
+ "If action is 'rm-label' then the corresponding"
+ "label of a file is removed."
+ "The 'label' value is either a string."
+ "\n"
+ "If action is 'chgrp' then the "
+ "command requests the change of "
+ "group-owner of the target file "
+ "or directory. The value of the "
+ "JSON object 'gid' item is the "
+ "numerical value of the desired "
+ "new group-owner."
+ "\n"
+ "If action is 'chmod' then the "
+ "command reqests the change of "
+ "the target file's or directory's "
+ "permissions. The value of the "
+ "JSON object 'mode' item is the "
+ "numerical value of the desired "
+ "mode.",
required = true,
examples = @Example({
@ExampleProperty(mediaType = "MV",
value = "{\n"
+ " \"action\" : \"mv\",\n"
+ " \"destination\" : \"../foo\"\n"
+ "}"),
@ExampleProperty(mediaType = "MKDIR",
value = "{\n"
+ " \"action\" : \"mkdir\",\n"
+ " \"name\" : \"new-subdir\"\n"
+ "}"),
@ExampleProperty(mediaType = "QOS",
value = "{\n"
+ " \"action\" : \"qos\",\n"
+ " \"target\" : \"DISK+TAPE\"\n"
+ "}"),
@ExampleProperty(mediaType = "PIN",
value = "{\n"
+ " \"action\" : \"pin\",\n"
+ " \"lifetime\" : \"number\"\n"
+ " \"lifetime-unit\" : \"SECONDS|MINUTES|HOURS|DAYS\"\n"
+ "}"),
@ExampleProperty(mediaType = "UNPIN",
value = "{\n"
+ " \"action\" : \"unpin\",\n"
+ "}"),
@ExampleProperty(mediaType = "SET-XATTR",
value = "{\n"
+ " \"action\" : \"set-xattr\",\n"
+ " \"mode\" : \"CREATE\",\n"
+ " \"attributes\" : {\n"
+ " \"attr-1\": \"First attribute\",\n"
+ " \"attr-2\": \"Second attribute\"\n"
+ " }\n"
+ "}"),
@ExampleProperty(mediaType = "RM-XATTR",
value = "{\n"
+ " \"action\" : \"rm-xattr\",\n"
+ " \"names\" : [\n"
+ " \"attr-1\",\n"
+ " \"attr-2\"\n"
+ " ]\n"
+ "}"),
@ExampleProperty(mediaType = "SET-LABEL",
value = "{\n"
+ " \"action\" : \"set-label\",\n"
+ " \"label\" : : \"label\",\n"
+ "}"),
@ExampleProperty(mediaType = "RM-LABEL",
value = "{\n"
+ " \"action\" : \"rm-label\",\n"
+ " \"label\" : \"label\",\n"
+ "}"),
@ExampleProperty(mediaType = "CHGRP",
value = "{\n"
+ " \"action\" : \"chgrp\",\n"
+ " \"gid\" : 1000\n"
+ "}"),
@ExampleProperty(mediaType = "CHMOD",
value = "{\n"
+ " \"action\" : \"chmod\",\n"
+ " \"mode\" : 493\n"
+ "}")}))
String requestPayload) {
try {
JSONObject reqPayload = new JSONObject(requestPayload);
String action = (String) reqPayload.get("action");
PnfsHandler pnfsHandler = HandlerBuilders.roleAwarePnfsHandler(pnfsmanager);
FsPath path = pathMapper.asDcachePath(request, requestPath, ForbiddenException::new, pnfsHandler);
PnfsId pnfsId;
switch (action) {
case "mkdir":
String name = (String) reqPayload.get("name");
FsPath.checkChildName(name, BadRequestException::new);
pnfsHandler = HandlerBuilders.pnfsHandler(
pnfsmanager); // FIXME: non-role identity to ensure correct ownership
pnfsHandler.createPnfsDirectory(path.child(name).toString());
break;
case "mv":
String dest = (String) reqPayload.get("destination");
FsPath target = pathMapper.resolve(request, path.parent(), dest);
pnfsHandler.renameEntry(path.toString(), target.toString(), true);
break;
case "qos":
String targetQos =
reqPayload.has("target") ? reqPayload.getString("target") : null;
String qosPolicy =
reqPayload.has("policy") ? reqPayload.getString("policy") : null;
Integer qosState =
reqPayload.has("state") ? (Integer) reqPayload.get("state") : null;
Subject subject = RequestUser.getSubject();
if (!useQosService) {
new QoSTransitionEngine(poolmanager,
poolMonitor,
pnfsHandler,
pinmanager)
.adjustQoS(path,
targetQos, request.getRemoteHost());
} else {
/*
* fire and forget, does not wait for transition to complete
*/
FileAttributes attr
= pnfsHandler.getFileAttributes(path.toString(),
NamespaceUtils.getRequestedAttributes(false, false,
true, false, true));
FileQoSRequirements requirements = getBasicRequirements(targetQos,
qosPolicy, qosState, attr);
RemoteQoSRequirementsClient client = new RemoteQoSRequirementsClient();
client.setRequirementsService(qosEngine);
client.fileQoSRequirementsModified(requirements, subject);
}
break;
case "pin":
Integer lifetime = reqPayload.optInt("lifetime");
if (lifetime == null) {
lifetime = 0;
}
String lifetimeUnitVal = Strings.emptyToNull(
reqPayload.optString("lifetime-unit"));
TimeUnit lifetimeUnit = lifetimeUnitVal == null ?
TimeUnit.SECONDS : TimeUnit.valueOf(lifetimeUnitVal);
pnfsId = pnfsHandler.getPnfsIdByPath(path.toString());
/*
* Fire-and-forget, as it was in 5.2
*/
pinmanager.notify(new PinManagerPinMessage(FileAttributes.ofPnfsId(pnfsId),
getProtocolInfo(), getRequestId(),
lifetimeUnit.toMillis(lifetime)));
break;
case "unpin":
pnfsId = pnfsHandler.getPnfsIdByPath(path.toString());
PinManagerUnpinMessage message = new PinManagerUnpinMessage(pnfsId);
message.setRequestId(getRequestId());
pinmanager.notify(message);
break;
case "rm-xattr":
Object namesArgument = reqPayload.get("names");
if (namesArgument instanceof String) {
pnfsHandler.removeExtendedAttribute(path, (String) namesArgument);
} else if (namesArgument instanceof JSONArray) {
JSONArray namesArray = (JSONArray) namesArgument;
List<String> names = new ArrayList<>(namesArray.length());
for (int i = 0; i < namesArray.length(); i++) {
names.add(namesArray.getString(i));
}
pnfsHandler.removeExtendedAttribute(path, names);
} else {
throw new JSONException("\"names\" is not a String or an array");
}
break;
case "set-xattr":
String modeString = reqPayload.optString("mode", "EITHER");
Mode xattrSetMode = modeOf(modeString);
JSONObject attributeOject = reqPayload.getJSONObject("attributes");
Map<String, byte[]> attributes = new HashMap<>(attributeOject.length());
for (String key : attributeOject.keySet()) {
String value = attributeOject.getString(key);
attributes.put(key, value.getBytes(StandardCharsets.UTF_8));
}
pnfsHandler.writeExtendedAttribute(path, attributes, xattrSetMode);
break;
case "set-label":
String label = reqPayload.getString("label");
pnfsHandler.setFileAttributes(path, FileAttributes.ofLabel(label));
break;
case "rm-label":
String labelsArgument = reqPayload.getString("label");
pnfsHandler.removeLabel(path, labelsArgument);
break;
case "chgrp":
int gid = reqPayload.getInt("gid");
pnfsHandler.setFileAttributes(path, FileAttributes.ofGid(gid));
break;
case "chmod":
int mode = reqPayload.getInt("mode");
pnfsHandler.setFileAttributes(path, FileAttributes.ofMode(mode));
break;
default:
throw new UnsupportedOperationException("No such action " + action);
}
} catch (FileNotFoundCacheException e) {
throw new NotFoundException(e);
} catch (PermissionDeniedCacheException e) {
if (RequestUser.isAnonymous()) {
throw new NotAuthorizedException(e);
} else {
throw new ForbiddenException(e);
}
} catch (AttributeExistsCacheException e) {
throw new WebApplicationException(Response.status(409, "Attribute already exist")
.build());
} catch (NoAttributeCacheException e) {
throw new WebApplicationException(Response.status(409, "No such attribute")
.build());
} catch (NoRouteToCellException | InterruptedException e) {
throw new InternalServerErrorException(e.toString());
} catch (UnsupportedOperationException |
URISyntaxException |
JSONException |
CacheException e) {
throw new BadRequestException(e.getMessage(), e);
}
return successfulResponse(Response.Status.CREATED);
}
private ProtocolInfo getProtocolInfo() throws URISyntaxException {
return new HttpProtocolInfo("Http", 1, 1,
new InetSocketAddress("localhost", 0),
null, null, null,
new URI("http", "localhost", null, null));
}
private String getRequestId() throws PermissionDeniedCacheException {
if (RequestUser.isAnonymous()) {
throw new PermissionDeniedCacheException("cannot get request id for user.");
}
return String.valueOf(Subjects.getUid(RequestUser.getSubject()));
}
private Mode modeOf(String value) throws JSONException {
try {
return Mode.valueOf(value);
} catch (IllegalArgumentException e) {
throw new JSONException("Unknown mode \"" + value + "\", must be"
+ " one of " + Arrays.asList(Mode.values()));
}
}
@DELETE
@Path("{path : .*}")
@ApiOperation(value = "delete a file or directory",
notes = "If a directory is targeted then the directory must already be empty.")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses({
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 403, message = "Forbidden"),
@ApiResponse(code = 404, message = "Not Found"),
@ApiResponse(code = 500, message = "Internal Server Error"),
})
public Response deleteFileEntry(@ApiParam(value = "Path of file or directory.", required = true)
@PathParam("path") String requestPath) throws CacheException {
PnfsHandler handler = HandlerBuilders.roleAwarePnfsHandler(pnfsmanager);
FsPath path = pathMapper.asDcachePath(request, requestPath, ForbiddenException::new, handler);
try {
handler.deletePnfsEntry(path.toString());
} catch (FileNotFoundCacheException e) {
throw new NotFoundException(e);
} catch (PermissionDeniedCacheException e) {
if (RequestUser.isAnonymous()) {
throw new NotAuthorizedException(e);
} else {
throw new ForbiddenException(e);
}
} catch (JSONException | IllegalArgumentException | CacheException e) {
throw new BadRequestException(e);
} catch (Exception e) {
LOG.warn(Exceptions.meaningfulMessage(e));
throw new InternalServerErrorException(e);
}
return successfulResponse(Response.Status.OK);
}
@Required
public void setUseQosService(boolean useQosService) {
this.useQosService = useQosService;
}
private FileQoSRequirements getBasicRequirements(String targetQos, String qosPolicy,
Integer qosState, FileAttributes attributes) {
FileQoSRequirements requirements = new FileQoSRequirements(attributes.getPnfsId(),
attributes);
if (qosPolicy != null) {
requirements.setRequiredQoSPolicy(qosPolicy);
requirements.setRequiredQoSStateIndex( qosState == null ? 0 : qosState);
return requirements;
}
if (targetQos == null) {
throw new IllegalArgumentException("no target qos given.");
}
if (targetQos.toLowerCase(Locale.ROOT).contains("disk")) {
requirements.setRequiredDisk(1);
}
if (targetQos.toLowerCase(Locale.ROOT).contains("tape")) {
requirements.setRequiredTape(1);
}
return requirements;
}
}