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