Alternative MR replication method
[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                 mr_topics.put( ntopic.getFqtn(), ntopic );
201                 err.setCode(Status.OK.getStatusCode());
202                 return ntopic;
203         }
204                 
205         public Topic removeTopic( String pubId, ApiError apiError ) {
206                 Topic topic = mr_topics.get(pubId);
207                 if ( topic == null ) {
208                         apiError.setCode(Status.NOT_FOUND.getStatusCode());
209                         apiError.setMessage("Topic " + pubId + " does not exist");
210                         apiError.setFields("fqtn");
211                         return null;
212                 }
213                 ArrayList<MR_Client> clients = new ArrayList<MR_Client>(clientService.getAllMrClients( pubId ));
214                 for ( Iterator<MR_Client> it = clients.iterator(); it.hasNext(); ) {
215                         MR_Client c = it.next();
216                         
217         
218                         clientService.removeMr_Client(c.getMrClientId(), false, apiError);
219                         if ( ! apiError.is2xx()) {
220                                 return null;
221                         }
222                 }
223                 apiError.setCode(Status.OK.getStatusCode());
224                 return mr_topics.remove(pubId);
225         }       
226         public static ApiError setBridgeClientPerms( MR_Cluster node ) {
227                 DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
228                 String mmProvRole = p.getProperty("MM.ProvRole");
229                 String mmAgentRole = p.getProperty("MM.AgentRole");
230                 String[] Roles = { mmProvRole, mmAgentRole };
231                 String[] actions = { "view", "pub", "sub" };
232                 Topic bridgeAdminTopic = new Topic();
233                 bridgeAdminTopic.setTopicName( dmaapSvc.getBridgeAdminFqtn() );
234                 bridgeAdminTopic.setTopicDescription( "RESERVED topic for MirroMaker Provisioning");
235                 bridgeAdminTopic.setOwner( "DBC" );
236                 ArrayList<MR_Client> clients = new ArrayList<MR_Client>();
237                 for( String role: Roles ) {
238                         MR_Client client = new MR_Client();
239                         client.setAction(actions);
240                         client.setClientRole(role);
241                         client.setDcaeLocationName( node.getDcaeLocationName());
242                         clients.add( client );
243                 }
244                 bridgeAdminTopic.setClients(clients);
245                 
246                 TopicService ts = new TopicService();
247                 ApiError err = new ApiError();
248                 ts.addTopic(bridgeAdminTopic, err);
249                 
250                 if ( err.is2xx() || err.getCode() == 409 ){
251                         err.setCode(200);
252                         return err;
253                 }
254                 
255                 errorLogger.error( DmaapbcLogMessageEnum.TOPIC_CREATE_ERROR,  bridgeAdminTopic.getFqtn(), Integer.toString(err.getCode()), err.getFields(), err.getMessage());
256                 return err;
257         }       
258         
259         
260         public Topic checkForBridge( Topic topic, ApiError err ) {
261                 
262                 if ( topic.getReplicationCase() == ReplicationType.REPLICATION_NONE ) {
263                         topic.setStatus( DmaapObject_Status.VALID);
264                         return topic;   
265                 }
266                 
267                 boolean anythingWrong = false;
268                 
269                 Set<String> groups = clusters.getGroups();
270                 for ( String g : groups ) {
271                         anythingWrong |= buildBridge( topic, err, g );
272                 }
273                 if ( anythingWrong ) {
274                         topic.setStatus( DmaapObject_Status.INVALID);
275                         if ( ! err.is2xx() ) {
276                                 return null;
277                         }       
278                 } else {
279                         topic.setStatus( DmaapObject_Status.VALID);
280                 }
281                 return topic;
282         }
283                 
284         private boolean buildBridge( Topic topic, ApiError err, String group ) {
285
286                 boolean anythingWrong = false;
287                 Graph graph;
288                 if ( group == null || group.isEmpty() ) {
289                         graph = new Graph( topic.getClients(), true );
290                 } else {
291                         graph = new Graph( topic.getClients(), true, group );
292                 }
293                 MR_Cluster groupCentralCluster = null;
294                 
295                 if ( graph.isEmpty() ) {
296                         return false;
297                 } else if ( group == null &&  topic.getReplicationCase().involvesFQDN() ) {
298                         return false;
299                 } else if ( ! graph.hasCentral() ) {
300                         logger.warn( "Topic " + topic.getFqtn() + " wants to be " + topic.getReplicationCase() + " but has no central clients");
301                         return true;
302                 } else {
303                         groupCentralCluster = clusters.getMr_ClusterByLoc(graph.getCentralLoc());
304                 }
305                 Collection<String> clientLocations = graph.getKeys();
306                 for( String loc : clientLocations ) {
307                         logger.info( "loc=" + loc );
308                         DcaeLocation location = locations.getDcaeLocation(loc);
309                         MR_Cluster cluster = clusters.getMr_ClusterByLoc(loc);
310                         logger.info( "cluster=" + cluster );
311
312                         
313                                 
314                         String source = null;
315                         String target = null;
316                         
317                         /*
318                          * Provision Edge to Central bridges...
319                          */
320                         if ( ! location.isCentral()  && ! graph.getCentralLoc().equals(cluster.getDcaeLocationName()) ) {
321                                 switch( topic.getReplicationCase() ) {
322                                 case REPLICATION_EDGE_TO_CENTRAL:
323                                 case REPLICATION_EDGE_TO_CENTRAL_TO_GLOBAL:  // NOTE: this is for E2C portion only
324                                         source = cluster.getFqdn();
325                                         target = centralCname;
326                                         break;
327                                 case REPLICATION_CENTRAL_TO_EDGE:
328                                 case REPLICATION_GLOBAL_TO_CENTRAL_TO_EDGE:  // NOTE: this is for C2E portion only
329                                         source = centralCname;
330                                         target = cluster.getFqdn();
331                                         break;
332                                 case REPLICATION_CENTRAL_TO_GLOBAL:
333                                 case REPLICATION_GLOBAL_TO_CENTRAL:
334                                 case REPLICATION_FQDN_TO_GLOBAL:
335                                 case REPLICATION_GLOBAL_TO_FQDN:
336                                         break;
337
338                                 case REPLICATION_EDGE_TO_FQDN:
339                                 case REPLICATION_EDGE_TO_FQDN_TO_GLOBAL:  // NOTE: this is for E2C portion only
340                                         source = cluster.getFqdn();
341                                         target = groupCentralCluster.getFqdn();
342                                         break;
343                                 case REPLICATION_FQDN_TO_EDGE:
344                                 case REPLICATION_GLOBAL_TO_FQDN_TO_EDGE:  // NOTE: this is for F2E portion only
345                                         source = groupCentralCluster.getFqdn();
346                                         target = cluster.getFqdn();
347                                         break;
348
349                                 default:
350                                         logger.error( "Unexpected value for ReplicationType ("+ topic.getReplicationCase() + ") for topic " + topic.getFqtn() );
351                                         anythingWrong = true;
352                                         err.setCode(400);
353                                         err.setFields("topic=" + topic.genFqtn() + " replicationCase="
354                                                         + topic.getReplicationCase() );
355                                         err.setMessage("Unexpected value for ReplicationType");
356                                         continue;
357                                 }
358
359                         } else if ( location.isCentral() && graph.getCentralLoc().equals(cluster.getDcaeLocationName()) ) {
360                                 /*
361                                  * Provision Central to Global bridges
362                                  */
363                                 switch( topic.getReplicationCase() ) {
364
365                                 case REPLICATION_CENTRAL_TO_GLOBAL:
366                                 case REPLICATION_EDGE_TO_CENTRAL_TO_GLOBAL:
367                                         source = centralCname;
368                                         target = topic.getGlobalMrURL();
369                                         break;
370                                 case REPLICATION_GLOBAL_TO_CENTRAL:
371                                 case REPLICATION_GLOBAL_TO_CENTRAL_TO_EDGE:  // NOTE: this is for G2C portion only
372                                         source = topic.getGlobalMrURL();
373                                         target = centralCname;
374                                         break;
375
376                                 case REPLICATION_EDGE_TO_FQDN_TO_GLOBAL:  // NOTE: this is for E2F portion only
377                                         source = groupCentralCluster.getFqdn();
378                                         target = topic.getGlobalMrURL();
379                                         break;
380
381                                 case REPLICATION_FQDN_TO_GLOBAL:
382                                         source = groupCentralCluster.getFqdn();
383                                         target = topic.getGlobalMrURL();
384                                         break;
385                                         
386                                 case REPLICATION_GLOBAL_TO_FQDN:
387                                 case REPLICATION_GLOBAL_TO_FQDN_TO_EDGE:  // NOTE: this is for G2F portion only
388                                         source = topic.getGlobalMrURL();
389                                         target = groupCentralCluster.getFqdn();
390                                         break;
391
392                                 case REPLICATION_FQDN_TO_EDGE:
393                                 case REPLICATION_EDGE_TO_FQDN:
394                                 case REPLICATION_EDGE_TO_CENTRAL:
395                                 case REPLICATION_CENTRAL_TO_EDGE:
396                                         break;
397                                 default:
398                                         logger.error( "Unexpected value for ReplicationType ("+ topic.getReplicationCase() + ") for topic " + topic.getFqtn() );
399                                         anythingWrong = true;
400                                         err.setCode(400);
401                                         err.setFields("topic=" + topic.genFqtn() + " replicationCase="
402                                                         + topic.getReplicationCase() );
403                                         err.setMessage("Unexpected value for ReplicationType");
404                                         continue;
405                                 }                               
406                         } else {
407                                 logger.warn( "dcaeLocation " + loc + " is neither Edge nor Central so no mmagent provisioning was done");
408                                 anythingWrong = true;
409                                 continue;
410                         }
411                         if ( source != null && target != null ) {
412                                 try { 
413                                         logger.info( "Create a MM from " + source + " to " + target );
414                                         MirrorMaker mm = bridge.getMirrorMaker( source, target);
415                                         if ( mm == null ) {
416                                                 mm = new MirrorMaker(source, target);
417                                         }
418                                         mm.addTopic(topic.getFqtn());
419                                         bridge.updateMirrorMaker(mm);
420                                 } catch ( Exception ex ) {
421                                         err.setCode(500);
422                                         err.setFields( "mirror_maker.topic");
423                                         err.setMessage("Unexpected condition: " + ex );
424                                         anythingWrong = true;
425                                         break;
426                                 }
427                         }                       
428
429                         
430                 }
431                 return  anythingWrong;
432
433         }
434         
435         /*
436          * Prior to 1707, we only supported EDGE_TO_CENTRAL replication.
437          * This was determined automatically based on presence of edge publishers and central subscribers.
438          * The following method is a modification of that original logic, to preserve some backwards compatibility, 
439          * i.e. to be used when no ReplicationType is specified.
440          */
441         public ReplicationType reviewTopic( Topic topic ) {
442         
443                 
444                 if ( topic.getNumClients() > 1 ) {
445                         Graph graph = new Graph( topic.getClients(), false );
446                         
447                         String centralFqdn = new String();
448                         if ( graph.hasCentral() ) {
449                                 DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
450                                 centralFqdn = p.getProperty("MR.CentralCname");
451                         }
452
453                         Collection<String> locations = graph.getKeys();
454                         for( String loc : locations ) {
455                                 logger.info( "loc=" + loc );
456                                 MR_Cluster cluster = clusters.getMr_ClusterByLoc(loc);
457                                 if ( cluster == null ) {
458                                         logger.info( "No MR cluster for location " + loc );
459                                         continue;
460                                 }
461                                 if ( graph.hasCentral() &&  ! graph.getCentralLoc().equals(cluster.getDcaeLocationName())) {
462                                         logger.info( "Detected case for EDGE_TO_CENTRAL from " + cluster.getFqdn() + " to " + centralFqdn );
463                                         return ReplicationType.REPLICATION_EDGE_TO_CENTRAL;
464                                         
465                                 }
466                                 
467                         }
468                 }
469         
470                 return ReplicationType.REPLICATION_NONE;
471         }
472
473 }