c89a3b2cf705e3494d96b105c16bee4fba01904c
[dmaap/messagerouter/msgrtr.git] / src / main / java / com / att / dmf / mr / beans / DMaaPKafkaMetaBroker.java
1 /*******************************************************************************
2  *  ============LICENSE_START=======================================================
3  *  org.onap.dmaap
4  *  ================================================================================
5  *  Copyright © 2017 AT&T Intellectual Property. All rights reserved.
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  *        http://www.apache.org/licenses/LICENSE-2.0
11 *  
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *  ============LICENSE_END=========================================================
18  *  
19  *  ECOMP is a trademark and service mark of AT&T Intellectual Property.
20  *  
21  *******************************************************************************/
22 package com.att.dmf.mr.beans;
23
24 import java.util.Arrays;
25 import java.util.LinkedList;
26 import java.util.List;
27 import java.util.Properties;
28 import java.util.Set;
29 import java.util.TreeSet;
30 import java.util.concurrent.ExecutionException;
31
32 import org.I0Itec.zkclient.ZkClient;
33 import org.I0Itec.zkclient.exception.ZkNoNodeException;
34 import org.apache.kafka.clients.admin.AdminClient;
35 import org.apache.kafka.clients.admin.AdminClientConfig;
36 import org.apache.kafka.clients.admin.CreateTopicsResult;
37 import org.apache.kafka.clients.admin.NewTopic;
38 import org.apache.kafka.common.KafkaFuture;
39 import org.json.JSONObject;
40 import org.json.JSONArray;
41 import org.springframework.beans.factory.annotation.Qualifier;
42 import org.springframework.stereotype.Component;
43
44 import com.att.dmf.mr.CambriaApiException;
45 import com.att.dmf.mr.constants.CambriaConstants;
46 import com.att.dmf.mr.metabroker.Broker;
47 import com.att.dmf.mr.metabroker.Broker1;
48 import com.att.dmf.mr.metabroker.Topic;
49 import com.att.dmf.mr.utils.ConfigurationReader;
50 //import org.apache.log4-j.Logger;
51 import com.att.eelf.configuration.EELFLogger;
52 import com.att.eelf.configuration.EELFManager;
53
54 import com.att.nsa.configs.ConfigDb;
55 import com.att.nsa.configs.ConfigDbException;
56 import com.att.nsa.configs.ConfigPath;
57 import com.att.nsa.drumlin.service.standards.HttpStatusCodes;
58 import com.att.nsa.drumlin.till.nv.rrNvReadable;
59 import com.att.nsa.security.NsaAcl;
60 import com.att.nsa.security.NsaAclUtils;
61 import com.att.nsa.security.NsaApiKey;
62
63
64 /**
65  * class performing all topic operations
66  * 
67  * @author anowarul.islam
68  *
69  */
70 //@Component
71 public class DMaaPKafkaMetaBroker implements Broker1 {
72
73         public DMaaPKafkaMetaBroker() {
74                 fZk = null;
75                 fCambriaConfig = null;
76                 fBaseTopicData = null;
77                 final Properties props = new Properties ();
78                 String fkafkaBrokers = com.att.ajsc.filemonitor.AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,
79                                 "kafka.metadata.broker.list");
80                 if (null == fkafkaBrokers) {
81
82                         fkafkaBrokers = "localhost:9092";
83                 }
84                 
85              props.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, fkafkaBrokers );
86              props.put("sasl.jaas.config", "org.apache.kafka.common.security.plain.PlainLoginModule required username='admin' password='admin_secret';");
87                  props.put(AdminClientConfig.SECURITY_PROTOCOL_CONFIG, "SASL_PLAINTEXT");            
88              props.put("sasl.mechanism", "PLAIN");
89            
90              fKafkaAdminClient=AdminClient.create ( props );
91             
92         }
93
94         //private static final Logger log = Logger.getLogger(DMaaPKafkaMetaBroker.class);
95         private static final EELFLogger log = EELFManager.getInstance().getLogger(ConfigurationReader.class);
96         private final AdminClient fKafkaAdminClient;
97         
98         
99
100         /**
101          * DMaaPKafkaMetaBroker constructor initializing
102          * 
103          * @param settings
104          * @param zk
105          * @param configDb
106          */
107         public DMaaPKafkaMetaBroker(@Qualifier("propertyReader") rrNvReadable settings,
108                         @Qualifier("dMaaPZkClient") ZkClient zk, @Qualifier("dMaaPZkConfigDb") ConfigDb configDb) {
109                 //fSettings = settings;
110                 fZk = zk;
111                 fCambriaConfig = configDb;
112                 fBaseTopicData = configDb.parse("/topics");
113                 final Properties props = new Properties ();
114                 String fkafkaBrokers = com.att.ajsc.filemonitor.AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,
115                                 "kafka.metadata.broker.list");
116                 if (null == fkafkaBrokers) {
117
118                         fkafkaBrokers = "localhost:9092";
119                 }
120                 
121                 
122                  props.put("sasl.jaas.config", "org.apache.kafka.common.security.plain.PlainLoginModule required username='admin' password='admin_secret';");
123                  props.put(AdminClientConfig.SECURITY_PROTOCOL_CONFIG, "SASL_PLAINTEXT");            
124              props.put("sasl.mechanism", "PLAIN");
125              props.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, fkafkaBrokers );
126              
127              fKafkaAdminClient=AdminClient.create ( props );
128             
129                 
130                 
131         }
132         
133         public DMaaPKafkaMetaBroker( rrNvReadable settings,
134                         ZkClient zk,  ConfigDb configDb,AdminClient client) {
135                 
136                 fZk = zk;
137                 fCambriaConfig = configDb;
138                 fBaseTopicData = configDb.parse("/topics");
139             fKafkaAdminClient= client;
140            
141                 
142                 
143         }
144
145         @Override
146         public List<Topic> getAllTopics() throws ConfigDbException {
147                 log.info("Retrieving list of all the topics.");
148                 final LinkedList<Topic> result = new LinkedList<Topic>();
149                 try {
150                         log.info("Retrieving all topics from root: " + zkTopicsRoot);
151                         final List<String> topics = fZk.getChildren(zkTopicsRoot);
152                         for (String topic : topics) {
153                                 result.add(new KafkaTopic(topic, fCambriaConfig, fBaseTopicData));
154                         }
155                         JSONObject dataObj = new JSONObject();
156                         dataObj.put("topics", new JSONObject());
157
158                         for (String topic : topics) {
159                                 dataObj.getJSONObject("topics").put(topic, new JSONObject());
160                         }
161                 } catch (ZkNoNodeException excp) {
162                         // very fresh kafka doesn't have any topics or a topics node
163                         log.error("ZK doesn't have a Kakfa topics node at " + zkTopicsRoot, excp);
164                 }
165                 return result;
166         }
167
168         @Override
169         public Topic getTopic(String topic) throws ConfigDbException {
170                 if (fZk.exists(zkTopicsRoot + "/" + topic)) {
171                         return getKafkaTopicConfig(fCambriaConfig, fBaseTopicData, topic);
172                 }
173                 // else: no such topic in kafka
174                 return null;
175         }
176
177         /**
178          * static method get KafkaTopic object
179          * 
180          * @param db
181          * @param base
182          * @param topic
183          * @return
184          * @throws ConfigDbException
185          */
186         public static KafkaTopic getKafkaTopicConfig(ConfigDb db, ConfigPath base, String topic) throws ConfigDbException {
187                 return new KafkaTopic(topic, db, base);
188         }
189
190         /**
191          * creating topic
192          */
193         @Override
194         public Topic createTopic(String topic, String desc, String ownerApiKey, int partitions, int replicas,
195                         boolean transactionEnabled) throws TopicExistsException, CambriaApiException,ConfigDbException {
196                 log.info("Creating topic: " + topic);
197                 try {
198                         log.info("Check if topic [" + topic + "] exist.");
199                         // first check for existence "our way"
200                         final Topic t = getTopic(topic);
201                         if (t != null) {
202                                 log.info("Could not create topic [" + topic + "]. Topic Already exists.");
203                                 throw new TopicExistsException("Could not create topic [" + topic + "]. Topic Alreay exists.");
204                         }
205                 } catch (ConfigDbException e1) {
206                         log.error("Topic [" + topic + "] could not be created. Couldn't check topic data in config db.", e1);
207                         throw new CambriaApiException(HttpStatusCodes.k503_serviceUnavailable,
208                                         "Couldn't check topic data in config db.");
209                 }
210
211                 // we only allow 3 replicas. (If we don't test this, we get weird
212                 // results from the cluster,
213                 // so explicit test and fail.)
214                 if (replicas < 1 || replicas > 3) {
215                         log.info("Topic [" + topic + "] could not be created. The replica count must be between 1 and 3.");
216                         throw new CambriaApiException(HttpStatusCodes.k400_badRequest,
217                                         "The replica count must be between 1 and 3.");
218                 }
219                 if (partitions < 1) {
220                         log.info("Topic [" + topic + "] could not be created. The partition count must be at least 1.");
221                         throw new CambriaApiException(HttpStatusCodes.k400_badRequest, "The partition count must be at least 1.");
222                 }
223
224                 // create via kafka
225                 
226                         try
227                         {
228                                 final NewTopic topicRequest = new NewTopic ( topic, partitions, new Integer(replicas).shortValue () );
229                                 final CreateTopicsResult ctr = fKafkaAdminClient.createTopics ( Arrays.asList ( topicRequest ) );
230                                 final KafkaFuture<Void> ctrResult = ctr.all ();
231                                 ctrResult.get ();
232                                 // underlying Kafka topic created. now setup our API info
233                                 return createTopicEntry ( topic, desc, ownerApiKey, transactionEnabled );
234                         }
235                         catch ( InterruptedException e )
236                         {
237                                 
238                                 log.warn ( "Execution of describeTopics timed out." );
239                                 throw new ConfigDbException ( e );
240                         }
241                         catch ( ExecutionException e )
242                         {
243                                 
244                                 log.warn ( "Execution of describeTopics failed: " + e.getCause ().getMessage (), e.getCause () );
245                                 throw new ConfigDbException ( e.getCause () );
246                         }
247                 
248         }
249
250         @Override
251         public void deleteTopic(String topic) throws CambriaApiException, TopicExistsException,ConfigDbException {
252                 log.info("Deleting topic: " + topic);
253                 ZkClient zkClient = null;
254                 try {
255                         log.info("Loading zookeeper client for topic deletion.");
256                                         // topic creation. (Otherwise, the topic is only partially created
257                         // in ZK.)
258                         
259                         
260                         fKafkaAdminClient.deleteTopics(Arrays.asList(topic));
261                         log.info("Zookeeper client loaded successfully. Deleting topic.");
262                         
263                 } catch (Exception e) {
264                         log.error("Failed to delete topic [" + topic + "]. " + e.getMessage(), e);
265                         throw new ConfigDbException(e);
266                 }  finally {
267                         log.info("Closing zookeeper connection.");
268                         if (zkClient != null)
269                                 zkClient.close();
270                 }
271
272                 // throw new UnsupportedOperationException ( "We can't programmatically
273                 // delete Kafka topics yet." );
274         }
275
276         //private final rrNvReadable fSettings;
277         private final ZkClient fZk;
278         private final ConfigDb fCambriaConfig;
279         private final ConfigPath fBaseTopicData;
280
281         private static final String zkTopicsRoot = "/brokers/topics";
282         private static final JSONObject kEmptyAcl = new JSONObject();
283
284         /**
285          * method Providing KafkaTopic Object associated with owner and
286          * transactionenabled or not
287          * 
288          * @param name
289          * @param desc
290          * @param owner
291          * @param transactionEnabled
292          * @return
293          * @throws ConfigDbException
294          */
295         public KafkaTopic createTopicEntry(String name, String desc, String owner, boolean transactionEnabled)
296                         throws ConfigDbException {
297                 return createTopicEntry(fCambriaConfig, fBaseTopicData, name, desc, owner, transactionEnabled);
298         }
299
300         /**
301          * static method giving kafka topic object
302          * 
303          * @param db
304          * @param basePath
305          * @param name
306          * @param desc
307          * @param owner
308          * @param transactionEnabled
309          * @return
310          * @throws ConfigDbException
311          */
312         public static KafkaTopic createTopicEntry(ConfigDb db, ConfigPath basePath, String name, String desc, String owner,
313                         boolean transactionEnabled) throws ConfigDbException {
314                 final JSONObject o = new JSONObject();
315                 o.put("owner", owner);
316                 o.put("description", desc);
317                 o.put("txenabled", transactionEnabled);
318                 db.store(basePath.getChild(name), o.toString());
319                 return new KafkaTopic(name, db, basePath);
320         }
321
322         /**
323          * class performing all user opearation like user is eligible to read,
324          * write. permitting a user to write and read,
325          * 
326          * @author anowarul.islam
327          *
328          */
329         public static class KafkaTopic implements Topic {
330                 /**
331                  * constructor initializes
332                  * 
333                  * @param name
334                  * @param configdb
335                  * @param baseTopic
336                  * @throws ConfigDbException
337                  */
338                 public KafkaTopic(String name, ConfigDb configdb, ConfigPath baseTopic) throws ConfigDbException {
339                         fName = name;
340                         fConfigDb = configdb;
341                         fBaseTopicData = baseTopic;
342
343                         String data = fConfigDb.load(fBaseTopicData.getChild(fName));
344                         if (data == null) {
345                                 data = "{}";
346                         }
347
348                         final JSONObject o = new JSONObject(data);
349                         fOwner = o.optString("owner", "");
350                         fDesc = o.optString("description", "");
351                         fTransactionEnabled = o.optBoolean("txenabled", false);// default
352                                                                                                                                         // value is
353                                                                                                                                         // false
354                         // if this topic has an owner, it needs both read/write ACLs. If there's no
355                                                 // owner (or it's empty), null is okay -- this is for existing or implicitly
356                                                 // created topics.
357                                                 JSONObject readers = o.optJSONObject ( "readers" );
358                                                 if ( readers == null && fOwner.length () > 0 ) readers = kEmptyAcl;
359                                                 fReaders =  fromJson ( readers );
360
361                                                 JSONObject writers = o.optJSONObject ( "writers" );
362                                                 if ( writers == null && fOwner.length () > 0 ) writers = kEmptyAcl;
363                                                 fWriters = fromJson ( writers );
364                 }
365                 
366                 private NsaAcl fromJson(JSONObject o) {
367                         NsaAcl acl = new NsaAcl();
368                         if (o != null) {
369                                 JSONArray a = o.optJSONArray("allowed");
370                                 if (a != null) {
371                                         for (int i = 0; i < a.length(); ++i) {
372                                                 String user = a.getString(i);
373                                                 acl.add(user);
374                                         }
375                                 }
376                         }
377                         return acl;
378                 }
379
380                 @Override
381                 public String getName() {
382                         return fName;
383                 }
384
385                 @Override
386                 public String getOwner() {
387                         return fOwner;
388                 }
389
390                 @Override
391                 public String getDescription() {
392                         return fDesc;
393                 }
394
395                 @Override
396                 public NsaAcl getReaderAcl() {
397                         return fReaders;
398                 }
399
400                 @Override
401                 public NsaAcl getWriterAcl() {
402                         return fWriters;
403                 }
404
405                 @Override
406                 public void checkUserRead(NsaApiKey user) throws AccessDeniedException  {
407                         NsaAclUtils.checkUserAccess ( fOwner, getReaderAcl(), user );
408                 }
409
410                 @Override
411                 public void checkUserWrite(NsaApiKey user) throws AccessDeniedException  {
412                         NsaAclUtils.checkUserAccess ( fOwner, getWriterAcl(), user );
413                 }
414
415                 @Override
416                 public void permitWritesFromUser(String pubId, NsaApiKey asUser)
417                                 throws ConfigDbException, AccessDeniedException {
418                         updateAcl(asUser, false, true, pubId);
419                 }
420
421                 @Override
422                 public void denyWritesFromUser(String pubId, NsaApiKey asUser) throws ConfigDbException, AccessDeniedException {
423                         updateAcl(asUser, false, false, pubId);
424                 }
425
426                 @Override
427                 public void permitReadsByUser(String consumerId, NsaApiKey asUser)
428                                 throws ConfigDbException, AccessDeniedException {
429                         updateAcl(asUser, true, true, consumerId);
430                 }
431
432                 @Override
433                 public void denyReadsByUser(String consumerId, NsaApiKey asUser)
434                                 throws ConfigDbException, AccessDeniedException {
435                         updateAcl(asUser, true, false, consumerId);
436                 }
437
438                 private void updateAcl(NsaApiKey asUser, boolean reader, boolean add, String key)
439                                 throws ConfigDbException, AccessDeniedException{
440                         try
441                         {
442                                 final NsaAcl acl = NsaAclUtils.updateAcl ( this, asUser, key, reader, add );
443         
444                                 // we have to assume we have current data, or load it again. for the expected use
445                                 // case, assuming we can overwrite the data is fine.
446                                 final JSONObject o = new JSONObject ();
447                                 o.put ( "owner", fOwner );
448                                 o.put ( "readers", safeSerialize ( reader ? acl : fReaders ) );
449                                 o.put ( "writers", safeSerialize ( reader ? fWriters : acl ) );
450                                 fConfigDb.store ( fBaseTopicData.getChild ( fName ), o.toString () );
451                                 
452                                 log.info ( "ACL_UPDATE: " + asUser.getKey () + " " + ( add ? "added" : "removed" ) + ( reader?"subscriber":"publisher" ) + " " + key + " on " + fName );
453         
454                         }
455                         catch ( ConfigDbException x )
456                         {
457                                 throw x;
458                         }
459                         catch ( AccessDeniedException x )
460                         {
461                                 throw x;
462                         }
463                         
464                 }
465
466                 private JSONObject safeSerialize(NsaAcl acl) {
467                         return acl == null ? null : acl.serialize();
468                 }
469
470                 private final String fName;
471                 private final ConfigDb fConfigDb;
472                 private final ConfigPath fBaseTopicData;
473                 private final String fOwner;
474                 private final String fDesc;
475                 private final NsaAcl fReaders;
476                 private final NsaAcl fWriters;
477                 private boolean fTransactionEnabled;
478         
479                 public boolean isTransactionEnabled() {
480                         return fTransactionEnabled;
481                 }
482
483                 @Override
484                 public Set<String> getOwners() {
485                         final TreeSet<String> owners = new TreeSet<String> ();
486                         owners.add ( fOwner );
487                         return owners;
488                 }
489         }
490
491 }