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 com.att.nsa.cambria.beans;
24 import java.util.LinkedList;
25 import java.util.List;
26 import java.util.Properties;
28 import java.util.TreeSet;
30 import org.I0Itec.zkclient.ZkClient;
31 import org.I0Itec.zkclient.exception.ZkNoNodeException;
32 //import org.apache.log4-j.Logger;
33 import com.att.eelf.configuration.EELFLogger;
34 import com.att.eelf.configuration.EELFManager;
36 import org.json.JSONArray;
37 import org.json.JSONObject;
38 import org.springframework.beans.factory.annotation.Qualifier;
40 import com.att.nsa.cambria.CambriaApiException;
41 import com.att.nsa.cambria.metabroker.Broker;
42 import com.att.nsa.cambria.metabroker.Topic;
43 import com.att.nsa.cambria.utils.ConfigurationReader;
44 import com.att.nsa.configs.ConfigDb;
45 import com.att.nsa.configs.ConfigDbException;
46 import com.att.nsa.configs.ConfigPath;
47 import com.att.nsa.drumlin.service.standards.HttpStatusCodes;
48 import com.att.nsa.drumlin.till.nv.rrNvReadable;
49 import com.att.nsa.security.NsaAcl;
50 import com.att.nsa.security.NsaAclUtils;
51 import com.att.nsa.security.NsaApiKey;
53 import kafka.admin.AdminUtils;
54 import kafka.utils.ZKStringSerializer$;
57 * class performing all topic operations
63 public class DMaaPKafkaMetaBroker implements Broker {
65 //private static final Logger log = Logger.getLogger(DMaaPKafkaMetaBroker.class);
66 private static final EELFLogger log = EELFManager.getInstance().getLogger(ConfigurationReader.class);
70 * DMaaPKafkaMetaBroker constructor initializing
76 public DMaaPKafkaMetaBroker(@Qualifier("propertyReader") rrNvReadable settings,
77 @Qualifier("dMaaPZkClient") ZkClient zk, @Qualifier("dMaaPZkConfigDb") ConfigDb configDb) {
78 //fSettings = settings;
80 fCambriaConfig = configDb;
81 fBaseTopicData = configDb.parse("/topics");
85 public List<Topic> getAllTopics() throws ConfigDbException {
86 log.info("Retrieving list of all the topics.");
87 final LinkedList<Topic> result = new LinkedList<Topic>();
89 log.info("Retrieving all topics from root: " + zkTopicsRoot);
90 final List<String> topics = fZk.getChildren(zkTopicsRoot);
91 for (String topic : topics) {
92 result.add(new KafkaTopic(topic, fCambriaConfig, fBaseTopicData));
95 JSONObject dataObj = new JSONObject();
96 dataObj.put("topics", new JSONObject());
98 for (String topic : topics) {
99 dataObj.getJSONObject("topics").put(topic, new JSONObject());
101 } catch (ZkNoNodeException excp) {
102 // very fresh kafka doesn't have any topics or a topics node
103 log.error("ZK doesn't have a Kakfa topics node at " + zkTopicsRoot, excp);
109 public Topic getTopic(String topic) throws ConfigDbException {
110 if (fZk.exists(zkTopicsRoot + "/" + topic)) {
111 return getKafkaTopicConfig(fCambriaConfig, fBaseTopicData, topic);
113 // else: no such topic in kafka
118 * static method get KafkaTopic object
124 * @throws ConfigDbException
126 public static KafkaTopic getKafkaTopicConfig(ConfigDb db, ConfigPath base, String topic) throws ConfigDbException {
127 return new KafkaTopic(topic, db, base);
134 public Topic createTopic(String topic, String desc, String ownerApiKey, int partitions, int replicas,
135 boolean transactionEnabled) throws TopicExistsException, CambriaApiException {
136 log.info("Creating topic: " + topic);
138 log.info("Check if topic [" + topic + "] exist.");
139 // first check for existence "our way"
140 final Topic t = getTopic(topic);
142 log.info("Could not create topic [" + topic + "]. Topic Already exists.");
143 throw new TopicExistsException("Could not create topic [" + topic + "]. Topic Alreay exists.");
145 } catch (ConfigDbException e1) {
146 log.error("Topic [" + topic + "] could not be created. Couldn't check topic data in config db.", e1);
147 throw new CambriaApiException(HttpStatusCodes.k503_serviceUnavailable,
148 "Couldn't check topic data in config db.");
151 // we only allow 3 replicas. (If we don't test this, we get weird
152 // results from the cluster,
153 // so explicit test and fail.)
154 if (replicas < 1 || replicas > 3) {
155 log.info("Topic [" + topic + "] could not be created. The replica count must be between 1 and 3.");
156 throw new CambriaApiException(HttpStatusCodes.k400_badRequest,
157 "The replica count must be between 1 and 3.");
159 if (partitions < 1) {
160 log.info("Topic [" + topic + "] could not be created. The partition count must be at least 1.");
161 throw new CambriaApiException(HttpStatusCodes.k400_badRequest, "The partition count must be at least 1.");
166 ZkClient zkClient = null;
168 log.info("Loading zookeeper client for creating topic.");
169 // FIXME: use of this scala module$ thing is a goofy hack to
170 // make Kafka aware of the
171 // topic creation. (Otherwise, the topic is only partially
173 zkClient = ZkClientFactory.createZkClient();
174 log.info("Zookeeper client loaded successfully. Creating topic.");
175 AdminUtils.createTopic(zkClient, topic, partitions, replicas, new Properties());
176 } catch (kafka.common.TopicExistsException e) {
177 log.error("Topic [" + topic + "] could not be created. " + e.getMessage(), e);
178 throw new TopicExistsException(topic);
179 } catch (ZkNoNodeException e) {
180 log.error("Topic [" + topic + "] could not be created. The Kafka cluster is not setup.", e);
181 // Kafka throws this when the server isn't running (and perhaps
183 throw new CambriaApiException(HttpStatusCodes.k503_serviceUnavailable,
184 "The Kafka cluster is not setup.");
185 } catch (kafka.admin.AdminOperationException e) {
186 // Kafka throws this when the server isn't running (and perhaps
188 log.error("The Kafka cluster can't handle your request. Talk to the administrators: " + e.getMessage(),
190 throw new CambriaApiException(HttpStatusCodes.k503_serviceUnavailable,
191 "The Kafka cluster can't handle your request. Talk to the administrators.");
193 log.info("Closing zookeeper connection.");
194 if (zkClient != null)
198 log.info("Creating topic entry for topic: " + topic);
199 // underlying Kafka topic created. now setup our API info
200 return createTopicEntry(topic, desc, ownerApiKey, transactionEnabled);
201 } catch (ConfigDbException excp) {
202 log.error("Failed to create topic data. Talk to the administrators: " + excp.getMessage(), excp);
203 throw new CambriaApiException(HttpStatusCodes.k503_serviceUnavailable,
204 "Failed to create topic data. Talk to the administrators.");
209 public void deleteTopic(String topic) throws CambriaApiException, TopicExistsException {
210 log.info("Deleting topic: " + topic);
211 ZkClient zkClient = null;
213 log.info("Loading zookeeper client for topic deletion.");
214 // FIXME: use of this scala module$ thing is a goofy hack to make
215 // Kafka aware of the
216 // topic creation. (Otherwise, the topic is only partially created
218 zkClient = ZkClientFactory.createZkClient();
220 log.info("Zookeeper client loaded successfully. Deleting topic.");
221 AdminUtils.deleteTopic(zkClient, topic);
222 } catch (kafka.common.TopicExistsException e) {
223 log.error("Failed to delete topic [" + topic + "]. " + e.getMessage(), e);
224 throw new TopicExistsException(topic);
225 } catch (ZkNoNodeException e) {
226 log.error("Failed to delete topic [" + topic + "]. The Kafka cluster is not setup." + e.getMessage(), e);
227 // Kafka throws this when the server isn't running (and perhaps
229 throw new CambriaApiException(HttpStatusCodes.k503_serviceUnavailable, "The Kafka cluster is not setup.");
230 } catch (kafka.admin.AdminOperationException e) {
231 // Kafka throws this when the server isn't running (and perhaps
233 log.error("The Kafka cluster can't handle your request. Talk to the administrators." + e.getMessage(), e);
234 throw new CambriaApiException(HttpStatusCodes.k503_serviceUnavailable,
235 "The Kafka cluster can't handle your request. Talk to the administrators.");
237 log.info("Closing zookeeper connection.");
238 if (zkClient != null)
242 // throw new UnsupportedOperationException ( "We can't programmatically
243 // delete Kafka topics yet." );
248 //private final rrNvReadable fSettings;
249 private final ZkClient fZk;
250 private final ConfigDb fCambriaConfig;
251 private final ConfigPath fBaseTopicData;
253 private static final String zkTopicsRoot = "/brokers/topics";
254 private static final JSONObject kEmptyAcl = new JSONObject();
257 * method Providing KafkaTopic Object associated with owner and
258 * transactionenabled or not
263 * @param transactionEnabled
265 * @throws ConfigDbException
267 public KafkaTopic createTopicEntry(String name, String desc, String owner, boolean transactionEnabled)
268 throws ConfigDbException {
269 return createTopicEntry(fCambriaConfig, fBaseTopicData, name, desc, owner, transactionEnabled);
273 * static method giving kafka topic object
280 * @param transactionEnabled
282 * @throws ConfigDbException
284 public static KafkaTopic createTopicEntry(ConfigDb db, ConfigPath basePath, String name, String desc, String owner,
285 boolean transactionEnabled) throws ConfigDbException {
286 final JSONObject o = new JSONObject();
287 o.put("owner", owner);
288 o.put("description", desc);
289 o.put("txenabled", transactionEnabled);
290 db.store(basePath.getChild(name), o.toString());
291 return new KafkaTopic(name, db, basePath);
295 * class performing all user opearation like user is eligible to read,
296 * write. permitting a user to write and read,
301 public static class KafkaTopic implements Topic {
303 * constructor initializes
308 * @throws ConfigDbException
310 public KafkaTopic(String name, ConfigDb configdb, ConfigPath baseTopic) throws ConfigDbException {
312 fConfigDb = configdb;
313 fBaseTopicData = baseTopic;
315 String data = fConfigDb.load(fBaseTopicData.getChild(fName));
320 final JSONObject o = new JSONObject(data);
321 fOwner = o.optString("owner", "");
322 fDesc = o.optString("description", "");
323 fTransactionEnabled = o.optBoolean("txenabled", false);// default
326 // if this topic has an owner, it needs both read/write ACLs. If there's no
327 // owner (or it's empty), null is okay -- this is for existing or implicitly
329 JSONObject readers = o.optJSONObject ( "readers" );
330 if ( readers == null && fOwner.length () > 0 ) readers = kEmptyAcl;
331 fReaders = fromJson ( readers );
333 JSONObject writers = o.optJSONObject ( "writers" );
334 if ( writers == null && fOwner.length () > 0 ) writers = kEmptyAcl;
335 fWriters = fromJson ( writers );
337 private NsaAcl fromJson(JSONObject o) {
338 NsaAcl acl = new NsaAcl();
340 JSONArray a = o.optJSONArray("allowed");
342 for (int i = 0; i < a.length(); ++i) {
343 String user = a.getString(i);
351 public String getName() {
356 public String getOwner() {
361 public String getDescription() {
366 public NsaAcl getReaderAcl() {
371 public NsaAcl getWriterAcl() {
376 public void checkUserRead(NsaApiKey user) throws AccessDeniedException {
377 NsaAclUtils.checkUserAccess ( fOwner, getReaderAcl(), user );
381 public void checkUserWrite(NsaApiKey user) throws AccessDeniedException {
382 NsaAclUtils.checkUserAccess ( fOwner, getWriterAcl(), user );
386 public void permitWritesFromUser(String pubId, NsaApiKey asUser)
387 throws ConfigDbException, AccessDeniedException {
388 updateAcl(asUser, false, true, pubId);
392 public void denyWritesFromUser(String pubId, NsaApiKey asUser) throws ConfigDbException, AccessDeniedException {
393 updateAcl(asUser, false, false, pubId);
397 public void permitReadsByUser(String consumerId, NsaApiKey asUser)
398 throws ConfigDbException, AccessDeniedException {
399 updateAcl(asUser, true, true, consumerId);
403 public void denyReadsByUser(String consumerId, NsaApiKey asUser)
404 throws ConfigDbException, AccessDeniedException {
405 updateAcl(asUser, true, false, consumerId);
408 private void updateAcl(NsaApiKey asUser, boolean reader, boolean add, String key)
409 throws ConfigDbException, AccessDeniedException{
412 final NsaAcl acl = NsaAclUtils.updateAcl ( this, asUser, key, reader, add );
414 // we have to assume we have current data, or load it again. for the expected use
415 // case, assuming we can overwrite the data is fine.
416 final JSONObject o = new JSONObject ();
417 o.put ( "owner", fOwner );
418 o.put ( "readers", safeSerialize ( reader ? acl : fReaders ) );
419 o.put ( "writers", safeSerialize ( reader ? fWriters : acl ) );
420 fConfigDb.store ( fBaseTopicData.getChild ( fName ), o.toString () );
422 log.info ( "ACL_UPDATE: " + asUser.getKey () + " " + ( add ? "added" : "removed" ) + ( reader?"subscriber":"publisher" ) + " " + key + " on " + fName );
425 catch ( ConfigDbException x )
429 catch ( AccessDeniedException x )
436 private JSONObject safeSerialize(NsaAcl acl) {
437 return acl == null ? null : acl.serialize();
440 private final String fName;
441 private final ConfigDb fConfigDb;
442 private final ConfigPath fBaseTopicData;
443 private final String fOwner;
444 private final String fDesc;
445 private final NsaAcl fReaders;
446 private final NsaAcl fWriters;
447 private boolean fTransactionEnabled;
449 public boolean isTransactionEnabled() {
450 return fTransactionEnabled;
454 public Set<String> getOwners() {
455 final TreeSet<String> owners = new TreeSet<String> ();
456 owners.add ( fOwner );