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