33c8847ecfc1490d2a478dd03544f7ae9c9f6086
[dcaegen2/services.git] /
1 /*
2 * ============LICENSE_START=======================================================
3 * ONAP : DATALAKE
4 * ================================================================================
5 * Copyright 2019 China Mobile
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 * ============LICENSE_END=========================================================
19 */
20
21 package org.onap.datalake.feeder.service.db;
22
23 import java.util.ArrayList;
24 import java.util.List;
25 import java.util.UUID;
26
27 import javax.annotation.PostConstruct;
28 import javax.annotation.PreDestroy;
29
30 import org.json.JSONObject;
31 import org.onap.datalake.feeder.config.ApplicationConfiguration;
32 import org.onap.datalake.feeder.domain.Db;
33 import org.onap.datalake.feeder.domain.EffectiveTopic;
34 import org.onap.datalake.feeder.domain.Topic;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37 import org.springframework.beans.factory.annotation.Autowired;
38 import org.springframework.stereotype.Service;
39
40 import com.couchbase.client.java.Bucket;
41 import com.couchbase.client.java.Cluster;
42 import com.couchbase.client.java.CouchbaseCluster;
43 import com.couchbase.client.java.document.JsonDocument;
44 import com.couchbase.client.java.document.json.JsonObject;
45 import com.couchbase.client.java.env.CouchbaseEnvironment;
46 import com.couchbase.client.java.env.DefaultCouchbaseEnvironment;
47 import com.couchbase.client.java.error.DocumentAlreadyExistsException;
48
49 import rx.Observable;
50 import rx.functions.Func1;
51
52 /**
53  * Service to use Couchbase
54  * 
55  * @author Guobiao Mo
56  *
57  */
58 @Service
59 public class CouchbaseService implements DbStoreService {
60
61         private final Logger log = LoggerFactory.getLogger(this.getClass());
62
63         @Autowired
64         ApplicationConfiguration config;
65         
66         private Db couchbase;
67 /*
68         @Autowired
69         private DbService dbService;
70
71         private boolean isReady = false;
72 */
73         Bucket bucket;
74
75         public CouchbaseService( ) {
76                 
77         }
78         public CouchbaseService(Db db) {
79                 couchbase = db;
80         }
81         
82         @PostConstruct
83         private void init() {
84                 // Initialize Couchbase Connection
85                 try {
86                         //this tunes the SDK (to customize connection timeout)
87                         CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder().connectTimeout(60000) // 60s, default is 5s
88                                         .build();
89                         Cluster cluster = CouchbaseCluster.create(env, couchbase.getHost());
90                         cluster.authenticate(couchbase.getLogin(), couchbase.getPass());
91                         bucket = cluster.openBucket(couchbase.getDatabase());
92                         // Create a N1QL Primary Index (but ignore if it exists)
93                         bucket.bucketManager().createN1qlPrimaryIndex(true, false);
94
95                         log.info("Connected to Couchbase {} as {}", couchbase.getHost(), couchbase.getLogin());
96 //                      isReady = true;
97                 } catch (Exception ex) {
98                         log.error("error connection to Couchbase.", ex);
99         //              isReady = false;
100                 }
101         }
102
103         @PreDestroy
104         public void cleanUp() {
105                 config.getShutdownLock().readLock().lock();
106
107                 try {
108                         log.info("bucket.close() at cleanUp.");
109                         bucket.close();
110                 } finally {
111                         config.getShutdownLock().readLock().unlock();
112                 }
113         }
114
115         @Override
116         public void saveJsons(EffectiveTopic effectiveTopic, List<JSONObject> jsons) {
117                 List<JsonDocument> documents = new ArrayList<>(jsons.size());
118                 for (JSONObject json : jsons) {
119                         //convert to Couchbase JsonObject from org.json JSONObject
120                         JsonObject jsonObject = JsonObject.fromJson(json.toString());
121
122                         long timestamp = jsonObject.getLong(config.getTimestampLabel());//this is Kafka time stamp, which is added in StoreService.messageToJson()
123
124                         //setup TTL
125                         int expiry = (int) (timestamp / 1000L) + effectiveTopic.getTopic().getTtl() * 3600 * 24; //in second
126
127                         String id = getId(effectiveTopic.getTopic(), json);
128                         JsonDocument doc = JsonDocument.create(id, expiry, jsonObject);
129                         documents.add(doc);
130                 }
131                 try {
132                         saveDocuments(documents);
133                 } catch (DocumentAlreadyExistsException e) {
134                         log.error("Some or all the following ids are duplicate.");
135                         for(JsonDocument document : documents) {
136                                 log.error("saveJsons() DocumentAlreadyExistsException {}", document.id());
137                         }
138                 } catch (rx.exceptions.CompositeException e) {
139                         List<Throwable> causes = e.getExceptions();
140                         for(Throwable cause : causes) {
141                                 log.error("saveJsons() CompositeException cause {}", cause.getMessage());
142                         }                       
143                 } catch (Exception e) {
144                         log.error("error saving to Couchbase.", e);
145                 }
146                 log.debug("saved text to topic = {}, this batch count = {} ", effectiveTopic, documents.size());
147         }
148
149         public String getId(Topic topic, JSONObject json) {
150                 //if this topic requires extract id from JSON
151                 String id = topic.getMessageId(json);
152                 if (id != null) {
153                         return id;
154                 }
155
156                 String topicStr = topic.getName();
157                 id = topicStr+":"+UUID.randomUUID();
158
159                 //https://forums.couchbase.com/t/how-to-set-an-auto-increment-id/4892/2
160                 //atomically get the next sequence number:
161                 // increment by 1, initialize at 0 if counter doc not found
162                 //TODO how slow is this compared with above UUID approach?
163                 //sometimes this gives java.util.concurrent.TimeoutException
164                 //JsonLongDocument nextIdNumber = bucket.counter(topicStr, 1, 0); //like 12345 
165                 //id = topicStr + ":" + nextIdNumber.content();
166
167                 return id;
168         }
169
170         //https://docs.couchbase.com/java-sdk/2.7/document-operations.html
171         private void saveDocuments(List<JsonDocument> documents) {
172                 Observable.from(documents).flatMap(new Func1<JsonDocument, Observable<JsonDocument>>() {
173                         @Override
174                         public Observable<JsonDocument> call(final JsonDocument docToInsert) {
175                                 return bucket.async().insert(docToInsert);
176                         }
177                 }).last().toBlocking().single();
178         }
179
180 }