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