2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
7 * Modifications Copyright (C) 2019 IBM.
8 * ================================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
20 * ============LICENSE_END=========================================================
23 package org.onap.dmaap.dbcapi.service;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.Iterator;
28 import java.util.List;
32 import javax.ws.rs.core.Response.Status;
34 import org.onap.dmaap.dbcapi.aaf.AafNamespace;
35 import org.onap.dmaap.dbcapi.aaf.AafRole;
36 import org.onap.dmaap.dbcapi.aaf.AafService;
37 import org.onap.dmaap.dbcapi.aaf.DmaapGrant;
38 import org.onap.dmaap.dbcapi.aaf.AafService.ServiceType;
39 import org.onap.dmaap.dbcapi.aaf.DmaapPerm;
40 import org.onap.dmaap.dbcapi.database.DatabaseClass;
41 import org.onap.dmaap.dbcapi.logging.BaseLoggingClass;
42 import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum;
43 import org.onap.dmaap.dbcapi.model.ApiError;
44 import org.onap.dmaap.dbcapi.model.DcaeLocation;
45 import org.onap.dmaap.dbcapi.model.DmaapObject.DmaapObject_Status;
46 import org.onap.dmaap.dbcapi.model.MR_Client;
47 import org.onap.dmaap.dbcapi.model.MR_Cluster;
48 import org.onap.dmaap.dbcapi.model.MirrorMaker;
49 import org.onap.dmaap.dbcapi.model.ReplicationType;
50 import org.onap.dmaap.dbcapi.model.Topic;
51 import org.onap.dmaap.dbcapi.util.DmaapConfig;
52 import org.onap.dmaap.dbcapi.util.Fqdn;
53 import org.onap.dmaap.dbcapi.util.Graph;
55 public class TopicService extends BaseLoggingClass {
59 // REF: https://wiki.web.att.com/pages/viewpage.action?pageId=519703122
60 private static String defaultGlobalMrHost;
62 private Map<String, Topic> mr_topics = DatabaseClass.getTopics();
64 private static DmaapService dmaapSvc = new DmaapService();
65 private MR_ClientService clientService = new MR_ClientService();
66 private MR_ClusterService clusters = new MR_ClusterService();
67 private DcaeLocationService locations = new DcaeLocationService();
68 private MirrorMakerService bridge = new MirrorMakerService();
70 private static String centralCname;
71 private static boolean createTopicRoles;
72 private boolean strictGraph = true;
75 public TopicService(){
76 DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
77 defaultGlobalMrHost = p.getProperty("MR.globalHost", "global.host.not.set");
78 centralCname = p.getProperty("MR.CentralCname");
79 createTopicRoles = "true".equalsIgnoreCase(p.getProperty("aaf.CreateTopicRoles", "true"));
80 String unit_test = p.getProperty( "UnitTest", "No" );
81 if ( unit_test.equals( "Yes" ) ) {
84 logger.info( "TopicService properties: CentralCname=" + centralCname +
85 " defaultGlobarlMrHost=" + defaultGlobalMrHost +
86 " createTopicRoles=" + createTopicRoles );
89 public Map<String, Topic> getTopics() {
93 public List<Topic> getAllTopics() {
94 return getAllTopics( true );
96 public List<Topic> getAllTopicsWithoutClients() {
97 return getAllTopics(false);
100 private List<Topic> getAllTopics( Boolean withClients ) {
101 ArrayList<Topic> topics = new ArrayList<>(mr_topics.values());
103 for( Topic topic: topics ) {
104 topic.setClients( clientService.getAllMrClients(topic.getFqtn()));
111 public Topic getTopic( String key, ApiError apiError ) {
112 logger.info( "getTopic: key=" + key);
113 Topic t = mr_topics.get( key );
115 apiError.setCode(Status.NOT_FOUND.getStatusCode());
116 apiError.setFields( "fqtn");
117 apiError.setMessage("topic with fqtn " + key + " not found");
120 t.setClients( clientService.getAllMrClients( key ));
121 apiError.setCode(Status.OK.getStatusCode());
125 private void aafTopicSetup(Topic topic, ApiError err ) {
127 String nsr = dmaapSvc.getDmaap().getTopicNsRoot();
130 err.setMessage("Unable to establish AAF namespace root: (check /dmaap object)" );
131 err.setFields("topicNsRoot");
135 // establish AAF Connection using TopicMgr identity
136 AafService aaf = new AafService(ServiceType.AAF_TopicMgr);
138 AafRole pubRole = null;
139 AafRole subRole = null;
141 // creating Topic Roles was not an original feature.
142 // For backwards compatibility, only do this if the feature is enabled.
143 // Also, if the namespace of the topic is a foreign namespace, (i.e. not the same as our root ns)
144 // then we likely don't have permission to create sub-ns and Roles so don't try.
145 if ( createTopicRoles && topic.getFqtn().startsWith(nsr)) {
146 // create AAF namespace for this topic
147 AafNamespace ns = new AafNamespace( topic.getFqtn(), aaf.getIdentity());
149 int rc = aaf.addNamespace( ns );
150 if ( rc != 201 && rc != 409 ) {
152 err.setMessage("Unexpected response from AAF:" + rc );
153 err.setFields("namespace:" + topic.getFqtn() + " identity="+ aaf.getIdentity());
158 // create AAF Roles for MR clients of this topic
159 String rn = "publisher";
160 pubRole = new AafRole( topic.getFqtn(), rn );
161 int rc = aaf.addRole( pubRole );
162 if ( rc != 201 && rc != 409 ) {
164 err.setMessage("Unexpected response from AAF:" + rc );
165 err.setFields("topic:" + topic.getFqtn() + " role="+ rn);
168 topic.setPublisherRole( pubRole.getFullyQualifiedRole() );
171 subRole = new AafRole( topic.getFqtn(), rn );
172 rc = aaf.addRole( subRole );
173 if ( rc != 201 && rc != 409 ) {
175 err.setMessage("Unexpected response from AAF:" + rc );
176 err.setFields("topic:" + topic.getFqtn() + " role="+ rn);
179 topic.setSubscriberRole( subRole.getFullyQualifiedRole() );
182 // create AAF perms checked by MR
183 String instance = ":topic." + topic.getFqtn();
184 String[] actions = { "pub", "sub", "view" };
185 String t = dmaapSvc.getTopicPerm();
186 for ( String action : actions ){
187 DmaapPerm perm = new DmaapPerm( t, instance, action );
188 int rc = aaf.addPerm( perm );
189 if ( rc != 201 && rc != 409 ) {
191 err.setMessage("Unexpected response from AAF:" + rc );
192 err.setFields("t="+t + " instance="+ instance + " action="+ action);
195 if ( createTopicRoles ) {
196 // Grant perms to our default Roles
197 if ( action.equals( "pub") || action.equals( "view") ) {
198 DmaapGrant g = new DmaapGrant( perm, pubRole.getFullyQualifiedRole() );
199 rc = aaf.addGrant( g );
200 if ( rc != 201 && rc != 409 ) {
202 err.setMessage( "Grant of " + perm.toString() + " failed for " + pubRole.getFullyQualifiedRole() );
203 logger.warn( err.getMessage());
207 if ( action.equals( "sub") || action.equals( "view") ) {
208 DmaapGrant g = new DmaapGrant( perm, subRole.getFullyQualifiedRole() );
209 rc = aaf.addGrant( g );
210 if ( rc != 201 && rc != 409 ) {
212 err.setMessage( "Grant of " + perm.toString() + " failed for " + subRole.getFullyQualifiedRole() );
213 logger.warn( err.getMessage());
222 public Topic addTopic( Topic topic, ApiError err, Boolean useExisting ) {
223 logger.info( "Entry: addTopic");
224 logger.info( "Topic name=" + topic.getTopicName() + " fqtnStyle=" + topic.getFqtnStyle() );
225 String nFqtn = topic.genFqtn();
226 logger.info( "FQTN=" + nFqtn );
227 Topic pTopic = getTopic( nFqtn, err );
228 if ( pTopic != null ) {
229 String t = "topic already exists: " + nFqtn;
232 err.setCode(Status.OK.getStatusCode());
236 err.setFields( "fqtn");
237 err.setCode(Status.CONFLICT.getStatusCode());
240 err.reset(); // err filled with NOT_FOUND is expected case, but don't want to litter...
242 topic.setFqtn( nFqtn );
244 aafTopicSetup( topic, err );
245 if ( err.getCode() >= 400 ) {
249 if ( topic.getReplicationCase().involvesGlobal() ) {
250 if ( topic.getGlobalMrURL() == null ) {
251 topic.setGlobalMrURL(defaultGlobalMrHost);
253 if ( ! Fqdn.isValid( topic.getGlobalMrURL())) {
254 logger.error( "GlobalMR FQDN not valid: " + topic.getGlobalMrURL());
255 topic.setStatus( DmaapObject_Status.INVALID);
257 err.setMessage("Value is not a valid FQDN:" + topic.getGlobalMrURL() );
258 err.setFields("globalMrURL");
265 if ( topic.getNumClients() > 0 ) {
266 ArrayList<MR_Client> clients = new ArrayList<MR_Client>(topic.getClients());
269 ArrayList<MR_Client> clients2 = new ArrayList<MR_Client>();
270 for ( Iterator<MR_Client> it = clients.iterator(); it.hasNext(); ) {
271 MR_Client c = it.next();
273 logger.info( "c fqtn=" + c.getFqtn() + " ID=" + c.getMrClientId() + " url=" + c.getTopicURL());
274 MR_Client nc = new MR_Client( c.getDcaeLocationName(), topic.getFqtn(), c.getClientRole(), c.getAction());
275 nc.setFqtn(topic.getFqtn());
276 nc.setClientIdentity( c.getClientIdentity());
277 logger.info( "nc fqtn=" + nc.getFqtn() + " ID=" + nc.getMrClientId() + " url=" + nc.getTopicURL());
278 clients2.add( clientService.addMr_Client(nc, topic, err));
279 if ( ! err.is2xx()) {
284 topic.setClients(clients2);
287 Topic ntopic = checkForBridge( topic, err );
288 if ( ntopic == null ) {
289 topic.setStatus( DmaapObject_Status.INVALID);
290 if ( ! err.is2xx()) {
296 mr_topics.put( nFqtn, ntopic );
298 err.setCode(Status.OK.getStatusCode());
303 public Topic updateTopic( Topic topic, ApiError err ) {
304 logger.info( "updateTopic: entry");
305 logger.info( "updateTopic: topic=" + topic);
306 logger.info( "updateTopic: fqtn=" + topic.getFqtn() );
307 if ( topic.getFqtn().isEmpty()) {
310 logger.info( "updateTopic: call checkForBridge");
311 Topic ntopic = checkForBridge( topic, err );
312 if ( ntopic == null ) {
313 topic.setStatus( DmaapObject_Status.INVALID);
314 if ( ! err.is2xx() ) {
319 logger.info( "updateTopic: call put");
320 mr_topics.put( ntopic.getFqtn(), ntopic );
322 err.setCode(Status.OK.getStatusCode());
326 public Topic removeTopic( String pubId, ApiError apiError ) {
327 Topic topic = mr_topics.get(pubId);
328 if ( topic == null ) {
329 apiError.setCode(Status.NOT_FOUND.getStatusCode());
330 apiError.setMessage("Topic " + pubId + " does not exist");
331 apiError.setFields("fqtn");
334 ArrayList<MR_Client> clients = new ArrayList<MR_Client>(clientService.getAllMrClients( pubId ));
335 for ( Iterator<MR_Client> it = clients.iterator(); it.hasNext(); ) {
336 MR_Client c = it.next();
339 clientService.removeMr_Client(c.getMrClientId(), false, apiError);
340 if ( ! apiError.is2xx()) {
344 apiError.setCode(Status.OK.getStatusCode());
345 return mr_topics.remove(pubId);
347 public static ApiError setBridgeClientPerms( MR_Cluster node ) {
348 DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
349 String mmProvRole = p.getProperty("MM.ProvRole");
350 String mmAgentRole = p.getProperty("MM.AgentRole");
351 String[] Roles = { mmProvRole, mmAgentRole };
352 String[] actions = { "view", "pub", "sub" };
353 Topic bridgeAdminTopic = new Topic().init();
354 bridgeAdminTopic.setTopicName( dmaapSvc.getBridgeAdminFqtn() );
355 bridgeAdminTopic.setTopicDescription( "RESERVED topic for MirroMaker Provisioning");
356 bridgeAdminTopic.setOwner( "DBC" );
358 ArrayList<MR_Client> clients = new ArrayList<MR_Client>();
359 for( String role: Roles ) {
360 MR_Client client = new MR_Client();
361 client.setAction(actions);
362 client.setClientRole(role);
363 client.setDcaeLocationName( node.getDcaeLocationName());
364 clients.add( client );
366 bridgeAdminTopic.setClients(clients);
368 TopicService ts = new TopicService();
369 ApiError err = new ApiError();
370 ts.addTopic(bridgeAdminTopic, err, true);
372 if ( err.is2xx() || err.getCode() == 409 ){
377 errorLogger.error( DmaapbcLogMessageEnum.TOPIC_CREATE_ERROR, bridgeAdminTopic.getFqtn(), Integer.toString(err.getCode()), err.getFields(), err.getMessage());
382 public Topic checkForBridge( Topic topic, ApiError err ) {
383 logger.info( "checkForBridge: entry");
384 logger.info( "fqtn=" + topic.getFqtn() + "replicatonType=" + topic.getReplicationCase());
385 if ( topic.getReplicationCase() == ReplicationType.REPLICATION_NONE ) {
386 topic.setStatus( DmaapObject_Status.VALID);
390 boolean anythingWrong = false;
392 Set<String> groups = clusters.getGroups();
393 for ( String g : groups ) {
394 logger.info( "buildBridge for " + topic.getFqtn() + " on group" + g);
395 anythingWrong |= buildBridge( topic, err, g );
397 if ( anythingWrong ) {
398 topic.setStatus( DmaapObject_Status.INVALID);
399 if ( ! err.is2xx() ) {
403 topic.setStatus( DmaapObject_Status.VALID);
408 private boolean buildBridge( Topic topic, ApiError err, String group ) {
409 logger.info( "buildBridge: entry");
410 boolean anythingWrong = false;
412 logger.info( "buildBridge: strictGraph=" + strictGraph );
413 if ( group == null || group.isEmpty() ) {
414 graph = new Graph( topic.getClients(), strictGraph );
416 graph = new Graph( topic.getClients(), strictGraph, group );
418 logger.info( "buildBridge: graph=" + graph );
419 MR_Cluster groupCentralCluster = null;
422 if ( graph.isEmpty() ) {
423 logger.info( "buildBridge: graph is empty. return false" );
425 } else if ( group == null && topic.getReplicationCase().involvesFQDN() ) {
426 logger.info( "buildBridge: group is null and replicationCaseInvolvesFQDN. return false" );
428 } else if ( ! graph.hasCentral() ) {
429 logger.warn( "Topic " + topic.getFqtn() + " wants to be " + topic.getReplicationCase() + " but has no central clients");
432 groupCentralCluster = clusters.getMr_ClusterByLoc(graph.getCentralLoc());
434 Collection<String> clientLocations = graph.getKeys();
435 for( String loc : clientLocations ) {
436 logger.info( "loc=" + loc );
437 DcaeLocation location = locations.getDcaeLocation(loc);
438 MR_Cluster cluster = clusters.getMr_ClusterByLoc(loc);
439 logger.info( "cluster=" + cluster );
443 String source = null;
444 String target = null;
447 * Provision Edge to Central bridges...
449 if ( ! location.isCentral() && ! graph.getCentralLoc().equals(cluster.getDcaeLocationName()) ) {
450 switch( topic.getReplicationCase() ) {
451 case REPLICATION_EDGE_TO_CENTRAL:
452 case REPLICATION_EDGE_TO_CENTRAL_TO_GLOBAL: // NOTE: this is for E2C portion only
453 source = cluster.getFqdn();
454 target = centralCname;
456 case REPLICATION_CENTRAL_TO_EDGE:
457 case REPLICATION_GLOBAL_TO_CENTRAL_TO_EDGE: // NOTE: this is for C2E portion only
458 source = centralCname;
459 target = cluster.getFqdn();
461 case REPLICATION_CENTRAL_TO_GLOBAL:
462 case REPLICATION_GLOBAL_TO_CENTRAL:
463 case REPLICATION_FQDN_TO_GLOBAL:
464 case REPLICATION_GLOBAL_TO_FQDN:
467 case REPLICATION_EDGE_TO_FQDN:
468 case REPLICATION_EDGE_TO_FQDN_TO_GLOBAL: // NOTE: this is for E2C portion only
469 source = cluster.getFqdn();
470 target = groupCentralCluster.getFqdn();
472 case REPLICATION_FQDN_TO_EDGE:
473 case REPLICATION_GLOBAL_TO_FQDN_TO_EDGE: // NOTE: this is for F2E portion only
474 source = groupCentralCluster.getFqdn();
475 target = cluster.getFqdn();
479 logger.error( "Unexpected value for ReplicationType ("+ topic.getReplicationCase() + ") for topic " + topic.getFqtn() );
480 anythingWrong = true;
482 err.setFields("topic=" + topic.genFqtn() + " replicationCase="
483 + topic.getReplicationCase() );
484 err.setMessage("Unexpected value for ReplicationType");
488 } else if ( location.isCentral() && graph.getCentralLoc().equals(cluster.getDcaeLocationName()) ) {
490 * Provision Central to Global bridges
492 switch( topic.getReplicationCase() ) {
494 case REPLICATION_CENTRAL_TO_GLOBAL:
495 case REPLICATION_EDGE_TO_CENTRAL_TO_GLOBAL:
496 source = centralCname;
497 target = topic.getGlobalMrURL();
499 case REPLICATION_GLOBAL_TO_CENTRAL:
500 case REPLICATION_GLOBAL_TO_CENTRAL_TO_EDGE: // NOTE: this is for G2C portion only
501 source = topic.getGlobalMrURL();
502 target = centralCname;
505 case REPLICATION_EDGE_TO_FQDN_TO_GLOBAL: // NOTE: this is for E2F portion only
506 source = groupCentralCluster.getFqdn();
507 target = topic.getGlobalMrURL();
510 case REPLICATION_FQDN_TO_GLOBAL:
511 source = groupCentralCluster.getFqdn();
512 target = topic.getGlobalMrURL();
515 case REPLICATION_GLOBAL_TO_FQDN:
516 case REPLICATION_GLOBAL_TO_FQDN_TO_EDGE: // NOTE: this is for G2F portion only
517 source = topic.getGlobalMrURL();
518 target = groupCentralCluster.getFqdn();
521 case REPLICATION_FQDN_TO_EDGE:
522 case REPLICATION_EDGE_TO_FQDN:
523 case REPLICATION_EDGE_TO_CENTRAL:
524 case REPLICATION_CENTRAL_TO_EDGE:
527 logger.error( "Unexpected value for ReplicationType ("+ topic.getReplicationCase() + ") for topic " + topic.getFqtn() );
528 anythingWrong = true;
530 err.setFields("topic=" + topic.genFqtn() + " replicationCase="
531 + topic.getReplicationCase() );
532 err.setMessage("Unexpected value for ReplicationType");
536 logger.warn( "dcaeLocation " + loc + " is neither Edge nor Central so no mmagent provisioning was done");
537 anythingWrong = true;
540 if ( source != null && target != null ) {
542 logger.info( "Create a MM from " + source + " to " + target );
543 MirrorMaker mm = bridge.getNextMM( source, target, topic.getFqtn());
544 mm.addTopic(topic.getFqtn());
545 bridge.updateMirrorMaker(mm);
546 } catch ( Exception ex ) {
548 err.setFields( "mirror_maker.topic");
549 err.setMessage("Unexpected condition: " + ex );
550 anythingWrong = true;
557 return anythingWrong;
563 * Prior to 1707, we only supported EDGE_TO_CENTRAL replication.
564 * This was determined automatically based on presence of edge publishers and central subscribers.
565 * The following method is a modification of that original logic, to preserve some backwards compatibility,
566 * i.e. to be used when no ReplicationType is specified.
568 public ReplicationType reviewTopic( Topic topic ) {
571 if ( topic.getNumClients() > 1 ) {
572 Graph graph = new Graph( topic.getClients(), false );
574 String centralFqdn = new String();
575 if ( graph.hasCentral() ) {
576 DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
577 centralFqdn = p.getProperty("MR.CentralCname");
580 Collection<String> locations = graph.getKeys();
581 for( String loc : locations ) {
582 logger.info( "loc=" + loc );
583 MR_Cluster cluster = clusters.getMr_ClusterByLoc(loc);
584 if ( cluster == null ) {
585 logger.info( "No MR cluster for location " + loc );
588 if ( graph.hasCentral() && ! graph.getCentralLoc().equals(cluster.getDcaeLocationName())) {
589 logger.info( "Detected case for EDGE_TO_CENTRAL from " + cluster.getFqdn() + " to " + centralFqdn );
590 return ReplicationType.REPLICATION_EDGE_TO_CENTRAL;
597 return ReplicationType.REPLICATION_NONE;