aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java
blob: d871a5073eb645ecce1c67c5655b92e79469b50d (plain)
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
/*
 * ============LICENSE_START==========================================
 * org.onap.music
 * ===================================================================
 *  Copyright (c) 2017 AT&T Intellectual Property
 * ===================================================================
 *  Licensed 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.
 * 
 * ============LICENSE_END=============================================
 * ====================================================================
 */
package org.onap.music.rest;

import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.onap.music.datastore.jsonobjects.JsonLeasedLock;
import org.onap.music.eelf.logging.EELFLoggerDelegate;
import org.onap.music.eelf.logging.format.AppMessages;
import org.onap.music.eelf.logging.format.ErrorSeverity;
import org.onap.music.eelf.logging.format.ErrorTypes;
import org.onap.music.lockingservice.MusicLockState;
import org.onap.music.main.MusicCore;
import org.onap.music.main.MusicUtil;
import org.onap.music.main.ResultType;
import org.onap.music.main.ReturnType;
import org.onap.music.response.jsonobjects.JsonResponse;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;


@Path("/v{version: [0-9]+}/locks/")
@Api(value="Lock Api")
public class RestMusicLocksAPI {

	@SuppressWarnings("unused")
    private EELFLoggerDelegate logger =EELFLoggerDelegate.getLogger(RestMusicLocksAPI.class);
	private static String xLatestVersion = "X-latestVersion";

	/**
	 * Puts the requesting process in the q for this lock. The corresponding
	 * node will be created in zookeeper if it did not already exist
	 * 
	 * @param lockName
	 * @return
	 * @throws Exception 
	 */

	@POST
	@Path("/create/{lockname}")
	@ApiOperation(value = "Create Lock",
		notes = "Puts the requesting process in the q for this lock." +
		" The corresponding node will be created in zookeeper if it did not already exist." +
		" Lock Name is the \"key\" of the form keyspaceName.tableName.rowId",
		response = Map.class)
	@Produces(MediaType.APPLICATION_JSON)	
	public Map<String,Object> createLockReference(
			@ApiParam(value="Lock Name",required=true) @PathParam("lockname") String lockName,
			@ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
            @ApiParam(value = "Application namespace",
                            required = true) @HeaderParam("ns") String ns,
            @ApiParam(value = "userId",
                            required = true) @HeaderParam("userId") String userId,
            @ApiParam(value = "Password",
                            required = true) @HeaderParam("password") String password,
			@Context HttpServletResponse response) throws Exception{
		response.addHeader(xLatestVersion,MusicUtil.getVersion());	
        Map<String, Object> resultMap = MusicCore.validateLock(lockName);
        if (resultMap.containsKey("Exception")) {
            return resultMap;
        }
        String keyspaceName = (String) resultMap.get("keyspace");
        resultMap.remove("keyspace");
        resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
                "createLockReference");
        if (resultMap.containsKey("aid"))
            resultMap.remove("aid");
        if (!resultMap.isEmpty()) {
                return resultMap;
        }
		ResultType status = ResultType.SUCCESS;
		String lockId = MusicCore.createLockReference(lockName);
		
