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