Merge "Docker update and POM fix"
[music.git] / src / main / java / org / onap / music / rest / RestMusicLocksAPI.java
1 /*
2  * ============LICENSE_START==========================================
3  * org.onap.music
4  * ===================================================================
5  *  Copyright (c) 2017 AT&T Intellectual Property
6  * ===================================================================
7  *  Licensed under the Apache License, Version 2.0 (the "License");
8  *  you may not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  * 
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS,
15  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  * 
19  * ============LICENSE_END=============================================
20  * ====================================================================
21  */
22 package org.onap.music.rest;
23
24 import java.util.Map;
25
26 import javax.servlet.http.HttpServletResponse;
27 import javax.ws.rs.Consumes;
28 import javax.ws.rs.DELETE;
29 import javax.ws.rs.GET;
30 import javax.ws.rs.HeaderParam;
31 import javax.ws.rs.POST;
32 import javax.ws.rs.Path;
33 import javax.ws.rs.PathParam;
34 import javax.ws.rs.Produces;
35 import javax.ws.rs.core.Context;
36 import javax.ws.rs.core.MediaType;
37
38 import org.onap.music.datastore.jsonobjects.JsonLeasedLock;
39 import org.onap.music.eelf.logging.EELFLoggerDelegate;
40 import org.onap.music.eelf.logging.format.AppMessages;
41 import org.onap.music.eelf.logging.format.ErrorSeverity;
42 import org.onap.music.eelf.logging.format.ErrorTypes;
43 import org.onap.music.lockingservice.MusicLockState;
44 import org.onap.music.main.MusicCore;
45 import org.onap.music.main.MusicUtil;
46 import org.onap.music.main.ResultType;
47 import org.onap.music.main.ReturnType;
48 import org.onap.music.response.jsonobjects.JsonResponse;
49
50 import io.swagger.annotations.Api;
51 import io.swagger.annotations.ApiOperation;
52 import io.swagger.annotations.ApiParam;
53
54
55 @Path("/v{version: [0-9]+}/locks/")
56 @Api(value="Lock Api")
57 public class RestMusicLocksAPI {
58
59         @SuppressWarnings("unused")
60     private EELFLoggerDelegate logger =EELFLoggerDelegate.getLogger(RestMusicLocksAPI.class);
61         private static String xLatestVersion = "X-latestVersion";
62
63         /**
64          * Puts the requesting process in the q for this lock. The corresponding
65          * node will be created in zookeeper if it did not already exist
66          * 
67          * @param lockName
68          * @return
69          * @throws Exception 
70          */
71
72         @POST
73         @Path("/create/{lockname}")
74         @ApiOperation(value = "Create Lock",
75                 notes = "Puts the requesting process in the q for this lock." +
76                 " The corresponding node will be created in zookeeper if it did not already exist." +
77                 " Lock Name is the \"key\" of the form keyspaceName.tableName.rowId",
78                 response = Map.class)
79         @Produces(MediaType.APPLICATION_JSON)   
80         public Map<String,Object> createLockReference(
81                         @ApiParam(value="Lock Name",required=true) @PathParam("lockname") String lockName,
82                         @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
83             @ApiParam(value = "Application namespace",
84                             required = true) @HeaderParam("ns") String ns,
85             @ApiParam(value = "userId",
86                             required = true) @HeaderParam("userId") String userId,
87             @ApiParam(value = "Password",
88                             required = true) @HeaderParam("password") String password,
89                         @Context HttpServletResponse response) throws Exception{
90                 response.addHeader(xLatestVersion,MusicUtil.getVersion());      
91         Map<String, Object> resultMap = MusicCore.validateLock(lockName);
92         if (resultMap.containsKey("Exception")) {
93             return resultMap;
94         }
95         String keyspaceName = (String) resultMap.get("keyspace");
96         resultMap.remove("keyspace");
97         resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
98                 "createLockReference");
99         if (resultMap.containsKey("aid"))
100             resultMap.remove("aid");
101         if (!resultMap.isEmpty()) {
102                 return resultMap;
103         }
104                 ResultType status = ResultType.SUCCESS;
105                 String lockId = MusicCore.createLockReference(lockName);
106                 
107                 if (lockId == null) { 
108                         status = ResultType.FAILURE; 
109                         response.setStatus(400);
110                 }
111                 return new JsonResponse(status).setLock(lockId).toMap();
112         }
113
114         /**
115          * 
116          * Checks if the node is in the top of the queue and hence acquires the lock
117          * 
118          * @param lockId
119          * @return
120          * @throws Exception 
121          */
122         @GET
123         @Path("/acquire/{lockreference}")
124         @ApiOperation(value = "Aquire Lock", 
125                 notes = "Checks if the node is in the top of the queue and hence acquires the lock",
126                 response = Map.class)
127         @Produces(MediaType.APPLICATION_JSON)   
128         public Map<String,Object> accquireLock(
129                         @ApiParam(value="Lock Reference",required=true) @PathParam("lockreference") String lockId,
130                         @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
131             @ApiParam(value = "Application namespace",
132                             required = true) @HeaderParam("ns") String ns,
133             @ApiParam(value = "userId",
134                             required = true) @HeaderParam("userId") String userId,
135             @ApiParam(value = "Password",
136                             required = true) @HeaderParam("password") String password,
137                         @Context HttpServletResponse response) throws Exception{
138                 response.addHeader(xLatestVersion,MusicUtil.getVersion());
139         Map<String, Object> resultMap = MusicCore.validateLock(lockId);
140         if (resultMap.containsKey("Exception")) {
141             return resultMap;
142         }
143         String keyspaceName = (String) resultMap.get("keyspace");
144         resultMap.remove("keyspace");
145         resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
146                 "accquireLock");
147         if (resultMap.containsKey("aid"))
148             resultMap.remove("aid");
149         if (!resultMap.isEmpty()) {
150                 return resultMap;
151         }
152                 try {
153                         String lockName = lockId.substring(lockId.indexOf('$')+1, lockId.lastIndexOf('$'));
154                         ReturnType lockStatus = MusicCore.acquireLock(lockName,lockId);
155                         return new JsonResponse(lockStatus.getResult()).setLock(lockId)
156                                                                                 .setMessage(lockStatus.getMessage()).toMap();
157                 } catch (Exception e) {
158                         logger.error(EELFLoggerDelegate.errorLogger,AppMessages.INVALIDLOCK + lockId, ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
159                         resultMap.put("Exception","Unable to aquire lock");
160                         response.setStatus(400);
161                         return new JsonResponse(ResultType.FAILURE).setError("Unable to aquire lock").toMap();
162                 }
163         }
164         
165
166
167         
168         @POST
169         @Path("/acquire-with-lease/{lockreference}")
170         @ApiOperation(value = "Aquire Lock with Lease", response = Map.class)
171         @Consumes(MediaType.APPLICATION_JSON)
172         @Produces(MediaType.APPLICATION_JSON)   
173         public Map<String,Object> accquireLockWithLease(JsonLeasedLock lockObj, 
174                         @ApiParam(value="Lock Reference",required=true) @PathParam("lockreference") String lockId,
175                         @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
176             @ApiParam(value = "Application namespace",
177                             required = true) @HeaderParam("ns") String ns,
178             @ApiParam(value = "userId",
179                             required = true) @HeaderParam("userId") String userId,
180             @ApiParam(value = "Password",
181                             required = true) @HeaderParam("password") String password,
182                         @Context HttpServletResponse response) throws Exception{
183                 response.addHeader(xLatestVersion,MusicUtil.getVersion());
184         Map<String, Object> resultMap = MusicCore.validateLock(lockId);
185         if (resultMap.containsKey("Exception")) {
186             return resultMap;
187         }
188         String keyspaceName = (String) resultMap.get("keyspace");
189         resultMap.remove("keyspace");
190         resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
191                 "accquireLockWithLease");
192
193         if (resultMap.containsKey("aid"))
194             resultMap.remove("aid");
195         if (!resultMap.isEmpty()) {
196             response.setStatus(400);    
197                 return resultMap;
198         }
199                 String lockName = lockId.substring(lockId.indexOf('$')+1, lockId.lastIndexOf('$'));
200                 ReturnType lockLeaseStatus = MusicCore.acquireLockWithLease(lockName, lockId, lockObj.getLeasePeriod());
201                 return new JsonResponse(lockLeaseStatus.getResult()).setLock(lockName)
202                                                                         .setMessage(lockLeaseStatus.getMessage())
203                                                                         .setLockLease(String.valueOf(lockObj.getLeasePeriod())).toMap();
204         } 
205         
206
207         @GET
208         @Path("/enquire/{lockname}")
209         @ApiOperation(value = "Get Lock Holder", 
210                 notes = "Gets the current Lock Holder",
211                 response = Map.class)
212         @Produces(MediaType.APPLICATION_JSON)   
213         public Map<String,Object> currentLockHolder(
214                         @ApiParam(value="Lock Name",required=true) @PathParam("lockname") String lockName,
215                         @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
216             @ApiParam(value = "Application namespace",
217                             required = true) @HeaderParam("ns") String ns,
218             @ApiParam(value = "userId",
219                             required = true) @HeaderParam("userId") String userId,
220             @ApiParam(value = "Password",
221                             required = true) @HeaderParam("password") String password,
222                         @Context HttpServletResponse response) throws Exception{
223                 response.addHeader(xLatestVersion,MusicUtil.getVersion());
224         Map<String, Object> resultMap = MusicCore.validateLock(lockName);
225         if (resultMap.containsKey("Exception")) {
226             return resultMap;
227         }
228         String keyspaceName = (String) resultMap.get("keyspace");
229         resultMap.remove("keyspace");
230         resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
231                 "currentLockHolder");
232         if (resultMap.containsKey("aid"))
233             resultMap.remove("aid");
234         if (!resultMap.isEmpty()) {
235                 return resultMap;
236         }
237                 String who = MusicCore.whoseTurnIsIt(lockName);
238                 ResultType status = ResultType.SUCCESS;
239                 String error = "";
240                 if ( who == null ) { 
241                         status = ResultType.FAILURE; 
242                         error = "There was a problem getting the lock holder";
243                         response.setStatus(400);
244                 }
245                 return new JsonResponse(status).setError(error)
246                                                 .setLock(lockName).setLockHolder(who).toMap();
247         }
248
249         @GET
250         @Path("/{lockname}")
251         @ApiOperation(value = "Lock State",
252                 notes = "Returns current Lock State and Holder.",
253                 response = Map.class)
254         @Produces(MediaType.APPLICATION_JSON)   
255         public Map<String,Object> currentLockState(
256                         @ApiParam(value="Lock Name",required=true) @PathParam("lockname") String lockName,
257                         @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
258             @ApiParam(value = "Application namespace",
259                             required = true) @HeaderParam("ns") String ns,
260             @ApiParam(value = "userId",
261                             required = true) @HeaderParam("userId") String userId,
262             @ApiParam(value = "Password",
263                             required = true) @HeaderParam("password") String password,
264                         @Context HttpServletResponse response) throws Exception{
265                 response.addHeader(xLatestVersion,MusicUtil.getVersion());
266         Map<String, Object> resultMap = MusicCore.validateLock(lockName);
267         if (resultMap.containsKey("Exception")) {
268             return resultMap;
269         }
270         String keyspaceName = (String) resultMap.get("keyspace");
271         resultMap.remove("keyspace");
272         resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
273                 "currentLockState");
274         
275         if (resultMap.containsKey("aid"))
276             resultMap.remove("aid");
277         if (!resultMap.isEmpty()) {
278                 response.setStatus(400);
279                 return resultMap;
280         }
281                 
282         MusicLockState mls = MusicCore.getMusicLockState(lockName);
283                 Map<String,Object> returnMap = null;
284                 JsonResponse jsonResponse = new JsonResponse(ResultType.FAILURE).setLock(lockName);
285                 if(mls == null) {
286                         jsonResponse.setError("");
287                         jsonResponse.setMessage("No lock object created yet..");
288                 } else { 
289                         jsonResponse.setStatus(ResultType.SUCCESS);
290                         jsonResponse.setLockStatus(mls.getLockStatus());
291                         jsonResponse.setLockHolder(mls.getLockHolder());
292                 } 
293                 return jsonResponse.toMap();
294         }
295
296         /**
297          * 
298          * deletes the process from the zk queue
299          * 
300          * @param lockId
301          * @throws Exception 
302          */
303         @DELETE
304         @Path("/release/{lockreference}")
305         @ApiOperation(value = "Release Lock",
306                 notes = "deletes the process from the zk queue",
307                 response = Map.class)
308         @Produces(MediaType.APPLICATION_JSON)   
309         public Map<String,Object> unLock(@PathParam("lockreference") String lockId,
310                         @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
311             @ApiParam(value = "Application namespace",
312                             required = true) @HeaderParam("ns") String ns,
313             @ApiParam(value = "userId",
314                             required = true) @HeaderParam("userId") String userId,
315             @ApiParam(value = "Password",
316                             required = true) @HeaderParam("password") String password,
317                         @Context HttpServletResponse response) throws Exception{
318                 response.addHeader(xLatestVersion,MusicUtil.getVersion());
319         Map<String, Object> resultMap = MusicCore.validateLock(lockId);
320         if (resultMap.containsKey("Exception")) {
321             return resultMap;
322         }
323         String keyspaceName = (String) resultMap.get("keyspace");
324         resultMap.remove("keyspace");
325         resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
326                 "unLock");
327         if (resultMap.containsKey("aid"))
328             resultMap.remove("aid");
329         if (!resultMap.isEmpty()) {
330                 response.setStatus(400);
331             return resultMap;
332         }
333                 boolean voluntaryRelease = true; 
334                 MusicLockState mls = MusicCore.releaseLock(lockId,voluntaryRelease);
335                 if(mls.getErrorMessage() != null) {
336                         resultMap.put(ResultType.EXCEPTION.getResult(), mls.getErrorMessage());
337                         return resultMap;
338                 }
339                 Map<String,Object> returnMap = null;
340                 if (mls.getLockStatus() == MusicLockState.LockStatus.UNLOCKED) {
341                         returnMap = new JsonResponse(ResultType.SUCCESS).setLock(lockId)
342                                                                 .setLockStatus(mls.getLockStatus()).toMap();
343                 }
344                 if (mls.getLockStatus() == MusicLockState.LockStatus.LOCKED) {
345                         returnMap = new JsonResponse(ResultType.FAILURE).setLock(lockId)
346                                                                 .setLockStatus(mls.getLockStatus()).toMap();
347                 }
348                 return returnMap;
349         }
350
351         /**
352          * 
353          * @param lockName
354          * @throws Exception 
355          */
356         @DELETE
357         @Path("/delete/{lockname}")
358         @ApiOperation(value = "Delete Lock", response = Map.class)
359         @Produces(MediaType.APPLICATION_JSON)   
360         public Map<String,Object> deleteLock(@PathParam("lockname") String lockName,
361                         @ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
362             @ApiParam(value = "Application namespace",
363                             required = true) @HeaderParam("ns") String ns,
364             @ApiParam(value = "userId",
365                             required = true) @HeaderParam("userId") String userId,
366             @ApiParam(value = "Password",
367                             required = true) @HeaderParam("password") String password,
368                         @Context HttpServletResponse response) throws Exception{
369                 response.addHeader(xLatestVersion,MusicUtil.getVersion());
370         Map<String, Object> resultMap = MusicCore.validateLock(lockName);
371         if (resultMap.containsKey("Exception")) {
372             return resultMap;
373         }
374         String keyspaceName = (String) resultMap.get("keyspace");
375         resultMap.remove("keyspace");
376         resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
377                 "deleteLock");
378         if (resultMap.containsKey("aid"))
379             resultMap.remove("aid");
380         if (!resultMap.isEmpty()) {
381                 response.setStatus(400);
382             return resultMap;
383         }
384                 MusicCore.deleteLock(lockName);
385                 return new JsonResponse(ResultType.SUCCESS).toMap();
386         }
387
388 }