49966d785a990fc2a2627f5fec2b9ac9bfbd1413
[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().init();
255                 bridgeAdminTopic.setTopicName( dmaapSvc.getBridgeAdminFqtn() );
256                 bridgeAdminTopic.setTopicDescription( "RESERVED topic for MirroMaker Provisioning");
257                 bridgeAdminTopic.setOwner( "DBC" );
258                 
259                 ArrayList<MR_Client> clients = new ArrayList<MR_Client>();
260                 for( String role: Roles ) {
261                         MR_Client client = new MR_Client();
262                         client.setAction(actions);
263                         client.setClientRole(role);
264                         client.setDcaeLocationName( node.getDcaeLocationName());
265                         clients.add( client );
266                 }
267                 bridgeAdminTopic.setClients(clients);
268                 
269                 TopicService ts = new TopicService();
270                 ApiError err = new ApiError();
271                 ts.addTopic(bridgeAdminTopic, err, true);
272                 
273                 if ( err.is2xx() || err.getCode() == 409 ){
274                         err.setCode(200);
275                         return err;
276                 }
277                 
278                 errorLogger.error( DmaapbcLogMessageEnum.TOPIC_CREATE_ERROR,  bridgeAdminTopic.getFqtn(), Integer.toString(err.getCode()), err.getFields(), err.getMessage());
279                 return err;
280         }       
281         
282         
283         public Topic checkForBridge( Topic topic, ApiError err ) {
284                 
285                 if ( topic.getReplicationCase() == ReplicationType.REPLICATION_NONE ) {
286                         topic.setStatus( DmaapObject_Status.VALID);
287                         return topic;   
288                 }
289                 
290                 boolean anythingWrong = false;
291                 
292                 Set<String> groups = clusters.getGroups();
293                 for ( String g : groups ) {
294                         anythingWrong |= buildBridge( topic, err, g );
295                 }
296                 if ( anythingWrong ) {
297                         topic.setStatus( DmaapObject_Status.INVALID);
298                         if ( ! err.is2xx() ) {
299                                 return null;
300                         }       
301                 } else {
302                         topic.setStatus( DmaapObject_Status.VALID);
303                 }
304                 return topic;
305         }
306                 
307         private boolean buildBridge( Topic topic, ApiError err, String group ) {
308
309                 boolean anythingWrong = false;
310                 Graph graph;
311                 if ( group == null || group.isEmpty() ) {
312                         graph = new Graph( topic.getClients(), true );
313                 } else {
314                         graph = new Graph( topic.getClients(), true, group );
315                 }
316                 MR_Cluster groupCentralCluster = null;
317                 
318                 if ( graph.isEmpty() ) {
319                         return false;
320                 } else if ( group == null &&  topic.getReplicationCase().involvesFQDN() ) {
321                         return false;
322                 } else if ( ! graph.hasCentral() ) {
323                         logger.warn( "Topic " + topic.getFqtn() + " wants to be " + topic.getReplicationCase() + " but has no central clients");
324                         return true;
325                 } else {
326                         groupCentralCluster = clusters.getMr_ClusterByLoc(graph.getCentralLoc());
327                 }
328                 Collection<String> clientLocations = graph.getKeys();
329                 for( String loc : clientLocations ) {
330                         logger.info( "loc=" + loc );
331                         DcaeLocation location = locations.getDcaeLocation(loc);
332                         MR_Cluster cluster = clusters.getMr_ClusterByLoc(loc);
333                         logger.info( "cluster=" + cluster );
334
335                         
336                                 
337                         String source = null;
338                         String target = null;
339                         
340                         /*
341                          * Provision Edge to Central bridges...
342                          */
343                         if ( ! location.isCentral()  && ! graph.getCentralLoc().equals(cluster.getDcaeLocationName()) ) {
344                                 switch( topic.getReplicationCase() ) {
345                                 case REPLICATION_EDGE_TO_CENTRAL:
346                                 case REPLICATION_EDGE_TO_CENTRAL_TO_GLOBAL:  // NOTE: this is for E2C portion only
347                                         source = cluster.getFqdn();
348                                         target = centralCname;
349                                         break;
350                                 case REPLICATION_CENTRAL_TO_EDGE:
351                                 case REPLICATION_GLOBAL_TO_CENTRAL_TO_EDGE:  // NOTE: this is for C2E portion only
352                                         source = centralCname;
353                                         target = cluster.getFqdn();
354                                         break;
355                                 case REPLICATION_CENTRAL_TO_GLOBAL:
356                                 case REPLICATION_GLOBAL_TO_CENTRAL:
357                                 case REPLICATION_FQDN_TO_GLOBAL:
358                                 case REPLICATION_GLOBAL_TO_FQDN:
359                                         break;
360
361                                 case REPLICATION_EDGE_TO_FQDN:
362                                 case REPLICATION_EDGE_TO_FQDN_TO_GLOBAL:  // NOTE: this is for E2C portion only
363                                         source = cluster.getFqdn();
364                                         target = groupCentralCluster.getFqdn();
365                                         break;
366                                 case REPLICATION_FQDN_TO_EDGE:
367                                 case REPLICATION_GLOBAL_TO_FQDN_TO_EDGE:  // NOTE: this is for F2E portion only
368                                         source = groupCentralCluster.getFqdn();
369                                         target = cluster.getFqdn();
370                                         break;
371
372                                 default:
373                                         logger.error( "Unexpected value for ReplicationType ("+ topic.getReplicationCase() + ") for topic " + topic.getFqtn() );
374                                         anythingWrong = true;
375                                         err.setCode(400);
376                                         err.setFields("topic=" + topic.genFqtn() + " replicationCase="
377                                                         + topic.getReplicationCase() );
378                                         err.setMessage("Unexpected value for ReplicationType");
379                                         continue;
380                                 }
381
382                         } else if ( location.isCentral() && graph.getCentralLoc().equals(cluster.getDcaeLocationName()) ) {
383                                 /*
384                                  * Provision Central to Global bridges
385                                  */
386                                 switch( topic.getReplicationCase() ) {
387
388                                 case REPLICATION_CENTRAL_TO_GLOBAL:
389                                 case REPLICATION_EDGE_TO_CENTRAL_TO_GLOBAL:
390                                         source = centralCname;
391                                         target = topic.getGlobalMrURL();
392                                         break;
393                                 case REPLICATION_GLOBAL_TO_CENTRAL:
394                                 case REPLICATION_GLOBAL_TO_CENTRAL_TO_EDGE:  // NOTE: this is for G2C portion only
395                                         source = topic.getGlobalMrURL();
396                                         target = centralCname;
397                                         break;
398
399                                 case REPLICATION_EDGE_TO_FQDN_TO_GLOBAL:  // NOTE: this is for E2F portion only
400                                         source = groupCentralCluster.getFqdn();
401                                         target = topic.getGlobalMrURL();
402                                         break;
403
404                                 case REPLICATION_FQDN_TO_GLOBAL:
405                                         source = groupCentralCluster.getFqdn();
406                                         target = topic.getGlobalMrURL();
407                                         break;
408                                         
409                                 case REPLICATION_GLOBAL_TO_FQDN:
410                                 case REPLICATION_GLOBAL_TO_FQDN_TO_EDGE:  // NOTE: this is for G2F portion only
411                                         source = topic.getGlobalMrURL();
412                                         target = groupCentralCluster.getFqdn();
413                                         break;
414
415                                 case REPLICATION_FQDN_TO_EDGE:
416                                 case REPLICATION_EDGE_TO_FQDN:
417                                 case REPLICATION_EDGE_TO_CENTRAL:
418                                 case REPLICATION_CENTRAL_TO_EDGE:
419                                         break;
420                                 default:
421                                         logger.error( "Unexpected value for ReplicationType ("+ topic.getReplicationCase() + ") for topic " + topic.getFqtn() );
422                                         anythingWrong = true;
423                                         err.setCode(400);
424                                         err.setFields("topic=" + topic.genFqtn() + " replicationCase="
425                                                         + topic.getReplicationCase() );
426                                         err.setMessage("Unexpected value for ReplicationType");
427                                         continue;
428                                 }                               
429                         } else {
430                                 logger.warn( "dcaeLocation " + loc + " is neither Edge nor Central so no mmagent provisioning was done");
431                                 anythingWrong = true;
432                                 continue;
433                         }
434                         if ( source != null && target != null ) {
435                                 try { 
436                                         logger.info( "Create a MM from " + source + " to " + target );
437                                         MirrorMaker mm = bridge.getNextMM( source, target, topic.getFqtn());
438                                         mm.addTopic(topic.getFqtn());
439                                         bridge.updateMirrorMaker(mm);
440                                 } catch ( Exception ex ) {
441                                         err.setCode(500);
442                                         err.setFields( "mirror_maker.topic");
443                                         err.setMessage("Unexpected condition: " + ex );
444                                         anythingWrong = true;
445                                         break;
446                                 }
447                         }                       
448
449                         
450                 }
451                 return  anythingWrong;
452
453         }
454         
455         
456         /*
457          * Prior to 1707, we only supported EDGE_TO_CENTRAL replication.
458          * This was determined automatically based on presence of edge publishers and central subscribers.
459          * The following method is a modification of that original logic, to preserve some backwards compatibility, 
460          * i.e. to be used when no ReplicationType is specified.
461          */
462         public ReplicationType reviewTopic( Topic topic ) {
463         
464                 
465                 if ( topic.getNumClients() > 1 ) {
466                         Graph graph = new Graph( topic.getClients(), false );
467                         
468                         String centralFqdn = new String();
469                         if ( graph.hasCentral() ) {
470                                 DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
471                                 centralFqdn = p.getProperty("MR.CentralCname");
472                         }
473
474                         Collection<String> locations = graph.getKeys();
475                         for( String loc : locations ) {
476                                 logger.info( "loc=" + loc );
477                                 MR_Cluster cluster = clusters.getMr_ClusterByLoc(loc);
478                                 if ( cluster == null ) {
479                                         logger.info( "No MR cluster for location " + loc );
480                                         continue;
481                                 }
482                                 if ( graph.hasCentral() &&  ! graph.getCentralLoc().equals(cluster.getDcaeLocationName())) {
483                                         logger.info( "Detected case for EDGE_TO_CENTRAL from " + cluster.getFqdn() + " to " + centralFqdn );
484                                         return ReplicationType.REPLICATION_EDGE_TO_CENTRAL;
485                                         
486                                 }
487                                 
488                         }
489                 }
490         
491                 return ReplicationType.REPLICATION_NONE;
492         }
493
494 }