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.putAll(Utils.addSaslProps());
81 fKafkaAdminClient=AdminClient.create ( props );
85 private static final EELFLogger log = EELFManager.getInstance().getLogger(ConfigurationReader.class);
86 private final AdminClient fKafkaAdminClient;
91 * DMaaPKafkaMetaBroker constructor initializing
97 public DMaaPKafkaMetaBroker(@Qualifier("propertyReader") rrNvReadable settings,
98 @Qualifier("dMaaPZkClient") ZkClient zk, @Qualifier("dMaaPZkConfigDb") ConfigDb configDb) {
100 fCambriaConfig = configDb;
101 fBaseTopicData = configDb.parse("/topics");
102 final Properties props = new Properties ();
103 String fkafkaBrokers = com.att.ajsc.filemonitor.AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,
104 "kafka.metadata.broker.list");
105 if (null == fkafkaBrokers) {
107 fkafkaBrokers = "localhost:9092";
110 if(Utils.isCadiEnabled()){
111 props.putAll(Utils.addSaslProps());
113 props.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, fkafkaBrokers );
115 fKafkaAdminClient=AdminClient.create ( props );
121 public DMaaPKafkaMetaBroker( rrNvReadable settings,
122 ZkClient zk, ConfigDb configDb,AdminClient client) {
125 fCambriaConfig = configDb;
126 fBaseTopicData = configDb.parse("/topics");
127 fKafkaAdminClient= client;
134 public List<Topic> getAllTopics() throws ConfigDbException {
135 log.info("Retrieving list of all the topics.");
136 final LinkedList<Topic> result = new LinkedList<>();
138 log.info("Retrieving all topics from root: " + zkTopicsRoot);
139 final List<String> topics = fZk.getChildren(zkTopicsRoot);
140 for (String topic : topics) {
141 result.add(new KafkaTopic(topic, fCambriaConfig, fBaseTopicData));
143 JSONObject dataObj = new JSONObject();
144 dataObj.put("topics", new JSONObject());
146 for (String topic : topics) {
147 dataObj.getJSONObject("topics").put(topic, new JSONObject());
149 } catch (ZkNoNodeException excp) {
150 // very fresh kafka doesn't have any topics or a topics node
151 log.error("ZK doesn't have a Kakfa topics node at " + zkTopicsRoot, excp);
157 public Topic getTopic(String topic) throws ConfigDbException {
158 if (fZk.exists(zkTopicsRoot + "/" + topic)) {
159 return getKafkaTopicConfig(fCambriaConfig, fBaseTopicData, topic);
161 // else: no such topic in kafka
166 * static method get KafkaTopic object
172 * @throws ConfigDbException
174 public static KafkaTopic getKafkaTopicConfig(ConfigDb db, ConfigPath base, String topic) throws ConfigDbException {
175 return new KafkaTopic(topic, db, base);
182 public Topic createTopic(String topic, String desc, String ownerApiKey, int partitions, int replicas,
183 boolean transactionEnabled) throws TopicExistsException, CambriaApiException,ConfigDbException {
184 log.info("Creating topic: " + topic);
186 log.info("Check if topic [" + topic + "] exist.");
187 // first check for existence "our way"
188 final Topic t = getTopic(topic);
190 log.info("Could not create topic [" + topic + "]. Topic Already exists.");
191 throw new TopicExistsException("Could not create topic [" + topic + "]. Topic Alreay exists.");
193 } catch (ConfigDbException e1) {
194 log.error("Topic [" + topic + "] could not be created. Couldn't check topic data in config db.", e1);
195 throw new CambriaApiException(HttpStatusCodes.k503_serviceUnavailable,
196 "Couldn't check topic data in config db.");
199 // we only allow 3 replicas. (If we don't test this, we get weird
200 // results from the cluster,
201 // so explicit test and fail.)
202 if (replicas < 1 || replicas > 3) {
203 log.info("Topic [" + topic + "] could not be created. The replica count must be between 1 and 3.");
204 throw new CambriaApiException(HttpStatusCodes.k400_badRequest,
205 "The replica count must be between 1 and 3.");
207 if (partitions < 1) {
208 log.info("Topic [" + topic + "] could not be created. The partition count must be at least 1.");
209 throw new CambriaApiException(HttpStatusCodes.k400_badRequest, "The partition count must be at least 1.");
215 final NewTopic topicRequest =
216 new NewTopic(topic, partitions, (short)replicas);
217 final CreateTopicsResult ctr =
218 fKafkaAdminClient.createTopics(Arrays.asList(topicRequest));
219 final KafkaFuture<Void> ctrResult = ctr.all();
221 // underlying Kafka topic created. now setup our API info
222 return createTopicEntry(topic, desc, ownerApiKey, transactionEnabled);
223 } catch (InterruptedException e) {
224 log.warn("Execution of describeTopics timed out.");
225 throw new ConfigDbException(e);
226 } catch (ExecutionException e) {
227 log.warn("Execution of describeTopics failed: " + e.getCause().getMessage(), e);
228 throw new ConfigDbException(e.getCause());
234 public void deleteTopic(String topic) throws CambriaApiException, TopicExistsException,ConfigDbException {
235 log.info("Deleting topic: " + topic);
237 log.info("Loading zookeeper client for topic deletion.");
238 // topic creation. (Otherwise, the topic is only partially created
242 fKafkaAdminClient.deleteTopics(Arrays.asList(topic));
243 log.info("Zookeeper client loaded successfully. Deleting topic.");
245 } catch (Exception e) {
246 log.error("Failed to delete topic [" + topic + "]. " + e.getMessage(), e);
247 throw new ConfigDbException(e);
249 log.info("Closing zookeeper connection.");
253 private final ZkClient fZk;
254 private final ConfigDb fCambriaConfig;
255 private final ConfigPath fBaseTopicData;
257 private static final String zkTopicsRoot = "/brokers/topics";
258 private static final JSONObject kEmptyAcl = new JSONObject();
261 * method Providing KafkaTopic Object associated with owner and
262 * transactionenabled or not
267 * @param transactionEnabled
269 * @throws ConfigDbException
271 public KafkaTopic createTopicEntry(String name, String desc, String owner, boolean transactionEnabled)
272 throws ConfigDbException {
273 return createTopicEntry(fCambriaConfig, fBaseTopicData, name, desc, owner, transactionEnabled);
277 * static method giving kafka topic object
284 * @param transactionEnabled
286 * @throws ConfigDbException
288 public static KafkaTopic createTopicEntry(ConfigDb db, ConfigPath basePath, String name, String desc, String owner,
289 boolean transactionEnabled) throws ConfigDbException {
290 final JSONObject o = new JSONObject();
291 o.put("owner", owner);
292 o.put("description", desc);
293 o.put("txenabled", transactionEnabled);
294 db.store(basePath.getChild(name), o.toString());
295 return new KafkaTopic(name, db, basePath);
299 * class performing all user opearation like user is eligible to read,
300 * write. permitting a user to write and read,
302 * @author anowarul.islam
305 public static class KafkaTopic implements Topic {
307 * constructor initializes
312 * @throws ConfigDbException
314 public KafkaTopic(String name, ConfigDb configdb, ConfigPath baseTopic) throws ConfigDbException {
316 fConfigDb = configdb;
317 fBaseTopicData = baseTopic;
319 String data = fConfigDb.load(fBaseTopicData.getChild(fName));
324 final JSONObject o = new JSONObject(data);
325 fOwner = o.optString("owner", "");
326 fDesc = o.optString("description", "");
327 fTransactionEnabled = o.optBoolean("txenabled", false);// default
330 // if this topic has an owner, it needs both read/write ACLs. If there's no
331 // owner (or it's empty), null is okay -- this is for existing or implicitly
333 JSONObject readers = o.optJSONObject ( "readers" );
334 if ( readers == null && fOwner.length () > 0 )
338 fReaders = fromJson ( readers );
340 JSONObject writers = o.optJSONObject ( "writers" );
341 if ( writers == null && fOwner.length () > 0 )
345 fWriters = fromJson ( writers );
348 private NsaAcl fromJson(JSONObject o) {
349 NsaAcl acl = new NsaAcl();
351 JSONArray a = o.optJSONArray("allowed");
353 for (int i = 0; i < a.length(); ++i) {
354 String user = a.getString(i);
363 public String getName() {
368 public String getOwner() {
373 public String getDescription() {
378 public NsaAcl getReaderAcl() {
383 public NsaAcl getWriterAcl() {
388 public void checkUserRead(NsaApiKey user) throws AccessDeniedException {
389 NsaAclUtils.checkUserAccess ( fOwner, getReaderAcl(), user );
393 public void checkUserWrite(NsaApiKey user) throws AccessDeniedException {
394 NsaAclUtils.checkUserAccess ( fOwner, getWriterAcl(), user );
398 public void permitWritesFromUser(String pubId, NsaApiKey asUser)
399 throws ConfigDbException, AccessDeniedException {
400 updateAcl(asUser, false, true, pubId);
404 public void denyWritesFromUser(String pubId, NsaApiKey asUser) throws ConfigDbException, AccessDeniedException {
405 updateAcl(asUser, false, false, pubId);
409 public void permitReadsByUser(String consumerId, NsaApiKey asUser)
410 throws ConfigDbException, AccessDeniedException {
411 updateAcl(asUser, true, true, consumerId);
415 public void denyReadsByUser(String consumerId, NsaApiKey asUser)
416 throws ConfigDbException, AccessDeniedException {
417 updateAcl(asUser, true, false, consumerId);
420 private void updateAcl(NsaApiKey asUser, boolean reader, boolean add, String key)
421 throws ConfigDbException, AccessDeniedException{
424 final NsaAcl acl = NsaAclUtils.updateAcl ( this, asUser, key, reader, add );
426 // we have to assume we have current data, or load it again. for the expected use
427 // case, assuming we can overwrite the data is fine.
428 final JSONObject o = new JSONObject ();
429 o.put ( "owner", fOwner );
430 o.put ( "readers", safeSerialize ( reader ? acl : fReaders ) );
431 o.put ( "writers", safeSerialize ( reader ? fWriters : acl ) );
432 fConfigDb.store ( fBaseTopicData.getChild ( fName ), o.toString () );
434 log.info ( "ACL_UPDATE: " + asUser.getKey () + " " + ( add ? "added" : "removed" ) + ( reader?"subscriber":"publisher" ) + " " + key + " on " + fName );
437 catch ( ConfigDbException | AccessDeniedException x )
444 private JSONObject safeSerialize(NsaAcl acl) {
445 return acl == null ? null : acl.serialize();
448 private final String fName;
449 private final ConfigDb fConfigDb;
450 private final ConfigPath fBaseTopicData;
451 private final String fOwner;
452 private final String fDesc;
453 private final NsaAcl fReaders;
454 private final NsaAcl fWriters;
455 private boolean fTransactionEnabled;
457 public boolean isTransactionEnabled() {
458 return fTransactionEnabled;
462 public Set<String> getOwners() {
463 final TreeSet<String> owners = new TreeSet<>();
464 owners.add ( fOwner );