7082b9bda7b0de6c27b9dec156e8e8f9734eec16
[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
29 import javax.ws.rs.core.Response.Status;
30
31 import org.onap.dmaap.dbcapi.aaf.AafService;
32 import org.onap.dmaap.dbcapi.aaf.DmaapPerm;
33 import org.onap.dmaap.dbcapi.aaf.AafService.ServiceType;
34 import org.onap.dmaap.dbcapi.aaf.database.DatabaseClass;
35 import org.onap.dmaap.dbcapi.logging.BaseLoggingClass;
36 import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum;
37 import org.onap.dmaap.dbcapi.model.ApiError;
38 import org.onap.dmaap.dbcapi.model.Dmaap;
39 import org.onap.dmaap.dbcapi.model.MR_Client;
40 import org.onap.dmaap.dbcapi.model.MR_Cluster;
41 import org.onap.dmaap.dbcapi.model.MirrorMaker;
42 import org.onap.dmaap.dbcapi.model.ReplicationType;
43 import org.onap.dmaap.dbcapi.model.Topic;
44 import org.onap.dmaap.dbcapi.model.DmaapObject.DmaapObject_Status;
45 import org.onap.dmaap.dbcapi.util.DmaapConfig;
46 import org.onap.dmaap.dbcapi.util.Graph;
47
48 public class TopicService extends BaseLoggingClass {
49
50         
51
52         // REF: https://wiki.web.att.com/pages/viewpage.action?pageId=519703122
53         private static String defaultGlobalMrHost;
54         
55         private Map<String, Topic> mr_topics = DatabaseClass.getTopics();
56         private Map<String, MR_Cluster> clusters = DatabaseClass.getMr_clusters();
57         
58         private static DmaapService dmaapSvc = new DmaapService();
59         private static Dmaap dmaap = new DmaapService().getDmaap();
60         private MR_ClientService clientService = new MR_ClientService();
61         private MirrorMakerService      bridge = new MirrorMakerService();
62
63         public TopicService(){
64                 DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
65                 defaultGlobalMrHost = p.getProperty("MR.globalHost", "global.host.not.set");
66         }
67         
68         public Map<String, Topic> getTopics() {                 
69                 return mr_topics;
70         }
71                 
72         public List<Topic> getAllTopics() {
73                 ArrayList<Topic> topics = new ArrayList<Topic>(mr_topics.values());
74                 for( Topic topic: topics ) {
75                         topic.setClients( clientService.getAllMrClients(topic.getFqtn()));
76                 }
77                 return topics;
78         }
79         
80                 
81         public Topic getTopic( String key, ApiError apiError ) {        
82                 logger.info( "getTopic: key=" + key);
83                 Topic t = mr_topics.get( key );
84                 if ( t == null ) {
85                         apiError.setCode(Status.NOT_FOUND.getStatusCode());
86                         apiError.setFields( "fqtn");
87                         apiError.setMessage("topic with fqtn " + key + " not found");
88                         return null;
89                 }
90                 t.setClients( clientService.getAllMrClients( key ));
91                 apiError.setCode(Status.OK.getStatusCode());
92                 return t;
93         }
94
95         public Topic addTopic( Topic topic, ApiError err ) {
96                 logger.info( "Entry: addTopic");
97                 logger.info( "Topic name=" + topic.getTopicName() + " fqtnStyle=" + topic.getFqtnStyle() );
98                 String nFqtn =  topic.genFqtn();
99                 logger.info( "FQTN=" + nFqtn );
100                 if ( getTopic( nFqtn, err ) != null ) {
101                         String t = "topic already exists: " + nFqtn;
102                         logger.info( t );
103                         err.setMessage( t );
104                         err.setFields( "fqtn");
105                         err.setCode(Status.CONFLICT.getStatusCode());
106                         return null;
107                 }
108                 err.reset();  // err filled with NOT_FOUND is expected case, but don't want to litter...
109
110                 topic.setFqtn( nFqtn );
111
112                 AafService aaf = new AafService(ServiceType.AAF_TopicMgr);
113                 String t = dmaap.getTopicNsRoot() + "." + dmaap.getDmaapName() + ".mr.topic";
114                 String instance = ":topic." + topic.getFqtn();
115
116                 String[] actions = { "pub", "sub", "view" };
117                 for ( String action : actions ){
118                         DmaapPerm perm = new DmaapPerm( t, instance, action );
119                         int rc = aaf.addPerm( perm );
120                         if ( rc != 201 && rc != 409 ) {
121                                 err.setCode(500);
122                                 err.setMessage("Unexpected response from AAF:" + rc );
123                                 err.setFields("t="+t + " instance="+ instance + " action="+ action);
124                                 return null;
125                         }
126                 }
127
128
129                 if ( topic.getNumClients() > 0 ) {
130                         ArrayList<MR_Client> clients = new ArrayList<MR_Client>(topic.getClients());
131                 
132         
133                         ArrayList<MR_Client> clients2 = new ArrayList<MR_Client>();
134                         for ( Iterator<MR_Client> it = clients.iterator(); it.hasNext(); ) {
135                                 MR_Client c = it.next();
136
137                                 logger.info( "c fqtn=" + c.getFqtn() + " ID=" + c.getMrClientId() + " url=" + c.getTopicURL());
138                                 MR_Client nc = new MR_Client( c.getDcaeLocationName(), topic.getFqtn(), c.getClientRole(), c.getAction());
139                                 nc.setFqtn(topic.getFqtn());
140                                 logger.info( "nc fqtn=" + nc.getFqtn() + " ID=" + nc.getMrClientId() + " url=" + nc.getTopicURL());
141                                 clients2.add( clientService.addMr_Client(nc, topic, err));
142                                 if ( ! err.is2xx()) {
143                                         return null;
144                                 }
145                         }
146
147                         topic.setClients(clients2);
148                 }
149                 if ( topic.getReplicationCase().involvesGlobal() ) {
150                         if ( topic.getGlobalMrURL() == null ) {
151                                 topic.setGlobalMrURL(defaultGlobalMrHost);
152                         }
153                 }
154                 Topic ntopic = checkForBridge( topic, err );
155                 if ( ntopic == null ) {
156                         topic.setStatus( DmaapObject_Status.INVALID);
157                         return null;
158                 }
159
160                 mr_topics.put( nFqtn, ntopic );
161
162                 err.setCode(Status.OK.getStatusCode());
163                 return ntopic;
164         }
165         
166                 
167         public Topic updateTopic( Topic topic, ApiError err ) {
168                 logger.info( "Entry: updateTopic");
169                 if ( topic.getFqtn().isEmpty()) {
170                         return null;
171                 }
172                 Topic ntopic = checkForBridge( topic, err );
173                 if ( ntopic == null ) {
174                         topic.setStatus( DmaapObject_Status.INVALID);
175                         return null;
176                 }
177                 mr_topics.put( ntopic.getFqtn(), ntopic );
178                 err.setCode(Status.OK.getStatusCode());
179                 return ntopic;
180         }
181                 
182         public Topic removeTopic( String pubId, ApiError apiError ) {
183                 Topic topic = mr_topics.get(pubId);
184                 if ( topic == null ) {
185                         apiError.setCode(Status.NOT_FOUND.getStatusCode());
186                         apiError.setMessage("Topic " + pubId + " does not exist");
187                         apiError.setFields("fqtn");
188                         return null;
189                 }
190                 ArrayList<MR_Client> clients = new ArrayList<MR_Client>(clientService.getAllMrClients( pubId ));
191                 for ( Iterator<MR_Client> it = clients.iterator(); it.hasNext(); ) {
192                         MR_Client c = it.next();
193                         
194         
195                         clientService.removeMr_Client(c.getMrClientId(), false, apiError);
196                         if ( ! apiError.is2xx()) {
197                                 return null;
198                         }
199                 }
200                 apiError.setCode(Status.OK.getStatusCode());
201                 return mr_topics.remove(pubId);
202         }       
203         public static ApiError setBridgeClientPerms( MR_Cluster node ) {
204                 DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
205                 String mmProvRole = p.getProperty("MM.ProvRole");
206                 String mmAgentRole = p.getProperty("MM.AgentRole");
207                 String[] Roles = { mmProvRole, mmAgentRole };
208                 String[] actions = { "view", "pub", "sub" };
209                 Topic bridgeAdminTopic = new Topic();
210                 bridgeAdminTopic.setTopicName( dmaapSvc.getBridgeAdminFqtn() );
211                 bridgeAdminTopic.setTopicDescription( "RESERVED topic for MirroMaker Provisioning");
212                 bridgeAdminTopic.setOwner( "DBC" );
213                 ArrayList<MR_Client> clients = new ArrayList<MR_Client>();
214                 for( String role: Roles ) {
215                         MR_Client client = new MR_Client();
216                         client.setAction(actions);
217                         client.setClientRole(role);
218                         client.setDcaeLocationName( node.getDcaeLocationName());
219                         clients.add( client );
220                 }
221                 bridgeAdminTopic.setClients(clients);
222                 
223                 TopicService ts = new TopicService();
224                 ApiError err = new ApiError();
225                 ts.addTopic(bridgeAdminTopic, err);
226                 
227                 if ( err.is2xx() || err.getCode() == 409 ){
228                         err.setCode(200);
229                         return err;
230                 }
231                 
232                 errorLogger.error( DmaapbcLogMessageEnum.TOPIC_CREATE_ERROR,  bridgeAdminTopic.getFqtn(), Integer.toString(err.getCode()), err.getFields(), err.getMessage());
233                 return err;
234         }       
235         
236         
237         public Topic checkForBridge( Topic topic, ApiError err ) {
238                 
239                 if ( topic.getReplicationCase() == ReplicationType.REPLICATION_NONE ) {
240                         topic.setStatus( DmaapObject_Status.VALID);
241                         return topic;   
242                 }
243                 
244                 boolean anythingWrong = false;                          
245                 String centralFqdn = new String();
246                 Graph graph = new Graph( topic.getClients(), true );
247                 
248                 if ( graph.isHasCentral() ) {
249                         DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
250                         centralFqdn = p.getProperty("MR.CentralCname");
251                         logger.info( "CentralCname=" + centralFqdn );
252                 } else {
253                         logger.warn( "Topic " + topic.getFqtn() + " wants to be " + topic.getReplicationCase() + " but has no cental clients");
254                 }
255                 Collection<String> locations = graph.getKeys();
256                 for( String loc : locations ) {
257                         logger.info( "loc=" + loc );
258                         MR_Cluster cluster = clusters.get(loc);
259                         logger.info( "cluster=" + cluster );
260
261                         
262                                 
263                         String source = null;
264                         String target = null;
265                         /*
266                          * all replication rules have 1 bridge...
267                          */
268                         switch( topic.getReplicationCase() ) {
269                         case REPLICATION_EDGE_TO_CENTRAL:
270                         case REPLICATION_EDGE_TO_CENTRAL_TO_GLOBAL:  // NOTE: this is for E2C portion only
271                                 if ( graph.isHasCentral() &&  graph.getCentralLoc().equals(cluster.getDcaeLocationName())) {
272                                         break;
273                                 }
274                                 source = cluster.getFqdn();
275                                 target = centralFqdn;
276                                 break;
277                         case REPLICATION_CENTRAL_TO_EDGE:
278                                 if ( graph.isHasCentral() &&  graph.getCentralLoc().equals(cluster.getDcaeLocationName())) {
279                                         continue;
280                                 }
281                                 source = centralFqdn;
282                                 target = cluster.getFqdn();
283                                 break;
284                         case REPLICATION_CENTRAL_TO_GLOBAL:
285                                 if ( graph.isHasCentral() &&  ! graph.getCentralLoc().equals(cluster.getDcaeLocationName())) {
286                                         continue;
287                                 }
288                                 source = centralFqdn;
289                                 target = topic.getGlobalMrURL();
290                                 break;
291                         case REPLICATION_GLOBAL_TO_CENTRAL:
292                         case REPLICATION_GLOBAL_TO_CENTRAL_TO_EDGE:  // NOTE: this is for G2C portion only
293                                 if ( graph.isHasCentral() &&  ! graph.getCentralLoc().equals(cluster.getDcaeLocationName())) {
294                                         continue;
295                                 }
296                                 source = topic.getGlobalMrURL();
297                                 target = centralFqdn;
298                                 break;
299                         default:
300                                 logger.error( "Unexpected value for ReplicationType ("+ topic.getReplicationCase() + ") for topic " + topic.getFqtn() );
301                                 anythingWrong = true;
302                                 continue;
303                         }
304                         if ( source != null && target != null ) {
305                                 try { 
306                                         logger.info( "Create a MM from " + source + " to " + target );
307                                         MirrorMaker mm = bridge.getMirrorMaker( source, target);
308                                         if ( mm == null ) {
309                                                 mm = new MirrorMaker(source, target);
310                                         }
311                                         mm.addTopic(topic.getFqtn());
312                                         bridge.updateMirrorMaker(mm);
313                                 } catch ( Exception ex ) {
314                                         err.setCode(500);
315                                         err.setFields( "mirror_maker.topic");
316                                         err.setMessage("Unexpected condition: " + ex );
317                                         anythingWrong = true;
318                                         break;
319                                 }
320                         }
321                         
322                         
323                         /*
324                          * some replication rules have a 2nd bridge!
325                          */
326                         source = target = null;
327                         switch( topic.getReplicationCase() ) {
328                         case REPLICATION_EDGE_TO_CENTRAL:
329                         case REPLICATION_CENTRAL_TO_EDGE:
330                         case REPLICATION_CENTRAL_TO_GLOBAL:
331                         case REPLICATION_GLOBAL_TO_CENTRAL:
332                                 continue;
333                         case REPLICATION_EDGE_TO_CENTRAL_TO_GLOBAL:  // NOTE: this is for C2G portion only
334                                 if ( graph.isHasCentral() && ! graph.getCentralLoc().equals(cluster.getDcaeLocationName())) {
335                                         continue;
336                                 }
337                                 source = centralFqdn;
338                                 target = topic.getGlobalMrURL();
339                                 break;
340         
341                         case REPLICATION_GLOBAL_TO_CENTRAL_TO_EDGE:  // NOTE: this is for C2E portion only
342                                 if ( graph.isHasCentral() &&  graph.getCentralLoc().equals(cluster.getDcaeLocationName())) {
343                                         continue;
344                                 }
345                                 source = centralFqdn;
346                                 target = cluster.getFqdn();
347                                 break;
348                         default:
349                                 logger.error( "Unexpected value for ReplicationType ("+ topic.getReplicationCase() + ") for topic " + topic.getFqtn() );
350                                 anythingWrong = true;
351                                 break;
352                         }
353                         if ( source != null && target != null ) {
354                                 try { 
355                                         logger.info( "Create a MM from " + source + " to " + target );
356                                         MirrorMaker mm = bridge.getMirrorMaker( source, target);
357                                         if ( mm == null ) {
358                                                 mm = new MirrorMaker(source, target);
359                                         }
360                                         mm.addTopic(topic.getFqtn());
361                                         bridge.updateMirrorMaker(mm);
362                                 } catch ( Exception ex ) {
363                                         err.setCode(500);
364                                         err.setFields( "mirror_maker.topic");
365                                         err.setMessage("Unexpected condition: " + ex );
366                                         anythingWrong = true;
367                                         break;
368                                 }       
369                         }
370                         
371                 }
372                 if ( anythingWrong ) {
373                         topic.setStatus( DmaapObject_Status.INVALID);
374                         return null;
375                 }
376         
377                 topic.setStatus( DmaapObject_Status.VALID);
378                 return topic;
379         }
380         
381         /*
382          * Prior to 1707, we only supported EDGE_TO_CENTRAL replication.
383          * This was determined automatically based on presence of edge publishers and central subscribers.
384          * The following method is a modification of that original logic, to preserve some backwards compatibility, 
385          * i.e. to be used when no ReplicationType is specified.
386          */
387         public ReplicationType reviewTopic( Topic topic ) {
388         
389                 
390                 if ( topic.getNumClients() > 1 ) {
391                         Graph graph = new Graph( topic.getClients(), false );
392                         
393                         String centralFqdn = new String();
394                         if ( graph.isHasCentral() ) {
395                                 DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
396                                 centralFqdn = p.getProperty("MR.CentralCname");
397                         }
398
399                         Collection<String> locations = graph.getKeys();
400                         for( String loc : locations ) {
401                                 logger.info( "loc=" + loc );
402                                 MR_Cluster cluster = clusters.get(loc);
403                                 if ( cluster == null ) {
404                                         logger.info( "No MR cluster for location " + loc );
405                                         continue;
406                                 }
407                                 if ( graph.isHasCentral() &&  ! graph.getCentralLoc().equals(cluster.getDcaeLocationName())) {
408                                         logger.info( "Detected case for EDGE_TO_CENTRAL from " + cluster.getFqdn() + " to " + centralFqdn );
409                                         return ReplicationType.REPLICATION_EDGE_TO_CENTRAL;
410                                         
411                                 }
412                                 
413                         }
414                 }
415         
416                 return ReplicationType.REPLICATION_NONE;
417         }
418
419 }