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