1 /*******************************************************************************
2 * ============LICENSE_START=======================================================
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
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=========================================================
19 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21 *******************************************************************************/
22 package org.onap.dmaap.dmf.mr.beans;
24 import com.att.eelf.configuration.EELFLogger;
25 import com.att.eelf.configuration.EELFManager;
26 import com.att.nsa.configs.ConfigDb;
27 import com.att.nsa.configs.ConfigDbException;
28 import com.att.nsa.configs.ConfigPath;
29 import com.att.nsa.drumlin.service.standards.HttpStatusCodes;
30 import com.att.nsa.drumlin.till.nv.rrNvReadable;
31 import com.att.nsa.security.NsaAcl;
32 import com.att.nsa.security.NsaAclUtils;
33 import com.att.nsa.security.NsaApiKey;
34 import org.I0Itec.zkclient.ZkClient;
35 import org.I0Itec.zkclient.exception.ZkNoNodeException;
36 import org.apache.kafka.clients.admin.AdminClient;
37 import org.apache.kafka.clients.admin.AdminClientConfig;
38 import org.apache.kafka.clients.admin.CreateTopicsResult;
39 import org.apache.kafka.clients.admin.NewTopic;
40 import org.apache.kafka.common.KafkaFuture;
41 import org.json.JSONArray;
42 import org.json.JSONObject;
43 import org.onap.dmaap.dmf.mr.CambriaApiException;
44 import org.onap.dmaap.dmf.mr.constants.CambriaConstants;
45 import org.onap.dmaap.dmf.mr.metabroker.Broker1;
46 import org.onap.dmaap.dmf.mr.metabroker.Topic;
47 import org.onap.dmaap.dmf.mr.utils.ConfigurationReader;
48 import org.onap.dmaap.dmf.mr.utils.Utils;
49 import org.springframework.beans.factory.annotation.Qualifier;
50 import org.springframework.util.StringUtils;
53 import java.util.concurrent.ExecutionException;
57 * class performing all topic operations
59 * @author anowarul.islam
63 public class DMaaPKafkaMetaBroker implements Broker1 {
65 public DMaaPKafkaMetaBroker() {
67 fCambriaConfig = null;
68 fBaseTopicData = null;
69 final Properties props = new Properties ();
70 String fkafkaBrokers = com.att.ajsc.filemonitor.AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,
71 "kafka.metadata.broker.list");
72 if (StringUtils.isEmpty(fkafkaBrokers)) {
74 fkafkaBrokers = "localhost:9092";
77 props.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, fkafkaBrokers );
78 if(Utils.isCadiEnabled()){
79 props.put("sasl.jaas.config", "org.apache.kafka.common.security.plain.PlainLoginModule required username='admin' password='"+Utils.getKafkaproperty()+"';");
80 props.put(AdminClientConfig.SECURITY_PROTOCOL_CONFIG, "SASL_PLAINTEXT");
81 props.put("sasl.mechanism", "PLAIN");
84 fKafkaAdminClient=AdminClient.create ( props );
88 private static final EELFLogger log = EELFManager.getInstance().getLogger(ConfigurationReader.class);
89 private final AdminClient fKafkaAdminClient;
94 * DMaaPKafkaMetaBroker constructor initializing
100 public DMaaPKafkaMetaBroker(@Qualifier("propertyReader") rrNvReadable settings,
101 @Qualifier("dMaaPZkClient") ZkClient zk, @Qualifier("dMaaPZkConfigDb") ConfigDb configDb) {
103 fCambriaConfig = configDb;
104 fBaseTopicData = configDb.parse("/topics");
105 final Properties props = new Properties ();
106 String fkafkaBrokers = com.att.ajsc.filemonitor.AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,
107 "kafka.metadata.broker.list");
108 if (null == fkafkaBrokers) {
110 fkafkaBrokers = "localhost:9092";
113 if(Utils.isCadiEnabled()){
114 props.put("sasl.jaas.config", "org.apache.kafka.common.security.plain.PlainLoginModule required username='admin' password='"+Utils.getKafkaproperty()+"';");
115 props.put(AdminClientConfig.SECURITY_PROTOCOL_CONFIG, "SASL_PLAINTEXT");
116 props.put("sasl.mechanism", "PLAIN");
118 props.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, fkafkaBrokers );
120 fKafkaAdminClient=AdminClient.create ( props );
126 public DMaaPKafkaMetaBroker( rrNvReadable settings,
127 ZkClient zk, ConfigDb configDb,AdminClient client) {
130 fCambriaConfig = configDb;
131 fBaseTopicData = configDb.parse("/topics");
132 fKafkaAdminClient= client;
139 public List<Topic> getAllTopics() throws ConfigDbException {
140 log.info("Retrieving list of all the topics.");
141 final LinkedList<Topic> result = new LinkedList<>();
143 log.info("Retrieving all topics from root: " + zkTopicsRoot);
144 final List<String> topics = fZk.getChildren(zkTopicsRoot);
145 for (String topic : topics) {
146 result.add(new KafkaTopic(topic, fCambriaConfig, fBaseTopicData));
148 JSONObject dataObj = new JSONObject();
149 dataObj.put("topics", new JSONObject());
151 for (String topic : topics) {
152 dataObj.getJSONObject("topics").put(topic, new JSONObject());
154 } catch (ZkNoNodeException excp) {
155 // very fresh kafka doesn't have any topics or a topics node
156 log.error("ZK doesn't have a Kakfa topics node at " + zkTopicsRoot, excp);
162 public Topic getTopic(String topic) throws ConfigDbException {
163 if (fZk.exists(zkTopicsRoot + "/" + topic)) {
164 return getKafkaTopicConfig(fCambriaConfig, fBaseTopicData, topic);
166 // else: no such topic in kafka
171 * static method get KafkaTopic object
177 * @throws ConfigDbException
179 public static KafkaTopic getKafkaTopicConfig(ConfigDb db, ConfigPath base, String topic) throws ConfigDbException {
180 return new KafkaTopic(topic, db, base);
187 public Topic createTopic(String topic, String desc, String ownerApiKey, int partitions, int replicas,
188 boolean transactionEnabled) throws TopicExistsException, CambriaApiException,ConfigDbException {
189 log.info("Creating topic: " + topic);
191 log.info("Check if topic [" + topic + "] exist.");
192 // first check for existence "our way"
193 final Topic t = getTopic(topic);
195 log.info("Could not create topic [" + topic + "]. Topic Already exists.");
196 throw new TopicExistsException("Could not create topic [" + topic + "]. Topic Alreay exists.");
198 } catch (ConfigDbException e1) {
199 log.error("Topic [" + topic + "] could not be created. Couldn't check topic data in config db.", e1);
200 throw new CambriaApiException(HttpStatusCodes.k503_serviceUnavailable,
201 "Couldn't check topic data in config db.");
204 // we only allow 3 replicas. (If we don't test this, we get weird
205 // results from the cluster,
206 // so explicit test and fail.)
207 if (replicas < 1 || replicas > 3) {
208 log.info("Topic [" + topic + "] could not be created. The replica count must be between 1 and 3.");
209 throw new CambriaApiException(HttpStatusCodes.k400_badRequest,
210 "The replica count must be between 1 and 3.");
212 if (partitions < 1) {
213 log.info("Topic [" + topic + "] could not be created. The partition count must be at least 1.");
214 throw new CambriaApiException(HttpStatusCodes.k400_badRequest, "The partition count must be at least 1.");
220 final NewTopic topicRequest =
221 new NewTopic(topic, partitions, (short)replicas);
222 final CreateTopicsResult ctr =
223 fKafkaAdminClient.createTopics(Arrays.asList(topicRequest));
224 final KafkaFuture<Void> ctrResult = ctr.all();
226 // underlying Kafka topic created. now setup our API info
227 return createTopicEntry(topic, desc, ownerApiKey, transactionEnabled);
228 } catch (InterruptedException e) {
229 log.warn("Execution of describeTopics timed out.");
230 throw new ConfigDbException(e);
231 } catch (ExecutionException e) {
232 log.warn("Execution of describeTopics failed: " + e.getCause().getMessage(), e);
233 throw new ConfigDbException(e.getCause());
239 public void deleteTopic(String topic) throws CambriaApiException, TopicExistsException,ConfigDbException {
240 log.info("Deleting topic: " + topic);
242 log.info("Loading zookeeper client for topic deletion.");
243 // topic creation. (Otherwise, the topic is only partially created
247 fKafkaAdminClient.deleteTopics(Arrays.asList(topic));
248 log.info("Zookeeper client loaded successfully. Deleting topic.");
250 } catch (Exception e) {
251 log.error("Failed to delete topic [" + topic + "]. " + e.getMessage(), e);
252 throw new ConfigDbException(e);
254 log.info("Closing zookeeper connection.");
258 private final ZkClient fZk;
259 private final ConfigDb fCambriaConfig;
260 private final ConfigPath fBaseTopicData;
262 private static final String zkTopicsRoot = "/brokers/topics";
263 private static final JSONObject kEmptyAcl = new JSONObject();
266 * method Providing KafkaTopic Object associated with owner and
267 * transactionenabled or not
272 * @param transactionEnabled
274 * @throws ConfigDbException
276 public KafkaTopic createTopicEntry(String name, String desc, String owner, boolean transactionEnabled)
277 throws ConfigDbException {
278 return createTopicEntry(fCambriaConfig, fBaseTopicData, name, desc, owner, transactionEnabled);
282 * static method giving kafka topic object
289 * @param transactionEnabled
291 * @throws ConfigDbException
293 public static KafkaTopic createTopicEntry(ConfigDb db, ConfigPath basePath, String name, String desc, String owner,
294 boolean transactionEnabled) throws ConfigDbException {
295 final JSONObject o = new JSONObject();
296 o.put("owner", owner);
297 o.put("description", desc);
298 o.put("txenabled", transactionEnabled);
299 db.store(basePath.getChild(name), o.toString());
300 return new KafkaTopic(name, db, basePath);
304 * class performing all user opearation like user is eligible to read,
305 * write. permitting a user to write and read,
307 * @author anowarul.islam
310 public static class KafkaTopic implements Topic {
312 * constructor initializes
317 * @throws ConfigDbException
319 public KafkaTopic(String name, ConfigDb configdb, ConfigPath baseTopic) throws ConfigDbException {
321 fConfigDb = configdb;
322 fBaseTopicData = baseTopic;
324 String data = fConfigDb.load(fBaseTopicData.getChild(fName));
329 final JSONObject o = new JSONObject(data);
330 fOwner = o.optString("owner", "");
331 fDesc = o.optString("description", "");
332 fTransactionEnabled = o.optBoolean("txenabled", false);// default
335 // if this topic has an owner, it needs both read/write ACLs. If there's no
336 // owner (or it's empty), null is okay -- this is for existing or implicitly
338 JSONObject readers = o.optJSONObject ( "readers" );
339 if ( readers == null && fOwner.length () > 0 )
343 fReaders = fromJson ( readers );
345 JSONObject writers = o.optJSONObject ( "writers" );
346 if ( writers == null && fOwner.length () > 0 )
350 fWriters = fromJson ( writers );
353 private NsaAcl fromJson(JSONObject o) {
354 NsaAcl acl = new NsaAcl();
356 JSONArray a = o.optJSONArray("allowed");
358 for (int i = 0; i < a.length(); ++i) {
359 String user = a.getString(i);
368 public String getName() {
373 public String getOwner() {
378 public String getDescription() {
383 public NsaAcl getReaderAcl() {
388 public NsaAcl getWriterAcl() {
393 public void checkUserRead(NsaApiKey user) throws AccessDeniedException {
394 NsaAclUtils.checkUserAccess ( fOwner, getReaderAcl(), user );
398 public void checkUserWrite(NsaApiKey user) throws AccessDeniedException {
399 NsaAclUtils.checkUserAccess ( fOwner, getWriterAcl(), user );
403 public void permitWritesFromUser(String pubId, NsaApiKey asUser)
404 throws ConfigDbException, AccessDeniedException {
405 updateAcl(asUser, false, true, pubId);
409 public void denyWritesFromUser(String pubId, NsaApiKey asUser) throws ConfigDbException, AccessDeniedException {
410 updateAcl(asUser, false, false, pubId);
414 public void permitReadsByUser(String consumerId, NsaApiKey asUser)
415 throws ConfigDbException, AccessDeniedException {
416 updateAcl(asUser, true, true, consumerId);
420 public void denyReadsByUser(String consumerId, NsaApiKey asUser)
421 throws ConfigDbException, AccessDeniedException {
422 updateAcl(asUser, true, false, consumerId);
425 private void updateAcl(NsaApiKey asUser, boolean reader, boolean add, String key)
426 throws ConfigDbException, AccessDeniedException{
429 final NsaAcl acl = NsaAclUtils.updateAcl ( this, asUser, key, reader, add );
431 // we have to assume we have current data, or load it again. for the expected use
432 // case, assuming we can overwrite the data is fine.
433 final JSONObject o = new JSONObject ();
434 o.put ( "owner", fOwner );
435 o.put ( "readers", safeSerialize ( reader ? acl : fReaders ) );
436 o.put ( "writers", safeSerialize ( reader ? fWriters : acl ) );
437 fConfigDb.store ( fBaseTopicData.getChild ( fName ), o.toString () );
439 log.info ( "ACL_UPDATE: " + asUser.getKey () + " " + ( add ? "added" : "removed" ) + ( reader?"subscriber":"publisher" ) + " " + key + " on " + fName );
442 catch ( ConfigDbException | AccessDeniedException x )
449 private JSONObject safeSerialize(NsaAcl acl) {
450 return acl == null ? null : acl.serialize();
453 private final String fName;
454 private final ConfigDb fConfigDb;
455 private final ConfigPath fBaseTopicData;
456 private final String fOwner;
457 private final String fDesc;
458 private final NsaAcl fReaders;
459 private final NsaAcl fWriters;
460 private boolean fTransactionEnabled;
462 public boolean isTransactionEnabled() {
463 return fTransactionEnabled;
467 public Set<String> getOwners() {
468 final TreeSet<String> owners = new TreeSet<>();
469 owners.add ( fOwner );