		if (lockId == null) { 
			status = ResultType.FAILURE; 
			response.setStatus(400);
		}
		return new JsonResponse(status).setLock(lockId).toMap();
	}

	/**
	 * 
	 * Checks if the node is in the top of the queue and hence acquires the lock
	 * 
	 * @param lockId
	 * @return
	 * @throws Exception 
	 */
	@GET
	@Path("/acquire/{lockreference}")
	@ApiOperation(value = "Aquire Lock", 
		notes = "Checks if the node is in the top of the queue and hence acquires the lock",
		response = Map.class)
	@Produces(MediaType.APPLICATION_JSON)	
	public Map<String,Object> accquireLock(
			@ApiParam(value="Lock Reference",required=true) @PathParam("lockreference") String lockId,
			@ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
            @ApiParam(value = "Application namespace",
                            required = true) @HeaderParam("ns") String ns,
            @ApiParam(value = "userId",
                            required = true) @HeaderParam("userId") String userId,
            @ApiParam(value = "Password",
                            required = true) @HeaderParam("password") String password,
			@Context HttpServletResponse response) throws Exception{
		response.addHeader(xLatestVersion,MusicUtil.getVersion());
        Map<String, Object> resultMap = MusicCore.validateLock(lockId);
        if (resultMap.containsKey("Exception")) {
            return resultMap;
        }
        String keyspaceName = (String) resultMap.get("keyspace");
        resultMap.remove("keyspace");
        resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
                "accquireLock");
        if (resultMap.containsKey("aid"))
            resultMap.remove("aid");
        if (!resultMap.isEmpty()) {
                return resultMap;
        }
		try {
			String lockName = lockId.substring(lockId.indexOf('$')+1, lockId.lastIndexOf('$'));
			ReturnType lockStatus = MusicCore.acquireLock(lockName,lockId);
			return new JsonResponse(lockStatus.getResult()).setLock(lockId)
										.setMessage(lockStatus.getMessage()).toMap();
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger,AppMessages.INVALIDLOCK + lockId, ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
			resultMap.put("Exception","Unable to aquire lock");
			response.setStatus(400);
			return new JsonResponse(ResultType.FAILURE).setError("Unable to aquire lock").toMap();
		}
	}
	


	
	@POST
	@Path("/acquire-with-lease/{lockreference}")
	@ApiOperation(value = "Aquire Lock with Lease", response = Map.class)
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)	
	public Map<String,Object> accquireLockWithLease(JsonLeasedLock lockObj, 
			@ApiParam(value="Lock Reference",required=true) @PathParam("lockreference") String lockId,
			@ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
            @ApiParam(value = "Application namespace",
                            required = true) @HeaderParam("ns") String ns,
            @ApiParam(value = "userId",
                            required = true) @HeaderParam("userId") String userId,
            @ApiParam(value = "Password",
                            required = true) @HeaderParam("password") String password,
			@Context HttpServletResponse response) throws Exception{
		response.addHeader(xLatestVersion,MusicUtil.getVersion());
        Map<String, Object> resultMap = MusicCore.validateLock(lockId);
        if (resultMap.containsKey("Exception")) {
            return resultMap;
        }
        String keyspaceName = (String) resultMap.get("keyspace");
        resultMap.remove("keyspace");
        resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
                "accquireLockWithLease");

        if (resultMap.containsKey("aid"))
            resultMap.remove("aid");
        if (!resultMap.isEmpty()) {
            response.setStatus(400);    
        	return resultMap;
        }
		String lockName = lockId.substring(lockId.indexOf('$')+1, lockId.lastIndexOf('$'));
		ReturnType lockLeaseStatus = MusicCore.acquireLockWithLease(lockName, lockId, lockObj.getLeasePeriod());
		return new JsonResponse(lockLeaseStatus.getResult()).setLock(lockName)
									.setMessage(lockLeaseStatus.getMessage())
									.setLockLease(String.valueOf(lockObj.getLeasePeriod())).toMap();
	} 
	

	@GET
	@Path("/enquire/{lockname}")
	@ApiOperation(value = "Get Lock Holder", 
		notes = "Gets the current Lock Holder",
		response = Map.class)
	@Produces(MediaType.APPLICATION_JSON)	
	public Map<String,Object> currentLockHolder(
			@ApiParam(value="Lock Name",required=true) @PathParam("lockname") String lockName,
			@ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
            @ApiParam(value = "Application namespace",
                            required = true) @HeaderParam("ns") String ns,
            @ApiParam(value = "userId",
                            required = true) @HeaderParam("userId") String userId,
            @ApiParam(value = "Password",
                            required = true) @HeaderParam("password") String password,
			@Context HttpServletResponse response) throws Exception{
		response.addHeader(xLatestVersion,MusicUtil.getVersion());
        Map<String, Object> resultMap = MusicCore.validateLock(lockName);
        if (resultMap.containsKey("Exception")) {
            return resultMap;
        }
        String keyspaceName = (String) resultMap.get("keyspace");
        resultMap.remove("keyspace");
        resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
                "currentLockHolder");
        if (resultMap.containsKey("aid"))
            resultMap.remove("aid");
        if (!resultMap.isEmpty()) {
                return resultMap;
        }
		String who = MusicCore.whoseTurnIsIt(lockName);
		ResultType status = ResultType.SUCCESS;
		String error = "";
		if ( who == null ) { 
			status = ResultType.FAILURE; 
			error = "There was a problem getting the lock holder";
			response.setStatus(400);
		}
		return new JsonResponse(status).setError(error)
						.setLock(lockName).setLockHolder(who).toMap();
	}

	@GET
	@Path("/{lockname}")
	@ApiOperation(value = "Lock State",
		notes = "Returns current Lock State and Holder.",
		response = Map.class)
	@Produces(MediaType.APPLICATION_JSON)	
	public Map<String,Object> currentLockState(
			@ApiParam(value="Lock Name",required=true) @PathParam("lockname") String lockName,
			@ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
            @ApiParam(value = "Application namespace",
                            required = true) @HeaderParam("ns") String ns,
            @ApiParam(value = "userId",
                            required = true) @HeaderParam("userId") String userId,
            @ApiParam(value = "Password",
                            required = true) @HeaderParam("password") String password,
			@Context HttpServletResponse response) throws Exception{
		response.addHeader(xLatestVersion,MusicUtil.getVersion());
        Map<String, Object> resultMap = MusicCore.validateLock(lockName);
        if (resultMap.containsKey("Exception")) {
            return resultMap;
        }
        String keyspaceName = (String) resultMap.get("keyspace");
        resultMap.remove("keyspace");
        resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
                "currentLockState");
        
        if (resultMap.containsKey("aid"))
            resultMap.remove("aid");
        if (!resultMap.isEmpty()) {
        	response.setStatus(400);
                return resultMap;
        }
		
        MusicLockState mls = MusicCore.getMusicLockState(lockName);
		Map<String,Object> returnMap = null;
		JsonResponse jsonResponse = new JsonResponse(ResultType.FAILURE).setLock(lockName);
		if(mls == null) {
			jsonResponse.setError("");
			jsonResponse.setMessage("No lock object created yet..");
		} else { 
			jsonResponse.setStatus(ResultType.SUCCESS);
			jsonResponse.setLockStatus(mls.getLockStatus());
			jsonResponse.setLockHolder(mls.getLockHolder());
		} 
		return jsonResponse.toMap();
	}

	/**
	 * 
	 * deletes the process from the zk queue
	 * 
	 * @param lockId
	 * @throws Exception 
	 */
	@DELETE
	@Path("/release/{lockreference}")
	@ApiOperation(value = "Release Lock",
		notes = "deletes the process from the zk queue",
		response = Map.class)
	@Produces(MediaType.APPLICATION_JSON)	
	public Map<String,Object> unLock(@PathParam("lockreference") String lockId,
			@ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
            @ApiParam(value = "Application namespace",
                            required = true) @HeaderParam("ns") String ns,
            @ApiParam(value = "userId",
                            required = true) @HeaderParam("userId") String userId,
            @ApiParam(value = "Password",
                            required = true) @HeaderParam("password") String password,
			@Context HttpServletResponse response) throws Exception{
		response.addHeader(xLatestVersion,MusicUtil.getVersion());
        Map<String, Object> resultMap = MusicCore.validateLock(lockId);
        if (resultMap.containsKey("Exception")) {
            return resultMap;
        }
        String keyspaceName = (String) resultMap.get("keyspace");
        resultMap.remove("keyspace");
        resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
                "unLock");
        if (resultMap.containsKey("aid"))
            resultMap.remove("aid");
        if (!resultMap.isEmpty()) {
        	response.setStatus(400);
            return resultMap;
        }
		boolean voluntaryRelease = true; 
		MusicLockState mls = MusicCore.releaseLock(lockId,voluntaryRelease);
		if(mls.getErrorMessage() != null) {
			resultMap.put(ResultType.EXCEPTION.getResult(), mls.getErrorMessage());
			return resultMap;
		}
		Map<String,Object> returnMap = null;
		if (mls.getLockStatus() == MusicLockState.LockStatus.UNLOCKED) {
			returnMap = new JsonResponse(ResultType.SUCCESS).setLock(lockId)
								.setLockStatus(mls.getLockStatus()).toMap();
		}
		if (mls.getLockStatus() == MusicLockState.LockStatus.LOCKED) {
			returnMap = new JsonResponse(ResultType.FAILURE).setLock(lockId)
								.setLockStatus(mls.getLockStatus()).toMap();
		}
		return returnMap;
	}

	/**
	 * 
	 * @param lockName
	 * @throws Exception 
	 */
	@DELETE
	@Path("/delete/{lockname}")
	@ApiOperation(value = "Delete Lock", response = Map.class)
	@Produces(MediaType.APPLICATION_JSON)	
	public Map<String,Object> deleteLock(@PathParam("lockname") String lockName,
			@ApiParam(value = "AID", required = true) @HeaderParam("aid") String aid,
            @ApiParam(value = "Application namespace",
                            required = true) @HeaderParam("ns") String ns,
            @ApiParam(value = "userId",
                            required = true) @HeaderParam("userId") String userId,
            @ApiParam(value = "Password",
                            required = true) @HeaderParam("password") String password,
			@Context HttpServletResponse response) throws Exception{
		response.addHeader(xLatestVersion,MusicUtil.getVersion());
        Map<String, Object> resultMap = MusicCore.validateLock(lockName);
        if (resultMap.containsKey("Exception")) {
            return resultMap;
        }
        String keyspaceName = (String) resultMap.get("keyspace");
        resultMap.remove("keyspace");
        resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
                "deleteLock");
        if (resultMap.containsKey("aid"))
            resultMap.remove("aid");
        if (!resultMap.isEmpty()) {
        	response.setStatus(400);
            return resultMap;
        }
		MusicCore.deleteLock(lockName);
		return new JsonResponse(ResultType.SUCCESS).toMap();
	}

}