Limit number of topics per mmagent whitelist
[dmaap/dbcapi.git] / src / main / java / org / onap / dmaap / dbcapi / service / TopicService.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * org.onap.dmaap
4  * ================================================================================
5  * Copyright (C) 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  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.dmaap.dbcapi.service;
22
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Iterator;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Set;
29
30 import javax.ws.rs.core.Response.Status;
31
32 import org.onap.dmaap.dbcapi.aaf.AafService;
33 import org.onap.dmaap.dbcapi.aaf.AafService.ServiceType;
34 import org.onap.dmaap.dbcapi.aaf.DmaapPerm;
35 import org.onap.dmaap.dbcapi.database.DatabaseClass;
36 import org.onap.dmaap.dbcapi.logging.BaseLoggingClass;
37 import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum;
38 import org.onap.dmaap.dbcapi.model.ApiError;
39 import org.onap.dmaap.dbcapi.model.DcaeLocation;
40 import org.onap.dmaap.dbcapi.model.Dmaap;
41 import org.onap.dmaap.dbcapi.model.DmaapObject.DmaapObject_Status;
42 import org.onap.dmaap.dbcapi.model.MR_Client;
43 import org.onap.dmaap.dbcapi.model.MR_Cluster;
44 import org.onap.dmaap.dbcapi.model.MirrorMaker;
45 import org.onap.dmaap.dbcapi.model.ReplicationType;
46 import org.onap.dmaap.dbcapi.model.Topic;
47 import org.onap.dmaap.dbcapi.util.DmaapConfig;
48 import org.onap.dmaap.dbcapi.util.Fqdn;
49 import org.onap.dmaap.dbcapi.util.Graph;
50
51 public class TopicService extends BaseLoggingClass {
52
53         
54
55         // REF: https://wiki.web.att.com/pages/viewpage.action?pageId=519703122
56         private static String defaultGlobalMrHost;
57         
58         private Map<String, Topic> mr_topics = DatabaseClass.getTopics();
59         
60         private static DmaapService dmaapSvc = new DmaapService();
61         private static Dmaap dmaap = new DmaapService().getDmaap();
62         private MR_ClientService clientService = new MR_ClientService();
63         private MR_ClusterService clusters = new MR_ClusterService();
64         private DcaeLocationService locations = new DcaeLocationService();
65         private MirrorMakerService      bridge = new MirrorMakerService();
66         
67         private static String centralCname;
68
69
70         public TopicService(){
71                 DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
72                 defaultGlobalMrHost = p.getProperty("MR.globalHost", "global.host.not.set");
73                 centralCname = p.getProperty("MR.CentralCname");
74
75                 
76                 logger.info( "TopicService properties: CentralCname=" + centralCname + 
77                                 "   defaultGlobarlMrHost=" + defaultGlobalMrHost  );
78         }
79         
80         public Map<String, Topic> getTopics() {                 
81                 return mr_topics;
82         }
83                 
84         public List<Topic> getAllTopics() {
85                 return getAllTopics( true );
86         }
87         public List<Topic> getAllTopicsWithoutClients() {
88                 return getAllTopics(false);
89         }
90         
91         private List<Topic> getAllTopics( Boolean withClients ) {
92                 ArrayList<Topic> topics = new ArrayList<Topic>(mr_topics.values());
93                 if ( withClients ) {
94                         for( Topic topic: topics ) {
95                                 topic.setClients( clientService.getAllMrClients(topic.getFqtn()));
96                         }
97                 }
98                 return topics;
99         }
100         
101                 
102         public Topic getTopic( String key, ApiError apiError ) {        
103                 logger.info( "getTopic: key=" + key);
104                 Topic t = mr_topics.get( key );
105                 if ( t == null ) {
106                         apiError.setCode(Status.NOT_FOUND.getStatusCode());
107                         apiError.setFields( "fqtn");
108                         apiError.setMessage("topic with fqtn " + key + " not found");
109                         return null;
110                 }
111                 t.setClients( clientService.getAllMrClients( key ));
112                 apiError.setCode(Status.OK.getStatusCode());
113                 return t;
114         }
115
116         public Topic addTopic( Topic topic, ApiError err, Boolean useExisting ) {
117                 logger.info( "Entry: addTopic");
118                 logger.info( "Topic name=" + topic.getTopicName() + " fqtnStyle=" + topic.getFqtnStyle() );
119                 String nFqtn =  topic.genFqtn();
120                 logger.info( "FQTN=" + nFqtn );
121                 Topic pTopic = getTopic( nFqtn, err );
122                 if ( pTopic != null ) {
123                         String t = "topic already exists: " + nFqtn;
124                         logger.info( t );
125                         if (  useExisting ) {
126                                 err.setCode(Status.OK.getStatusCode());
127                                 return pTopic;
128                         }
129                         err.setMessage( t );
130                         err.setFields( "fqtn");
131                         err.setCode(Status.CONFLICT.getStatusCode());
132                         return null;
133                 }
134                 err.reset();  // err filled with NOT_FOUND is expected case, but don't want to litter...
135
136                 topic.setFqtn( nFqtn );
137                 
138                 AafService aaf = new AafService(ServiceType.AAF_TopicMgr);
139
140                 String t = dmaapSvc.getTopicPerm();
141
142                 String instance = ":topic." + topic.getFqtn();
143
144                 String[] actions = { "pub", "sub", "view" };
145                 for ( String action : actions ){
146                         DmaapPerm perm = new DmaapPerm( t, instance, action );
147                         int rc = aaf.addPerm( perm );
148                         if ( rc != 201 && rc != 409 ) {
149                                 err.setCode(500);
150                                 err.setMessage("Unexpected response from AAF:" + rc );
151                                 err.setFields("t="+t + " instance="+ instance + " action="+ action);
152                                 return null;
153                         }
154                 }
155                 if ( topic.getReplicationCase().involvesGlobal() ) {
156                         if ( topic.getGlobalMrURL() == null ) {
157                                 topic.setGlobalMrURL(defaultGlobalMrHost);
158                         }
159                         if ( ! Fqdn.isValid( topic.getGlobalMrURL())) {
160                                 logger.error( "GlobalMR FQDN not valid: " + topic.getGlobalMrURL());
161                                 topic.setStatus( DmaapObject_Status.INVALID);
162                                 err.setCode(500);
163                                 err.setMessage("Value is not a valid FQDN:" +  topic.getGlobalMrURL() );
164                                 err.setFields("globalMrURL");
165         
166                                 return null;
167                         }
168                 }
169
170
171                 if ( topic.getNumClients() > 0 ) {
172                         ArrayList<MR_Client> clients = new ArrayList<MR_Client>(topic.getClients());
173                 
174         
175                         ArrayList<MR_Client> clients2 = new ArrayList<MR_Client>();
176                         for ( Iterator<MR_Client> it = clients.iterator(); it.hasNext(); ) {
177                                 MR_Client c = it.next();
178
179                                 logger.info( "c fqtn=" + c.getFqtn() + " ID=" + c.getMrClientId() + " url=" + c.getTopicURL());
180                                 MR_Client nc = new MR_Client( c.getDcaeLocationName(), topic.getFqtn(), c.getClientRole(), c.getAction());
181                                 nc.setFqtn(topic.getFqtn());
182                                 logger.info( "nc fqtn=" + nc.getFqtn() + " ID=" + nc.getMrClientId() + " url=" + nc.getTopicURL());
183                                 clients2.add( clientService.addMr_Client(nc, topic, err));
184                                 if ( ! err.is2xx()) {
185                                         return null;
186                                 }
187                         }
188
189                         topic.setClients(clients2);
190                 }
191
192                 Topic ntopic = checkForBridge( topic, err );
193                 if ( ntopic == null ) {
194                         topic.setStatus( DmaapObject_Status.INVALID);
195                         if ( ! err.is2xx()) {
196                                 return null;
197                         }
198                 }
199
200                 
201                 mr_topics.put( nFqtn, ntopic );
202
203                 err.setCode(Status.OK.getStatusCode());
204                 return ntopic;
205         }
206         
207                 
208         public Topic updateTopic( Topic topic, ApiError err ) {
209                 logger.info( "Entry: updateTopic");
210                 if ( topic.getFqtn().isEmpty()) {
211                         return null;
212                 }
213                 Topic ntopic = checkForBridge( topic, err );
214                 if ( ntopic == null ) {
215                         topic.setStatus( DmaapObject_Status.INVALID);
216                         if ( ! err.is2xx() ) {
217                                 return null;
218                         }
219                 }
220                 if(ntopic != null) {
221                         mr_topics.put( ntopic.getFqtn(), ntopic );
222                 }
223                 err.setCode(Status.OK.getStatusCode());
224                 return ntopic;
225         }
226                 
227         public Topic removeTopic( String pubId, ApiError apiError ) {
228                 Topic topic = mr_topics.get(pubId);
229                 if ( topic == null ) {
230                         apiError.setCode(Status.NOT_FOUND.getStatusCode());
231                         apiError.setMessage("Topic " + pubId + " does not exist");
232                         apiError.setFields("fqtn");
233                         return null;
234                 }
235                 ArrayList<MR_Client> clients = new ArrayList<MR_Client>(clientService.getAllMrClients( pubId ));
236                 for ( Iterator<MR_Client> it = clients.iterator(); it.hasNext(); ) {
237                         MR_Client c = it.next();
238                         
239         
240                         clientService.removeMr_Client(c.getMrClientId(), false, apiError);
241                         if ( ! apiError.is2xx()) {
242                                 return null;
243                         }
244                 }
245                 apiError.setCode(Status.OK.getStatusCode());
246                 return mr_topics.remove(pubId);
247         }       
248         public static ApiError setBridgeClientPerms( MR_Cluster node ) {
249                 DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
250                 String mmProvRole = p.getProperty("MM.ProvRole");
251                 String mmAgentRole = p.getProperty("MM.AgentRole");
252                 String[] Roles = { mmProvRole, mmAgentRole };
253                 String[] actions = { "view", "pub", "sub" };
254                 Topic bridgeAdminTopic = new Topic();
255                 bridgeAdminTopic.setTopicName( dmaapSvc.getBridgeAdminFqtn() );
256                 bridgeAdminTopic.setTopicDescription( "RESERVED topic for MirroMaker Provisioning");
257                 bridgeAdminTopic.setOwner( "DBC" );
258                 ArrayList<MR_Client> clients = new ArrayList<MR_Client>();
259                 for( String role: Roles ) {
260                         MR_Client client = new MR_Client();
261                         client.setAction(actions);
262                         client.setClientRole(role);
263                         client.setDcaeLocationName( node.getDcaeLocationName());
264                         clients.add( client );
265                 }
266                 bridgeAdminTopic.setClients(clients);
267                 
268                 TopicService ts = new TopicService();
269                 ApiError err = new ApiError();
270                 ts.addTopic(bridgeAdminTopic, err, true);
271                 
272                 if ( err.is2xx() || err.getCode() == 409 ){
273                         err.setCode(200);
274                         return err;
275                 }
276                 
277                 errorLogger.error( DmaapbcLogMessageEnum.TOPIC_CREATE_ERROR,  bridgeAdminTopic.getFqtn(), Integer.toString(err.getCode()), err.getFields(), err.getMessage());
278                 return err;
279         }       
280         
281         
282         public Topic checkForBridge( Topic topic, ApiError err ) {
283                 
284                 if ( topic.getReplicationCase() == ReplicationType.REPLICATION_NONE ) {
285                         topic.setStatus( DmaapObject_Status.VALID);
286                         return topic;   
287                 }
288                 
289                 boolean anythingWrong = false;
290                 
291                 Set<String> groups = clusters.getGroups();
292                 for ( String g : groups ) {
293                         anythingWrong |= buildBridge( topic, err, g );
294                 }
295                 if ( anythingWrong ) {
296                         topic.setStatus( DmaapObject_Status.INVALID);
297                         if ( ! err.is2xx() ) {
298                                 return null;
299                         }       
300                 } else {
301                         topic.setStatus( DmaapObject_Status.VALID);
302                 }
303                 return topic;
304         }
305                 
306         private boolean buildBridge( Topic topic, ApiError err, String group ) {
307
308                 boolean anythingWrong = false;
309                 Graph graph;
310                 if ( group == null || group.isEmpty() ) {
311                         graph = new Graph( topic.getClients(), true );
312                 } else {
313                         graph = new Graph( topic.getClients(), true, group );
314                 }
315                 MR_Cluster groupCentralCluster = null;
316                 
317                 if ( graph.isEmpty() ) {
318                         return false;
319                 } else if ( group == null &&  topic.getReplicationCase().involvesFQDN() ) {
320                         return false;
321                 } else if ( ! graph.hasCentral() ) {
322                         logger.warn( "Topic " + topic.getFqtn() + " wants to be " + topic.getReplicationCase() + " but has no central clients");
323                         return true;
324                 } else {
325                         groupCentralCluster = clusters.getMr_ClusterByLoc(graph.getCentralLoc());
326                 }
327                 Collection<String> clientLocations = graph.getKeys();
328                 for( String loc : clientLocations ) {
329                         logger.info( "loc=" + loc );
330                         DcaeLocation location = locations.getDcaeLocation(loc);
331                         MR_Cluster cluster = clusters.getMr_ClusterByLoc(loc);
332                         logger.info( "cluster=" + cluster );
333
334                         
335                                 
336                         String source = null;
337                         String target = null;
338                         
339                         /*
340                          * Provision Edge to Central bridges...
341                          */
342                         if ( ! location.isCentral()  && ! graph.getCentralLoc().equals(cluster.getDcaeLocationName()) ) {
343                                 switch( topic.getReplicationCase() ) {
344                                 case REPLICATION_EDGE_TO_CENTRAL:
345                                 case REPLICATION_EDGE_TO_CENTRAL_TO_GLOBAL:  // NOTE: this is for E2C portion only
346                                         source = cluster.getFqdn();
347                                         target = centralCname;
348                                         break;
349                                 case REPLICATION_CENTRAL_TO_EDGE:
350                                 case REPLICATION_GLOBAL_TO_CENTRAL_TO_EDGE:  // NOTE: this is for C2E portion only
351                                         source = centralCname;
352                                         target = cluster.getFqdn();
353                                         break;
354                                 case REPLICATION_CENTRAL_TO_GLOBAL:
355                                 case REPLICATION_GLOBAL_TO_CENTRAL:
356                                 case REPLICATION_FQDN_TO_GLOBAL:
357                                 case REPLICATION_GLOBAL_TO_FQDN:
358                                         break;
359
360                                 case REPLICATION_EDGE_TO_FQDN:
361                                 case REPLICATION_EDGE_TO_FQDN_TO_GLOBAL:  // NOTE: this is for E2C portion only
362                                         source = cluster.getFqdn();
363                                         target = groupCentralCluster.getFqdn();
364                                         break;
365                                 case REPLICATION_FQDN_TO_EDGE:
366                                 case REPLICATION_GLOBAL_TO_FQDN_TO_EDGE:  // NOTE: this is for F2E portion only
367                                         source = groupCentralCluster.getFqdn();
368                                         target = cluster.getFqdn();
369                                         break;
370
371                                 default:
372                                         logger.error( "Unexpected value for ReplicationType ("+ topic.getReplicationCase() + ") for topic " + topic.getFqtn() );
373                                         anythingWrong = true;
374                                         err.setCode(400);
375                                         err.setFields("topic=" + topic.genFqtn() + " replicationCase="
376                                                         + topic.getReplicationCase() );
377                                         err.setMessage("Unexpected value for ReplicationType");
378                                         continue;
379                                 }
380
381                         } else if ( location.isCentral() && graph.getCentralLoc().equals(cluster.getDcaeLocationName()) ) {
382                                 /*
383                                  * Provision Central to Global bridges
384                                  */
385                                 switch( topic.getReplicationCase() ) {
386
387                                 case REPLICATION_CENTRAL_TO_GLOBAL:
388                                 case REPLICATION_EDGE_TO_CENTRAL_TO_GLOBAL:
389                                         source = centralCname;
390                                         target = topic.getGlobalMrURL();
391                                         break;
392                                 case REPLICATION_GLOBAL_TO_CENTRAL:
393                                 case REPLICATION_GLOBAL_TO_CENTRAL_TO_EDGE:  // NOTE: this is for G2C portion only
394                                         source = topic.getGlobalMrURL();
395                                         target = centralCname;
396                                         break;
397
398                                 case REPLICATION_EDGE_TO_FQDN_TO_GLOBAL:  // NOTE: this is for E2F portion only
399                                         source = groupCentralCluster.getFqdn();
400                                         target = topic.getGlobalMrURL();
401                                         break;
402
403                                 case REPLICATION_FQDN_TO_GLOBAL:
404                                         source = groupCentralCluster.getFqdn();
405                                         target = topic.getGlobalMrURL();
406                                         break;
407                                         
408                                 case REPLICATION_GLOBAL_TO_FQDN:
409                                 case REPLICATION_GLOBAL_TO_FQDN_TO_EDGE:  // NOTE: this is for G2F portion only
410                                         source = topic.getGlobalMrURL();
411                                         target = groupCentralCluster.getFqdn();
412                                         break;
413
414                                 case REPLICATION_FQDN_TO_EDGE:
415                                 case REPLICATION_EDGE_TO_FQDN:
416                                 case REPLICATION_EDGE_TO_CENTRAL:
417                                 case REPLICATION_CENTRAL_TO_EDGE:
418                                         break;
419                                 default:
420                                         logger.error( "Unexpected value for ReplicationType ("+ topic.getReplicationCase() + ") for topic " + topic.getFqtn() );
421                                         anythingWrong = true;
422                                         err.setCode(400);
423                                         err.setFields("topic=" + topic.genFqtn() + " replicationCase="
424                                                         + topic.getReplicationCase() );
425                                         err.setMessage("Unexpected value for ReplicationType");
426                                         continue;
427                                 }                               
428                         } else {
429                                 logger.warn( "dcaeLocation " + loc + " is neither Edge nor Central so no mmagent provisioning was done");
430                                 anythingWrong = true;
431                                 continue;
432                         }
433                         if ( source != null && target != null ) {
434                                 try { 
435                                         logger.info( "Create a MM from " + source + " to " + target );
436                                         MirrorMaker mm = bridge.getNextMM( source, target);
437                                         mm.addTopic(topic.getFqtn());
438                                         bridge.updateMirrorMaker(mm);
439                                 } catch ( Exception ex ) {
440                                         err.setCode(500);
441                                         err.setFields( "mirror_maker.topic");
442                                         err.setMessage("Unexpected condition: " + ex );
443                                         anythingWrong = true;
444                                         break;
445                                 }
446                         }                       
447
448                         
449                 }
450                 return  anythingWrong;
451
452         }
453         
454         
455         /*
456          * Prior to 1707, we only supported EDGE_TO_CENTRAL replication.
457          * This was determined automatically based on presence of edge publishers and central subscribers.
458          * The following method is a modification of that original logic, to preserve some backwards compatibility, 
459          * i.e. to be used when no ReplicationType is specified.
460          */
461         public ReplicationType reviewTopic( Topic topic ) {
462         
463                 
464                 if ( topic.getNumClients() > 1 ) {
465                         Graph graph = new Graph( topic.getClients(), false );
466                         
467                         String centralFqdn = new String();
468                         if ( graph.hasCentral() ) {
469                                 DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
470                                 centralFqdn = p.getProperty("MR.CentralCname");
471                         }
472
473                         Collection<String> locations = graph.getKeys();
474                         for( String loc : locations ) {
475                                 logger.info( "loc=" + loc );
476                                 MR_Cluster cluster = clusters.getMr_ClusterByLoc(loc);
477                                 if ( cluster == null ) {
478                                         logger.info( "No MR cluster for location " + loc );
479                                         continue;
480                                 }
481                                 if ( graph.hasCentral() &&  ! graph.getCentralLoc().equals(cluster.getDcaeLocationName())) {
482                                         logger.info( "Detected case for EDGE_TO_CENTRAL from " + cluster.getFqdn() + " to " + centralFqdn );
483                                         return ReplicationType.REPLICATION_EDGE_TO_CENTRAL;
484                                         
485                                 }
486                                 
487                         }
488                 }
489         
490                 return ReplicationType.REPLICATION_NONE;
491         }
492
493 }