aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/org/onap/music/rest/RestMusicBmAPI.java
blob: f2946c14babcf28e262236375981196e0b9a9b8f (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
/*
 * ============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.List;
import java.util.Map;
import java.util.UUID;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
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 javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriInfo;
import org.onap.music.datastore.jsonobjects.JsonInsert;
import org.onap.music.eelf.logging.EELFLoggerDelegate;
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.service.impl.MusicZKCore;
import org.onap.music.datastore.MusicDataStoreHandle;
import org.onap.music.datastore.PreparedQueryObject;
import com.datastax.driver.core.DataType;
import com.datastax.driver.core.TableMetadata;
import io.swagger.annotations.Api;

/*
 * These are functions created purely for benchmarking purposes. Commented out Swagger - This should
 * be undocumented API
 * 
 */
@Path("/v{version: [0-9]+}/benchmarks/")
@Api(value = "Benchmark API", hidden = true)
public class RestMusicBmAPI {

    private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicBmAPI.class);
    public static final String UPDATE_CONST=" update-";
    // pure zk calls...

    /**
     * 
     * @param nodeName
     * @throws Exception
     */
    @POST
    @Path("/purezk/{name}")
    @Consumes(MediaType.APPLICATION_JSON)
    public void pureZkCreate(@PathParam("name") String nodeName) throws Exception {
        MusicZKCore.pureZkCreate("/" + nodeName);
    }


    /**
     * 
     * @param insObj
     * @param nodeName
     * @throws Exception
     */
    @PUT
    @Path("/purezk/{name}")
    @Consumes(MediaType.APPLICATION_JSON)
    public void pureZkUpdate(JsonInsert insObj, @PathParam("name") String nodeName)
                    throws Exception {
        logger.info(EELFLoggerDelegate.applicationLogger,"--------------Zk normal update-------------------------");
        long start = System.currentTimeMillis();
        MusicZKCore.pureZkWrite(nodeName, insObj.serialize());
        long end = System.currentTimeMillis();
        logger.info(EELFLoggerDelegate.applicationLogger,"Total time taken for Zk normal update:" + (end - start) + " ms");
    }

    /**
     * 
     * @param nodeName
     * @return
     * @throws Exception
     */
    @GET
    @Path("/purezk/{name}")
    @Consumes(MediaType.TEXT_PLAIN)
    public byte[] pureZkGet(@PathParam("name") String nodeName) throws Exception {
        return MusicZKCore.pureZkRead(nodeName);
    }

    /**
     * 
     * @param insObj
     * @param lockName
     * @param nodeName
     * @throws Exception
     */
    @PUT
    @Path("/purezk/atomic/{lockname}/{name}")
    @Consumes(MediaType.APPLICATION_JSON)
    public void pureZkAtomicPut(JsonInsert updateObj, @PathParam("lockname") String lockname,
                    @PathParam("name") String nodeName) throws Exception {
        long startTime = System.currentTimeMillis();
        String operationId = UUID.randomUUID().toString();// just for debugging purposes.
        String consistency = updateObj.getConsistencyInfo().get("type");

        logger.info(EELFLoggerDelegate.applicationLogger,"--------------Zookeeper " + consistency + UPDATE_CONST + operationId
                        + "-------------------------");

        byte[] data = updateObj.serialize();
        long jsonParseCompletionTime = System.currentTimeMillis();

        String lockId = MusicCore.createLockReference(lockname);

        long lockCreationTime = System.currentTimeMillis();

        long leasePeriod = MusicUtil.getDefaultLockLeasePeriod();
        ReturnType lockAcqResult = MusicCore.acquireLockWithLease(lockname, lockId, leasePeriod);
        long lockAcqTime = System.currentTimeMillis();
        long zkPutTime = 0;
        long lockReleaseTime = 0;

        if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) {
            logger.info(EELFLoggerDelegate.applicationLogger,"acquired lock with id " + lockId);
            MusicZKCore.pureZkWrite(lockname, data);
            zkPutTime = System.currentTimeMillis();
            boolean voluntaryRelease = true;
/*<<<<<<< HEAD
            if (("atomic").equals(consistency))
                MusicCore.releaseLock(lockId, voluntaryRelease);
            else if (("atomic_delete_lock").equals(consistency))
                MusicCore.deleteLock(lockname);
=======*/
            if (consistency.equals("atomic"))
                MusicCore.releaseLock(lockId, voluntaryRelease);
            else if (consistency.equals("atomic_delete_lock"))
                MusicCore.deleteLock(lockname);
            lockReleaseTime = System.currentTimeMillis();
        } else {
            MusicCore.destroyLockRef(lockId);
        }

        long actualUpdateCompletionTime = System.currentTimeMillis();


        long endTime = System.currentTimeMillis();

        String lockingInfo = "|lock creation time:" + (lockCreationTime - jsonParseCompletionTime)
                        + "|lock accquire time:" + (lockAcqTime - lockCreationTime)
                        + "|zk put time:" + (zkPutTime - lockAcqTime);

        if ("atomic".equals(consistency))
            lockingInfo = lockingInfo + "|lock release time:" + (lockReleaseTime - zkPutTime) + "|";
        else if ("atomic_delete_lock".equals(consistency))
            lockingInfo = lockingInfo + "|lock delete time:" + (lockReleaseTime - zkPutTime) + "|";

        String timingString = "Time taken in ms for Zookeeper " + consistency + UPDATE_CONST
                        + operationId + ":" + "|total operation time:" + (endTime - startTime)
                        + "|json parsing time:" + (jsonParseCompletionTime - startTime)
                        + "|update time:" + (actualUpdateCompletionTime - jsonParseCompletionTime)
                        + lockingInfo;

        logger.info(EELFLoggerDelegate.applicationLogger,timingString);
    }

    /**
     * 
     * @param insObj
     * @param lockName
     * @param nodeName
     * @throws Exception
     */
    @GET
    @Path("/purezk/atomic/{lockname}/{name}")
    @Consumes(MediaType.APPLICATION_JSON)
    public void pureZkAtomicGet(JsonInsert insObj, @PathParam("lockname") String lockName,
                    @PathParam("name") String nodeName) throws Exception {
        logger.info("--------------Zk atomic read-------------------------");
        long start = System.currentTimeMillis();
        String lockId = MusicCore.createLockReference(lockName);
        long leasePeriod = MusicUtil.getDefaultLockLeasePeriod();
        ReturnType lockAcqResult = MusicCore.acquireLockWithLease(lockName, lockId, leasePeriod);
        if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) {
            logger.info("acquired lock with id " + lockId);
            MusicZKCore.pureZkRead(nodeName);
            boolean voluntaryRelease = true;
            MusicCore.releaseLock(lockId, voluntaryRelease);
        } else {
            MusicCore.destroyLockRef(lockId);
        }

        long end = System.currentTimeMillis();
        logger.info(EELFLoggerDelegate.applicationLogger,"Total time taken for Zk atomic read:" + (end - start) + " ms");
    }

    /**
     *
     * doing an update directly to cassa but through the rest api
     * 
     * @param insObj
     * @param keyspace
     * @param tablename
     * @param info
     * @return
     * @throws Exception
     */
    @PUT
    @Path("/cassa/keyspaces/{keyspace}/tables/{tablename}/rows")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public boolean updateTableCassa(JsonInsert insObj, @PathParam("keyspace") String keyspace,
                    @PathParam("tablename") String tablename, @Context UriInfo info)
                    throws Exception {
        long startTime = System.currentTimeMillis();
        String operationId = UUID.randomUUID().toString();// just for debugging purposes.
        String consistency = insObj.getConsistencyInfo().get("type");
        logger.info(EELFLoggerDelegate.applicationLogger,"--------------Cassandra " + consistency + UPDATE_CONST + operationId
                        + "-------------------------");
        PreparedQueryObject queryObject = new PreparedQueryObject();
        Map<String, Object> valuesMap = insObj.getValues();
        TableMetadata tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename);
        String vectorTs = "'" + Thread.currentThread().getId() + System.currentTimeMillis() + "'";
        String fieldValueString = "vector_ts= ? ,";
        queryObject.addValue(vectorTs);

        int counter = 0;
        for (Map.Entry<String, Object> entry : valuesMap.entrySet()) {
            Object valueObj = entry.getValue();
            DataType colType = tableInfo.getColumn(entry.getKey()).getType();
            Object valueString = MusicUtil.convertToActualDataType(colType, valueObj);
            fieldValueString = fieldValueString + entry.getKey() + "= ?";
            queryObject.addValue(valueString);
            if (counter != valuesMap.size() - 1)
                fieldValueString = fieldValueString + ",";
            counter = counter + 1;
        }

        // get the row specifier
        String rowSpec = "";
        counter = 0;
        queryObject.appendQueryString("UPDATE " + keyspace + "." + tablename + " ");
        MultivaluedMap<String, String> rowParams = info.getQueryParameters();
        String primaryKey = "";
        for (MultivaluedMap.Entry<String, List<String>> entry : rowParams.entrySet()) {
            String keyName = entry.getKey();
            List<String> valueList = entry.getValue();
            String indValue = valueList.get(0);
            DataType colType = tableInfo.getColumn(entry.getKey()).getType();
            Object formattedValue = MusicUtil.convertToActualDataType(colType, indValue);
            primaryKey = primaryKey + indValue;
            rowSpec = rowSpec + keyName + "= ? ";
            queryObject.addValue(formattedValue);
            if (counter != rowParams.size() - 1)
                rowSpec = rowSpec + " AND ";
            counter = counter + 1;
        }


        String ttl = insObj.getTtl();
        String timestamp = insObj.getTimestamp();

        if ((ttl != null) && (timestamp != null)) {

            logger.info(EELFLoggerDelegate.applicationLogger,"both there");
            queryObject.appendQueryString(" USING TTL ? AND TIMESTAMP ?");
            queryObject.addValue(Integer.parseInt(ttl));
            queryObject.addValue(Long.parseLong(timestamp));
        }

        if ((ttl != null) && (timestamp == null)) {
            logger.info(EELFLoggerDelegate.applicationLogger,"ONLY TTL there");
            queryObject.appendQueryString(" USING TTL ?");
            queryObject.addValue(Integer.parseInt(ttl));
        }

        if ((ttl == null) && (timestamp != null)) {
            logger.info(EELFLoggerDelegate.applicationLogger,"ONLY timestamp there");
            queryObject.appendQueryString(" USING TIMESTAMP ?");
            queryObject.addValue(Long.parseLong(timestamp));
        }
        queryObject.appendQueryString(" SET " + fieldValueString + " WHERE " + rowSpec + ";");

        long jsonParseCompletionTime = System.currentTimeMillis();

        boolean operationResult = true;
        MusicDataStoreHandle.getDSHandle().executePut(queryObject, insObj.getConsistencyInfo().get("type"));

        long actualUpdateCompletionTime = System.currentTimeMillis();

        long endTime = System.currentTimeMillis();

        String timingString = "Time taken in ms for Cassandra " + consistency + UPDATE_CONST
                        + operationId + ":" + "|total operation time:" + (endTime - startTime)
                        + "|json parsing time:" + (jsonParseCompletionTime - startTime)
                        + "|update time:" + (actualUpdateCompletionTime - jsonParseCompletionTime)
                        + "|";
        logger.info(EELFLoggerDelegate.applicationLogger,timingString);

        return operationResult;
    }
}